package main

import (
	"fmt"
	"github.com/howeyc/fsnotify"
	"log"
	"os"
	"os/exec"
)

func main() {
	if len(os.Args) < 3 {
		fmt.Fprintln(os.Stderr, "Usage: aroc DIRECTORY COMMAND [ARGS…]")
		os.Exit(1)
	}

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	err = watcher.Watch(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}

	var cmd *exec.Cmd

	go func() {
		for {
			select {
			case _ = <-watcher.Event:
				log.Println("Changes in directory, restarting")
				cmd.Process.Signal(os.Interrupt)
			case err := <-watcher.Error:
				log.Fatal("error:", err)
			}
		}
	}()

	for {
		cmd = exec.Command(os.Args[2])
		cmd.Args = os.Args[2:]
		cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
		err := cmd.Run()
		if err != nil {
			if err, ok := err.(*exec.ExitError); !ok {
				log.Fatal(err)
			}
		}
	}
}

package main

import (
	"fmt"
	"github.com/sdegutis/go.fsevents"
	"log"
	"os"
	"os/exec"
)

func main() {
	if len(os.Args) < 3 {
		fmt.Fprintln(os.Stderr, "Usage: aroc DIRECTORY COMMAND [ARGS…]")
		os.Exit(1)
	}

	ch := fsevents.WatchPaths([]string{os.Args[1]})

	var cmd *exec.Cmd

	go func() {
		for _ = range ch {
			log.Println("Changes in directory, restarting")
			cmd.Process.Signal(os.Interrupt)
		}
	}()

	for {
		cmd = exec.Command(os.Args[2])
		cmd.Args = os.Args[2:]
		cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
		err := cmd.Run()
		if err != nil {
			if err, ok := err.(*exec.ExitError); !ok {
				log.Fatal(err)
			}
		}
	}
}

Switch from fsnotify to fsevents


