package components

import (
	"testing"

	"github.com/scipipe/scipipe"
)

func TestCommandToParams(tt *testing.T) {
	// Run test workflow and make sure that the parameter read from the file is
	// always "abc"
	wf := scipipe.NewWorkflow("wf", 4)

	cmdToParams := NewCommandToParams(wf, "cmdtoparams", "echo foo; echo bar; echo baz;")

	checker := wf.NewProc("checker", "# {p:param}")
	checker.CustomExecute = func(t *scipipe.Task) {
		expected := []string{"foo", "bar", "baz"}
		actual := t.Param("param")
		if actual != expected[0] && actual != expected[1] && actual != expected[2] {
			tt.Errorf("Actual string (%s) was not one of the expected ones (%s, %s, %s)", actual, expected[0], expected[1], expected[2])
		}
	}
	checker.InParam("param").From(cmdToParams.OutParam())

	wf.Run()
}

package components

import (
	"testing"

	"github.com/scipipe/scipipe"
)

func TestCommandToParams(tt *testing.T) {
	// Run test workflow and make sure that the parameter read from the file is
	// always "abc"
	wf := scipipe.NewWorkflow("wf", 4)

	cmdToParams := NewCommandToParams(wf, "cmdtoparams", "{ echo foo; echo bar; echo baz; }")

	checker := wf.NewProc("checker", "# {p:param}")
	checker.CustomExecute = func(t *scipipe.Task) {
		expected := []string{"foo", "bar", "baz"}
		actual := t.Param("param")
		if actual != expected[0] && actual != expected[1] && actual != expected[2] {
			tt.Errorf("Actual string (%s) was not one of the expected ones (%s, %s, %s)", actual, expected[0], expected[1], expected[2])
		}
	}
	checker.InParam("param").From(cmdToParams.OutParam())

	wf.Run()
}

Improve shell command in test


package entities

import "time"

var (
	timeStamp int64   = time.Date(2012, time.November, 10, 23, 0, 0, 0, time.UTC).UnixNano() / 1e6
	mission   Mission = Mission{
		Color:       Color{22, 22, 22},
		Source:      []int{100, 200},
		Target:      []int{800, 150},
		Type:        "Attack",
		CurrentTime: timeStamp,
		StartTime:   timeStamp,
		TravelTime:  timeStamp,
		Player:      "gophie",
		ShipCount:   5,
	}
	planet Planet = Planet{
		Color:               Color{22, 22, 22},
		Coords:              []int{271, 203},
		IsHome:              false,
		Texture:             3,
		Size:                1,
		LastShipCountUpdate: timeStamp,
		ShipCount:           0,
		MaxShipCount:        0,
		Owner:               "gophie",
	}
)

package entities

import "time"

var (
	timeStamp int64   = time.Date(2012, time.November, 10, 23, 0, 0, 0, time.UTC).UnixNano() / 1e6
	mission   Mission = Mission{
		Color:       Color{22, 22, 22},
		Source:      []int{100, 200},
		Target:      []int{800, 150},
		Type:        "Attack",
		CurrentTime: timeStamp,
		StartTime:   timeStamp,
		TravelTime:  timeStamp,
		Player:      "gophie",
		ShipCount:   5,
	}
	planet Planet = Planet{
		Color:               Color{22, 22, 22},
		Coords:              []int{271, 203},
		IsHome:              false,
		Texture:             3,
		Size:                1,
		LastShipCountUpdate: timeStamp,
		ShipCount:           0,
		MaxShipCount:        0,
		Owner:               "gophie",
	}
	player Player = Player{
		username: "gophie",
		Color: Color{22, 22, 22},
		TwitterID: "asdf",
		HomePlanet: "planet.271_203",
		ScreenSize: []int{1, 1},
		ScreenPosition: []int{2, 2},
	}
)

Add player in the test data


package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

Update go hello world with tab instead of spaces indentation.


package core

import (
	"testing"

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

func TestBoolEqual(t *testing.T) {
	for _, ts := range [][2]*Thunk{
		{True, True},
		{False, False},
	} {
		assert.True(t, testEqual(ts[0], ts[1]))
	}

	for _, ts := range [][2]*Thunk{
		{True, False},
		{False, True},
	} {
		assert.True(t, !testEqual(ts[0], ts[1]))
	}
}

func TestBoolToString(t *testing.T) {
	test := func(s string, b bool) {
		assert.Equal(t, StringType(s), PApp(ToString, NewBool(b)).Eval())
	}

	test("true", true)
	test("false", false)
}

func TestIf(t *testing.T) {
	assert.Equal(t, Nil.Eval(), PApp(If, True, Nil, False).Eval())
	assert.Equal(t, Nil.Eval(), PApp(If, False, False, Nil).Eval())
}

func TestIfWithInvalidArguments(t *testing.T) {
	_, ok := PApp(If, Nil, Nil, Nil).Eval().(ErrorType)
	assert.True(t, ok)
}

Increase test coverange of core/bool.go


package narcissus

import (
	"testing"

	"honnef.co/go/augeas"
)

type foo struct {
}

func TestParseNotAPtr(t *testing.T) {
	n := New(&augeas.Augeas{})
	err := n.Parse(foo{}, "/files/some/path")

	if err == nil {
		t.Error("Expected an error, got nothing")
	}

	if err.Error() != "not a ptr" {
		t.Errorf("Expected error not a ptr, got %s", err.Error())
	}
}

func TestParseNotAStruct(t *testing.T) {
	n := New(&augeas.Augeas{})
	f := "foo"
	err := n.Parse(&f, "/files/some/path")

	if err == nil {
		t.Error("Expected an error, got nothing")
	}

	if err.Error() != "not a struct" {
		t.Errorf("Expected error not a struct, got %s", err.Error())
	}
}

package narcissus

import (
	"testing"

	"honnef.co/go/augeas"
)

type foo struct {
	A string `path:"a"`
}

func TestParseNotAPtr(t *testing.T) {
	n := New(&augeas.Augeas{})
	err := n.Parse(foo{}, "/files/some/path")

	if err == nil {
		t.Error("Expected an error, got nothing")
	}

	if err.Error() != "not a ptr" {
		t.Errorf("Expected error not a ptr, got %s", err.Error())
	}
}

func TestParseNotAStruct(t *testing.T) {
	n := New(&augeas.Augeas{})
	f := "foo"
	err := n.Parse(&f, "/files/some/path")

	if err == nil {
		t.Error("Expected an error, got nothing")
	}

	if err.Error() != "not a struct" {
		t.Errorf("Expected error not a struct, got %s", err.Error())
	}
}

func TestParseFieldNotFound(t *testing.T) {
	n := New(&augeas.Augeas{})
	t.Skip("This causes a segfault with the Augeas lib. Open a bug!")
	err := n.Parse(&foo{}, "/files/some/path")

	if err == nil {
		t.Error("Expected an error, got nothing")
	}
}

Add test for field not found (currently failing)


// +build linux

package common

import "os"

func NumProcs() (uint64, error) {
	f, err := os.Open(HostProc())
	if err != nil {
		return 0, err
	}

	list, err := f.Readdir(-1)
	defer f.Close()
	if err != nil {
		return 0, err
	}
	return uint64(len(list)), err
}

// +build linux

package common

import (
	"os"
	"os/exec"
	"strings"
)

func DoSysctrl(mib string) ([]string, error) {
	err := os.Setenv("LC_ALL", "C")
	if err != nil {
		return []string{}, err
	}
	sysctl, err := exec.LookPath("/sbin/sysctl")
	if err != nil {
		return []string{}, err
	}
	out, err := exec.Command(sysctl, "-n", mib).Output()
	if err != nil {
		return []string{}, err
	}
	v := strings.Replace(string(out), "{ ", "", 1)
	v = strings.Replace(string(v), " }", "", 1)
	values := strings.Fields(string(v))

	return values, nil
}

func NumProcs() (uint64, error) {
	f, err := os.Open(HostProc())
	if err != nil {
		return 0, err
	}

	list, err := f.Readdir(-1)
	defer f.Close()
	if err != nil {
		return 0, err
	}
	return uint64(len(list)), err
}

Add DoSysctrl() to Linux's common utilities.


// +build go1.8

package avatica

import (
	"database/sql/driver"
	"fmt"
)

type namedValue struct {
	Name    string
	Ordinal int
	Value   driver.Value
}

func driverValueToNamedValue(values []driver.Value) []namedValue {
	list := make([]namedValue, len(values))

	for i, v := range values {
		list[i] = namedValue{
			Ordinal: i + 1,
			Value:   v,
		}
	}

	return list
}

func driverNamedValueToNamedValue(values []driver.NamedValue) ([]namedValue,error ) {
	list := make([]namedValue, len(values))

	for i, nv := range values {
		list[i] = namedValue(nv)

		if nv.Name != ""{
			return list,fmt.Errorf("named paramters are not supported: %s given", nv.Name)
		}
	}

	return list, nil
}

type isoLevel int32

const (
	isolationUseCurrent      isoLevel = -1
	isolationNone            isoLevel = 0
	isolationReadUncommitted isoLevel = 1
	isolationReadComitted    isoLevel = 2
	isolationRepeatableRead  isoLevel = 4
	isolationSerializable    isoLevel = 8
)

package avatica

import (
	"database/sql/driver"
	"fmt"
)

type namedValue struct {
	Name    string
	Ordinal int
	Value   driver.Value
}

func driverValueToNamedValue(values []driver.Value) []namedValue {
	list := make([]namedValue, len(values))

	for i, v := range values {
		list[i] = namedValue{
			Ordinal: i + 1,
			Value:   v,
		}
	}

	return list
}

func driverNamedValueToNamedValue(values []driver.NamedValue) ([]namedValue, error) {
	list := make([]namedValue, len(values))

	for i, nv := range values {
		list[i] = namedValue(nv)

		if nv.Name != "" {
			return list, fmt.Errorf("named paramters are not supported: %s given", nv.Name)
		}
	}

	return list, nil
}

type isoLevel int32

const (
	isolationUseCurrent      isoLevel = -1
	isolationNone            isoLevel = 0
	isolationReadUncommitted isoLevel = 1
	isolationReadComitted    isoLevel = 2
	isolationRepeatableRead  isoLevel = 4
	isolationSerializable    isoLevel = 8
)

Remove go 1.8 build tag for compatibility structs and constants


package orchestrators

import (
	log "github.com/Sirupsen/logrus"
	"github.com/camptocamp/conplicity/handler"
	"github.com/camptocamp/conplicity/volume"
)

// Orchestrator implements a container Orchestrator interface
type Orchestrator interface {
	GetHandler() *handler.Conplicity
	GetVolumes() ([]*volume.Volume, error)
	LaunchContainer(image string, env map[string]string, cmd []string, v []*volume.Volume) (state int, stdout string, err error)
	GetMountedVolumes() ([]*volume.MountedVolumes, error)
	ContainerExec(containerID string, command []string) error
}

// GetOrchestrator returns the Orchestrator as specified in configuration
func GetOrchestrator(c *handler.Conplicity) Orchestrator {
	orch := c.Config.Orchestrator
	log.Debugf("orchestrator=%s", orch)

	switch orch {
	case "docker":
		return NewDockerOrchestrator(c)
	}

	log.Fatalf("Unknown orchestrator %s", orch)
	return nil
}

package orchestrators

import (
	log "github.com/Sirupsen/logrus"
	"github.com/camptocamp/conplicity/handler"
	"github.com/camptocamp/conplicity/volume"
)

// Orchestrator implements a container Orchestrator interface
type Orchestrator interface {
	GetHandler() *handler.Conplicity
	GetVolumes() ([]*volume.Volume, error)
	LaunchContainer(image string, env map[string]string, cmd []string, volumes []*volume.Volume) (state int, stdout string, err error)
	GetMountedVolumes() ([]*volume.MountedVolumes, error)
	ContainerExec(containerID string, command []string) error
}

// GetOrchestrator returns the Orchestrator as specified in configuration
func GetOrchestrator(c *handler.Conplicity) Orchestrator {
	orch := c.Config.Orchestrator
	log.Debugf("orchestrator=%s", orch)

	switch orch {
	case "docker":
		return NewDockerOrchestrator(c)
	}

	log.Fatalf("Unknown orchestrator %s", orch)
	return nil
}

Update volumes variable name for LaunchContainer


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

// +build linux,!appengine darwin freebsd openbsd

package term

import (
	"unsafe"

	"golang.org/x/sys/unix"
)

// IsTty returns true if the given file descriptor is a terminal.
func IsTty(fd uintptr) bool {
	var termios Termios
	_, _, err := unix.Syscall6(unix.SYS_IOCTL, fd, ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
	return err == 0
}

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

// +build linux,!appengine darwin freebsd openbsd

package term

import (
	"golang.org/x/sys/unix"
)

// IsTty returns true if the given file descriptor is a terminal.
func IsTty(fd uintptr) bool {
	_, err := unix.IoctlGetTermios(int(fd), ioctlReadTermios)
	return err == nil
}

Fix due to recent unix change


package qemuengine

import (
	"fmt"
	"os"

	"github.com/taskcluster/taskcluster-worker/engines/qemu/image"
	"github.com/taskcluster/taskcluster-worker/runtime"
	"github.com/taskcluster/taskcluster-worker/runtime/fetcher"
)

// A fetcher for downloading images.
var imageFetcher = fetcher.Combine(
	// Allow fetching images from URL
	fetcher.URL,
	// Allow fetching images from queue artifacts
	fetcher.Artifact,
)

type fetchImageContext struct {
	*runtime.TaskContext
}

func (c fetchImageContext) Progress(description string, percent float64) {
	c.Log(fmt.Sprintf("Fetching image: %s - %f %%", description, percent))
}

func imageDownloader(c *runtime.TaskContext, image interface{}) image.Downloader {
	return func(imageFile string) error {
		target, err := os.Create(imageFile)
		if err != nil {
			return err
		}
		err = imageFetcher.Fetch(fetchImageContext{c}, image, &fetcher.FileReseter{File: target})
		if err != nil {
			defer target.Close()
			return err
		}
		return target.Close()
	}
}

package qemuengine

import (
	"fmt"
	"os"

	"github.com/taskcluster/taskcluster-worker/engines/qemu/image"
	"github.com/taskcluster/taskcluster-worker/runtime"
	"github.com/taskcluster/taskcluster-worker/runtime/fetcher"
)

// A fetcher for downloading images.
var imageFetcher = fetcher.Combine(
	// Allow fetching images from URL
	fetcher.URL,
	// Allow fetching images from queue artifacts
	fetcher.Artifact,
)

type fetchImageContext struct {
	*runtime.TaskContext
}

func (c fetchImageContext) Progress(description string, percent float64) {
	c.Log(fmt.Sprintf("Fetching image: %s - %f %%", description, percent))
}

func imageDownloader(c *runtime.TaskContext, image interface{}) image.Downloader {
	return func(imageFile string) error {
		target, err := os.Create(imageFile)
		if err != nil {
			return err
		}
		err = imageFetcher.Fetch(fetchImageContext{c}, image, &fetcher.FileReseter{File: target})
		if err != nil {
			defer target.Close()
			if fetcher.IsBrokenReferenceError(err) {
				return runtime.NewMalformedPayloadError("unable to fetch image, error:", err)
			}
			return err
		}
		return target.Close()
	}
}

Transform broken reference to malformed-payload error


package values

// Keys returns all the keys.
func (m SMap) Keys() []string {
	r := make([]string, 0)
	for k := range m {
		r = append(r, k)
	}
	return r
}

// Values returns all the values.
func (m SMap) Values() []interface{} {
	r := make([]interface{}, 0)
	for _, v := range m {
		r = append(r, v)
	}
	return r
}

// In returns true if k is a key of SMap, or false.
func (m SMap) In(k string) bool {
	_, ok := m[k]
	return ok
}

Add the method In for SMap.


package termios

import (
	"fmt"
	"unsafe"

	"golang.org/x/sys/unix"
)

func open_pty_master() (uintptr, error) {
	return open_device("/dev/ptmx")
}

func Ptsname(fd uintptr) (string, error) {
	var n uintptr
	err := ioctl(fd, unix.TIOCGPTN, uintptr(unsafe.Pointer(&n)))
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("/dev/pts/%d", n), nil
}

func grantpt(fd uintptr) error {
	var n uintptr
	return ioctl(fd, unix.TIOCGPTN, uintptr(unsafe.Pointer(&n)))
}

func unlockpt(fd uintptr) error {
	var n uintptr
	return ioctl(fd, unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&n)))
}

