// +build windows

/*
Copyright 2019 The Kubernetes Authors.

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

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

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

package dockershim

import (
	"bytes"
	"fmt"
	"io"

	"k8s.io/kubernetes/pkg/kubelet/util/ioutils"
)

func (r *streamingRuntime) portForward(podSandboxID string, port int32, stream io.ReadWriteCloser) error {
	stderr := new(bytes.Buffer)
	err := r.exec(podSandboxID, []string{"wincat.exe", "localhost", fmt.Sprint(port)}, stream, stream, ioutils.WriteCloserWrapper(stderr), false, nil, 0)
	if err != nil {
		return fmt.Errorf("%v: %s", err, stderr.String())
	}

	return nil
}

// +build windows

/*
Copyright 2019 The Kubernetes Authors.

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

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

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

package dockershim

import (
	"bytes"
	"fmt"
	"io"

	"k8s.io/kubernetes/pkg/kubelet/util/ioutils"
)

func (r *streamingRuntime) portForward(podSandboxID string, port int32, stream io.ReadWriteCloser) error {
	stderr := new(bytes.Buffer)
	err := r.exec(podSandboxID, []string{"wincat.exe", "127.0.0.1", fmt.Sprint(port)}, stream, stream, ioutils.WriteCloserWrapper(stderr), false, nil, 0)
	if err != nil {
		return fmt.Errorf("%v: %s", err, stderr.String())
	}

	return nil
}

Use ipv4 in wincat port forward


package main

import (
    "github.com/codegangsta/negroni"
    "github.com/gorilla/mux"
    "gopkg.in/unrolled/render.v1"
    "net/http"
)

var printer = render.New(render.Options {
    Layout: "layout",
    IndentJSON: true,
})

func main() {
    router := mux.NewRouter().StrictSlash(true)
    router.Path("/").HandlerFunc(HomeHandler).Name("home")

    resources := router.PathPrefix("/urls").Subrouter()
    resources.Methods("GET").Path("/").HandlerFunc(ResourcesIndexHandler).Name("resources_index")

    app := negroni.Classic()
    app.UseHandler(router)
    app.Run(":8080")
}

func HomeHandler(w http.ResponseWriter, req *http.Request) {
    data := map[string]interface{} {
        "title": "Home",
    }
    printer.HTML(w, http.StatusOK, "home", data)
}

func ResourcesIndexHandler(w http.ResponseWriter, req *http.Request) {
    urls := []string {
        "www.google.com",
        "www.yahoo.com",
        "www.cnn.com",
    }
    printer.JSON(w, http.StatusOK, map[string][]string {"urls": urls})
}

package main

import (
    "github.com/codegangsta/negroni"
    "github.com/gorilla/mux"
    "gopkg.in/unrolled/render.v1"
    "net/http"
)

var printer = render.New(render.Options {
    Layout: "layout",
    IndentJSON: true,
})

func main() {
    router := mux.NewRouter().StrictSlash(true)
    router.Path("/").HandlerFunc(HomeHandler).Name("home")

    urls := router.PathPrefix("/urls").Subrouter()
    urls.Methods("GET").Path("/").HandlerFunc(UrlsIndexHandler).Name("urls_index")

    app := negroni.Classic()
    app.UseHandler(router)
    app.Run(":8080")
}

func HomeHandler(w http.ResponseWriter, req *http.Request) {
    data := map[string]interface{} {
        "title": "Home",
    }
    printer.HTML(w, http.StatusOK, "home", data)
}

func UrlsIndexHandler(w http.ResponseWriter, req *http.Request) {
    urls := []string {
        "www.google.com",
        "www.yahoo.com",
        "www.cnn.com",
    }
    printer.JSON(w, http.StatusOK, map[string][]string {"urls": urls})
}

Use Urls instead of Resources for name


package godbg

import (
	"os"
	"testing"
	. "github.com/smartystreets/goconvey/convey"
)

func TestProject(t *testing.T) {
	Convey("Test buffers", t, func() {

		Convey("By Default, equals to std", func() {
			So(Out(), ShouldEqual, os.Stdout)
			So(Err(), ShouldEqual, os.Stderr)
		})
		Convey("When set to buffer, no longer equals to std", func() {
			SetBuffers(nil)
			So(Out(), ShouldNotEqual, os.Stdout)
			So(Err(), ShouldNotEqual, os.Stderr)
		})
	})
}

package godbg

import (
	"os"
	"testing"
	. "github.com/smartystreets/goconvey/convey"
)

func TestProject(t *testing.T) {
	Convey("Test buffers", t, func() {

		Convey("By Default, equals to std", func() {
			So(Out(), ShouldEqual, os.Stdout)
			So(Err(), ShouldEqual, os.Stderr)
		})
		Convey("When set to buffer, no longer equals to std", func() {
			SetBuffers(nil)
			So(Out(), ShouldNotEqual, os.Stdout)
			So(Err(), ShouldNotEqual, os.Stderr)
		})
		Convey("By Default, a new pdbg instance buffer equals to std", func() {
			apdbg := NewPdbg()
			So(apdbg.Out(), ShouldEqual, os.Stdout)
			So(apdbg.Err(), ShouldEqual, os.Stderr)
		})
		Convey("By Default, a new pdbg instance set to buffer writes no longer equals to std", func() {
			apdbg := NewPdbg(SetBuffers)
			So(apdbg.Out(), ShouldNotEqual, os.Stdout)
			So(apdbg.Err(), ShouldNotEqual, os.Stderr)
		})
	})
}

Test buffers for a new instance of Pdbg


// +build !glib_deprecated

package glib

// #include <gio/gio.h>
// #include <glib.h>
// #include <glib-object.h>
// #include "glib.go.h"
import "C"
import "unsafe"

// DupSource is a wrapper around g_binding_dup_source().
func (v *Binding) DupSource() *Object {
	obj := C.g_binding_dup_source(v.native())
	if obj == nil {
		return nil
	}
	return wrapObject(unsafe.Pointer(obj))
}

// DupTarget is a wrapper around g_binding_dup_target().
func (v *Binding) DupTarget() *Object {
	obj := C.g_binding_dup_target(v.native())
	if obj == nil {
		return nil
	}
	return wrapObject(unsafe.Pointer(obj))
}

//go:build !glib_deprecated && !glib_2_40 && !glib_2_42 && !glib_2_44 && !glib_2_46 && !glib_2_48 && !glib_2_50 && !glib_2_52 && !glib_2_54 && !glib_2_56 && !glib_2_58 && !glib_2_60 && !glib_2_62 && !glib_2_64 && !glib_2_66
// +build !glib_deprecated,!glib_2_40,!glib_2_42,!glib_2_44,!glib_2_46,!glib_2_48,!glib_2_50,!glib_2_52,!glib_2_54,!glib_2_56,!glib_2_58,!glib_2_60,!glib_2_62,!glib_2_64,!glib_2_66

package glib

// #include <gio/gio.h>
// #include <glib.h>
// #include <glib-object.h>
// #include "glib.go.h"
import "C"
import "unsafe"

// DupSource is a wrapper around g_binding_dup_source().
func (v *Binding) DupSource() *Object {
	obj := C.g_binding_dup_source(v.native())
	if obj == nil {
		return nil
	}
	return wrapObject(unsafe.Pointer(obj))
}

// DupTarget is a wrapper around g_binding_dup_target().
func (v *Binding) DupTarget() *Object {
	obj := C.g_binding_dup_target(v.native())
	if obj == nil {
		return nil
	}
	return wrapObject(unsafe.Pointer(obj))
}

Update Binding build tags to only build on later versions of Glib. This adds the build tags in both the old and new format, for maximum compatibility.


package sub

import (
	"github.com/Symantec/Dominator/lib/filesystem"
	"github.com/Symantec/Dominator/lib/hash"
	"github.com/Symantec/Dominator/lib/triggers"
	"github.com/Symantec/Dominator/proto/common"
	"github.com/Symantec/Dominator/sub/scanner"
)

type Configuration struct {
	ScanSpeedPercent    uint
	NetworkSpeedPercent uint
	ScanExclusionList   []string
}

type FetchRequest struct {
	ServerAddress string
	Hashes        []hash.Hash
}

type FetchResponse common.StatusResponse

type GetConfigurationRequest struct {
}

type GetConfigurationResponse Configuration

type PollRequest struct {
	HaveGeneration uint64
}

type PollResponse struct {
	NetworkSpeed     uint64
	FetchInProgress  bool // Fetch() and Update() are mutually exclusive.
	UpdateInProgress bool
	GenerationCount  uint64
	FileSystem       *scanner.FileSystem
}

type SetConfigurationRequest Configuration

type SetConfigurationResponse common.StatusResponse

type Directory struct {
	Name string
	Mode filesystem.FileMode
	Uid  uint32
	Gid  uint32
}

type UpdateRequest struct {
	PathsToDelete       []string
	DirectoriesToMake   []Directory
	DirectoriesToChange []Directory
	Triggers            *triggers.Triggers
}

type UpdateResponse struct{}

package sub

import (
	"github.com/Symantec/Dominator/lib/filesystem"
	"github.com/Symantec/Dominator/lib/hash"
	"github.com/Symantec/Dominator/lib/triggers"
	"github.com/Symantec/Dominator/proto/common"
	"github.com/Symantec/Dominator/sub/scanner"
)

type Configuration struct {
	ScanSpeedPercent    uint
	NetworkSpeedPercent uint
	ScanExclusionList   []string
}

type FetchRequest struct {
	ServerAddress string
	Hashes        []hash.Hash
}

type FetchResponse common.StatusResponse

type GetConfigurationRequest struct {
}

type GetConfigurationResponse Configuration

type PollRequest struct {
	HaveGeneration uint64
}

type PollResponse struct {
	NetworkSpeed     uint64
	FetchInProgress  bool // Fetch() and Update() are mutually exclusive.
	UpdateInProgress bool
	GenerationCount  uint64
	FileSystem       *scanner.FileSystem
}

type SetConfigurationRequest Configuration

type SetConfigurationResponse common.StatusResponse

type Directory struct {
	Name string
	Mode filesystem.FileMode
	Uid  uint32
	Gid  uint32
}

type Hardlink struct {
	Source string
	Target string
}

type UpdateRequest struct {
	PathsToDelete       []string
	DirectoriesToMake   []Directory
	DirectoriesToChange []Directory
	HardlinksToMake     []Hardlink
	Triggers            *triggers.Triggers
}

type UpdateResponse struct{}

Add HardlinksToMake to UpdateRequest RPC message.


// Copyright 2015 Andrew E. Bruno. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.

package nwalgo

import (
	"testing"
)

func TestAlign(t *testing.T) {
	seqs := [][]string{
		[]string{"CGAGAGA", "GAGAGA", "CGAGAGA", "-GAGAGA"}}

	for _, a := range seqs {
		aln1, aln2, _ := Align(a[0], a[1], 1, -1, -1)
		if aln1 != a[2] || aln2 != a[3] {
			t.Errorf("Align(%s, %s)\n***GOT***\n%s\n%s\n***WANT***\n%s\n%s", a[0], a[1], aln1, aln2, a[2], a[3])
		}
	}

}

func BenchmarkAlign(b *testing.B) {
	seq1 := "GGAATTAATCCAGGTAATGGACCCCAAGAT"
	seq2 := "GCCAGGATTCCCAGATATGGCCAAGGTTCC"

	for i := 0; i < b.N; i++ {
		Align(seq1, seq2, 1, -1, -1)
	}
}

Add basic benchmark for Align


package main

import (
    "github.com/dustin/go-humanize"
    "time"
    "strings"
)

func HumanTime(time time.Time) string {
    original := humanize.Time(time)
    parts := strings.Split(original, " ")
    return parts[0] + " " + parts[1]
}

package main

import (
    "github.com/dustin/go-humanize"
    "time"
    "strings"
    "math"
)

func HumanTime(time time.Time) string {
    original := humanize.Time(time)
    parts := strings.Split(original, " ")
    length := int(math.Min(float64(len(parts)), 2)) // now / x minutes
    parts = parts[:length]
    return strings.Join(parts, " ")
}

Fix fatal error when pokemon expires “now”


// Package hashutil provides alloc free alternatives for pkg/hash
package hashutil

func HashStringFnv64a(str string) uint64 {
	h := NewInlineFNV64a()
	h.WriteString(str)
	return h.Sum64()
}

// TODO:
// https://segment.com/blog/allocation-efficiency-in-high-performance-go-services/
// https://github.com/segmentio/fasthash

Update refer for perf optimization


package usb

import "testing"

func BenchmarkCGo(b *testing.B) {
	for _, bc := range []struct {
		name  string
		bfunc func(*libusbContext, int)
	}{
		{
			name: "simple function",
			bfunc: func(ctx *libusbContext, N int) {
				for i := 0; i < N; i++ {
					libusbSetDebug(ctx, i&1)
				}
			},
		},
		{
			name: "method",
			bfunc: func(ctx *libusbContext, N int) {
				impl := libusbImpl{}
				for i := 0; i < N; i++ {
					impl.setDebug(ctx, i&1)
				}
			},
		},
		{
			name: "interface",
			bfunc: func(ctx *libusbContext, N int) {
				var intf libusbIntf = libusbImpl{}
				for i := 0; i < N; i++ {
					intf.setDebug(ctx, i&1)
				}
			},
		},
	} {
		b.Run(bc.name, func(b *testing.B) {
			ctx, err := libusbImpl{}.init()
			if err != nil {
				b.Fatalf("libusb_init() failed: %v", err)
			}
			b.ResetTimer()
			bc.bfunc(ctx, b.N)
		})
	}
}

package usb

import "testing"

func BenchmarkCGo(b *testing.B) {
	for _, bc := range []struct {
		name  string
		bfunc func(*libusbContext, int)
	}{
		{
			name: "simple function",
			bfunc: func(ctx *libusbContext, N int) {
				for i := 0; i < N; i++ {
					libusbSetDebug(ctx, i&1)
				}
			},
		},
		{
			name: "method",
			bfunc: func(ctx *libusbContext, N int) {
				impl := libusbImpl{}
				for i := 0; i < N; i++ {
					impl.setDebug(ctx, i&1)
				}
			},
		},
		{
			name: "interface",
			bfunc: func(ctx *libusbContext, N int) {
				var intf libusbIntf = libusbImpl{}
				for i := 0; i < N; i++ {
					intf.setDebug(ctx, i&1)
				}
			},
		},
	} {
		b.Run(bc.name, func(b *testing.B) {
			ctx, err := libusbImpl{}.init()
			if err != nil {
				b.Fatalf("libusb_init() failed: %v", err)
			}
			defer libusbImpl{}.exit(ctx)
			b.ResetTimer()
			bc.bfunc(ctx, b.N)
		})
	}
}

Exit libusb context when done.


package awsSdkGo

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/autoscaling"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/aws/aws-sdk-go/service/s3"
)

type Sdk struct {
	Ec2 *ec2.EC2
	S3  *s3.S3
	ASG *autoscaling.AutoScaling
}

func NewSdk(region string) (*Sdk, error) {
	sdk := &Sdk{}
	session, err := session.NewSession(&aws.Config{Region: aws.String(region)})
	if err != nil {
		return nil, err
	}
	sdk.Ec2 = ec2.New(session)
	sdk.ASG = autoscaling.New(session)
	sdk.S3 = s3.New(session)
	return sdk, nil
}

package awsSdkGo

import (
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/autoscaling"
	"github.com/aws/aws-sdk-go/service/ec2"
	"github.com/aws/aws-sdk-go/service/s3"
)

type Sdk struct {
	Ec2 *ec2.EC2
	S3  *s3.S3
	ASG *autoscaling.AutoScaling
}

func NewSdk(region string) (*Sdk, error) {
	sdk := &Sdk{}
	session, err := session.NewSessionWithOptions(session.Options{
		Config: aws.Config{Region: aws.String(region)},
		// Support MFA when authing using assumed roles.
		SharedConfigState:       session.SharedConfigEnable,
		AssumeRoleTokenProvider: stscreds.StdinTokenProvider,
	})
	if err != nil {
		return nil, err
	}
	sdk.Ec2 = ec2.New(session)
	sdk.ASG = autoscaling.New(session)
	sdk.S3 = s3.New(session)
	return sdk, nil
}

Support MFA and roles when doing auth


package gradientdescent_test

import (
	"github.com/amitkgupta/goodlearn/optimizer/gradientdescent"

	"errors"

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

var _ = Describe("GradientDescent", func() {
	var goodGradient func([]float64) ([]float64, error)

	BeforeEach(func() {
		goodGradient = func(x []float64) ([]float64, error) {
			g := make([]float64, len(x))
			for i, xi := range x {
				g[i] = 2 * xi
			}
			return g, nil
		}
	})

	Context("When given an empty initial guess", func() {
		It("Returns an error", func() {
			_, err := gradientdescent.GradientDescent([]float64{}, 0.05, 0.0005, 100000, goodGradient)
			Ω(err).Should(HaveOccurred())
		})
	})

	Context("When the given gradient function returns an error", func() {
		It("Returns an error", func() {
			badGradient := func(x []float64) ([]float64, error) {
				return nil, errors.New("I'm bad")
			}
			_, err := gradientdescent.GradientDescent([]float64{0.3, -0.4}, 0.05, 0.0005, 100000, badGradient)
			Ω(err).Should(HaveOccurred())
		})
	})

	Context("When given reasonable inputs", func() {
		var estimatedArgMin []float64
		var err error

		BeforeEach(func() {
			estimatedArgMin, err = gradientdescent.GradientDescent([]float64{0.3, -0.4}, 0.05, 0.0005, 100000, goodGradient)
		})

		It("Does not return an error", func() {
			Ω(err).ShouldNot(HaveOccurred())
		})

		It("Returns a reasonable output (local arg-min of the function with given gradient)", func() {
			Ω(estimatedArgMin[0]).Should(BeNumerically("~", 0.0, 0.005))
			Ω(estimatedArgMin[1]).Should(BeNumerically("~", 0.0, 0.005))
		})
	})
})

Add test for gradient descent


package lib

import (
	"errors"
	"strings"
)

// MultiError implements error interface.
// An instance of MultiError has zero or more errors.
type MultiError struct {
	errs []error
}

// Push adds an error to MultiError.
func (m *MultiError) Push(errString string) {
	m.errs = append(m.errs, errors.New(errString))
}

// HasError checks if MultiError has any error.
func (m *MultiError) HasError() *MultiError {
	if len(m.errs) == 0 {
		return nil
	}
	return m
}

// Error implements error interface.
func (m *MultiError) Error() string {
	var formattedError []string
	for _, e := range m.errs {
		formattedError = append(formattedError, e.Error())
	}

	return strings.Join(formattedError, "\n")
}

package lib

import (
	"errors"
	"strings"
)

// MultiError implements error interface.
// An instance of MultiError has zero or more errors.
type MultiError struct {
	errs []error
}

// Push adds an error to MultiError.
func (m *MultiError) Push(errString string) {
	m.errs = append(m.errs, errors.New(errString))
}

// HasError checks if MultiError has any error.
func (m *MultiError) HasError() *MultiError {
	if len(m.errs) == 0 {
		return nil
	}
	return m
}

// Error implements error interface.
func (m *MultiError) Error() string {
	formattedError := make([]string, len(m.errs))
	for i, e := range m.errs {
		formattedError[i] = e.Error()
	}

	return strings.Join(formattedError, "\n")
}

Use array if fixed size length for errors


package v7

import (
	"code.cloudfoundry.org/cli/command/translatableerror"
)

type PasswdCommand struct {
	BaseCommand

	usage interface{} `usage:"CF_NAME passwd"`
}

func (cmd PasswdCommand) Execute(args []string) error {
	err := cmd.SharedActor.CheckTarget(false, false)
	if err != nil {
		return err
	}

	currentUser, err := cmd.Config.CurrentUser()
	if err != nil {
		return err
	}

	currentPassword, err := cmd.UI.DisplayPasswordPrompt("Current password")
	if err != nil {
		return err
	}

	newPassword, err := cmd.UI.DisplayPasswordPrompt("New password")
	if err != nil {
		return err
	}

	verifyPassword, err := cmd.UI.DisplayPasswordPrompt("Verify password")
	if err != nil {
		return err
	}

	cmd.UI.DisplayNewline()

	cmd.UI.DisplayTextWithFlavor("Changing password for user {{.Username}}...", map[string]interface{}{
		"Username": currentUser.Name,
	})

	cmd.UI.DisplayNewline()

	if newPassword != verifyPassword {
		return translatableerror.PasswordVerificationFailedError{}
	}

	err = cmd.Actor.UpdateUserPassword(currentUser.GUID, currentPassword, newPassword)
	if err != nil {
		return err
	}

	cmd.UI.DisplayOK()

	cmd.Config.UnsetUserInformation()
	cmd.UI.DisplayText("Please log in again.")

	return nil
}

package v7

import (
	"code.cloudfoundry.org/cli/command/translatableerror"
)

type PasswdCommand struct {
	BaseCommand

	usage interface{} `usage:"CF_NAME passwd"`
}

func (cmd PasswdCommand) Execute(args []string) error {
	err := cmd.SharedActor.CheckTarget(false, false)
	if err != nil {
		return err
	}

	currentUser, err := cmd.Config.CurrentUser()
	if err != nil {
		return err
	}

	currentPassword, err := cmd.UI.DisplayPasswordPrompt("Current password")
	if err != nil {
		return err
	}

	newPassword, err := cmd.UI.DisplayPasswordPrompt("New password")
	if err != nil {
		return err
	}

	verifyPassword, err := cmd.UI.DisplayPasswordPrompt("Verify password")
	if err != nil {
		return err
	}

	cmd.UI.DisplayNewline()

	cmd.UI.DisplayTextWithFlavor("Changing password for user {{.Username}}...", map[string]interface{}{
		"Username": currentUser.Name,
	})

	if newPassword != verifyPassword {
		return translatableerror.PasswordVerificationFailedError{}
	}

	err = cmd.Actor.UpdateUserPassword(currentUser.GUID, currentPassword, newPassword)
	if err != nil {
		return err
	}

	cmd.UI.DisplayOK()

	cmd.Config.UnsetUserInformation()
	cmd.UI.DisplayText("Please log in again.")

	return nil
}

Remove extra newline from `passwd` output


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

package local_test

import (
	gc "launchpad.net/gocheck"

	"launchpad.net/juju-core/environs/local"
	jc "launchpad.net/juju-core/testing/checkers"
)

type environSuite struct {
	baseProviderSuite
}

var _ = gc.Suite(&environSuite{})

func (*environSuite) TestOpenFailsWithoutDirs(c *gc.C) {
	testConfig := minimalConfig(c)

	environ, err := local.Provider.Open(testConfig)
	c.Assert(err, gc.ErrorMatches, "storage directory .* does not exist, bootstrap first")
	c.Assert(environ, gc.IsNil)
}

func (s *environSuite) TestName(c *gc.C) {
	c.Logf("root: %s", s.root)
	c.Assert(s.root, jc.IsDirectory)

	testConfig := minimalConfig(c)
	err := local.CreateDirs(c, testConfig)
	c.Assert(err, gc.IsNil)

	environ, err := local.Provider.Open(testConfig)
	c.Assert(err, gc.IsNil)

	c.Assert(environ.Name(), gc.Equals, "test")
}

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

package local_test

import (
	gc "launchpad.net/gocheck"

	"launchpad.net/juju-core/environs/local"
	jc "launchpad.net/juju-core/testing/checkers"
)

type environSuite struct {
	baseProviderSuite
}

var _ = gc.Suite(&environSuite{})

func (*environSuite) TestOpenFailsWithoutDirs(c *gc.C) {
	testConfig := minimalConfig(c)

	environ, err := local.Provider.Open(testConfig)
	c.Assert(err, gc.ErrorMatches, "storage directory .* does not exist, bootstrap first")
	c.Assert(environ, gc.IsNil)
}

func (s *environSuite) TestNameAndStorage(c *gc.C) {
	c.Logf("root: %s", s.root)
	c.Assert(s.root, jc.IsDirectory)

	testConfig := minimalConfig(c)
	err := local.CreateDirs(c, testConfig)
	c.Assert(err, gc.IsNil)

	environ, err := local.Provider.Open(testConfig)
	c.Assert(err, gc.IsNil)
	c.Assert(environ.Name(), gc.Equals, "test")
	c.Assert(environ.Storage(), gc.NotNil)
	c.Assert(environ.SharedStorate(), gc.NotNil)
}

Test that the environment as non-nil storage.


package minion

// AllRoutes a shortcut to be used on the UnauthenticatedRoutes when
// you want to have all your routes without jwt verification
const AllRoutes = "^.*$"

func lastChar(str string) (lc uint8) {
	size := len(str)
	if size == 0 {
		return lc
	}
	return str[size-1]
}

package minion

// AllRoutes a shortcut to be used on the UnauthenticatedRoutes when
// you want to have all your routes without jwt verification
var AllRoutes = []string{"^.*$"}

func lastChar(str string) (lc uint8) {
	size := len(str)
	if size == 0 {
		return lc
	}
	return str[size-1]
}

Simplify the shortcut for AllRoutes


package main

import (
	"fmt"
	"socialapi/workers/common/runner"
	"socialapi/workers/helper"

	"socialapi/workers/sitemap/sitemapgenerator/generator"
)

var (
	Name = "SitemapGenerator"
)

func main() {
	r := runner.New(Name)
	if err := r.Init(); err != nil {
		fmt.Println(err)
		return
	}

	redisConn := helper.MustInitRedisConn(r.Conf.Redis)
	defer redisConn.Close()

	handler, err := generator.New(r.Log)
	if err != nil {
		r.Log.Error("Could not create sitemap generator: %s", err)
	}

	r.ShutdownHandler = handler.Shutdown
	r.Wait()
}

package main

import (
	"fmt"
	"socialapi/workers/common/runner"
	"socialapi/workers/helper"

	"socialapi/workers/sitemap/sitemapgenerator/generator"
)

var (
	Name = "SitemapGenerator"
)

func main() {
	r := runner.New(Name)
	if err := r.Init(); err != nil {
		fmt.Println(err)
		return
	}

	redisConn := helper.MustInitRedisConn(r.Conf.Redis)
	defer redisConn.Close()

	controller, err := generator.New(r.Log)
	if err != nil {
		r.Log.Error("Could not create sitemap generator: %s", err)
	}

	r.ShutdownHandler = controller.Shutdown
	r.Wait()
}

Change handler variable to controller


package buffer

import (
	"strings"

	log "github.com/golang/glog"

	"github.com/youtube/vitess/go/vt/vterrors"

	vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc"
)

// This function is in a separate file to make it easier to swap out an
// open-source implementation with any internal Google-only implementation.

func causedByFailover(err error) bool {
	log.V(2).Infof("Checking error (type: %T) if it is caused by a failover. err: %v", err, err)
	if vtErr, ok := err.(vterrors.VtError); ok {
		if vtErr.VtErrorCode() == vtrpcpb.ErrorCode_QUERY_NOT_SERVED {
			if strings.Contains(err.Error(), "retry: operation not allowed in state NOT_SERVING") ||
				strings.Contains(err.Error(), "retry: operation not allowed in state SHUTTING_DOWN") ||
				strings.Contains(err.Error(), "retry: The MariaDB server is running with the --read-only option so it cannot execute this statement (errno 1290) (sqlstate HY000)") {
				return true
			}
		}
	}
	return false
}

package buffer

import (
	"strings"

	log "github.com/golang/glog"

	"github.com/youtube/vitess/go/vt/vterrors"

	vtrpcpb "github.com/youtube/vitess/go/vt/proto/vtrpc"
)

// This function is in a separate file to make it easier to swap out an
// open-source implementation with any internal Google-only implementation.

func causedByFailover(err error) bool {
	log.V(2).Infof("Checking error (type: %T) if it is caused by a failover. err: %v", err, err)
	if vtErr, ok := err.(vterrors.VtError); ok {
		if vtErr.VtErrorCode() == vtrpcpb.ErrorCode_QUERY_NOT_SERVED {
			if strings.Contains(err.Error(), "retry: operation not allowed in state NOT_SERVING") ||
				strings.Contains(err.Error(), "retry: operation not allowed in state SHUTTING_DOWN") ||
				strings.Contains(err.Error(), "retry: The MariaDB server is running with the --read-only option so it cannot execute this statement (errno 1290) (sqlstate HY000)") ||
				// Match 1290 if -queryserver-config-terse-errors explicitly hid the error message (which it does to avoid logging the original query including any PII).
				strings.Contains(err.Error(), "retry: (errno 1290) (sqlstate HY000) during query:") {
				return true
			}
		}
	}
	return false
}

Add matching for errno 1290 if no error message is present.


package pnet

import (
	"io"

	ipnet "github.com/libp2p/go-libp2p-interface-pnet"
)

func NewProtector(input io.Reader) (ipnet.Protector, error) {
	psk, err := decodeV1PSKKey(input)
	if err != nil {
		return nil, err
	}
	return &protector{psk}, nil
}

package pnet

import (
	"bytes"

	ipnet "github.com/libp2p/go-libp2p-interface-pnet"
)

func NewProtector(key []byte) (ipnet.Protector, error) {
	reader := bytes.NewReader(key)

	psk, err := decodeV1PSKKey(reader)
	if err != nil {
		return nil, err
	}
	return &protector{psk}, nil
}

Move from reader base ctor to bytestring based one


package jiradata

import (
	"strings"
)

// Find will search the transitions for one that matches
// the given name.  It will return a valid trantion that matches
// or nil
func (t Transitions) Find(name string) *Transition {
	name = strings.ToLower(name)
	for _, trans := range t {
		if strings.Contains(strings.ToLower(trans.Name), name) {
			return trans
		}
	}
	return nil
}

package jiradata

import (
	"strings"
)

// Find will search the transitions for one that matches
// the given name.  It will return a valid trantion that matches
// or nil
func (t Transitions) Find(name string) *Transition {
	name = strings.ToLower(name)
	matches := []Transitions{}
	for _, trans := range t {
		if strings.Compare(strings.ToLower(trans.Name), name) == 0 {
			return trans
		}
		if strings.Contains(strings.ToLower(trans.Name), name) {
			matches = append(matches, trans)
		}
	}
	if len(matches) > 0 {
		return matches[0]
	}
	return nil
}

Choose exact transition match if available


package aws

import (
	"testing"

	"fmt"

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

func TestAccAWSSQSQueue_importBasic(t *testing.T) {
	resourceName := "aws_sqs_queue.queue-with-defaults"
	queueName := fmt.Sprintf("sqs-queue-%s", acctest.RandString(5))

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSSQSQueueDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAWSSQSConfigWithDefaults(queueName),
			},

			resource.TestStep{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
				//The name is never returned after the initial create of the queue.
				//It is part of the URL and can be split down if needed
				//ImportStateVerifyIgnore: []string{"name"},
			},
		},
	})
}

package aws

import (
	"testing"

	"fmt"

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

func TestAccAWSSQSQueue_importBasic(t *testing.T) {
	resourceName := "aws_sqs_queue.queue"
	queueName := fmt.Sprintf("sqs-queue-%s", acctest.RandString(5))

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckAWSSQSQueueDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAWSSQSConfigWithDefaults(queueName),
			},

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

Change the resource name expected as part of sqs queue import test


package env

import (
	"encoding/json"
	"flag"
	"os"
)

type config struct {
	Database string   `json:"database"`
	Telegram telegram `json:"telegram"`
	VK       vk       `json:"vk"`
}

type telegram struct {
	Webhook string `json:"webhook"`
	Token   string `json:"token"`
}

type vk struct {
	Confirmation string `json:"confirmation"`
	Token        string `json:"token"`
}

// Config returns current configuration.
var Config config

func init() {
	var path = os.Getenv("RAND_CHAT_ROOT")

	if flag.Lookup("test.v") == nil {
		path += "/config.json"
	} else {
		path += "/config.test.json"
	}

	file, err := os.Open(path)

	if err != nil {
		panic(err)
	}

	json.NewDecoder(file).Decode(&Config)

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

package env

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

type config struct {
	Database   string   `json:"database"`
	Telegram   telegram `json:"telegram"`
	VK         vk       `json:"vk"`
	Migrations string
}

type telegram struct {
	Webhook string `json:"webhook"`
	Token   string `json:"token"`
}

type vk struct {
	Confirmation string `json:"confirmation"`
	Token        string `json:"token"`
}

// Config returns current configuration.
var Config config

func init() {
	var configPath string

	root := os.Getenv("RAND_CHAT_ROOT")

	if flag.Lookup("test.v") == nil {
		configPath = path.Join(root, "/config.json")
	} else {
		configPath = path.Join(root, "/config.test.json")
	}

	configFile, err := os.Open(configPath)

	if err != nil {
		panic(err)
	}

	json.NewDecoder(configFile).Decode(&Config)

	Config.Migrations = "file://" + path.Join(root, "/migrations")
}

Add migrations path to env.Config


package pes

type PacketChannel <-chan *Packet

func (input PacketChannel) PayloadOnly() <-chan []byte {
	output := make(chan []byte)
	go func() {
		for packet := range input {
			output <- packet.Payload
		}
		close(output)
	}()
	return output
}

package pes

type PacketChannel <-chan *Packet

func (input PacketChannel) PayloadOnly() <-chan []byte {
	output := make(chan []byte)
	go func() {
		defer close(output)
		for packet := range input {
			output <- packet.Payload
		}
	}()
	return output
}

Use defer to schedule channel closing


package errors

import "fmt"

type HttpError interface {
	Error
	StatusCode() int
	Headers() string
	Body() string
}

type httpError struct {
	statusCode  int
	headers     string
	body        string
	code        string
	description string
}

type HttpNotFoundError struct {
	*httpError
}

func NewHttpError(statusCode int, header string, body string, code string, description string) HttpError {
	err := httpError{
		statusCode:  statusCode,
		headers:     header,
		body:        body,
		code:        code,
		description: description,
	}
	switch statusCode {
	case 404:
		return HttpNotFoundError{&err}
	default:
		return &err
	}
}

func (err *httpError) StatusCode() int {
	return err.statusCode
}

func (err *httpError) Headers() string {
	return err.headers
}

func (err *httpError) Body() string {
	return err.body
}

func (err *httpError) Error() string {
	return fmt.Sprintf(
		"Server error, status code: %d, error code: %s, message: %s",
		err.statusCode,
		err.code,
		err.description,
	)
}

func (err *httpError) ErrorCode() string {
	return err.code
}

package errors

import "fmt"

type HttpError interface {
	error
	StatusCode() int   // actual HTTP status code
	ErrorCode() string // error code returned in response body from CC or UAA
	Headers() string   // see: known_error_codes.go
	Body() string
}

type httpError struct {
	statusCode  int
	headers     string
	body        string
	code        string
	description string
}

type HttpNotFoundError struct {
	*httpError
}

func NewHttpError(statusCode int, header string, body string, code string, description string) HttpError {
	err := httpError{
		statusCode:  statusCode,
		headers:     header,
		body:        body,
		code:        code,
		description: description,
	}
	switch statusCode {
	case 404:
		return HttpNotFoundError{&err}
	default:
		return &err
	}
}

func (err *httpError) StatusCode() int {
	return err.statusCode
}

func (err *httpError) Headers() string {
	return err.headers
}

func (err *httpError) Body() string {
	return err.body
}

func (err *httpError) Error() string {
	return fmt.Sprintf(
		"Server error, status code: %d, error code: %s, message: %s",
		err.statusCode,
		err.code,
		err.description,
	)
}

func (err *httpError) ErrorCode() string {
	return err.code
}

Add comments to HTTPError interface


package client

import "fmt"

// An EnsuredState represents some state that is needed in order for a function to execute.
type EnsuredState interface {
	// EnsureState will check if the state is active and activate it if that is not the case.
	// The boolean return value indicates if the state was activated or not.
	EnsureState() (bool, error)

	// Deactivate the state (i.e. quit, remove, disconnect)
	DeactivateState() error
}

// WithEnsuredState ensures the given state, calls the function, and then, if the state
// was activated, it is deactivated unless the retain flag is true.
func WithEnsuredState(r EnsuredState, retain bool, f func() error) (err error) {
	var wasAcquired bool
	wasAcquired, err = r.EnsureState()
	if wasAcquired && !retain {
		defer func() {
			if cerr := r.DeactivateState(); cerr != nil {
				if err == nil {
					err = cerr
				} else {
					err = fmt.Errorf("%s\n%s", err.Error(), cerr.Error())
				}
			}
		}()
	}
	if err != nil {
		return err
	}
	err = f()
	return
}

package client

import "fmt"

// An EnsuredState represents some state that is needed in order for a function to execute.
type EnsuredState interface {
	// EnsureState will check if the state is active and activate it if that is not the case.
	// The boolean return value indicates if the state was activated or not.
	EnsureState() (bool, error)

	// Deactivate the state (i.e. quit, remove, disconnect)
	DeactivateState() error
}

// WithEnsuredState ensures the given state, calls the function, and then, if the state
// was activated, it is deactivated unless the retain flag is true.
func WithEnsuredState(r EnsuredState, retain bool, f func() error) (err error) {
	var wasAcquired bool
	defer func() {
		// Always deactivate an acquired state unless there's no error
		// and a desire to retain it.
		if wasAcquired && !(err == nil && retain) {
			if cerr := r.DeactivateState(); cerr != nil {
				if err == nil {
					err = cerr
				} else {
					err = fmt.Errorf("%s\n%s", err.Error(), cerr.Error())
				}
			}
		}
	}()

	if wasAcquired, err = r.EnsureState(); err != nil {
		return err
	}
	return f()
}

Make EnsuredState rollback unconditionally on error


// repository.go
package main

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

type Repository struct {
	ID       int    `json:"id"`
	CloneURL string `json:"clone_url"`
}

// StartBuild executes a build on the Commit Payload
func (r Repository) StartBuild() {

	cmd := exec.Command("git", "clone", r.CloneURL, "clones/"+string(r.ID))
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()

	if err != nil {
		log.Println(out.String())
		log.Fatal(err)
	}
	fmt.Printf("Result: %s", out.String())

}

// repository.go
package main

import (
	"bytes"
	"fmt"
	"log"
	"os/exec"
	"strconv"
)

type Repository struct {
	ID       int    `json:"id"`
	CloneURL string `json:"clone_url"`
}

// StartBuild executes a build on the Commit Payload
func (r Repository) StartBuild() {

	repoID := strconv.Itoa(r.ID)

	cmd := exec.Command("git", "clone", r.CloneURL, "clones/"+repoID)
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()

	if err != nil {
		log.Println(out.String())
		log.Fatal(err)
	}
	fmt.Printf("Result: %s", out.String())

}

Use Itoa instead of string function


package game

type EventType uint8

const (
	EventTypeError EventType = iota
	EventTypeObjectCreate
	EventTypeObjectDelete
	EventTypeObjectUpdate
	EventTypeObjectChecked
)

type Event struct {
	Type    EventType
	Payload interface{}
}

package game

type EventType uint8

const (
	EventTypeError EventType = iota
	EventTypeObjectCreate
	EventTypeObjectDelete
	EventTypeObjectUpdate
	EventTypeObjectChecked
)

var eventsLabels = map[EventType]string{
	EventTypeError:         "error",
	EventTypeObjectCreate:  "create",
	EventTypeObjectDelete:  "delete",
	EventTypeObjectUpdate:  "update",
	EventTypeObjectChecked: "checked",
}

func (event EventType) String() string {
	if label, ok := eventsLabels[event]; ok {
		return label
	}
	return "unknown"
}

type Event struct {
	Type    EventType
	Payload interface{}
}

Implement stringer interface for game.EventType


package lxc

import (
	"fmt"
	"github.com/docker/libcontainer/namespaces"
	"github.com/docker/libcontainer/utils"
)

func finalizeNamespace(args *InitArgs) error {
	if err := utils.CloseExecFrom(3); err != nil {
		return err
	}

	if err := namespaces.SetupUser(args.User); err != nil {
		return fmt.Errorf("setup user %s", err)
	}

	if err := setupWorkingDirectory(args); err != nil {
		return err
	}

	return nil
}

package lxc

import (
	"fmt"

	"github.com/docker/libcontainer"
	"github.com/docker/libcontainer/namespaces"
	"github.com/docker/libcontainer/utils"
)

func finalizeNamespace(args *InitArgs) error {
	if err := utils.CloseExecFrom(3); err != nil {
		return err
	}
	if err := namespaces.SetupUser(&libcontainer.Config{
		User: args.User,
	}); err != nil {
		return fmt.Errorf("setup user %s", err)
	}
	if err := setupWorkingDirectory(args); err != nil {
		return err
	}
	return nil
}

Update lxc with libcontainer SetupUser change


package main

import (
	"github.com/bmorton/deployster/fleet"
	"log"
	"net/http"
	"net/url"
)

type UnitsResource struct {
	Fleet fleet.Client
}

type UnitsResponse struct {
	Units []VersionedUnit `json:"units"`
}

func (self *UnitsResource) Index(u *url.URL, h http.Header, req interface{}) (int, http.Header, *UnitsResponse, error) {
	statusCode := http.StatusOK
	response := &UnitResponse{}

	units, err := self.Fleet.Units()
	if err != nil {
		log.Printf("%#v\n", err)
		return http.StatusInternalServerError, nil, nil, err
	}
	response.Units = FindServiceUnits(u.Query().Get("name"), units)

	return statusCode, nil, response, nil
}

package main

import (
	"github.com/bmorton/deployster/fleet"
	"log"
	"net/http"
	"net/url"
)

type UnitsResource struct {
	Fleet fleet.Client
}

type UnitsResponse struct {
	Units []VersionedUnit `json:"units"`
}

func (self *UnitsResource) Index(u *url.URL, h http.Header, req interface{}) (int, http.Header, *UnitsResponse, error) {
	statusCode := http.StatusOK
	response := &UnitsResponse{}

	units, err := self.Fleet.Units()
	if err != nil {
		log.Printf("%#v\n", err)
		return http.StatusInternalServerError, nil, nil, err
	}
	response.Units = FindServiceUnits(u.Query().Get("name"), units)

	return statusCode, nil, response, nil
}

Fix missed struct renaming of UnitsResponse.


package nvim

import (
	"fmt"

	"github.com/garyburd/neovim-go/vim"
)

func Echomsg(v *vim.Vim, format string, args ...interface{}) error {
	return v.WriteOut(fmt.Sprintf(format, args...))
}

func Echoerr(v *vim.Vim, format string, args ...interface{}) error {
	return v.WriteErr(fmt.Sprintf(format, args...))
}

package nvim

import (
	"fmt"

	"github.com/garyburd/neovim-go/vim"
)

func Echo(v *vim.Vim, format string, a ...interface{}) error {
	return v.Command("echo '" + fmt.Sprintf(format, a...) + "'")
}

func Echomsg(v *vim.Vim, format string, a ...interface{}) error {
	return v.Command("echomsg '" + fmt.Sprintf(format, a...) + "'")
}

func Echoerr(v *vim.Vim, format string, a ...interface{}) error {
	return v.Command("echoerr '" + fmt.Sprintf(format, a...) + "'")
}

func ReportError(v *vim.Vim, format string, a ...interface{}) error {
	return v.ReportError(fmt.Sprintf(format, a...))
}

Fix Echo*** and Add ReportError interface wrapper


// +build !windows

package util

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

func openCommand() string {
	switch runtime.GOOS {
	case "darwin":
		return "open"
	default:
		return "xdg-open"
	}
}

func CallBrowser(url string) error {
	fmt.Fprintf(os.Stderr, "Running a browser to open %s...", url)
	command := openCommand()
	bin, err := exec.LookPath(command)
	if err != nil {

		command = "/usr/bin/x-www-browser"
		bin, err = exec.LookPath(command)
		if err != nil {
			return err
		}
	}
	fmt.Fprintf(os.Stderr, "%s %s\r\n", bin, url)

	var attr os.ProcAttr
	proc, err := os.StartProcess(command, []string{url}, &attr)
	if err != nil {
		return err
	}
	_, err = proc.Wait()
	return err

}

// +build !windows

package util

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

func openCommand() string {
	switch runtime.GOOS {
	case "darwin":
		return "open"
	default:
		return "xdg-open"
	}
}

func CallBrowser(url string) error {
	fmt.Fprintf(os.Stderr, "Running a browser to open %s...", url)
	command := openCommand()
	bin, err := exec.LookPath(command)
	if err != nil {

		command = "/usr/bin/x-www-browser"
		bin, err = exec.LookPath(command)
		if err != nil {
			return err
		}
	}
	fmt.Fprintf(os.Stderr, "%s %s\r\n", bin, url)

	var attr os.ProcAttr
	proc, err := os.StartProcess(bin, []string{bin, url}, &attr)
	if err != nil {
		return err
	}
	_, err = proc.Wait()
	return err

}

Fix console command on linux


package converter

import (
	"fmt"
	"log"
	"strings"
)

type KrSpaKa struct {
	comma rune
}

func NewKrSpaKa() KrSpaKa {
	return KrSpaKa{
		comma: ';',
	}
}

func (k KrSpaKa) Comma() rune {
	return k.comma
}

func (k KrSpaKa) IsTransaction(record []string) bool {
	return !(len(record) != 17 || record[0] == "Auftragskonto" || strings.Contains(record[16], "vorgemerkt"))
}

func (k KrSpaKa) Convert(record []string) []string {
	result := make([]string, 6)
	var err error

	// Date
	result[0], err = convertDateFrom("02.01.06", record[1])
	if err != nil {
		log.Fatal(err)
	}

	// Payee
	result[1] = record[11]

	// Memo
	result[3] = fmt.Sprintf("[%v] %v", record[3], record[4])

	// Amount
	amount := convertThousandAndCommaSeparator(record[14])
	if isNegative(amount) {
		result[4] = abs(amount)
	} else {
		result[5] = amount
	}

	return result
}

package converter

import (
	"log"
	"strings"
)

type KrSpaKa struct {
	comma rune
}

func NewKrSpaKa() KrSpaKa {
	return KrSpaKa{
		comma: ';',
	}
}

func (k KrSpaKa) Comma() rune {
	return k.comma
}

func (k KrSpaKa) IsTransaction(record []string) bool {
	return !(len(record) != 17 || record[0] == "Auftragskonto" || strings.Contains(record[16], "vorgemerkt"))
}

func (k KrSpaKa) Convert(record []string) []string {
	result := make([]string, 6)
	var err error

	// Date
	result[0], err = convertDateFrom("02.01.06", record[1])
	if err != nil {
		log.Fatal(err)
	}

	// Payee
	result[1] = record[11]

	// Memo
	result[3] = record[4]

	// Amount
	amount := convertThousandAndCommaSeparator(record[14])
	if isNegative(amount) {
		result[4] = abs(amount)
	} else {
		result[5] = amount
	}

	return result
}

Fix failing test, bei removing transaction type from "Memo"


package base

// OpaqueProxyFlyweight enables implementation of its eponymous design pattern. You need lots of
// objects, but creating them is expensive. You want to externalize state, but your object is opaque
// (you access it through an interface) Only these objects can know the type of the external state.
// So create an extension of this object that acts like a proxy When needed, it will grab the
// extrinsic, without exposing the details to the client.
type OpaqueProxyFlyweight interface {
	ClaimExtrinsics()
}

package base

// OpaqueProxyFlyweight enables implementation of its eponymous design pattern. You need lots of
// objects, but creating them is expensive. You want to externalize state, but your object is opaque
// (you access it through an interface) Only these objects can know the type of the external state.
// So create an extension of this object that acts like a proxy When needed, it will grab the
// extrinsic, without exposing the details to the client.
type OpaqueProxyFlyweight interface {
	ClaimExtrinsics()
    Extrinsically(func())
}

Add Extrinsically to interface definition


package database

import (
	"github.com/go-martini/martini"
	"log"
	"net/http"
)

// The Martini handler to use for injecting the database context
func Middleware() martini.Handler {
	db, err := OpenAndInit()

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

	return func(w http.ResponseWriter, r *http.Request, c martini.Context) {
		c.Map(db)
	}
}

package database

import (
	"github.com/go-martini/martini"
	"log"
	"net/http"
)

// The Martini handler to use for injecting the database context
func Middleware() martini.Handler {
	db, err := OpenAndInit()

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

	return func(w http.ResponseWriter, r *http.Request, c martini.Context) {
		c.Map(&db)
	}
}

Revert "Accidentally was giving it the pointer to a pointer."


package retention

import (
	"time"

	"github.com/influxdb/influxdb/toml"
)

type Config struct {
	Enabled       bool          `toml:"enabled"`
	CheckInterval toml.Duration `toml:"check-interval"`
}

func NewConfig() Config {
	return Config{Enabled: true, CheckInterval: toml.Duration(10 * time.Minute)}
}

package retention

import (
	"time"

	"github.com/influxdb/influxdb/toml"
)

type Config struct {
	Enabled       bool          `toml:"enabled"`
	CheckInterval toml.Duration `toml:"check-interval"`
}

func NewConfig() Config {
	return Config{Enabled: true, CheckInterval: toml.Duration(30 * time.Minute)}
}

Set default retention check interval to 30 minutes


package obj

import (
	"fmt"
	"reflect"

	. "github.com/polydawn/refmt/tok"
)

// ErrInvalidUnmarshalTarget describes an invalid argument passed to UnmarshalDriver.Bind.
// (Unmarshalling must target a non-nil pointer so that it can address the value.)
type ErrInvalidUnmarshalTarget struct {
	Type reflect.Type
}

func (e ErrInvalidUnmarshalTarget) Error() string {
	if e.Type == nil {
		return "invalid unmarshal target (nil)"
	}
	if e.Type.Kind() != reflect.Ptr {
		return "invalid unmarshal target (non-pointer " + e.Type.String() + ")"
	}
	return "invalid unmarshal target: (nil " + e.Type.String() + ")"
}

// ErrUnmarshalIncongruent is the error returned when unmarshalling cannot
// coerce the tokens in the stream into the variables the unmarshal is targetting,
// for example if a map open token comes when an int is expected.
type ErrUnmarshalIncongruent struct {
	Token Token
	Value reflect.Value
}

func (e ErrUnmarshalIncongruent) Error() string {
	return fmt.Sprintf("cannot assign %s to %s field", e.Token, e.Value.Kind())
}

type ErrUnexpectedTokenType struct {
	Got      TokenType // Token in the stream that triggered the error.
	Expected string    // Freeform string describing valid token types.  Often a summary like "array close or start of value", or "map close or key".
}

func (e ErrUnexpectedTokenType) Error() string {
	return fmt.Sprintf("unexpected %s token; expected %s", e.Got, e.Expected)
}

Introduce ErrUnexpectedTokenType, which our unmarshaller machines should start returning here on out.


package typetalk

import (
	"errors"
	"github.com/Sirupsen/logrus"
	"net/http"
	"net/url"
)

const (
	VERISON = "1.0.0"
)

type TypetalkHook struct {
	AcceptedLevels []logrus.Level
	BotURL         string
}

func (th *TypetalkHook) Levels() []logrus.Level {
	if th.AcceptedLevels == nil {
		return AllLevels
	}
	return th.AcceptedLevels
}

func (th *TypetalkHook) Fire(e *logrus.Entry) error {
	resp, err := http.PostForm(th.BotURL, url.Values{"message": {e.Message}})
	if err != nil {
		return err
	}
	if resp.StatusCode != http.StatusOK {
		return errors.New(e.Message)
	}
	return nil
}

package typetalk

import (
	"errors"
	"github.com/Sirupsen/logrus"
	"net/http"
	"net/url"
)

const (
	VERISON = "1.0.0"
)

type TypetalkHook struct {
	AcceptedLevels []logrus.Level
	BotURL         string
}

func (th *TypetalkHook) Levels() []logrus.Level {
	if th.AcceptedLevels == nil {
		return AllLevels
	}
	return th.AcceptedLevels
}

func (th *TypetalkHook) Fire(e *logrus.Entry) error {
	resp, err := http.PostForm(th.BotURL, url.Values{"message": {e.Message}})
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return errors.New(e.Message)
	}
	return nil
}

Add closing HTTP response body


package fabric

import (
	"context"
)

// HandlerFunc defines the handler function for the server
type HandlerFunc func(context.Context, Conn) (context.Context, Conn, error)

// NegotiatorFunc defines the negotiator functions for the clients
type NegotiatorFunc func(ctx context.Context, conn Conn) (context.Context, Conn, error)

// Handler is responsible for handling a negotiation on the server's side
type Handler interface {
	Handle(context.Context, Conn) (context.Context, Conn, error)
	Name() string
}

// Negotiator is responsible for initiating a negotiation on the client's side
type Negotiator interface {
	Negotiate(ctx context.Context, conn Conn) (context.Context, Conn, error)
	Name() string
}

// Middleware are composites of a handler, a negotiator, and a name methods
type Middleware interface {
	Handle(context.Context, Conn) (context.Context, Conn, error)
	Negotiate(ctx context.Context, conn Conn) (context.Context, Conn, error)
	Name() string
}

package fabric

import (
	"context"
)

// HandlerFunc defines the handler function for the server
type HandlerFunc func(ctx context.Context, conn Conn) (context.Context, Conn, error)

// NegotiatorFunc defines the negotiator functions for the clients
type NegotiatorFunc func(ctx context.Context, conn Conn) (context.Context, Conn, error)

// Handler is responsible for handling a negotiation on the server's side
type Handler interface {
	Handle(ctx context.Context, conn Conn) (context.Context, Conn, error)
	Name() string
}

// Negotiator is responsible for initiating a negotiation on the client's side
type Negotiator interface {
	Negotiate(ctx context.Context, conn Conn) (context.Context, Conn, error)
	Name() string
}

// Middleware are composites of a handler, a negotiator, and a name methods
type Middleware interface {
	Handle(ctx context.Context, conn Conn) (context.Context, Conn, error)
	Negotiate(ctx context.Context, conn Conn) (context.Context, Conn, error)
	Name() string
}

Fix var names on interfaces


package main

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

func setupRoutes(e *echo.Echo) {
	e.GET("/", route_main)
	e.GET("/search/:query", route_search)
}

func route_main(c echo.Context) error {
	return c.String(http.StatusOK, "You've reached /")
}

func route_search(c echo.Context) error {
	allResults := make(map[string][]SearchResult)
	query := c.Param("query")

	if len(query) < 5 {
		return c.String(http.StatusBadRequest, "Search query is too short")
	}

	for _, b := range BACKENDS {
		results, err := b.Search(query)
		if err != nil {
			log.Error(err)
			continue
		}
		allResults[b.Name()] = results
	}

	return c.JSON(http.StatusOK, allResults)
}

package main

import (
	"github.com/labstack/echo"
	"github.com/texttheater/golang-levenshtein/levenshtein"
	"net/http"
	"sort"
)

// So that we can sort
var query string

func setupRoutes(e *echo.Echo) {
	e.GET("/", route_main)
	e.GET("/search/:query", route_search)
}

func route_main(c echo.Context) error {
	return c.String(http.StatusOK, "You've reached /")
}

type ByLevenshteinDistance []SearchResult

func (r ByLevenshteinDistance) Len() int {
	return len(r)
}

func (r ByLevenshteinDistance) Swap(i int, j int) {
	r[i], r[j] = r[j], r[i]
}

func (r ByLevenshteinDistance) Less(i int, j int) bool {
	return levenshtein.DistanceForStrings([]rune(query), []rune(r[i].Title), levenshtein.DefaultOptions) < levenshtein.DistanceForStrings([]rune(query), []rune(r[j].Title), levenshtein.DefaultOptions)
}

func route_search(c echo.Context) error {
	allResults := make(map[string][]SearchResult)
	query = c.Param("query")

	if len(query) < 5 {
		return c.String(http.StatusBadRequest, "Search query is too short")
	}

	for _, b := range BACKENDS {
		results, err := b.Search(query)
		if err != nil {
			log.Error(err)
			continue
		}

		sort.Sort(ByLevenshteinDistance(results))

		allResults[b.Name()] = results
	}

	return c.JSON(http.StatusOK, allResults)
}

Sort search results based on Levenshtein distance from query


package sqs

import (
	"fmt"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/goadapp/goad/api"
	"github.com/stretchr/testify/assert"
)

func init() {
}

func TestAdapterConstruction(t *testing.T) {
	config := aws.NewConfig().WithRegion("somewhere")
	testsqs := NewSQSAdapter(config, "testqueue")
	assert.Equal(t, testsqs.QueueURL, "testqueue")
}

func TestJSON(t *testing.T) {
	assert := assert.New(t)
	// This test just verifies the json api.
	result := api.RunnerResult{
		RequestCount:     299,
		TimedOut:         234,
		ConnectionErrors: 256,
		AveTimeToFirst:   9999,
		BytesRead:        2136,
		// Statuses:         new(map[string]int),
		AveTimeForReq: 12345,
		// AveReqPerSec:         6789,
		// AveKBytesPerSec:      6789,
		Slowest:    4567,
		Fastest:    4567,
		Region:     "eu-west",
		RunnerID:   0,
		FatalError: "sorry",
	}
	str, jsonerr := jsonFromResult(result)
	if jsonerr != nil {
		fmt.Println(jsonerr)
		return
	}
	json, err := resultFromJSON(str)
	if err != nil {
		t.Fatal(err)
	}
	assert.EqualValues(result, json, "Should serialize and deserialize without error and loosing information")
}

package sqs

import (
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/stretchr/testify/assert"
)

func TestAdapterConstruction(t *testing.T) {
	config := aws.NewConfig().WithRegion("somewhere")
	testsqs := NewSQSAdapter(config, "testqueue")
	assert.Equal(t, testsqs.QueueURL, "testqueue")
}

Remove weak unit test for json serialisation


package storage

import (
	"os"

	"github.com/hnakamur/api2go-gorm-gin-crud-example/model"
	"github.com/jinzhu/gorm"
)

func InitDB() (*gorm.DB, error) {
	db, err := gorm.Open(os.Getenv("DB_DIALECT"), os.Getenv("DB_PARAMS"))
	if err != nil {
		return nil, err
	}

	//db.LogMode(true)
	db.AutoMigrate(&model.User{}, &model.Chocolate{})

	return &db, nil
}

package storage

import (
	"os"

	"github.com/hnakamur/api2go-gorm-gin-crud-example/model"
	"github.com/jinzhu/gorm"
)

// InitDB creates and migrates the database
func InitDB() (*gorm.DB, error) {
	db, err := gorm.Open(os.Getenv("DB_DIALECT"), os.Getenv("DB_PARAMS"))
	if err != nil {
		return nil, err
	}

	//db.LogMode(true)
	db.AutoMigrate(&model.User{}, &model.Chocolate{})

	return &db, nil
}

Comment the exported function InitDB


package main

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

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) {
	    	log.Fatal("ListenAndServe: ", err)
		    http.Error(w, err.Error(), http.StatusInternalServerError)
		    return
	    }
	    log.Fatal("ListenAndServe: ", err)
    }

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

	http.Redirect(w, r, "http://experiment.safkanyazilim.com/"+filename, http.StatusTemporaryRedirect)
}

func generateRandomURL() string {
	return "1234556"
}

func main() {
	http.HandleFunc("/save", saveHandler)

    //http.ListenAndServe(":8080", nil)
    err := http.ListenAndServe(":8080", nil)

    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

package main

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

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)) {
	    	log.Fatal("ListenAndServe: ", err)
		    http.Error(w, err.Error(), http.StatusInternalServerError)
		    return
	    }
	    log.Fatal("ListenAndServe: ", err)
    }

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

	http.Redirect(w, r, "http://experiment.safkanyazilim.com/"+filename, http.StatusTemporaryRedirect)
}

func generateRandomURL() string {
	return "1234556"
}

func main() {
	http.HandleFunc("/save", saveHandler)

    //http.ListenAndServe(":8080", nil)
    err := http.ListenAndServe(":8080", nil)

    if err != nil {
        log.Fatal("Main: ", err)
    }
}

Check whether file does exist


package rest

func compareEtag(etag, baseEtag string) bool {
	if etag == baseEtag {
		return true
	}
	if l := len(etag); l == len(baseEtag)+2 && l > 3 && etag[0] == '"' && etag[l-1] == '"' && etag[1:l-1] == baseEtag {
		return true
	}
	return false
}

package rest

// compareEtag compares a client provided etag with a base etag. The client provided
// etag may or may not have quotes while the base etag is never quoted. This loose
// comparison of etag allows clients not stricly respecting RFC to send the etag with
// or without quotes when the etag comes from, for instance, the API JSON response.
func compareEtag(etag, baseEtag string) bool {
	if etag == baseEtag {
		return true
	}
	if l := len(etag); l == len(baseEtag)+2 && l > 3 && etag[0] == '"' && etag[l-1] == '"' && etag[1:l-1] == baseEtag {
		return true
	}
	return false
}

Add some doc to compareEtag


package main

import (
	"fmt"
	"os"

	"github.com/gholt/brimtext"
	"github.com/gholt/ring"
)

func main() {
	i := -1
	for j, v := range os.Args {
		if v == "--no-color" {
			i = j
			break
		}
	}
	if i != -1 {
		os.Args = append(os.Args[:i], os.Args[i+1:]...)
	}
	if err := ring.CLI(os.Args, os.Stdout, i == -1); err != nil {
		fmt.Fprintln(os.Stderr, brimtext.Sentence(err.Error()))
		os.Exit(1)
	}
}

package main

import (
	"fmt"
	"os"

	"github.com/gholt/brimtext"
	"github.com/gholt/ring"
	"golang.org/x/crypto/ssh/terminal"
)

func main() {
	var args []string
	color := terminal.IsTerminal(int(os.Stdout.Fd()))
	for _, arg := range os.Args {
		switch arg {
		case "--color":
			color = true
		case "--no-color":
			color = false
		default:
			args = append(args, arg)
		}
	}
	if err := ring.CLI(args, os.Stdout, color); err != nil {
		fmt.Fprintln(os.Stderr, brimtext.Sentence(err.Error()))
		os.Exit(1)
	}
}

Update to color output handling


package test

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"github.com/fabiofalci/sconsify/events"
	"github.com/fabiofalci/sconsify/spotify"
	"github.com/howeyc/gopass"
)

func main2() {
	username, pass := credentials()
	events := events.InitialiseEvents()

	go spotify.Initialise(username, pass, events)
	playlists := <-events.WaitForPlaylists()

	playlist := playlists["Ramones"]
	playlist.Wait()
	track := playlist.Track(3).Track()
	track.Wait()

	events.ToPlay <- track

	println(track.Name())
	<-events.WaitForStatus()
	<-events.NextPlay
}

func credentials() (*string, *[]byte) {
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Username: ")
	username, _ := reader.ReadString('\n')
	username = strings.Trim(username, " \n\r")
	fmt.Print("Password: ")
	pass := gopass.GetPasswd()
	return &username, &pass
}

package test

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"strings"

	"github.com/fabiofalci/sconsify/events"
	"github.com/fabiofalci/sconsify/spotify"
	ui "github.com/fabiofalci/sconsify/ui"
	"github.com/howeyc/gopass"
	sp "github.com/op/go-libspotify/spotify"
)

func main2() {
	username, pass := credentials()
	events := events.InitialiseEvents()

	go spotify.Initialise(username, pass, events)
	playlists := <-events.WaitForPlaylists()

	allTracks := getAllTracks(playlists).Contents()

	for {
		index := rand.Intn(len(allTracks))
		track := allTracks[index]

		events.ToPlay <- track

		println(<-events.WaitForStatus())
		<-events.NextPlay
	}
}

func getAllTracks(playlists map[string]*sp.Playlist) *ui.Queue {
	queue := ui.InitQueue()

	for _, playlist := range playlists {
		playlist.Wait()
		for i := 0; i < playlist.Tracks(); i++ {
			track := playlist.Track(i).Track()
			track.Wait()
			queue.Add(track)
		}
	}

	return queue
}

func credentials() (*string, *[]byte) {
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Username: ")
	username, _ := reader.ReadString('\n')
	username = strings.Trim(username, " \n\r")
	fmt.Print("Password: ")
	pass := gopass.GetPasswd()
	return &username, &pass
}

Make no gui test random all tracks


package builder

import (
	"fmt"

	"github.com/spf13/cobra"

	"github.com/openshift/origin/pkg/build/builder/cmd"
)

const longCommandSTIDesc = `
Perform a Source-to-Image Build

This command executes a Source-to-Image build using arguments passed via the environment.
It expects to be run inside of a container.
`

func NewCommandSTIBuilder(name string) *cobra.Command {
	cmd := &cobra.Command{
		Use:   fmt.Sprintf("%s", name),
		Short: "Run an OpenShift Source-to-Images build",
		Long:  longCommandSTIDesc,
		Run: func(c *cobra.Command, args []string) {
			cmd.RunSTIBuild()
		},
	}

	return cmd
}

const longCommandDockerDesc = `
Perform a Docker Build

This command executes a Docker build using arguments passed via the environment.
It expects to be run inside of a container.
`

func NewCommandDockerBuilder(name string) *cobra.Command {
	cmd := &cobra.Command{
		Use:   fmt.Sprintf("%s", name),
		Short: "Run an OpenShift Docker build",
		Long:  longCommandDockerDesc,
		Run: func(c *cobra.Command, args []string) {
			cmd.RunDockerBuild()
		},
	}

	return cmd
}

package builder

import (
	"fmt"

	"github.com/spf13/cobra"

	"github.com/openshift/origin/pkg/build/builder/cmd"
)

const longCommandSTIDesc = `
Perform a Source-to-Image Build

This command executes a Source-to-Image build using arguments passed via the environment.
It expects to be run inside of a container.
`

func NewCommandSTIBuilder(name string) *cobra.Command {
	return &cobra.Command{
		Use:   fmt.Sprintf("%s", name),
		Short: "Run an OpenShift Source-to-Images build",
		Long:  longCommandSTIDesc,
		Run: func(c *cobra.Command, args []string) {
			cmd.RunSTIBuild()
		},
	}
}

const longCommandDockerDesc = `
Perform a Docker Build

This command executes a Docker build using arguments passed via the environment.
It expects to be run inside of a container.
`

func NewCommandDockerBuilder(name string) *cobra.Command {
	return &cobra.Command{
		Use:   fmt.Sprintf("%s", name),
		Short: "Run an OpenShift Docker build",
		Long:  longCommandDockerDesc,
		Run: func(c *cobra.Command, args []string) {
			cmd.RunDockerBuild()
		},
	}
}

Simplify code to get rid variable shadowing


package ss13

import (
	"log"
	"time"
)

var (
	now            = time.Now()
	debugging bool = false
)

func log_error(err error) {
	if err != nil {
		log.Panic("WARNING ", err)
	}
}

func check_error(err error) {
	if err != nil {
		log.Fatal("ERROR ", err)
	}
}

func SetDebug(val bool) {
	debugging = val
}

func IsDebugging() bool {
	return debugging
}

func ResetNow() {
	now = time.Now()
}

func Now() time.Time {
	return now.UTC()
}

package ss13

import (
	"log"
	"time"
)

var (
	now            = time.Now()
	debugging bool = false
)

func log_error(err error) bool {
	if err != nil {
		log.Printf("WARNING: %s\n", err)
		return true
	}
	return false
}

func check_error(err error) {
	if err != nil {
		log.Fatal("ERROR ", err)
	}
}

func SetDebug(val bool) {
	debugging = val
}

func IsDebugging() bool {
	return debugging
}

func ResetNow() {
	now = time.Now()
}

func Now() time.Time {
	return now.UTC()
}

Make log_error actually log errors without panicing.


package term

import (
	"os"
	"os/exec"
	"runtime"
)

func Clear() {
	var cmd *exec.Cmd
	switch os := runtime.GOOS; os {
	case "linux":
		cmd = exec.Command("clear")
	case "windows":
		cmd = exec.Command("cls")
	}
	cmd.Stdout = os.Stdout
	cmd.Run()
}

package term

import (
	"os"
	"os/exec"
	"runtime"
)

func Clear() {
	var cmd *exec.Cmd
	switch os := runtime.GOOS; os {
	case "linux":
		cmd = exec.Command("clear")
	case "windows":
		cmd = exec.Command("cmd", "/C", "cls")
	}
	cmd.Stdout = os.Stdout
	cmd.Run()
}

Fix clear screen on windows


package retry

import (
	"time"
)

// Func is the function to retry returning true if it's successfully completed
type Func = func() bool

// Do retries provided function "attempts" times with provided interval and returning true if it's successfully completed
func Do(attempts int, interval time.Duration, f Func) bool {
	for attempt := 0; ; attempt++ {
		if f() {
			return true
		}

		if attempt > attempts {
			break
		}

		time.Sleep(interval)
	}

	return false
}

package retry

import (
	"fmt"
	"time"
)

// Func is the function to retry returning true if it's successfully completed
type Func = func() bool

// Do retries provided function "attempts" times with provided interval and returning true if it's successfully completed
func Do(attempts int, interval time.Duration, f Func) bool {
	if interval < 1*time.Second/10 {
		panic(fmt.Sprintf("retry.Do used with interval less then 1/10 second, it seems dangerous: %s", interval))
	}

	for attempt := 0; ; attempt++ {
		if f() {
			return true
		}

		if attempt > attempts {
			break
		}

		time.Sleep(interval)
	}

	return false
}

Make retry.Do panic if it's started with interval less then 1/10 second


package divsd

// The top configuration structure for the DiVS daemon
type Config struct {
	Global   globalConfig
	Raft     raftConfig
	Discover discoverConfig
	Mdns     mdnsConfig
	Tun      tunConfig
}

// Global config
type globalConfig struct {
	Name   string
	Host   string
	Port   int
	Serial string
}

// RAFT
type raftConfig struct {
	DataPath string
	IsLeader bool
	Leader   string
}

// MDNS discovery
type mdnsConfig struct {
	Port   int
}

// DHT discovery
type discoverConfig struct {
	Port int
}

// NAT: TUN config
type tunConfig struct {
	NumReaders int
}

// Create a new DiVS daemon configuration
func NewConfig() (c *Config) {
	c = &Config{}
	return
}

package divsd

// The top configuration structure for the DiVS daemon
type Config struct {
	Global   globalConfig
	Raft     raftConfig
	Discover discoverConfig
	Mdns     mdnsConfig
	Tun      tunConfig
}

// Global config
type globalConfig struct {
	Name   string
	Host   string
	Port   int
	Serial UUID
}

// RAFT
type raftConfig struct {
	DataPath string
	IsLeader bool
	Leader   string
}

// MDNS discovery
type mdnsConfig struct {
	Port   int
}

// DHT discovery
type discoverConfig struct {
	Port int
}

// NAT: TUN config
type tunConfig struct {
	NumReaders int
}

// Create a new DiVS daemon configuration
func NewConfig() (c *Config) {
	c = &Config{}
	return
}

Use proper UUIDs and not just strings: we will perform conversion later on...


package action

import (
	boshcomp "github.com/cloudfoundry/bosh-agent/agent/compiler"
	boshcrypto "github.com/cloudfoundry/bosh-utils/crypto"
)

type CompilePackageWithSignedURLRequest struct {
	SignedURL string `json:"signed_url"`

	MultiDigest boshcrypto.MultipleDigest `json:"multi_digest"`
	Name        string                    `json:"name"`
	Version     string                    `json:"version"`
	Deps        boshcomp.Dependencies     `json:"deps"`
}

type CompilePackageWithSignedURLResponse struct {
	SHA1Digest string `json:"sha1_digest"`
}

type CompilePackageWithSignedURL struct{}

func (a CompilePackageWithSignedURL) Run(request CompilePackageWithSignedURLRequest) (CompilePackageWithSignedURLResponse, error) {
	return CompilePackageWithSignedURLResponse{}, nil
}

package action

import (
	boshcomp "github.com/cloudfoundry/bosh-agent/agent/compiler"
	boshcrypto "github.com/cloudfoundry/bosh-utils/crypto"
)

type CompilePackageWithSignedURLRequest struct {
	PackageGetSignedURL string `json:"package_get_signed_url"`
	UploadSignedUrl     string `json:"upload_signed_url"`

	MultiDigest boshcrypto.MultipleDigest `json:"multi_digest"`
	Name        string                    `json:"name"`
	Version     string                    `json:"version"`
	Deps        boshcomp.Dependencies     `json:"deps"`
}

type CompilePackageWithSignedURLResponse struct {
	SHA1Digest string `json:"sha1_digest"`
}

type CompilePackageWithSignedURL struct{}

func (a CompilePackageWithSignedURL) Run(request CompilePackageWithSignedURLRequest) (CompilePackageWithSignedURLResponse, error) {
	return CompilePackageWithSignedURLResponse{}, nil
}

Fix missing signedUrl for uploading compiled pkg


package main

import (
	"testing"

	log "github.com/Sirupsen/logrus"
)

func TestLineBreaking(t *testing.T) {
	log.SetLevel(log.DebugLevel)

	var tests = []struct {
		text   string
		result string
	}{
		{
			`\\name[Domestic scent]（…Properly……I want to take a bath……
　today…Let's go home.……）`,
			`\\name[Domestic scent]（…Properly……I want to take a bath……
　today…Let's go home.……）`,
		},
		{
			`"Money %s\\\\G I got！"`,
			`"Money %s\\\\G I got！"`,
		},
	}

	for _, pair := range tests {
		r := breakLines(pair.text)
		if r != pair.result {
			t.Errorf("For\n%q\nexpected\n%q\ngot\n%q\n", pair.text, pair.result, r)
		}
	}

}

package main

import "testing"

func TestLineBreaking(t *testing.T) {
	var tests = []struct {
		text   string
		result string
	}{
		{
			`\\name[Domestic scent]（…Properly……I want to take a bath……
　today…Let's go home.……）`,
			`\\name[Domestic scent]（…Properly……I want to take a bath……
　today…Let's go home.……）`,
		},
		{
			`"Money %s\\\\G I got！"`,
			`"Money %s\\\\G I got！"`,
		},
	}

	for _, pair := range tests {
		r := breakLines(pair.text)
		if r != pair.result {
			t.Errorf("For\n%q\nexpected\n%q\ngot\n%q\n", pair.text, pair.result, r)
		}
	}

}

Remove debug output from test


package nom

import (
	"encoding/gob"
	"time"
)

// NodeQuery queries the information of a node.
type NodeQuery struct {
	Node UID
}

// NodeQueryResult is the result for NodeQuery.
type NodeQueryResult struct {
	Err  error
	Node Node
}

// PortQuery queries the information of a port.
type PortQuery struct {
	Port UID
}

// PortQueryResult is the result for a PortQuery.
type PortQueryResult struct {
	Err  error
	Port Port
}

// FlowStatQuery queries the flows that would match the query. If Exact is
// false, it removes all flow entries that are subsumed by the given match.
type FlowStatQuery struct {
	Match Match
	Exact bool
}

// FlowStatQueryResult is the result for a FlowStatQuery
type FlowStatQueryResult struct {
	Flow     FlowEntry
	Duration time.Duration
	PktCount uint64
	Bytes    uint64
}

func init() {
	gob.Register(FlowStatQuery{})
	gob.Register(FlowStatQueryResult{})
	gob.Register(NodeQuery{})
	gob.Register(NodeQueryResult{})
	gob.Register(PortQuery{})
	gob.Register(PortQueryResult{})
}

package nom

import (
	"encoding/gob"
	"time"
)

// NodeQuery queries the information of a node.
type NodeQuery struct {
	Node UID
}

// NodeQueryResult is the result for NodeQuery.
type NodeQueryResult struct {
	Err  error
	Node Node
}

// PortQuery queries the information of a port.
type PortQuery struct {
	Port UID
}

// PortQueryResult is the result for a PortQuery.
type PortQueryResult struct {
	Err  error
	Port Port
}

// FlowStatsQuery queries the flows that would match the query. If Exact is
// false, it removes all flow entries that are subsumed by the given match.
type FlowStatsQuery struct {
	Node  UID
	Match Match
	Exact bool
}

// FlowStatsQueryResult is the result for a FlowStatQuery
type FlowStatsQueryResult struct {
	Node  UID
	Stats []FlowStats
}

// FlowStats is the statistics of flow
type FlowStats struct {
	Match    Match
	Duration time.Duration
	Packets  uint64
	Bytes    uint64
}

func init() {
	gob.Register(FlowStatsQuery{})
	gob.Register(FlowStatsQueryResult{})
	gob.Register(NodeQuery{})
	gob.Register(NodeQueryResult{})
	gob.Register(PortQuery{})
	gob.Register(PortQueryResult{})
}

Change flow stat reply to include multiple stats


package force

import (
	"fmt"
)

// Custom Error to handle salesforce api responses.
type ApiErrors []*ApiError

type ApiError struct {
	Fields           []string `json:"fields,omitempty" force:"fields,omitempty"`
	Message          string   `json:"message,omitempty" force:"message,omitempty"`
	ErrorCode        string   `json:"errorCode,omitempty" force:"errorCode,omitempty"`
	ErrorName        string   `json:"error,omitempty" force:"error,omitempty"`
	ErrorDescription string   `json:"error_description,omitempty" force:"error_description,omitempty"`
}

func (e ApiErrors) Error() string {
	return fmt.Sprintf("%#v", e.Errors())
}

func (e ApiErrors) Errors() []string {
	eArr := make([]string, len(e))
	for i, err := range e {
		eArr[i] = err.Error()
	}
	return eArr
}

func (e ApiErrors) Validate() bool {
	if len(e) != 0 {
		return true
	}

	return false
}

func (e ApiError) Error() string {
	return fmt.Sprintf("%#v", e)
}

func (e ApiError) Validate() bool {
	if len(e.Fields) != 0 || len(e.Message) != 0 || len(e.ErrorCode) != 0 || len(e.ErrorName) != 0 || len(e.ErrorDescription) != 0 {
		return true
	}

	return false
}

package force

import (
	"fmt"
	"strings"
)

// Custom Error to handle salesforce api responses.
type ApiErrors []*ApiError

type ApiError struct {
	Fields           []string `json:"fields,omitempty" force:"fields,omitempty"`
	Message          string   `json:"message,omitempty" force:"message,omitempty"`
	ErrorCode        string   `json:"errorCode,omitempty" force:"errorCode,omitempty"`
	ErrorName        string   `json:"error,omitempty" force:"error,omitempty"`
	ErrorDescription string   `json:"error_description,omitempty" force:"error_description,omitempty"`
}

func (e ApiErrors) Error() string {
	return e.String()
}

func (e ApiErrors) String() string {
	s := make([]string, len(e))
	for i, err := range e {
		s[i] = err.String()
	}

	return strings.Join(s, "\n")
}

func (e ApiErrors) Validate() bool {
	if len(e) != 0 {
		return true
	}

	return false
}

func (e ApiError) Error() string {
	return e.String()
}

func (e ApiError) String() string {
	return fmt.Sprintf("%#v", e)
}

func (e ApiError) Validate() bool {
	if len(e.Fields) != 0 || len(e.Message) != 0 || len(e.ErrorCode) != 0 || len(e.ErrorName) != 0 || len(e.ErrorDescription) != 0 {
		return true
	}

	return false
}

Use Stringer interface for ApiErrors and ApiError.


package i18n

// TranslatableString is the interface implemented
// by strings that can be translated.
type TranslatableString interface {
	TranslatedString(lang Languager) string
}

// String is an alias for string, but variables
// or constants declared with the type String will
// be extracted for translation.
type String string

// String returns the String as a plain string.
func (s String) String() string {
	return string(s)
}

// TranslatedString returns the string translated into
// the language returned by lang.
func (s String) TranslatedString(lang Languager) string {
	return T(string(s), lang)
}

package i18n

import (
	"gnd.la/util/textutil"
)

// TranslatableString is the interface implemented
// by strings that can be translated.
type TranslatableString interface {
	TranslatedString(lang Languager) string
}

// String is an alias for string, but variables
// or constants declared with the type String will
// be extracted for translation.
type String string

// String returns the String as a plain string.
func (s String) String() string {
	return string(s)
}

// TranslatedString returns the string translated into
// the language returned by lang.
func (s String) TranslatedString(lang Languager) string {
	if string(s) == "" {
		return ""
	}
	fields, _ := textutil.SplitFields(string(s), "|")
	if len(fields) > 1 {
		return Tc(fields[0], fields[1], lang)
	}
	if len(fields) > 0 {
		return T(fields[0], lang)
	}
	return T(string(s), lang)
}

Add support for i18n.String with multiple fields


package rpcd

import (
	"github.com/Symantec/Dominator/lib/filter"
	"github.com/Symantec/Dominator/lib/srpc"
	"github.com/Symantec/Dominator/proto/sub"
)

func (t *rpcType) SetConfiguration(conn *srpc.Conn,
	request sub.SetConfigurationRequest,
	reply *sub.SetConfigurationResponse) error {
	t.scannerConfiguration.FsScanContext.GetContext().SetSpeedPercent(
		request.ScanSpeedPercent)
	t.scannerConfiguration.NetworkReaderContext.SetSpeedPercent(
		request.NetworkSpeedPercent)
	newFilter, err := filter.NewFilter(request.ScanExclusionList)
	if err != nil {
		return err
	}
	t.scannerConfiguration.ScanFilter = newFilter
	return nil
}

package rpcd

import (
	"github.com/Symantec/Dominator/lib/filter"
	"github.com/Symantec/Dominator/lib/srpc"
	"github.com/Symantec/Dominator/proto/sub"
)

func (t *rpcType) SetConfiguration(conn *srpc.Conn,
	request sub.SetConfigurationRequest,
	reply *sub.SetConfigurationResponse) error {
	t.scannerConfiguration.FsScanContext.GetContext().SetSpeedPercent(
		request.ScanSpeedPercent)
	t.scannerConfiguration.NetworkReaderContext.SetSpeedPercent(
		request.NetworkSpeedPercent)
	newFilter, err := filter.NewFilter(request.ScanExclusionList)
	if err != nil {
		return err
	}
	t.scannerConfiguration.ScanFilter = newFilter
	t.logger.Printf("SetConfiguration()\n")
	return nil
}

Add logging for Sub.SetConfiguration SRPC method.


package discountcalculator

type discountCalculator struct {
	strategy     func() (rate float64, strategyCode int)
	strategyCode int
}

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

func (calculator *discountCalculator) DiscountFor(customer *customer) *discount {
	switch c := customer.category; c {
	case STANDARD:
		return NewDiscount(STANDARD_DISCOUNT)
	case SILVER:
		return NewDiscount(SILVER_DISCOUNT)
	case GOLD:
		return NewDiscount(GOLD_DISCOUNT)
	case PREMIUM:
		return NewDiscount(PREMIUM_DISCOUNT)
	}

	return nil
}

func (calculator *discountCalculator) SpecialDiscountFor(customer *customer, couponType int) *discount {
	customerDiscount := calculator.DiscountFor(customer)

	var d *discount
	switch couponType {
	case BIRTHDAY_ANNIVERSARY:
		d = NewDiscount(BIRTHDAY_DISCOUNT)
	}

	decimal := 2
	d.addRates(customerDiscount, decimal)
	return d
}

package discountcalculator

type discountCalculator struct {
	strategy func() (rate float64, strategyCode int)
}

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

func (calculator *discountCalculator) DiscountFor(customer *customer) *discount {
	switch c := customer.category; c {
	case STANDARD:
		return NewDiscount(STANDARD_DISCOUNT)
	case SILVER:
		return NewDiscount(SILVER_DISCOUNT)
	case GOLD:
		return NewDiscount(GOLD_DISCOUNT)
	case PREMIUM:
		return NewDiscount(PREMIUM_DISCOUNT)
	}

	return nil
}

func (calculator *discountCalculator) SpecialDiscountFor(customer *customer, couponType int) *discount {
	customerDiscount := calculator.DiscountFor(customer)

	var d *discount
	switch couponType {
	case BIRTHDAY_ANNIVERSARY:
		d = NewDiscount(BIRTHDAY_DISCOUNT)
	}

	decimal := 2
	d.addRates(customerDiscount, decimal)
	return d
}

Remove unused field in the calculator struct.


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

package migration

import (
	"testing"

	gc "gopkg.in/check.v1"
)

// Useful test constants.

const gig uint64 = 1024 * 1024 * 1024

// None of the tests in this package require mongo.
func TestPackage(t *testing.T) {
	gc.TestingT(t)
}

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

package migration

import (
	"testing"

	gc "gopkg.in/check.v1"
)

// Useful test constants.

// Constraints and CloudInstance store megabytes
const gig uint64 = 1024

// None of the tests in this package require mongo.
func TestPackage(t *testing.T) {
	gc.TestingT(t)
}

Change the gig constant to reflect state values.


package controllers

import (
	"github.com/julienschmidt/httprouter"
	"github.com/raggaer/castro/app/util"
	"net/http"
)

func ExtensionStatic(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
	// Get extension identifier
	id := ps.ByName("id")

	// Check if static file exists
	dir, exists := util.ExtensionStatic.FileExists(id)

	if !exists {
		w.WriteHeader(404)
		return
	}

	// Open desired file
	f, err := dir.Open(ps.ByName("filepath"))

	if err != nil {
		w.WriteHeader(404)
		return
	}

	// Close file handle
	defer f.Close()

	// Get file information
	fi, err := f.Stat()

	if err != nil {
		w.WriteHeader(404)
		return
	}

	// Check if file is directory
	if fi.IsDir() {
		w.WriteHeader(404)
		return
	}

	// Serve file
	http.ServeContent(w, req, ps.ByName("filepath"), fi.ModTime(), f)
}

package controllers

import (
	"github.com/julienschmidt/httprouter"
	"github.com/raggaer/castro/app/util"
	"net/http"
)

func ExtensionStatic(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
	// Get extension identifier
	id := ps.ByName("id")

	// Check if static file exists
	dir, exists := util.ExtensionStatic.FileExists(id)

	if !exists {
		w.WriteHeader(404)
		return
	}

	// Open desired file
	f, err := dir.Open(ps.ByName("filepath"))

	if err != nil {
		w.WriteHeader(404)
		return
	}

	// Close file handle
	defer f.Close()

	// Get file information
	fi, err := f.Stat()

	if err != nil {
		w.WriteHeader(404)
		return
	}

	// Check if file is directory
	if fi.IsDir() {
		w.WriteHeader(404)
		return
	}

	// Serve file
	http.ServeContent(w, req, fi.Name(), fi.ModTime(), f)
}

Use proper filename for http.ServeContent


package rapi_test

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/waltzofpearls/relay-api/rapi"
)

func TestEndpoint(t *testing.T) {

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	defer ts.Close()

	conf := rapi.NewConfig()
	conf.Backend.Address = strings.TrimPrefix(ts.URL, "http://")

	api := rapi.New(conf)
	require.NotNil(t, api)

	ep := rapi.NewEndpoint(api, "GET", "/foo")
	assert.NotNil(t, ep)

	req, err := http.NewRequest("GET", "/foo", nil)
	require.Nil(t, err)
	require.NotNil(t, req)

	resp := httptest.NewRecorder()
	require.NotNil(t, resp)

	ep.ServeHTTP(resp, req)
}

package rapi_test

import (
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/waltzofpearls/relay-api/rapi"
)

func TestEndpointUnchanged(t *testing.T) {

	var requestContent string

	expectedResult := `test`
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		req, _ := ioutil.ReadAll(r.Body)
		requestContent = string(req)
		w.Write([]byte(expectedResult))
	}))
	defer ts.Close()

	conf := rapi.NewConfig()
	conf.Backend.Address = strings.TrimPrefix(ts.URL, "http://")

	api := rapi.New(conf)
	require.NotNil(t, api)

	ep := rapi.NewEndpoint(api, "POST", "/foo")
	assert.NotNil(t, ep)

	fixture := `{"One":"this is the one", "Two":"this is the second"}`
	req, err := http.NewRequest("POST", "/foo", strings.NewReader(fixture))
	require.Nil(t, err)
	require.NotNil(t, req)

	resp := httptest.NewRecorder()
	require.NotNil(t, resp)

	ep.ServeHTTP(resp, req)

	assert.Equal(t, http.StatusOK, resp.Code)
	assert.Equal(t, fixture, requestContent, "request body is unchanged")
}

Validate that the request body is unchanged by default


package sys

/*
#include <unistd.h>

int f(int fd, pid_t pid) {
	return tcsetpgrp(fd, pid);
}
*/
import "C"
import "syscall"

