/*
Copyright 2016 The Kubernetes Authors.

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

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

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

// +k8s:deepcopy-gen=package,register

// +genconversion=true
package v1beta1

/*
Copyright 2016 The Kubernetes Authors.

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

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

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

// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=k8s.io/kubernetes/federation/apis/federation

package v1beta1

Use file tags to generate conversions


package uploadService

import (
	"strings"
)

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

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

package uploadService

import (
	"strings"
)

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

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

Update list of dead trackers


package middlewares

import (
	"fmt"
	"io"
	"net/http"

	"github.com/urfave/negroni"

	"os"
	"time"

	"github.com/pkg/errors"
)

type MetricsMiddleware struct {
	writer io.Writer
}

func NewMetricsMiddlewareFromFilename(filename string) *MetricsMiddleware {
	fileWriter, e := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0664)
	if e != nil {
		panic(errors.Wrapf(e, "Could not open file '%v' for appending", filename))
	}
	return &MetricsMiddleware{writer: fileWriter}
}

func NewMetricsMiddleware(writer io.Writer) *MetricsMiddleware {
	return &MetricsMiddleware{writer: writer}
}

func (middleware *MetricsMiddleware) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request, next http.HandlerFunc) {
	startTime := time.Now()
	negroniResponseWriter, ok := responseWriter.(negroni.ResponseWriter)
	if !ok {
		negroniResponseWriter = negroni.NewResponseWriter(responseWriter)
	}

	next(negroniResponseWriter, request)

	fmt.Fprintf(middleware.writer, "%v %v %v;%v;%v\n",
		request.Method, request.URL.Path, request.Proto, time.Since(startTime).Seconds(), negroniResponseWriter.Size())
}

package middlewares

import (
	"fmt"
	"io"
	"net/http"
	"sync"

	"github.com/urfave/negroni"

	"os"
	"time"

	"github.com/pkg/errors"
)

type MetricsMiddleware struct {
	writer      io.Writer
	writerMutex sync.Mutex
}

func NewMetricsMiddlewareFromFilename(filename string) *MetricsMiddleware {
	fileWriter, e := os.OpenFile(filename, os.O_CREATE|os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0664)
	if e != nil {
		panic(errors.Wrapf(e, "Could not open file '%v' for appending", filename))
	}
	return &MetricsMiddleware{writer: fileWriter}
}

func NewMetricsMiddleware(writer io.Writer) *MetricsMiddleware {
	return &MetricsMiddleware{writer: writer}
}

func (middleware *MetricsMiddleware) ServeHTTP(responseWriter http.ResponseWriter, request *http.Request, next http.HandlerFunc) {
	startTime := time.Now()
	negroniResponseWriter, ok := responseWriter.(negroni.ResponseWriter)
	if !ok {
		negroniResponseWriter = negroni.NewResponseWriter(responseWriter)
	}

	next(negroniResponseWriter, request)

	middleware.writerMutex.Lock()
	defer middleware.writerMutex.Unlock()
	fmt.Fprintf(middleware.writer, "%v %v %v;%v;%v\n",
		request.Method, request.URL.Path, request.Proto, time.Since(startTime).Seconds(), negroniResponseWriter.Size())
}

Use mutex to avoid concurrent write to metrics log file


package jsify

import (
	"testing"
)

func Test_Example(t *testing.T) {
	structs := make([]interface{}, 3)
	structs[0] = &Foo{}
	structs[1] = &Bar{}
	structs[2] = &Baz{}
	_, err := GenerateJavascriptToString(structs)
	if err != nil {
		t.Fail()
	}
}

package jsify

import (
	"os"
	"testing"
)

func Test_NoErrors(t *testing.T) {
	structs := make([]interface{}, 3)
	structs[0] = &Foo{}
	structs[1] = &Bar{}
	structs[2] = &Baz{}
	_, err := GenerateJavascriptToString(structs)
	if err != nil {
		t.Fail()
	}
}

func Test_MakeFile(t *testing.T) {
	fileName := "./structs.js"
	defer os.Remove(fileName)
	structs := make([]interface{}, 3)
	structs[0] = &Foo{}
	structs[1] = &Bar{}
	structs[2] = &Baz{}
	err := GenerateJavascriptToFile(fileName, structs)
	if err != nil {
		t.Fail()
	}
	if _, err := os.Stat(fileName); os.IsNotExist(err) {
		t.Fail()
	}
}

Add simple test for file generation.


package gondole

import ()
import (
	"github.com/sendgrid/rest"
	"fmt"
)

const (
	APIVersion = "0.0"

	APIEndpoint = "/api/v1"

	NoRedirect = "urn:ietf:wg:oauth:2.0:oob"
)

// prepareRequest insert all pre-defined stuff
func (g *Gondole) prepareRequest(what string) (req rest.Request) {
	endPoint := APIEndpoint + fmt.Sprintf("/%s/", what)
	key, ok := HasAPIKey()

	// Add at least one option, the APIkey if present
	hdrs := make(map[string]string)
	opts := make(map[string]string)

	// Insert our sig
	hdrs["User-Agent"] = fmt.Sprintf("Gondole/%s", APIVersion)

	// Insert key
	if ok {
		opts["key"] = key
	}

	req = rest.Request{
		BaseURL:     endPoint,
		Headers:     hdrs,
		QueryParams: opts,
	}
	return
}

package gondole

import ()
import (
	"github.com/sendgrid/rest"
	"fmt"
)

const (
	APIVersion = "0.0"

	APIEndpoint = "/api/v1"

	NoRedirect = "urn:ietf:wg:oauth:2.0:oob"
)

// prepareRequest insert all pre-defined stuff
func (g *Gondole) prepareRequest(what string) (req rest.Request) {
	endPoint := APIEndpoint + fmt.Sprintf("/%s/", what)

	// Add at least one option, the APIkey if present
	hdrs := make(map[string]string)
	opts := make(map[string]string)

	// Insert our sig
	hdrs["User-Agent"] = fmt.Sprintf("Gondole/%s", APIVersion)

	req = rest.Request{
		BaseURL:     endPoint,
		Headers:     hdrs,
		QueryParams: opts,
	}
	return
}

Add a tailored version of prepareRequest().


// +build !windows

package gottyclient

import (
	"encoding/json"
	"fmt"
	"os"
	"os/signal"
	"syscall"
	"unsafe"
)

func notifySignalSIGWINCH(c chan<- os.Signal) {
	signal.Notify(c, syscall.SIGWINCH)
}

func resetSignalSIGWINCH() {
	signal.Reset(syscall.SIGWINCH)
}

func syscallTIOCGWINSZ() ([]byte, error) {
	ws := winsize{}

	syscall.Syscall(syscall.SYS_IOCTL,
		uintptr(0), uintptr(syscall.TIOCGWINSZ),
		uintptr(unsafe.Pointer(&ws)))

	b, err := json.Marshal(ws)
	if err != nil {
		return nil, fmt.Errorf("json.Marshal error: %v", err)
	}
	return b, err
}

// +build !windows

package gottyclient

import (
	"encoding/json"
	"fmt"
	"golang.org/x/sys/unix"
	"os"
	"os/signal"
	"syscall"
)

func notifySignalSIGWINCH(c chan<- os.Signal) {
	signal.Notify(c, syscall.SIGWINCH)
}

func resetSignalSIGWINCH() {
	signal.Reset(syscall.SIGWINCH)
}

func syscallTIOCGWINSZ() ([]byte, error) {
	ws, err := unix.IoctlGetWinsize(0, 0)
	if err != nil {
		return nil, fmt.Errorf("ioctl error: %v", err)
	}
	b, err := json.Marshal(ws)
	if err != nil {
		return nil, fmt.Errorf("json.Marshal error: %v", err)
	}
	return b, err
}

Replace SYS_IOCTL by cross platform version


// Copyright 2013 Marc Weistroff. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.

package log

import (
	"testing"
	"time"
)

func TestMinimalLineFormatter(t *testing.T) {
	r := newRecord(DEBUG, "foobar", "msg", map[string]string{"foo": "bar"})
	formatter := NewMinimalLineFormatter()
	formatter.Format(r)
	if r.Formatted != "foobar.DEBUG: msg\n" {
		t.Error(r.Formatted)
	}
}

func TestSimpleLineFormatter(t *testing.T) {
	r := newRecord(DEBUG, "foobar", "msg", map[string]string{"foo": "bar"})
	r.Time = time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC)
	formatter := NewSimpleLineFormatter()
	formatter.Format(r)
	if r.Formatted != "[2009-11-10T23:00:00Z] foobar.DEBUG: msg foo=\"bar\" \n" {
		t.Error(r.Formatted)
	}
}

// Copyright 2013 Marc Weistroff. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.

package log

import (
	"testing"
	"time"
)

func TestMinimalLineFormatter(t *testing.T) {
	r := newRecord(DEBUG, "foobar", "msg", map[string]string{"foo": "bar"})
	formatter := NewMinimalLineFormatter()
	formatter.Format(r)
	if r.Formatted != "foobar.DEBUG: msg\n" {
		t.Error(r.Formatted)
	}
}

func TestSimpleLineFormatter(t *testing.T) {
	r := newRecord(DEBUG, "foobar", "msg\n", map[string]string{"foo": "bar"})
	r.Time = time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC)
	formatter := NewSimpleLineFormatter()
	formatter.Format(r)
	if r.Formatted != "[2009-11-10T23:00:00Z] foobar.DEBUG: msg foo=\"bar\" \n" {
		t.Error(r.Formatted)
	}
}

Update test to take account that newlines can occur in message


package chain

import "testing"

func TestFuncEnd(t *testing.T) {
	c := New(nestedHandler0, nestedHandler0)
	c = c.Append(nestedHandler1, nestedHandler1)

	mc := New(nestedHandler0, nestedHandler0)
	c = c.Merge(mc)

	h := c.EndFn(endHandler)

	w, err := record(h)
	if err != nil {
		t.Fatalf("unexpected error: %s\n", err.Error())
	}

	resp := w.Body.String()
	wResp := b0 + b0 + b1 + b1 + b0 + b0 + bEnd + b0 + b0 + b1 + b1 + b0 + b0
	if wResp != resp {
		t.Fatalf("want response %s, got %s\n", wResp, resp)
	}
}

package chain

import "testing"

func TestFuncHandlerOrder(t *testing.T) {
	c := New(nestedHandler0, nestedHandler0)
	c = c.Append(nestedHandler1, nestedHandler1)

	mc := New(nestedHandler0, nestedHandler0)
	c = c.Merge(mc)

	h := c.EndFn(endHandler)

	w, err := record(h)
	if err != nil {
		t.Fatalf("unexpected error: %s\n", err.Error())
	}

	resp := w.Body.String()
	wResp := b0 + b0 + b1 + b1 + b0 + b0 + bEnd + b0 + b0 + b1 + b1 + b0 + b0
	if wResp != resp {
		t.Fatalf("want response %s, got %s\n", wResp, resp)
	}
}

Rename functional test with specificity.


// Package linear provides a linear-algebra toolbox.
package linear

// Tensor computes the tensor product of a number of vectors.
func Tensor(data ...[]float64) []float64 {
	nd := len(data)

	dims := make([]int, nd)
	for i := 0; i < nd; i++ {
		dims[i] = len(data[i])
	}

	aprod := make([]int, nd)
	aprod[0] = 1
	for i := 1; i < nd; i++ {
		aprod[i] = dims[i-1] * aprod[i-1]
	}

	dprod := make([]int, nd)
	dprod[nd-1] = 1
	for i := nd - 2; i >= 0; i-- {
		dprod[i] = dims[i+1] * dprod[i+1]
	}

	np := dims[0] * dprod[0]

	tensor := make([]float64, np*nd)
	for i, z := 0, 0; i < nd; i++ {
		for j := 0; j < dprod[i]; j++ {
			for k := 0; k < dims[i]; k++ {
				for l := 0; l < aprod[i]; l++ {
					tensor[z] = data[i][k]
					z++
				}
			}
		}
	}

	return tensor
}

// Package linear provides a linear-algebra toolbox.
package linear

// Tensor computes the tensor product of a number of vectors.
func Tensor(vectors ...[]float64) []float64 {
	nd := len(vectors)

	dims := make([]int, nd)
	for i := 0; i < nd; i++ {
		dims[i] = len(vectors[i])
	}

	aprod := make([]int, nd)
	aprod[0] = 1
	for i := 1; i < nd; i++ {
		aprod[i] = dims[i-1] * aprod[i-1]
	}

	dprod := make([]int, nd)
	dprod[nd-1] = 1
	for i := nd - 2; i >= 0; i-- {
		dprod[i] = dims[i+1] * dprod[i+1]
	}

	np := dims[0] * dprod[0]

	tensor := make([]float64, np*nd)
	for i, z := 0, 0; i < nd; i++ {
		for j := 0; j < dprod[i]; j++ {
			for k := 0; k < dims[i]; k++ {
				for l := 0; l < aprod[i]; l++ {
					tensor[z] = vectors[i][k]
					z++
				}
			}
		}
	}

	return tensor
}

Rename the argument of Tensor


// +build !linux

package plugin

import (
	"fmt"

	cnitypes "github.com/containernetworking/cni/pkg/types"

	"github.com/openshift/origin/pkg/sdn/plugin/cniserver"
)

func (m *podManager) setup(req *cniserver.PodRequest) (*cnitypes.Result, *runningPod, error) {
	return nil, nil, fmt.Errorf("openshift-sdn is unsupported on this OS!")
}

func (m *podManager) update(req *cniserver.PodRequest) (*runningPod, error) {
	return nil, fmt.Errorf("openshift-sdn is unsupported on this OS!")
}

// Clean up all pod networking (clear OVS flows, release IPAM lease, remove host/container veth)
func (m *podManager) teardown(req *cniserver.PodRequest) error {
	return fmt.Errorf("openshift-sdn is unsupported on this OS!")
}

// +build !linux

package plugin

import (
	"fmt"

	cnitypes "github.com/containernetworking/cni/pkg/types"

	"github.com/openshift/origin/pkg/sdn/plugin/cniserver"
)

func (m *podManager) setup(req *cniserver.PodRequest) (*cnitypes.Result, *runningPod, error) {
	return nil, nil, fmt.Errorf("openshift-sdn is unsupported on this OS!")
}

func (m *podManager) update(req *cniserver.PodRequest) (uint32, error) {
	return 0, fmt.Errorf("openshift-sdn is unsupported on this OS!")
}

// Clean up all pod networking (clear OVS flows, release IPAM lease, remove host/container veth)
func (m *podManager) teardown(req *cniserver.PodRequest) error {
	return fmt.Errorf("openshift-sdn is unsupported on this OS!")
}

Fix stub interface so Mac compilations work


package main

import (
	"fmt"

	log "github.com/Sirupsen/logrus"
	openwhisk "github.com/c3sr/openwhisk-go"
	actions "github.com/c3sr/openwhisk-go/client/actions"
	models "github.com/c3sr/openwhisk-go/models"
)

func main() {
	cli, err := openwhisk.NewBasicAuthClientFromEnv()
	if err != nil {
		log.Fatal(err)
	}

	p := actions.NewUpdateActionParams()

	p.SetActionName("example-action")
	p.SetNamespace("IBM-ILLINOIS-C3SR_dev")

	ap := &models.ActionPut{Version: "0.0.1", Publish: true}
	kindStr := "blackbox"
	ap.Exec = &models.ActionExec{Kind: &kindStr, Image: "c3sr/echo-go"}
	memLimit := int32(256)
	timeout := int32(60000)
	ap.Limits = &models.ActionLimits{Memory: &memLimit, Timeout: &timeout}
	p.SetAction(ap)

	ok, err := cli.Actions.UpdateAction(p)

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

}

package main

import (
	"fmt"

	log "github.com/Sirupsen/logrus"
	openwhisk "github.com/c3sr/openwhisk-go"
	actions "github.com/c3sr/openwhisk-go/client/actions"
	models "github.com/c3sr/openwhisk-go/models"
)

func main() {
	cli, err := openwhisk.NewBasicAuthClientFromEnv()
	if err != nil {
		log.Fatal(err)
	}

	p := actions.NewUpdateActionParams()

	overwriteStr := "false"
	p.Overwrite = &overwriteStr
	p.SetActionName("example-action")
	p.SetNamespace("IBM-ILLINOIS-C3SR_dev")

	ap := &models.ActionPut{Version: "0.0.2", Publish: true}
	kindStr := "blackbox"
	ap.Exec = &models.ActionExec{Kind: &kindStr, Image: "c3sr/echo-go"}
	memLimit := int32(256)
	timeout := int32(60000)
	ap.Limits = &models.ActionLimits{Memory: &memLimit, Timeout: &timeout}
	p.SetAction(ap)

	ok, err := cli.Actions.UpdateAction(p)

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

}

Add overwrite to update action example


package task

type TaskServer struct {
}

package task

import (
	"net/http"

	"example.com/internal/taskstore"
	"github.com/labstack/echo/v4"
)

type TaskServer struct {
	store *taskstore.TaskStore
}

func NewTaskServer() *TaskServer {
	store := taskstore.New()
	return &TaskServer{store: store}
}

func (ts *TaskServer) GetDueYearMonthDay(ctx echo.Context, year int, month int, day int) error {
	return nil
}

func (ts *TaskServer) GetTagTagname(ctx echo.Context, tagname string) error {
	return nil
}

func (ts *TaskServer) GetTask(ctx echo.Context) error {
	return nil
}

func (ts *TaskServer) PostTask(ctx echo.Context) error {
	var taskBody PostTaskJSONBody
	err := ctx.Bind(&taskBody)
	if err != nil {
		return err
	}

	// TODO: check non-nil on these fields?!
	// TODO: do I need additional error checking here?
	id := ts.store.CreateTask(*taskBody.Text, *taskBody.Tags, *taskBody.Due)
	type ResponseId struct {
		Id int `json:"id"`
	}
	ctx.JSON(http.StatusOK, ResponseId{Id: id})
}

func (ts *TaskServer) DeleteTaskId(ctx echo.Context, id int) error {
	return nil
}

func (ts *TaskServer) GetTaskId(ctx echo.Context, id int) error {
	task, err := ts.store.GetTask(id)
	if err != nil {
		return err
	}
	ctx.JSON(http.StatusOK, task)
}

Add implementation for PostTask and GetTaskId, untested


package messenger

import "time"

type Message struct {
	Sender      Sender       `json:"-"`
	Recipient   Recipient    `json:"-"`
	Time        time.Time    `json:"-"`
	Mid         string       `json:"mid"`
	Text        string       `json:"text"`
	Seq         int          `json:"seq"`
	Attachments []Attachment `json:"attachments"`
}

type Delivery struct {
	Mids         []string `json:"mids"`
	RawWatermark int64    `json:"watermark"`
	Seq          int      `json:"seq"`
}

func (d Delivery) Watermark() time.Time {
	return time.Unix(d.RawWatermark, 0)
}

package messenger

import "time"

// Message represents a Facebook messenge message.
type Message struct {
	// Sender is who the message was sent from.
	Sender Sender `json:"-"`
	// Recipient is who the message was sent to.
	Recipient Recipient `json:"-"`
	// Time is when the message was sent.
	Time time.Time `json:"-"`
	// Mid is the ID of the message.
	Mid string `json:"mid"`
	// Seq is order the message was sent in relation to other messages.
	Seq int `json:"seq"`
	// Text is the textual contents of the message.
	Text string `json:"text"`
	// Attachments is the information about the attachments which were sent
	// with the message.
	Attachments []Attachment `json:"attachments"`
}

// Delivery represents a the event fired when a recipient reads one of Messengers sent
// messages.
type Delivery struct {
	// Mids are the IDs of the messages which were read.
	Mids []string `json:"mids"`
	// RawWatermark is the timestamp contained in the message of when the read was.
	RawWatermark int64 `json:"watermark"`
	// Seq is the sequence the message was sent in.
	Seq int `json:"seq"`
}

// Watermark is the RawWatermark timestamp rendered as a time.Time.
func (d Delivery) Watermark() time.Time {
	return time.Unix(d.RawWatermark, 0)
}

Add documentation to Message and Delivery


package main

import (
	"errors"
	"fmt"
	"github.com/Symantec/Dominator/lib/srpc"
	"io"
	"os"
	"os/exec"
)

func addDeviceSubcommand(client *srpc.Client, args []string) {
	if err := addDevice(client, args[0], args[1], args[2:]); err != nil {
		fmt.Fprintf(os.Stderr, "Error adding device: %s\n", err)
		os.Exit(1)
	}
	os.Exit(0)
}

func addDevice(client *srpc.Client, deviceId, command string,
	args []string) error {
	conn, err := client.Call("ImageUnpacker.AddDevice")
	if err != nil {
		return err
	}
	response, err := conn.ReadString('\n')
	if err != nil {
		return err
	}
	response = response[:len(response)-1]
	if response != "" {
		return errors.New(response)
	}
	cmd := exec.Command(command, args...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		if err != io.EOF {
			return err
		}
	}
	if _, err := conn.WriteString(deviceId + "\n"); err != nil {
		return err
	}
	if err := conn.Flush(); err != nil {
		return err
	}
	response, err = conn.ReadString('\n')
	if err != nil {
		return err
	}
	response = response[:len(response)-1]
	if response != "" {
		return errors.New(response)
	}
	return nil
}

package main

import (
	"fmt"
	uclient "github.com/Symantec/Dominator/imageunpacker/client"
	"github.com/Symantec/Dominator/lib/srpc"
	"io"
	"os"
	"os/exec"
)

func addDeviceSubcommand(client *srpc.Client, args []string) {
	if err := addDevice(client, args[0], args[1], args[2:]); err != nil {
		fmt.Fprintf(os.Stderr, "Error adding device: %s\n", err)
		os.Exit(1)
	}
	os.Exit(0)
}

func addDevice(client *srpc.Client, deviceId, command string,
	args []string) error {
	return uclient.AddDevice(client, deviceId,
		func() error { return adder(command, args) })
}

func adder(command string, args []string) error {
	cmd := exec.Command(command, args...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		if err != io.EOF {
			return err
		}
	}
	return nil
}

Use new imageunpacker/client.AddDevice() function in unpacker-tool.


package main

import (
	"github.com/nlf/dlite/utils"
)

type RebuildCommand struct {
	Disk   int    `short:"d" long:"disk" description:"size of disk to create" default:"30"`
	SSHKey string `short:"s" long:"ssh-key" description:"path to public ssh key" default:"$HOME/.ssh/id_rsa.pub"`
}

func (c *RebuildCommand) Execute(args []string) error {
	fmap := utils.FunctionMap{}
	fmap["Rebuilding disk image"] = func() error {
		return utils.CreateDisk(c.SSHKey, c.Disk)
	}

	return utils.Spin(fmap)
}

func init() {
	var rebuildCommand RebuildCommand
	cmd.AddCommand("rebuild", "rebuild your vm", "rebuild the disk for your vm to reset any modifications. this will DESTROY ALL DATA inside your vm.", &rebuildCommand)
}

package main

import (
	"github.com/nlf/dlite/utils"
)

type RebuildCommand struct {
	Disk   int    `short:"d" long:"disk" description:"size of disk in GiB to create" default:"30"`
	SSHKey string `short:"s" long:"ssh-key" description:"path to public ssh key" default:"$HOME/.ssh/id_rsa.pub"`
}

func (c *RebuildCommand) Execute(args []string) error {
	fmap := utils.FunctionMap{}
	fmap["Rebuilding disk image"] = func() error {
		return utils.CreateDisk(c.SSHKey, c.Disk)
	}

	return utils.Spin(fmap)
}

func init() {
	var rebuildCommand RebuildCommand
	cmd.AddCommand("rebuild", "rebuild your vm", "rebuild the disk for your vm to reset any modifications. this will DESTROY ALL DATA inside your vm.", &rebuildCommand)
}

Use GiB as default disk size unit


package control

import (
	"fmt"
	"strings"

	"github.com/rancher/os/log"
)

func yes(question string) bool {
	fmt.Printf("%s [y/N]: ", question)
	var line string
	_, err := fmt.Scan(&line)
	if err != nil {
		log.Fatal(err)
	}

	return strings.ToLower(line[0:1]) == "y"
}

package control

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

	"github.com/rancher/os/log"
)

func yes(question string) bool {
	fmt.Printf("%s [y/N]: ", question)
	in := bufio.NewReader(os.Stdin)
	line, err := in.ReadString('\n')
	if err != nil {
		log.Fatal(err)
	}

	return strings.ToLower(line[0:1]) == "y"
}

Use of bufio instead of fmt.Scan for yes function


package core

type ModelId uint16

// These data types are defined in the SunSpec Information Model Specification.
// http://sunspec.org/wp-content/uploads/2015/06/SunSpec-Information-Models-12041.pdf
// In Version 1.8 of the document, the data type definitions can be found on
// page 13.

type Acc16 uint16
type Enum16 uint16
type Bitfield16 uint16
type Pad uint16

type Acc32 uint32
type Enum32 uint32
type Bitfield32 uint32

type Acc64 uint64

type Ipaddr [4]byte
type Ipv6addr [16]byte

type String []byte

type Float float32

type ScaleFactor int16

package core

type ModelId uint16

// These data types are defined in the SunSpec Information Model Specification.
// http://sunspec.org/wp-content/uploads/2015/06/SunSpec-Information-Models-12041.pdf
// In Version 1.8 of the document, the data type definitions can be found on
// page 13.

type Acc16 uint16
type Enum16 uint16
type Bitfield16 uint16
type Pad uint16

type Acc32 uint32
type Enum32 uint32
type Bitfield32 uint32

type Acc64 uint64

type Ipaddr [4]byte
type Ipv6addr [16]byte
type EUI48 [6]byte

type String []byte

type Float float32

type ScaleFactor int16

type Count uint16

Add two additional types found in the SMDX models.


// Package sockets provides helper functions to create and configure Unix or TCP sockets.
package sockets

import (
	"crypto/tls"
	"net"
)

// NewTCPSocket creates a TCP socket listener with the specified address and
// and the specified tls configuration. If TLSConfig is set, will encapsulate the
// TCP listener inside a TLS one.
func NewTCPSocket(addr string, tlsConfig *tls.Config) (net.Listener, error) {
	l, err := net.Listen("tcp", addr)
	if err != nil {
		return nil, err
	}
	if tlsConfig != nil {
		tlsConfig.NextProtos = []string{"http/1.1"}
		l = tls.NewListener(l, tlsConfig)
	}
	return l, nil
}

// Package sockets provides helper functions to create and configure Unix or TCP sockets.
package sockets

import (
	"crypto/tls"
	"net"
)

// NewTCPSocket creates a TCP socket listener with the specified address and
// the specified tls configuration. If TLSConfig is set, will encapsulate the
// TCP listener inside a TLS one.
func NewTCPSocket(addr string, tlsConfig *tls.Config) (net.Listener, error) {
	l, err := net.Listen("tcp", addr)
	if err != nil {
		return nil, err
	}
	if tlsConfig != nil {
		tlsConfig.NextProtos = []string{"http/1.1"}
		l = tls.NewListener(l, tlsConfig)
	}
	return l, nil
}

Remove duplicate "and" in GoDoc


// Test that blank imports in library packages are flagged.

// Package foo ...
package foo

// The instructions need to go before the imports below so they will not be
// mistaken for documentation.

/* MATCH /blank import/ */ import _ "encoding/json"