package termios

import (
	"fmt"
	"unsafe"

	"golang.org/x/sys/unix"
)

func open_pty_master() (uintptr, error) {
	return open_device("/dev/ptmx")
}

func Ptsname(fd uintptr) (string, error) {
	var n uint32
	err := ioctl(fd, unix.TIOCGPTN, uintptr(unsafe.Pointer(&n)))
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("/dev/pts/%d", n), nil
}

func grantpt(fd uintptr) error {
	var n uintptr
	return ioctl(fd, unix.TIOCGPTN, uintptr(unsafe.Pointer(&n)))
}

func unlockpt(fd uintptr) error {
	var n uintptr
	return ioctl(fd, unix.TIOCSPTLCK, uintptr(unsafe.Pointer(&n)))
}

Fix ptsname() for big-endian architectures


// Package events defines the structures used for events dispatched from the
// wrangler package.
package events

import (
	"github.com/youtube/vitess/go/event"
	"github.com/youtube/vitess/go/vt/topo"
)

// Reparent is an event that describes a single step in the reparent process.
type Reparent struct {
	ShardInfo topo.ShardInfo

	OldMaster, NewMaster topo.Tablet

	Status string
}

// UpdateStatus sets a new status and then dispatches the event.
func (r *Reparent) UpdateStatus(status string) {
	r.Status = status

	// make a copy since we're calling Dispatch asynchronously
	ev := *r
	go event.Dispatch(&ev)
}

// Package events defines the structures used for events dispatched from the
// wrangler package.
package events

import (
	"time"

	"github.com/youtube/vitess/go/event"
	"github.com/youtube/vitess/go/vt/topo"
)

// Reparent is an event that describes a single step in the reparent process.
type Reparent struct {
	ShardInfo topo.ShardInfo

	OldMaster, NewMaster topo.Tablet

	Status string

	// eventID is used to group the steps of a single reparent in progress.
	// It is set internally the first time UpdateStatus() is called.
	eventID int64
}

// UpdateStatus sets a new status and then dispatches the event.
func (r *Reparent) UpdateStatus(status string) {
	r.Status = status

	// initialize event ID
	if r.eventID == 0 {
		r.eventID = time.Now().UnixNano()
	}

	// make a copy since we're calling Dispatch asynchronously
	ev := *r
	go event.Dispatch(&ev)
}

Add eventID to Reparent event for grouping.


package urlutil

import (
	"errors"
	"io"
	"net/http"
	"net/url"
	"os"
)

func open(rawurl string) (io.ReadCloser, error) {
	u, err := url.Parse(rawurl)
	if err != nil {
		return nil, err
	}
	if u.Scheme == "file" {
		return os.Open(u.Path)
	}
	if u.Scheme == "http" || u.Scheme == "https" {
		resp, err := http.Get(rawurl)
		if err != nil {
			return nil, err
		}
		if resp.StatusCode != http.StatusOK {
			return nil, errors.New(resp.Status)
		}
		return resp.Body, nil
	}
	return nil, errors.New("unknown scheme: " + u.Scheme)
}

package urlutil

import (
	"errors"
	"io"
	"net/http"
	"net/url"
	"os"
)

func open(rawurl string) (io.ReadCloser, error) {
	u, err := url.Parse(rawurl)
	if err != nil {
		return nil, err
	}
	if u.Scheme == "file" {
		return os.Open(u.Path)
	}
	if u.Scheme == "http" || u.Scheme == "https" {
		resp, err := http.Get(rawurl)
		if err != nil {
			return nil,
				errors.New("error getting: " + rawurl + ": " + err.Error())
		}
		if resp.StatusCode != http.StatusOK {
			return nil,
				errors.New("error getting: " + rawurl + ": " + resp.Status)
		}
		return resp.Body, nil
	}
	return nil, errors.New("unknown scheme: " + u.Scheme)
}

Improve error messages in lib/url/urlutil.Open().


package fs

import (
	"mime"
	"path"
	"strings"
)

// MimeTypeFromName returns a guess at the mime type from the name
func MimeTypeFromName(remote string) (mimeType string) {
	mimeType = mime.TypeByExtension(path.Ext(remote))
	if !strings.ContainsRune(mimeType, '/') {
		mimeType = "application/octet-stream"
	}
	return mimeType
}

// MimeType returns the MimeType from the object, either by calling
// the MimeTyper interface or using MimeTypeFromName
func MimeType(o ObjectInfo) (mimeType string) {
	// Read the MimeType from the optional interface if available
	if do, ok := o.(MimeTyper); ok {
		mimeType = do.MimeType()
		// Debugf(o, "Read MimeType as %q", mimeType)
		if mimeType != "" {
			return mimeType
		}
	}
	return MimeTypeFromName(o.Remote())
}

// MimeTypeDirEntry returns the MimeType of a DirEntry
//
// It returns "inode/directory" for directories, or uses
// MimeType(Object)
func MimeTypeDirEntry(item DirEntry) string {
	switch x := item.(type) {
	case Object:
		return MimeType(x)
	case Directory:
		return "inode/directory"
	}
	return ""
}

Add MimeTypeDirEntry to return the MimeType of a DirEntry


package main

import (
	"fmt"
	"net"

	"github.com/Symantec/Dominator/lib/errors"
)

func findHypervisor(vmIpAddr net.IP) (string, error) {
	if *hypervisorHostname != "" {
		return fmt.Sprintf("%s:%d", *hypervisorHostname, *hypervisorPortNum),
			nil
	} else {
		return "", errors.New("no Hypervisor specified")
	}
}

package main

import (
	"fmt"
	"net"

	"github.com/Symantec/Dominator/lib/errors"
	"github.com/Symantec/Dominator/lib/srpc"
	proto "github.com/Symantec/Dominator/proto/fleetmanager"
)

func findHypervisor(vmIpAddr net.IP) (string, error) {
	if *fleetManagerHostname != "" {
		cm := fmt.Sprintf("%s:%d", *fleetManagerHostname,
			*fleetManagerPortNum)
		client, err := srpc.DialHTTP("tcp", cm, 0)
		if err != nil {
			return "", err
		}
		defer client.Close()
		request := proto.GetHypervisorForVMRequest{vmIpAddr}
		var reply proto.GetHypervisorForVMResponse
		err = client.RequestReply("FleetManager.GetHypervisorForVM", request,
			&reply)
		if err != nil {
			return "", err
		}
		if err := errors.New(reply.Error); err != nil {
			return "", err
		}
		return reply.HypervisorAddress, nil
	} else if *hypervisorHostname != "" {
		return fmt.Sprintf("%s:%d", *hypervisorHostname, *hypervisorPortNum),
			nil
	} else {
		return fmt.Sprintf("localhost:%d", *hypervisorPortNum), nil
	}
}

Support fleet manager in vm-control command.


