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

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

// Used to crash the compiler.
// http://code.google.com/p/go/issues/detail?id=158

package main

type A struct {
	a A;
}			// ERROR "recursive"
func foo()		{ new(A).bar() }
func (a A) bar()	{}

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

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

// Used to crash the compiler.
// http://code.google.com/p/go/issues/detail?id=158

package main

type A struct {	a A }	// ERROR "recursive"
func foo()		{ new(A).bar() }
func (a A) bar()	{}

Tweak test to work with both 6g and gccgo.


package actors

import (
	"github.com/cloudfoundry/cli/cf/i18n"
	goi18n "github.com/nicksnyder/go-i18n/i18n"
)

var T goi18n.TranslateFunc

func init() {
	T = i18n.Init("actors", i18n.GetResourcesPath())
}

Add newline at end of some random file


// Package acctest provides the ability to opt in to the new binary test driver. The binary
// test driver allows you to run your acceptance tests with a binary of Terraform instead of
// an emulated version packaged inside the SDK. This allows for a number of important
// enhancements, but most notably a more realistic testing experience and matrix testing
// against multiple versions of Terraform CLI. This also allows the SDK to be completely
// separated, at a dependency level, from the Terraform CLI, as long as it is >= 0.12.0
//
// The new test driver must be enabled by initialising the test helper in your TestMain
// function in all provider packages that run acceptance tests. Most providers have only
// one package.
//
// In v2 of the SDK, the binary test driver will be mandatory.
//
// After importing this package, you can add code similar to the following:
//
//   func TestMain(m *testing.M) {
//     acctest.UseBinaryDriver("provider_name", Provider)
//     resource.TestMain(m)
//   }
//
// Where `Provider` is the function that returns the instance of a configured `terraform.ResourceProvider`
// Some providers already have a TestMain defined, usually for the purpose of enabling test
// sweepers. These additional occurrences should be removed.
//
// Initialising the binary test helper using UseBinaryDriver causes all tests to be run using
// the new binary driver. Until SDK v2, the DisableBinaryDriver boolean property can be used
// to use the legacy test driver for an individual TestCase.
//
// It is no longer necessary to import other Terraform providers as Go modules: these
// imports should be removed.
package acctest

// Package acctest provides the ability to use the binary test driver. The binary
// test driver allows you to run your acceptance tests with a binary of Terraform.
// This is currently the only mechanism for driving tests. It provides a realistic testing
// experience and matrix testing against multiple versions of Terraform CLI,
// as long as they are >= 0.12.0
//
// The driver must be enabled by initialising the test helper in your TestMain
// function in all provider packages that run acceptance tests. Most providers have only
// one package.
//
// After importing this package, you must define a TestMain and have the following:
//
//   func TestMain(m *testing.M) {
//     acctest.UseBinaryDriver("provider_name", Provider)
//     resource.TestMain(m)
//   }
//
// Where `Provider` is the function that returns the instance of a configured `*schema.Provider`
// Some providers already have a TestMain defined, usually for the purpose of enabling test
// sweepers. These additional occurrences should be removed.
//
// It is no longer necessary to import other Terraform providers as Go modules: these
// imports should be removed.
package acctest

Update wording for a V2 context


package api

import (
	"github.com/matttproud/prometheus/rules"
	"github.com/matttproud/prometheus/rules/ast"
        "time"
)
func (serv MetricsService) Query(Expr string, Json string, Start string, End string) (result string) {
        exprNode, err := rules.LoadExprFromString(Expr)
        if err != nil {
                return err.Error()
        }

        timestamp := time.Now()

        format := ast.TEXT
        if Json != "" {
                format = ast.JSON
        }
        return ast.EvalToString(exprNode, &timestamp, format)
}

package api

import (
        "code.google.com/p/gorest"
	"github.com/matttproud/prometheus/rules"
	"github.com/matttproud/prometheus/rules/ast"
        "time"
)
func (serv MetricsService) Query(Expr string, Json string, Start string, End string) (result string) {
        exprNode, err := rules.LoadExprFromString(Expr)
        if err != nil {
                return err.Error()
        }

        timestamp := time.Now()

        rb := serv.ResponseBuilder()
        var format ast.OutputFormat
        if Json != "" {
                format = ast.JSON
                rb.SetContentType(gorest.Application_Json)
        } else {
                format = ast.TEXT
                rb.SetContentType(gorest.Text_Plain)
        }

        return ast.EvalToString(exprNode, &timestamp, format)
}

Set correct Content-Type header based on output format.


package main

import (
	"container/ring"
)

type Color string

type Face []Color

type Cube map[Color]Face

type ThreeDTransformer struct {
    faceRing ring.Ring
    edgeRing ring.Ring
}

func main() {

}

package main

import (
	"container/ring"
)

type Color string

var colors = [...]Color {"white","blue","red","yellow","orange","green"}

type Face []Color

type Cube map[Color]Face

type ThreeDTransformer struct {
    faceRing ring.Ring
    edgeRing ring.Ring
}

func main() {

}

Declare a sequence for the colors.


package main

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

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

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

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

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

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

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

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

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}

package main

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

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

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

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

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

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

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

func doAll(c *cli.Context) {
	hn := make(chan loader.ResultData)
	go loader.GetHNFeed(hn)
	phres := <- hn
	var HNData loader.Feed = &phres
	HNData.Display()
}

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}

Fix with interface and display method


package main

import (
	"fmt"

	"github.com/md14454/gosensors"
)

func main() {
	gosensors.Init()
	defer gosensors.Cleanup()

	chips := gosensors.GetDetectedChips()

	for i := 0; i < len(chips); i++ {
		chip := chips[i]

		fmt.Printf("%v\n", chip)
		fmt.Printf("Adapter: %v\n", chip.AdapterName())

		features := chip.GetFeatures()

		for j := 0; j < len(features); j++ {
			feature := features[j]

			fmt.Printf("%v (%v): %.1f\n", feature.Name, feature.GetLabel(), feature.GetValue())

			subfeatures := feature.GetSubFeatures()

			for k := 0; k < len(subfeatures); k++ {
				subfeature := subfeatures[k]

				fmt.Printf("  %v: %.1f\n", subfeature.Name, subfeature.GetValue())
			}
		}

		fmt.Printf("\n")
	}
}

package main

import (
	"fmt"

	"github.com/md14454/gosensors"
)

func main() {
	gosensors.Init()
	defer gosensors.Cleanup()

	chips := gosensors.GetDetectedChips()

	for i := 0; i < len(chips); i++ {
		chip := chips[i]

		fmt.Printf("%v\n", chip)
		fmt.Printf("Adapter: %v\n", chip.AdapterName())

		features := chip.GetFeatures()

		for j := 0; j < len(features); j++ {
			feature := features[j]

			fmt.Printf("%v ('%v'): %.1f\n", feature.Name, feature.GetLabel(), feature.GetValue())

			subfeatures := feature.GetSubFeatures()

			for k := 0; k < len(subfeatures); k++ {
				subfeature := subfeatures[k]

				fmt.Printf("  %v: %.1f\n", subfeature.Name, subfeature.GetValue())
			}
		}

		fmt.Printf("\n")
	}
}

Fix to generate identical output to PySensors


package main

import (
	_ "github.com/sheenobu/quicklog/filters/uuid"
	"github.com/sheenobu/quicklog/inputs/stdin"
	_ "github.com/sheenobu/quicklog/outputs/stdout"
	_ "github.com/sheenobu/quicklog/parsers/plain"

	"golang.org/x/net/context"

	"github.com/sheenobu/quicklog/ql"
)

func main() {

	chain := ql.Chain{
		Input:  &stdin.Process{},
		Output: ql.GetOutput("stdout"),
		Filter: ql.GetFilter("uuid"),
		Parser: ql.GetParser("plain"),
	}

	ctx := context.Background()
	chain.Execute(ctx)

}

package main

import (
	"github.com/sheenobu/quicklog/filters/uuid"
	"github.com/sheenobu/quicklog/inputs/stdin"
	"github.com/sheenobu/quicklog/outputs/debug"
	"github.com/sheenobu/quicklog/parsers/plain"

	"golang.org/x/net/context"

	"github.com/sheenobu/quicklog/ql"
)

func main() {

	chain := ql.Chain{
		Input: &stdin.Process{},
		//Output: &stdout.Process{},
		Output: &debug.Handler{PrintFields: debug.NullableBool{NotNull: false, Value: true}},
		Filter: &uuid.Handler{FieldName: "uuid"},
		Parser: &plain.Parser{},
	}

	ctx := context.Background()
	chain.Execute(ctx)

}

Convert embedded example to use objects directly


package pair

import(
    "io"
    "fmt"
)

type PairingHandler interface {
    Handle(Container) (Container, error)
}

func HandleReaderForHandler(r io.Reader, h PairingHandler) (io.Reader, error) {
    cont_in, err := NewTLV8ContainerFromReader(r)
    if err != nil {
        return nil, err
    }

    fmt.Println("->     Seq:", cont_in.GetByte(TLVType_SequenceNumber))

    cont_out, err := h.Handle(cont_in)

    if err != nil {
        fmt.Println("[ERROR]", err)
        return nil, err
    } else {
        if cont_out != nil {
            fmt.Println("<-     Seq:", cont_out.GetByte(TLVType_SequenceNumber))
            fmt.Println("-------------")
            return cont_out.BytesBuffer(), nil
        }
    }

    return nil, err
}

package pair

import(
    "io"
    "fmt"
)

type PairingHandler interface {
    Handle(Container) (Container, error)
}

func HandleReaderForHandler(r io.Reader, h PairingHandler) (r_out io.Reader, err error) {
    cont_in, err := NewTLV8ContainerFromReader(r)
    if err != nil {
        return nil, err
    }

    fmt.Println("->     Seq:", cont_in.GetByte(TLVType_SequenceNumber))

    cont_out, err := h.Handle(cont_in)

    if err != nil {
        fmt.Println("[ERROR]", err)
    } else {
        if cont_out != nil {
            fmt.Println("<-     Seq:", cont_out.GetByte(TLVType_SequenceNumber))
            r_out = cont_out.BytesBuffer()
        }
    }
    fmt.Println("--------------------------")

    return r_out, err
}

Update log output when handling pairing requests


package main

import (
	"log"

	"github.com/coreos/go-etcd/etcd"
)

func main() {
	client := etcd.NewClient([]string{"http://104.130.8.142:4001"})
	resp, err := client.Get("testcluster", false, false)
	if err != nil {
		log.Fatal(err)
	}
	for _, n := range resp.Node.Nodes {
		log.Printf("%s: %s\n", n.Key, n.Value)
	}
}

package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"sort"

	"github.com/coreos/go-etcd/etcd"
)

type NodeGroup []*etcd.Node //NodeGroup is a slice of pointers to etcd Nodes

// Sort Interface implementation methods
func (n NodeGroup) Len() int {
	return len(n)
}

func (n NodeGroup) Less(i, j int) bool {
	if n[i].Key < n[j].Key {
		return true
	}
	return false
}

func (n NodeGroup) Swap(i, j int) {
	n[i], n[j] = n[j], n[i]
}

func Usage() {
	fmt.Printf("Usage: %s\n", os.Args[0])
	flag.PrintDefaults()
	os.Exit(2)
}

func SetupFlags() (discoveryHost, discoveryPath *string) {
	discoveryHost = flag.String("discovery_host",
		"http://127.0.0.1:4001", "Discovery URL:Port")
	discoveryPath = flag.String("discovery_path",
		"",
		"Discovery path i.e. _etcd/registry/uVa2GHOTTxl27eyKk6clBwyaurf7KiWd")

	flag.Parse()

	if *discoveryHost == "" || *discoveryPath == "" {
		Usage()
	}

	return discoveryHost, discoveryPath
}

func main() {
	// Connect to the etcd discovery to pull the nodes
	discoveryHost, discoveryPath := SetupFlags()

	client := etcd.NewClient([]string{*discoveryHost})
	resp, _ := client.Get(*discoveryPath, false, false)

	// Store the pointer to the etcd nodes as a NodeGroup
	group := NodeGroup{}
	for _, n := range resp.Node.Nodes {
		group = append(group, n)
	}

	// Sort the NodeGroup
	sort.Sort(group)

	// Print out sorted NodeGroup by key
	for _, n := range group {
		log.Printf("%s: %s\n", n.Key, n.Value)
	}
}

Sort nodes by uuid, add discovery info via flags


// Package golang implements the "golang" runtime.
package golang