func Tcsetpgrp(fd int, pid int) error {
	i := syscall.Errno(C.f(C.int(fd), C.pid_t(pid)))
	if i != 0 {
		return syscall.Errno(i)
	}
	return nil
}

package sys

/*
#include <unistd.h>
#include <errno.h>

int f(int fd, pid_t pid) {
	return tcsetpgrp(fd, pid);
}

int e() {
	return errno;
}
*/
import "C"
import "syscall"

func Tcsetpgrp(fd int, pid int) error {
	i := C.f(C.int(fd), C.pid_t(pid))
	if i != 0 {
		return syscall.Errno(C.e())
	}
	return nil
}

Fix error reporting of Tcsetgrp.


/*
Copyright 2015 The Kubernetes Authors All rights reserved.

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

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

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

package unversioned

const LabelZoneFailureDomain = "failure-domain.alpha.kubernetes.io/zone"
const LabelZoneRegion = "failure-domain.alpha.kubernetes.io/region"
const LabelInstanceType = "beta.kubernetes.io/instance-type"

Add instance-type label to cloud providers


package commands

import (
	"fmt"

	"github.com/cloudfoundry/bosh-bootloader/flags"
	"github.com/cloudfoundry/bosh-bootloader/storage"
)

type FilteredDeleter interface {
	Delete(filter string) error
}

type CleanupLeftovers struct {
	deleter FilteredDeleter
}

func NewCleanupLeftovers(deleter FilteredDeleter) CleanupLeftovers {
	return CleanupLeftovers{
		deleter: deleter,
	}
}

func (l CleanupLeftovers) CheckFastFails(subcommandFlags []string, state storage.State) error {
	return nil
}

func (l CleanupLeftovers) Execute(subcommandFlags []string, state storage.State) error {
	var filter string
	f := flags.New("cleanup-leftovers")
	f.String(&filter, "filter", "")

	err := f.Parse(subcommandFlags)
	if err != nil {
		return fmt.Errorf("Parsing cleanup-leftovers args: %s", err)
	}

	return l.deleter.Delete(filter)
}

func (l CleanupLeftovers) Usage() string {
	return fmt.Sprintf("%s%s%s", CleanupLeftoversCommandUsage, requiresCredentials, Credentials)
}

package commands

import (
	"fmt"

	"github.com/cloudfoundry/bosh-bootloader/flags"
	"github.com/cloudfoundry/bosh-bootloader/storage"
)

type FilteredDeleter interface {
	Delete(filter string) error
}

type CleanupLeftovers struct {
	deleter FilteredDeleter
}

func NewCleanupLeftovers(deleter FilteredDeleter) CleanupLeftovers {
	return CleanupLeftovers{
		deleter: deleter,
	}
}

func (l CleanupLeftovers) CheckFastFails(subcommandFlags []string, state storage.State) error {
	return nil
}

func (l CleanupLeftovers) Execute(subcommandFlags []string, state storage.State) error {
	var filter string
	f := flags.New("cleanup-leftovers")
	f.String(&filter, "filter", "")

	err := f.Parse(subcommandFlags)
	if err != nil {
		return fmt.Errorf("Parsing cleanup-leftovers args: %s", err)
	}

	if state.IAAS == "vsphere" || state.IAAS == "openstack" {
		// we don't create network infrastructure on vsphere or openstack
		// and we don't tear it down either
		return nil
	}

	return l.deleter.Delete(filter)
}

func (l CleanupLeftovers) Usage() string {
	return fmt.Sprintf("%s%s%s", CleanupLeftoversCommandUsage, requiresCredentials, Credentials)
}

Fix leftovers panic on vSphere


package main

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

func main() {
	httpListen := flag.String("http", "127.0.0.1:8080", "host:port to listen on")
	// basePath := flag.String("base", ".", "base path for web interface templates and static resources")
	// cvsPath := flag.String("cvs", ".", "path to the cvs repository checkout")
	flag.Parse()

	// http.Handle("/static/", http.FileServer(http.Dir(*basePath)))

	if strings.HasPrefix(*httpListen, "127.0.0.1") ||
		strings.HasPrefix(*httpListen, "localhost") {
		log.Print("Bind to your external IP address if you want to share the service with others")
	}

	log.Printf("Open your web browser and visit http://%s/", *httpListen)
	log.Fatal(http.ListenAndServe(*httpListen, nil))
}

package main

import (
	"flag"
	"log"
	"net/http"
	"os"
	"strings"

	"github.com/mulander/norway"
)

var cvs norway.Entries

func Init(cvsPath string) {
	entriesFile, err := os.Open(cvsPath + "/CVS/Entries")
	if err != nil {
		log.Fatal(err)
	}
	defer entriesFile.Close()

	cvs, err = norway.ParseEntries(entriesFile)
	if err != nil {
		log.Fatal(err)
	}
}

func main() {
	httpListen := flag.String("http", "127.0.0.1:8080", "host:port to listen on")
	// basePath := flag.String("base", ".", "base path for web interface templates and static resources")
	cvsPath := flag.String("cvs", ".", "path to the cvs repository checkout")
	flag.Parse()

	// http.Handle("/static/", http.FileServer(http.Dir(*basePath)))

	Init(*cvsPath)

	if strings.HasPrefix(*httpListen, "127.0.0.1") ||
		strings.HasPrefix(*httpListen, "localhost") {
		log.Print("Bind to your external IP address if you want to share the service with others")
	}

	log.Printf("Open your web browser and visit http://%s/", *httpListen)
	log.Fatal(http.ListenAndServe(*httpListen, nil))
}

Add basic single directory entries parse on startup


package copy

import (
	"strings"
)

// Use the object Meta from files (move to other file?)

type LinkService struct {
	client *Client
}

var (
	// Links paths
	linksTopLevelSuffix = "links"
	linksGetSuffix      = strings.Join([]string{linksTopLevelSuffix, "%v"}, "/") // https://.../links/TOKEN
)

func NewLinkService(client *Client) *LinkService {
	fs := new(LinkService)
	fs.client = client
	return fs
}

func (ls *LinkService) GetLink(token string) (*Meta, error) {
	return nil, nil
}

func (ls *LinkService) GetLinks() ([]Meta, error) {
	return nil, nil
}

func (ls *LinkService) CreateLink(name string, paths []string, public bool) error {
	return nil, nil
}

func (ls *LinkService) AddPaths(token string, paths []string) error {
	return nil, nil
}

func (ls *LinkService) AddRecipients(token string, recipients []Recipient) error {
	return nil, nil
}

func (ls *LinkService) DeleteLink(token string) error {
	return nil, nil
}

func (ls *LinkService) GetFilesMetaFromLink(token string) (*Meta, error) {
	return nil, nil
}

package copy

import (
	"strings"
)

// Use the object Meta from files (move to other file?)

type LinkService struct {
	client *Client
}

var (
	// Links paths
	linksTopLevelSuffix = "links"
	linksGetSuffix      = strings.Join([]string{linksTopLevelSuffix, "%v"}, "/") // https://.../links/TOKEN
)

func NewLinkService(client *Client) *LinkService {
	fs := new(LinkService)
	fs.client = client
	return fs
}

func (ls *LinkService) GetLink(token string) (*Meta, error) {
	return nil, nil
}

func (ls *LinkService) GetLinks() ([]Meta, error) {
	return nil, nil
}

func (ls *LinkService) CreateLink(name string, paths []string, public bool) error {
	return nil
}

func (ls *LinkService) AddPaths(token string, paths []string) error {
	return nil
}

func (ls *LinkService) AddRecipients(token string, recipients []Recipient) error {
	return nil
}

func (ls *LinkService) DeleteLink(token string) error {
	return nil
}

func (ls *LinkService) GetFilesMetaFromLink(token string) (*Meta, error) {
	return nil, nil
}

Fix return types to return correct number of values


package ambition

import (
	"encoding/json"
)

func PostOccurrenceByActionIdJson(ActionId int, occurrenceJson []byte) error {
	var occurrence Occurrence
	err := json.Unmarshal(occurrenceJson, occurrence)

	occurrence.ActionId = ActionId
	database.InsertOccurrence(&occurrence)

	return err
}

func PostActionBySetIdJson(SetId int, actionJson []byte) error {
	var action Action
	err := json.Unmarshal(actionJson, action)

	action.SetId = SetId
	database.InsertAction(&action)

	return err
}

func PostArrayOfSetsJson(setJson []byte) error {
	var sets []Set
	json.Unmarshal(setJson, &sets)
	var err error
	for _, set := range sets {
		err = database.InsertSet(&set)
	}

	return err
}

func PostArrayOfActionsJson(actionJson []byte) error {
	var actions []Action
	json.Unmarshal(actionJson, &actions)
	var err error
	for _, action := range actions {
		err = database.InsertAction(&action)
	}

	return err
}

func PostArrayOfOccurrencesJson(occurrenceJson []byte) error {
	var occurrences []Occurrence
	json.Unmarshal(occurrenceJson, &occurrences)
	var err error
	for _, occurrence := range occurrences {
		err = database.InsertOccurrence(&occurrence)
	}

	return err
}

package ambition

import (
	"encoding/json"
)

func PostOccurrenceByActionIdJson(ActionId int, occurrenceJson []byte) error {
	var occurrence Occurrence
	err := json.Unmarshal(occurrenceJson, &occurrence)

	occurrence.ActionId = ActionId
	database.InsertOccurrence(&occurrence)

	return err
}

func PostActionBySetIdJson(SetId int, actionJson []byte) error {
	var action Action
	err := json.Unmarshal(actionJson, &action)

	action.SetId = SetId
	database.InsertAction(&action)

	return err
}

func PostArrayOfSetsJson(setJson []byte) error {
	var sets []Set
	json.Unmarshal(setJson, &sets)
	var err error
	for _, set := range sets {
		err = database.InsertSet(&set)
	}

	return err
}

func PostArrayOfActionsJson(actionJson []byte) error {
	var actions []Action
	json.Unmarshal(actionJson, &actions)
	var err error
	for _, action := range actions {
		err = database.InsertAction(&action)
	}

	return err
}

func PostArrayOfOccurrencesJson(occurrenceJson []byte) error {
	var occurrences []Occurrence
	json.Unmarshal(occurrenceJson, &occurrences)
	var err error
	for _, occurrence := range occurrences {
		err = database.InsertOccurrence(&occurrence)
	}

	return err
}

Fix passing json unmarshal non-pointer values


// Copyright ©2014 The gonum 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 mat64

// Inner computes the generalized inner product between x and y with matrix A.
//  x^T A y
// This is only a true inner product if m is symmetric positive definite, though
// the operation works for any matrix A.
//
// Inner panics if len(x) != m or len(y) != n when A is an m x n matrix.
func Inner(x []float64, A Matrix, y []float64) float64 {
	m, n := A.Dims()
	if len(x) != m {
		panic(ErrShape)
	}
	if len(y) != n {
		panic(ErrShape)
	}
	if m == 0 || n == 0 {
		return 0
	}

	var sum float64

	switch b := A.(type) {
	case RawMatrixer:
		bmat := b.RawMatrix()
		for i, xi := range x {
			for j, yj := range y {
				sum += xi * bmat.Data[i*bmat.Stride+j] * yj
			}
		}
	default:
		for i, xi := range x {
			for j, yj := range y {
				sum += xi * A.At(i, j) * yj
			}
		}
	}
	return sum
}

// Copyright ©2014 The gonum 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 mat64

// Inner computes the generalized inner product
//   x^T A y
// between vectors x and y with matrix A. This is only a true inner product if
// A is symmetric positive definite, though the operation works for any matrix A.
//
// Inner panics if len(x) != m or len(y) != n when A is an m x n matrix.
func Inner(x []float64, A Matrix, y []float64) float64 {
	m, n := A.Dims()
	if len(x) != m {
		panic(ErrShape)
	}
	if len(y) != n {
		panic(ErrShape)
	}
	if m == 0 || n == 0 {
		return 0
	}

	var sum float64

	switch b := A.(type) {
	case RawMatrixer:
		bmat := b.RawMatrix()
		for i, xi := range x {
			for j, yj := range y {
				sum += xi * bmat.Data[i*bmat.Stride+j] * yj
			}
		}
	default:
		for i, xi := range x {
			for j, yj := range y {
				sum += xi * A.At(i, j) * yj
			}
		}
	}
	return sum
}

Reformat and update comment for func Inner()


package main

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

type config struct {
	controllerKey string
	ourPort       string
	logOut        io.Writer
}

func loadConfigFromEnv() (*config, error) {
	c := &config{}
	c.controllerKey = os.Getenv("CONTROLLER_KEY")
	if c.controllerKey == "" {
		return nil, fmt.Errorf("CONTROLLER_KEY is required")
	}
	port := os.Getenv("PORT")
	if port == "" {
		port = "4456"
	}
	c.ourPort = port

	logPath := os.Getenv("LOGFILE")
	c.logOut = ioutil.Discard
	if logPath != "" {
		if f, err := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666); err == nil {
			c.logOut = f
		}
	}
	return c, nil
}

package main

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

type config struct {
	controllerKey string
	ourPort       string
	logOut        io.Writer
}

func loadConfigFromEnv() (*config, error) {
	c := &config{}
	c.controllerKey = os.Getenv("CONTROLLER_KEY")
	if c.controllerKey == "" {
		return nil, fmt.Errorf("CONTROLLER_KEY is required")
	}
	port := os.Getenv("PORT")
	if port == "" {
		port = "4456"
	}
	c.ourPort = port

	if logPath := os.Getenv("LOGFILE"); logPath != "" {
		if f, err := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666); err == nil {
			c.logOut = f
		}
	}
	if c.logOut == nil {
		c.logOut = os.Stderr
	}
	return c, nil
}

Send log output to STDERR by default


package common

const (
	OpGet = iota
	OpSet
	OpDel
	OpLst
)

var opNames map[byte]string

func init() {
	opNames = make(map[byte]string, 0)
	opNames[OpGet] = "GET"
	opNames[OpSet] = "SET"
	opNames[OpDel] = "DEL"
	opNames[OpLst] = "LST"
}

type Operation struct {
	OpCode byte
	Key    []byte
	Val    []byte
	WID    int // ID of the handling worker
}

func (op *Operation) Name() string {
	return opNames[op.OpCode]
}

type Request struct {
	Op   *Operation
	Resp chan *Response
}

func (req *Request) OpName() string {
	return req.Op.Name()
}

type Response struct {
	Body []byte
}

package common

const (
	OpGet = iota
	OpSet
	OpDel
	OpLst
)

var opNames map[byte]string

func init() {
	opNames = make(map[byte]string, 0)
	opNames[OpGet] = "GET"
	opNames[OpSet] = "SET"
	opNames[OpDel] = "DEL"
	opNames[OpLst] = "LST"
}

type Operation struct {
	OpCode byte
	Key    []byte
	Val    []byte
	WID    int // ID of the handling worker
}

func (op *Operation) Name() string {
	return opNames[op.OpCode]
}

type Request struct {
	Op   *Operation
	Resp chan *Response
}

func (req *Request) OpName() string {
	return req.Op.Name()
}

type Response struct {
	KeyOK  bool
	Body   []byte
	ErrMsg string
}

Add field in Response indicating presence of key in store.


//Package main is an example package
package main

func main() {
	doThisOrThat(false)
}

func doThisOrThat(flag bool) { // Issue
	if flag {
		doThis()
	} else {
		doThat()
	}
}

func returnsTrue() bool {
	return true
}

func doThis() {}

func doThat() {}

Add package comment to adhere to CodeLingo review bot