/*
Copyright 2014 Google Inc. All rights reserved.

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

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

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

package api

import (
	"strings"
)

func IsPullAlways(p PullPolicy) bool {
	// Default to pull always
	if len(p) == 0 {
		return true
	}
	return pullPoliciesEqual(p, PullAlways)
}

func IsPullNever(p PullPolicy) bool {
	return pullPoliciesEqual(p, PullNever)
}

func IsPullIfNotPresent(p PullPolicy) bool {
	return pullPoliciesEqual(p, PullIfNotPresent)
}

func pullPoliciesEqual(p1, p2 PullPolicy) bool {
	return strings.ToLower(string(p1)) == strings.ToLower(string(p2))
}

/*
Copyright 2014 Google Inc. All rights reserved.

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

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

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

package api

import (
	"strings"
)

func IsPullAlways(p PullPolicy) bool {
	return pullPoliciesEqual(p, PullAlways)
}

func IsPullNever(p PullPolicy) bool {
	return pullPoliciesEqual(p, PullNever)
}

func IsPullIfNotPresent(p PullPolicy) bool {
	// Default to pull if not present
	if len(p) == 0 {
		return true
	}
	return pullPoliciesEqual(p, PullIfNotPresent)
}

func pullPoliciesEqual(p1, p2 PullPolicy) bool {
	return strings.ToLower(string(p1)) == strings.ToLower(string(p2))
}

Change the default Pull policy to PullIfNotPresent.


package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/labstack/gommon/log"
	"github.com/scritch007/go-moviename"
)

var debug bool

func init() {
	flag.BoolVar(&debug, "v", false, "Enable debug logs")
}

func main() {
	flag.Parse()
	logger := log.New("cmdLine")
	if debug {
		logger.SetLevel(log.DEBUG)
	}
	mp := moviename.NewMovieParser(logger)
	if len(flag.Args()) != 1 {
		fmt.Printf("Usage: %s filename", os.Args[0])
		os.Exit(1)
	}
	m, err := mp.Parse(flag.Args()[0])
	if err != nil {
		fmt.Printf("%v", err)
		os.Exit(1)
	}
	fmt.Printf("%s (%d) => %s\n", m.Name, m.Year, m.Quality)
}

package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/labstack/gommon/log"
	"github.com/scritch007/go-medianame"
)

var debug bool

func init() {
	flag.BoolVar(&debug, "v", false, "Enable debug logs")
}

func main() {
	flag.Parse()
	logger := log.New("cmdLine")
	if debug {
		logger.SetLevel(log.DEBUG)
	}
	mp := moviename.NewMovieParser(logger)
	if len(flag.Args()) != 1 {
		fmt.Printf("Usage: %s filename", os.Args[0])
		os.Exit(1)
	}
	m, err := mp.Parse(flag.Args()[0])
	if err != nil {
		fmt.Printf("%v", err)
		os.Exit(1)
	}
	fmt.Printf("%s (%d) => %s\n", m.Name, m.Year, m.Quality)
}

Rename to new repo name


package main

import "testing"

func TestEncodeDecode(t *testing.T) {
	dims := []int{3, 2, 4, 17, 26, 15, 1, 2, 1}
	for i := 0; i < 318240; i++ {   // Product of dims
		addr := DecodeIndex(dims, i)
		for j := 0; j < len(dims); j++ {
			if addr[j] >= dims[j] {
				t.Fail()
			}
		}
		if EncodeIndex(dims, addr) != i {
			t.Fail()
		}
	}
}

package main

import "testing"

func TestEncodeDecode(t *testing.T) {
	dims := []int{3, 2, 4, 17, 26, 15, 2, 1, 2, 1}
	var i int32
	for i = 0; i < 636480; i++ { // Product of dims
		addr := DecodeIndex(dims, i)
		for j := 0; j < len(dims); j++ {
			if addr[j] >= dims[j] {
				t.Fail()
			}
		}
		if EncodeIndex(dims, addr) != i {
			t.Fail()
		}
	}
}

Fix test: Add trading dimension.


package nptl

import (
	"fmt"
	"io"

	"github.com/krasin/g3"
	"github.com/krasin/voxel/raster"
	"github.com/krasin/voxel/volume"
)

func Write(w io.Writer, vol volume.Space16, grid raster.Grid) (err error) {
	stepX := (grid.P1[0] - grid.P0[0]) / float64(vol.N())
	stepY := (grid.P1[1] - grid.P0[1]) / float64(vol.N())
	stepZ := (grid.P1[2] - grid.P0[2]) / float64(vol.N())

	vol.MapBoundary(func(node g3.Node) {
		nv := volume.Normal(vol, node)
		if _, err = fmt.Fprintf(w, "%f %f %f %f %f %f\n",
			grid.P0[0]+float64(node[0])*stepX,
			grid.P0[1]+float64(node[1])*stepY,
			grid.P0[2]+float64(node[2])*stepZ,
			nv[0], nv[1], nv[2]); err != nil {
			return
		}
	})
	return
}

package nptl

import (
	"fmt"
	"io"

	"github.com/krasin/g3"
	"github.com/krasin/voxel/volume"
)

func Write(w io.Writer, vol volume.Space16, grid g3.Grid) (err error) {
	vol.MapBoundary(func(node g3.Node) {
		nv := volume.Normal(vol, node)
		cur := grid.At(node)
		if _, err = fmt.Fprintf(w, "%f %f %f %f %f %f\n",
			cur[0], cur[1], cur[2], nv[0], nv[1], nv[2]); err != nil {
			return
		}
	})
	return
}

Convert ntpl.Write to use g3.Grid


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

package signal

import (
	"syscall"
	"testing"
)

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

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

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

package signal

import (
	"syscall"
	"testing"
)

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

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

Use t.Errorf for formatted error output.


package types

//type Config map[string][]map[string]string
type ConfigRecord map[string]string
type Config map[string]ConfigRecord

type BaseRecord struct {
	Title string
	Link string
}

type RecordList []BaseRecord

// Package types provides types for the custom JSON configuration and the
// custom JSON read, watch and book JSON file.
package types

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

// A single record of the configuration file.
type ConfigRecord map[string]string

// A whole configuration file.
type Config map[string]ConfigRecord

// A single base record of the read, watch or book JSON file.
type BaseRecord struct {
	Title string
	Link string
}

// A whole read, watch or book JSON file.
type RecordList []BaseRecord

// Read opens and read a given JSON file into the RecordList.
// It returns nil on success and the error on failure (propagates the error).
func (list *RecordList) Read(file string) error {
	// open JSON file
	readFile, err := os.Open(file)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error while opening %s\n", file)
		return err
	}

	// decode JSON file
	jsonParser := json.NewDecoder(readFile)
	if err = jsonParser.Decode(&list); err != nil {
		fmt.Fprintf(os.Stderr, "Error while parsing %s\n", file)
		readFile.Close()
		return err
	}

	readFile.Close()
	return nil
}

// Write opens and writes the RecordList to a given JSON file.
// It returns nil on success and the error on failure (propagates the error).
func (list *RecordList) Write(file string) error {
	// write back to JSON file
	readFile, err := os.Create(file)
	jsonWriter := json.NewEncoder(readFile)
	if err = jsonWriter.Encode(&list); err != nil {
		fmt.Fprintf(os.Stderr, "Error while writing back %s\n", file)
		readFile.Close()
		return err
	}

	readFile.Close()
	return nil
}

Add RecordList Read, Write and documentation


package main

import (
	"github.com/albertyw/reaction-pics/server"
	"github.com/albertyw/reaction-pics/tumblr"
	_ "github.com/joho/godotenv/autoload"
	"os"
	"strings"
)

const readPostsFromTumblrEnv = "READ_POSTS_FROM_TUMBLR"

func getReadPostsFromTumblr() bool {
	readPostsEnv := os.Getenv(readPostsFromTumblrEnv)
	if strings.ToLower(readPostsEnv) == "true" {
		return true
	}
	return false
}

func main() {
	readPosts := getReadPostsFromTumblr()
	posts := tumblr.GetPosts(readPosts)
	tumblr.WritePostsToCSV(posts)
	server.Run(posts)
}

package main

import (
	"github.com/albertyw/reaction-pics/server"
	"github.com/albertyw/reaction-pics/tumblr"
	_ "github.com/joho/godotenv/autoload"
	"os"
	"strings"
)

const readPostsFromTumblrEnv = "READ_POSTS_FROM_TUMBLR"

func getReadPostsFromTumblr() bool {
	readPostsEnv := os.Getenv(readPostsFromTumblrEnv)
	if strings.ToLower(readPostsEnv) == "true" {
		return true
	}
	return false
}

func main() {
	readPosts := getReadPostsFromTumblr()
	posts := tumblr.GetPosts(readPosts)
	go tumblr.WritePostsToCSV(posts)
	server.Run(posts)
}

Make WritePostsToCSV run in a goroutine


// Copyright 2015 Reed O'Brien <reed@reedobrien.com>.
// All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

package main

import (
	"fmt"
)

func main() {
	fmt.Print("code appears here")
}

// Copyright 2015 Reed O'Brien <reed@reedobrien.com>.
// All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"time"
)

var (
	err    error
	secret string // The hex or base32 secret
	// otp string 	// If a value is supplied for varification

	//// Flags
	// common flags add in flagParse method
	// base32 = flag.Bool("b", false, "Use base32 encoding instead of hex")
	// digits = flag.Int("d", 6, "The number of digits in the OTP")
	// window = flag.Int("w", 1, "Window of counter values to test when validating OTPs")

	hFlag   = flag.NewFlagSet("hotp", flag.ContinueOnError)
	counter = hFlag.Int64("c", 0, "HOTP counter Value")

	tFlag = flag.NewFlagSet("totp", flag.ContinueOnError)
	now   = tFlag.Int64("N", time.Now().UTC().Unix(), "Use this time as current time for TOTP")
	step  = tFlag.Int64("s", 30, "The time-step duration")
	epoch = tFlag.String("S", "1970−01−01 00:00:00 UTC", "When to start counting time-steps for TOTP")
)

func main() {
	fmt.Print("code appears here")
}

Add initial whack at flags.


package main

import (
	"fmt"
	"github.com/nitishparkar/muffliato/crawler"
	"io/ioutil"
	"strings"
)

const sitesFile string = "sites.txt"

func main() {
	data, err := ioutil.ReadFile(sitesFile)

	if err != nil {
		panic(err)
	}

	sites := strings.Split(string(data), "\n")

	done := make(chan bool)

	for _, site := range sites {
		go func(site string) {
			crawler := crawler.NewCrawler(site)
			crawler.Crawl()

			done <- true
		}(site)
	}

	<-done

	fmt.Println("Exiting")
}

package main

import (
	"fmt"
	"github.com/nitishparkar/muffliato/crawler"
	"io/ioutil"
	"strings"
)

const sitesFile string = "sites.txt"

func main() {
	data, err := ioutil.ReadFile(sitesFile)

	if err != nil {
		panic(err)
	}

	sites := strings.Split(string(data), "\n")

	validSites := make([]string, 0)

	for _, site := range sites {
		t := strings.TrimSpace(site)
		if t != "" {
			validSites = append(validSites, t)
		}
	}

	done := make(chan bool)

	for _, site := range validSites {
		go func(site string) {
			crawler := crawler.NewCrawler(site)
			crawler.Crawl()

			done <- true
		}(site)
	}

	<-done

	fmt.Println("Exiting")
}

Handle empty strings in sites file


package main

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

	"github.com/rtwire/mock/service"
)

var (
	port = flag.Int("port", 8085, "service port number")
)

func main() {
	flag.Parse()

	addr := ":" + strconv.Itoa(*port)

	log.Printf("Mock RTWire service running on port %d.", *port)
	log.Fatal(http.ListenAndServe(addr, service.New()))
}

package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"strconv"

	"github.com/rtwire/mock/service"
)

var (
	port = flag.Int("port", 8085, "service port number")
)

func main() {
	flag.Parse()

	url := fmt.Sprintf("http://localhost:%d/v1/mainnet/", *port)
	log.Printf("RTWire service running at %s.", url)

	addr := ":" + strconv.Itoa(*port)
	log.Fatal(http.ListenAndServe(addr, service.New()))
}

Improve start up logging message.


// Package public adds some public routes that can be used to give information
// to anonymous users, or to the not yet authentified cozy owner on its login
// page.
package public

import (
	"net/http"
	"time"

	"github.com/cozy/cozy-stack/pkg/statik/fs"
	"github.com/cozy/cozy-stack/web/middlewares"
	"github.com/cozy/cozy-stack/web/statik"
	"github.com/cozy/echo"
)

// Avatar returns the default avatar currently.
func Avatar(c echo.Context) error {
	f, ok := fs.Get("/images/default-avatar.png", "")
	if !ok {
		return echo.NewHTTPError(http.StatusNotFound, "Page not found")
	}
	handler := statik.NewHandler()
	handler.ServeFile(c.Response(), c.Request(), f, true)
	return nil
}

// Routes sets the routing for the public service
func Routes(router *echo.Group) {
	cacheControl := middlewares.CacheControl(middlewares.CacheOptions{
		MaxAge: 24 * time.Hour,
	})
	router.GET("/avatar", Avatar, cacheControl)
}

// Package public adds some public routes that can be used to give information
// to anonymous users, or to the not yet authentified cozy owner on its login
// page.
package public

import (
	"net/http"
	"time"

	"github.com/cozy/cozy-stack/pkg/statik/fs"
	"github.com/cozy/cozy-stack/web/middlewares"
	"github.com/cozy/cozy-stack/web/statik"
	"github.com/cozy/echo"
)

// Avatar returns the default avatar currently.
func Avatar(c echo.Context) error {
	inst := middlewares.GetInstance(c)
	f, ok := fs.Get("/images/default-avatar.png", inst.ContextName)
	if !ok {
		f, ok = fs.Get("/images/default-avatar.png", "")
		if !ok {
			return echo.NewHTTPError(http.StatusNotFound, "Page not found")
		}
	}
	handler := statik.NewHandler()
	handler.ServeFile(c.Response(), c.Request(), f, true)
	return nil
}

// Routes sets the routing for the public service
func Routes(router *echo.Group) {
	cacheControl := middlewares.CacheControl(middlewares.CacheOptions{
		MaxAge: 24 * time.Hour,
	})
	router.GET("/avatar", Avatar, cacheControl, middlewares.NeedInstance)
}

Allow to customize the default avatar by context


// Copyright 2015 Alex Browne.  All rights reserved.
// Use of this source code is governed by the MIT
// license, which can be found in the LICENSE file.

// Package zoom A blazing-fast datastore and querying engine for
// Go built on Redis. It supports models of any arbitrary struct
// type and provides basic querying functionality. It also supports
// atomic transactions, lua scripts, and running Redis commands
// directly if needed.
package zoom

// Copyright 2015 Alex Browne.  All rights reserved.
// Use of this source code is governed by the MIT
// license, which can be found in the LICENSE file.

// Package zoom is a blazing-fast datastore and querying engine for
// Go built on Redis. It supports models of any arbitrary struct
// type and provides basic querying functionality. It also supports
// atomic transactions, lua scripts, and running Redis commands
// directly if needed.
package zoom

Fix typo in doc comment


/* Copyright 2019 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy 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 gonids

func FuzzParseRule(data []byte) int {
	r, err := ParseRule(string(data))
	if err != nil {
		// Handle parse error
		return 0
	}
	r.OptimizeHTTP()
	return 1
}

/* Copyright 2019 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy 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 gonids

// FuzzParseRule is used by OSS-Fuzz to fuzz the library.
func FuzzParseRule(data []byte) int {
	r, err := ParseRule(string(data))
	if err != nil {
		// Handle parse error
		return 0
	}
	r.OptimizeHTTP()
	return 1
}

Add comment for exported function.


package main

import "net/http"

// Middleware to add HSTS header
func hstsHandler(h http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Strict-Transport-Security", "max-age=31536000; preload")
        h.ServeHTTP(w, r)
    })
}

package main

import "net/http"

// Middleware to add HSTS header
func hstsHandler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
		h.ServeHTTP(w, r)
	})
}

Add sub domain HTTPS enhancement


// Copyright © 2015 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

package components

import (
	"github.com/thethingsnetwork/core"
	//"github.com/thethingsnetwork/core/lorawan"
	"fmt"
	"github.com/thethingsnetwork/core/semtech"
)

var ErrImpossibleConversion = fmt.Errorf("The given packet can't be converted")

func ConvertSemtechPacket(p semtech.Packet) (core.Packet, error) {
	return core.Packet{}, nil
}

// Copyright © 2015 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

package components

import (
	"github.com/thethingsnetwork/core"
	//"github.com/thethingsnetwork/core/lorawan"
	"fmt"
	"github.com/thethingsnetwork/core/semtech"
)

var ErrImpossibleConversion = fmt.Errorf("The given packet can't be converted")

func ConvertRXPK(p semtech.RXPK) (core.Packet, error) {
	return core.Packet{}, nil
}

Change signature of convert method


package client

import (
    "net/http"
    "golang.org/x/oauth2"
)

type authCodeFn func(string) func() string

func NewOauthClient(clientId, clientSecret, tokenFile string, authFn authCodeFn) (*http.Client, error) {
    conf := &oauth2.Config{
        ClientID:     clientId,
        ClientSecret: clientSecret,
        Scopes:       []string{"https://www.googleapis.com/auth/drive"},
        RedirectURL:  "urn:ietf:wg:oauth:2.0:oob",
        Endpoint: oauth2.Endpoint{
            AuthURL:  "https://accounts.google.com/o/oauth2/auth",
            TokenURL: "https://accounts.google.com/o/oauth2/token",
        },
    }

    // Read cached token
    token, exists, err := ReadToken(tokenFile)
    if err != nil {
        return nil, err
    }

    // Request auth code if token does not exist
    if !exists {
        authUrl := conf.AuthCodeURL("state", oauth2.AccessTypeOffline)
        authCode := authFn(authUrl)()
        token, err = conf.Exchange(oauth2.NoContext, authCode)
    }

    return oauth2.NewClient(
        oauth2.NoContext,
        FileSource(tokenFile, token, conf),
    ), nil
}

package client

import (
    "net/http"
    "golang.org/x/oauth2"
)

type authCodeFn func(string) func() string

func NewOauthClient(clientId, clientSecret, tokenFile string, authFn authCodeFn) (*http.Client, error) {
    conf := &oauth2.Config{
        ClientID:     clientId,
        ClientSecret: clientSecret,
        Scopes:       []string{"https://www.googleapis.com/auth/drive"},
        RedirectURL:  "urn:ietf:wg:oauth:2.0:oob",
        Endpoint: oauth2.Endpoint{
            AuthURL:  "https://accounts.google.com/o/oauth2/auth",
            TokenURL: "https://accounts.google.com/o/oauth2/token",
        },
    }

    // Read cached token
    token, exists, err := ReadToken(tokenFile)
    if err != nil {
        return nil, err
    }

    // Require auth code if token file does not exist
    // or refresh token is missing
    if !exists || token.RefreshToken == "" {
        authUrl := conf.AuthCodeURL("state", oauth2.AccessTypeOffline)
        authCode := authFn(authUrl)()
        token, err = conf.Exchange(oauth2.NoContext, authCode)
    }

    return oauth2.NewClient(
        oauth2.NoContext,
        FileSource(tokenFile, token, conf),
    ), nil
}

Check for missing refresh token


package appui

import (
	"context"

	"github.com/docker/docker/api/types/events"
	"github.com/moncho/dry/docker"
	"github.com/moncho/dry/ui/termui"
)

//RegisterWidget registers the given widget for updates from the given source
func RegisterWidget(source docker.SourceType, w termui.Widget) {
	docker.GlobalRegistry.Register(
		source,
		func(ctx context.Context, message events.Message) error {
			return w.Unmount()
		})
}

package appui

import (
	"context"
	"time"

	"github.com/docker/docker/api/types/events"
	"github.com/moncho/dry/docker"
	"github.com/moncho/dry/ui/termui"
)

var timeBetweenRefresh = 500 * time.Millisecond

//RegisterWidget registers the given widget for updates from the given source
func RegisterWidget(source docker.SourceType, w termui.Widget) {
	last := time.Now()
	docker.GlobalRegistry.Register(
		source,
		func(ctx context.Context, message events.Message) error {
			if time.Now().Sub(last) > timeBetweenRefresh {
				last = time.Now()

				return w.Unmount()
			}
			return nil
		})
}

Refresh only if a certain time has passed since the previous event


package template

import (
	"errors"
	"io/ioutil"
	"text/template"
)

const defaultTemplate = `{{ range . }}
{{ . }}
{{ end }}
`

// -------------------------------------------------------
// Parser.
// -------------------------------------------------------

// Parse a template (and select the appropriate engine based on the file's extension).
func Parse(templateFilename string) (*template.Template, error) {

	// If not available, use the default template.
	if templateFilename == "" {
		return useDefaultTemplate(), nil
	}

	content, err := ioutil.ReadFile(templateFilename)
	if err != nil {
		return nil, errors.New("cannot read the template")
	}

	return useTextTemplate(string(content))
}

func useTextTemplate(content string) (*template.Template, error) {
	t, err := template.New("").Parse(content)
	if err != nil {
		return nil, errors.New("invalid Text/Markdown template file")
	}

	return t, nil
}

func useDefaultTemplate() *template.Template {
	return template.Must(
		template.New("").Parse(defaultTemplate),
	)
}

package template

import (
	"errors"
	"io/ioutil"
	"text/template"
)

const defaultTemplate = "{{ range . }}{{ . }}\n\n{{ end }}"

// -------------------------------------------------------
// Parser.
// -------------------------------------------------------

// Parse a template (and select the appropriate engine based on the file's extension).
func Parse(templateFilename string) (*template.Template, error) {

	// If not available, use the default template.
	if templateFilename == "" {
		return useDefaultTemplate(), nil
	}

	content, err := ioutil.ReadFile(templateFilename)
	if err != nil {
		return nil, errors.New("cannot read the template")
	}

	return useTextTemplate(string(content))
}

func useTextTemplate(content string) (*template.Template, error) {
	t, err := template.New("").Parse(content)
	if err != nil {
		return nil, errors.New("invalid Text/Markdown template file")
	}

	return t, nil
}

func useDefaultTemplate() *template.Template {
	return template.Must(
		template.New("").Parse(defaultTemplate),
	)
}

Use normal string to encapsulate the default tpl


package main

import "fmt"
import "io/ioutil"
import "os"

func main() {
	fmt.Println("Advent of code: Golang\nTask 8")

	PrintCurrentDir()

	file, err := ioutil.ReadFile("../input.txt")
	if err != nil {
		fmt.Println(err)
		return
	}

	content := string(file)
	fmt.Println(content)
}

func PrintCurrentDir() {
	pwd, err := os.Getwd()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println("current dir: " + pwd)
}

package main

import "fmt"
import "io/ioutil"
import "os"

func main() {
	fmt.Println("Advent of code: Golang\nTask 8")

	PrintCurrentDir()

	file, err := ioutil.ReadFile("../input.txt")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	content := string(file)
	fmt.Println(content)
}

func PrintCurrentDir() {
	pwd, err := os.Getwd()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println("current dir: " + pwd)
}

Exit in more cruel form


package main

import (
	"os"
	"path/filepath"
)

// goGenerate executes the command "go generate"
func goGenerate() {
	cmd("go", "generate").Run()
}

// goBuild executes the command "go build" for the desired
// target OS and architecture, and writes the generated
// executable to the 'outDir' directory.
func goBuild(name string, version string, goos string, goarch string) {
	os.Setenv("goos", goos)
	os.Setenv("goarch", goarch)

	out := distPath(name, version, goos, goarch)
	cmd("go", "build", "-o", out, "-ldflags", "-X main.version="+version).Run()
}

// distPath constructs a file path for a given target
func distPath(name string, version string, os string, arch string) string {
	return filepath.Join("dist", buildName(name, version, os, arch), name+exeSuffix())
}

// exeSuffix returns ".exe" if the GOOS
// environment variable is set to
// "windows".
func exeSuffix() string {
	if os.Getenv("GOOS") == "windows" {
		return ".exe"
	}
	return ""
}

// goOS returns the value of GOOS
func goOS() string {
	return cmd("go", "env", "GOOS").OutputLine()
}

// goArch returns the value of GOARCH
func goArch() string {
	return cmd("go", "env", "GOARCH").OutputLine()
}

package main

import (
	"os"
	"path/filepath"
)

// goGenerate executes the command "go generate"
func goGenerate() {
	cmd("go", "generate").Run()
}

// goBuild executes the command "go build" for the desired
// target OS and architecture, and writes the generated
// executable to the 'outDir' directory.
func goBuild(name string, version string, goos string, goarch string) {
	os.Setenv("GOOS", goos)
	os.Setenv("GOARCH", goarch)

	out := distPath(name, version, goos, goarch)
	cmd("go", "build", "-o", out, "-ldflags", "-X main.version="+version).Run()
}

// distPath constructs a file path for a given target
func distPath(name string, version string, os string, arch string) string {
	return filepath.Join("dist", buildName(name, version, os, arch), name+exeSuffix())
}

// exeSuffix returns ".exe" if the GOOS
// environment variable is set to
// "windows".
func exeSuffix() string {
	if goOS() == "windows" {
		return ".exe"
	}
	return ""
}

// goOS returns the value of GOOS
func goOS() string {
	return cmd("go", "env", "GOOS").OutputLine()
}

// goArch returns the value of GOARCH
func goArch() string {
	return cmd("go", "env", "GOARCH").OutputLine()
}

Fix getting and setting Go env vars during build


package main

import (
	"fmt"
	"math/rand"
	"strings"
	"time"
)

func mesosTestProvider(taskId string) (RunningTask, error) {
	parts := strings.Split(taskId, ".")
	if len(parts) == 2 && parts[0] != "" {
		return RunningTask{
			Id: taskId,
			Name: parts[0],
			StartTime: time.Now(),
		}, nil
	} else {
		return RunningTask{
			Id: fmt.Sprintf("%s.%d", parts[0], rand.Int()),
			Name: parts[0],
			StartTime: time.Now(),
		}, nil
	}
}

package main

import (
	"fmt"
	"math/rand"
	"strings"
	"time"
)

func mesosTestProvider(taskId string) (RunningTask, error) {
	parts := strings.Split(taskId, ".")
	if len(parts) == 2 && parts[1] != "" {
		return RunningTask{
			Id:        taskId,
			Name:      parts[0],
			StartTime: time.Now(),
		}, nil
	} else {
		return RunningTask{
			Id:        fmt.Sprintf("%s.%d", parts[0], rand.Int()),
			Name:      parts[0],
			StartTime: time.Now(),
		}, nil
	}
}

Fix test provider, go fmt


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

package main

import (
	"fmt"
	"net/http"
)

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

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

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

func init() {

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

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

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

package main

import (
	"fmt"
	"net/http"
)

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

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

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

func init() {

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

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

Correct version for deploy to GAE


package wl_integration_test

import (
	"github.com/nu7hatch/gouuid"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/robdimsdale/wl"
)

var _ = Describe("basic user functionality", func() {
	It("can update the user's name", func() {
		By("Creating a new random user name")
		uuid1, err := uuid.NewV4()
		Expect(err).NotTo(HaveOccurred())
		newUserName := uuid1.String()

		By("Getting user")
		var user wl.User
		Eventually(func() error {
			user, err = client.User()
			return err
		}).Should(Succeed())

		By("Updating user")
		var updatedUser wl.User
		user.Name = "test-" + newUserName
		Eventually(func() error {
			updatedUser, err = client.UpdateUser(user)
			return err
		}).Should(Succeed())

		Expect(updatedUser.ID).To(Equal(user.ID))
	})
})

package wl_integration_test

import (
	"github.com/nu7hatch/gouuid"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/robdimsdale/wl"
)

var _ = Describe("basic user functionality", func() {
	It("can update the user's name", func() {
		By("Creating a new random user name")
		uuid1, err := uuid.NewV4()
		Expect(err).NotTo(HaveOccurred())
		newUserName := uuid1.String()

		By("Getting and updating user")
		var user wl.User
		var updatedUser wl.User
		Eventually(func() error {
			user, err = client.User()
			user.Name = "test-" + newUserName
			updatedUser, err = client.UpdateUser(user)
			return err
		}).Should(Succeed())

		Expect(updatedUser.ID).To(Equal(user.ID))
	})
})

Make user integration test more resilient to 409 errors.


//
// Copyright (c) 2017 Mainflux
//
// SPDX-License-Identifier: Apache-2.0
//

package export

// Message - Encapsulating / wrapper message object that contains Event
// to be exported and the client export registration details
type Message struct {
	Registration Registration
	Evt          Event
}

// Event - packet of Readings
type Event struct {
	Pushed   int64     `json:"pushed"`
	Device   string    `json:"device,omitempty"`
	Readings []Reading `json:"readings,omitempty"`
	Created  int64     `json:"created"`
	Modified int64     `json:"modified"`
	Origin   int64     `json:"origin"`
}

// Reading - Sensor measurement
type Reading struct {
	Pushed   int64  `json:"pushed"`
	Name     string `json:"name,omitempty"`
	Value    string `json:"value,omitempty"`
	Device   string `json:"device,omitempty"`
	Created  int64  `json:"created"`
	Modified int64  `json:"modified"`
	Origin   int64  `json:"origin"`
}

//
// Copyright (c) 2017 Mainflux
//
// SPDX-License-Identifier: Apache-2.0
//

package export

// Message - Encapsulating / wrapper message object that contains Event
// to be exported and the client export registration details
type Message struct {
	Registration Registration
	Evt          Event
}

// Event - packet of Readings
type Event struct {
	ID       string    `json:"id,omitempty"`
	Pushed   int64     `json:"pushed"`
	Device   string    `json:"device,omitempty"`
	Readings []Reading `json:"readings,omitempty"`
	Created  int64     `json:"created"`
	Modified int64     `json:"modified"`
	Origin   int64     `json:"origin"`
}

// Reading - Sensor measurement
type Reading struct {
	ID       string `json:"id,omitempty"`
	Pushed   int64  `json:"pushed"`
	Name     string `json:"name,omitempty"`
	Value    string `json:"value,omitempty"`
	Device   string `json:"device,omitempty"`
	Created  int64  `json:"created"`
	Modified int64  `json:"modified"`
	Origin   int64  `json:"origin"`
}

Add missing id fields in readings and events


package main

import (
	"time"

	"github.com/prometheus/client_golang/prometheus"
)

var (
	gaugeTotal = prometheus.NewGauge(prometheus.GaugeOpts{
		Name:      "total",
		Namespace: "scan",
		Subsystem: "ips",
		Help:      "Total IPs found",
	})

	gaugeLatest = prometheus.NewGauge(prometheus.GaugeOpts{
		Name:      "latest",
		Namespace: "scan",
		Subsystem: "ips",
		Help:      "Latest IPs found",
	})

	gaugeNew = prometheus.NewGauge(prometheus.GaugeOpts{
		Name:      "new",
		Namespace: "scan",
		Subsystem: "ips",
		Help:      "New IPs found",
	})
)

func init() {
	prometheus.MustRegister(gaugeTotal)
	prometheus.MustRegister(gaugeLatest)
	prometheus.MustRegister(gaugeNew)
}

func metrics() {
	for {
		results, err := resultData("", "", "")
		if err == nil {
			gaugeTotal.Set(float64(results.Total))
			gaugeLatest.Set(float64(results.Latest))
			gaugeNew.Set(float64(results.New))
		}
		time.Sleep(1 * time.Minute)
	}
}

package main

import (
	"time"

	"github.com/prometheus/client_golang/prometheus"
)

var (
	gaugeTotal = prometheus.NewGauge(prometheus.GaugeOpts{
		Name:      "total",
		Namespace: "scan",
		Subsystem: "ips",
		Help:      "Total IPs found",
	})

	gaugeLatest = prometheus.NewGauge(prometheus.GaugeOpts{
		Name:      "latest",
		Namespace: "scan",
		Subsystem: "ips",
		Help:      "Latest IPs found",
	})

	gaugeNew = prometheus.NewGauge(prometheus.GaugeOpts{
		Name:      "new",
		Namespace: "scan",
		Subsystem: "ips",
		Help:      "New IPs found",
	})

	gaugeJobs = prometheus.NewGaugeVec(
		prometheus.GaugeOpts{
			Name:      "job",
			Namespace: "scan",
			Help:      "Number of IPs found in each each job, with submitted and received times",
		},
		[]string{"id", "submitted", "received"})
)

func init() {
	prometheus.MustRegister(gaugeTotal)
	prometheus.MustRegister(gaugeLatest)
	prometheus.MustRegister(gaugeNew)
	prometheus.MustRegister(gaugeJobs)
}

func metrics() {
	for {
		results, err := resultData("", "", "")
		if err == nil {
			gaugeTotal.Set(float64(results.Total))
			gaugeLatest.Set(float64(results.Latest))
			gaugeNew.Set(float64(results.New))
		}
		time.Sleep(1 * time.Minute)
	}
}

Add a metric for jobs


package sanntid

type Line struct {
	Name        string
	Destination string
}

type Arrival struct {
	Line                Line
	ExpectedArrivalTime string
	Platform            string
}

func GetArrivals(locationId int) ([]Arrival, error) {
	var arrivals []Arrival

	data, err := requestArrivalData(locationId)

	if err == nil {
		for i, j := 0, 0; i < len(data); i, j = i+1, j+1 {
			line := Line{
				data[i].MonitoredVehicleJourney.PublishedLineName,
				data[i].MonitoredVehicleJourney.DestinationName,
			}
			arrival := Arrival{
				line,
				data[i].MonitoredVehicleJourney.MonitoredCall.ExpectedArrivalTime,
				data[i].MonitoredVehicleJourney.MonitoredCall.DeparturePlatformName,
			}

			arrivals = append(arrivals, arrival)
		}
	}

	return arrivals, err
}

package sanntid

type Line struct {
	Name        string
	Destination string
}

type Arrival struct {
	Line                Line
	ExpectedArrivalTime string
	Platform            string
}

func GetArrivals(locationId int) ([]Arrival, error) {
	var arrivals []Arrival

	data, err := requestArrivalData(locationId)

	if err == nil {
		for i := 0; i < len(data); i++ {
			line := Line{
				data[i].MonitoredVehicleJourney.PublishedLineName,
				data[i].MonitoredVehicleJourney.DestinationName,
			}
			arrival := Arrival{
				line,
				data[i].MonitoredVehicleJourney.MonitoredCall.ExpectedArrivalTime,
				data[i].MonitoredVehicleJourney.MonitoredCall.DeparturePlatformName,
			}

			arrivals = append(arrivals, arrival)
		}
	}

	return arrivals, err
}

Remove unused variable from data processing loop


package auth

import (
	"net/http"
)

const CookieName = "ATC-Authorization"

type CookieSetHandler struct {
	Handler http.Handler
}

func (handler CookieSetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	cookie, err := r.Cookie(CookieName)
	if err == nil && r.Header.Get("Authorization") == "" {
		r.Header.Set("Authorization", cookie.Value)
	}

	handler.Handler.ServeHTTP(w, r)
}

Add X- headers for security


package gstrings

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

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

	assert.Equal(5, Length("hello"))
}

package gstrings

import (
	"fmt"
	"github.com/wallclockbuilder/testify/assert"
	"testing"
)

func ExampleLength(){
	fmt.Println(Length("hello"))
	// Output: 5
}

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

	assert.Equal(5, Length("hello"))
}

Add example to docs for Length


package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
	"time"
)

func main() {
	start := time.Now()
	ch := make(chan string)
	for _, url := range os.Args[1:] {
		if !strings.HasPrefix(url, "http://") {
			url = "http://" + url
		}
		go fetch(url, ch)
	}
	for range os.Args[1:] {
		fmt.Println(<-ch)
	}
	fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
}

func fetch(url string, ch chan<- string) {
	start := time.Now()
	resp, err := http.Get(url)
	if err != nil {
		ch <- fmt.Sprint(err)
		return
	}
	nbytes, err := io.Copy(ioutil.Discard, resp.Body)
	resp.Body.Close()
	if err != nil {
		ch <- fmt.Sprintf("while reading %s: %v", url, err)
		return
	}
	secs := time.Since(start).Seconds()
	ch <- fmt.Sprintf("%.2fs  %7d  %s", secs, nbytes, url)
}

package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
	"time"
)

func main() {
	start := time.Now()
	ch := make(chan string)
	for _, url := range os.Args[1:] {
		if !strings.HasPrefix(url, "http://") {
			url = "http://" + url
		}
		go fetch(url, ch)
	}
	for range os.Args[1:] {
		fmt.Println(<-ch)
	}
	fmt.Printf("%.2fs elapsed\n", time.Since(start).Seconds())
}

func fetch(url string, ch chan<- string) {
	ch <- fmt.Sprintf("Fetching %s...", url)
	start := time.Now()
	resp, err := http.Get(url)
	if err != nil {
		ch <- fmt.Sprint(err)
		return
	}
	nbytes, err := io.Copy(ioutil.Discard, resp.Body)
	resp.Body.Close()
	if err != nil {
		ch <- fmt.Sprintf("while reading %s: %v", url, err)
		return
	}
	secs := time.Since(start).Seconds()
	ch <- fmt.Sprintf("%.2fs  %7d  %s", secs, nbytes, url)
}

Send start message to channel.


package daemon

import (
	"fmt"

	"github.com/docker/docker/container"
	"github.com/docker/docker/libcontainerd"
)

func (daemon *Daemon) getLibcontainerdCreateOptions(container *container.Container) (*[]libcontainerd.CreateOption, error) {
	createOptions := []libcontainerd.CreateOption{}

	rt := daemon.configStore.GetRuntime(container.HostConfig.Runtime)
	if rt == nil {
		return nil, fmt.Errorf("No such runtime '%s'", container.HostConfig.Runtime)
	}
	createOptions = append(createOptions, libcontainerd.WithRuntime(rt.Path, rt.Args))

	return &createOptions, nil
}

package daemon

import (
	"fmt"

	"github.com/docker/docker/container"
	"github.com/docker/docker/libcontainerd"
	"github.com/docker/engine-api/types"
)

func (daemon *Daemon) getLibcontainerdCreateOptions(container *container.Container) (*[]libcontainerd.CreateOption, error) {
	createOptions := []libcontainerd.CreateOption{}

	// Ensure a runtime has been assigned to this container
	if container.HostConfig.Runtime == "" {
		container.HostConfig.Runtime = types.DefaultRuntimeName
		container.ToDisk()
	}

	rt := daemon.configStore.GetRuntime(container.HostConfig.Runtime)
	if rt == nil {
		return nil, fmt.Errorf("no such runtime '%s'", container.HostConfig.Runtime)
	}
	createOptions = append(createOptions, libcontainerd.WithRuntime(rt.Path, rt.Args))

	return &createOptions, nil
}

Fix missing container runtime on upgrade


package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/lxc/lxd/client"
)

func cmdShutdown(args *Args) error {
	connArgs := &lxd.ConnectionArgs{
		SkipGetServer: true,
	}
	c, err := lxd.ConnectLXDUnix("", connArgs)
	if err != nil {
		return err
	}

	_, _, err = c.RawQuery("PUT", "/internal/shutdown", nil, "")
	if err != nil && strings.HasSuffix(err.Error(), ": EOF") {
		// NOTE: if we got an EOF error here it means that the daemon
		// has shutdown so quickly that it already closed the unix
		// socket. We consider the daemon dead in this case.
		return err
	}

	chMonitor := make(chan bool, 1)
	go func() {
		monitor, err := c.GetEvents()
		if err != nil {
			close(chMonitor)
			return
		}

		monitor.Wait()
		close(chMonitor)
	}()

	if args.Timeout > 0 {
		select {
		case <-chMonitor:
			break
		case <-time.After(time.Second * time.Duration(args.Timeout)):
			return fmt.Errorf("LXD still running after %ds timeout.", args.Timeout)
		}
	} else {
		<-chMonitor
	}

	return nil
}

package main

import (
	"fmt"
	"strings"
	"time"

	"github.com/lxc/lxd/client"
)

func cmdShutdown(args *Args) error {
	connArgs := &lxd.ConnectionArgs{
		SkipGetServer: true,
	}
	c, err := lxd.ConnectLXDUnix("", connArgs)
	if err != nil {
		return err
	}

	_, _, err = c.RawQuery("PUT", "/internal/shutdown", nil, "")
	if err != nil && !strings.HasSuffix(err.Error(), ": EOF") {
		// NOTE: if we got an EOF error here it means that the daemon
		// has shutdown so quickly that it already closed the unix
		// socket. We consider the daemon dead in this case.
		return err
	}

	chMonitor := make(chan bool, 1)
	go func() {
		monitor, err := c.GetEvents()
		if err != nil {
			close(chMonitor)
			return
		}

		monitor.Wait()
		close(chMonitor)
	}()

	if args.Timeout > 0 {
		select {
		case <-chMonitor:
			break
		case <-time.After(time.Second * time.Duration(args.Timeout)):
			return fmt.Errorf("LXD still running after %ds timeout.", args.Timeout)
		}
	} else {
		<-chMonitor
	}

	return nil
}

Fix typo in error handling


// +build windows

package util

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"github.com/jcelliott/lumber"
	"github.com/nanobox-io/nanobox-golang-stylish"
)

// PrivilegeExec runs a command, but assumes your already running as adminsitrator
func PrivilegeExec(command, msg string) {
	fmt.Printf(stylish.Bullet(msg))

	//
	cmd := exec.Command(os.Args[0], strings.Split(command, " ")...)

	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	// run command
	if err := cmd.Run(); err != nil {
		lumber.Fatal("[commands/commands_windows]", err.Error())
	}
}

// +build windows

package util

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

// PrivilegeExec will run the requested command
func PrivilegeExec(command string) error {

	// Windows is tricky. Unfortunately we can't just prefix the command with sudo
	// Instead, we have to use powershell to create a profile, and then create
	// a process within powershell requesting Administrative permissions.
	//
	// Generating the command is complicated.
	// The following resources were used as documentation for the logic below:
	// https://msdn.microsoft.com/en-us/powershell/scripting/core-powershell/console/powershell.exe-command-line-help
	// http://ss64.com/ps/start-process.html
	// http://www.howtogeek.com/204088/how-to-use-a-batch-file-to-make-powershell-scripts-easier-to-run/

	// The process is constructed by passing the executable as a single argument
	// and the argument list as a space-delimited string in a single argument.
	//
	// Since the command is provided as a space-delimited string containing both
	// the executable and the argument list (just like a command would be entered
	// on the command prompt), we need to pop off the executable.

	// split the command into pieces using a space delimiter
	parts := strings.Split(command, " ")

	// extract the executable (the first item)
	executable := parts[0]

	// assemble the argument list from the rest of the parts
	arguments := strings.Join(parts[1:], " ")

	// generate the powershell process
	process := fmt.Sprintf("\"& {Start-Process %s -ArgumentList '%s' -Verb RunAs}\"", executable, arguments)

	// now we can generate a command to exec
	cmd := exec.Command("PowerShell.exe", "-NoProfile", "-Command", process)

	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	// run command
	if err := cmd.Run(); err != nil {
		return err
	}

	return nil
}

Add privilege exec for windows. Needs tested


// Copyright 2015 Alex Browne and Soroush Pour.
// Allrights reserved. Use of this source code is
// governed by the MIT license, which can be found
// in the LICENSE file.

package router_test

import (
	"fmt"
	"github.com/go-humble/router"
)

func ExampleRoutes() {
	// Create a new Router object
	r := router.New()
	// Use HandleFunc to add routes.
	r.HandleFunc("/greet/{name}", func(params map[string]string) {
		// The handler for this route simply grabs the name parameter
		// from the map of params and says hello.
		fmt.Printf("Hello, %s\n", params["name"])
	})
	// You must call Start in order to start listening for changes
	// in the url and trigger the appropriate handler function.
	r.Start()
}

// Copyright 2015 Alex Browne and Soroush Pour.
// Allrights reserved. Use of this source code is
// governed by the MIT license, which can be found
// in the LICENSE file.

package router_test

import (
	"fmt"
	"github.com/go-humble/router"
)

func ExampleRouter_HandleFunc() {
	// Create a new Router object
	r := router.New()
	// Use HandleFunc to add routes.
	r.HandleFunc("/greet/{name}", func(params map[string]string) {
		// The handler for this route simply grabs the name parameter
		// from the map of params and says hello.
		fmt.Printf("Hello, %s\n", params["name"])
	})
	// You must call Start in order to start listening for changes
	// in the url and trigger the appropriate handler function.
	r.Start()
}

Update example to be compatible with godoc


package dynatest

import (
	"github.com/underarmour/dynago"
	"github.com/underarmour/dynago/schema"
)

// A Mock executor
type Executor struct {
}

func (e *Executor) GetItem(*dynago.GetItem) (*dynago.GetItemResult, error) {
	return nil, nil
}

func (e *Executor) PutItem(*dynago.PutItem) (*dynago.PutItemResult, error) {
	return nil, nil
}

func (e *Executor) Query(*dynago.Query) (*dynago.QueryResult, error) {
	return nil, nil
}

func (e *Executor) UpdateItem(*dynago.UpdateItem) (*dynago.UpdateItemResult, error) {
	return nil, nil
}

func (e *Executor) CreateTable(*schema.CreateRequest) (*schema.CreateResponse, error) {
	return nil, nil
}

package dynatest

import (
	"github.com/underarmour/dynago"
	"github.com/underarmour/dynago/schema"
)

// A Mock executor
type Executor struct {
}

func (e *Executor) BatchWriteItem(*dynago.BatchWrite) (*dynago.BatchWriteResult, error) {
	return nil, nil
}

func (e *Executor) GetItem(*dynago.GetItem) (*dynago.GetItemResult, error) {
	return nil, nil
}

func (e *Executor) PutItem(*dynago.PutItem) (*dynago.PutItemResult, error) {
	return nil, nil
}

func (e *Executor) Query(*dynago.Query) (*dynago.QueryResult, error) {
	return nil, nil
}

func (e *Executor) UpdateItem(*dynago.UpdateItem) (*dynago.UpdateItemResult, error) {
	return nil, nil
}

func (e *Executor) CreateTable(*schema.CreateRequest) (*schema.CreateResponse, error) {
	return nil, nil
}

Make sure we still satisfy Executor


// +build pkcs11,linux

package yubikey

var possiblePkcs11Libs = []string{
	"/usr/lib/libykcs11.so",
	"/usr/lib64/libykcs11.so",
	"/usr/lib/x86_64-linux-gnu/libykcs11.so",
	"/usr/local/lib/libykcs11.so",
}

// +build pkcs11,linux

package yubikey

var possiblePkcs11Libs = []string{
	"/usr/lib/libykcs11.so",
	"/usr/lib/libykcs11.so.1",    // yubico-piv-tool on Fedora installs here
	"/usr/lib64/libykcs11.so",
	"/usr/lib64/libykcs11.so.1",  // yubico-piv-tool on Fedora installs here
	"/usr/lib/x86_64-linux-gnu/libykcs11.so",
	"/usr/local/lib/libykcs11.so",
}

Add some filepaths on Fedora where libykcs11 may be found.


package v2

import (
	"os"

	"code.cloudfoundry.org/cli/cf/cmd"
	"code.cloudfoundry.org/cli/commands"
	"code.cloudfoundry.org/cli/commands/flags"
)

type DeleteSpaceCommand struct {
	RequiredArgs flags.Space `positional-args:"yes"`
	Force        bool        `short:"f" description:"Force deletion without confirmation"`
	usage        interface{} `usage:"CF_NAME delete-space SPACE [-f]"`
}

func (_ DeleteSpaceCommand) Setup(config commands.Config, ui commands.UI) error {
	return nil
}

func (_ DeleteSpaceCommand) Execute(args []string) error {
	cmd.Main(os.Getenv("CF_TRACE"), os.Args)
	return nil
}

package v2

import (
	"os"

	"code.cloudfoundry.org/cli/cf/cmd"
	"code.cloudfoundry.org/cli/commands"
	"code.cloudfoundry.org/cli/commands/flags"
)

type DeleteSpaceCommand struct {
	RequiredArgs flags.Space `positional-args:"yes"`
	Force        bool        `short:"f" description:"Force deletion without confirmation"`
	Org          string      `short:"o" description:"Delete space within specified org"`
	usage        interface{} `usage:"CF_NAME delete-space SPACE [-o] [-f]"`
}

func (_ DeleteSpaceCommand) Setup(config commands.Config, ui commands.UI) error {
	return nil
}

func (_ DeleteSpaceCommand) Execute(args []string) error {
	cmd.Main(os.Getenv("CF_TRACE"), os.Args)
	return nil
}

Add delete-space -o flag to V2 command list


package main

/*
This could probably be smarter, but it'll do for now.
*/