import (
	"github.com/apex/apex/function"
	"github.com/apex/apex/plugins/nodejs"
)

func init() {
	function.RegisterPlugin("golang", &Plugin{})
}

const (
	// Runtime name used by Apex
	Runtime = "golang"
)

// Plugin implementation.
type Plugin struct{}

// Open adds the shim and golang defaults.
func (p *Plugin) Open(fn *function.Function) error {
	if fn.Runtime != Runtime {
		return nil
	}

	if fn.Hooks.Build == "" {
		fn.Hooks.Build = "GOOS=linux GOARCH=amd64 go build -o main main.go"
	}

	fn.Shim = true
	fn.Runtime = nodejs.Runtime
	fn.Hooks.Clean = "rm -f main"

	return nil
}

// Package golang implements the "golang" runtime.
package golang

import (
	"github.com/apex/apex/function"
	"github.com/apex/apex/plugins/nodejs"
)

func init() {
	function.RegisterPlugin("golang", &Plugin{})
}

const (
	// Runtime name used by Apex
	Runtime = "golang"
)

// Plugin implementation.
type Plugin struct{}

// Open adds the shim and golang defaults.
func (p *Plugin) Open(fn *function.Function) error {
	if fn.Runtime != Runtime {
		return nil
	}

	if fn.Hooks.Build == "" {
		fn.Hooks.Build = "GOOS=linux GOARCH=amd64 go build -o main *.go"
	}

	fn.Shim = true
	fn.Runtime = nodejs.Runtime
	fn.Hooks.Clean = "rm -f main"

	return nil
}

Allow to build all Golang source files for function


package main

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

	"github.com/guregu/kami"
	"golang.org/x/net/context"
)

func main() {
	kami.Get("/contacts/", getContacts)
	kami.Serve()
}

func getContacts(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	page, err := strconv.Atoi(r.FormValue("page"))
	if err != nil {
		page = 1
	}

	perPage, err := strconv.Atoi(r.FormValue("per_page"))
	if err != nil {
		perPage = 100
	}

	json.NewEncoder(w).Encode(
		NewContactQuery(page, perPage).All())
}

package main

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

	"github.com/guregu/kami"
	"golang.org/x/net/context"
)

func main() {
	kami.Get("/contacts/", getContacts)
	kami.Serve()
}

func getContacts(
	ctx context.Context,
	w http.ResponseWriter,
	r *http.Request,
) {
	page, err := strconv.Atoi(r.FormValue("page"))
	if err != nil {
		page = 1
	}

	perPage, err := strconv.Atoi(r.FormValue("per_page"))
	if err != nil {
		perPage = 100
	}

	json.NewEncoder(w).Encode(
		NewContactQuery(page, perPage).All())
}

Make getContacts signature more readable


package learn

import (
	"davidb.org/x/stenome/timelearn"
)

// The UI is responsible for asking the user a question, and
// determining if they got it right.  The prob argument will always
// point to the problem to learn.  'next' may point to an upcoming
// problem.
type UI interface {
	Single(prob, next *timelearn.Problem) (int, error)
	Close() error
}

// Mapping holding all of the UIs that can be learned.  The mapping
// holds a generator to generate the UI.
var allUI map[string]func() (UI, error)

func init() {
	allUI = make(map[string]func() (UI, error))

	Register("simple", newSimpleUI)
}

// Register adds a new user interface.  Any database with the given
// kind will use this function to make a new UI for it.
func Register(kind string, gen func() (UI, error)) {
	allUI[kind] = gen
}

package learn

import (
	"davidb.org/x/stenome/timelearn"
)

// The UI is responsible for asking the user a question, and
// determining if they got it right.  The prob argument will always
// point to the problem to learn.  'next' may point to an upcoming
// problem.
type UI interface {
	Single(prob, next *timelearn.Problem) (int, error)
	Close() error
}

// Mapping holding all of the UIs that can be learned.  The mapping
// holds a generator to generate the UI.
var allUI = map[string]func() (UI, error){
	"simple": newSimpleUI,
}

// Register adds a new user interface.  Any database with the given
// kind will use this function to make a new UI for it.
func Register(kind string, gen func() (UI, error)) {
	allUI[kind] = gen
}

Use map literal instead of init func


package editor

import (
	"strings"
	"testing"
)

func TestInsertMode(t *testing.T) {
	i := insert{}
	i.init()
	input := "abc"
	i.in = NewReader(strings.NewReader(input))
	for n := range input {
		c, _, err := i.Run()
		if err != nil {
			t.Errorf("Run: %v", err)
		}
		if c != cont {
			t.Errorf("Run: want %v, but got %v", cont, c)
		}
		if got, want := string(i.Runes()), input[:n+1]; got != want {
			t.Errorf("Run: want %v, but got %v", want, got)
		}
	}
}

func TestInputMatches(t *testing.T) {
	i := insert{}
	i.init()
	input := "a 'b"
	i.in = NewReader(strings.NewReader(input))
	tt := []string{"a", "a ", "a ''", "a 'b'"}
	for n := range input {
		c, _, err := i.Run()
		if err != nil {
			t.Errorf("Run: %v", err)
		}
		if c != cont {
			t.Errorf("Run: want %v, but got %v", cont, c)
		}
		if got, want := string(i.Runes()), tt[n]; got != want {
			t.Errorf("Run/%d: want %q, but got %q", n, want, got)
		}
	}
}

Add test for input of matching characters


/*-
 * Copyright (c) 2016, Jörg Pernfuß <joerg.pernfuss@1und1.de>
 * All rights reserved
 *
 * Use of this source code is governed by a 2-clause BSD license
 * that can be found in the LICENSE file.
 */

package msg