import (
	"fmt"
	/* MATCH /blank import/ */ _ "os"

	/* MATCH /blank import/ */ _ "net/http"
	_ "path"
)

import _ "encoding/base64" // Don't gripe about this

import (
	// Don't gripe about these next two lines.
	_ "compress/zlib"
	_ "syscall"

	/* MATCH /blank import/ */ _ "path/filepath"
)

import (
	"go/ast"
	_ "go/scanner" // Don't gripe about this or the following line.
	_ "go/token"
)

Add a blank line in a test so that gofmt won't break the magic comment's location.


package assets

import (
	"testing"
	"time"

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

func TestMain(t *testing.T) {
	Convey("ETags generated on startup", t, func() {
		So(etags, ShouldHaveLength, len(_bindata))

		tag, err := GetAssetETag("path/doesnt/exist")
		So(tag, ShouldBeEmpty)
		So(err, ShouldEqual, ErrETagNotFound)

		_bindata["path/does/exist"] = func() (*asset, error) {
			return &asset{
				bytes: []byte("test"),
				info:  bindataFileInfo{"test", 4, 0600, time.Now()},
			}, nil
		}

		updateETags()

		tag, err = GetAssetETag("path/does/exist")
		So(tag, ShouldEqual, `W/"4-D87F7E0C"`)
		So(err, ShouldBeNil)
	})
}

package assets

import (
	"os"
	"testing"
	"time"

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

type testBindataFileInfo struct {
	name    string
	size    int64
	mode    os.FileMode
	modTime time.Time
}

func (fi testBindataFileInfo) Name() string {
	return fi.name
}
func (fi testBindataFileInfo) Size() int64 {
	return fi.size
}
func (fi testBindataFileInfo) Mode() os.FileMode {
	return fi.mode
}
func (fi testBindataFileInfo) ModTime() time.Time {
	return fi.modTime
}
func (fi testBindataFileInfo) IsDir() bool {
	return false
}
func (fi testBindataFileInfo) Sys() interface{} {
	return nil
}

func TestMain(t *testing.T) {
	Convey("ETags generated on startup", t, func() {
		So(etags, ShouldHaveLength, len(_bindata))

		tag, err := GetAssetETag("path/doesnt/exist")
		So(tag, ShouldBeEmpty)
		So(err, ShouldEqual, ErrETagNotFound)

		_bindata["path/does/exist"] = func() (*asset, error) {
			return &asset{
				bytes: []byte("test"),
				info:  testBindataFileInfo{"test", 4, 0600, time.Now()},
			}, nil
		}

		updateETags()

		tag, err = GetAssetETag("path/does/exist")
		So(tag, ShouldEqual, `W/"4-D87F7E0C"`)
		So(err, ShouldBeNil)
	})
}

Fix assets test for debug version generated files


package main

import (
	"io"
	"net"
)

func chkfatal(err error) {
	if err != nil {
		panic(err)
	}
}

func copyClose(a, b net.Conn) {
	done := make(chan struct{})
	oneWay := func(dst, src net.Conn) {
		io.Copy(dst, src)
		dst.Close()
	}
	go oneWay(a, b)
	go oneWay(b, a)
	<-done
	<-done
}

package main

import (
	"io"
	"net"
)

func chkfatal(err error) {
	if err != nil {
		panic(err)
	}
}

func copyClose(a, b net.Conn) {
	done := make(chan struct{})
	oneWay := func(dst, src net.Conn) {
		io.Copy(dst, src)
		dst.Close()
		done <- struct{}{}
	}
	go oneWay(a, b)
	go oneWay(b, a)
	<-done
	<-done
}

Add missing send in copyClose()


// +build tools

package hotstuff

import (
	_ "github.com/relab/gorums"
	_ "google.golang.org/protobuf/cmd/protoc-gen-go"
)

// +build tools

package examples

import (
	_ "github.com/relab/gorums"
	_ "google.golang.org/protobuf/cmd/protoc-gen-go"
)

Fix package name in examples


package types

import (
	"testing"
)

func TestShapeRetainsRowsAndColumns(t *testing.T) {
	rows, columns := 2, 1

	s := NewShape(rows, columns)

	if s.Rows() == rows && s.Columns() == columns {
		return
	}

	t.Fatal("Shape should retains the rows and columns equivalent to the given ones.")
}

func TestIndexRetainsRowAndColumn(t *testing.T) {
	row, column := 1, 0

	i := NewIndex(row, column)

	if i.Row() == row && i.Column() == column {
		return
	}

	t.Fatal("Index should retains the row and column equivalent to the given ones.")
}

Write test cases for "Shape" and "Index".


package main

import (
	"code.google.com/p/goprotobuf/proto"
	"flag"
	"fmt"
	"github.com/rootsdev/fsbff/fs_data"
	"io/ioutil"
	"log"
	"os"
)

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

func main() {
	var numRecords = flag.Int("n", 10, "number of records to dump")
	flag.Parse()

	file, err := os.Open(flag.Arg(0))
	check(err)
	defer file.Close()

	bytes, err := ioutil.ReadAll(file)
	check(err)

	fsPersons := &fs_data.FamilySearchPersons{}
	err = proto.Unmarshal(bytes, fsPersons)
	check(err)

	for i := 0; i < *numRecords; i++ {
		fmt.Printf("fsPersons[%d]=%+v\n\n", i, fsPersons.Persons[i])
	}
}

package main

import (
	"code.google.com/p/goprotobuf/proto"
	"flag"
	"fmt"
	"github.com/rootsdev/fsbff/fs_data"
	"io/ioutil"
	"log"
	"os"
)

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

func main() {
	var numRecords = flag.Int("n", 10, "number of records to dump")
	var field = flag.String("f", "", "field to dump: [a]ll, [i]d")
	flag.Parse()

	file, err := os.Open(flag.Arg(0))
	check(err)
	defer file.Close()

	bytes, err := ioutil.ReadAll(file)
	check(err)

	fsPersons := &fs_data.FamilySearchPersons{}
	err = proto.Unmarshal(bytes, fsPersons)
	check(err)

	for i := 0; i < *numRecords; i++ {
		switch *field {
		case "i":
			fmt.Printf("%s\n", fsPersons.Persons[i].GetId())
		default:
			fmt.Printf("fsPersons[%d]=%+v\n\n", i, fsPersons.Persons[i])
		}
	}
}

Add flag for dumping a specific field.


package make

import (
	"fmt"
	log "github.com/Sirupsen/logrus"
	"os"
	"strings"
	"time"
)

// InstallFileSystem installs a basic private file system for any given input.
func (Site *Site) InstallFileSystem(DirectoryPath string) {
	// Test the file system, create it if it doesn't exist!
	dirPath := fmt.Sprintf(strings.Join([]string{Site.Path, Site.Domain + ".latest", "sites", Site.Name, DirectoryPath}, "/"))
	_, err := os.Stat(dirPath + "/" + dirPath)
	if err != nil {
		dirErr := os.MkdirAll(dirPath, 0755)
		if dirErr != nil {
			log.Errorln("Couldn't create file system at", dirPath, dirErr)
		} else {
			log.Infoln("Created file system at", dirPath)
			time.Sleep(1 * time.Second)
		}
	}
}

package make

import (
	"fmt"
	log "github.com/Sirupsen/logrus"
	"os"
	"strings"
	"time"
)

// InstallFileSystem installs a basic private file system for any given input.
func (Site *Site) InstallFileSystem(DirectoryPath string) {
	// Test the file system, create it if it doesn't exist!
	dirPath := fmt.Sprintf(strings.Join([]string{Site.Path, Site.TimeStampGet(), "sites", Site.Name, DirectoryPath}, "/"))
	_, err := os.Stat(dirPath + "/" + dirPath)
	if err != nil {
		dirErr := os.MkdirAll(dirPath, 0755)
		if dirErr != nil {
			log.Errorln("Couldn't create file system at", dirPath, dirErr)
		} else {
			log.Infoln("Created file system at", dirPath)
			time.Sleep(1 * time.Second)
		}
	}
}

Change path to install file systems - should not be created inside non-existant folder.


package instagram_scraper

import (
	"net/http"
	"io/ioutil"
	"fmt"
	"encoding/json"
	"log"
)

func GetAccoutByUsername(username string) (account Account) {
	url := fmt.Sprintf(ACCOUNT_JSON_INFO, username)
	info := _GetJsonFromUrl(url)
	account = GetFromAccountPage(info)
	return account
}

func GetMedyaByUrl(url string) (media Media) {
	url += "?__a=1"
	info := _GetJsonFromUrl(url)
	media = GetFromMediaPage(info)
	return
}

func _GetJsonFromUrl(url string) (json_body map[string]interface{}) {
	resp, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	if resp.StatusCode == 404 {
		log.Fatal("Page Not Found, Code 404")
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	err = json.Unmarshal(body, &json_body)
	if err != nil {
		log.Fatal(err)
	}

	return
}

package instagram_scraper

import (
	"net/http"
	"io/ioutil"
	"fmt"
	"encoding/json"
	"log"
)

func GetAccoutByUsername(username string) (account Account) {
	url := fmt.Sprintf(ACCOUNT_JSON_INFO, username)
	info, err := _GetJsonFromUrl(url)
	if err != nil {
		log.Fatal(err)
	}
	account = GetFromAccountPage(info)
	return account
}

func GetMedyaByUrl(url string) (media Media) {
	url += "?__a=1"
	info, err := _GetJsonFromUrl(url)
	if err != nil {
		log.Fatal(err)
	}
	media = GetFromMediaPage(info)
	return
}

func _GetJsonFromUrl(url string) (json_body map[string]interface{}, err error) {
	resp, err := http.Get(url)
	if err != nil || resp.StatusCode == 404 {
		return nil, err
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal(body, &json_body)
	if err != nil {
		return nil, err
	}

	return
}

Change error handling for json function


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

package ptypes

// SwapBits swaps the bits of x at indices i and j, and returns the result.
func SwapBits(x uint64, i, j uint64) uint64 {
	if (x >> i & 1) != (x >> j & 1) {
		x ^= (1<<i | 1<<j)
	}
	return x
}

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

package ptypes

// SwapBits swaps the bits of x at indices i and j, and returns the result.
// The time and space complexity is O(1), independent of word size.
func SwapBits(x uint64, i, j uint64) uint64 {
	if (x >> i & 1) != (x >> j & 1) {
		x ^= (1<<i | 1<<j)
	}
	return x
}

Add time/space complexity analysis to ptypes.SwapBits function


package z80

type MemoryAccessor interface {
	ReadByte(address uint16) byte
	ReadByteInternal(address uint16) byte

	WriteByte(address uint16, value byte)
	WriteByteInternal(address uint16, value byte)

	ContendRead(address uint16, time uint)
	ContendReadNoMreq(address uint16, time uint)
	ContendReadNoMreq_loop(address uint16, time uint, count uint)

	ContendWriteNoMreq(address uint16, time uint)
	ContendWriteNoMreq_loop(address uint16, time uint, count uint)

	Read(address uint16) byte
	Write(address uint16, value byte, protectROM bool)
	Data() *[0x10000]byte
}

type MemoryReader interface {
	ReadByte(address uint16) byte
}

package z80

// MemoryAccessor is an interface to access memory addressed by the
// Z80.
// It defines four read/write method for accessing memory, taking
// into account contention when needed. In systems where memory
// contention is not an issue ReadByte and WriteByte should simply
// call ReadByteInternal and WriteByteInternal.
type MemoryAccessor interface {
	// ReadByte reads a byte from address taking into account
	// contention.
	ReadByte(address uint16) byte

	// ReadByteInternal reads a byte from address without taking
	// into account contetion.
	ReadByteInternal(address uint16) byte

	// WriteByte writes a byte at address taking into account
	// contention.
	WriteByte(address uint16, value byte)

	// WriteByteInternal writes a byte at address without taking
	// into account contention.
	WriteByteInternal(address uint16, value byte)

	// Follow contention methods. Leave unimplemented if you don't
	// care about memory contention.

	// ContendRead increments the Tstates counter by time as a
	// result of a memory read at the given address.
	ContendRead(address uint16, time uint)

	ContendReadNoMreq(address uint16, time uint)
	ContendReadNoMreq_loop(address uint16, time uint, count uint)

	ContendWriteNoMreq(address uint16, time uint)
	ContendWriteNoMreq_loop(address uint16, time uint, count uint)

	Read(address uint16) byte
	Write(address uint16, value byte, protectROM bool)

	// Data returns the memory content.
	Data() []byte
}

// MemoryReader is a simple interface that defines only a ReadByte
// method. It's used mainly by the disassembler.
type MemoryReader interface {
	ReadByte(address uint16) byte
}

Improve documentation of MemoryAccessor interface


package rpcd

import (
	"errors"
	"fmt"
	"github.com/Symantec/Dominator/proto/imageserver"
)

func (t *rpcType) AddImage(request imageserver.AddImageRequest,
	reply *imageserver.AddImageResponse) error {
	if imageDataBase.CheckImage(request.ImageName) {
		return errors.New("image already exists")
	}
	// Verify all objects are available.
	objectServer := imageDataBase.ObjectServer()
	for _, inode := range request.Image.FileSystem.RegularInodeTable {
		found, err := objectServer.CheckObject(inode.Hash)
		if err != nil {
			return err
		}
		if !found {
			return errors.New(fmt.Sprintf("object: %x is not available",
				inode.Hash))
		}
	}
	fmt.Printf("AddImage(%s)\n", request.ImageName) // HACK
	return imageDataBase.AddImage(request.Image, request.ImageName)
}

package rpcd

import (
	"errors"
	"fmt"
	"github.com/Symantec/Dominator/proto/imageserver"
)

func (t *rpcType) AddImage(request imageserver.AddImageRequest,
	reply *imageserver.AddImageResponse) error {
	if imageDataBase.CheckImage(request.ImageName) {
		return errors.New("image already exists")
	}
	// Verify all objects are available.
	objectServer := imageDataBase.ObjectServer()
	for _, inode := range request.Image.FileSystem.RegularInodeTable {
		found, err := objectServer.CheckObject(inode.Hash)
		if err != nil {
			return err
		}
		if !found {
			return errors.New(fmt.Sprintf("object: %x is not available",
				inode.Hash))
		}
	}
	// TODO(rgooch): Remove debugging output.
	fmt.Printf("AddImage(%s)\n", request.ImageName)
	return imageDataBase.AddImage(request.Image, request.ImageName)
}

Change comment about debugging output.


// Copyright 2018 The containerd Authors.
// Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://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 runtimeoptions contains the runtimeoptions proto.
package runtimeoptions

import proto "github.com/gogo/protobuf/proto"

func init() {
	// TODO(gvisor.dev/issue/6449): Upgrade runtimeoptions.proto after upgrading to containerd 1.5
	proto.RegisterType((*Options)(nil), "runtimeoptions.v1.Options")
}

Support runtime options type used in containerd v1.5


package storage

import (
	"testing"

	"os"

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

func TestAWSCredentialsFromConfig(t *testing.T) {
	chain := []*CredentialsProviderConfig{
		{
			Provider: EnvProviderName,
		},
	}

	value := credentials.Value{
		AccessKeyID:     "access-key-1",
		SecretAccessKey: "secret-access-key-1",
		ProviderName:    credentials.EnvProviderName,
	}

	err := os.Setenv("AWS_ACCESS_KEY_ID", value.AccessKeyID)
	assert.NoError(t, err)
	err = os.Setenv("AWS_SECRET_ACCESS_KEY", value.SecretAccessKey)
	assert.NoError(t, err)
	creds, err := AWSCredentialsFromChain(chain)
	assert.NoError(t, err)
	valueOut, err := creds.Get()
	assert.NoError(t, err)
	assert.Equal(t, value, valueOut)
}

func TestDefaultS3Config(t *testing.T) {
	assertStorageConfigSerialisation(t, DefaultS3Config())
}

package storage

import (
	"testing"

	"os"

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

func TestDefaultS3Config(t *testing.T) {
	assertStorageConfigSerialisation(t, DefaultS3Config())
}

Remove redundant test that may leak keys


package s3proxy

import (
	"io"
	"net/http"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/aws/aws-sdk-go/aws"
)

type S3BucketServer struct {
	Bucket string
	sss *s3.S3
}

func NewS3BucketServer(bucketName string, region string) *S3BucketServer {
	return &S3BucketServer{
		Bucket: bucketName,
		sss: s3.New(aws.NewConfig().WithRegion(region)),
	}
}

func (self *S3BucketServer) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	params := s3.GetObjectInput{
		Bucket: aws.String(self.Bucket),
		Key: aws.String(r.URL.Path),
	}
	resp, err := self.sss.GetObject(&params)
	if err != nil {
		// TODO: WAY better error handling
		panic(err)
		return
	}
	rw.WriteHeader(200)
	io.Copy(rw, resp.Body)
}

package s3proxy

import (
	"io"
	"net/http"
	"fmt"
	"github.com/aws/aws-sdk-go/service/s3"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
)

type S3BucketServer struct {
	Bucket string
	sss *s3.S3
}

func NewS3BucketServer(bucketName string, region string) *S3BucketServer {
	return &S3BucketServer{
		Bucket: bucketName,
		sss: s3.New(aws.NewConfig().WithRegion(region)),
	}
}

func (self *S3BucketServer) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	params := s3.GetObjectInput{
		Bucket: aws.String(self.Bucket),
		Key: aws.String(r.URL.Path),
	}
	resp, err := self.sss.GetObject(&params)
	if err != nil {
		azErr := err.(awserr.Error)
		errCode := azErr.Code()
		if errCode == "NoSuchKey" {
			http.NotFound(rw, r)
			return
		}

		rw.WriteHeader(500)
		rw.Write([]byte(fmt.Sprintf("%s: %s", azErr.Code(), azErr.Message())))
		return
	}
	rw.WriteHeader(200)
	io.Copy(rw, resp.Body)
}

Add proper 404 error handling


/*
Copyright 2014 The Kubernetes Authors All rights reserved.

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

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

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

package validation

import (
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/util"
	errs "k8s.io/kubernetes/pkg/util/fielderrors"
)

// ValidateEvent makes sure that the event makes sense.
func ValidateEvent(event *api.Event) errs.ValidationErrorList {
	allErrs := errs.ValidationErrorList{}
	// TODO: There is no namespace required for minion
	if event.InvolvedObject.Kind != "Node" &&
		event.Namespace != event.InvolvedObject.Namespace {
		allErrs = append(allErrs, errs.NewFieldInvalid("involvedObject.namespace", event.InvolvedObject.Namespace, "namespace does not match involvedObject"))
	}
	if !util.IsDNS1123Subdomain(event.Namespace) {
		allErrs = append(allErrs, errs.NewFieldInvalid("namespace", event.Namespace, ""))
	}
	return allErrs
}

/*
Copyright 2014 The Kubernetes Authors All rights reserved.

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

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

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

package validation

import (
	"k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/util"
	errs "k8s.io/kubernetes/pkg/util/fielderrors"
)

// ValidateEvent makes sure that the event makes sense.
func ValidateEvent(event *api.Event) errs.ValidationErrorList {
	allErrs := errs.ValidationErrorList{}
	// TODO: There is no namespace required for node.
	if event.InvolvedObject.Kind != "Node" &&
		event.Namespace != event.InvolvedObject.Namespace {
		allErrs = append(allErrs, errs.NewFieldInvalid("involvedObject.namespace", event.InvolvedObject.Namespace, "namespace does not match involvedObject"))
	}
	if !util.IsDNS1123Subdomain(event.Namespace) {
		allErrs = append(allErrs, errs.NewFieldInvalid("namespace", event.Namespace, ""))
	}
	return allErrs
}

Replace "minion" with "node" in bunch of places.


package json

import (
	"github.com/polydawn/refmt/tok/fixtures"
)

type situation byte

const (
	situationEncoding situation = 0x1
	situationDecoding situation = 0x2
)

var jsonFixtures = []struct {
	title    string
	sequence fixtures.Sequence
	serial   string
	only     situation
}{
	// Strings
	{"",
		fixtures.SequenceMap["empty string"],
		`""`,
		situationEncoding | situationDecoding,
	},

	// Maps
	{"",
		fixtures.SequenceMap["empty map"].SansLengthInfo(),
		`{}`,
		situationEncoding | situationDecoding,
	},

	// Arrays
	{"",
		fixtures.SequenceMap["empty array"].SansLengthInfo(),
		`[]`,
		situationEncoding | situationDecoding,
	},
}

package json

import (
	"github.com/polydawn/refmt/tok/fixtures"
)

type situation byte

const (
	situationEncoding situation = 0x1
	situationDecoding situation = 0x2
)

var jsonFixtures = []struct {
	title    string
	sequence fixtures.Sequence
	serial   string
	only     situation
}{
	// Strings
	{"",
		fixtures.SequenceMap["empty string"],
		`""`,
		situationEncoding | situationDecoding,
	},
	{"decoding with extra whitespace",
		fixtures.SequenceMap["empty string"].SansLengthInfo(),
		`  "" `,
		situationDecoding,
	},

	// Maps
	{"",
		fixtures.SequenceMap["empty map"].SansLengthInfo(),
		`{}`,
		situationEncoding | situationDecoding,
	},
	{"decoding with extra whitespace",
		fixtures.SequenceMap["empty map"].SansLengthInfo(),
		`{  }`,
		situationDecoding,
	},

	// Arrays
	{"",
		fixtures.SequenceMap["empty array"].SansLengthInfo(),
		`[]`,
		situationEncoding | situationDecoding,
	},
	{"decoding with extra whitespace",
		fixtures.SequenceMap["empty array"].SansLengthInfo(),
		`  [ ] `,
		situationDecoding,
	},
}

Test json decoder munching extraneous whitespace correctly.


package agent

import (
	boshvitals "github.com/cloudfoundry/bosh-agent/platform/vitals"
)

type Heartbeat struct {
	Deployment string            `json:"deployment"`
	Job        *string           `json:"job"`
	Index      *int              `json:"index"`
	JobState   string            `json:"job_state"`
	Vitals     boshvitals.Vitals `json:"vitals"`
	NodeID     string            `json:"node_id"`
}

//Heartbeat payload example:
//{
//  "job": "cloud_controller",
//  "index": 3,
//  "job_state":"running",
//  "vitals": {
//    "load": ["0.09","0.04","0.01"],
//    "cpu": {"user":"0.0","sys":"0.0","wait":"0.4"},
//    "mem": {"percent":"3.5","kb":"145996"},
//    "swap": {"percent":"0.0","kb":"0"},
//    "disk": {
//      "system": {"percent" => "82"},
//      "ephemeral": {"percent" => "5"},
//      "persistent": {"percent" => "94"}
//    },
//  "ntp": {
//      "offset": "-0.06423",
//      "timestamp": "14 Oct 11:13:19"
//  }
//}

package agent

import (
	boshvitals "github.com/cloudfoundry/bosh-agent/platform/vitals"
)

// NodeID is no longer being used by the director as of completion of
// https://www.pivotaltracker.com/story/show/132265151

type Heartbeat struct {
	Deployment string            `json:"deployment"`
	Job        *string           `json:"job"`
	Index      *int              `json:"index"`
	JobState   string            `json:"job_state"`
	Vitals     boshvitals.Vitals `json:"vitals"`
	NodeID     string            `json:"node_id"`
}

//Heartbeat payload example:
//{
//  "job": "cloud_controller",
//  "index": 3,
//  "job_state":"running",
//  "vitals": {
//    "load": ["0.09","0.04","0.01"],
//    "cpu": {"user":"0.0","sys":"0.0","wait":"0.4"},
//    "mem": {"percent":"3.5","kb":"145996"},
//    "swap": {"percent":"0.0","kb":"0"},
//    "disk": {
//      "system": {"percent" => "82"},
//      "ephemeral": {"percent" => "5"},
//      "persistent": {"percent" => "94"}
//    },
//  "ntp": {
//      "offset": "-0.06423",
//      "timestamp": "14 Oct 11:13:19"
//  }
//}

Add comment noting removal of NodeID handling in director


// Copyright 2012 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 ignore

package main

import "code.google.com/p/go-tour-french/pic"

func Pic(dx, dy int) [][]uint8 {
	p := make([][]uint8, dy)
	for i := range p {
		p[i] = make([]uint8, dx)
	}

	for y, row := range p {
		for x := range row {
			row[x] = uint8(x * y)
		}
	}

	return p
}

func main() {
	pic.Show(Pic)
}

// Copyright 2012 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 ignore

package main

import "github.com/dupoxy/go-tour-fr/pic"

func Pic(dx, dy int) [][]uint8 {
	p := make([][]uint8, dy)
	for i := range p {
		p[i] = make([]uint8, dx)
	}

	for y, row := range p {
		for x := range row {
			row[x] = uint8(x * y)
		}
	}

	return p
}

func main() {
	pic.Show(Pic)
}

Update imports from googlecode to github


package generator

import "os"

// Generator is in charge of generating files for packages.
type Generator struct {
	filename string
}

// NewGenerator creates a new generator that can save on the given filename.
func NewGenerator(filename string) *Generator {
	return &Generator{filename}
}

// Generate writes the file with the contents of the given package.
func (g *Generator) Generate(pkg *Package) error {
	return g.writeFile(pkg)
}

func (g *Generator) writeFile(pkg *Package) error {
	file, err := os.Create(g.filename)
	if err != nil {
		return err
	}

	defer file.Close()
	return Base.Execute(file, pkg)
}

package generator

import (
	"fmt"
	"os"
)

// Generator is in charge of generating files for packages.
type Generator struct {
	filename string
}

// NewGenerator creates a new generator that can save on the given filename.
func NewGenerator(filename string) *Generator {
	return &Generator{filename}
}

// Generate writes the file with the contents of the given package.
func (g *Generator) Generate(pkg *Package) error {
	return g.writeFile(pkg)
}

func (g *Generator) writeFile(pkg *Package) (err error) {
	file, err := os.Create(g.filename)
	if err != nil {
		return err
	}

	defer func() {
		file.Close()
		if err != nil {
			fmt.Println()
			fmt.Println("kallax: No file generated due to an occurred error:")
			os.Remove(g.filename)
		}
	}()

	return Base.Execute(file, pkg)
}

Delete autogenerated kallax.go if generation failed


package randstr

import (
	"crypto/rand"
	"io"
)

// New generates a new random string of length given, using only the characters given in runes.
func New(length int, runes []rune) string {
	password := make([]rune, length)

	runesCount := len(runes)
	byteCount := byteLen(runesCount)
	bytes := make([]byte, byteCount)

	for i := 0; i < length; i++ {
		io.ReadFull(rand.Reader, bytes)

		n := bytesToInt(bytes)
		if n < 0 {
			n = -n
		}
		n = n % runesCount

		password[i] = runes[n]
	}

	return string(password)
}

package randstr

import (
	"crypto/rand"
	"io"
)

// New generates a new random string of length given, using only the characters given in runes.
func New(length int, runes []rune) string {
	s := make([]rune, length)

	runesCount := len(runes)
	byteCount := byteLen(runesCount)
	bytes := make([]byte, byteCount)

	for i := 0; i < length; i++ {
		io.ReadFull(rand.Reader, bytes)

		n := bytesToInt(bytes)
		if n < 0 {
			n = -n
		}
		n = n % runesCount

		s[i] = runes[n]
	}

	return string(s)
}

Rename `password` to `s` in `New`.


// +build !windows,!plan9,!js

package eval

import (
	"testing"

	"github.com/elves/elvish/pkg/tt"
)

func TestExternalCmdExit_Error(t *testing.T) {
	tt.Test(t, tt.Fn("Error", error.Error), tt.Table{
		tt.Args(ExternalCmdExit{0, "ls", 100}).Rets("ls exited with 0"),
	})
}

// +build !windows,!plan9,!js

package eval

import (
	"fmt"
	"syscall"
	"testing"

	"github.com/elves/elvish/pkg/tt"
)

func TestExternalCmdExit_Error(t *testing.T) {
	tt.Test(t, tt.Fn("Error", error.Error), tt.Table{
		tt.Args(ExternalCmdExit{0x0, "ls", 1}).Rets("ls exited with 0"),
		tt.Args(ExternalCmdExit{0x100, "ls", 1}).Rets("ls exited with 1"),
		// Note: all Unix'es have SIGINT = 2 and the syscall package has same
		// string for it ("interrupt").
		tt.Args(ExternalCmdExit{0x2, "ls", 1}).Rets("ls killed by signal interrupt"),
		// 0x80 + signal for core dumped
		tt.Args(ExternalCmdExit{0x82, "ls", 1}).Rets("ls killed by signal interrupt (core dumped)"),
		// 0x7f + signal<<8 for stopped
		tt.Args(ExternalCmdExit{0x27f, "ls", 1}).Rets("ls stopped by signal interrupt (pid=1)"),
		// 0x057f + cause<<16 for trapped. SIGTRAP is 5 on all Unix'es but have
		// different string representations on different OSes.
		tt.Args(ExternalCmdExit{0x1057f, "ls", 1}).Rets(fmt.Sprintf(
			"ls stopped by signal %s (pid=1) (trapped 1)", syscall.SIGTRAP)),
		// 0xff is the only exit code that is not exited, signaled or stopped.
		tt.Args(ExternalCmdExit{0xff, "ls", 1}).Rets("ls has unknown WaitStatus 255"),
	})
}

Test all branches of ExternalCmdExit.Error.


package main

import (
	"image/color"

	"engo.io/ecs"
	"engo.io/engo/common"
)

type game struct{}

func (g *game) Type() string { return sceneGame }
func (g *game) Preload()     {}
func (g *game) Setup(*ecs.World) {

	common.SetBackground(color.White)
}

package main

import (
	"image/color"

	"engo.io/ecs"
	"engo.io/engo"
	"engo.io/engo/common"
)

const buttonOpenMenu = "OpenMenu"

type game struct{}

func (g *game) Type() string { return sceneGame }
func (g *game) Preload()     {}
func (g *game) Setup(world *ecs.World) {

	engo.Input.RegisterButton(buttonOpenMenu, engo.Escape)

	common.SetBackground(color.White)
	world.AddSystem(&common.RenderSystem{})
	world.AddSystem(&inputSystem{})
}

type inputSystem struct{}

// Update is ran every frame, with `dt` being the time
// in seconds since the last frame
func (is *inputSystem) Update(float32) {
	if engo.Input.Button(buttonOpenMenu).JustPressed() {
		engo.SetSceneByName(sceneMainMenu, true)
	}
}

// Remove is called whenever an Entity is removed from the World, in order to remove it from this sytem as well
func (is *inputSystem) Remove(ecs.BasicEntity) {}

Add scene change to mainmenu on esc


package provider

import (
	"github.com/hashicorp/terraform-plugin-framework/providerserver"
	"github.com/hashicorp/terraform-plugin-go/tfprotov5"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func protoV5ProviderFactories() map[string]func() (tfprotov5.ProviderServer, error) {
	return map[string]func() (tfprotov5.ProviderServer, error){
		"null": providerserver.NewProtocol5WithError(New()),
	}
}

func providerVersion311() map[string]resource.ExternalProvider {
	return map[string]resource.ExternalProvider{
		"time": {
			VersionConstraint: "3.1.1",
			Source:            "hashicorp/null",
		},
	}
}

package provider

import (
	"github.com/hashicorp/terraform-plugin-framework/providerserver"
	"github.com/hashicorp/terraform-plugin-go/tfprotov5"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func protoV5ProviderFactories() map[string]func() (tfprotov5.ProviderServer, error) {
	return map[string]func() (tfprotov5.ProviderServer, error){
		"null": providerserver.NewProtocol5WithError(New()),
	}
}

func providerVersion311() map[string]resource.ExternalProvider {
	return map[string]resource.ExternalProvider{
		"null": {
			VersionConstraint: "3.1.1",
			Source:            "hashicorp/null",
		},
	}
}

Fix typo in retrieving external provider


package main

import (
	"github.com/42wim/mm-go-irckit"
	"github.com/alexcesaro/log"
	"github.com/alexcesaro/log/golog"
	"net"
	"os"
)

var logger log.Logger = log.NullLogger

func main() {
	logger = golog.New(os.Stderr, log.Debug)
	irckit.SetLogger(logger)

	socket, err := net.Listen("tcp", "127.0.0.1:6667")
	if err != nil {
		logger.Errorf("Failed to listen on socket: %v\n", err)
	}
	defer socket.Close()

	start(irckit.NewServer("matterircd"), socket)
}

func start(srv irckit.Server, socket net.Listener) {
	for {
		conn, err := socket.Accept()
		if err != nil {
			logger.Errorf("Failed to accept connection: %v", err)
			return
		}

		go func() {
			logger.Infof("New connection: %s", conn.RemoteAddr())
			err = srv.Connect(irckit.NewUserMM(conn, srv))
			if err != nil {
				logger.Errorf("Failed to join: %v", err)
				return
			}
		}()
	}
}

package main

import (
	"github.com/42wim/mm-go-irckit"
	"github.com/alexcesaro/log"
	"github.com/alexcesaro/log/golog"
	"net"
	"os"
)

var logger log.Logger = log.NullLogger

func main() {
	logger = golog.New(os.Stderr, log.Debug)
	irckit.SetLogger(logger)

	socket, err := net.Listen("tcp", "127.0.0.1:6667")
	if err != nil {
		logger.Errorf("Failed to listen on socket: %v\n", err)
	}
	defer socket.Close()

	start(socket)
}

func start(socket net.Listener) {
	for {
		conn, err := socket.Accept()
		if err != nil {
			logger.Errorf("Failed to accept connection: %v", err)
			return
		}

		go func() {
			newsrv := irckit.NewServer("matterircd")
			logger.Infof("New connection: %s", conn.RemoteAddr())
			err = newsrv.Connect(irckit.NewUserMM(conn, newsrv))
			if err != nil {
				logger.Errorf("Failed to join: %v", err)
				return
			}
		}()
	}
}

Create different server per user/connection


package pongo2

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	p2 "github.com/flosch/pongo2"
	"sync"
)

type Context map[string]interface{}

var templates = map[string]*p2.Template{}
var mutex = &sync.RWMutex{}

var devMode = beego.AppConfig.String("runmode") == "dev"

// Render takes a Beego context, template name and a Context (map[string]interface{}).
// The template is parsed and cached, and gets executed into beegoCtx's ResponseWriter.
//
// Templates are looked up in `templates/` instead of Beego's default `views/` so that
// Beego doesn't attempt to load and parse our templates with `html/template`.
func Render(beegoCtx *context.Context, tmpl string, ctx Context) {
	mutex.RLock()
	template, ok := templates[tmpl]
	mutex.RUnlock()

	if !ok || devMode {
		var err error
		template, err = p2.FromFile("templates/" + tmpl)
		if err != nil {
			panic(err)
		}
		mutex.Lock()
		templates[tmpl] = template
		mutex.Unlock()
	}

	err := template.ExecuteRW(beegoCtx.ResponseWriter, p2.Context(ctx))
	if err != nil {
		panic(err)
	}
}

package pongo2

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	p2 "github.com/flosch/pongo2"
	"sync"
)

type Context map[string]interface{}

var templates = map[string]*p2.Template{}
var mutex = &sync.RWMutex{}

var devMode bool

// Render takes a Beego context, template name and a Context (map[string]interface{}).
// The template is parsed and cached, and gets executed into beegoCtx's ResponseWriter.
//
// Templates are looked up in `templates/` instead of Beego's default `views/` so that
// Beego doesn't attempt to load and parse our templates with `html/template`.
func Render(beegoCtx *context.Context, tmpl string, ctx Context) {
	mutex.RLock()
	template, ok := templates[tmpl]
	mutex.RUnlock()

	if !ok || devMode {
		var err error
		template, err = p2.FromFile("templates/" + tmpl)
		if err != nil {
			panic(err)
		}
		mutex.Lock()
		templates[tmpl] = template
		mutex.Unlock()
	}

	err := template.ExecuteRW(beegoCtx.ResponseWriter, p2.Context(ctx))
	if err != nil {
		panic(err)
	}
}

func init() {
	devMode = beego.AppConfig.String("runmode") == "dev"
	beego.AutoRender = false
}

Disable autorender for Beego when beego-pongo2 is imported.


package reset

import (
	"os"
	"strings"
	"sync"
)

var (
	testModeOnce = sync.Once{}
	_testMode    bool
)

// TestMode returns true if run as unit test
func TestMode() bool {
	testModeOnce.Do(func() {
		_testMode = strings.HasSuffix(os.Args[0], ".test")
	})
	return _testMode
}

package reset

import (
	"io/ioutil"
	"log"
	"os"
	"strings"
	"sync"
)

var (
	testModeOnce = sync.Once{}
	_testMode    bool
)

// TestMode returns true if run as unit test
func TestMode() bool {
	testModeOnce.Do(func() {
		_testMode = strings.HasSuffix(os.Args[0], ".test")

		if _testMode {
			log.SetOutput(ioutil.Discard)
		}
	})
	return _testMode
}

Drop logging output in test mode


package model_validator

import (
	"fmt"
	"github.com/asaskevich/govalidator"
	"github.com/centurylinkcloud/clc-go-cli/base"
	"strings"
)

func ValidateModel(model interface{}) error {
	_, err := govalidator.ValidateStruct(model)
	if err != nil {
		var msg string
		parts := strings.Split(err.Error(), ";")
		errors := parts[:len(parts)-1]
		for _, fieldErr := range errors {
			msg += fmt.Sprintf("%s\n", fieldErr)
		}
		return fmt.Errorf(msg)
	}
	if m, ok := model.(base.ValidatableModel); ok {
		err = m.Validate()
	}
	return err
}

package model_validator

import (
	"fmt"
	"github.com/asaskevich/govalidator"
	"github.com/centurylinkcloud/clc-go-cli/base"
	"strings"
)

func ValidateModel(model interface{}) error {
	_, err := govalidator.ValidateStruct(model)
	if err != nil {
		parts := strings.Split(err.Error(), ";")
		errors := parts[:len(parts)-1]
		return fmt.Errorf(strings.Join(errors, "\n"))
	}
	if m, ok := model.(base.ValidatableModel); ok {
		err = m.Validate()
	}
	return err
}

Remove an extra newline from the model validation errors.


package httpimg_test

import (
	"github.com/jung-kurt/gofpdf"
	"github.com/jung-kurt/gofpdf/contrib/httpimg"
	"github.com/jung-kurt/gofpdf/internal/example"
)

func ExampleRegister() {
	pdf := gofpdf.New("", "", "", "")
	pdf.SetFont("Helvetica", "", 12)
	pdf.SetFillColor(200, 200, 220)
	pdf.AddPage()

	url := "https://github.com/jung-kurt/gofpdf/raw/master/image/logo_gofpdf.jpg?raw=true"
	httpimg.Register(pdf, url, "")
	pdf.Image(url, 100, 100, 20, 20, false, "", 0, "")

	fileStr := example.Filename("contrib_httpimg_Register")
	err := pdf.OutputFileAndClose(fileStr)
	example.Summary(err, fileStr)
	// Output:
	// Successfully generated ../../pdf/contrib_httpimg_Register.pdf
}

package httpimg_test

import (
	"github.com/jung-kurt/gofpdf"
	"github.com/jung-kurt/gofpdf/contrib/httpimg"
	"github.com/jung-kurt/gofpdf/internal/example"
)

func ExampleRegister() {
	pdf := gofpdf.New("L", "mm", "A4", "")
	pdf.SetFont("Helvetica", "", 12)
	pdf.SetFillColor(200, 200, 220)
	pdf.AddPage()

	url := "https://github.com/jung-kurt/gofpdf/raw/master/image/logo_gofpdf.jpg?raw=true"
	httpimg.Register(pdf, url, "")
	pdf.Image(url, 15, 15, 267, 0, false, "", 0, "")
	fileStr := example.Filename("contrib_httpimg_Register")
	err := pdf.OutputFileAndClose(fileStr)
	example.Summary(err, fileStr)
	// Output:
	// Successfully generated ../../pdf/contrib_httpimg_Register.pdf
}

Maintain aspect ratio of registered image


package go_camunda_client

type CamundaClient interface {
	StartProcess(processDefinitionKey string, request interface{}) (Process, error)
	GetProcess(processId string) (Process, error)
	GetProcessVariable(processId string, variableName string) (VariableResponse, error)
	GetNextTask(processId string) (Task, error)
	GetAllTasks(processId string) ([]Task, error)
	CompleteTask(taskId string, request interface{}) (error)
	GetTaskVariable(taskId string, variableName string) (VariableResponse, error)
	HandleErrors(errorCallback func(error))
}

type Process interface {
	GetId() string
	IsEnded() bool
}

type Task interface {
	GetId() string
	GetName() string
	GetTaskDefinitionKey() string
}

type VariableResponse interface {
	GetValue() string
}

package go_camunda_client

type CamundaClient interface {
	StartProcess(processDefinitionKey string, request interface{}) (Process, error)
	GetProcess(processId string) (Process, error)
	FindProcess(query string) (Process, error)
	GetProcessVariable(processId string, variableName string) (VariableResponse, error)
	GetNextTask(processId string) (Task, error)
	GetAllTasks(processId string) ([]Task, error)
	CompleteTask(taskId string, request interface{}) (error)
	GetTaskVariable(taskId string, variableName string) (VariableResponse, error)
	HandleErrors(errorCallback func(error))
}

type Process interface {
	GetId() string
	IsEnded() bool
}

type Task interface {
	GetId() string
	GetName() string
	GetTaskDefinitionKey() string
}

type VariableResponse interface {
	GetValue() string
}

Add FindProcess to CamundaClient interface


package main

import (
	"time"
)

// Deployment describes a deployment
type Deployment struct {
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"created_at"`
	ImageName string    `json:"image_name"`
	Version   string    `json:"version"`
	Priority  int       `json:"priority"`
	State     string    `json:"status"`
	LogKey    string    `json:"-"`
}

// Config for the deployment system for a user.
type Config struct {
	RepoURL        string `json:"repo_url" yaml:"repo_url"`
	RepoPath       string `json:"repo_path" yaml:"repo_path"`
	RepoKey        string `json:"repo_key" yaml:"repo_key"`
	KubeconfigPath string `json:"kubeconfig_path" yaml:"kubeconfig_path"`

	Notifications []NotificationConfig `json:"notifications" yaml:"notifications"`
}

// NotificationConfig describes how to send notifications
type NotificationConfig struct {
	SlackWebhookURL string `json:"slack_webhook_url" yaml:"slack_webhook_url"`
	SlackUsername   string `json:"slack_username" yaml:"slack_username"`
}

package main

import (
	"time"
)

// Deployment describes a deployment
type Deployment struct {
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"created_at"`
	ImageName string    `json:"image_name"`
	Version   string    `json:"version"`
	Priority  int       `json:"priority"`
	State     string    `json:"status"`
	LogKey    string    `json:"-"`
}

// Config for the deployment system for a user.
type Config struct {
	RepoURL        string `json:"repo_url" yaml:"repo_url"`
	RepoPath       string `json:"repo_path" yaml:"repo_path"`
	RepoKey        string `json:"repo_key" yaml:"repo_key"`
	KubeconfigPath string `json:"kubeconfig_path" yaml:"kubeconfig_path"`

	Notifications []NotificationConfig `json:"notifications" yaml:"notifications"`

	// Globs of files not to change, relative to the route of the repo
	ConfigFileBlackList []string `json:"config_file_black_list" yaml:"config_file_black_list"`
}

// NotificationConfig describes how to send notifications
type NotificationConfig struct {
	SlackWebhookURL string `json:"slack_webhook_url" yaml:"slack_webhook_url"`
	SlackUsername   string `json:"slack_username" yaml:"slack_username"`
}

Add blacklist to wcloud client


/*
 *
 * k6 - a next-generation load testing tool
 * Copyright (C) 2020 Load Impact
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package executor

import "github.com/loadimpact/k6/stats"

func sumMetricValues(samples chan stats.SampleContainer, metricName string) (sum float64) {
	bufferedSmaples := stats.GetBufferedSamples(samples)
	for _, sc := range bufferedSmaples {
		samples := sc.GetSamples()
		for _, s := range samples {
			if s.Metric.Name == metricName {
				sum += s.Value
			}
		}
	}
	return sum
}

/*
 *
 * k6 - a next-generation load testing tool
 * Copyright (C) 2020 Load Impact
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

package executor

import "github.com/loadimpact/k6/stats"

func sumMetricValues(samples chan stats.SampleContainer, metricName string) (sum float64) {
	for _, sc := range stats.GetBufferedSamples(samples) {
		samples := sc.GetSamples()
		for _, s := range samples {
			if s.Metric.Name == metricName {
				sum += s.Value
			}
		}
	}
	return sum
}

Fix a typo by simplifying the code


package humanlog

import (
	"regexp"
)

// dcLogsPrefixRe parses out a prefix like 'web_1 | ' from docker-compose
var dcLogsPrefixRe = regexp.MustCompile("^(?:\x1b\\[\\d+m)?([a-zA-Z0-9._-]+)\\s+\\|(?:\x1b\\[0m)? (.*)$")

type handler interface {
	TryHandle([]byte) bool
	setField(key, val []byte)
}

func tryDockerComposePrefix(d []byte, nextHandler handler) bool {
	if matches := dcLogsPrefixRe.FindSubmatch(d); matches != nil {
		if nextHandler.TryHandle(matches[2]) {
			nextHandler.setField([]byte(`service`), matches[1])
			return true
		}
	}
	return false
}

package humanlog

import (
	"regexp"
)

// dcLogsPrefixRe parses out a prefix like 'web_1 | ' from docker-compose
var dcLogsPrefixRe = regexp.MustCompile("^(?:\x1b\\[\\d+m)?(?P<service_name>[a-zA-Z0-9._-]+)\\s+\\|(?:\x1b\\[0m)? (?P<rest_of_line>.*)$")

type handler interface {
	TryHandle([]byte) bool
	setField(key, val []byte)
}

func tryDockerComposePrefix(d []byte, nextHandler handler) bool {
	if matches := dcLogsPrefixRe.FindSubmatch(d); matches != nil {
		if nextHandler.TryHandle(matches[2]) {
			nextHandler.setField([]byte(`service`), matches[1])
			return true
		}
	}
	return false
}

Add names to capture groups


package statsd

import (
	"time"

	"github.com/tecnickcom/statsd"
)

type MetricsService struct {
	statsdClient *statsd.Client
	prefix       string
}

func NewMetricsService() *MetricsService {
	statsdClient, e := statsd.New() // Connect to the UDP port 8125 by default.
	if e != nil {
		panic(e)
	}
	return &MetricsService{statsdClient: statsdClient, prefix: "bits."}
}

func (service *MetricsService) SendTimingMetric(name string, duration time.Duration) {
	service.statsdClient.Timing(service.prefix+name, duration.Seconds()*1000)
}
func (service *MetricsService) SendGaugeMetric(name string, value int64) {
	service.statsdClient.Gauge(service.prefix+name, value)
}

func (service *MetricsService) SendCounterMetric(name string, value int64) {
	service.statsdClient.Count(service.prefix+name, value)
}

package statsd

import (
	"time"

	"github.com/tecnickcom/statsd"
)

type MetricsService struct {
	statsdClient *statsd.Client
	prefix       string
}

func NewMetricsService() *MetricsService {
	statsdClient, e := statsd.New() // Connect to the UDP port 8125 by default.
	if e != nil {
		panic(e)
	}
	return &MetricsService{statsdClient: statsdClient, prefix: "bits."}
}

func (service *MetricsService) SendTimingMetric(name string, duration time.Duration) {
	service.statsdClient.Timing(service.prefix+name, duration.Seconds()*1000)
	// we send this additional metric, because our test envs use metrics.ng.bluemix.net
	// and for aggregation purposes this service needs this suffix.
	service.statsdClient.Timing(service.prefix+name+".sparse-avg", duration.Seconds()*1000)
}
func (service *MetricsService) SendGaugeMetric(name string, value int64) {
	service.statsdClient.Gauge(service.prefix+name, value)
}

func (service *MetricsService) SendCounterMetric(name string, value int64) {
	service.statsdClient.Count(service.prefix+name, value)
}

Add new timing metric with .sparse-avg suffix


package sudoku

import (
	"fmt"
)

type SolveDirections []*SolveStep

const (
	ONLY_LEGAL_NUMBER = iota
)

type SolveStep struct {
	Row       int
	Col       int
	Num       int
	Technique SolveTechnique
}

type SolveTechnique interface {
	Name() string
	Description(*SolveStep) string
	Apply(*Grid) *SolveStep
}

var techniques []SolveTechnique

func init() {
	//TODO: init techniques with enough space
	techniques = append(techniques, onlyLegalNumberTechnique{})
}

type onlyLegalNumberTechnique struct {
}

func (self onlyLegalNumberTechnique) Name() string {
	return "Only Legal Number"
}

func (self onlyLegalNumberTechnique) Description(step *SolveStep) string {
	return fmt.Sprintf("%d is the only remaining valid number for that cell", step.Num)
}

func (self onlyLegalNumberTechnique) Apply(grid *Grid) *SolveStep {
	grid.refillQueue()
	//This will be a random item
	obj := grid.queue.NewGetter().GetSmallerThan(2)
	if obj == nil {
		//There weren't any cells with one option.
		return nil
	}
	cell := obj.(*Cell)

	cell.SetNumber(cell.implicitNumber())
	return &SolveStep{cell.Row, cell.Col, cell.Number(), self}
}

func (self *Grid) HumanSolve() *SolveDirections {
	return nil
}

package sudoku

import (
	"fmt"
)

type SolveDirections []*SolveStep

const (
	ONLY_LEGAL_NUMBER = iota
)

type SolveStep struct {
	Row       int
	Col       int
	Num       int
	Technique SolveTechnique
}

type SolveTechnique interface {
	Name() string
	Description(*SolveStep) string
	Apply(*Grid) *SolveStep
}

var techniques []SolveTechnique

func init() {
	//TODO: init techniques with enough space
	techniques = append(techniques, onlyLegalNumberTechnique{})
}

type onlyLegalNumberTechnique struct {
}

func (self onlyLegalNumberTechnique) Name() string {
	return "Only Legal Number"
}

func (self onlyLegalNumberTechnique) Description(step *SolveStep) string {
	return fmt.Sprintf("%d is the only remaining valid number for that cell", step.Num)
}

func (self onlyLegalNumberTechnique) Apply(grid *Grid) *SolveStep {
	//This will be a random item
	obj := grid.queue.NewGetter().GetSmallerThan(2)
	if obj == nil {
		//There weren't any cells with one option.
		return nil
	}
	cell := obj.(*Cell)

	cell.SetNumber(cell.implicitNumber())
	return &SolveStep{cell.Row, cell.Col, cell.Number(), self}
}

func (self *Grid) HumanSolve() *SolveDirections {
	return nil
}

Remove refillQueue now that cells reinsert themselves when their number changes from 0 or not.


/*
Copyright The Kubernetes Authors.

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

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

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

// Code generated by informer-gen. DO NOT EDIT.

package internalinterfaces

import (
	time "time"

	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	runtime "k8s.io/apimachinery/pkg/runtime"
	cache "k8s.io/client-go/tools/cache"
	versioned "k8s.io/sample-controller/pkg/client/clientset/versioned"
)

type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer

// SharedInformerFactory a small interface to allow for adding an informer without an import cycle
type SharedInformerFactory interface {
	Start(stopCh <-chan struct{})
	InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer
}

type TweakListOptionsFunc func(*v1.ListOptions)

/*
Copyright The Kubernetes Authors.

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

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

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

// Code generated by informer-gen. DO NOT EDIT.

package internalinterfaces

import (
	time "time"

	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	runtime "k8s.io/apimachinery/pkg/runtime"
	cache "k8s.io/client-go/tools/cache"
	versioned "k8s.io/sample-controller/pkg/client/clientset/versioned"
)

// NewInformerFunc takes versioned.Interface and time.Duration to return a SharedIndexInformer.
type NewInformerFunc func(versioned.Interface, time.Duration) cache.SharedIndexInformer

// SharedInformerFactory a small interface to allow for adding an informer without an import cycle
type SharedInformerFactory interface {
	Start(stopCh <-chan struct{})
	InformerFor(obj runtime.Object, newFunc NewInformerFunc) cache.SharedIndexInformer
}

// TweakListOptionsFunc is a function that transforms a v1.ListOptions.
type TweakListOptionsFunc func(*v1.ListOptions)

Fix golint errors when generating informer code


package cli_test

import (
	"regexp"
	"testing"
)

func TestCreate(t *testing.T) {
	run(t, []Command{
		{
			"apps",
			"",
		},
		{
			"create acme-inc",
			"Created acme-inc.",
		},
	})
}

func TestApps(t *testing.T) {
	run(t, []Command{
		{
			"create acme-inc",
			"Created acme-inc.",
		},
		{
			"apps",
			"acme-inc      Dec 31 17:01",
		},
	})
}

func TestAppInfo(t *testing.T) {
	regex, err := regexp.Compile("Name: acme-inc\nID:   [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\n")
	if err != nil {
		t.Fatal(err)
	}

	run(t, []Command{
		{
			"create acme-inc",
			"Created acme-inc.",
		},
		{
			"info -a acme-inc",
			regex,
		},
	})
}

package cli_test

import (
	"regexp"
	"testing"
)

func TestCreate(t *testing.T) {
	run(t, []Command{
		{
			"apps",
			"",
		},
		{
			"create acme-inc",
			"Created acme-inc.",
		},
	})
}

func TestApps(t *testing.T) {
	run(t, []Command{
		{
			"create acme-inc",
			"Created acme-inc.",
		},
		{
			"apps",
			"acme-inc      Dec 31 17:01",
		},
	})
}

func TestAppInfo(t *testing.T) {
	run(t, []Command{
		{
			"create acme-inc",
			"Created acme-inc.",
		},
		{
			"info -a acme-inc",
			regexp.MustCompile("Name: acme-inc\nID:   [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\n"),
		},
	})
}

Use regexp.MustCompile() instead of regexp.Compile().


package proof

import (
	"hash"
	"io"
)

type Reader32 struct {
	r   io.Reader
	h   hash.Hash32
	sum uint32
}

func NewReader32(r io.reader, h hash.Hash32, sum uint32) {
	// WIP
}

func (r *Reader32) Read(p []byte) (int, error) {
	// WIP
}

package proof

import (
	"errors"
	"hash"
	"io"
)

var EHASHFAIL error = errors.New("checksum mismatch")

type Reader32 struct {
	r   io.Reader
	h   hash.Hash32
	sum uint32
}

func NewReader32(r io.Reader, h hash.Hash32, sum uint32) *Reader32 {
	if r == nil || h == nil {
		return nil
	}
	r32 := &Reader32{r, h, sum}
	return r32
}

func (r *Reader32) Read(p []byte) (int, error) {
	n, err := r.r.Read(p)
	r.h.Write(p[:n])

	if err == io.EOF && r.h.Sum32() != r.sum {
		err = EHASHFAIL
	}

	return n, err
}

Make Reader32 pass CRC32 test


//+build !guidev

package main

import (
	"fmt"
	"log"
	"mime"
	"net/http"
	"path/filepath"
	"time"

	"github.com/calmh/syncthing/auto"
)

func embeddedStatic() interface{} {
	var modt = time.Now().UTC().Format(http.TimeFormat)

	return func(res http.ResponseWriter, req *http.Request, log *log.Logger) {
		file := req.URL.Path

		if file[0] == '/' {
			file = file[1:]
		}

		bs, ok := auto.Assets[file]
		if !ok {
			return
		}

		mtype := mime.TypeByExtension(filepath.Ext(req.URL.Path))
		if len(mtype) != 0 {
			res.Header().Set("Content-Type", mtype)
		}
		res.Header().Set("Content-Size", fmt.Sprintf("%d", len(bs)))
		res.Header().Set("Last-Modified", modt)

		res.Write(bs)
	}
}

//+build !guidev

package main

import (
	"fmt"
	"log"
	"mime"
	"net/http"
	"path/filepath"
	"time"

	"github.com/calmh/syncthing/auto"
)

func embeddedStatic() interface{} {
	var modt = time.Now().UTC().Format(http.TimeFormat)

	return func(res http.ResponseWriter, req *http.Request, log *log.Logger) {
		file := req.URL.Path

		if file[0] == '/' {
			file = file[1:]
		}

		bs, ok := auto.Assets[file]
		if !ok {
			return
		}

		mtype := mime.TypeByExtension(filepath.Ext(req.URL.Path))
		if len(mtype) != 0 {
			res.Header().Set("Content-Type", mtype)
		}
		res.Header().Set("Content-Length", fmt.Sprintf("%d", len(bs)))
		res.Header().Set("Last-Modified", modt)

		res.Write(bs)
	}
}

Fix typo in header name


package ghostinspector

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

// APIV1Path is the protocol and base path of the Ghost Inspector API version 1
const APIV1Path = "https://api.ghostinspector.com/v1"

// GhostInspector handles sending to the API
type GhostInspector struct {
	apikey string
}

// New creates a new *GhostInspector
func New(apikey string) *GhostInspector {
	return &GhostInspector{
		apikey: apikey,
	}
}

// Get sends GET requests to the Ghost Inspector API, using APIV1Path as the
// base path. This is mainly to be used internally, but exported for users if
// new API calls exists without them being reflected in this package.
func (gi *GhostInspector) Get(path, args string) (*Response, error) {
	response, err := http.Get(fmt.Sprintf("%s%s?apiKey=%s&%s", APIV1Path, path, gi.apikey, args))
	if err != nil {
		return nil, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	resp := Response{}
	json.Unmarshal(body, &resp)
	return &resp, nil
}

package ghostinspector

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

// APIV1Path is the protocol and base path of the Ghost Inspector API version 1
const APIV1Path = "https://api.ghostinspector.com/v1"

// GhostInspector handles sending to the API
type GhostInspector struct {
	apikey string
}

// New creates a new Ghost Inspector client that can be used to send requests.
func New(apikey string) *GhostInspector {
	return &GhostInspector{
		apikey: apikey,
	}
}

// Get sends GET requests to the Ghost Inspector API, using APIV1Path as the
// base path. This is mainly to be used internally, but exported for users if
// new API calls exists without them being reflected in this package.
func (gi *GhostInspector) Get(path, args string) (*Response, error) {
	response, err := http.Get(fmt.Sprintf("%s%s?apiKey=%s&%s", APIV1Path, path, gi.apikey, args))
	if err != nil {
		return nil, err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, err
	}

	resp := Response{}
	json.Unmarshal(body, &resp)
	return &resp, nil
}

Update comment about the New function


package slinga

import (
	"fmt"
	"github.com/gosuri/uiprogress"
	"github.com/gosuri/uiprogress/util/strutil"
	"time"
)

func NewProgress() *uiprogress.Progress {
	progress := uiprogress.New()
	progress.RefreshInterval = time.Second
	progress.Start()

	return progress
}

func AddProgressBar(progress *uiprogress.Progress, total int) *uiprogress.Bar {
	progressBar := progress.AddBar(total)
	progressBar.PrependFunc(func(b *uiprogress.Bar) string {
		return fmt.Sprintf("  [%d/%d]", b.Current(), b.Total)
	})
	progressBar.AppendCompleted()
	progressBar.AppendFunc(func(b *uiprogress.Bar) string {
		return fmt.Sprintf("  Time: %s", strutil.PrettyTime(time.Since(b.TimeStarted)))
	})

	return progressBar
}

package slinga

import (
	"fmt"
	"github.com/gosuri/uiprogress"
	"time"
)

func NewProgress() *uiprogress.Progress {
	progress := uiprogress.New()
	progress.RefreshInterval = time.Second
	progress.Start()

	return progress
}

func AddProgressBar(progress *uiprogress.Progress, total int) *uiprogress.Bar {
	progressBar := progress.AddBar(total)
	progressBar.PrependFunc(func(b *uiprogress.Bar) string {
		return fmt.Sprintf("  [%d/%d]", b.Current(), b.Total)
	})
	progressBar.AppendCompleted()
	progressBar.AppendFunc(func(b *uiprogress.Bar) string {
		return fmt.Sprintf("  Time: %s", b.TimeElapsedString())
	})

	return progressBar
}

Use native elapsed time printer


/*
Copyright 2015 Nodetemple <hostmaster@nodetemple.com>

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 common

const Version = "0.0.1"

var AvailableProviders = []string{"do", "aws", "gce"}

/*
Copyright 2015 Nodetemple <hostmaster@nodetemple.com>

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 common

const Version = "0.0.1"

var AvailableProviders = []string{"do"}

Set primary list of available providers


package cues

import (
	"errors"
	"strings"
)

type CueTemplate struct {
	Mapping map[string]int
} //end CueTemplate

func (tmpl CueTemplate) Create(headers []string) (CueTemplate, error) {
	var err error
	tmpl.Mapping = make(map[string]int)

	//iterate headers
	for i := range headers {
		//check name match
		header := headers[i]
		switch {
		case strings.ToLower(header) == "cue":
			tmpl.Mapping["cue"] = i
		case strings.ToLower(header) == "description":
			tmpl.Mapping["text"] = i
		case strings.ToLower(header) == "page",
			strings.ToLower(header) == "pg":
			tmpl.Mapping["page"] = i
		case strings.ToLower(header) == "time":
			tmpl.Mapping["time"] = i
		case strings.ToLower(header) == "link":
			tmpl.Mapping["link"] = i
		case strings.ToLower(header) == "flags":
			tmpl.Mapping["flags"] = i
		} //end switch
	} //end iterate headers for}

	if _, ok := tmpl.Mapping["cue"]; !ok {
		err = errors.New("No cue header specified")
	}

	return tmpl, err
}

package cues

import (
	"errors"
	"strings"
)

type CueTemplate struct {
	Mapping map[string]int
} //end CueTemplate

func (tmpl CueTemplate) Create(headers []string) (CueTemplate, error) {
	var err error
	tmpl.Mapping = make(map[string]int)

	//iterate headers
	for i := range headers {
		//check name match
		header := headers[i]
		switch {
		case strings.ToLower(header) == "cue":
			tmpl.Mapping["cue"] = i
		case strings.ToLower(header) == "description":
			tmpl.Mapping["text"] = i
		case strings.ToLower(header) == "page",
			strings.ToLower(header) == "pg":
			tmpl.Mapping["page"] = i
		case strings.ToLower(header) == "time":
			tmpl.Mapping["time"] = i
		case strings.ToLower(header) == "link":
			tmpl.Mapping["link"] = i
		case strings.ToLower(header) == "flags":
			tmpl.Mapping["flags"] = i
		case strings.ToLower(header) == "follow":
			tmpl.Mapping["follow"] = i
		} //end switch
	} //end iterate headers for}

	if _, ok := tmpl.Mapping["cue"]; !ok {
		err = errors.New("No cue header specified")
	}

	return tmpl, err
}

Add support for Follow in its own column


// Copyright 2016 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.

/*
cbtemulator launches the in-memory Cloud Bigtable server on the given address.
*/
package main

import (
	"flag"
	"fmt"
	"log"

	"cloud.google.com/go/bigtable/bttest"
)

var (
	host = flag.String("host", "localhost", "the address to bind to on the local machine")
	port = flag.Int("port", 9000, "the port number to bind to on the local machine")
)

func main() {
	flag.Parse()
	srv, err := bttest.NewServer(fmt.Sprintf("%s:%d", *host, *port))
	if err != nil {
		log.Fatalf("failed to start emulator: %v", err)
	}

	fmt.Printf("Cloud Bigtable emulator running on %s\n", srv.Addr)
	select {}
}

// Copyright 2016 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.

/*
cbtemulator launches the in-memory Cloud Bigtable server on the given address.
*/
package main

import (
	"flag"
	"fmt"
	"log"

	"cloud.google.com/go/bigtable/bttest"
	"google.golang.org/grpc"
)

var (
	host = flag.String("host", "localhost", "the address to bind to on the local machine")
	port = flag.Int("port", 9000, "the port number to bind to on the local machine")
)

func main() {
	grpc.EnableTracing = false
	flag.Parse()
	srv, err := bttest.NewServer(fmt.Sprintf("%s:%d", *host, *port))
	if err != nil {
		log.Fatalf("failed to start emulator: %v", err)
	}

	fmt.Printf("Cloud Bigtable emulator running on %s\n", srv.Addr)
	select {}
}

Disable grpc tracing for emulator server


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

package utils

// Comparator will make type assertion (see IntComparator for example),
// which will panic if a or b are not of the asserted type.
//
// Should return a number:
//    negative , if a < b
//    zero     , if a == b
//    positive , if a > b
type Comparator func(a, b interface{}) int

// IntComparator provides a basic comparison on ints
func IntComparator(a, b interface{}) int {
	return a.(int) - b.(int)
}

// StringComparator provides a fast comparison on strings
func StringComparator(a, b interface{}) int {
	s1 := a.(string)
	s2 := b.(string)
	min := len(s2)
	if len(s1) < len(s2) {
		min = len(s1)
	}
	diff := 0
	for i := 0; i < min && diff == 0; i++ {
		diff = int(s1[i]) - int(s2[i])
	}
	if diff == 0 {
		diff = len(s1) - len(s2)
	}
	if diff < 0 {
		return -1
	}
	if diff > 0 {
		return 1
	}
	return 0
}

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

package utils

// Comparator will make type assertion (see IntComparator for example),
// which will panic if a or b are not of the asserted type.
//
// Should return a number:
//    negative , if a < b
//    zero     , if a == b
//    positive , if a > b
type Comparator func(a, b interface{}) int

// IntComparator provides a basic comparison on ints
func IntComparator(a, b interface{}) int {
	aInt := a.(int)
	bInt := b.(int)
	switch {
	case aInt > bInt:
		return 1
	case aInt < bInt:
		return -1
	default:
		return 0
	}
}

// StringComparator provides a fast comparison on strings
func StringComparator(a, b interface{}) int {
	s1 := a.(string)
	s2 := b.(string)
	min := len(s2)
	if len(s1) < len(s2) {
		min = len(s1)
	}
	diff := 0
	for i := 0; i < min && diff == 0; i++ {
		diff = int(s1[i]) - int(s2[i])
	}
	if diff == 0 {
		diff = len(s1) - len(s2)
	}
	if diff < 0 {
		return -1
	}
	if diff > 0 {
		return 1
	}
	return 0
}

Revert "Make IntComparator a bit more direct"


package octokat

import (
	"github.com/bmizerany/assert"
	"os"
	"testing"
)

func TestRepositories(t *testing.T) {
	c := NewClient().WithToken(os.Getenv("GITHUB_TOKEN"))
	repo := Repo{"octokat", "jingweno"}

	repository, err := c.Repository(repo)
	assert.Equal(t, nil, err)
	assert.Equal(t, "octokat", repository.Name)
	assert.Equal(t, "jingweno", repository.Owner.Login)
}

package octokat

import (
	"github.com/bmizerany/assert"
	"os"
	"testing"
)

func TestRepositories(t *testing.T) {
	c := NewClient().WithToken(os.Getenv("GITHUB_TOKEN"))
	repo := Repo{"octokat", "jingweno"}

	repository, err := c.Repository(repo)
	assert.Equal(t, nil, err)
	assert.Equal(t, "octokat", repository.Name)
	assert.Equal(t, "jingweno", repository.Owner.Login)

	repo = Repo{"foo", "jingweno"}
	_, err = c.Repository(repo)
	assert.NotEqual(t, nil, err)
}

Add test case for repository not found


package main

import "github.com/ssandke/gomicbot/Godeps/_workspace/src/github.com/tucnak/telebot"

type SayHiMessageConsumer struct {
	bot   *telebot.Bot
	store StateStore
}

func (c *SayHiMessageConsumer) Initialize(config *Configuration, store StateStore, bot *telebot.Bot) error {
	c.bot = bot
	c.store = store

	return nil
}

func (c *SayHiMessageConsumer) ConsumeMessage(message telebot.Message) (consumed bool, err error) {

	err = nil
	consumed = false

	if message.Text == "/hi" {
		c.bot.SendMessage(message.Chat,
			"Hello, "+message.Sender.FirstName+"!", &telebot.SendOptions{ReplyTo: message})
		consumed = true
	}

	return
}

package main

import "github.com/ssandke/gomicbot/Godeps/_workspace/src/github.com/tucnak/telebot"

type SayHiMessageConsumer struct {
	bot   *telebot.Bot
	store StateStore
}

func (c *SayHiMessageConsumer) Initialize(config *Configuration, store StateStore, bot *telebot.Bot) error {
	c.bot = bot
	c.store = store

	return nil
}

func (c *SayHiMessageConsumer) ConsumeMessage(message telebot.Message) (consumed bool, err error) {

	err = nil
	consumed = false

	if message.Text == "/hi" || message.Text == "/hi@gomicbot" {
		c.bot.SendMessage(message.Chat,
			"Hello, "+message.Sender.FirstName+"!", &telebot.SendOptions{ReplyTo: message})
		consumed = true
	}

	return
}

Support direct message to the bot in group chats.


package cli

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use:          "polymerase",
	Short:        "MySQL backup management API integreted with Percona Xtrabackup",
	SilenceUsage: true,
}

// Run creates, configures and runs
func Run() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Fprintf(os.Stderr, "Failed running %q\n", os.Args[1])
		os.Exit(1)
	}
}

func _exit(err error) {
	if err != nil {
		fmt.Fprintln(os.Stdout, err)
		os.Exit(1)
	}
}

package cli

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use:          "polymerase",
	Short:        "MySQL backup management API integreted with Percona Xtrabackup",
	SilenceUsage: true,
}