const HTML_STOPPED = `

The instances for this service are currently powered down.

Click here to start.

	`

const HTML_STARTING = `

Your service is starting, please wait.

	`

const HTML_STOPPING = `

The instances for this service are being powered down.

	`

const HTML_UNHEALTHY = `

The instances for this service appear to be in an unhealthy or inconsistent state.

	`

const HTML_ERROR = `

An error occured processing your request: %v

	`

Add auto page refresh when starting/stopping


package main

import "fmt"

import "os"
import "bufio"
import "strings"
import "time"
import "strconv"
import "flag"

func main() {
	dur := flag.Duration("d", time.Second, "duration unit")
	flag.Parse()

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := scanner.Text()
		// fmt.Println(line) // Println will add back the final '\n'
		if strings.HasPrefix(line, "Benchmark") {
			fields := strings.Fields(line)
			if len(fields) < 4 || fields[3] != "ns/op" {
				fmt.Println(line)
				continue
			}
			nsPerOp, err := strconv.ParseInt(fields[2], 10, 64)
			if err != nil {
				fmt.Println(line)
				continue
			}
			opsPerDur := dur.Nanoseconds() / nsPerOp
			fmt.Printf("%s\t%d ops/%v\n", line, opsPerDur, dur)
			continue
		}
		fmt.Println(line)
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}
}