type Supervisor struct {
	Verdict    uint16
	RemoteAddr string
	KexId      string
	Data       []byte
	Kex        auth.Kex
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix

/*-
 * Copyright (c) 2016, Jörg Pernfuß <joerg.pernfuss@1und1.de>
 * All rights reserved
 *
 * Use of this source code is governed by a 2-clause BSD license
 * that can be found in the LICENSE file.
 */

package msg

type Supervisor struct {
	Verdict        uint16
	RemoteAddr     string
	KexId          string
	Data           []byte
	Kex            auth.Kex
	BasicAuthUser  string
	BasicAuthToken string
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix

Add BasicAuth fields to msg.Supervisor


package main

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

func saveHandler(w http.ResponseWriter, r *http.Request) {
	folder := "/PRODUCTION/EXPERIMENT/web/savedfiles/"
    filename := generateRandomURL()
    path := folder + filename

    if _, err := os.Stat(path); err != nil {
	    if os.IsNotExist(err) {
		    http.Error(w, err.Error(), http.StatusInternalServerError)
	    }
    }

    r.ParseForm()
    text := r.Form.Get("text")
	ioutil.WriteFile(path, []byte(text), 0400)

	http.Redirect(w, r, "/"+filename, http.StatusCreated)
}

func generateRandomURL() string {
	return "1234556"
}

func main() {
	http.HandleFunc("/save", saveHandler)
    http.ListenAndServe(":8080", nil)
}

package main

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

func saveHandler(w http.ResponseWriter, r *http.Request) {
	folder := "/PRODUCTION/EXPERIMENT/web/savedfiles/"
    filename := generateRandomURL()
    path := folder + filename

    if _, err := os.Stat(path); err != nil {
	    if os.IsNotExist(err) {
		    http.Error(w, err.Error(), http.StatusInternalServerError)
		    return
	    }
    }

    r.ParseForm()
    text := r.Form.Get("text")
	ioutil.WriteFile(path, []byte(text), 0400)

	http.Redirect(w, r, "/"+filename, http.StatusCreated)
}

func generateRandomURL() string {
	return "1234556"
}

func main() {
	http.HandleFunc("/save", saveHandler)
    http.ListenAndServe(":8080", nil)
}

Return error if file already exists


package geocodio

import (
	"errors"
)

const (
	// GeocodioAPIBaseURLv1 is the Geocod.io Base URL
	GeocodioAPIBaseURLv1 = "https://api.geocod.io/v1.4"
)

// NewGeocodio is a helper to create new Geocodio pointer
func NewGeocodio(apiKey string) (*Geocodio, error) {

	if apiKey == "" {
		return nil, errors.New("apiKey is missing")
	}

	newGeocodio := new(Geocodio)
	newGeocodio.APIKey = apiKey

	return newGeocodio, nil
}

package geocodio

import (
	"errors"
)

const (
	// GeocodioAPIBaseURLv1 is the Geocod.io Base URL
	GeocodioAPIBaseURLv1 = "https://api.geocod.io/v1.5"
)

// NewGeocodio is a helper to create new Geocodio pointer
func NewGeocodio(apiKey string) (*Geocodio, error) {

	if apiKey == "" {
		return nil, errors.New("apiKey is missing")
	}

	newGeocodio := new(Geocodio)
	newGeocodio.APIKey = apiKey

	return newGeocodio, nil
}

Update to use api 1.5


package hashvalues

import (
	"hash"
	"net/url"
)

type HashValues struct {
	Values   *url.Values
	hashfunc hash.Hash
	hashkey  []byte
}

func NewHashValues(hashkey []byte, hashfunc hash.Hash) *HashValues {
	return &HashValues{
		Values:   &url.Values{},
		hashfunc: hashfunc,
		hashkey:  hashkey,
	}
}

func (h *HashValues) Set(key, value string) {
	h.Values.Set(key, value)
}

func (h *HashValues) Add(key, value string) {
	h.Values.Add(key, value)
}

func (h *HashValues) Del(key string) {
	h.Values.Del(key)
}

func (h *HashValues) Get(key string) string {
	return h.Values.Get(key)
}

Add Get, Set, Del, Add.


package goat

import (
	"net"
)

// ConnHandler interface method Handle defines how to handle incoming network connections
type ConnHandler interface {
	Handle(c net.Conn) bool
}

// HttpConnHandler handles incoming HTTP (TCP) network connections
type HttpConnHandler struct {
}

func (h HttpConnHandler) Handle(c net.Conn) bool {
	return true
}

// UdpConnHandler handles incoming UDP network connections
type UdpConnHandler struct {
}

func (u UdpConnHandler) Handle(c net.Conn) bool {
	return true
}

package goat

import (
	"fmt"
	"net"
	"strings"
)

// ConnHandler interface method Handle defines how to handle incoming network connections
type ConnHandler interface {
	Handle(c net.Conn) bool
}

// HttpConnHandler handles incoming HTTP (TCP) network connections
type HttpConnHandler struct {
}

// Handle an incoming HTTP request and provide a HTTP response
func (h HttpConnHandler) Handle(c net.Conn) bool {
	// Read in data from socket
	var buf = make([]byte, 1024)
	c.Read(buf)

	// TODO: remove temporary printing and fake response
	fmt.Println("http: ", string(buf))
	res := []string {
		"HTTP/1.1 200 OK\r\n",
		"Content-Type: text/plain\r\n",
		"Content-Length: 4\r\n",
		"Connection: close\r\n\r\n",
		"goat\r\n",
	}

	// Write response
	c.Write(strings.Join(res, ""))
	c.Close()

	return true
}

// UdpConnHandler handles incoming UDP network connections
type UdpConnHandler struct {
}

func (u UdpConnHandler) Handle(c net.Conn) bool {
	return true
}

Add basic HTTP read/write over socket


package main

import (
	. "github.com/stefanhans/go-present/slides/HighOrderFunctions/hof"
	"fmt"
)

func main() {
	var list = ListOfInt{-2, -1, 0, 2, 2, 3}

	tenTimes := func(x int) int { return x * 10 }
	isEven := func(x int) bool { return x%2 == 0 }

	fmt.Printf("List %v: Map(tenTimes).Filter(isEven) yields %v\n", list,
		list.
			Map(tenTimes).
			Filter(isEven))
}

package main

import (
	. "github.com/stefanhans/go-present/tree/master/slides/HighOrderFunctions/hof"
	"fmt"
)

func main() {
	var list = ListOfInt{-2, -1, 0, 2, 2, 3}

	tenTimes := func(x int) int { return x * 10 }
	isEven := func(x int) bool { return x%2 == 0 }

	fmt.Printf("List %v: Map(tenTimes).Filter(isEven) yields %v\n", list,
		list.
			Map(tenTimes).
			Filter(isEven))
}

Correct hof path from bitbucket to github


// Copyright (c) 2019 Sick Yoon
// This file is part of gocelery which is released under MIT license.
// See file LICENSE for full license details.

package gocelery

import (
	"log"

	"github.com/streadway/amqp"
)

// deliveryAck acknowledges delivery message with retries on error
func deliveryAck(delivery amqp.Delivery) {
	retryCount := 3
	var err error
	for retryCount > 0 {
		if err = delivery.Ack(false); err == nil {
			break
		}
	}
	if err != nil {
		log.Printf("amqp_backend: failed to acknowledge result message %+v: %+v", delivery.MessageId, err)
	}
}

// Copyright (c) 2019 Sick Yoon
// This file is part of gocelery which is released under MIT license.
// See file LICENSE for full license details.

package gocelery

import (
	"log"

	"github.com/streadway/amqp"
)

// deliveryAck acknowledges delivery message with retries on error
func deliveryAck(delivery amqp.Delivery) {
	var err error
	for retryCount := 3; retryCount > 0; retryCount-- {
		if err = delivery.Ack(false); err == nil {
			break
		}
	}
	if err != nil {
		log.Printf("amqp_backend: failed to acknowledge result message %+v: %+v", delivery.MessageId, err)
	}
}

Fix infinite loop bug in deliveryAck


package main

import (
	"fmt"
	"os"
	"path"
)

const BUFFER_SIZE = 1024

// fatal crashes the program if the given error is non-nil
// This isn't a good way to perform production error-handling,
// but it will serve for this demo.
func fatal(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func main() {
	xdgConfigPath := os.Getenv("XDG_CONFIG_HOME")
	if xdgConfigPath == "" {
		home := os.Getenv("HOME")
		if home == "" {
			fmt.Println("$HOME undefined, aborting...")
			os.Exit(1)
		}
		xdgConfigPath = path.Join(home, ".config")
	}
	fmt.Println("Config Dir:", xdgConfigPath)
	configFile, err := os.Open(path.Join(xdgConfigPath, "matterleast.conf"))
	fatal(err)

	defer configFile.Close()
	data := make([]byte, BUFFER_SIZE)
	bytesRead, err := configFile.Read(data)
	fatal(err)

}

package main

import (
	"encoding/json"
	"fmt"
	"os"
	"path"
)

const BUFFER_SIZE = 1024

// fatal crashes the program if the given error is non-nil
// This isn't a good way to perform production error-handling,
// but it will serve for this demo.
func fatal(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func main() {
	xdgConfigPath := os.Getenv("XDG_CONFIG_HOME")
	if xdgConfigPath == "" {
		home := os.Getenv("HOME")
		if home == "" {
			fmt.Println("$HOME undefined, aborting...")
			os.Exit(1)
		}
		xdgConfigPath = path.Join(home, ".config")
	}
	fmt.Println("Config Dir:", xdgConfigPath)
	configFile, err := os.Open(path.Join(xdgConfigPath, "matterleast.conf"))
	fatal(err)

	defer configFile.Close()
	data := make([]byte, BUFFER_SIZE)
	bytesRead, err := configFile.Read(data)
	fatal(err)

	config := make(map[string]string)
	err = json.Unmarshal(data[:bytesRead], &config)
	fatal(err)

	fmt.Println(config)
}

Implement conversion of json file to golang map


package pgpass

import (
	"os"
	"os/user"
	"path"
)

// OpenDefault opens default pgpass file, which is ~/.pgpass
func OpenDefault() (f *os.File, err error) {
	usr, err := user.Current()
	if err != nil {
		return
	}
	// TODO: check file permission is 0600
	return os.Open(path.Join(usr.HomeDir, ".pgpass"))
}

package pgpass

import (
	"os"
	"os/user"
	"path"
)

// OpenDefault opens default pgpass file, which is ~/.pgpass.
// Current homedir will be retrieved by calling user.Current
// or using $HOME on failure.
func OpenDefault() (f *os.File, err error) {
	var homedir = os.Getenv("HOME")
	usr, err := user.Current()
	if err == nil {
		homedir = usr.HomeDir
	} else if homedir == "" {
		return
	}
	// TODO: check file permission is 0600
	return os.Open(path.Join(homedir, ".pgpass"))
}

Use $HOME for user's home directory if user.Current fails.


package apollostats

import (
	"html"
	"strings"
)

// Func to take care of garbled text data.
func filter_string(s string) string {
	// Fuck it, might aswell assume all text has been escaped.
	tmp := html.UnescapeString(s)

	// Usually seen in the character table.
	tmp = strings.Replace(tmp, "&", "&", -1)

	// Usually seen in the room names in the death table.
	tmp = strings.Trim(tmp, "ÿ")

	tmp = strings.TrimSpace(tmp)
	return tmp
}

package apollostats

import (
	"html"
	"strings"
)

// Func to take care of garbled text data.
func filter_string(s string) string {
	// Fuck it, might aswell assume all text has been escaped.
	tmp := html.UnescapeString(s)

	// Usually seen in the room names in the death table.
	tmp = strings.Trim(tmp, "ÿ")

	tmp = strings.TrimSpace(tmp)
	return tmp
}

Remove unneeded html entity filter.


package test

import (
	"testing"
	"time"

	"github.com/b2aio/typhon/server"
)

// InitServer for testing
func InitServer(t *testing.T, name string) server.Server {
	// Initialize our Server
	server.Init(&server.Config{
		Name:        name,
		Description: "Example service",
	})

	go server.Run()

	select {
	case <-server.NotifyConnected():
	case <-time.After(1 * time.Second):
		t.Fatalf("StubServer couldn't connect to RabbitMQ")
	}

	return server.DefaultServer
}

package test

import (
	"testing"
	"time"

	"github.com/b2aio/typhon/server"
)

// InitServer for testing
func InitServer(t *testing.T, name string) server.Server {
	// Initialize our Server
	server.Init(&server.Config{
		Name:        name,
		Description: "Example service",
	})

	go server.Run()

	select {
	case <-server.NotifyConnected():
	case <-time.After(1 * time.Second):
		t.Fatalf("Test Server couldn't connect to RabbitMQ")
	}

	return server.DefaultServer
}

Fix error logging in test


package sort

import (
	"testing"

	"github.com/ready-steady/support/assert"
)

func TestQuickSort(t *testing.T) {
	data := []float64{3, 1, 6, 9, 4, 2}

	order1, order2 := Quick(data)

	assert.Equal(data, []float64{1, 2, 3, 4, 6, 9}, t)
	assert.Equal(order1, []uint{1, 5, 0, 4, 2, 3}, t)
	assert.Equal(order2, []uint{2, 0, 4, 5, 3, 1}, t)
}

package sort

import (
	"testing"

	"github.com/ready-steady/assert"
)

func TestQuickSort(t *testing.T) {
	data := []float64{3, 1, 6, 9, 4, 2}

	order1, order2 := Quick(data)

	assert.Equal(data, []float64{1, 2, 3, 4, 6, 9}, t)
	assert.Equal(order1, []uint{1, 5, 0, 4, 2, 3}, t)
	assert.Equal(order2, []uint{2, 0, 4, 5, 3, 1}, t)
}

Update the path to assert


// Copyright (C) 2017 Damon Revoe. All rights reserved.
// Use of this source code is governed by the MIT
// license, which can be found in the LICENSE file.

package main

import (
	"testing"
)

func runTemplateFunctionTest(t *testing.T,
	funcName, arg, expected string) {

	result := funcMap[funcName].(func(string) string)(arg)

	if result != expected {
		t.Error("Error: \"" + result + "\" != \"" + expected + "\"")
	}
}

func TestTemplateFunctions(t *testing.T) {
	runTemplateFunctionTest(t, "VarName", "C++11", "Cxx11")
	runTemplateFunctionTest(t, "VarName", "one-half", "one_half")

	runTemplateFunctionTest(t, "VarNameUC", "C++11", "CXX11")
	runTemplateFunctionTest(t, "VarNameUC", "cross-country", "CROSS_COUNTRY")

	runTemplateFunctionTest(t, "LibName", "libc++11", "libc++11")
	runTemplateFunctionTest(t, "LibName", "dash-dot.", "dash-dot.")
}

Break a line exceeding 80 chars into two


package main

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
)

func main() {
	svc := ec2.New(session.New(), &aws.Config{Region: aws.String("us-west-2")})

	resp, err := svc.DescribeInstances(nil)
	if err != nil {
		panic(err)
	}

	fmt.Println("> Number of reservation sets: ", len(resp.Reservations))

	for idx, res := range resp.Reservations {
		fmt.Println("  > Number of instances: ", len(res.Instances))
		for _, inst := range resp.Reservations[idx].Instances {
			fmt.Println("    - Instance ID: ", *inst.InstanceId)
		}
	}
}

package main

import (
	"fmt"
	"os"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ec2"
)

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage:\n\tmain region_name")
		os.Exit(-1)
	}

	region := os.Args[1]
	if region == "" {
		fmt.Println("Usage:\n\tmain region_name")
		os.Exit(-1)
	}

	svc := ec2.New(session.New(), &aws.Config{Region: aws.String(region)})

	resp, err := svc.DescribeInstances(nil)
	if err != nil {
		panic(err)
	}

	fmt.Println("> Number of reservation sets: ", len(resp.Reservations))

	for idx, res := range resp.Reservations {
		fmt.Println("  > Number of instances: ", len(res.Instances))
		for _, inst := range resp.Reservations[idx].Instances {
			fmt.Println("    - Instance ID: ", *inst.InstanceId)
		}
	}
}

Add defensive check to program arguments


package main

import (
	"flag"
	"github.com/alinpopa/barvin/handlers/slack"
	"github.com/op/go-logging"
	"os"
	"sync"
)

func main() {
	userID := flag.String("userid", "", "The privileged slack userid.")
	token := flag.String("token", "", "Slack token to connect.")
	flag.Parse()

	var format = logging.MustStringFormatter(
		`%{color}%{time:15:04:05.000} %{shortfunc} >>> %{level} %{id:03x} %{message}%{color:reset}`,
	)
	loggingBackend := logging.NewLogBackend(os.Stderr, "", 0)
	backend2Formatter := logging.NewBackendFormatter(loggingBackend, format)
	loggingBackendLeveled := logging.AddModuleLevel(loggingBackend)
	loggingBackendLeveled.SetLevel(logging.DEBUG, "")
	logging.SetBackend(backend2Formatter)

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		restartChannel := make(chan string)
		go func() {
			restartChannel <- "Initial start"
		}()
		for {
			msg := <-restartChannel
			go slack.SlackHandler(msg, restartChannel, *userID, *token)
		}
	}()
	wg.Wait()
}

package main

import (
	"flag"
	"github.com/alinpopa/barvin/handlers/slack"
	"github.com/op/go-logging"
	"os"
	"sync"
)

func main() {
	userID := flag.String("userid", "", "The privileged slack userid.")
	token := flag.String("token", "", "Slack token to connect.")
	flag.Parse()

	var format = logging.MustStringFormatter(
		`%{color}%{time:2006-01-02T15:04:05.000} %{shortfunc} >>> %{level} %{id:03x} %{message}%{color:reset}`,
	)
	loggingBackend := logging.NewLogBackend(os.Stderr, "", 0)
	backend2Formatter := logging.NewBackendFormatter(loggingBackend, format)
	loggingBackendLeveled := logging.AddModuleLevel(loggingBackend)
	loggingBackendLeveled.SetLevel(logging.DEBUG, "")
	logging.SetBackend(backend2Formatter)

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		defer wg.Done()
		restartChannel := make(chan string)
		go func() {
			restartChannel <- "Initial start"
		}()
		for {
			msg := <-restartChannel
			go slack.SlackHandler(msg, restartChannel, *userID, *token)
		}
	}()
	wg.Wait()
}

Add date as part of the log messages.