/*
Copyright 2020 The Tekton Authors

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

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

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

package v1beta1

import (
	"context"

	"github.com/tektoncd/pipeline/pkg/apis/validate"
	"knative.dev/pkg/apis"
)

var _ apis.Validatable = (*ClusterTask)(nil)

func (t *ClusterTask) Validate(ctx context.Context) *apis.FieldError {
	if err := validate.ObjectMetadata(t.GetObjectMeta()); err != nil {
		return err.ViaField("metadata")
	}
	return t.Spec.Validate(ctx)
}

/*
Copyright 2020 The Tekton Authors

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

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

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

package v1beta1

import (
	"context"

	"github.com/tektoncd/pipeline/pkg/apis/validate"
	"knative.dev/pkg/apis"
)

var _ apis.Validatable = (*ClusterTask)(nil)

func (t *ClusterTask) Validate(ctx context.Context) *apis.FieldError {
	errs := validate.ObjectMetadata(t.GetObjectMeta()).ViaField("metadata")
	return errs.Also(t.Spec.Validate(apis.WithinSpec(ctx)).ViaField("spec"))
}

Enhance v1beta1 validation code for clustertask 🍸


package testrail

// ResultField represents a ResultField
type ResultField struct {
	Configs      []ResultFieldConfig `json:"configs"`
	Description  string              `json:"description"`
	DisplayOrder int                 `json:"display_order"`
	ID           int                 `json:"ID"`
	Label        string              `json:"label"`
	Name         string              `json:"name"`
	SystemName   string              `json:"system_name"`
	TypeID       int                 `json:"type_id"`
}

// ResultFieldConfig represents a config
// a ResultField can have
type ResultFieldConfig struct {
	Context Context           `json:"context"`
	ID      string            `json:"id"`
	Options ResultFieldOption `json:"options"`
}

// ResultFieldOption represents an option
// a ResultField can have
type ResultFieldOption struct {
	Format      string `json:"format"`
	HasActual   bool   `json:"has_actual"`
	HasExpected bool   `json:"has_expected"`
	IsRequired  bool   `json:"is_required"`
}

// GetResultFields returns a list of available test result custom fields
func (c *Client) GetResultFields() ([]ResultField, error) {
	caseFields := []ResultField{}
	err := c.sendRequest("GET", "get_result_fields", nil, &caseFields)
	return caseFields, err
}

package testrail

// ResultField represents a ResultField
type ResultField struct {
	Configs      []ResultFieldConfig `json:"configs"`
	Description  string              `json:"description"`
	DisplayOrder int                 `json:"display_order"`
	ID           int                 `json:"ID"`
	Label        string              `json:"label"`
	Name         string              `json:"name"`
	SystemName   string              `json:"system_name"`
	TypeID       int                 `json:"type_id"`
	IsActive     bool                `json:"is_active"`
}

// ResultFieldConfig represents a config
// a ResultField can have
type ResultFieldConfig struct {
	Context Context           `json:"context"`
	ID      string            `json:"id"`
	Options ResultFieldOption `json:"options"`
}

// ResultFieldOption represents an option
// a ResultField can have
type ResultFieldOption struct {
	Format      string `json:"format"`
	HasActual   bool   `json:"has_actual"`
	HasExpected bool   `json:"has_expected"`
	IsRequired  bool   `json:"is_required"`
}

// GetResultFields returns a list of available test result custom fields
func (c *Client) GetResultFields() ([]ResultField, error) {
	caseFields := []ResultField{}
	err := c.sendRequest("GET", "get_result_fields", nil, &caseFields)
	return caseFields, err
}

Add missing undocumented is_active field


package main

import (
	"math/big"
	"testing"
)

func sumOfPrimesBelow(x int64) int64 {
	var i int64
	var sum int64 = 0
	for i = 2; i < x; i++ {
		if i > 2 && i%2 == 0 {
			continue
		}

		j := big.NewInt(i)
		if !j.ProbablyPrime(10) {
			continue
		}
		sum += i

	}
	return sum
}

func TestSumOfPrimesBelow2M(t *testing.T) {
	x := sumOfPrimesBelow(2000000)
	var answer int64 = 142913828922
	if x != answer {
		t.Errorf("result = %v, want %v", x, answer)
	}

}

package main

import (
	"testing"
)

func sumOfPrimesBelow(x int) int {
	sieve := make([]bool, x)
	for i:=0; i<x; i++ {
		sieve[i] = true
	}
	sieve[0] = false
	sieve[1] = false

	for i:=2; i<x; i++ {
		if sieve[i] == false {
			continue
		}
		for j:=2*i; j<x; j+=i {
			sieve[j] = false
		}

	}

	sum := 0
	for i:=2; i<x; i++ {
		if sieve[i] {
			sum += i;
		}
	}
	return sum
}

func TestSumOfPrimesBelow2M(t *testing.T) {
	x := sumOfPrimesBelow(2000000)
	answer := 142913828922
	if x != answer {
		t.Errorf("result = %v, want %v", x, answer)
	}

}

Use a sieve for Prob 10


package chalmers_chop

type Allergen int

const (
	Gluten Allergen = iota
	Egg
	Milk
)

type Dish struct {
	Name string
	Contents string
	Price int
	Allergens []Allergen
}

func NewDish(name, contents string) *Dish {
	return &Dish{
		Name: name,
		Contents: contents,
	}
}

package chalmers_chop

type Allergen int

const (
	Gluten Allergen = iota
	Egg
	Lactose
)

type Dish struct {
	Name string
	Contents string
	Price int
	Allergens []Allergen
}

func NewDish(name, contents string) *Dish {
	return &Dish{
		Name: name,
		Contents: contents,
	}
}

Correct “Milk” allergen to “Lactose”


package web

import (
	"net/http"

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

type ClientFactory interface {
	Build(request *http.Request) concourse.Client
}

type clientFactory struct {
	apiEndpoint string
}

func NewClientFactory(apiEndpoint string) ClientFactory {
	return &clientFactory{
		apiEndpoint: apiEndpoint,
	}
}

func (cf *clientFactory) Build(r *http.Request) concourse.Client {
	transport := authorizationTransport{
		Authorization: r.Header.Get("Authorization"),

		Base: &http.Transport{
			// disable connection pooling
			DisableKeepAlives: true,
		},
	}

	httpClient := &http.Client{
		Transport: transport,
	}

	return concourse.NewClient(cf.apiEndpoint, httpClient)
}

type authorizationTransport struct {
	Base          http.RoundTripper
	Authorization string
}

func (transport authorizationTransport) RoundTrip(r *http.Request) (*http.Response, error) {
	r.Header.Set("Authorization", transport.Authorization)
	return transport.Base.RoundTrip(r)
}

package web

import (
	"crypto/tls"
	"net/http"

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

type ClientFactory interface {
	Build(request *http.Request) concourse.Client
}

type clientFactory struct {
	apiEndpoint                 string
	allowSelfSignedCertificates bool
}

func NewClientFactory(apiEndpoint string, allowSelfSignedCertificates bool) ClientFactory {
	return &clientFactory{
		apiEndpoint:                 apiEndpoint,
		allowSelfSignedCertificates: allowSelfSignedCertificates,
	}
}

func (cf *clientFactory) Build(r *http.Request) concourse.Client {
	transport := authorizationTransport{
		Authorization: r.Header.Get("Authorization"),

		Base: &http.Transport{

			DisableKeepAlives: true, // disable connection pooling
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: cf.allowSelfSignedCertificates,
			},
		},
	}

	httpClient := &http.Client{
		Transport: transport,
	}

	return concourse.NewClient(cf.apiEndpoint, httpClient)
}

type authorizationTransport struct {
	Base          http.RoundTripper
	Authorization string
}

func (transport authorizationTransport) RoundTrip(r *http.Request) (*http.Response, error) {
	r.Header.Set("Authorization", transport.Authorization)
	return transport.Base.RoundTrip(r)
}

Use external_url when TLS enabled or IP address otherwise - Allow self-signed certificates only when in development mode


// +build oracle

package testfixtures

import (
	_ "gopkg.in/rana/ora.v3"
)

func init() {
	databases = append(databases,
		databaseTest{
			"ora",
			"ORACLE_CONN_STRING",
			"testdata/schema/oracle.sql",
			&OracleHelper{},
		},
	)
}

// +build oracle

package testfixtures

import (
	_ "github.com/mattn/go-oci8"
)

func init() {
	databases = append(databases,
		databaseTest{
			"oci8",
			"ORACLE_CONN_STRING",
			"testdata/schema/oracle.sql",
			&OracleHelper{},
		},
	)
}

Change Oracle driver (use github.com/mattn/go-oci8)


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

// +build linux,!android darwin,!arm,!arm64

package sensor

import (
	"errors"
	"time"
)

type manager struct {
}

func (m *manager) initialize() {
}

func (m *manager) enable(t Type, delay time.Duration) error {
	return errors.New("sensor: no sensors available")
}

func (m *manager) disable(t Type) error {
	return errors.New("sensor: no sensors available")
}

func (m *manager) read(e []Event) (n int, err error) {
	return 0, errors.New("sensor: no sensor data available")
}

func (m *manager) close() error {
	return nil
}

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

// +build linux,!android darwin,!arm,!arm64

package sensor

import (
	"errors"
	"time"
)

type manager struct{}

func (m *manager) initialize() {}

func (m *manager) enable(s sender, t Type, delay time.Duration) error {
	return errors.New("sensor: no sensors available")
}

func (m *manager) disable(t Type) error {
	return errors.New("sensor: no sensors available")
}

func (m *manager) close() error {
	return nil
}

Fix the broken build for non-darwin and non-android.


package lib

const (
	Version = "2.2.1"
)

package lib

const (
	// Version is the version number the client believes it is
	Version = "2.2.1"
)

Put the Version comment back


package main

import (
    "database/sql"
    "log"

    _ "github.com/mattn/go-sqlite3"
)

var createUsers = `
CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name VARCHAR
);
`

var insertUser = `INSERT INTO users (id, name) VALUES (?, ?)`

var selectUser = `SELECT id, name FROM users`

func main() {

    db, err := sql.Open("sqlite3", ":memory:")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    if _, err := db.Exec(createUsers); err != nil {
        panic(err)
    }

    if _, err := db.Exec(insertUser, 23, "skidoo"); err != nil {
        panic(err)
    }

    var id int64
    var name string
    row := db.QueryRow(selectUser)

    if err = row.Scan(&id, &name); err != nil {
        panic(err)
    }

    log.Println(id, name)

}

package main

import (
	"database/sql"
	"log"

	_ "github.com/mattn/go-sqlite3"
)

var createUsers = `
CREATE TABLE users (
    id INTEGER,
    name VARCHAR
);
`

var insertUser = `INSERT INTO users (id, name) VALUES (?, ?)`

var selectUser = `SELECT id, name FROM users`

type User struct {
	ID   int64
	Name sql.NullString
}

func (u User) String() string {
	if u.Name.Valid {
		return u.Name.String
	}
	return "No name"
}

func main() {
	// Connect to an in-memory sqlite3 instance
	db, err := sql.Open("sqlite3", ":memory:")
	if err != nil {
		panic(err)
	}
	defer db.Close()

	// Create the table
	if _, err := db.Exec(createUsers); err != nil {
		panic(err)
	}

	// Insert a user without a name
	if _, err := db.Exec(insertUser, 1, nil); err != nil {
		panic(err)
	}

	// Select a user
	var user User
	row := db.QueryRow(selectUser)
	if err = row.Scan(&user.ID, &user.Name); err != nil {
		panic(err)
	}
	log.Println(user)
}

INSERT a NULL value and SELECT it back out


package main

import (
    "testing"
)

func TestPacketAdd(t *testing.T) {
    pq := PacketQueue{}

    if pq.Length() != 0 {
        t.Errorf("Length should be 0 but was %d", pq.Length())
    }

    i, err := pq.Add([]byte{1,2,3,4,5})

    if err != nil {
        t.Error(err)
    }

    if i != 0 {
        t.Errorf("Serial no. should be 0 but was %d", i)
    }

    if pq.Length() != 1 {
        t.Errorf("Length should be 1 but was %d", pq.Length())
    }

    i, err = pq.Add([]byte{6, 7, 8, 9, 0})

    if err != nil {
        t.Error(err)
    }

    if pq.Length() != 2 {
        t.Errorf("Length should be 2 but was %d", pq.Length())
    }

}

func TestQueueCapacity(t *testing.T) {
    pq := PacketQueue{}
    for i := 0; i < PACKET_BUFFER_SIZE; i++ {
        serial, err := pq.Add([]byte{0, 0, byte(i)})
        if err != nil {
            t.Error(err)
        }
        if serial != uint64(i) {
            t.Errorf("Serial %d did not match %d", serial, i)
        }
    }

    _, err := pq.Add([]byte{0})
    if err == nil {
        t.Errorf("Queue did not error when adding past capacity")
    }

    const trimNum uint64 = 5
    pq.TrimUpTo(trimNum)

    for i := 0; uint64(i) < trimNum; i++ {
        serial, err := pq.Add([]byte{1, byte(i)})
        if err != nil {
            t.Error(err)
        }
        if serial != uint64(PACKET_BUFFER_SIZE + i) {
            t.Errorf("Serial %d did not match %d", serial, i)
        }
    }

    _, err = pq.Add([]byte{0})
    if err == nil {
        t.Errorf("Queue did not error when adding past capacity")
    }
}

Add some more queue tests


package h2spec

import (
	"github.com/bradfitz/http2"
	"github.com/bradfitz/http2/hpack"
)

func FrameSizeTestGroup() *TestGroup {
	tg := NewTestGroup("4.2", "Frame Size")

	tg.AddTestCase(NewTestCase(
		"Sends large size frame that exceeds the SETTINGS_MAX_FRAME_SIZE",
		"The endpoint MUST send a FRAME_SIZE_ERROR error.",
		func(ctx *Context) (expected []Result, actual Result) {
			http2Conn := CreateHttp2Conn(ctx, false)
			defer http2Conn.conn.Close()

			http2Conn.fr.WriteSettings()

			hdrs := []hpack.HeaderField{
				pair(":method", "GET"),
				pair(":scheme", "http"),
				pair(":path", "/"),
				pair(":authority", ctx.Authority()),
			}

			var hp http2.HeadersFrameParam
			hp.StreamID = 1
			hp.EndStream = false
			hp.EndHeaders = true
			hp.BlockFragment = http2Conn.EncodeHeader(hdrs)
			http2Conn.fr.WriteHeaders(hp)
			http2Conn.fr.WriteData(1, true, []byte(dummyData(16385)))

			actualCodes := []http2.ErrCode{http2.ErrCodeFrameSize}
			return TestStreamError(ctx, http2Conn, actualCodes)
		},
	))

	return tg
}

package h2spec

import (
	"github.com/bradfitz/http2"
	"github.com/bradfitz/http2/hpack"
)

func FrameSizeTestGroup() *TestGroup {
	tg := NewTestGroup("4.2", "Frame Size")

	tg.AddTestCase(NewTestCase(
		"Sends large size frame that exceeds the SETTINGS_MAX_FRAME_SIZE",
		"The endpoint MUST send a FRAME_SIZE_ERROR error.",
		func(ctx *Context) (expected []Result, actual Result) {
			http2Conn := CreateHttp2Conn(ctx, true)
			defer http2Conn.conn.Close()

			hdrs := []hpack.HeaderField{
				pair(":method", "GET"),
				pair(":scheme", "http"),
				pair(":path", "/"),
				pair(":authority", ctx.Authority()),
			}

			var hp http2.HeadersFrameParam
			hp.StreamID = 1
			hp.EndStream = false
			hp.EndHeaders = true
			hp.BlockFragment = http2Conn.EncodeHeader(hdrs)
			http2Conn.fr.WriteHeaders(hp)
			max_size, ok := http2Conn.Settings[http2.SettingMaxFrameSize]
			if( !ok ) {
				max_size = 18384
			}

			http2Conn.fr.WriteData(1, true, []byte(dummyData(int(max_size) + 1)))

			actualCodes := []http2.ErrCode{http2.ErrCodeFrameSize}
			return TestStreamError(ctx, http2Conn, actualCodes)
		},
	))

	return tg
}

Test 4.2: use the max frame size from the server's SETTINGS frame


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

package main

import (
	"log"
	"os"
	"os/user"

	"github.com/codegangsta/cli"
)

func init() {
	// Check for the environment early on and gracefuly report.
	_, err := user.Current()
	if err != nil {
		log.Fatalf("mc: Unable to obtain user's home directory. \nERROR[%v]\n", err)
	}
}

func main() {
	app := cli.NewApp()
	app.Name = "mc"
	app.Usage = "Minio Client for S3 Compatible Object Storage"
	app.Version = "0.1.0"
	app.Commands = options
	app.Flags = flags
	app.Author = "Minio.io"
	app.EnableBashCompletion = true
	app.Action = parseGlobalOptions
	app.Run(os.Args)
}

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

package main

import (
	"log"
	"os"
	"os/user"

	"github.com/codegangsta/cli"
)

func init() {
	// Check for the environment early on and gracefuly report.
	_, err := user.Current()
	if err != nil {
		log.Fatalf("mc: Unable to obtain user's home directory. \nERROR[%v]\n", err)
	}
}

func main() {
	app := cli.NewApp()
	app.Usage = "Minio Client for S3 Compatible Object Storage"
	app.Version = "0.1.0"
	app.Commands = options
	app.Flags = flags
	app.Author = "Minio.io"
	app.EnableBashCompletion = true
	app.Action = parseGlobalOptions
	app.Run(os.Args)
}

Remove redundant app.Name, internally codegangsta uses os.Args[0]


package main

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

var config struct {
	path    string
	address string
	port    int
}

func main() {
	flag.StringVar(&config.path, "path", "", "Optional path to serve static files from.")
	flag.StringVar(&config.address, "address", "127.0.0.1", "Address to listen on.")
	flag.IntVar(&config.port, "port", 3333, "Port to listen on.")
	flag.Parse()

	stubHandler := NewStubHandler()
	if config.path != "" {
		stubHandler.fallbackHandler = http.FileServer(http.Dir(config.path))
	}
	http.Handle("/", stubHandler)
	http.ListenAndServe(fmt.Sprintf("%s:%d", config.address, config.port), stubHandler)
}

package main

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

var config struct {
	path    string
	address string
	port    int
}

func main() {
	flag.StringVar(&config.path, "path", "", "Optional path to serve static files from.")
	flag.StringVar(&config.address, "address", "127.0.0.1", "Address to listen on.")
	flag.IntVar(&config.port, "port", 3333, "Port to listen on.")
	flag.Parse()

	stubHandler := NewStubHandler()
	if config.path != "" {
		stubHandler.fallbackHandler = http.FileServer(http.Dir(config.path))
	}
	http.Handle("/", stubHandler)

	var err error
	err = http.ListenAndServe(fmt.Sprintf("%s:%d", config.address, config.port), stubHandler)
	if err != nil {
		log.Fatalf("Unable to start server: %v\n", err)
	}
}

Add error reporting when web server fails


package main

import (
	"bufio"
	"fmt"
	"os"

	"github.com/go-distributed/gog/agent"
	"github.com/go-distributed/gog/config"
)

func main() {
	config, err := config.ParseConfig()
	if err != nil {
		fmt.Println("Failed to parse configuration", err)
		return
	}
	ag := agent.NewAgent(config)
	ag.RegisterMessageHandler(msgCallBack)
	fmt.Printf("serving at %v...\n", config.AddrStr)
	go ag.Serve()

	if config.Peers != nil {
		if err := ag.Join(config.ShufflePeers()); err != nil {
			fmt.Println("No available peers")
			//return
		}
	}
	input := bufio.NewReader(os.Stdin)
	for {
		fmt.Println("input a message:")
		bs, err := input.ReadString('\n')
		if err != nil {
			fmt.Println("error reading:", err)
			break
		}
		if bs == "list\n" {
			ag.List()
			continue
		}
		fmt.Println(bs)
		ag.Broadcast([]byte(bs))
	}
}

func msgCallBack(msg []byte) {
	fmt.Println(string(msg))
}

package main

import (
	"bufio"
	"fmt"
	"os"

	"github.com/go-distributed/gog/agent"
	"github.com/go-distributed/gog/config"
)

func main() {
	config, err := config.ParseConfig()
	if err != nil {
		fmt.Println("Failed to parse configuration", err)
		return
	}
	ag := agent.NewAgent(config)
	ag.RegisterMessageHandler(msgCallBack)
	fmt.Printf("serving at %v...\n", config.AddrStr)
	go ag.Serve()

	if config.Peers != nil {
		if err := ag.Join(config.Peers); err != nil {
			fmt.Println("No available peers")
			//return
		}
	}
	input := bufio.NewReader(os.Stdin)
	for {
		fmt.Println("input a message:")
		bs, err := input.ReadString('\n')
		if err != nil {
			fmt.Println("error reading:", err)
			break
		}
		if bs == "list\n" {
			ag.List()
			continue
		}
		fmt.Println(bs)
		ag.Broadcast([]byte(bs))
	}
}

func msgCallBack(msg []byte) {
	fmt.Println(string(msg))
}

Remove ShufflePeers() to avoid partion in setup.


/*
Copyright 2017 The Kubernetes Authors.

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

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

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

package cloudup

import "k8s.io/apimachinery/pkg/util/sets"

// Phase is a portion of work that kops completes.
type Phase string

const (
	// PhaseStageAssets uploads various assets such as containers in a private registry
	PhaseStageAssets Phase = "assets"
	// PhaseNetwork creates network infrastructure.
	PhaseNetwork Phase = "network"
	// PhaseIAM creates IAM profiles and roles, security groups and firewalls
	PhaseSecurity Phase = "security"
	// PhaseCluster creates the servers, and load-alancers
	PhaseCluster Phase = "cluster"
)

// Phases are used for validation and cli help.
var Phases = sets.NewString(
	string(PhaseStageAssets),
	string(PhaseSecurity),
	string(PhaseNetwork),
	string(PhaseCluster),
)

/*
Copyright 2017 The Kubernetes Authors.

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

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

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

package cloudup

import "k8s.io/apimachinery/pkg/util/sets"

// Phase is a portion of work that kops completes.
type Phase string

const (
	// PhaseStageAssets uploads various assets such as containers in a private registry
	PhaseStageAssets Phase = "assets"
	// PhaseNetwork creates network infrastructure.
	PhaseNetwork Phase = "network"
	// PhaseSecurity creates IAM profiles and roles, security groups and firewalls
	PhaseSecurity Phase = "security"
	// PhaseCluster creates the servers, and load-alancers
	PhaseCluster Phase = "cluster"
)

// Phases are used for validation and cli help.
var Phases = sets.NewString(
	string(PhaseStageAssets),
	string(PhaseSecurity),
	string(PhaseNetwork),
	string(PhaseCluster),
)

Fix code comment on PhaseSecurity


package hamming

import (
	"testing"
)

var testCases = []struct {
	expected         int
	strandA, strandB string
	description      string
}{
	{0, "GGACTGA", "GGACTGA", "no difference between identical strands"},
	{3, "ACT", "GGA", "complete hamming distance in small strand"},
	{9, "GGACGGATTCTG", "AGGACGGATTCT", "distance in off by one strand"},
	{1, "GGACG", "GGTCG", "small hamming distance in middle somewhere"},
	{2, "ACCAGGG", "ACTATGG", "larger distance"},
	{3, "AAACTAGGGG", "AGGCTAGCGGTAGGAC", "ignores extra length on other strand when longer"},
	{5, "GACTACGGACAGGGTAGGGAAT", "GACATCGCACACC", "ignores extra length on original strand when longer"},
}

func TestHamming(t *testing.T) {
	for _, tc := range testCases {

		observed := Distance(tc.strandA, tc.strandB)

		if tc.expected != observed {
			t.Fatalf(`%s:
expected: %v
observed: %v`,
				tc.description,
				tc.expected,
				observed,
			)
		}
	}
}

package hamming

import (
	"testing"
)

var testCases = []struct {
	expected         int
	strandA, strandB string
	description      string
}{
	{0, "", "", "no difference between empty strands"},
	{2, "AG", "CT", "complete hamming distance for small strand"},
	{0, "A", "A", "no difference between identical strands"},
	{1, "A", "G", "complete distance for single nucleotide strand"},
	{1, "AT", "CT", "small hamming distance"},
	{1, "GGACG", "GGTCG", "small hamming distance in longer strand"},
	{0, "AAAG", "AAA", "ignores extra length on first strand when longer"},
	{0, "AAA", "AAAG", "ignores extra length on second strand when longer"},
	{4, "GATACA", "GCATAA", "large hamming distance"},
	{9, "GGACGGATTCTG", "AGGACGGATTCT", "hamming distance in very long strand"},
}

func TestHamming(t *testing.T) {
	for _, tc := range testCases {

		observed := Distance(tc.strandA, tc.strandB)

		if tc.expected != observed {
			t.Fatalf(`%s:
expected: %v
observed: %v`,
				tc.description,
				tc.expected,
				observed,
			)
		}
	}
}

Update hamming tests in Go


// Pygments wrapper for golang. Pygments is a syntax highlighter

package pygments

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

var (
	bin = "pygmentize"
)

func Binary(path string) {
	bin = path
}

func Which() string {
	return bin
}

func Highlight(code string, lexer string, format string, enc string) string {

	if _, err := exec.LookPath(bin); err != nil {
		fmt.Println("You do not have " + bin + " installed!")
		os.Exit(0)
	}

	cmd := exec.Command(bin, "-l"+lexer, "-f"+format, "-O encoding="+enc)
	cmd.Stdin = strings.NewReader(code)

	var out bytes.Buffer
	cmd.Stdout = &out

	var stderr bytes.Buffer
	cmd.Stderr = &stderr

	if err := cmd.Run(); err != nil {
		fmt.Println(stderr.String())
		fmt.Println(err)
		os.Exit(0)
	}

	return out.String()
}

// Pygments wrapper for golang. Pygments is a syntax highlighter

package pygments

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

var (
	bin = "pygmentize"
)

func Binary(path string) {
	bin = path
}

func Which() string {
	return bin
}

func Highlight(code string, lexer string, format string, enc string) string {

	if _, err := exec.LookPath(bin); err != nil {
		fmt.Println("You do not have " + bin + " installed!")
		os.Exit(0)
	}

	// Guess the lexer based on content if a specific one is not provided
	lexerArg := "-g"
	if lexer != "" {
		lexerArg = "-l" + lexer
	}

	cmd := exec.Command(bin, lexerArg, "-f"+format, "-O encoding="+enc)
	cmd.Stdin = strings.NewReader(code)

	var out bytes.Buffer
	cmd.Stdout = &out

	var stderr bytes.Buffer
	cmd.Stderr = &stderr

	if err := cmd.Run(); err != nil {
		fmt.Println(stderr.String())
		fmt.Println(err)
		os.Exit(0)
	}

	return out.String()
}

Make lexer argument optional and guess content if not provided


package hellomessage // import "myitcv.io/react/examples/hellomessage"

import (
	r "myitcv.io/react"
)

//go:generate reactGen

// HelloMessageDef is the definition of the HelloMessage component
type HelloMessageDef struct {
	r.ComponentDef
}

// HelloMessageProps is the props type for the HelloMessage component
type HelloMessageProps struct {
	Name string
}

// HelloMessage creates instances of the HelloMessage component
func HelloMessage(p HelloMessageProps) *HelloMessageElem {
	return &HelloMessageElem{
		Element: r.CreateElement(buildCmp, p),
	}
}

func buildCmp(elem r.ComponentDef) r.Component {
	return HelloMessageDef{ComponentDef: elem}
}

// Render renders the HelloMessage component
func (h HelloMessageDef) Render() r.Element {
	return r.Div(nil,
		r.S("Hello "+h.Props().Name),
	)
}

package hellomessage // import "myitcv.io/react/examples/hellomessage"

import (
	r "myitcv.io/react"
)

//go:generate reactGen

// HelloMessageDef is the definition of the HelloMessage component
type HelloMessageDef struct {
	r.ComponentDef
}

// HelloMessageProps is the props type for the HelloMessage component
type HelloMessageProps struct {
	Name string
}

// HelloMessage creates instances of the HelloMessage component
func HelloMessage(p HelloMessageProps) *HelloMessageElem {
	return buildHelloMessageElem(p)
}

// Render renders the HelloMessage component
func (h HelloMessageDef) Render() r.Element {
	return r.Div(nil,
		r.S("Hello "+h.Props().Name),
	)
}

Remove old code from hello message example


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

package utils

import (
	"path/filepath"

	"github.com/projectriff/riff/riff-cli/pkg/options"
)

func ResolveOptions(functionArtifact string, language string, opts *options.InitOptions) {

	if opts.Input == "" {
		opts.Input = opts.FunctionName
	}

	if opts.Artifact == "" {
		opts.Artifact = filepath.Base(functionArtifact)
	}

	protocolForLanguage := map[string]string{
		"shell": "grpc",
		"java":  "grpc",
		"js":    "grpc",
		"node":  "grpc",
		"python": "stdio",
	}

	if opts.Protocol == "" {
		opts.Protocol = protocolForLanguage[language]
	}
}

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

package utils

import (
	"path/filepath"

	"github.com/projectriff/riff/riff-cli/pkg/options"
)

func ResolveOptions(functionArtifact string, language string, opts *options.InitOptions) {

	if opts.Input == "" {
		opts.Input = opts.FunctionName
	}

	if opts.Artifact == "" {
		opts.Artifact = filepath.Base(functionArtifact)
	}

	protocolForLanguage := map[string]string{
		"shell":  "grpc",
		"java":   "grpc",
		"js":     "grpc",
		"node":   "grpc",
		"python": "grpc",
	}

	if opts.Protocol == "" {
		opts.Protocol = protocolForLanguage[language]
	}
}

Switch python to grpc protocol


package zoom // Use this file for /user endpoints

// CreateUserPath - v2 path for creating a user
const CreateUserPath = "/users"

type CreateUserInfo struct {
	Email     string   `json:"email"`
	Type      UserType `json:"type"`
	FirstName string   `json:"first_name,omitempty"`
	LastName  string   `json:"last_name,omitempty"`
	Password  string   `json:"password,omitempty"`
}

// CreateUserOptions are the options to create a user with
type CreateUserOptions struct {
	Action   CreateUserAction `json:"action"`
	UserInfo CreateUserInfo   `json:"user_info"`
}

// CreateUser calls POST /users/{userId}/meetings
func CreateUser(opts CreateUserOptions) (User, error) {
	return defaultClient.CreateUser(opts)
}

// CreateUser calls POST /users
// https://marketplace.zoom.us/docs/api-reference/zoom-api/users/usercreate
func (c *Client) CreateUser(opts CreateUserOptions) (User, error) {
	var ret = User{}
	return ret, c.requestV2(requestV2Opts{
		Method:         Post,
		Path:           CreateUserPath,
		DataParameters: &opts,
		Ret:            &ret,
	})
}

package zoom // Use this file for /user endpoints

// CreateUserPath - v2 path for creating a user
const CreateUserPath = "/users"

// CreateUserInfo are details about a user to create
type CreateUserInfo struct {
	Email     string   `json:"email"`
	Type      UserType `json:"type"`
	FirstName string   `json:"first_name,omitempty"`
	LastName  string   `json:"last_name,omitempty"`
	Password  string   `json:"password,omitempty"`
}

// CreateUserOptions are the options to create a user with
type CreateUserOptions struct {
	Action   CreateUserAction `json:"action"`
	UserInfo CreateUserInfo   `json:"user_info"`
}

// CreateUser calls POST /users/{userId}/meetings
func CreateUser(opts CreateUserOptions) (User, error) {
	return defaultClient.CreateUser(opts)
}

// CreateUser calls POST /users
// https://marketplace.zoom.us/docs/api-reference/zoom-api/users/usercreate
func (c *Client) CreateUser(opts CreateUserOptions) (User, error) {
	var ret = User{}
	return ret, c.requestV2(requestV2Opts{
		Method:         Post,
		Path:           CreateUserPath,
		DataParameters: &opts,
		Ret:            &ret,
	})
}

Add a comment to CreateUserInfo


package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/nlopes/slack"
)

func main() {
	api := slack.New("SLACK-TOKEN")

	slackMessage := "[Atlassian Server] "
	if len(os.Args) > 1 {
		slackMessage += strings.Join(os.Args[1:], " ")
	} else {
		slackMessage += " Empty Message"
	}

	channelID, timestamp, err := api.PostMessage("SLACK-CHANNEL-ID", slack.MsgOptionText(slackMessage, false))
	if err != nil {
		fmt.Printf("%s\n", err)
		return
	}
	fmt.Printf("MSG SENT channel %s at %s , Message %s ", channelID, timestamp, slackMessage)
}

package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/nlopes/slack"
)

func main() {
	api := slack.New("SLACK-TOKEN")

	slackMessage := "[Atlassian Server] "
	if len(os.Args) > 1 {
		slackMessage += strings.Join(os.Args[1:], " ")
	} else {
		slackMessage += " Empty Message"
	}

	channelID, timestamp, err := api.PostMessage("SLACK-CHANNEL-ID", slack.MsgOptionText(slackMessage, false))
	if err != nil {
		fmt.Printf("%s\n", err)
		return
	}
	fmt.Printf("MSG SENT channel %s at %s , Message %s \n", channelID, timestamp, slackMessage)
}

Add new line to end of message


package softlayer

import (
	"fmt"
	"log"
)

// Artifact represents a Softlayer image as the result of a Packer build.
type Artifact struct {
	imageName      string
	imageId        string
	datacenterName string
	client         *SoftlayerClient
}

// BuilderId returns the builder Id.
func (*Artifact) BuilderId() string {
	return BuilderId
}

// Destroy destroys the Softlayer image represented by the artifact.
func (self *Artifact) Destroy() error {
	log.Printf("Destroying image: %s", self.String())
	err := self.client.destroyImage(self.imageId)
	return err
}

// Files returns the files represented by the artifact.
func (*Artifact) Files() []string {
	return nil
}

// Id returns the Softlayer image ID.
func (self *Artifact) Id() string {
	return self.imageId
}

// String returns the string representation of the artifact.
func (self *Artifact) String() string {
	return fmt.Sprintf("%s::%s (%s)", self.datacenterName, self.imageId, self.imageName)
}

package softlayer

import (
	"fmt"
	"log"
)

// Artifact represents a Softlayer image as the result of a Packer build.
type Artifact struct {
	imageName      string
	imageId        string
	datacenterName string
	client         *SoftlayerClient
}

// BuilderId returns the builder Id.
func (*Artifact) BuilderId() string {
	return BuilderId
}

// Destroy destroys the Softlayer image represented by the artifact.
func (self *Artifact) Destroy() error {
	log.Printf("Destroying image: %s", self.String())
	err := self.client.destroyImage(self.imageId)
	return err
}

// Files returns the files represented by the artifact.
func (*Artifact) Files() []string {
	return nil
}

// Id returns the Softlayer image ID.
func (self *Artifact) Id() string {
	return self.imageId
}

func (self *Artifact) State(name string) interface{} {
	return nil
}

// String returns the string representation of the artifact.
func (self *Artifact) String() string {
	return fmt.Sprintf("%s::%s (%s)", self.datacenterName, self.imageId, self.imageName)
}

Add State to Artifact struct to support the new packer api (v0.7.2)


// +build linux

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

// Manager of resctrl for containers.
package resctrl

import (
	"github.com/google/cadvisor/stats"

	"github.com/opencontainers/runc/libcontainer/intelrdt"
)

type manager struct {
	id string
	stats.NoopDestroy
}

func (m manager) GetCollector(resctrlPath string) (stats.Collector, error) {
	collector := newCollector(m.id, resctrlPath)
	return collector, nil
}

func NewManager(id string) (stats.Manager, error) {

	if intelrdt.IsMBMEnabled() || intelrdt.IsCMTEnabled() {
		return &manager{id: id}, nil
	}

	return &stats.NoopManager{}, nil
}

// +build linux

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

// Manager of resctrl for containers.
package resctrl

import (
	"os"

	"github.com/google/cadvisor/stats"

	"github.com/opencontainers/runc/libcontainer/intelrdt"
)

type manager struct {
	id string
	stats.NoopDestroy
}

func (m manager) GetCollector(resctrlPath string) (stats.Collector, error) {
	if _, err := os.Stat(resctrlPath); err != nil {
		return &stats.NoopCollector{}, err
	}
	collector := newCollector(m.id, resctrlPath)
	return collector, nil
}

func NewManager(id string) (stats.Manager, error) {

	if intelrdt.IsMBMEnabled() || intelrdt.IsCMTEnabled() {
		return &manager{id: id}, nil
	}

	return &stats.NoopManager{}, nil
}

Add checking if resctrl path exists


package rethink

import (
	r "github.com/dancannon/gorethink"
)

type DB struct {
	Session *r.Session
}

func NewDB(session *r.Session) *DB {
	return &DB{
		Session: session,
	}
}

func (db *DB) Get(table, id string) (map[string]interface{}, error) {
	result, err := r.Table(table).Get(id).RunRow(db.Session)
	if err != nil || result.IsNil() {
		return nil, err
	}

	var response map[string]interface{}
	result.Scan(&response)
	return response, nil
}

func (db *DB) GetAll(query r.RqlTerm) ([]map[string]interface{}, error) {
	var results []map[string]interface{}
	rows, err := query.Run(db.Session)
	if err != nil {
		return results, err
	}

	for rows.Next() {
		var response map[string]interface{}
		rows.Scan(&response)
		results = append(results, response)
	}

	return results, nil
}

package rethink

import (
	r "github.com/dancannon/gorethink"
	"fmt"
)

type DB struct {
	Session *r.Session
}

func NewDB(session *r.Session) *DB {
	return &DB{
		Session: session,
	}
}

var emptyMap map[string]interface{}

func (db *DB) Get(table, id string) (map[string]interface{}, error) {
	result, err := r.Table(table).Get(id).RunRow(db.Session)
	switch {
	case err != nil:
		return emptyMap, err
	case result.IsNil():
		return emptyMap, fmt.Errorf("No such id: %s", id)
	default:
		var response map[string]interface{}
		result.Scan(&response)
		return response, nil
	}
}

func (db *DB) GetAll(query r.RqlTerm) ([]map[string]interface{}, error) {
	var results []map[string]interface{}
	rows, err := query.Run(db.Session)
	if err != nil {
		return results, err
	}

	for rows.Next() {
		var response map[string]interface{}
		rows.Scan(&response)
		results = append(results, response)
	}

	return results, nil
}

Return error if we don't find a key.


package handler

import (
	"net/http"
	"time"

	"github.com/yuuki/dynamond/log"
	"github.com/yuuki/dynamond/timeparser"
)

const (
	DAYTIME = time.Duration(24 * 60 * 60) * time.Second
)

func Render(w http.ResponseWriter, r *http.Request) {
	until := time.Now()
	from := until.Add(-DAYTIME)

	if v := r.FormValue("from"); v != "" {
		t, err := timeparser.ParseAtTime(v)
		if err != nil {
			BadRequest(w, err.Error())
			return
		}
		from = t
	}
	if v := r.FormValue("until"); v != "" {
		t, err := timeparser.ParseAtTime(v)
		if err != nil {
			BadRequest(w, err.Error())
			return
		}
		until = t
	}
	log.Debugf("from:%d until:%d", from.Unix(), until.Unix())

	return
}

package handler

import (
	"net/http"
	"net/url"
	"time"

	"github.com/yuuki/dynamond/log"
	"github.com/yuuki/dynamond/timeparser"
)

const (
	DAYTIME = time.Duration(24 * 60 * 60) * time.Second
)

func Render(w http.ResponseWriter, r *http.Request) {
	until := time.Now()
	from := until.Add(-DAYTIME)

	if v := r.FormValue("from"); v != "" {
		t, err := timeparser.ParseAtTime(url.QueryEscape(v))
		if err != nil {
			BadRequest(w, err.Error())
			return
		}
		from = t
	}
	if v := r.FormValue("until"); v != "" {
		t, err := timeparser.ParseAtTime(url.QueryEscape(v))
		if err != nil {
			BadRequest(w, err.Error())
			return
		}
		until = t
	}
	log.Debugf("from:%d until:%d", from.Unix(), until.Unix())

	return
}

Fix to parse 'now+1y' becase FormValue has already unescaped


package of10

import . "github.com/oshothebig/goflow/openflow"

type FeaturesRequest struct {
	Header
}

type FeaturesReply struct {
	Header
	DatapathId   DatapathId
	Buffers      uint32
	Tables       uint8
	pad          [3]uint8
	Capabilities Capability
	Actions      ActionType
	Ports        []PhysicalPort
}

type DatapathId uint64
type Capability uint32

const (
	OFPC_FLOW_STATS Capability = 1 << iota
	OFPC_TABLE_STATS
	OFPC_PORT_STATS
	OFPC_STP
	OFPC_RESERVED
	OFPC_IP_REASM
	OFPC_QUEUE_STATS
	OFPC_ARP_MATCH_IP
)

var Capabilities = struct {
	FlowStats    Capability
	TableStats   Capability
	PortStats    Capability
	Stp          Capability
	Reserved     Capability
	IpReassemble Capability
	QueueStats   Capability
	ArpMatchIp   Capability
}{
	OFPC_FLOW_STATS,
	OFPC_TABLE_STATS,
	OFPC_PORT_STATS,
	OFPC_STP,
	OFPC_RESERVED,
	OFPC_IP_REASM,
	OFPC_QUEUE_STATS,
	OFPC_ARP_MATCH_IP,
}

Declare constant related to capability


package main

import (
	_ "expvar"
	"github.com/codegangsta/negroni"
	"github.com/meatballhat/negroni-logrus"
	"github.com/unrolled/render"
	"net/http"
)

func main() {
	Run()
}

func Run() {
	m := http.DefaultServeMux
	n := negroni.New(negroni.NewRecovery(), negroni.NewStatic(http.Dir("assets")))
	l := negronilogrus.NewMiddleware()
	r := render.New(render.Options{
		Layout: "layout",
	})

	n.Use(l)
	n.UseHandler(m)

	m.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		r.HTML(w, http.StatusOK, "index", "world")
	})

	addr := ":3000"
	l.Logger.Infof("Listening on %s", addr)
	l.Logger.Fatal(http.ListenAndServe(addr, n))
}

package main

import (
	_ "expvar"
	"github.com/codegangsta/negroni"
	"github.com/meatballhat/negroni-logrus"
	"github.com/unrolled/render"
	"net/http"
	"os"
)

func main() {
	Run()
}

func Run() {
	m := http.DefaultServeMux
	n := negroni.New(negroni.NewRecovery(), negroni.NewStatic(http.Dir("assets")))
	l := negronilogrus.NewMiddleware()
	r := render.New(render.Options{
		Layout: "layout",
	})

	n.Use(l)
	n.UseHandler(m)

	m.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		r.HTML(w, http.StatusOK, "index", "world")
	})

	var addr string
	if len(os.Getenv("PORT")) > 0 {
		addr = ":" + os.Getenv("PORT")
	} else {
		addr = ":3000"
	}

	l.Logger.Infof("Listening on %s", addr)
	l.Logger.Fatal(http.ListenAndServe(addr, n))
}

Allow port to be specified by environment variable


package main

import (
	"path"

	"gnd.la/app"
	"gnd.la/apps/docs"
	"gnd.la/net/urlutil"
)

const (
	//gondolaURL = "http://www.gondolaweb.com"
	gondolaURL = "ssh://abra.rm-fr.net/home/fiam/git/gondola.git"
)

func gndlaHandler(ctx *app.Context) {
	if ctx.FormValue("go-get") == "1" {
		ctx.MustExecute("goget.html", nil)
		return
	}
	// Check if the request path is a pkg name
	var p string
	pkg := path.Join("gnd.la", ctx.R.URL.Path)
	if _, err := docs.DefaultContext.Import(pkg, "", 0); err == nil {
		p = ctx.MustReverse(docs.PackageHandlerName, pkg)
	}
	redir, err := urlutil.Join(gondolaURL, p)
	if err != nil {
		panic(err)
	}
	ctx.Redirect(redir, false)
}

package main

import (
	"path"

	"gnd.la/app"
	"gnd.la/apps/docs"
	"gnd.la/net/urlutil"
)

const (
	gondolaURL = "http://www.gondolaweb.com"
)

func gndlaHandler(ctx *app.Context) {
	if ctx.FormValue("go-get") == "1" {
		ctx.MustExecute("goget.html", nil)
		return
	}
	// Check if the request path is a pkg name
	var p string
	pkg := path.Join("gnd.la", ctx.R.URL.Path)
	if _, err := docs.DefaultContext.Import(pkg, "", 0); err == nil {
		p = ctx.MustReverse(docs.PackageHandlerName, pkg)
	}
	redir, err := urlutil.Join(gondolaURL, p)
	if err != nil {
		panic(err)
	}
	ctx.Redirect(redir, false)
}

Update path to Gondola repository


package ec2

import (
	"github.com/jagregory/cfval/resources/common"
	. "github.com/jagregory/cfval/schema"
)

// see: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internet-gateway.html
func InternetGateway() Resource {
	return Resource{
		AwsType: "AWS::EC2::InternetGateway",

		// Name
		ReturnValue: Schema{
			Type: ValueString,
		},

		Properties: Properties{
			"Tags": Schema{
				Type:  common.ResourceTag,
				Array: true,
			},
		},
	}
}

package ec2

import (
	"github.com/jagregory/cfval/resources/common"
	. "github.com/jagregory/cfval/schema"
)

// see: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-internet-gateway.html
func InternetGateway() Resource {
	return Resource{
		AwsType: "AWS::EC2::InternetGateway",

		// Name -- not sure about this. Docs say Name, but my testing we can Ref
		//         this into an InternetGatewayId property successfully.
		ReturnValue: Schema{
			Type: InternetGatewayID,
		},

		Properties: Properties{
			"Tags": Schema{
				Type:  common.ResourceTag,
				Array: true,
			},
		},
	}
}

Change Ref value of Internet Gateway to an ID despite what the docs say


// gogl provides a framework for representing and working with graphs.
package gogl

type Vertex interface{}

type Graph interface {
	EachVertex(f func(vertex Vertex))
	EachEdge(f func(source Vertex, target Vertex))
	EachAdjacent(vertex Vertex, f func(adjacent Vertex))
	HasVertex(vertex Vertex) bool
	GetSubgraph([]Vertex) Graph
}

type MutableGraph interface {
	Graph
	AddVertex(v interface{}) bool
	RemoveVertex(v interface{}) bool
}

type DirectedGraph interface {
	Graph
	Transpose() DirectedGraph
	IsAcyclic() bool
	GetCycles() [][]interface{}
}

type MutableDirectedGraph interface {
	MutableGraph
	DirectedGraph
	addDirectedEdge(source interface{}, target interface{}) bool
	removeDirectedEdge(source interface{}, target interface{}) bool
}

type Edge interface {
	Tail() Vertex
	Head() Vertex
}

// gogl provides a framework for representing and working with graphs.
package gogl

// Constants defining graph capabilities and behaviors.
const (
  E_DIRECTED, EM_DIRECTED = 1 << iota, 1 << iota - 1
  E_UNDIRECTED, EM_UNDIRECTED
  E_WEIGHTED, EM_WEIGHTED
  E_TYPED, EM_TYPED
  E_SIGNED, EM_SIGNED
  E_LOOPS, EM_LOOPS
  E_MULTIGRAPH, EM_MULTIGRAPH
)

type Vertex interface{}

type Graph interface {
	EachVertex(f func(vertex Vertex))
	EachEdge(f func(source Vertex, target Vertex))
	EachAdjacent(vertex Vertex, f func(adjacent Vertex))
	HasVertex(vertex Vertex) bool
	GetSubgraph([]Vertex) Graph
}

type MutableGraph interface {
	Graph
	AddVertex(v interface{}) bool
	RemoveVertex(v interface{}) bool
}

type DirectedGraph interface {
	Graph
	Transpose() DirectedGraph
	IsAcyclic() bool
	GetCycles() [][]interface{}
}

type MutableDirectedGraph interface {
	MutableGraph
	DirectedGraph
	addDirectedEdge(source interface{}, target interface{}) bool
	removeDirectedEdge(source interface{}, target interface{}) bool
}

type Edge interface {
	Tail() Vertex
	Head() Vertex
}

Introduce bitfield describing edge capabilities.


package jo

// Events signal changes in scanning state.
type Event int

const (
	// Nothing of interest, continue scanning.
	None Event = 0

	// Same as None, but specifically for whitespace.
	Space = (1 << iota)

	// Start events.
	ObjectStart = (1 << iota)
	KeyStart
	ArrayStart
	StringStart
	NumberStart
	BoolStart
	NullStart

	// End events.
	ObjectEnd = (1 << iota)
	KeyEnd
	ArrayEnd
	StringEnd
	NumberEnd
	BoolEnd
	NullEnd

	// Syntax error.
	Error = (1 << iota)
)

package jo

// Events signal changes in scanning state.
type Event int

const (
	// Nothing of interest, continue scanning.
	None Event = 0

	// Same as None, but specifically for whitespace.
	Space = (1 << iota)

	// Start events.
	ObjectStart = (1 << iota)
	KeyStart
	ArrayStart
	StringStart
	NumberStart
	BoolStart
	NullStart

	// End events.
	ObjectEnd = (1 << iota)
	KeyEnd
	ArrayEnd
	StringEnd
	NumberEnd
	BoolEnd
	NullEnd

	// Start and end bitsets.
	Start = ObjectStart | KeyStart | ArrayStart | StringStart | NumberStart | BoolStart | NullStart
	End   = ObjectEnd | KeyEnd | ArrayEnd | StringEnd | NumberEnd | BoolEnd | NullEnd

	// Syntax error.
	Error = (1 << iota)
)

Add the Start and End bitsets


// +build freebsd darwin

package main

func (m *memData) Update() error {
	return nil
}

func getifnum() (int, error) {
	return 0, nil
}

func (nd *netData) Setup() error {
	return nil
}

func (nd *netData) Update() error {
	return nil
}

// +build freebsd darwin

package main

import (
	"github.com/blabber/go-freebsd-sysctl/sysctl"
)

var pagesize int64
var pae bool

func init() {
	var err error
	pagesize, err = sysctl.GetInt64("hw.pagesize")
	if err != nil {
		panic(err)
	}

	_, err = sysctl.GetString("kern.features.pae")
	if err.Error() == "no such file or directory" {
		pae = false
	} else {
		pae = true
	}

}

func (m *memData) Update() error {
	if pae {
		mtemp, err := sysctl.GetInt64("hw.availpages")
		if err != nil {
			panic(err)
		}
		m.memTotal = uint64(mtemp * pagesize)
	}
	mtemp, err := sysctl.GetInt64("hw.physmem")
	if err != nil {
		panic(err)
	}
	m.memTotal = uint64(mtemp)

	mtemp, err = sysctl.GetInt64("vm.stats.vm.v_free_count")
	if err != nil {
		panic(err)
	}
	m.memFree = uint64(mtemp * pagesize)

	m.memUse = m.memTotal - m.memFree
	m.memPercent = int(m.memUse * 100 / m.memTotal)
	return nil
}

func getifnum() (int, error) {
	return 0, nil
}

func (nd *netData) Setup() error {
	return nil
}

func (nd *netData) Update() error {
	return nil
}

Correct memory usage status on FreeBSD


package main

import (
	"flag"
	"os"

	"github.com/ian-kent/Go-MailHog/MailHog-Server/config"
	"github.com/ian-kent/Go-MailHog/MailHog-UI/assets"
	"github.com/ian-kent/Go-MailHog/MailHog-UI/http/web"
	"github.com/ian-kent/Go-MailHog/http"
	"github.com/ian-kent/go-log/log"
	gotcha "github.com/ian-kent/gotcha/app"
)

var conf *config.Config
var exitCh chan int

func configure() {
	config.RegisterFlags()
	flag.Parse()
	conf = config.Configure()
}

func main() {
	configure()

	// FIXME need to make API URL configurable

	exitCh = make(chan int)
	cb := func(app *gotcha.App) {
		web.CreateWeb(conf, app)
	}
	go http.Listen(conf, assets.Asset, exitCh, cb)

	for {
		select {
		case <-exitCh:
			log.Printf("Received exit signal")
			os.Exit(0)
		}
	}
}

package main

import (
	"flag"
	"os"

	"github.com/ian-kent/Go-MailHog/MailHog-Server/config"
	"github.com/ian-kent/Go-MailHog/MailHog-UI/assets"
	"github.com/ian-kent/Go-MailHog/MailHog-UI/web"
	"github.com/ian-kent/Go-MailHog/http"
	"github.com/ian-kent/go-log/log"
	gotcha "github.com/ian-kent/gotcha/app"
)

var conf *config.Config
var exitCh chan int

func configure() {
	config.RegisterFlags()
	flag.Parse()
	conf = config.Configure()
}

func main() {
	configure()

	// FIXME need to make API URL configurable

	exitCh = make(chan int)
	cb := func(app *gotcha.App) {
		web.CreateWeb(conf, app)
	}
	go http.Listen(conf, assets.Asset, exitCh, cb)

	for {
		select {
		case <-exitCh:
			log.Printf("Received exit signal")
			os.Exit(0)
		}
	}
}

Remove old tests, fix import


package main

import (
	"bufio"
	"os"

	"github.com/calebthompson/ftree/tree"
)

func main() {
	r := bufio.NewScanner(os.Stdin)
	lines := []string{}
	for r.Scan() {
		lines = append(lines, r.Text())
	}

	t := tree.Tree(lines, "/")
	t.Print(0, nil)
}

package main

import (
	"bufio"
	"fmt"
	"os"

	"github.com/calebthompson/ftree/tree"
)

const (
	version = "v0.1.0"
	help    = `Pipe output from some command that lists a single file per line to ftree.
	find . | ftree
	git ls-files {app,spec}/models | ftree
	lsrc | cut -d : -f 1 | ftree
`
)

func main() {
	handleArguments()

	r := bufio.NewScanner(os.Stdin)
	lines := []string{}
	for r.Scan() {
		lines = append(lines, r.Text())
	}

	t := tree.Tree(lines, "/")
	t.Print(0, nil)
}

func handleArguments() {
	for _, a := range os.Args[1:] {
		switch a {
		case "--version", "-v":
			fmt.Printf("ftree %s\n", version)
			os.Exit(0)
		case "--help", "-h":
			fmt.Print(help)
			os.Exit(0)
		default:
			fmt.Fprintf(os.Stderr, "No such argument: %v\n", a)
			os.Exit(1)
		}
	}
}

Add version and help arguments


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

package main

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

var port = flag.Int("port", 8000, "port number")

func init() {
	flag.Parse()
}

func main() {
	http.Handle("/", http.FileServer(http.Dir("public")))
	fmt.Printf("http://localhost:%d/\n", *port)
	log.Fatal(http.ListenAndServe(":"+strconv.Itoa(*port), nil))
}

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

package main

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

var port = flag.Int("port", 8000, "port number")

func init() {
	flag.Parse()
}

func main() {
	http.Handle("/", http.FileServer(http.Dir("public")))
	fmt.Printf("http://localhost:%d/\n", *port)
	log.Fatal(http.ListenAndServe(":"+strconv.Itoa(*port), nil))
}

Update license year in a new file


package stats

import (
	"fmt"
	"github.com/callpraths/gorobdd/internal/node"
)

func CountNodes(n *node.Node) (int, error) {
	m := make(map[*node.Node]bool)
	return countNodesHelper(n, m)
}

func countNodesHelper(n *node.Node, m map[*node.Node]bool) (int, error) {
	_, seen := m[n]
	if seen {
		return 0, nil
	}
	m[n] = true
	switch n.Type {
	case node.LeafType:
		return 1, nil
	case node.InternalType:
		t, et := countNodesHelper(n.True, m)
		if et != nil {
			return t, et
		}
		f, ef := countNodesHelper(n.False, m)
		if ef != nil {
			return f, ef
		}
		return t + f + 1, nil
	default:
		return -1, fmt.Errorf("Malformed node: %v", n)
	}

}

package stats

import (
	"fmt"
	"github.com/callpraths/gorobdd/internal/node"
	"github.com/callpraths/gorobdd/internal/tag"
)

func CountNodes(n *node.Node) (int, error) {
	s := tag.NewSeenContext()
	return countNodesHelper(n, s)
}

func countNodesHelper(n *node.Node, s tag.SeenContext) (int, error) {
	if s.IsSeen(n) {
		return 0, nil
	}
	s.MarkSeen(n)
	switch n.Type {
	case node.LeafType:
		return 1, nil
	case node.InternalType:
		t, et := countNodesHelper(n.True, s)
		if et != nil {
			return t, et
		}
		f, ef := countNodesHelper(n.False, s)
		if ef != nil {
			return f, ef
		}
		return t + f + 1, nil
	default:
		return -1, fmt.Errorf("Malformed node: %v", n)
	}

}

Implement CountNodes using the seen tag.


package rdbtools

import (
	"fmt"
	"time"
)

type KeyObject struct {
	ExpiryTime time.Time
	Key        interface{}
}

func NewKeyObject(key interface{}, expiryTime int64) KeyObject {
	k := KeyObject{
		Key: key,
	}
	if expiryTime >= 0 {
		k.ExpiryTime = time.Unix(expiryTime/1000, 0)
	}

	return k
}

func (k KeyObject) Expired() bool {
	return k.ExpiryTime.Before(time.Now())
}

func (k KeyObject) String() string {
	if !k.ExpiryTime.IsZero() {
		return fmt.Sprintf("KeyObject{ExpiryTime: %s, Key: %s}", k.ExpiryTime.UTC(), DataToString(k.Key))
	}

	return fmt.Sprintf("%s", DataToString(k.Key))
}

package rdbtools

import (
	"fmt"
	"time"
)

type KeyObject struct {
	ExpiryTime time.Time
	Key        interface{}
}

func NewKeyObject(key interface{}, expiryTime int64) KeyObject {
	k := KeyObject{
		Key: key,
	}
	if expiryTime >= 0 {
		k.ExpiryTime = time.Unix(expiryTime/1000, 0).UTC()
	}

	return k
}

func (k KeyObject) Expired() bool {
	return k.ExpiryTime.Before(time.Now())
}

func (k KeyObject) String() string {
	if !k.ExpiryTime.IsZero() {
		return fmt.Sprintf("KeyObject{ExpiryTime: %s, Key: %s}", k.ExpiryTime, DataToString(k.Key))
	}

	return fmt.Sprintf("%s", DataToString(k.Key))
}

Store the expiry time in UTC directly


package ast_test

import (
	"strings"
	"testing"

	"github.com/DeedleFake/wdte/ast"
)

func printTree(t *testing.T, cur ast.Node, depth int) {
	indent := strings.Repeat("  ", depth)
	switch cur := cur.(type) {
	case *ast.Term:
		t.Logf("%v%v", indent, cur)

	case *ast.NTerm:
		t.Logf("%v(%v", indent, cur)
		for _, c := range cur.Children() {
			printTree(t, c, depth+1)
		}
		t.Logf("%v)", indent)

	case *ast.Epsilon:
		t.Logf("%vε", indent)

	default:
		t.Fatalf("Unexpected node: %#v", cur)
	}
}

func TestParse(t *testing.T) {
	//const test = `"test" => t; + x y => nil;`

	const test = `
'test' => test;

fib n => switch n {
	0 => 0;
	default => + (fib (- n 1;);) (fib (- n 2;););
};

main => print (fib 5;);
`

	root, err := ast.Parse(strings.NewReader(test))
	if err != nil {
		t.Fatal(err)
	}
	printTree(t, root, 0)
}

package ast_test

import (
	"strings"
	"testing"

	"github.com/DeedleFake/wdte/ast"
)

func printTree(t *testing.T, cur ast.Node, depth int) {
	indent := strings.Repeat("  ", depth)
	switch cur := cur.(type) {
	case *ast.Term:
		t.Logf("%v%v", indent, cur)

	case *ast.NTerm:
		t.Logf("%v(%v", indent, cur)
		for _, c := range cur.Children() {
			printTree(t, c, depth+1)
		}
		t.Logf("%v)", indent)

	case *ast.Epsilon:
		t.Logf("%vε", indent)

	default:
		t.Fatalf("Unexpected node: %#v", cur)
	}
}

func TestParse(t *testing.T) {
	//const test = `"test" => t; + x y => nil;`

	const test = `
'test' => test;

fib n => switch n {
	0 => 0;
	default => + (fib (- n 1)) (fib (- n 2));
};

main => print (fib 5);
`

	root, err := ast.Parse(strings.NewReader(test))
	if err != nil {
		t.Fatal(err)
	}
	printTree(t, root, 0)
}

Remove optional semicolons from test.


package main

import (
	"net/http"
	"strings"
)

var (
	// Whitelist crawlers here
	crawlerPatterns = [...]string{
		"Googlebot",
		"bingbot",
		"MSNbot",
		"facebookexternalhit",
		"PlurkBot",
		"Twitterbot",
		"CloudFlare-AlwaysOnline",
	}
)

func isCrawlerUserAgent(r *http.Request) bool {
	ua := r.UserAgent()

	for _, pattern := range crawlerPatterns {
		if strings.Contains(ua, pattern) {
			return true
		}
	}

	return false
}

package main

import (
	"net/http"
	"strings"
)

var (
	// Whitelist crawlers here
	crawlerPatterns = [...]string{
		"Google (+https://developers.google.com/+/web/snippet/)",
		"Googlebot",
		"bingbot",
		"MSNbot",
		"facebookexternalhit",
		"PlurkBot",
		"Twitterbot",
		"CloudFlare-AlwaysOnline",
	}
)

func isCrawlerUserAgent(r *http.Request) bool {
	ua := r.UserAgent()

	for _, pattern := range crawlerPatterns {
		if strings.Contains(ua, pattern) {
			return true
		}
	}

	return false
}

Add Google+ snippet fetcher to crawler list


package cf_test

import (
	. "cf"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"path/filepath"
)

var _ = Describe("AppFiles", func() {
	fixturePath := filepath.Join("..", "fixtures", "applications")

	Describe("AppFilesInDir", func() {
		It("all files have '/' path separators", func() {
			files, err := AppFilesInDir(fixturePath)
			Expect(err).ShouldNot(HaveOccurred())

			for _, afile := range files {
				Expect(afile.Path).Should(Equal(filepath.ToSlash(afile.Path)))
			}
		})

		It("excludes files based on the .cfignore file", func() {
			appPath := filepath.Join(fixturePath, "app-with-cfignore")
			files, err := AppFilesInDir(appPath)
			Expect(err).ShouldNot(HaveOccurred())

			paths := []string{}
			for _, file := range files {
				paths = append(paths, file.Path)
			}

			Expect(paths).To(Equal([]string{
				filepath.Join("dir1", "child-dir", "file3.txt"),
				filepath.Join("dir1", "file1.txt"),
			}))
		})
	})
})

package cf_test

import (
	. "cf"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"path/filepath"
	"path"
)

var _ = Describe("AppFiles", func() {
	fixturePath := filepath.Join("..", "fixtures", "applications")

	Describe("AppFilesInDir", func() {
		It("all files have '/' path separators", func() {
			files, err := AppFilesInDir(fixturePath)
			Expect(err).ShouldNot(HaveOccurred())

			for _, afile := range files {
				Expect(afile.Path).Should(Equal(filepath.ToSlash(afile.Path)))
			}
		})

		It("excludes files based on the .cfignore file", func() {
			appPath := filepath.Join(fixturePath, "app-with-cfignore")
			files, err := AppFilesInDir(appPath)
			Expect(err).ShouldNot(HaveOccurred())

			paths := []string{}
			for _, file := range files {
				paths = append(paths, file.Path)
			}

			Expect(paths).To(Equal([]string{
				path.Join("dir1", "child-dir", "file3.txt"),
				path.Join("dir1", "file1.txt"),
			}))
		})
	})
})

Fix app files test on windows


package anaconda

type Tweet struct {
	Source        string
	Id            int64
	Retweeted     bool
	Favorited     bool
	User          TwitterUser
	Truncated     bool
	Text          string
	Retweet_count int64
	Id_str        string
	Created_at    string
	Entities      TwitterEntities
}

package anaconda

import (
    "time"
)

type Tweet struct {
	Source        string
	Id            int64
	Retweeted     bool
	Favorited     bool
	User          TwitterUser
	Truncated     bool
	Text          string
	Retweet_count int64
	Id_str        string
	Created_at    string
	Entities      TwitterEntities
}

// CreatedAtTime is a convenience wrapper that returns the Created_at time, parsed as a time.Time struct
func (t Tweet) CreatedAtTime() (time.Time, error){
    return time.Parse(time.RubyDate, t.Created_at)
}

Add CreatedAtTime() convenience wrapper function


package radius

import (
	"encoding/binary"
	"io"
)

// AttributeType defines types for an Attribute
type AttributeType int64

const (

	// Attributes for RFC2866/Radius accounting
	AccountingStatusType     AttributeType = 40
	AccountingDelayTime      AttributeType = 41
	AccountingInputOctets    AttributeType = 42
	AccountingOutputOctets   AttributeType = 43
	AccountingSessionID      AttributeType = 44
	AccountingAuthentic      AttributeType = 45
	AccountingSessionTime    AttributeType = 46
	AccountingInputPackets   AttributeType = 47
	AccountingOutputPackets  AttributeType = 48
	AccountingTerminateCause AttributeType = 49
	AccountingMultiSessionID AttributeType = 50
	AccountingMultiLinkCount AttributeType = 51
	// --

)

// Write writes the attribute type to the given writer
func (a AttributeType) Write(w io.Writer) error {
	return binary.Write(w, binary.BigEndian, int8(a))
}

package radius

import "io"

// AttributeType defines types for an Attribute
type AttributeType int64

const (

	// Attributes for RFC2866/Radius accounting
	AccountingStatusType     AttributeType = 40
	AccountingDelayTime      AttributeType = 41
	AccountingInputOctets    AttributeType = 42
	AccountingOutputOctets   AttributeType = 43
	AccountingSessionID      AttributeType = 44
	AccountingAuthentic      AttributeType = 45
	AccountingSessionTime    AttributeType = 46
	AccountingInputPackets   AttributeType = 47
	AccountingOutputPackets  AttributeType = 48
	AccountingTerminateCause AttributeType = 49
	AccountingMultiSessionID AttributeType = 50
	AccountingMultiLinkCount AttributeType = 51
	// --

)

// Write writes the attribute type to the given writer
func (a AttributeType) Write(w io.Writer) error {
	_, err := w.Write([]byte{byte(a)})
	return err
}

Remove unnecesary endianness from attribute type writer


// The original error message returned by stdlib changed with go1.8.
// We only test the latest release.
//
//+build go1.8 forcego1.8

package jsonptrerror_test

import (
	"fmt"
	"strings"

	"github.com/dolmen-go/jsonptrerror"
)

func ExampleDecoder() {
	decoder := jsonptrerror.NewDecoder(strings.NewReader(
		`{"key": "x", "value": 5}`,
	))
	var out struct {
		Key   string `json:"key"`
		Value bool   `json:"value"`
	}
	err := decoder.Decode(&out)
	fmt.Println(err)
	if err, ok := err.(*jsonptrerror.UnmarshalTypeError); ok {
		fmt.Println("Original error:", err.UnmarshalTypeError.Error())
		fmt.Println("Error location:", err.Pointer)
	}

	// Output:
	// /value: cannot unmarshal number into Go value of type bool
	// Original error: json: cannot unmarshal number into Go struct field .value of type bool
	// Error location: /value
}

// The original error message returned by stdlib changed with go1.8.
// We only test the latest release.
//
//+build go1.8 forcego1.8

package jsonptrerror_test

import (
	"fmt"
	"strings"

	"github.com/dolmen-go/jsonptrerror"
)

func ExampleDecoder() {
	decoder := jsonptrerror.NewDecoder(strings.NewReader(
		`{"key": "x", "value": 5}`,
	))
	var out struct {
		Key   string `json:"key"`
		Value bool   `json:"value"`
	}
	err := decoder.Decode(&out)
	fmt.Println(err)
	if err, ok := err.(*jsonptrerror.UnmarshalTypeError); ok {
		//fmt.Println("Original error:", err.UnmarshalTypeError.Error())
		fmt.Println("Error location:", err.Pointer)
	}

	// Output:
	// /value: cannot unmarshal number into Go value of type bool
	// Error location: /value
}

Fix Example to not show the original error (which is go version dependent)


package api_test

import (
	"log"
	"net/http"
	"os"
	"testing"

	"github.com/jvikstedt/alarmy/api"
	"github.com/jvikstedt/alarmy/store"
)

var handler http.Handler
var mockStore *store.MockStore

func TestMain(m *testing.M) {
	setup()
	retCode := m.Run()
	os.Exit(retCode)
}

func setup() {
	mockStore = &store.MockStore{}
	store := store.Store{
		ProjectStore: mockStore,
	}

	logger := log.New(os.Stdout, "", log.LstdFlags)
	api := api.NewApi(store, logger)

	var err error
	handler, err = api.Handler()
	if err != nil {
		panic(err)
	}
}

package api_test

import (
	"bytes"
	"log"
	"net/http"
	"os"
	"testing"

	"github.com/jvikstedt/alarmy/api"
	"github.com/jvikstedt/alarmy/store"
)

var handler http.Handler
var mockStore *store.MockStore
var logs = &bytes.Buffer{}

func TestMain(m *testing.M) {
	setup()
	retCode := m.Run()
	os.Exit(retCode)
}

func setup() {
	mockStore = &store.MockStore{}
	store := store.Store{
		ProjectStore: mockStore,
	}

	logger := log.New(logs, "", log.LstdFlags)
	api := api.NewApi(store, logger)

	var err error
	handler, err = api.Handler()
	if err != nil {
		panic(err)
	}
}

Write test logs to a buffer, so it can be used for testing and cleaner test output


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

package lxdclient

import (
	"github.com/juju/errors"
)

type rawProfileClient interface {
	ProfileCreate(name string) error
	ListProfiles() ([]string, error)
	SetProfileConfigItem(name, key, value string) error
}

type profileClient struct {
	raw rawProfileClient
}

// CreateProfile attempts to create a new lxc profile and set the given config.
func (p profileClient) CreateProfile(name string, config map[string]string) error {
	if err := p.raw.ProfileCreate(name); err != nil {
		//TODO(wwitzel3) use HasProfile to generate a more useful AlreadyExists error
		return errors.Trace(err)
	}

	for k, v := range config {
		if err := p.raw.SetProfileConfigItem(name, k, v); err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}

// HasProfile returns true/false if the profile exists.
func (p profileClient) HasProfile(name string) (bool, error) {
	profiles, err := p.raw.ListProfiles()
	if err != nil {
		return false, errors.Trace(err)
	}
	for _, profile := range profiles {
		if profile == name {
			return true, nil
		}
	}
	return false, nil
}

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

// +build go1.3

package lxdclient

import (
	"github.com/juju/errors"
)

type rawProfileClient interface {
	ProfileCreate(name string) error
	ListProfiles() ([]string, error)
	SetProfileConfigItem(name, key, value string) error
}

type profileClient struct {
	raw rawProfileClient
}

// CreateProfile attempts to create a new lxc profile and set the given config.
func (p profileClient) CreateProfile(name string, config map[string]string) error {
	if err := p.raw.ProfileCreate(name); err != nil {
		//TODO(wwitzel3) use HasProfile to generate a more useful AlreadyExists error
		return errors.Trace(err)
	}

	for k, v := range config {
		if err := p.raw.SetProfileConfigItem(name, k, v); err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}

// HasProfile returns true/false if the profile exists.
func (p profileClient) HasProfile(name string) (bool, error) {
	profiles, err := p.raw.ListProfiles()
	if err != nil {
		return false, errors.Trace(err)
	}
	for _, profile := range profiles {
		if profile == name {
			return true, nil
		}
	}
	return false, nil
}

Add a missing build constraint.


package main

import (
	"flag"
	"fmt"
	"os"
)

var (
	flBroker        string
	flConsumerGroup string
	flTopic         string
	flPartition     int
	flNewest        bool

	fsConsumerGroup = flag.NewFlagSet("cgo", flag.ContinueOnError)
	fsGetOffset     = flag.NewFlagSet("go", flag.ContinueOnError)
)

func init() {
	flag.Usage = printUsage

	fsConsumerGroup.StringVar(&flBroker, "b", "", "The broker to use")
	fsConsumerGroup.StringVar(&flConsumerGroup, "c", "", "The consumer group")
	fsConsumerGroup.StringVar(&flTopic, "t", "", "The topic")
	fsConsumerGroup.IntVar(&flPartition, "p", -1, "The partition")

	fsGetOffset.StringVar(&flBroker, "b", "", "The broker to use")
	fsGetOffset.StringVar(&flTopic, "t", "", "The topic")
	fsGetOffset.IntVar(&flPartition, "p", -1, "The partition")
	fsGetOffset.BoolVar(&flNewest, "n", true, "Get the newest offset instead of the oldest")
}

func printUsage() {
	fmt.Fprintf(os.Stderr, "Usage of %s\n", os.Args[0])
	flag.PrintDefaults()
	fmt.Fprintf(os.Stderr, "\nSubcommands:\n\ncgo (consumer group get offset)\n")
	fsConsumerGroup.PrintDefaults()
	fmt.Fprintf(os.Stderr, "\ngo (get offset)\n")
	fsGetOffset.PrintDefaults()
}

package main

import (
	"flag"
	"fmt"
	"os"
)

var (
	flBroker        string
	flConsumerGroup string
	flTopic         string
	flPartition     int
	flNewest        bool

	fsConsumerGroup = flag.NewFlagSet("cgo", flag.ContinueOnError)
	fsGetOffset     = flag.NewFlagSet("go", flag.ContinueOnError)
)

func init() {
	flag.Usage = printUsage

	flag.StringVar(&flBroker, "b", "", "The broker to use")

	fsConsumerGroup.StringVar(&flConsumerGroup, "c", "", "The consumer group")
	fsConsumerGroup.StringVar(&flTopic, "t", "", "The topic")
	fsConsumerGroup.IntVar(&flPartition, "p", -1, "The partition")

	fsGetOffset.StringVar(&flTopic, "t", "", "The topic")
	fsGetOffset.IntVar(&flPartition, "p", -1, "The partition")
	fsGetOffset.BoolVar(&flNewest, "n", true, "Get the newest offset instead of the oldest")
}

func printUsage() {
	fmt.Fprintf(os.Stderr, "Usage of %s\n", os.Args[0])
	flag.PrintDefaults()
	fmt.Fprintf(os.Stderr, "\nSubcommands:\n\ncgo (consumer group get offset)\n")
	fsConsumerGroup.PrintDefaults()
	fmt.Fprintf(os.Stderr, "\ngo (get offset)\n")
	fsGetOffset.PrintDefaults()
}

Make the broker flag global


// package core contains the core data structures and functionality
// leveraged y the other other Goed packages.
package core

import "os"

const Version = "0.0.3"
const ApiVersion = "v1"

var Trace = false

// Ed is thew editor singleton
var Ed Editable

// Colors is the number of colors to use in the terminal
var Colors int

// Home represent the goed "home" folder.
var Home string

// testing : whether we are in "unit test" mode.
var Testing bool

// ConfigFile holds the path to the config file currently in use.
var ConfFile string

// LogFile holds the path of the log file currently in use.
var LogFile *os.File

// terminal as defined by $SHELL
var Terminal string

var Bus ActionDispatcher

var ApiPort int

var Socket string // instance RPC socket

var InstanceId int64 // instance ID

type CursorMvmt byte

const (
	CursorMvmtRight CursorMvmt = iota
	CursorMvmtLeft
	CursorMvmtUp
	CursorMvmtDown
	CursorMvmtPgDown
	CursorMvmtPgUp
	CursorMvmtHome
	CursorMvmtEnd
	CursorMvmtTop
	CursorMvmtBottom
)

type ViewType int

const (
	ViewTypeStandard ViewType = iota
	ViewTypeInteractive
)

// package core contains the core data structures and functionality
// leveraged y the other other Goed packages.
package core

import "os"

const Version = "0.0.3"
const ApiVersion = "v1"

var Trace = true

// Ed is thew editor singleton
var Ed Editable

// Colors is the number of colors to use in the terminal
var Colors int

// Home represent the goed "home" folder.
var Home string

// testing : whether we are in "unit test" mode.
var Testing bool

// ConfigFile holds the path to the config file currently in use.
var ConfFile string

// LogFile holds the path of the log file currently in use.
var LogFile *os.File

// terminal as defined by $SHELL
var Terminal string

var Bus ActionDispatcher

var ApiPort int

var Socket string // instance RPC socket

var InstanceId int64 // instance ID

type CursorMvmt byte

const (
	CursorMvmtRight  CursorMvmt = 0
	CursorMvmtLeft              = 1
	CursorMvmtUp                = 2
	CursorMvmtDown              = 3
	CursorMvmtPgDown            = 4
	CursorMvmtPgUp              = 5
	CursorMvmtHome              = 6
	CursorMvmtEnd               = 7
	CursorMvmtTop               = 8
	CursorMvmtBottom            = 9
)

type ViewType int

const (
	ViewTypeStandard ViewType = iota
	ViewTypeInteractive
)

Use fixed constant values for cursorMvmt


package main

import (
	"encoding/json"
	"io/ioutil"

	"github.com/jinzhu/gorm"
	_ "github.com/lib/pq"
)

type ThumbnailSize struct {
	Width  uint
	Height uint
}

var ThumbnailSizes = map[string]ThumbnailSize{
	"small": ThumbnailSize{100, 100},
	"large": ThumbnailSize{500, 500},
}

type Config struct {
	SourceFolderPath         string `json:"source_folder_path"`
	DestinationFolderPath    string `json:"destination_folder_path"`
	ThumbnailsFolderPath     string `json:"thumbnails_folder_path"`
	DatabaseConnectionString string `json:"database_connection_string"`
}

func LoadConfig(configPath string) (Config, error) {
	var config Config
	file, err := ioutil.ReadFile(configPath)
	if err != nil {
		return config, err
	}
	err = json.Unmarshal(file, &config)
	return config, err
}

func SetupDatabase(connectionString string) gorm.DB {
	db, err := gorm.Open("postgres", connectionString)
	if err != nil {
		panic("Unable to open database")
	}

	db.AutoMigrate(&Photo{}, &SimilarPhoto{})
	return db
}

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"path"

	"github.com/jinzhu/gorm"
	_ "github.com/lib/pq"
)

type ThumbnailSize struct {
	Width  uint
	Height uint
}

var ThumbnailSizes = map[string]ThumbnailSize{
	"small": ThumbnailSize{100, 100},
	"large": ThumbnailSize{500, 500},
}

type Config struct {
	SourceFolderPath         string `json:"source_folder_path"`
	DestinationFolderPath    string `json:"destination_folder_path"`
	ThumbnailsFolderPath     string `json:"thumbnails_folder_path"`
	DatabaseConnectionString string `json:"database_connection_string"`
}

func LoadConfig(configPath string) (Config, error) {
	var config Config
	file, err := ioutil.ReadFile(configPath)
	if err != nil {
		return config, err
	}
	err = json.Unmarshal(file, &config)
	return config, err
}

func SetupDatabase(connectionString string) gorm.DB {
	db, err := gorm.Open("postgres", connectionString)
	if err != nil {
		panic("Unable to open database")
	}

	db.AutoMigrate(&Photo{}, &SimilarPhoto{})
	return db
}

func PartitionIdAsPath(input int64) string {
	inputRunes := []rune(fmt.Sprintf("%09d", input))
	return path.Join(
		string(inputRunes[0:3]),
		string(inputRunes[3:6]),
		string(inputRunes[6:]),
	)
}

Add method to partition id into thumbnail path


package cli

import (
	"testing"

	"github.com/libopenstorage/openstorage/api"
	"github.com/stretchr/testify/require"
)

func TestCmdMarshalProto(t *testing.T) {
	volumeSpec := &api.VolumeSpec{
		Size:   64,
		Format: api.FSType_FS_TYPE_EXT4,
	}
	data := cmdMarshalProto(volumeSpec, false)
	require.Equal(
		t,
		`{
 "ephemeral": false,
 "size": "64",
 "format": "ext4",
 "block_size": "0",
 "ha_level": "0",
 "cos": "none",
 "io_profile": "sequential",
 "dedupe": false,
 "snapshot_interval": 0,
 "shared": false,
 "aggregation_level": 0,
 "encrypted": false,
 "passphrase": "",
 "snapshot_schedule": "",
 "scale": 0,
 "sticky": false,
 "max_backups": 0,
 "backup_schedule": "",
 "group_enforced": false
}`,
		data,
	)
}

package cli

import (
	"testing"

	"github.com/libopenstorage/openstorage/api"
	"github.com/stretchr/testify/require"
)

func TestCmdMarshalProto(t *testing.T) {
	volumeSpec := &api.VolumeSpec{
		Size:   64,
		Format: api.FSType_FS_TYPE_EXT4,
	}
	data := cmdMarshalProto(volumeSpec, false)
	require.Equal(
		t,
		`{
 "ephemeral": false,
 "size": "64",
 "format": "ext4",
 "block_size": "0",
 "ha_level": "0",
 "cos": "none",
 "io_profile": "sequential",
 "dedupe": false,
 "snapshot_interval": 0,
 "shared": false,
 "aggregation_level": 0,
 "encrypted": false,
 "passphrase": "",
 "snapshot_schedule": "",
 "scale": 0,
 "sticky": false,
 "group_enforced": false
}`,
		data,
	)
}

Update UT for removed fields


// +build !freebsd

package mint_test

import (
	"os"
	"testing"

	"github.com/otiai10/mint"
)

// Exit
func TestExit(t *testing.T) {
	mint.Expect(t, func() {
		os.Exit(999999)
	}).Exit(999999)

	mint.Expect(t, func() {
		os.Exit(1)
	}).Not().Exit(0)
}

// +build !freebsd

package mint_test

import (
	"os"
	"testing"

	"github.com/otiai10/mint"
)

// Exit
func TestExit(t *testing.T) {
	mint.Expect(t, func() {
		os.Exit(999999)
	}).Exit(999999)

	mint.Expect(t, func() {
		os.Exit(1)
	}).Not().Exit(0)

	r := mint.Expect(t, func() {
		os.Exit(0)
	}).Dry().Exit(1)
	mint.Expect(t, r.OK()).ToBe(false)
}

Cover negative test case of "Exit"


// +build linux

package specs

// LinuxSpec is the full specification for linux containers.
type LinuxSpec struct {
	Spec
	// Linux is platform specific configuration for linux based containers.
	Linux Linux `json:"linux"`
}

// Linux contains platform specific configuration for linux based containers.
type Linux struct {
	// Capabilities are linux capabilities that are kept for the container.
	Capabilities []string `json:"capabilities"`
	// RootfsPropagation is the rootfs mount propagation mode for the container.
	RootfsPropagation string `json:"rootfsPropagation"`
}

// User specifies linux specific user and group information for the container's
// main process.
type User struct {
	// Uid is the user id.
	Uid int32 `json:"uid"`
	// Gid is the group id.
	Gid int32 `json:"gid"`
	// AdditionalGids are additional group ids set for the container's process.
	AdditionalGids []int32 `json:"additionalGids"`
}

// +build linux

package specs

// LinuxSpec is the full specification for linux containers.
type LinuxSpec struct {
	Spec
	// Linux is platform specific configuration for linux based containers.
	Linux Linux `json:"linux"`
}

// Linux contains platform specific configuration for linux based containers.
type Linux struct {
	// Capabilities are linux capabilities that are kept for the container.
	Capabilities []string `json:"capabilities"`
	// RootfsPropagation is the rootfs mount propagation mode for the container.
	RootfsPropagation string `json:"rootfsPropagation"`
}

// User specifies linux specific user and group information for the container's
// main process.
type User struct {
	// UID is the user id.
	UID int32 `json:"uid"`
	// GID is the group id.
	GID int32 `json:"gid"`
	// AdditionalGids are additional group ids set for the container's process.
	AdditionalGids []int32 `json:"additionalGids"`
}

Return golang compliant names for UID and GID in User


package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"os"
	"os/signal"
)

type LogplexPrint struct{}

func (*LogplexPrint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	log.Printf("Request: %#v", *r)
	w.WriteHeader(http.StatusNoContent)
}

func main() {
	s := httptest.NewTLSServer(&LogplexPrint{})
	fmt.Println(s.URL)

	// Signal handling:
	sigch := make(chan os.Signal)
	signal.Notify(sigch, os.Interrupt, os.Kill)
	for sig := range sigch {
		log.Printf("got signal %v", sig)
		if sig == os.Kill {
			os.Exit(2)
		} else if sig == os.Interrupt {
			os.Exit(0)
		}
	}
}

package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httptest"
	"net/http/httputil"
	"os"
	"os/signal"
)

type LogplexPrint struct{}

func (*LogplexPrint) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	dump, err := httputil.DumpRequest(r, true)
	if err != nil {
		log.Printf("Could not dump request: %#v", err)
	}

	log.Printf("%s", dump)

	// Respond saying everything is OK.
	w.WriteHeader(http.StatusNoContent)

}

func main() {
	s := httptest.NewTLSServer(&LogplexPrint{})
	fmt.Println(s.URL)

	// Signal handling:
	sigch := make(chan os.Signal)
	signal.Notify(sigch, os.Interrupt, os.Kill)
	for sig := range sigch {
		log.Printf("got signal %v", sig)
		if sig == os.Kill {
			os.Exit(2)
		} else if sig == os.Interrupt {
			os.Exit(0)
		}
	}
}

Use httputil DumpRequest instead of just %v formatting


package CoreModule

import (
	"fmt"
	"github.com/bwmarrin/discordgo"
	"github.com/gendonl/genbot/Bot"
	"time"
)

func initPingCommand() (cc CoreCommand) {
	cc = CoreCommand{
		name:        "ping",
		description: "Returns pong.",
		usage:       "`%sping`",
		aliases:	 []string{},
		permission:  discordgo.PermissionSendMessages,
		execute:     (*CoreModule).pingCommand,
	}
	return
}

func (c *CoreModule) pingCommand(cmd CoreCommand, s *discordgo.Session, m *discordgo.MessageCreate, data *Bot.ServerData) {

	ping := s.HeartbeatLatency() / time.Millisecond

	response := Bot.NewEmbed().
		SetAuthorFromUser(m.Author).
		SetColorFromUser(s, m.ChannelID, m.Author).
		SetDescription(fmt.Sprintf("❤ %dms", ping))

	_, err := s.ChannelMessageSendEmbed(m.ChannelID, response.MessageEmbed)

	if err != nil {
		c.Bot.Log.Error(err)
		return
	}
}

package CoreModule

import (
	"fmt"
	"github.com/bwmarrin/discordgo"
	"github.com/gendonl/genbot/Bot"
	"time"
)

func initPingCommand() (cc CoreCommand) {
	cc = CoreCommand{
		name:        "ping",
		description: "Returns pong.",
		usage:       "`%sping`",
		aliases:	 []string{},
		permission:  discordgo.PermissionSendMessages,
		execute:     (*CoreModule).pingCommand,
	}
	return
}

func (c *CoreModule) pingCommand(cmd CoreCommand, s *discordgo.Session, m *discordgo.MessageCreate, data *Bot.ServerData) {

	ping := s.HeartbeatLatency() / time.Millisecond

	response := Bot.NewEmbed().
		SetColorFromUser(s, m.ChannelID, m.Author).
		SetTitle("🏓 Pong").
		SetDescription("Pinging...")

	// Benchmark round-trip time of sent message
	start := time.Now()
	msg, err := s.ChannelMessageSendEmbed(m.ChannelID, response.MessageEmbed)
	elapsed := time.Since(start) / time.Millisecond

	if err != nil {
		c.Bot.Log.Error(err)
		return
	}

	// Add the new data of the round-trip
	response.SetDescription("").
		AddInlineField("Bot", fmt.Sprintf("%dms", elapsed), true).
		AddInlineField("API", fmt.Sprintf("%dms", ping), true)

	_, err = s.ChannelMessageEditEmbed(msg.ChannelID, msg.ID, response.MessageEmbed)
	if err != nil {
		c.Bot.Log.Error(err)
		return
	}
}

Add bot-latency to ping command


package errors

import (
	nativeErrors "errors"
	"net/http"
	"testing"
)

func TestHTTPStatusCode(t *testing.T) {
	if HTTPStatusCode(nil) != http.StatusOK {
		t.Error("Status code does not match")
	}

	if HTTPStatusCode(New(INTERNAL, "internal error")) != http.StatusInternalServerError {
		t.Error("Status code does not match")
	}

	if HTTPStatusCode(New(FORBIDDEN, "status map")) != errorCodeToHTTPStatusMap[FORBIDDEN] {
		t.Error("Status code does not match")
	}

	if HTTPStatusCode(Wrap(New(INTERNAL, "status map"), "", "")) != errorCodeToHTTPStatusMap[INTERNAL] {
		t.Error("Status code does not match")
	}

	if HTTPStatusCode(New("unknown_code", "internal error")) != http.StatusInternalServerError {
		t.Error("Status code does not match")
	}

	if HTTPStatusCode(New("123", "code as int")) != 123 {
		t.Error("Status code does not match")
	}

	if HTTPStatusCode(nativeErrors.New("native error")) != http.StatusInternalServerError {
		t.Error("Status code does not match")
	}
}

package errors

import (
	nativeErrors "errors"
	"net/http"
	"testing"
)

func TestHTTPStatusCode(t *testing.T) {
	if HTTPStatusCode(nil) != http.StatusOK {
		t.Error("Status code does not match")
	}

	if HTTPStatusCode(New(INTERNAL, "internal error")) != http.StatusInternalServerError {
		t.Error("Status code does not match")
	}

	if HTTPStatusCode(New(FORBIDDEN, "status map")) != errorCodeToHTTPStatusMap[FORBIDDEN] {
		t.Error("Status code does not match")
	}

	if HTTPStatusCode(Wrap(New(INTERNAL, "status map"), "", "")) != errorCodeToHTTPStatusMap[INTERNAL] {
		t.Error("Status code does not match")
	}

	if HTTPStatusCode(New("unknown_code", "internal error")) != http.StatusInternalServerError {
		t.Error("Status code does not match")
	}

	if HTTPStatusCode(New("400", "code as int")) != http.StatusBadRequest {
		t.Error("Status code does not match")
	}

	if HTTPStatusCode(nativeErrors.New("native error")) != http.StatusInternalServerError {
		t.Error("Status code does not match")
	}
}

Fix code as int test


package api

import "regexp"

var idRegexp = regexp.MustCompile("^[[:alnum:]](?:[_-]?[[:alnum:]]){1,35}$")

// ValidID returns true if the given ID is a valid application or device ID
func ValidID(id string) bool {
	return idRegexp.Match([]byte(id))
}

package api

import "regexp"

var idRegexp = regexp.MustCompile("^[0-9a-z](?:[_-]?[0-9a-z]){1,35}$")

// ValidID returns true if the given ID is a valid application or device ID
func ValidID(id string) bool {
	return idRegexp.Match([]byte(id))
}

Use lowercase AppIDs and DevIDs


package v1

import "encoding/json"

// UnmarshalJSON implements the json.Unmarshaller interface.
// If the value is a string, it sets the Value field of the StringSource.
// Otherwise, it is unmarshaled into the StringSourceSpec struct
func (s *StringSource) UnmarshalJSON(value []byte) error {
	// If we can unmarshal to a simple string, just set the value
	var simpleValue string
	if err := json.Unmarshal(value, &simpleValue); err == nil {
		s.Value = simpleValue
		return nil
	}

	// Otherwise do the full struct unmarshal
	return json.Unmarshal(value, &s.StringSourceSpec)
}

// MarshalJSON implements the json.Marshaller interface.
// If the StringSource contains only a string Value (or is empty), it is marshaled as a JSON string.
// Otherwise, the StringSourceSpec struct is marshaled as a JSON object.
func (s StringSource) MarshalJSON() ([]byte, error) {
	// If we have only a cleartext value set, do a simple string marshal
	if s.StringSourceSpec == (StringSourceSpec{Value: s.Value}) {
		return json.Marshal(s.Value)
	}

	// Otherwise do the full struct marshal of the externalized bits
	return json.Marshal(s.StringSourceSpec)
}

package v1

import "encoding/json"

// UnmarshalJSON implements the json.Unmarshaller interface.
// If the value is a string, it sets the Value field of the StringSource.
// Otherwise, it is unmarshaled into the StringSourceSpec struct
func (s *StringSource) UnmarshalJSON(value []byte) error {
	// If we can unmarshal to a simple string, just set the value
	var simpleValue string
	if err := json.Unmarshal(value, &simpleValue); err == nil {
		s.Value = simpleValue
		return nil
	}

	// Otherwise do the full struct unmarshal
	return json.Unmarshal(value, &s.StringSourceSpec)
}

// MarshalJSON implements the json.Marshaller interface.
// If the StringSource contains only a string Value (or is empty), it is marshaled as a JSON string.
// Otherwise, the StringSourceSpec struct is marshaled as a JSON object.
func (s *StringSource) MarshalJSON() ([]byte, error) {
	// If we have only a cleartext value set, do a simple string marshal
	if s.StringSourceSpec == (StringSourceSpec{Value: s.Value}) {
		return json.Marshal(s.Value)
	}

	// Otherwise do the full struct marshal of the externalized bits
	return json.Marshal(s.StringSourceSpec)
}

Fix inconsistency in StringSource MarshalJSON


package main

import (
	"fmt"
	"github.com/urfave/cli"
	"log"
	"os"
	"strconv"
)

// init injects our "ip" related commands/options.
func init() {
	// Fill-in the various commands
	cliCommands = append(cliCommands, cli.Command{
		Name:        "ip",
		Usage:       "returns current ip",
		Description: "shorthand for getting current ip",
		Action:      cmdIP,
	})
}

// shortcuts

// cmdIP is a short for displaying the IPs for one probe
func cmdIP(c *cli.Context) error {

	var (
		probeID int
	)

	args := c.Args()
	if len(args) == 1 {
		probeID, _ = strconv.Atoi(args[0])
	}

	if probeID == 0 {
		if cnf.DefaultProbe == 0 {
			log.Fatal("Error: you must specify a probe ID!")
		} else {
			probeID = cnf.DefaultProbe
		}
	}

	p, err := client.GetProbe(probeID)
	if err != nil {
		fmt.Printf("err: %v", err)
		os.Exit(1)
	}

	fmt.Printf("IPv4: %s IPv6: %s\n", p.AddressV4, p.AddressV6)
	return nil
}

package main

import (
	"fmt"
	"github.com/urfave/cli"
	"log"
	"strconv"
)

// init injects our "ip" related commands/options.
func init() {
	// Fill-in the various commands
	cliCommands = append(cliCommands, cli.Command{
		Name:        "ip",
		Usage:       "returns current ip",
		Description: "shorthand for getting current ip",
		Action:      cmdIP,
	})
}

// shortcuts

// cmdIP is a short for displaying the IPs for one probe
func cmdIP(c *cli.Context) error {

	var (
		probeID int
	)

	args := c.Args()
	if len(args) == 1 {
		probeID, _ = strconv.Atoi(args[0])
	}

	if probeID == 0 {
		if cnf.DefaultProbe == 0 {
			log.Fatal("Error: you must specify a probe ID!")
		} else {
			probeID = cnf.DefaultProbe
		}
	}

	p, err := client.GetProbe(probeID)
	if err != nil {
		log.Fatalf("err: %v", err)
	}

	fmt.Printf("IPv4: %s IPv6: %s\n", p.AddressV4, p.AddressV6)
	return nil
}

Use log.Fatalf instead of Printf/Exit.


package main

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

func hello(rw http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(rw, "This is stalemate.")
}

func processPayload(rw http.ResponseWriter, req *http.Request) {
	dump, err := httputil.DumpRequest(req, true)
	if err != nil {
		log.Println(err)
	}
	log.Println(string(dump))
	fmt.Fprintf(rw, "{\"status\": \"ok\"}\n")
}

func main() {
	http.HandleFunc("/", hello)
	http.HandleFunc("/events", processPayload)
	if err := http.ListenAndServe(":9090", nil); err != nil {
		log.Fatal(err)
	}
}

package main

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

	"github.com/google/go-github/github"
	"github.com/rjz/githubhook"
)

func hello(rw http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(rw, "This is stalemate.")
}

func processPayload(rw http.ResponseWriter, req *http.Request) {
	hook, err := githubhook.Parse([]byte(os.Getenv("STALEMATE_SECRET_TOKEN")), req)
	if err != nil {
		log.Println(err)
		return
	}

	switch hook.Event {
	case "integration_installation":
		event := github.IntegrationInstallationEvent{}
		if err := json.Unmarshal(hook.Payload, &event); err != nil {
			log.Println(err)
			return
		}
		// Echo back the installation part of the payload.
		fmt.Fprintf(rw, event.Installation.String())

	default:
		log.Printf("not handling %s events yet", hook.Event)
	}

}

func main() {
	http.HandleFunc("/", hello)
	http.HandleFunc("/events", processPayload)
	if err := http.ListenAndServe(":9090", nil); err != nil {
		log.Fatal(err)
	}
}

Use client libraries to parse installation event


package main

import (
	"flag"
	"log"
	"os"
)

var (
	PlaybookFile  = flag.String("play", "site.yml", "Path to the playbook to execute")
	InventoryFile = flag.String("i", "hosts", "Path to the inventory file")
	LimitHosts    = flag.String("l", "", "Limit hosts")
)

func main() {
	flag.Parse()
	log.SetFlags(0)
	log.SetOutput(os.Stdout)

	inv, err := LoadInventoryFile(*InventoryFile)
	if err != nil {
		log.Fatalf("error loading inventory file %q reason=%s", *InventoryFile, err.Error())
	}

	if ngroups := len(inv); ngroups == 1 {
		log.Println("Loaded 1 group from inventory")
	} else {
		log.Printf("Loaded %d groups from inventory", ngroups)
	}

	// Run a sanity check on the inventory groups.
	for _, g := range inv {
		if err = g.Check(); err != nil {
			log.Fatalf("Error in group %q: %s", g.Name, err.Error())
		}
	}

	return
}

package main

import (
	"flag"
	"log"
	"os"
)

var (
	PlaybookFile  = flag.String("play", "site.yml", "Path to the playbook to execute")
	InventoryFile = flag.String("i", "hosts", "Path to the inventory file")
	LimitHosts    = flag.String("l", "", "Limit hosts")
)

func main() {
	flag.Parse()
	log.SetFlags(0)
	log.SetOutput(os.Stdout)

	inv, err := LoadInventoryFile(*InventoryFile)
	if err != nil {
		log.Fatalf("error loading inventory file %q reason=%s", *InventoryFile, err.Error())
	}

	if ngroups := len(inv); ngroups == 1 {
		log.Println("Loaded 1 group from inventory")
	} else {
		log.Printf("Loaded %d groups from inventory", ngroups)
	}

	// Run a sanity check on the inventory groups.
	for _, g := range inv {
		if err = g.Check(); err != nil {
			log.Fatalf("Error in group %q: %s", g.Name, err.Error())
		}
	}

	// Load the playbook.
	plays, err := LoadPlaybook(*PlaybookFile)
	if err != nil {
		log.Fatalf("Error loading playbook %q: %s", *PlaybookFile, err.Error())
	}

	if nplays := len(plays); nplays == 1 {
		log.Println("Loaded 1 play")
	} else {
		log.Printf("Loaded %d plays", len(plays))
	}

	// Check the plays.
	for _, p := range plays {
		if err := p.Check(); err != nil {
			log.Fatalf("Error in play %q: %s", p.Name, err.Error())
		}
	}

	return
}

Load and check the plays in the playbook.


package main

import (
	"bufio"
	"fmt"
	"os"
	)

func main() {
	file, err := os.Open("targetlist.txt")

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	defer file.Close()

	scanner := bufio.NewScanner(file)

	for scanner.Scan() {
		fmt.Println(scanner.Text())
	}
}

package main

import (
	"bufio"
	"fmt"
	"os"
	"regexp"
	)

func main() {
	file, err := os.Open("targetlist.txt")

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	defer file.Close()

	scanner := bufio.NewScanner(file)

	r, _ := regexp.Compile("https?://(www.)?[a-zA-Z0-9.]{2,512}.[a-z]{2,10}")

	for scanner.Scan() {
		line := scanner.Text()

		if r.MatchString(line) {
			fmt.Println("Valid: " + line)
		}
	}
}

Test lines for valid URL


package main

import "fmt"

type custom struct {
	firstname
	lastname
}

type custom1 struct {
	firstname
	lastname
}

func main() {

	fmt.Println("This is a simple text")
	// This is a modification from git hub

	custom.firstname = "Firstname String"
	custom.lastname = "Custom lastname"

	custom1.firstname = "This is the second struct of custom"
	custom.firstnam = " w"

}

package main

import (
	"net/http"
)

func main() {
	http.HandleFunc("/", serveHome)
	http.HandleFunc("/contact", serveContact)
	http.ListenAndServe(":8888", nil)
}

func serveHome(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello World"))
}

func serveContact(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello to contact page"))
}

Add something to this commit