package main

import "fmt"

import "os"
import "bufio"
import "strings"
import "time"
import "strconv"
import "flag"

func main() {
	dur := flag.Duration("d", time.Second, "duration unit")
	flag.Parse()

	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := scanner.Text()
		// fmt.Println(line) // Println will add back the final '\n'
		if strings.HasPrefix(line, "Benchmark") {
			fields := strings.Fields(line)
			if len(fields) < 4 || fields[3] != "ns/op" {
				fmt.Println(line)
				continue
			}
			nsPerOp, err := strconv.ParseFloat(fields[2], 64)
			if err != nil {
				fmt.Println(line)
				continue
			}
			opsPerDur := int64(float64(dur.Nanoseconds()) / nsPerOp)
			fmt.Printf("%s\t%d ops/%v\n", line, opsPerDur, dur)
			continue
		}
		fmt.Println(line)
	}
	if err := scanner.Err(); err != nil {
		fmt.Fprintln(os.Stderr, "reading standard input:", err)
	}
}

Support floating point ns/op lines


package main

import (
  "./mega"
  "./task"
  "os"
  "fmt"
  "log"
  "io/ioutil"
)

const MaxWorker = 10

func main() {
  if len(os.Args) == 0 {
    log.Fatal("Please offer json file.")
  }
  pool, err := task.CreatePool()
  if err != nil {
    log.Fatal(err)
  }

  pool.Registry(task.MegaType, mega.MegaRoot{})

  file, err := os.Open(os.Args[1])
  if err != nil {
    log.Fatal(err)
  }
  defer file.Close()

  data, err := ioutil.ReadAll(file)
  if err != nil {
    log.Fatal(err)
  }

  _, err = pool.Add(task.MegaType, file.Name(), data)
  if err != nil {
    log.Fatal(err)
  }

  go pool.Start()

  for i := 0; i < MaxWorker; i++{
    go func(i int) {
      for {
        fmt.Println("Process", i, "asking...")
        t, ok := pool.Ask()
        if ok {
          fmt.Println("Process", i, "downloading...")
          t.Download()
          fmt.Println("Process", i, "reporting...")
          pool.Report(t)
          fmt.Println("Process", i, "done")
        }
      }
    }(i)
  }

  select{}
}