/*
 Copyright 2018 Padduck, LLC
 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/gin-gonic/gin"
	"github.com/pufferpanel/apufferi/logging"
	"github.com/pufferpanel/pufferpanel/database"
	"github.com/pufferpanel/pufferpanel/web"
)

const Hash = "none"
const Version = "2.0.0-DEV"

func main() {

	logging.Init()

	err := database.Load()

	if err != nil {
		logging.Error("Error connecting to database", err)
	}

	defer database.Close()

	if err != nil {
		return
	}

	r := gin.Default()
	web.RegisterRoutes(r)

	r.Run() // listen and serve on 0.0.0.0:8080
}

/*
 Copyright 2018 Padduck, LLC
 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/gin-gonic/gin"
	"github.com/pufferpanel/apufferi/logging"
	"github.com/pufferpanel/pufferpanel/database"
	"github.com/pufferpanel/pufferpanel/web"
)

const Hash = "none"
const Version = "2.0.0-DEV"

func main() {

	logging.Init()

	err := database.Load()

	if err != nil {
		logging.Error("Error connecting to database", err)
	}

	defer database.Close()

	if err != nil {
		return
	}

	r := gin.Default()
	web.RegisterRoutes(r)

	err = r.Run() // listen and serve on 0.0.0.0:8080
	if err != nil {
		logging.Error("Error running web service", err)
	}
}

Add logging if web server errors


package main

import "fmt"

func main() {
	fmt.Println("hello app")

}

package main

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

var (
	homeTmpl        = template.Must(template.New("homeTmpl").Parse(baseTemplate + formTemplate))
	searchReplyTmpl = template.Must(template.New("searchReplyTmpl").Parse(baseTemplate + searchReplyTemplate))
)

// Pet is the pet of the app.
type Pet struct {
	Name string
	Age  int
}

var pets = []Pet{
	{Name: "Blackie", Age: 5},
	{Name: "Rocky", Age: 6},
	{Name: "Lasie", Age: 7},
}

func main() {
	http.Handle("/", http.HandlerFunc(homeHandler))
	http.Handle("/form", http.HandlerFunc(searchReplyHandler))

	http.ListenAndServe(":8080", nil)
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
	err := homeTmpl.Execute(w, nil)
	if err != nil {
		http.Error(w, "internal server error", 500)
		return
	}
}

func searchReplyHandler(w http.ResponseWriter, r *http.Request) {
	name := r.FormValue("name")

	for _, p := range pets {
		if p.Name == name {
			err := searchReplyTmpl.Execute(w, p)
			if err != nil {
				http.Error(w, "internal server error", 500)
				return
			}
			return
		}
	}

	err := searchReplyTmpl.Execute(w, "No pet found")
	if err != nil {
		http.Error(w, "internal server error", 500)
		return
	}

}

const (
	baseTemplate = `
<!DOCTYPE html>

<meta charset="UTF-8">
<title>Secure web app</title>

	{{.}}

`

	formTemplate = `
<form action="/form" method="GET">
	<input name="name">
	<input type="submit" value="Search for pet">
 </form>
`
	searchReplyTemplate = `
Name: {{.Name}}

Age: {{.Age}}
`
)

Add http server and search template


package ungo

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

func Picnictrans(url string) (string, error) {
	cookie, _ := cookiejar.New(nil)

	HH.Host = "picnictrans.com"
	html := htmlDownload(url, cookie)

	urlregex := regexp.MustCompile(`window\.location="(.*?)";}`)
	resutl := urlregex.FindAllStringSubmatch(html.Html, -1)[0:]

	return resutl[0][1], nil
}

package ungo

import (
	"net/http/cookiejar"
	"regexp"
)

func Picnictrans(url string) (string, error) {
	cookie, _ := cookiejar.New(nil)

	HH.Host = "picnictrans.com"
	html := htmlDownload(url, cookie)

	urlregex := regexp.MustCompile(`window\.location="(.*?)";}`)
	resutl := urlregex.FindAllStringSubmatch(html.Html, -1)[0:]

	return resutl[0][1], nil
}

Remove fmt package on picnitrans!


package split

import (
	"bytes"
	"mime"
	"mime/multipart"
	"net/http"
	"net/textproto"
)

// WriteResponses serialize the responses passed as argument into the ResponseWriter
func WriteResponses(w http.ResponseWriter, responses []*http.Response) error {
	var buf bytes.Buffer
	multipartWriter := multipart.NewWriter(&buf)

	mimeHeaders := textproto.MIMEHeader(make(map[string][]string))
	mimeHeaders.Set("Content-Type", "application/http")

	for _, resp := range responses {
		part, err := multipartWriter.CreatePart(mimeHeaders)
		if err != nil {
			return err
		}
		resp.Write(part)
	}

	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", mime.FormatMediaType("multipart/mixed", map[string]string{"boundary": multipartWriter.Boundary()}))
	buf.WriteTo(w)
	return nil
}

package split

import (
	"bytes"
	"mime"
	"mime/multipart"
	"net/http"
	"net/textproto"
)

// WriteResponses serialize the responses passed as argument into the ResponseWriter
func WriteResponses(w http.ResponseWriter, responses []*http.Response) error {
	var buf bytes.Buffer
	multipartWriter := multipart.NewWriter(&buf)

	mimeHeaders := textproto.MIMEHeader(make(map[string][]string))
	mimeHeaders.Set("Content-Type", "application/http")

	for _, resp := range responses {
		part, err := multipartWriter.CreatePart(mimeHeaders)
		if err != nil {
			return err
		}
		resp.Write(part)
	}

	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", mime.FormatMediaType("multipart/mixed", map[string]string{"boundary": multipartWriter.Boundary()}))
	w.WriteHeader(http.StatusOK)
	buf.WriteTo(w)
	return nil
}

Fix the response content type


package main

import (
	"os"
	"strings"
)

func init() {
	home := os.Getenv("HOME")
	paths := []string{
		home + "/bin",
		home + "/.vvmn/vim/current/bin",
		"/usr/local/bin",
		"/usr/local/opt/coreutils/libexec/gnubin",
	}
	setPath(paths...)
}

func setPath(args ...string) {
	s := os.Getenv("PATH")
	paths := strings.Split(s, ":")
	var newPaths []string
	for _, arg := range args {
		for _, path := range paths {
			if path != arg {
				newPaths = append(newPaths, path)
			}
		}
	}
	newPaths = append(args, newPaths...)
	os.Setenv("PATH", strings.Join(newPaths, ":"))
}

package main

import (
	"os"
	"strings"
)

func init() {
	home := os.Getenv("HOME")
	paths := []string{
		home + "/bin",
		home + "/.vvmn/vim/current/bin",
		"/usr/local/bin",
		"/usr/local/opt/coreutils/libexec/gnubin",
	}
	setPath(paths...)
}

func setPath(args ...string) {
	s := os.Getenv("PATH")
	paths := strings.Split(s, ":")
	var newPaths []string
	for _, path := range paths {
		for _, arg := range args {
			if path != arg {
				newPaths = append(newPaths, path)
			}
		}
	}
	newPaths = append(args, newPaths...)
	os.Setenv("PATH", strings.Join(newPaths, ":"))
}

Make setPath set $PATH correctly


package log

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

type Logger struct {
	PrintDebug bool
	Output     io.Writer
	DateFormat string
}

func NewLogger(opts ...func(*Logger)) *Logger {
	l := &Logger{
		PrintDebug: false,
		Output:     os.Stdout,
		DateFormat: "15:04",
	}

	for _, opt := range opts {
		opt(l)
	}

	return l
}

func (l *Logger) log(lvl, msg string, args ...interface{}) {
	fmt.Fprintf(l.Output, "%s %s %s\n", time.Now().Format(l.DateFormat), lvl, fmt.Sprintf(msg, args...))
}

func (l *Logger) Debug(msg string, args ...interface{}) {
	l.log("debug", msg, args...)
}

func (l *Logger) Info(msg string, args ...interface{}) {
	l.log("info ", msg, args...)
}

package log

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

type Logger struct {
	PrintDebug bool
	Output     io.Writer
	DateFormat string
}

func NewLogger(opts ...func(*Logger)) *Logger {
	l := &Logger{
		PrintDebug: false,
		Output:     os.Stdout,
		DateFormat: "15:04",
	}

	for _, opt := range opts {
		opt(l)
	}

	return l
}

func (l *Logger) log(lvl, msg string, args ...interface{}) {
	fmt.Fprintf(l.Output, "%s %s %s\n", time.Now().Format(l.DateFormat), lvl, fmt.Sprintf(msg, args...))
}

func (l *Logger) Debug(msg string, args ...interface{}) {
	if l.PrintDebug {
		l.log("debug", msg, args...)
	}
}

func (l *Logger) Info(msg string, args ...interface{}) {
	l.log("info ", msg, args...)
}

Fix the debug logging flag


package nzb

import "strings"

type File struct {
	Poster   string    `xml:"poster,attr"`
	Date     int       `xml:"date,attr"`
	Subject  string    `xml:"subject,attr"`
	Groups   []string  `xml:"groups>group,internalxml"`
	Segments []Segment `xml:"segments>segment"`
}

//A Segment is a piece to be downloaded separately
type Segment struct {
	Number int    `xml:"number,attr"`
	Bytes  int    `xml:"bytes,attr"`
	Id     string `xml:",innerxml"`
}

func (f *File) Name() string {
	parts := strings.Split(f.Subject, `"`)
	fName := strings.Replace(parts[1], "/", "-", -1)
	return fName
}

package nzb

import (
	"fmt"
	"strings"
)

type File struct {
	Poster   string    `xml:"poster,attr"`
	Date     int       `xml:"date,attr"`
	Subject  string    `xml:"subject,attr"`
	Groups   []string  `xml:"groups>group,internalxml"`
	Segments []Segment `xml:"segments>segment"`
}

//A Segment is a piece to be downloaded separately
type Segment struct {
	Number int    `xml:"number,attr"`
	Bytes  int    `xml:"bytes,attr"`
	Id     string `xml:",innerxml"`
}

func (f *File) Name() (string, error) {
	parts := strings.Split(f.Subject, `"`)

	n := ""
	if len(parts) > 1 {
		n = strings.Replace(parts[1], "/", "-", -1)
	} else {
		return "", fmt.Errorf("could not parse subject")
	}
	return n, nil
}

Add possiblity of error to name parsing function


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

const entryTmpl = `
entity "{{ .Name }}" {
{{- if .Comment.Valid }}
  {{ .Comment.String }}
  ..
{{- end }}
{{- range .Columns }}
  {{- if .IsPrimaryKey }}
  + {{ .Name }}:{{ .DDLType }} [PK]{{if .IsForeignKey }}[FK]{{end}}{{- if .Comment.Valid }} : {{ .Comment.String }}{{- end }}
  {{- end }}
{{- end }}
  --
{{- range .Columns }}
  {{- if not .IsPrimaryKey }}
  {{if .NotNull}}*{{end}}{{ .Name }}:{{ .DDLType }} {{if .IsForeignKey}}[FK]{{end}} {{- if .Comment.Valid }} : {{ .Comment.String }}{{- end }}
  {{- end }}
{{- end }}
}
`

const relationTmpl = `
{{ if .IsOneToOne }} {{ .SourceTableName }} ||-|| {{ .TargetTableName }}{{else}} {{ .SourceTableName }} }-- {{ .TargetTableName }}{{end}}
`

package main

const entryTmpl = `
entity "**{{ .Name }}**" {
{{- if .Comment.Valid }}
  {{ .Comment.String }}
  ..
{{- end }}
{{- range .Columns }}
  {{- if .IsPrimaryKey }}
  + ""{{ .Name }}"": //{{ .DDLType }} [PK]{{if .IsForeignKey }}[FK]{{end}}{{- if .Comment.Valid }} : {{ .Comment.String }}{{- end }}//
  {{- end }}
{{- end }}
  --
{{- range .Columns }}
  {{- if not .IsPrimaryKey }}
  {{if .NotNull}}*{{end}}""{{ .Name }}"": //{{ .DDLType }} {{if .IsForeignKey}}[FK]{{end}} {{- if .Comment.Valid }} : {{ .Comment.String }}{{- end }}//
  {{- end }}
{{- end }}
}
`

const relationTmpl = `
"**{{ .SourceTableName }}**" {{if .IsOneToOne}} ||-|| {{else}}  }-- {{end}} "**{{ .TargetTableName }}**"
`

Format entity to improve readability


package meep

type ErrInvalidParam struct {
	TraitAutodescribing
	TraitTraceable
	Param  string
	Reason string
}

type ErrNotYetImplemented struct {
	TraitAutodescribing
	TraitTraceable
}

type ErrProgrammer struct {
	TraitAutodescribing
	TraitTraceable
	TraitCausable
}

package meep

type ErrInvalidParam struct {
	TraitAutodescribing
	TraitTraceable
	Param  string
	Reason string
}

type ErrNotYetImplemented struct {
	TraitAutodescribing
	TraitTraceable
}

type ErrProgrammer struct {
	Msg string
	TraitAutodescribing
	TraitTraceable
	TraitCausable
}

Add message field to ErrProgrammer.


// The MIT License (MIT)
//
// Copyright (c) 2015 Douglas Thrift
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

package main

func rdpLaunchNative(instance *Instance, private bool, index int, arguments []string, prompt bool, username string) error {
	return nil
}

Add Mac OS X stub for rdpLaunchNative.


package api

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

const apiURL string = "https://api.onedrive.com/v1.0/"

var client *http.Client

func init() {
	c, err := getClient()
	if err != nil {
		log.Fatal(err)
	}
	client = c
}

// GetDriveInfos return the content length of the /drive/ api entry point
func GetDriveInfos() string {
	resp, err := client.Get(fmt.Sprintf("%s/drive/", apiURL))
	if err != nil {
		log.Fatalln(err)
	}
	return fmt.Sprintf("Status: %d-%s\n", resp.StatusCode, resp.Status)
}

package api

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

const apiURL string = "https://api.onedrive.com/v1.0"

var client *http.Client

func init() {
	c, err := getClient()
	if err != nil {
		log.Fatal(err)
	}
	client = c
}

// GetDriveInfos return the content length of the /drive/ api entry point
func GetDriveInfos() string {
	driveURI := fmt.Sprintf("%s/drive/", apiURL)
	log.Printf("Request: %s\n", driveURI)
	resp, err := client.Get(driveURI)
	if err != nil {
		log.Fatalln(err)
	}
	return fmt.Sprintf("Status: %s\nContentLength: %d", resp.Status, resp.ContentLength)
}

Correct URI for the API


package imageserver

import (
	"encoding/gob"
	"github.com/Symantec/Dominator/lib/filesystem"
)

func init() {
	gob.Register(&filesystem.RegularInode{})
	gob.Register(&filesystem.SymlinkInode{})
	gob.Register(&filesystem.SpecialInode{})
	gob.Register(&filesystem.DirectoryInode{})
}

package imageserver

import (
	"encoding/gob"
	"github.com/Symantec/Dominator/lib/filesystem"
)

func init() {
	gob.Register(&filesystem.RegularInode{})
	gob.Register(&filesystem.ComputedRegularInode{})
	gob.Register(&filesystem.SymlinkInode{})
	gob.Register(&filesystem.SpecialInode{})
	gob.Register(&filesystem.DirectoryInode{})
}

Add ComputedRegularFile to imageserver protocol definition.


package rpcd

import (
	"github.com/Symantec/Dominator/imageunpacker/unpacker"
	"github.com/Symantec/Dominator/lib/srpc"
	"io"
	"log"
	"sync"
)

type srpcType struct {
	unpacker      *unpacker.Unpacker
	logger        *log.Logger
	addDeviceLock sync.Mutex
}

type htmlWriter srpcType

func (hw *htmlWriter) WriteHtml(writer io.Writer) {
	hw.writeHtml(writer)
}

func Setup(unpackerObj *unpacker.Unpacker, logger *log.Logger) *htmlWriter {
	srpcObj := srpcType{
		unpacker: unpackerObj,
		logger:   logger}
	srpc.RegisterName("ImageUnpacker", &srpcObj)
	return (*htmlWriter)(&srpcObj)
}

package rpcd

import (
	"github.com/Symantec/Dominator/imageunpacker/unpacker"
	"github.com/Symantec/Dominator/lib/log"
	"github.com/Symantec/Dominator/lib/srpc"
	"io"
	"sync"
)

type srpcType struct {
	unpacker      *unpacker.Unpacker
	logger        log.Logger
	addDeviceLock sync.Mutex
}

type htmlWriter srpcType

func (hw *htmlWriter) WriteHtml(writer io.Writer) {
	hw.writeHtml(writer)
}

func Setup(unpackerObj *unpacker.Unpacker, logger log.Logger) *htmlWriter {
	srpcObj := srpcType{
		unpacker: unpackerObj,
		logger:   logger}
	srpc.RegisterName("ImageUnpacker", &srpcObj)
	return (*htmlWriter)(&srpcObj)
}

Switch imageunpacker/rpcd to lib/log/serverlogger package.


package watch

import etcd "github.com/coreos/etcd/clientv3"

// OpOption is a simple typedef for etcd.OpOption.
type OpOption etcd.OpOption

// WithFilterPut discards PUT events from the watcher.
func WithFilterPut() OpOption {
	return OpOption(etcd.WithFilterPut())
}

// WithFilterDelete discards DELETE events from the watcher.
func WithFilterDelete() OpOption {
	return OpOption(etcd.WithFilterDelete())
}

Add delete filter to watch package


package main

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

func main() {
	command := os.Args[1:]
	cmd := exec.Command(command[0], command[1:]...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		fmt.Fprintf(os.Stderr, "pew: %v\n", err)
		os.Exit(1)
	}
}

package main

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

func main() {
	command := os.Args[1:]
	cmd := exec.Command(command[0], command[1:]...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Start()
	if err != nil {
		exit(err)
	}
	err = cmd.Wait()
	if err != nil {
		exit(err)
	}
}

func exit(err error) {
	fmt.Fprintf(os.Stderr, "pew: %v\n", err)
	os.Exit(1)
}

Use Start/Wait instead of Run


package main

import (
	"fmt"

	"github.com/krasin/cobra"
)

func main() {
	rootCmd := &cobra.Command{
		Use:   "steel",
		Short: "A tool to tinker with STL files",
		Long:  "Command-line processor for STL files",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("Steel -- a tool to tinker with STL files.")
			cmd.Usage()
		},
	}
	rootCmd.Execute()
}

package main

import (
	"fmt"
	"os"

	"github.com/krasin/cobra"
	"github.com/krasin/stl"
)

func fail(args ...interface{}) {
	fmt.Fprintln(os.Stderr, args...)
	os.Exit(1)
}

func info(cmd *cobra.Command, args []string) {
	if len(args) == 0 {
		fail("STL file not specified")
	}
	f, err := os.Open(args[0])
	if err != nil {
		fail(err)
	}
	defer f.Close()
	t, err := stl.Read(f)
	if err != nil {
		fail("Failed to read STL file:", err)
	}
	fmt.Printf("Triangles: %d\n", len(t))
}

func main() {
	rootCmd := &cobra.Command{
		Use:   "steel",
		Short: "A tool to tinker with STL files",
		Long:  "Command-line processor for STL files",
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("Steel -- a tool to tinker with STL files.")
			cmd.Usage()
		},
	}
	infoCmd := &cobra.Command{
		Use:   "info [STL file]",
		Short: "STL file info",
		Long:  "info displays STL metrics, such as the number of triangles, bounding box, etc",
		Run:   info,
	}
	rootCmd.AddCommand(infoCmd)
	rootCmd.Execute()
}

Implement very basic 'info' command, that currently displays number of triangles.


package aws

import (
	"os"
	"testing"

	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
)

func TestAccAWSOpsWorksStack_importBasic(t *testing.T) {
	oldvar := os.Getenv("AWS_DEFAULT_REGION")
	os.Setenv("AWS_DEFAULT_REGION", "us-west-2")
	defer os.Setenv("AWS_DEFAULT_REGION", oldvar)

	name := acctest.RandString(10)

	resourceName := "aws_opsworks_stack.tf-acc"

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAwsOpsworksStackDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAwsOpsworksStackConfigVpcCreate(name),
			},

			resource.TestStep{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

package aws

import (
	"testing"

	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
)

func TestAccAWSOpsworksStackImportBasic(t *testing.T) {
	name := acctest.RandString(10)

	resourceName := "aws_opsworks_stack.tf-acc"

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAwsOpsworksStackDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAwsOpsworksStackConfigVpcCreate(name),
			},

			resource.TestStep{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
			},
		},
	})
}

Rename the Import aws_opsworks_stack import test


package edit

import (
	"testing"

	"github.com/elves/elvish/edit/ui"
)

var (
	theLine    = "qw search 'foo bar ~y'"
	theLastCmd = newLastCmd(theLine)

	lastcmdFilterTests = []listingFilterTestCases{
		{"", []shown{
			{"M-,", ui.Unstyled(theLine)},
			{"0", ui.Unstyled("qw")},
			{"1", ui.Unstyled("search")},
			{"2", ui.Unstyled("'foo bar ~y'")}}},
		{"1", []shown{{"1", ui.Unstyled("search")}}},
		{"-", []shown{
			{"M-,", ui.Unstyled(theLine)},
			{"-3", ui.Unstyled("qw")},
			{"-2", ui.Unstyled("search")},
			{"-1", ui.Unstyled("'foo bar ~y'")}}},
		{"-1", []shown{{"-1", ui.Unstyled("'foo bar ~y'")}}},
	}
)

func TestLastCmd(t *testing.T) {
	testListingFilter(t, "theLastCmd", theLastCmd, lastcmdFilterTests)
}

package edit

import (
	"testing"

	"github.com/elves/elvish/edit/ui"
)

var (
	theLine    = "qw search 'foo bar ~y'"
	theLastCmd = newLastCmd(theLine)

	lastcmdFilterTests = []listingFilterTestCases{
		{"", []shown{
			{"M-1", ui.Unstyled(theLine)},
			{"0", ui.Unstyled("qw")},
			{"1", ui.Unstyled("search")},
			{"2", ui.Unstyled("'foo bar ~y'")}}},
		{"1", []shown{{"1", ui.Unstyled("search")}}},
		{"-", []shown{
			{"M-1", ui.Unstyled(theLine)},
			{"-3", ui.Unstyled("qw")},
			{"-2", ui.Unstyled("search")},
			{"-1", ui.Unstyled("'foo bar ~y'")}}},
		{"-1", []shown{{"-1", ui.Unstyled("'foo bar ~y'")}}},
	}
)

func TestLastCmd(t *testing.T) {
	testListingFilter(t, "theLastCmd", theLastCmd, lastcmdFilterTests)
}

Fix test for lastcmd mode.


package core

import (
	"fmt"

	"github.com/akutz/gofig"

	"github.com/emccode/rexray/util"
)

func init() {
	initDrivers()

	gofig.SetGlobalConfigPath(util.EtcDirPath())
	gofig.SetUserConfigPath(fmt.Sprintf("%s/.rexray", util.HomeDir()))

	gofig.Register(globalRegistration())
	gofig.Register(driverRegistration())
}

func globalRegistration() *gofig.Registration {
	r := gofig.NewRegistration("Global")
	r.Yaml(`
rexray:
    host: tcp://:7979
    logLevel: warn
`)
	r.Key(gofig.String, "h", "tcp://:7979",
		"The REX-Ray host", "rexray.host")
	r.Key(gofig.String, "l", "warn",
		"The log level (error, warn, info, debug)", "rexray.logLevel")
	return r
}

func driverRegistration() *gofig.Registration {
	r := gofig.NewRegistration("Driver")
	r.Yaml(`
rexray:
    osDrivers:
    - linux
    storageDrivers:
    - libstorage
    volumeDrivers:
    - docker
`)
	r.Key(gofig.String, "", "linux",
		"The OS drivers to consider", "rexray.osDrivers")
	r.Key(gofig.String, "", "",
		"The storage drivers to consider", "rexray.storageDrivers")
	r.Key(gofig.String, "", "docker",
		"The volume drivers to consider", "rexray.volumeDrivers")
	return r
}

package core

import (
	"github.com/akutz/gofig"
)

func init() {
	initDrivers()
	gofig.Register(globalRegistration())
	gofig.Register(driverRegistration())
}

func globalRegistration() *gofig.Registration {
	r := gofig.NewRegistration("Global")
	r.Yaml(`
rexray:
    host: tcp://:7979
    logLevel: warn
`)
	r.Key(gofig.String, "h", "tcp://:7979",
		"The REX-Ray host", "rexray.host")
	r.Key(gofig.String, "l", "warn",
		"The log level (error, warn, info, debug)", "rexray.logLevel")
	return r
}

func driverRegistration() *gofig.Registration {
	r := gofig.NewRegistration("Driver")
	r.Yaml(`
rexray:
    osDrivers:
    - linux
    storageDrivers:
    - libstorage
    volumeDrivers:
    - docker
`)
	r.Key(gofig.String, "", "linux",
		"The OS drivers to consider", "rexray.osDrivers")
	r.Key(gofig.String, "", "",
		"The storage drivers to consider", "rexray.storageDrivers")
	r.Key(gofig.String, "", "docker",
		"The volume drivers to consider", "rexray.volumeDrivers")
	return r
}

Revert "Fix for not setting Gofig global/user dirs"


package main

import (
	"gform"
	"syscall"
	"w32"
)

const IDR_PNG1 = 100

func onpaint(arg *gform.EventArg) {
	if data, ok := arg.Data().(*gform.PaintEventData); ok {
		if bmp, err := gform.NewBitmapFromResource(
			gform.GetAppInstance(),
			w32.MakeIntResource(IDR_PNG1),
			syscall.StringToUTF16Ptr("PNG"),
			gform.RGB(255, 0, 0)); err == nil {
			data.Canvas.DrawBitmap(bmp, 10, 10)
			bmp.Dispose()
		} else {
			println(err.Error())
		}
	}
}

func main() {
	gform.Init()

	mf := gform.NewForm(nil)
	mf.SetSize(300, 200)
	mf.Center()

	mf.OnPaint().Bind(onpaint)

	mf.Show()

	gform.RunMainLoop()
}

package main

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

const IDR_PNG1 = 100

func onpaint(arg *gform.EventArg) {
	if data, ok := arg.Data().(*gform.PaintEventData); ok {
		if bmp, err := gform.NewBitmapFromResource(
			gform.GetAppInstance(),
			w32.MakeIntResource(IDR_PNG1),
			syscall.StringToUTF16Ptr("PNG"),
			gform.RGB(255, 0, 0)); err == nil {
			data.Canvas.DrawBitmap(bmp, 10, 10)
			bmp.Dispose()
		} else {
			println(err.Error())
		}
	}
}

func main() {
	gform.Init()

	mf := gform.NewForm(nil)
	mf.SetSize(300, 200)
	mf.Center()

	mf.OnPaint().Bind(onpaint)

	mf.Show()

	gform.RunMainLoop()
}

Update import path of gform and w32.


package http2

import (
	"github.com/summerwind/h2spec/config"
	"github.com/summerwind/h2spec/spec"
)

func HTTP2ConnectionPreface() *spec.TestGroup {
	tg := NewTestGroup("3.5", "HTTP/2 Connection Preface")

	tg.AddTestCase(&spec.TestCase{
		Desc:        "Sends invalid connection preface",
		Requirement: "The endpoint MUST terminate the TCP connection.",
		Run: func(c *config.Config, conn *spec.Conn) error {
			err := conn.Send("INVALID CONNECTION PREFACE\r\n\r\n")
			if err != nil {
				return err
			}

			return spec.VerifyConnectionClose(conn)
		},
	})

	return tg
}

package http2

import (
	"github.com/summerwind/h2spec/config"
	"github.com/summerwind/h2spec/spec"
	"golang.org/x/net/http2"
)

func HTTP2ConnectionPreface() *spec.TestGroup {
	tg := NewTestGroup("3.5", "HTTP/2 Connection Preface")

	// The server connection preface consists of a potentially empty
	// SETTINGS frame (Section 6.5) that MUST be the first frame
	// the server sends in the HTTP/2 connection.
	tg.AddTestCase(&spec.TestCase{
		Desc:        "Sends client connection preface",
		Requirement: "The server connection preface MUST be the first frame the server sends in the HTTP/2 connection.",
		Run: func(c *config.Config, conn *spec.Conn) error {
			setting := http2.Setting{
				ID:  http2.SettingInitialWindowSize,
				Val: spec.DefaultWindowSize,
			}

			conn.Send("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
			conn.WriteSettings(setting)

			return spec.VerifyFrameType(conn, http2.FrameSettings)
		},
	})

	// Clients and servers MUST treat an invalid connection preface as
	// a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
	tg.AddTestCase(&spec.TestCase{
		Desc:        "Sends invalid connection preface",
		Requirement: "The endpoint MUST terminate the TCP connection.",
		Run: func(c *config.Config, conn *spec.Conn) error {
			err := conn.Send("INVALID CONNECTION PREFACE\r\n\r\n")
			if err != nil {
				return err
			}

			// Connection has not negotiated, so we verify connection close
			// instead of connection error.
			return spec.VerifyConnectionClose(conn)
		},
	})

	return tg
}

Add test case for checking server connection preface


/*
ctxcopy is a Golang package which provides helper functions for performing context-aware copy task.

*/
package ctxcopy