// Run executes rootCmd.Execute().
func Run() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Fprintf(os.Stderr, "Failed running %q\n", os.Args[1])
		os.Exit(1)
	}
}

Remove unused codes and add comment


package main

import (
	"os"

	log "github.com/Sirupsen/logrus"
	logx "github.com/cerana/cerana/pkg/logrusx"
	"github.com/cerana/cerana/provider"
	"github.com/cerana/cerana/providers/systemd"
	flag "github.com/spf13/pflag"
)

func main() {
	log.SetFormatter(&logx.JSONFormatter{})

	config := systemd.NewConfig(nil, nil)
	flag.StringP("unit-file-dir", "d", "", "directory in which to create unit files")
	flag.Parse()

	dieOnError(config.LoadConfig())
	dieOnError(config.SetupLogging())

	server, err := provider.NewServer(config.Config)
	dieOnError(err)
	s, err := systemd.New(config)
	dieOnError(err)
	s.RegisterTasks(server)

	if len(server.RegisteredTasks()) != 0 {
		dieOnError(server.Start())
		server.StopOnSignal()
	} else {
		log.Warn("no registered tasks, exiting")
	}
}

func dieOnError(err error) {
	if err != nil {
		log.Fatal("encountered an error during startup, error:", err)
		os.Exit(1)
	}
}

package main

import (
	"os"

	log "github.com/Sirupsen/logrus"
	logx "github.com/cerana/cerana/pkg/logrusx"
	"github.com/cerana/cerana/provider"
	"github.com/cerana/cerana/providers/systemd"
	flag "github.com/spf13/pflag"
)

func main() {
	log.SetFormatter(&logx.JSONFormatter{})

	config := systemd.NewConfig(nil, nil)
	flag.StringP("unit_file_dir", "d", "", "directory in which to create unit files")
	flag.Parse()

	dieOnError(config.LoadConfig())
	dieOnError(config.SetupLogging())

	server, err := provider.NewServer(config.Config)
	dieOnError(err)
	s, err := systemd.New(config)
	dieOnError(err)
	s.RegisterTasks(server)

	if len(server.RegisteredTasks()) != 0 {
		dieOnError(server.Start())
		server.StopOnSignal()
	} else {
		log.Warn("no registered tasks, exiting")
	}
}

func dieOnError(err error) {
	if err != nil {
		log.Fatal("encountered an error during startup, error:", err)
		os.Exit(1)
	}
}

Fix systemd unit_file_dir flag name for consistency