package main

import (
  "./mega"
  "./task"
  "os"
  "fmt"
  "log"
  "runtime"
  "io/ioutil"
)

var MaxWorker int

func init() {
  MaxWorker = runtime.NumCPU() << 1
}

func main() {
  if len(os.Args) == 0 {
    log.Fatal("Please offer json file.")
  }
  pool, err := task.CreatePool()
  if err != nil {
    log.Fatal(err)
  }

  pool.Registry(task.MegaType, mega.MegaRoot{})

  file, err := os.Open(os.Args[1])
  if err != nil {
    log.Fatal(err)
  }
  defer file.Close()

  data, err := ioutil.ReadAll(file)
  if err != nil {
    log.Fatal(err)
  }

  _, err = pool.Add(task.MegaType, file.Name(), data)
  if err != nil {
    log.Fatal(err)
  }

  go pool.Start()

  for i := 0; i < MaxWorker; i++{
    go func(i int) {
      for {
        fmt.Println("Process", i, "asking...")
        t, ok := pool.Ask()
        if ok {
          fmt.Println("Process", i, "downloading...")
          t.Download()
          fmt.Println("Process", i, "reporting...")
          pool.Report(t)
          fmt.Println("Process", i, "done")
        }
      }
    }(i)
  }

  select{}
}