/*
Package ctxcopy is a Golang package which provides helper functions for performing context-aware copy task.

*/
package ctxcopy

Add 'Package' before description to remove golint warnings.


package gogopro

import (
	"io/ioutil"
)

type Power struct {
	APIRequester *APIRequester
}

func (p *Power) Init() *Power {
	return p
}

func CreatePower(APIRequester *APIRequester) *Power {
	power := &Power{}
	power.APIRequester = APIRequester
	return power
}

func (p *Power) GetPowerStatus() (string, error) {
	resp, err := p.APIRequester.get("/bacpac/se")
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if body[len(body)-1] == 0 {
		return "off", nil
	}
	return "on", nil
}

package gogopro

import ()

type Power struct {
	APIRequester   *APIRequester
	StatusCommands map[string]StatusCommand
}

func (p *Power) Init() *Power {
	return p
}

func CreatePower(APIRequester *APIRequester) *Power {
	power := &Power{}
	power.APIRequester = APIRequester
	statusCommands := CreateStatusCommands()
	power.StatusCommands = statusCommands
	return power
}

func CreateStatusCommands() map[string]StatusCommand {
	sc := make(map[string]StatusCommand)
	sc["power"] = StatusCommand{Endpoint: "/bacpac/se", ResultByte: -1,
		Translaters: []StatusTranslater{
			StatusTranslater{
				Result:         0,
				ExpectedReturn: "off"},
			StatusTranslater{
				Result:         1,
				ExpectedReturn: "on"}}}
	return sc
}