Create workers base on cpu number.


package main

import (
	"fmt"
	"github.com/zero-boilerplate/go-api-helpers/service"
	"path/filepath"

	service2 "github.com/ayufan/golang-kardianos-service"
)

type app struct {
	logger             service2.Logger
	watcherDoneChannel chan bool
}

func (a *app) OnStop() {
	defer recover()
	close(a.watcherDoneChannel)
}

func (a *app) Run(logger service2.Logger) {
	a.logger = logger
	defer func() {
		if r := recover(); r != nil {
			a.logger.Errorf("Run app error: %s", getStringFromRecovery(r))
		}
	}()

	userHomeDir := getUserHomeDir()
	watchDir := filepath.Join(userHomeDir, ".script-watcher", "scripts")
	if !doesDirExist(watchDir) {
		panic(fmt.Sprintf("The watch dir '%s' does not exist", watchDir))
		return
	}

	a.scanDirForExistingFile(watchDir)
	a.startWatching(watchDir)
}

func main() {
	a := &app{}
	service.NewServiceRunnerBuilder("Script Watcher", a).WithOnStopHandler(a).WithServiceUserName_AsCurrentUser().Run()
}

package main

import (
	"fmt"
	"github.com/zero-boilerplate/go-api-helpers/service"
	"path/filepath"

	service2 "github.com/ayufan/golang-kardianos-service"
)

type app struct {
	logger             service2.Logger
	watcherDoneChannel chan bool
}

func (a *app) OnStop() {
	defer recover()
	if a.watcherDoneChannel != nil {
		close(a.watcherDoneChannel)
	}
}

func (a *app) Run(logger service2.Logger) {
	a.logger = logger
	defer func() {
		if r := recover(); r != nil {
			a.logger.Errorf("Run app error: %s", getStringFromRecovery(r))
		}
	}()

	userHomeDir := getUserHomeDir()
	watchDir := filepath.Join(userHomeDir, ".script-watcher", "scripts")
	if !doesDirExist(watchDir) {
		panic(fmt.Sprintf("The watch dir '%s' does not exist", watchDir))
		return
	}

	a.scanDirForExistingFile(watchDir)
	a.startWatching(watchDir)
}

func main() {
	a := &app{}
	service.NewServiceRunnerBuilder("Script Watcher", a).WithOnStopHandler(a).WithServiceUserName_AsCurrentUser().Run()
}

Check NIL channel. This will happen if it did not yet get to starting to watch the directory.


package main

import (
	"os"

	"github.com/albertyw/reaction-pics/server"
	"github.com/joho/godotenv"
	newrelic "github.com/newrelic/go-agent"
	"github.com/rollbar/rollbar-go"
)

func setupEnv() {
	err := godotenv.Load()
	if err != nil {
		panic(err)
	}
}

func getNewRelicApp() newrelic.Application {
	newrelicKey := os.Getenv("NEWRELIC_KEY")
	config := newrelic.NewConfig("Reaction.pics", newrelicKey)
	app, err := newrelic.NewApplication(config)
	if err != nil {
		panic(err)
	}
	return app
}

func setupRollbar() {
	rollbar.SetToken(os.Getenv("ROLLBAR_SERVER_TOKEN"))
	rollbar.SetEnvironment(os.Getenv("ENVIRONMENT"))
}

func main() {
	setupEnv()
	newrelicApp := getNewRelicApp()
	server.Run(newrelicApp)
}

package main

import (
	"os"

	"github.com/albertyw/reaction-pics/server"
	"github.com/joho/godotenv"
	newrelic "github.com/newrelic/go-agent"
	"github.com/rollbar/rollbar-go"
)

func setupEnv() {
	err := godotenv.Load()
	if err != nil {
		panic(err)
	}
}

func getNewRelicApp() newrelic.Application {
	newrelicKey := os.Getenv("NEWRELIC_KEY")
	config := newrelic.NewConfig("Reaction.pics", newrelicKey)
	app, err := newrelic.NewApplication(config)
	if err != nil {
		panic(err)
	}
	return app
}

func setupRollbar() {
	rollbar.SetToken(os.Getenv("ROLLBAR_SERVER_TOKEN"))
	rollbar.SetEnvironment(os.Getenv("ENVIRONMENT"))
}

func main() {
	setupEnv()
	setupRollbar()
	newrelicApp := getNewRelicApp()
	server.Run(newrelicApp)
}

Make sure rollbar is setup correctly


package main

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/context"
)

func main() {
	app := iris.New()
	app.Handle("GET", "/", func(ctx context.Context) {
		ctx.Writef("hello world\n")
	})

	app.Run(iris.Addr(":8080"))
}

package main

import (
	"github.com/kataras/iris"
	"github.com/kataras/iris/context"
	"github.com/kataras/iris/view"
)

func main() {
	app := iris.New()

	// load the ./templates/**.html
	templates := view.HTML("./templates", ".html"))
	app.AttachView(templates)

	app.Handle("GET", "/", func(ctx context.Context) {
	        // bind the {{ .Name }}
		ctx.ViewData("Name", "iris")
		// render the ./templates/hi.html
		ctx.View("hi.html")
	})

	app.Run(iris.Addr(":8080"))
}

Update and make use of the existing templates folder


package main

import "time"

// Standards for the result by launching a Missile
type Harm struct {
    code      int        `json:"code"`
    timestamp time.Time     `json:"timestamp"`
    latency   time.Duration `json:"latency"`
    bytesOut  uint64        `json:"bytes_out"`
    bytesIn   uint64        `json:"bytes_in"`
    error     string        `json:"error"`
}

package main

import "time"

// Standards for the result by launching a Missile
type Harm struct {
    startTime time.Time `json:"start_time"`
    endTime time.Time `json:"end_time"`
    statusCode      int        `json:"status_code"`
    timestamp time.Time     `json:"timestamp"` // When a tick occur
    latency   time.Duration `json:"latency"`   // Round Trip Latency
    sentBytes  uint64        `json:"sent_bytes"`
    receivedBytes   uint64        `json:"received_bytes"`
    error     string        `json:"error"`
}

Add startTime,endTime and change some variables name


// Webserver
package main

import (
	"fmt"
	"gopkg.in/gcfg.v1"
	"log"
	"net/http"
	"os"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcome, %s!", r.URL.Path[1:])
}

type config struct {
	Main struct {
		Port string
	}
}

func getConfig() config {
	cfg := new(config)

	err := gcfg.ReadFileInto(cfg, "./config-example.conf")

	if err != nil {
		log.Fatalf("Failed to parse gcfg data: %s", err)
		os.Exit(1)
	}

	return *cfg
}

func main() {
	cfg := getConfig()
	port := cfg.Main.Port
	if port == "" {
		port = "8000"
	}

	fmt.Println(port)
	http.HandleFunc("/", handler)
	http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
}

// Webserver
package main

import (
	"flag"
	"fmt"
	"gopkg.in/gcfg.v1"
	"log"
	"net/http"
)

var configFile = flag.String("config", "/etc/bobbi.conf", "INI file for bobbi")

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Welcome, %s!", r.URL.Path[1:])
}

type config struct {
	Main struct {
		Port string
	}
}

func getConfig(filename string) config {
	cfg := new(config)

	err := gcfg.ReadFileInto(cfg, filename)

	if err != nil {
		log.Fatalf("Failed reading config: %s", err)
	}

	return *cfg
}

func main() {
	flag.Parse()
	cfg := getConfig(*configFile)
	port := cfg.Main.Port
	if port == "" {
		port = "8000"
	}

	fmt.Println("Listening on port:", port)
	http.HandleFunc("/", handler)
	http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
}

Read from a specified config file.


package main

import (
	"github.com/hashicorp/terraform/plugin"
	"github.com/jayhding/terraform-provider-pingdom/pingdom"
)

func main() {
	plugin.Serve(&plugin.ServeOpts{
		ProviderFunc: pingdom.Provider,
	})
}

package main

import (
	"github.com/hashicorp/terraform/plugin"
	"github.com/russellcardullo/terraform-provider-pingdom/pingdom"
)

func main() {
	plugin.Serve(&plugin.ServeOpts{
		ProviderFunc: pingdom.Provider,
	})
}

Change upstream repo back for pull request


package flagx

import (
	"fmt"
	"reflect"
	"strings"
)

func Map(m interface{}, parseValue func(string) (interface{}, error)) Value {
	v := reflect.ValueOf(m)
	if v.IsNil() || v.Kind() != reflect.Map {
		panic("non-nil pointer to a map expected")
	}
	// check that keys are strings
	if v.Type().Key().Kind() != reflect.String {
		panic("keys must be of type string")
	}
	return &stringMap{v, parseValue}
}

type stringMap struct {
	Map   reflect.Value
	Parse func(string) (interface{}, error)
}

func (m *stringMap) String() string {
	return ""
}

func (m *stringMap) Set(s string) error {
	i := strings.IndexByte(s, '=')
	if i < 0 {
		return fmt.Errorf("%q: '=' expected")
	}
	key := s[:i]
	var value interface{}
	if m.Parse == nil {
		value = s[i+1:]
	} else {
		var err error
		value, err = m.Parse(s[i+1:])
		if err != nil {
			return err
		}
	}
	m.Map.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(value))
	return nil
}

func (m *stringMap) Get() interface{} {
	return m.Map.Interface()
}

package flagx

import (
	"fmt"
	"reflect"
	"strings"
)

func Map(m interface{}, parseValue func(string) (interface{}, error)) Value {
	v := reflect.ValueOf(m)
	if v.IsNil() || v.Kind() != reflect.Map {
		panic("non-nil pointer to a map expected")
	}
	// check that keys are strings
	if v.Type().Key().Kind() != reflect.String {
		panic("keys must be of type string")
	}
	return &stringMap{v, parseValue}
}

type stringMap struct {
	Map   reflect.Value
	Parse func(string) (interface{}, error)
}

func (m *stringMap) String() string {
	return ""
}

func (m *stringMap) Set(s string) error {
	i := strings.IndexByte(s, '=')
	if i < 0 {
		return fmt.Errorf("%q: '=' expected", s)
	}
	key := s[:i]
	var value interface{}
	if m.Parse == nil {
		value = s[i+1:]
	} else {
		var err error
		value, err = m.Parse(s[i+1:])
		if err != nil {
			return err
		}
	}
	m.Map.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(value))
	return nil
}

func (m *stringMap) Get() interface{} {
	return m.Map.Interface()
}

Fix typo in Map error handling


package app

import termbox "github.com/nsf/termbox-go"

type servicesScreenEventHandler struct {
	baseEventHandler
}

func (h *servicesScreenEventHandler) handle(event termbox.Event) {
	handled := false

	switch event.Key {
	case termbox.KeyEnter:
		showServices := func(serviceID string) error {
			h.dry.ShowServiceTasks(serviceID)
			h.renderChan <- struct{}{}
			return nil
		}
		h.dry.state.activeWidget.OnEvent(showServices)
		handled = true
	}
	if !handled {
		h.baseEventHandler.handle(event)
	} else {
		h.setFocus(true)
	}
}

type serviceTaskScreenEventHandler struct {
	baseEventHandler
}

func (h *serviceTaskScreenEventHandler) handle(event termbox.Event) {

	switch event.Key {
	case termbox.KeyEsc:
		h.dry.ShowServices()
	}

	h.baseEventHandler.handle(event)

}

Add event handler for service tasks screen


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

Copyright 2015 Intel Coporation

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

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

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

package main

import (
	"os"

	"github.com/intelsdi-x/pulse/control/plugin"
	"github.com/intelsdi-x/pulse/plugin/publisher/pulse-publisher-influxdb/influx"
)

func main() {
	meta := influx.Meta()
	plugin.Start(meta, influx.NewInfluxPublisher(), os.Args[1])
}

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

Copyright 2015 Intel Coporation

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

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

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

package main

import (
	"os"

	"github.com/intelsdi-x/pulse-plugin-publisher-influxdb/influx"
	"github.com/intelsdi-x/pulse/control/plugin"
)

func main() {
	meta := influx.Meta()
	plugin.Start(meta, influx.NewInfluxPublisher(), os.Args[1])
}

Update import path for influx package


package main

import (
	"context"
	"flag"
	"log"

	"github.com/hashicorp/terraform-plugin-framework/providerserver"

	"github.com/terraform-providers/terraform-provider-null/internal/provider"
)

// Run "go generate" to format example terraform files and generate the docs for the registry/website

// If you do not have terraform installed, you can remove the formatting command, but its suggested to
// ensure the documentation is formatted properly.
//go:generate terraform fmt -recursive ./examples/

// Run the docs generation tool, check its repository for more information on how it works and how docs
// can be customized.
//go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs

func main() {
	var debug bool

	flag.BoolVar(&debug, "debug", false, "set to true to run the provider with support for debuggers like delve")
	flag.Parse()

	err := providerserver.Serve(context.Background(), provider.New, providerserver.ServeOpts{
		Address:         "registry.terraform.io/hashicorp/time",
		Debug:           debug,
		ProtocolVersion: 5,
	})
	if err != nil {
		log.Fatal(err)
	}
}

package main

import (
	"context"
	"flag"
	"log"

	"github.com/hashicorp/terraform-plugin-framework/providerserver"

	"github.com/terraform-providers/terraform-provider-null/internal/provider"
)

// Run "go generate" to format example terraform files and generate the docs for the registry/website

// If you do not have terraform installed, you can remove the formatting command, but its suggested to
// ensure the documentation is formatted properly.
//go:generate terraform fmt -recursive ./examples/

// Run the docs generation tool, check its repository for more information on how it works and how docs
// can be customized.
//go:generate go run github.com/hashicorp/terraform-plugin-docs/cmd/tfplugindocs

func main() {
	var debug bool

	flag.BoolVar(&debug, "debug", false, "set to true to run the provider with support for debuggers like delve")
	flag.Parse()

	err := providerserver.Serve(context.Background(), provider.New, providerserver.ServeOpts{
		Address:         "registry.terraform.io/hashicorp/null",
		Debug:           debug,
		ProtocolVersion: 5,
	})
	if err != nil {
		log.Fatal(err)
	}
}

Correct the registry address for the provider server


package app_helpers

import (
	"strings"
	"time"

	"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
	"github.com/cloudfoundry-incubator/cf-test-helpers/helpers"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gexec"
)

func guidForAppName(appName string) string {
	cfApp := cf.Cf("app", appName, "--guid")
	Expect(cfApp.Wait()).To(Exit(0))

	appGuid := strings.TrimSpace(string(cfApp.Out.Contents()))
	Expect(appGuid).NotTo(Equal(""))
	return appGuid
}

func ConditionallyEnableDiego(appName string) {
	config := helpers.LoadConfig()
	if config.UseDiego {
		guid := guidForAppName(appName)
		Eventually(cf.Cf("curl", "/v2/apps/"+guid, "-X", "PUT", "-d", `{"diego": true}`)).Should(Exit(0))
	}
}

func AppReport(appName string, timeout time.Duration) {
	Eventually(cf.Cf("app", appName, "--guid"), timeout).Should(Exit())
	Eventually(cf.Cf("logs", appName, "--recent"), timeout).Should(Exit())
}

package app_helpers

import (
	"strings"
	"time"

	"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
	"github.com/cloudfoundry-incubator/cf-test-helpers/helpers"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gexec"
)

func guidForAppName(appName string) string {
	cfApp := cf.Cf("app", appName, "--guid")
	Expect(cfApp.Wait()).To(Exit(0))

	appGuid := strings.TrimSpace(string(cfApp.Out.Contents()))
	Expect(appGuid).NotTo(Equal(""))
	return appGuid
}

func ConditionallyEnableDiego(appName string) {
	config := helpers.LoadConfig()
	if config.Backend == "diego" {
		guid := guidForAppName(appName)
		Eventually(cf.Cf("curl", "/v2/apps/"+guid, "-X", "PUT", "-d", `{"diego": true}`)).Should(Exit(0))
	} else if config.Backend == "dea" {
		guid := guidForAppName(appName)
		Eventually(cf.Cf("curl", "/v2/apps/"+guid, "-X", "PUT", "-d", `{"diego": false}`)).Should(Exit(0))
	}
}

func AppReport(appName string, timeout time.Duration) {
	Eventually(cf.Cf("app", appName, "--guid"), timeout).Should(Exit())
	Eventually(cf.Cf("logs", appName, "--recent"), timeout).Should(Exit())
}

Replace UseDiego config with Backend.


package main

import (
	"flag"
	"fmt"
	"os"

	log "github.com/cihub/seelog"
)

var (
	flagSet = flag.NewFlagSet("kraken", flag.ExitOnError)

	target = flagSet.String("target", "", "target URL to crawl")
)

func main() {
	// Process flags
	flagSet.Parse(os.Args[1:])

	// Flush logs before exit
	defer log.Flush()

	// Do we have a target?
	if *target == "" {
		fmt.Println("Please specify a target domain, eg. kraken -target=\"http://example.com\"")
		os.Exit(1)
	}
	log.Infof("Unleashing the Kraken at %s", target)

	// Use a HTTP based fetcher
	fetcher := &HttpFetcher{}

	// Crawl the specified site
	Crawl(*target, 4, fetcher)
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {

	_, urls, err := fetcher.Fetch(url)
	if err != nil {
		log.Errorf("Error:", err)
		return
	}

	log.Infof("URLs found: %+v", urls)
}

package main

import (
	"flag"
	"fmt"
	"os"

	log "github.com/cihub/seelog"
)

var (
	flagSet = flag.NewFlagSet("kraken", flag.ExitOnError)

	target = flagSet.String("target", "", "target URL to crawl")
)

func main() {
	// Process flags
	flagSet.Parse(os.Args[1:])

	// Flush logs before exit
	defer log.Flush()

	// Do we have a target?
	if *target == "" {
		fmt.Println("Please specify a target domain, eg. kraken -target=\"http://example.com\"")
		os.Exit(1)
	}
	log.Infof("Unleashing the Kraken at %s", *target)

	// Use a HTTP based fetcher
	fetcher := &HttpFetcher{}

	// Crawl the specified site
	Crawl(*target, 4, fetcher)
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {

	_, urls, err := fetcher.Fetch(url)
	if err != nil {
		log.Errorf("Error:", err)
		return
	}

	log.Infof("URLs found: %+v", urls)
}

Fix debug log of target url


package main

import (
	flags "github.com/jessevdk/go-flags"
	"github.com/monochromegane/the_platinum_searcher/search"
	"github.com/monochromegane/the_platinum_searcher/search/option"
	"os"
	"runtime"
)

var opts option.Option

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())
}

func main() {

	args, _ := flags.Parse(&opts)

	var root = "."

	if len(args) == 0 {
		os.Exit(1)
	}
	if len(args) == 2 {
		root = args[1]
	}

	searcher := search.Searcher{root, args[0], &opts}
	searcher.Search()
}

package main

import (
	"code.google.com/p/go.crypto/ssh/terminal"
	flags "github.com/jessevdk/go-flags"
	"github.com/monochromegane/the_platinum_searcher/search"
	"github.com/monochromegane/the_platinum_searcher/search/option"
	"os"
	"runtime"
)

var opts option.Option

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())
}

func main() {

	args, _ := flags.Parse(&opts)

	if !terminal.IsTerminal(int(os.Stdout.Fd())) {
		opts.NoColor = true
		opts.NoGroup = true
	}

	var root = "."

	if len(args) == 0 {
		os.Exit(1)
	}
	if len(args) == 2 {
		root = args[1]
	}

	searcher := search.Searcher{root, args[0], &opts}
	searcher.Search()
}

Print results with no color and no group if stdout isn't tty.


package scipipe

import (
	"os"
	"time"
)

type FileTarget struct {
	path string
}

func NewFileTarget(path string) *FileTarget {
	ft := new(FileTarget)
	ft.path = path
	return ft
}

func (ft *FileTarget) GetPath() string {
	return ft.path
}

func (ft *FileTarget) GetTempPath() string {
	return ft.path + ".tmp"
}

func (ft *FileTarget) Atomize() {
	time.Sleep(1 * time.Second) // TODO: Remove in production. Just for demo purposes!
	err := os.Rename(ft.GetTempPath(), ft.path)
	Check(err)
}

func (ft *FileTarget) Exists() bool {
	if _, err := os.Stat(ft.GetPath()); err == nil {
		return true
	}
	return false
}

Implement Exists() method on FileTarget


package main

import (
	"fmt"
	"github.com/rancher/convoy/api"
	"github.com/rancher/convoy/client"
	"os"
)

const (
	// version of Convoy
	VERSION = "0.4.3"
)

func cleanup() {
	if r := recover(); r != nil {
		api.ResponseLogAndError(r)
		os.Exit(1)
	}
}

func main() {
	defer cleanup()

	cli := client.NewCli(VERSION)
	err := cli.Run(os.Args)
	if err != nil {
		panic(fmt.Errorf("Error when executing command: %v", err))
	}
}

package main

import (
	"fmt"
	"github.com/rancher/convoy/api"
	"github.com/rancher/convoy/client"
	"os"
)

const (
	// version of Convoy
	VERSION = "0.4.4-dev"
)

func cleanup() {
	if r := recover(); r != nil {
		api.ResponseLogAndError(r)
		os.Exit(1)
	}
}

func main() {
	defer cleanup()

	cli := client.NewCli(VERSION)
	err := cli.Run(os.Args)
	if err != nil {
		panic(fmt.Errorf("Error when executing command: %v", err))
	}
}

Update Convoy version to 0.4.4-dev


package main

import "net/http"

func main() {
	http.HandleFunc("/hostname", hostnameHandler)
	http.HandleFunc("/time", timeHandler)
	http.HandleFunc("/issue", issueHandler)
	http.ListenAndServe(":3000", nil)
}

func hostnameHandler(w http.ResponseWriter, r *http.Request) {
	hostname, err := hostname()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write([]byte(hostname))
}

func timeHandler(w http.ResponseWriter, r *http.Request) {
	time, err := time()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write([]byte(time))
}

func issueHandler(w http.ResponseWriter, r *http.Request) {
	distro, kernel, err := issue()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write([]byte(distro + " " + kernel))
}

package main

import (
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/hostname", hostnameHandler)
	http.HandleFunc("/time", timeHandler)
	http.HandleFunc("/issue", issueHandler)
	fmt.Println("Serving on port 3000...")
	http.ListenAndServe(":3000", nil)
}

func hostnameHandler(w http.ResponseWriter, r *http.Request) {
	hostname, err := hostname()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write([]byte(hostname))
}

func timeHandler(w http.ResponseWriter, r *http.Request) {
	time, err := time()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write([]byte(time))
}

func issueHandler(w http.ResponseWriter, r *http.Request) {
	distro, kernel, err := issue()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write([]byte(distro + " " + kernel))
}

Add print statement to indicate server is running