func (p *Power) GetPowerStatus() (string, error) {
	result, err := p.StatusCommands["power"].RunStatusCommand(p.APIRequester)
	if err != nil {
		return "", err
	}
	return result, nil
}

Move status command to generic object


package day9

import "fmt"

func Solution() string {
	return fmt.Sprintf("Part 1: %d, Part 2: %s",
		len(decode(data)), decode(data))
}

func decode(input string) string {
	return input
}

package day9

import (
	"fmt"
	"regexp"
	"strconv"
)

var marker = regexp.MustCompile(`\((\d+)x(\d+)\)`)

func Solution() string {
	return fmt.Sprintf("Part 1: %d, Part 2: %s",
		len(decode(data)), "Not yet done")
}

func decode(input string) string {
	output := ""
	for i := 0; i < len(input); i++ {
		c := string(input[i])

		if c != "(" {
			output += c
		} else {
			length, next, repeat := getMarker(input[i:])
			i += length
			s := input[i : i+next]

			for ; repeat > 0; repeat-- {
				output += s
			}

			i += next - 1
		}
	}

	return output
}

func getMarker(input string) (int, int, int) {
	match := marker.FindStringSubmatch(input)
	next, _ := strconv.Atoi(match[1])
	repeat, _ := strconv.Atoi(match[2])

	return len(match[0]), next, repeat
}

Add day 9 part 1 solution


// Copyright 2018 The Ebiten 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.

// +build darwin
// +build !js
// +build !ios

package devicescale

// #cgo CFLAGS: -x objective-c
// #cgo LDFLAGS: -framework AppKit
//
// #import <AppKit/AppKit.h>
//
// static float scale() {
//   NSScreen* primary = [[NSScreen screens] firstObject];
//   return [primary backingScaleFactor];
// }
import "C"

func impl() float64 {
	return float64(C.scale())
}

// Copyright 2018 The Ebiten 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.

// +build darwin
// +build !js
// +build !ios

package devicescale

// #cgo CFLAGS: -x objective-c
// #cgo LDFLAGS: -framework AppKit
//
// #import <AppKit/AppKit.h>
//
// static float scale() {
//   NSScreen* primary = [NSScreen mainScreen];
//   return [primary backingScaleFactor];
// }
import "C"

func impl() float64 {
	return float64(C.scale())
}

Use mainScreen instead of screens[0] to get the 'current' screen state


package main

import (
	"fmt"
	"mime"
	"strings"
)

func main() {
	fmt.Println(strings.SplitN(mime.TypeByExtension(".avi"), "/", 2)[0])
}

package main

import (
	"../dlna/dms"
	"flag"
	"fmt"
)

func main() {
	flag.Parse()
	for _, arg := range flag.Args() {
		fmt.Println(dms.MimeTypeByPath(arg))
	}
}

Update the play file for testing dms.MimeTypeByPath


package bittrex

// Used in getmarkethistory
type Trade struct {
	OrderUuid string  `json:"OrderUuid"`
	Timestamp jTime   `json:"TimeStamp"`
	Quantity  float64 `json:"Quantity"`
	Price     float64 `json:"Price"`
	Total     float64 `json:"Total"`
	FillType  string  `json:"FillType"`
	OrderType string  `json:"OrderType"`
}

package bittrex

// Used in getmarkethistory
type Trade struct {
	OrderUuid int64   `json:"Id"`
	Timestamp jTime   `json:"TimeStamp"`
	Quantity  float64 `json:"Quantity"`
	Price     float64 `json:"Price"`
	Total     float64 `json:"Total"`
	FillType  string  `json:"FillType"`
	OrderType string  `json:"OrderType"`
}

Change json Tag for Trade struct from OrderUuid to Id for matching the current API


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

package prometheus

import (
	"reflect"
	"testing"

	"k8s.io/client-go/pkg/api/v1"

	"github.com/coreos/prometheus-operator/pkg/client/monitoring/v1alpha1"
)

func TestStatefulSetLabelingAndAnnotations(t *testing.T) {
	labels := map[string]string{
		"testlabel": "testlabelvalue",
	}
	annotations := map[string]string{
		"testannotation": "testannotationvalue",
	}

	sset := makeStatefulSet(v1alpha1.Prometheus{
		ObjectMeta: v1.ObjectMeta{
			Labels:      labels,
			Annotations: annotations,
		},
	}, nil)

	if !reflect.DeepEqual(labels, sset.Labels) || !reflect.DeepEqual(annotations, sset.Annotations) {
		t.Fatal("Labels or Annotations are not properly being propagated to the StatefulSet")
	}
}

Add license header to test file


package manager

import (
	ds "github.com/Comcast/traffic_control/traffic_monitor/experimental/traffic_monitor/deliveryservice"
	"sync"
)

type DSStatsThreadsafe struct {
	dsStats *ds.Stats
	m       *sync.RWMutex
}

func NewDSStatsThreadsafe() DSStatsThreadsafe {
	s := ds.NewStats()
	return DSStatsThreadsafe{m: &sync.RWMutex{}, dsStats: &s}
}

func (o *DSStatsThreadsafe) Get() ds.Stats {
	o.m.Lock()
	defer o.m.Unlock()
	return o.dsStats.Copy()
}

func (o *DSStatsThreadsafe) Set(newDsStats ds.Stats) {
	o.m.Lock()
	*o.dsStats = newDsStats
	o.m.Unlock()
}

package manager

import (
	ds "github.com/Comcast/traffic_control/traffic_monitor/experimental/traffic_monitor/deliveryservice"
	"sync"
)

type DSStatsThreadsafe struct {
	dsStats *ds.Stats
	m       *sync.RWMutex
}

func NewDSStatsThreadsafe() DSStatsThreadsafe {
	s := ds.NewStats()
	return DSStatsThreadsafe{m: &sync.RWMutex{}, dsStats: &s}
}

func (o *DSStatsThreadsafe) Get() ds.Stats {
	o.m.Lock()
	defer o.m.Unlock()
	return *o.dsStats
}

func (o *DSStatsThreadsafe) Set(newDsStats ds.Stats) {
	o.m.Lock()
	*o.dsStats = newDsStats
	o.m.Unlock()
}

Change TM2 DSStatsThreadsafe to not copy


package safe

import (
	"github.com/bndw/pick/errors"
)

func (s *Safe) Add(name, username, password string) (*Account, error) {
	if _, exists := s.Accounts[name]; exists {
		return nil, &errors.AccountExists{}
	}

	account := NewAccount(name, username, password)
	s.Accounts[name] = account

	if err := s.save(); err != nil {
		return nil, err
	}

	return &account, nil
}

package safe

import (
	"github.com/bndw/pick/errors"
)

func (s *Safe) Add(name, username, password string) (*Account, error) {
	if _, exists := s.Accounts[name]; exists {
		account := s.Accounts[name]
		return &account, &errors.AccountExists{}
	}

	account := NewAccount(name, username, password)
	s.Accounts[name] = account

	if err := s.save(); err != nil {
		return nil, err
	}

	return &account, nil
}

Fix issue when generating a new password for an already existing account.


package main

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

func main() {
	http.HandleFunc("/", handler)
	fmt.Println("listening...")
	err := http.ListenAndServe(":"+os.Getenv("PORT"), nil)
	if err != nil {
		panic(err)
	}
}

func handler(w http.ResponseWriter, r *http.Request) {
	// Read the Request Parameter "command"
	command := r.FormValue("command")

	if command == "/9gag" {
		fmt.Fprint(w, "Hello World")
	} else {
		fmt.Fprint(w, "I do not understand your command.")
	}
}

package main

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

func main() {
	http.HandleFunc("/", handler)
	fmt.Println("listening...")
	err := http.ListenAndServe(":"+os.Getenv("PORT"), nil)
	if err != nil {
		panic(err)
	}
}

func handler(w http.ResponseWriter, r *http.Request) {
	// Read the Request Parameter "command"
	command := r.FormValue("command")

	if command == "/9gag" {
		jsonResp(w, "Hello World")
	} else {
		fmt.Fprint(w, "I do not understand your command.")
	}
}

func jsonResp(w http.ResponseWriter, msg string) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	resp := map[string]string{"text": msg}
	r, err := json.Marshal(resp)
	if err != nil {
		fmt.Println("Couldn't marshal hook response:", err)
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Write(r)
}

Return json response instead of text.


package main

import (
	path "path/filepath"
	"os"
	"github.com/qlova/ilang/src"
	_ "github.com/qlova/ilang/src/modules/all"
	_ "github.com/qlova/ilang/src/types/all"
)

func ic(input, directory string) {

	file, err := os.Open(input)
	if err != nil {
		return
	}

	ic := ilang.NewCompiler(file)

	if directory == "" {
		directory = path.Dir(input)
	}

	//Open the output file with the file type replaced to .u
	var filename = path.Base(input)[:len(path.Base(input))-2]+".u"

	if output, err := os.Create(directory+"/"+filename); err != nil {
		ic.RaiseError("Could not create output file!", err.Error())
	} else {
		ic.Output = output
	}

	if lib, err := os.Create(directory+"/ilang.u"); err != nil {
		ic.RaiseError("Could not create output library file!", err.Error())
	} else {
		ic.Lib = lib
	}

	ic.Compile()
}

package main

import (
	path "path/filepath"
	"os"
	"github.com/qlova/ilang/src"
	_ "github.com/qlova/ilang/src/modules/all"
	_ "github.com/qlova/ilang/src/types/all"
)

func ic(input, directory string) {

	file, err := os.Open(input)
	if err != nil {
		return
	}

	ic := ilang.NewCompiler(file)

	if directory == "" {
		directory = path.Dir(input)
	}

	//Open the output file with the file type replaced to .u
	var filename = path.Base(input)[:len(path.Base(input))-2]+".u"

	if output, err := os.Create(directory+"/"+filename); err != nil {
		ic.RaiseError("Could not create output file!", err.Error())
	} else {
		ic.Output = output
		defer output.Close()
	}

	if lib, err := os.Create(directory+"/ilang.u"); err != nil {
		ic.RaiseError("Could not create output library file!", err.Error())
	} else {
		ic.Lib = lib
		defer lib.Close()
	}

	ic.Compile()
}

Fix .it directory not being deleted on windows.


package main

import (
	"log"
	"fmt"
)

type Synchronizer struct {
	Storage *Storage
}

func NewSynchronizer(storage *Storage) *Synchronizer {
	s := new(Synchronizer)
	s.Storage = storage

	return s
}

func (synchronizer *Synchronizer) Start() {
	provider := NewMattKetmoProvider()
	domains, _ := provider.Get()

	for _, domain := range domains {
		err := synchronizer.Storage.Add(domain)
		fmt.Println(domain)

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

	fmt.Println("done")
}

package main

import (
	"log"
	"fmt"
)

type Synchronizer struct {
	Storage *Storage
}

func NewSynchronizer(storage *Storage) *Synchronizer {
	synchronizer := new(Synchronizer)
	synchronizer.Storage = storage

	return synchronizer
}

func (synchronizer *Synchronizer) Start() {
	provider := NewMattKetmoProvider()
	domains, _ := provider.Get()
	synchronizer.addDomains(domains)

	fmt.Println("done")
}

func (synchronizer *Synchronizer) addDomains(domains []string) {
	for _, domain := range domains {
		err := synchronizer.Storage.Add(domain)
		fmt.Println(domain)

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

Add function for adding domains


// Package u5 currently provides a single utility to fetch the importers of a GoPackage via godoc.org API.
package u5

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

	"github.com/shurcooL/go/gists/gist7480523"
)

type goPackage struct {
	Path     string
	Synopsis string
}

// Importers contains the list of Go packages that import a given Go package.
type Importers struct {
	Results []goPackage
}

// GetGodocOrgImporters fetches the importers of goPackage via godoc.org API.
func GetGodocOrgImporters(goPackage *gist7480523.GoPackage) (*Importers, error) {
	resp, err := http.Get("http://api.godoc.org/importers/" + goPackage.Bpkg.ImportPath)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var importers Importers
	if err := json.NewDecoder(resp.Body).Decode(&importers); err != nil {
		return nil, err
	}

	return &importers, nil
}

// Package u5 currently provides a single utility to fetch the importers of a GoPackage via godoc.org API.
package u5

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

	"github.com/shurcooL/go/gists/gist7480523"
)

// GoPackage represents a Go package.
type GoPackage struct {
	Path     string // Import path of the package.
	Synopsis string // Synopsis of the package.
}

// Importers contains the list of Go packages that import a given Go package.
type Importers struct {
	Results []GoPackage
}

// GetGodocOrgImporters fetches the importers of goPackage via godoc.org API.
func GetGodocOrgImporters(goPackage *gist7480523.GoPackage) (*Importers, error) {
	resp, err := http.Get("http://api.godoc.org/importers/" + goPackage.Bpkg.ImportPath)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("non-200 status code: %v", resp.StatusCode)
	}

	var importers Importers
	if err := json.NewDecoder(resp.Body).Decode(&importers); err != nil {
		return nil, err
	}

	return &importers, nil
}

Check for 200 status code, better documented types.


package batcher

import (
	"runtime"
	"time"
)

const backoff = time.Microsecond

var yield func()

func yieldWithSleep() {
	time.Sleep(backoff)
}

func yieldWithGoSched() {
	runtime.Gosched()
}

func init() {
	yield = yieldWithSleep
}

package batcher

import (
	"runtime"
	"time"
)

const backoff = time.Microsecond * 10 // a too small backoff will lead to high CPU load

var yield func()

func yieldWithSleep() {
	time.Sleep(backoff)
}

func yieldWithGoSched() {
	runtime.Gosched()
}

func init() {
	yield = yieldWithSleep
}

FIX high CPU load issue


package golog

import "testing"

func TestFacts (t *testing.T) {
    db := NewDatabase().
            Asserta(NewTerm("father", NewTerm("michael"))).
            Asserta(NewTerm("father", NewTerm("marc")))
    t.Logf("%s\n", db.String())

    // these should be provably true
    if !IsTrue(db, NewTerm("father", NewTerm("michael"))) {
        t.Errorf("Couldn't prove father(michael)")
    }
    if !IsTrue(db, NewTerm("father", NewTerm("marc"))) {
        t.Errorf("Couldn't prove father(marc)")
    }

    // these should not be provable
    if IsTrue(db, NewTerm("father", NewTerm("sue"))) {
        t.Errorf("Proved father(sue)")
    }
    if IsTrue(db, NewTerm("mother", NewTerm("michael"))) {
        t.Errorf("Proved mother(michael)")
    }
}

package golog

import "testing"

func TestFacts (t *testing.T) {
    db := NewDatabase().
            Asserta(NewTerm("father", NewTerm("michael"))).
            Asserta(NewTerm("father", NewTerm("marc")))
    t.Logf("%s\n", db.String())

    // these should be provably true
    if !IsTrue(db, NewTerm("father", NewTerm("michael"))) {
        t.Errorf("Couldn't prove father(michael)")
    }
    if !IsTrue(db, NewTerm("father", NewTerm("marc"))) {
        t.Errorf("Couldn't prove father(marc)")
    }

    // these should not be provable
    if IsTrue(db, NewTerm("father", NewTerm("sue"))) {
        t.Errorf("Proved father(sue)")
    }
    if IsTrue(db, NewTerm("father", NewTerm("michael"), NewTerm("marc"))) {
        t.Errorf("Proved father(michael, marc)")
    }
    if IsTrue(db, NewTerm("mother", NewTerm("michael"))) {
        t.Errorf("Proved mother(michael)")
    }
}

Make sure arity mismatch affects provability


package sqlutil

// Returns a string containing the expression IN with one or more question
// marks for parameter interpolation. If numArgs argument is 3, the returned
// value would be "IN (?, ?, ?)"
func InParamString(numArgs int) string {
    resLen := 5 + ((numArgs * 3) - 2)
    res := make([]byte, resLen)
    res[0] = 'I'
    res[1] = 'N'
    res[2] = ' '
    res[3] = '('
    for x := 4; x < (resLen - 1); x++ {
        res[x] = '?'
        x++
        if x < (resLen - 1) {
            res[x] = ','
            x++
            res[x] = ' '
        }
    }
    res[resLen - 1] = ')'
    return string(res)
}

package sqlutil

import (
    "strings"

    "github.com/go-sql-driver/mysql"
)

// Returns a string containing the expression IN with one or more question
// marks for parameter interpolation. If numArgs argument is 3, the returned
// value would be "IN (?, ?, ?)"
func InParamString(numArgs int) string {
    resLen := 5 + ((numArgs * 3) - 2)
    res := make([]byte, resLen)
    res[0] = 'I'
    res[1] = 'N'
    res[2] = ' '
    res[3] = '('
    for x := 4; x < (resLen - 1); x++ {
        res[x] = '?'
        x++
        if x < (resLen - 1) {
            res[x] = ','
            x++
            res[x] = ' '
        }
    }
    res[resLen - 1] = ')'
    return string(res)
}

// Returns true if the supplied error represents a duplicate key error
func IsDuplicateKey(err error) bool {
    if err == nil {
        return false
    }
    me, ok := err.(*mysql.MySQLError)
    if ! ok {
        // TODO(jaypipes): Handle PostgreSQLisms here
        return false
    }
    if me.Number == 1062 {
        return true
    }
    return false
}

// Returns true if the supplied error is a duplicate key error and the supplied
// constraint name is the one that was violated
func IsDuplicateKeyOn(err error, constraintName string) bool {
    if err == nil {
        return false
    }
    me, ok := err.(*mysql.MySQLError)
    if ! ok {
        // TODO(jaypipes): Handle PostgreSQLisms here
        return false
    }
    return strings.Contains(me.Error(), constraintName)
}

Add utility functions for testing duplicate keys


package connections

type OutputMessageType uint8

const (
	OutputMessageTypeGame OutputMessageType = iota
	OutputMessageTypePlayer
	OutputMessageTypeBroadcast
)

var outputMessageTypeLabels = map[OutputMessageType]string{
	OutputMessageTypeGame:      "game",
	OutputMessageTypePlayer:    "player",
	OutputMessageTypeBroadcast: "broadcast",
}

func (t OutputMessageType) String() string {
	if label, ok := outputMessageTypeLabels[t]; ok {
		return label
	}
	return "unknown"
}

type OutputMessage struct {
	Type    OutputMessageType
	Payload interface{}
}

package connections

type OutputMessageType uint8

const (
	OutputMessageTypeGame OutputMessageType = iota
	OutputMessageTypePlayer
	OutputMessageTypeBroadcast
)

var outputMessageTypeLabels = map[OutputMessageType]string{
	OutputMessageTypeGame:      "game",
	OutputMessageTypePlayer:    "player",
	OutputMessageTypeBroadcast: "broadcast",
}

func (t OutputMessageType) String() string {
	if label, ok := outputMessageTypeLabels[t]; ok {
		return label
	}
	return "unknown"
}

var outputMessageTypeJSONs = map[OutputMessageType][]byte{
	OutputMessageTypeGame:      []byte(`"game"`),
	OutputMessageTypePlayer:    []byte(`"player"`),
	OutputMessageTypeBroadcast: []byte(`"broadcast"`),
}

func (t OutputMessageType) MarshalJSON() ([]byte, error) {
	if json, ok := outputMessageTypeJSONs[t]; ok {
		return json, nil
	}
	return []byte(`"unknown"`), nil
}

type OutputMessage struct {
	Type    OutputMessageType `json:"type"`
	Payload interface{}       `json:"payload"`
}

Implement JSON Marshaler interface for OutputMessage


package core

import (
	"fmt"
)

// writer points a shared state. sharedStateSink will point to the same shared state
// even after the state is removed from the context.
type sharedStateSink struct {
	writer Writer
}

// NewSharedStateSink creates a sink that writes to SharedState.
func NewSharedStateSink(ctx *Context, name string) (Sink, error) {
	// Get SharedState by name
	state, err := ctx.SharedStates.Get(name)
	if err != nil {
		return nil, err
	}

	// It fails if the shared state cannot be written
	writer, ok := state.(Writer)
	if !ok {
		return nil, fmt.Errorf("'%v' state cannot be written")
	}

	s := &sharedStateSink{
		writer: writer,
	}
	return s, nil
}

func (s *sharedStateSink) Write(ctx *Context, t *Tuple) error {
	return s.writer.Write(ctx, t)
}

func (s *sharedStateSink) Close(ctx *Context) error {
	closer, ok := s.writer.(WriteCloser)
	if !ok {
		return nil
	}
	return closer.Close(ctx)
}

package core

import (
	"fmt"
)

// writer points a shared state. sharedStateSink will point to the same shared state
// even after the state is removed from the context.
type sharedStateSink struct {
	writer Writer
}

// NewSharedStateSink creates a sink that writes to SharedState.
func NewSharedStateSink(ctx *Context, name string) (Sink, error) {
	// Get SharedState by name
	state, err := ctx.SharedStates.Get(name)
	if err != nil {
		return nil, err
	}

	// It fails if the shared state cannot be written
	writer, ok := state.(Writer)
	if !ok {
		return nil, fmt.Errorf("'%v' state cannot be written")
	}

	s := &sharedStateSink{
		writer: writer,
	}
	return s, nil
}

func (s *sharedStateSink) Write(ctx *Context, t *Tuple) error {
	return s.writer.Write(ctx, t)
}

func (s *sharedStateSink) Close(ctx *Context) error {
	return nil
}
}

Make sharedStateSink.Close return nil immediately


package sirius

/*
The MessageAction interface represents an action
that an extension wishes to perform on the
current message after execution has finished.

A MessageAction may return an error if it could
not be performed for any reason.
*/
type MessageAction interface {
	Perform(*Message) error
}

type EmptyAction struct{}

func NoAction() *EmptyAction {
	return &EmptyAction{}
}

func (na *EmptyAction) Perform(*Message) error {
	return nil
}

package sirius

/*
The MessageAction interface represents an action
that an extension wishes to perform on the
current message after execution has finished.

A MessageAction may return an error if it could
not be performed for any reason.
*/
type MessageAction interface {
	Perform(*Message) error
}

type EmptyAction struct{}

func NoAction() *EmptyAction {
	return &EmptyAction{}
}

func (*EmptyAction) Perform(*Message) error {
	return nil
}

Remove unnecessary receiver variable name


/*
Copyright 2014 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.
*/

// Examples contains sample applications for trying out the concepts in Kubernetes.
package examples // import "k8s.io/kubernetes/examples"

Use Go canonical import paths


package urlfetch

import "testing"
import "fmt"

// Local helper functions
func test_getdata4urls(urls []string) {
    // create HTTP client
    client := HttpClient()

    ch := make(chan []byte)
    n := 0
    for _, url := range urls {
        n++
        go Getdata(client, url, ch)
    }
    for i:=0; i<n; i++ {
        fmt.Println(string(<-ch))
    }
}
func test_getdata(url string) {
    // create HTTP client
    client := HttpClient()

    ch := make(chan []byte)
    go Getdata(client, url, ch)
    fmt.Println(string(<-ch))
}

// Test function
func TestGetdata(t *testing.T) {
    url1 := "http://www.google.com"
    url2 := "http://www.golang.org"
    urls := []string{url1, url2}
    t.Log("test getdata call")
    test_getdata(url1)
    t.Log("test getdata call with multiple urls")
    test_getdata4urls(urls)
}

package urlfetch

import "testing"
import "regexp"

// Local helper functions
func parse(output string) bool {
    test, err := regexp.MatchString("</html>", output)
    if  err != nil {
        return false
    }
    return test
}
func test_getdata4urls(urls []string) bool {
    ch := make(chan []byte)
    for _, url := range urls {
        go Getdata(url, ch)
    }
    for i := 0; i<len(urls); i++ {
        res := string(<-ch)
        if  ! parse(res) {
            return false
        }
    }
    return true
}
func test_getdata(url string) bool {
    ch := make(chan []byte)
    go Getdata(url, ch)
    res := string(<-ch)
    return parse(res)
}

// Test function
func TestGetdata(t *testing.T) {
    url1 := "http://www.google.com"
    url2 := "http://www.golang.org"
    urls := []string{url1, url2}
    var test bool
    test = test_getdata(url1)
    if  ! test {
        t.Log("test getdata call", url1)
        t.Fail()
    }
    test = test_getdata4urls(urls)
    if  ! test {
        t.Log("test getdata call with multiple urls", urls)
        t.Fail()
    }
}

Use regexp to match end of html; let local test function to return bool status


package github

import (
	"github.com/github/hub/git"
)

func IsHttpsProtocol() bool {
	httpProtocol, _ := git.Config("hub.protocol")
	if httpProtocol == "https" {
		return true
	}

	httpClone, _ := git.Config("--bool hub.http-clone")
	if httpClone == "true" {
		return true
	}

	return false
}

package github

import (
	"github.com/github/hub/git"
)

func IsHttpsProtocol() bool {
	httpProtocol, _ := git.Config("hub.protocol")
	if httpProtocol == "https" {
		return true
	}

	return false
}

Drop support for legacy `hub.http-clone` git config value


Remove the solution start with zero


package coreos

import (
	"github.com/bernardolins/clustereasy/scope"
	"github.com/bernardolins/clustereasy/service/etcd"
	"github.com/bernardolins/clustereasy/service/flannel"
	"github.com/bernardolins/clustereasy/service/fleet"
	"github.com/bernardolins/clustereasy/setup/types"
	"github.com/bernardolins/clustereasy/unit"
	"github.com/bernardolins/clustereasy/unit/default/coreos"
)

func CreateScope(node types.Node, cluster types.Cluster) *scope.Scope {
	etcd2 := etcd2.New()
	etcd2.Configure(node, cluster)

	fleet := fleet.New()
	fleet.Configure(node, cluster)

	flannel := flannel.New()
	flannel.Configure(node, cluster)

	coreos := scope.New("coreos")

	coreos.AddService(*etcd2)
	coreos.AddService(*fleet)
	coreos.AddService(*flannel)

	configureUnits(coreos, cluster)

	return coreos
}

func configureUnits(scope *scope.Scope, cluster types.Cluster) {
	for _, u := range cluster.GetUnits() {
		unit := unit.New(u.UnitName(), u.UnitCommand())
		scope.AddUnit(*unit)
	}

	for _, u := range unitdef.DefaultUnits() {
		scope.AddUnit(u)
	}
}

package coreos

import (
	"github.com/bernardolins/clustereasy/scope"
	"github.com/bernardolins/clustereasy/service/etcd"
	"github.com/bernardolins/clustereasy/service/flannel"
	"github.com/bernardolins/clustereasy/service/fleet"
	"github.com/bernardolins/clustereasy/setup/types"
	"github.com/bernardolins/clustereasy/unit"
	"github.com/bernardolins/clustereasy/unit/default"
)

func CreateScope(node types.Node, cluster types.Cluster) *scope.Scope {
	etcd2 := etcd2.New()
	etcd2.Configure(node, cluster)

	fleet := fleet.New()
	fleet.Configure(node, cluster)

	flannel := flannel.New()
	flannel.Configure(node, cluster)

	coreos := scope.New("coreos")

	coreos.AddService(*etcd2)
	coreos.AddService(*fleet)
	coreos.AddService(*flannel)

	configureUnits(coreos, cluster)

	return coreos
}

func configureUnits(scope *scope.Scope, cluster types.Cluster) {
	for _, u := range cluster.GetUnits() {
		unit := unit.New(u.UnitName(), u.UnitCommand())
		scope.AddUnit(unit)
	}

	for _, u := range unitdef.DefaultUnits() {
		scope.AddUnit(u)
	}
}

Fix error of unitdef package import after changing it's name


package uploadService

import (
	"strings"
)

func CheckTrackers(trackers []string) bool {
	// TODO: move to runtime configuration
	var deadTrackers = []string{ // substring matches!
		"://open.nyaatorrents.info:6544",
		"://tracker.openbittorrent.com:80",
		"://tracker.publicbt.com:80",
		"://stats.anisource.net:2710",
		"://exodus.desync.com",
		"://open.demonii.com:1337",
		"://tracker.istole.it:80",
		"://tracker.ccc.de:80",
		"://bt2.careland.com.cn:6969",
		"://announce.torrentsmd.com:8080"}

	var numGood int
	for _, t := range trackers {
		good := true
		for _, check := range deadTrackers {
			if strings.Contains(t, check) {
				good = false
			}
		}
		if good {
			numGood++
		}
	}
	return numGood > 0
}

package uploadService

import (
	"strings"
)

func CheckTrackers(trackers []string) bool {
	// TODO: move to runtime configuration
	var deadTrackers = []string{ // substring matches!
		"://open.nyaatorrents.info:6544",
		"://tracker.openbittorrent.com:80",
		"://tracker.publicbt.com:80",
		"://stats.anisource.net:2710",
		"://exodus.desync.com",
		"://open.demonii.com:1337",
		"://tracker.istole.it:80",
		"://tracker.ccc.de:80",
		"://bt2.careland.com.cn:6969",
		"://announce.torrentsmd.com:8080",
		"://open.demonii.com:1337",
		"://tracker.btcake.com",
		"://tracker.prq.to",
		"://bt.rghost.net"}

	var numGood int
	for _, t := range trackers {
		good := true
		for _, check := range deadTrackers {
			if strings.Contains(t, check) {
				good = false
			}
		}
		if good {
			numGood++
		}
	}
	return numGood > 0
}

Update list of dead trackers


package twigo

func NewClient(account_sid, auth_token, number string) (*Client, error) {

	c := &Client{AccountSid:account_sid,AuthToken:auth_token,Number:number}

	err := Validate(*c)

	if err != nil {
		return nil,err
	}

	return c, nil
}

func (c *Client) Text(msg_sms *SMS) (interface{}, error) {

	err := Validate(*msg_sms)

	if err != nil {
		return nil, err
	}

	smsResponse := &SMSResponse{}

	resp, err := Send(c, msg_sms, smsResponse)
	return resp,err
}

func (c *Client) Call(msg_voice *CALL) (interface{}, error) {

	err := Validate(*msg_voice)

	if err != nil {
		return nil, err
	}

	callResponse := &CALLResponse{}

	resp, err := Send(c, msg_voice, callResponse)
	return resp,err
}

package twigo

func NewClient(account_sid, auth_token, number string) (*Client, error) {

	c := &Client{AccountSid:account_sid,AuthToken:auth_token,Number:number}

	err := Validate(*c)

	if err != nil {
		return nil,err
	}

	return c, nil
}

func (c *Client) Text(msg_sms *SMS) (*SMSResponse, error) {

	err := Validate(*msg_sms)

	if err != nil {
		return nil, err
	}

	smsResponse := &SMSResponse{}

	err = Send(c, msg_sms, smsResponse)
	return smsResponse, err
}

func (c *Client) Call(msg_voice *CALL) (*CALLResponse, error) {

	err := Validate(*msg_voice)

	if err != nil {
		return nil, err
	}

	callResponse := &CALLResponse{}

	err = Send(c, msg_voice, callResponse)
	return callResponse, err
}

Return *SMSResponse for text and *CALLResponse for call


// Copyright 2017 Pilosa Corp.
//
// 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.
//
//go:generate statik -src=../webui -dest=..
//
// Package statik contains static assets for the Web UI. `go generate` or
// `make generate-statik` will produce statik.go, which is ignored by git.

package statik

import (
	"net/http"

	"github.com/pilosa/pilosa"
	"github.com/rakyll/statik/fs"
)

// Ensure nopFileSystem implements interface.
var _ pilosa.FileSystem = &FileSystem{}

// FileSystem represents a static FileSystem.
type FileSystem struct{}

// New is a statik implementation of FileSystem New method.
func (s *FileSystem) New() (http.FileSystem, error) {
	return fs.New()
}

Remove empty line between godoc and package declaration