package main

import (
	"os"

	log15 "gopkg.in/inconshreveable/log15.v2"

	"github.com/CyCoreSystems/ari/client/native"
)

func main() {
	if i := run(); i != 0 {
		os.Exit(i)
	}
}

func run() int {

	// setup logging
	native.Logger = log15.New()
	log := log15.New()

	opts := native.Options{
		Application:  "example",
		Username:     "admin",
		Password:     "admin",
		URL:          "http://localhost:8088/ari",
		WebsocketURL: "ws://localhost:8088/ari/events",
	}

	log.Info("Connecting")

	cl, err := native.New(opts)
	if err != nil {
		log.Error("Failed to build native ARI client", "error", err)
		return -1
	}
	defer cl.Close()

	log.Info("Connected")

	info, err := cl.Asterisk.Info("")
	if err != nil {
		log.Error("Failed to get Asterisk Info", "error", err)
		return -1
	}

	log.Info("Asterisk Info", "info", info)

	return 0
}

package main

import (
	"context"
	"os"

	log15 "gopkg.in/inconshreveable/log15.v2"

	"github.com/CyCoreSystems/ari"
	"github.com/CyCoreSystems/ari/client/native"
)

func main() {
	if i := run(); i != 0 {
		os.Exit(i)
	}
}

func run() int {

	// setup logging
	native.Logger = log15.New()
	log := log15.New()

	opts := native.Options{
		Application:  "example",
		Username:     "admin",
		Password:     "admin",
		URL:          "http://localhost:8088/ari",
		WebsocketURL: "ws://localhost:8088/ari/events",
	}

	log.Info("Connecting")

	cl, err := native.Connect(context.TODO(), &opts)
	if err != nil {
		log.Error("Failed to build native ARI client", "error", err)
		return -1
	}

	defer cl.Close()

	log.Info("Connected")

	info, err := cl.Asterisk().Info(&ari.Key{Kind: "build"})
	if err != nil {
		log.Error("Failed to get Asterisk Info", "error", err)
		return -1
	}

	log.Info("Asterisk Info", "info", info)

	return 0
}

Update example base on the new implementation of ari.Client


package server

import (
	"flag"
	"github.com/zenazn/goji"
	"github.com/zenazn/goji/web/middleware"
	"net/http"
)

var (
	defaults *config
	//decoder  = schema.NewDecoder()
)

func start(conf *config) {
	defaults = conf
	flag.Set("bind", conf.Address) // Uh, I guess that's a bit strange
	if conf.Proxy {
		goji.Insert(middleware.RealIP, middleware.Logger)
	}

	register("/skin/:player", serveSkin)

	register("/head/:player", serveHeadNormal)
	register("/head/:size/:player", serveHeadWithSize)

	register("/face/:player", serveFaceNormal)
	register("/face/:size/:player", serveFaceWithSize)

	goji.Get("/*", http.FileServer(http.Dir("www"))) // TODO: How to find the correct dir?

	goji.Serve()
}

func register(pattern string, handler interface{}) {
	goji.Get(pattern+".png", handler)
	goji.Get(pattern, handler)
}

package server

import (
	"flag"
	"github.com/zenazn/goji"
	"github.com/zenazn/goji/web"
	"github.com/zenazn/goji/web/middleware"
	"net/http"
)

var (
	defaults *config
	//decoder  = schema.NewDecoder()
)

func start(conf *config) {
	defaults = conf
	flag.Set("bind", conf.Address) // Uh, I guess that's a bit strange
	if conf.Proxy {
		goji.Insert(middleware.RealIP, middleware.Logger)
	}

	goji.Use(serveLapitar)

	register("/skin/:player", serveSkin)

	register("/head/:player", serveHeadNormal)
	register("/head/:size/:player", serveHeadWithSize)

	register("/face/:player", serveFaceNormal)
	register("/face/:size/:player", serveFaceWithSize)

	goji.Get("/*", http.FileServer(http.Dir("www"))) // TODO: How to find the correct dir?

	goji.Serve()
}

func register(pattern string, handler interface{}) {
	goji.Get(pattern+".png", handler)
	goji.Get(pattern, handler)
}

func serveLapitar(c *web.C, h http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Server", "Lapitar") // TODO: Version
		h.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}

Add Server header to identify Lapitar


package backend

import (
	"context"

	"github.com/docker/ecs-plugin/pkg/amazon/types"
	"github.com/docker/ecs-plugin/pkg/compose"
)

func (b *Backend) Down(ctx context.Context, options compose.ProjectOptions) error {
	project, err := compose.ProjectFromOptions(&options)
	if err != nil {
		return err
	}

	err = b.api.DeleteStack(ctx, project.Name)
	if err != nil {
		return err
	}

	err = b.WaitStackCompletion(ctx, project.Name, types.StackDelete)
	if err != nil {
		return err
	}
	return nil
}

package backend

import (
	"context"

	"github.com/docker/ecs-plugin/pkg/amazon/types"
	"github.com/docker/ecs-plugin/pkg/compose"
)

func (b *Backend) Down(ctx context.Context, options compose.ProjectOptions) error {
	name := options.Name
	if name == "" {
		project, err := compose.ProjectFromOptions(&options)
		if err != nil {
			return err
		}
		name = project.Name
	}

	err := b.api.DeleteStack(ctx, name)
	if err != nil {
		return err
	}

	err = b.WaitStackCompletion(ctx, name, types.StackDelete)
	if err != nil {
		return err
	}
	return nil
}

Fix broken build on master


/*
Package types implements support for the types used in the Navitia API (see doc.navitia.io), simplified and modified for idiomatic Go use.

This package was and is developped as a supporting library for the gonavitia API client (https://github.com/aabizri/gonavitia) but can be used to build other API clients.

This support includes or will include, for each type.
	- JSON Unmarshalling via UnmarshalJSON(b []byte), in the format of the navitia.io API
	- Validity Checking via Check()
	- Pretty-printing via String()

This package is still a work in progress. It is not API-Stable, and won't be until the v1 release.

Currently supported types
	- Journey ["journey"]
	- Section ["section"]
	- Region ["region"]
	- Place (This is an interface for your ease-of-use, which is implemented by the five following types)
	- Address ["address"]
	- StopPoint ["stop_point"]
	- StopArea ["stop_area"]
	- AdministrativeRegion ["administrative_region"]
	- POI ["poi"]
	- Line ["line"]
	- Route ["route"]
	- And others, such as DisplayInformations ["display_informations"], PTDateTime ["pt-date-time"], StopTime ["stop_time"], Coordinates ["coord"].
*/
package types

// DataFreshness codes for a specific data freshness requirement: realtime or base_schedule
type DataFreshness string

const (
	// DataFreshnessRealTime means you'll get undisrupted journeys
	DataFreshnessRealTime DataFreshness = "realtime"
	// DataFreshnessBaseSchedule means you can get disrupted journeys in the response.
	DataFreshnessBaseSchedule = "base_schedule"
)

// A QueryEscaper implements QueryEscape, which returns an escaped representation of the type for use in URL queries.
// Implemented by both ID and Coordinates
type QueryEscaper interface {
	QueryEscape() string
}

Add package-level documentation for gonavitia/types


package handlers

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

var (
	RedirectHandlerRedirectCountMetric = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "router_redirect_handler_redirect_count",
			Help: "Number of redirects handled by router redirect handlers",
		},
		[]string{
			"redirect_code",
			"redirect_type",
			"redirect_url",
		},
	)
)

func initMetrics() {
	prometheus.MustRegister(RedirectHandlerRedirectCountMetric)
}

package handlers

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

var (
	RedirectHandlerRedirectCountMetric = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "router_redirect_handler_redirect_count",
			Help: "Number of redirects handled by router redirect handlers",
		},
		[]string{
			"redirect_code",
			"redirect_type",
			"redirect_url",
		},
	)

	BackendHandlerRequestCountMetric = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "router_backend_handler_request_count",
			Help: "Number of requests handled by router backend handlers",
		},
		[]string{
			"backend_id",
		},
	)

	BackendHandlerResponseDurationSecondsMetric = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "router_backend_handler_response_duration_seconds",
			Help: "Time in seconds spent proxying requests to backends by router backend handlers",
		},
		[]string{
			"backend_id",
			"response_code",
		},
	)
)

func initMetrics() {
	prometheus.MustRegister(RedirectHandlerRedirectCountMetric)

	prometheus.MustRegister(BackendHandlerRequestCountMetric)
	prometheus.MustRegister(BackendHandlerResponseDurationSecondsMetric)
}

Add backend handler metric req count / resp secs


package axis

// Provider is the interface that wraps methods
// to manipulate position
type Provider interface {
	Current() Position
	Sleep(Distance)
	After(Distance) <-chan Position
	AfterFunc(Distance, func(Position)) Watcher
	AfterChan(Distance, chan Position) Watcher
	Since(Position) Distance
}

// UpdatableProvider is the interface which allow
// to update the position of the provider
type UpdatableProvider interface {
	Provider
	Update(Position)
}

package axis

// Positionable is the interface for positionable
// items on a axis
type Positionable interface {
	Current() Position
	Since(Position) Distance
}

// Sleepable is the interface for sleepable provider
type Sleepable interface {
	Sleep(Distance)
}

// Trigger is the interface that wraps methods
// to define triggers
type Trigger interface {
	After(Distance) <-chan Position
	AfterFunc(Distance, func(Position)) Watcher
	AfterChan(Distance, chan Position) Watcher
}

// Provider is the interface that wraps methods
// to manipulate position
type Provider interface {
        Positionable
        Sleepable
        Trigger
}

// UpdatableProvider is the interface which allow
// to update the position of the provider
type UpdatableProvider interface {
	Provider
	Update(Position)
}

Split the Provider interface into narrow ones


// +build mig_forward

package mig

const forward_only = true

type Step struct {
	Name    string
	Migrate string
	Prereq  string
	hash    string
	file    string
	pkg     string
	order   string
}

func (step *Step) revert() string {
	return ""
}

func (s *Step) setRevert(string) {
}

// +build mig_forward

package mig

const forward_only = true

type Step struct {
	Name    string
	Migrate string
	Prereq  string
	hash    string
	file    string
	pkg     string
	order   int
}

func (step *Step) revert() string {
	return ""
}

func (s *Step) setRevert(string) {
}

Fix an issue causing mig_forward tag to not compile


// Copyright 2014 Marc-Antoine Ruel. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

// +build !debug

package main

import (
	"io"
	"io/ioutil"
	"log"

	"github.com/maruel/wi/editor"
)

func debugHook() io.Closer {
	// It is important to get rid of log output on stderr as it would conflict
	// with the editor's use of the terminal. Sadly the strings are still
	// rasterized, I don't know of a way to get rid of this.
	log.SetFlags(0)
	log.SetOutput(ioutil.Discard)
	return nil
}

func debugHookEditor(e editor.Editor) {
}

// Copyright 2014 Marc-Antoine Ruel. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

// +build !debug

package main

import (
	"io"
	"io/ioutil"
	"log"

	_ "github.com/maruel/circular"
	"github.com/maruel/wi/editor"
)

func debugHook() io.Closer {
	// It is important to get rid of log output on stderr as it would conflict
	// with the editor's use of the terminal. Sadly the strings are still
	// rasterized, I don't know of a way to get rid of this.
	log.SetFlags(0)
	log.SetOutput(ioutil.Discard)
	return nil
}

func debugHookEditor(e editor.Editor) {
}

Add an artificial dependency on github.com/maruel/circular in release build.


package grid

import "fmt"

// ExportService handles communication with the Export related
// methods of the GRiD API.
//
// GRiD API docs: https://github.com/CRREL/GRiD-API/blob/v0.0/composed_api.rst#get-export-details
type ExportService struct {
	client *Client
}

type File struct {
	URL  string `json:"url"`
	Pk   int    `json:"pk"`
	Name string `json:"name"`
}

type ExportDetail struct {
	ExportFiles []File `json:"exportfiles"`
}

func (s *ExportService) ListByPk(pk int) ([]File, *Response, error) {
	url := fmt.Sprintf("api/v0/export/%v/", pk)

	req, err := s.client.NewRequest("GET", url, nil)

	exportDetail := new(ExportDetail)
	resp, err := s.client.Do(req, exportDetail)
	return exportDetail.ExportFiles, resp, err
}

package grid

import (
	"fmt"
	"io"
	"log"
	"mime"
	"os"
)

// ExportService handles communication with the Export related
// methods of the GRiD API.
//
// GRiD API docs: https://github.com/CRREL/GRiD-API/blob/v0.0/composed_api.rst#get-export-details
type ExportService struct {
	client *Client
}

type File struct {
	URL  string `json:"url"`
	Pk   int    `json:"pk"`
	Name string `json:"name"`
}

type ExportDetail struct {
	ExportFiles []File `json:"exportfiles"`
}

func (s *ExportService) ListByPk(pk int) ([]File, *Response, error) {
	url := fmt.Sprintf("api/v0/export/%v/", pk)

	req, err := s.client.NewRequest("GET", url, nil)

	exportDetail := new(ExportDetail)
	resp, err := s.client.Do(req, exportDetail)
	return exportDetail.ExportFiles, resp, err
}

func (s *ExportService) DownloadByPk(pk int) (*Response, error) {
	url := fmt.Sprintf("export/download/file/%v/", pk)

	req, err := s.client.NewRequest("GET", url, nil)

	var foo interface{}
	resp, err := s.client.Do(req, foo)

	cd := resp.Header.Get("Content-Disposition")
	_, params, err := mime.ParseMediaType(cd)
	fname := params["filename"]
	file, err := os.Create(fname)
	defer file.Close()

	numBytes, err := io.Copy(file, resp.Body)
	log.Println("Downloaded", numBytes, "bytes to", fname)
	return resp, err
}

Add DownloadByPk back to the SDK


package main

import (
	"fmt"
	"os"

	"github.com/Bowbaq/scala-imports"
	"github.com/codegangsta/cli"
	"github.com/spf13/viper"
)

var (
	Version string
	config  scalaimports.Config
)

func init() {
	viper.SetConfigName(".fix-imports")
	viper.AddConfigPath(".")
	viper.AddConfigPath("$HOME")
	if err := viper.ReadInConfig(); err != nil {
		fmt.Println("Error reading config file: %s\n", err)
		os.Exit(-1)
	}

	viper.Unmarshal(&config)
}

func main() {
	app := cli.NewApp()
	app.Name = "fix-imports"
	app.Usage = "organize imports in a scala project"
	app.Version = Version
	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "verbose",
			Usage: "enable debug output",
		},
	}
	app.Action = func(c *cli.Context) {
		if c.Bool("verbose") {
			config.Verbose = true
		}

		scalaimports.SetConfig(config)

		if len(c.Args()) > 0 {
			for _, path := range c.Args() {
				scalaimports.Format(path)
			}
		} else {
			scalaimports.Format(".")
		}
	}

	app.Run(os.Args)
}

package main

import (
	"fmt"
	"os"

	"github.com/Bowbaq/scala-imports"
	"github.com/codegangsta/cli"
	"github.com/spf13/viper"
)

var (
	Version string
	config  scalaimports.Config
)

func init() {
	viper.SetConfigName(".fix-imports")
	viper.AddConfigPath(".")
	viper.AddConfigPath("$HOME")
	if err := viper.ReadInConfig(); err != nil {
		fmt.Println("Error reading config file: %s\n", err)
		os.Exit(-1)
	}

	viper.Unmarshal(&config)
}

func main() {
	app := cli.NewApp()
	app.Name = "fix-imports"
	app.Usage = "organize imports in a scala project"
	app.Version = Version
	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "verbose",
			Usage: "enable debug output",
		},
	}
	app.Action = func(c *cli.Context) error {
		if c.Bool("verbose") {
			config.Verbose = true
		}

		scalaimports.SetConfig(config)

		if len(c.Args()) > 0 {
			for _, path := range c.Args() {
				scalaimports.Format(path)
			}
		} else {
			scalaimports.Format(".")
		}

		return nil
	}

	app.Run(os.Args)
}

Update to new codegangsta/cli api


// +build acceptance

package app

import (
	"os"
	"time"

	"github.com/DATA-DOG/godog"
)

func init() {
	runs = append(runs, func() int {
		format := "progress"
		for _, arg := range os.Args[1:] {
			// go test transforms -v option
			if arg == "-test.v=true" {
				format = "pretty"
				break
			}
		}

		return godog.RunWithOptions(
			"godog",
			FeatureContext,
			godog.Options{
				Format:    format,
				Paths:     []string{"features"},
				Randomize: time.Now().UTC().UnixNano(), // randomize scenario execution order
			},
		)
	})
}

func FeatureContext(s *godog.Suite) {
	// Add steps here
}

// +build acceptance

package app

import (
	"os"
	"time"

	"github.com/DATA-DOG/godog"
	"github.com/goph/stdlib/net"
	"google.golang.org/grpc"
)

func init() {
	runs = append(runs, func() int {
		format := "progress"
		for _, arg := range os.Args[1:] {
			// go test transforms -v option
			if arg == "-test.v=true" {
				format = "pretty"
				break
			}
		}

		return godog.RunWithOptions(
			"godog",
			FeatureContext,
			godog.Options{
				Format:    format,
				Paths:     []string{"features"},
				Randomize: time.Now().UTC().UnixNano(), // randomize scenario execution order
			},
		)
	})
}

func FeatureContext(s *godog.Suite) {
	addr := net.ResolveVirtualAddr("pipe", "pipe")
	listener, dialer := net.PipeListen(addr)

	server := grpc.NewServer()
	client, _ := grpc.Dial("", grpc.WithInsecure(), grpc.WithDialer(func(s string, t time.Duration) (stdnet.Conn, error) { return dialer.Dial() }))

	// Add steps here

	go server.Serve(listener)
}

Add gRPC specific code to acceptance test


package b2

import ()

type B2 struct {
	AccountID          string
	ApplicationKey     string
	AuthorizationToken string
	ApiUrl             string
	DownloadUrl        string
}

func MakeB2(accountId, appKey string) (*B2, error) {
	return &B2{}, nil
}

package b2

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

type B2 struct {
	AccountID          string
	ApplicationKey     string
	AuthorizationToken string
	ApiUrl             string
	DownloadUrl        string
}

type authResponse struct {
	AccountID          string `json:"accountId"`
	AuthorizationToken string `json:"authorizationToken"`
	ApiUrl             string `json:"apiUrl"`
	DownloadUrl        string `json:"downloadUrl"`
}

func MakeB2(accountId, appKey string) (*B2, error) {
	req, err := http.NewRequest("GET",
		"https://api.backblaze.com/b2api/v1/b2_authorize_account", nil)
	if err != nil {
		return &B2{}, err
	}

	req.SetBasicAuth(accountId, appKey)

	c := http.Client{}
	resp, err := c.Do(req)
	if err != nil {
		return &B2{}, err
	}
	defer resp.Body.Close()

	// TODO handle response errors

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

	authJson := authResponse{}
	if err := json.Unmarshal(body, authJson); err != nil {
		return &B2{}, err
	}

	return &B2{
		AccountID:          authJson.AccountID,
		ApplicationKey:     appKey,
		AuthorizationToken: authJson.AuthorizationToken,
		ApiUrl:             authJson.ApiUrl,
		DownloadUrl:        authJson.DownloadUrl,
	}, nil
}

Implement authorization (no error handling yet)


package common

type NetString []byte

// implement encoding.TextMarshaller interface to treat []byte as raw string
// by other encoders/serializers (e.g. JSON)

func (n NetString) MarshalText() ([]byte, error) {
	return n, nil
}

package common

// NetString store the byte length of the data that follows, making it easier
// to unambiguously pass text and byte data between programs that could be
// sensitive to values that could be interpreted as delimiters or terminators
// (such as a null character).
type NetString []byte

// MarshalText exists to implement encoding.TextMarshaller interface to
// treat []byte as raw string by other encoders/serializers (e.g. JSON)
func (n NetString) MarshalText() ([]byte, error) {
	return n, nil
}

Document NetString & MarshalText interface


package mastodon

import (
	"encoding/base64"
	"net/http"
	"os"
)

func Base64EncodeFileName(filename string) (string, error) {
	file, err := os.Open(filename)
	if err != nil {
		return "", err
	}
	defer file.Close()

	return Base64Encode(file)
}

func Base64Encode(file *os.File) (string, error) {
	fi, err := file.Stat()
	if err != nil {
		return "", err
	}

	d := make([]byte, fi.Size())
	_, err = file.Read(d)
	if err != nil {
		return "", err
	}

	return "data:" + http.DetectContentType(d) +
		";base64," + base64.StdEncoding.EncodeToString(d), nil
}

// String is a helper function to get the pointer value of a string.
func String(v string) *string { return &v }

package mastodon

import (
	"encoding/base64"
	"net/http"
	"os"
)

// Base64EncodeFileName returns the base64 data URI format string of the file with the file name.
func Base64EncodeFileName(filename string) (string, error) {
	file, err := os.Open(filename)
	if err != nil {
		return "", err
	}
	defer file.Close()

	return Base64Encode(file)
}

// Base64Encode returns the base64 data URI format string of the file.
func Base64Encode(file *os.File) (string, error) {
	fi, err := file.Stat()
	if err != nil {
		return "", err
	}

	d := make([]byte, fi.Size())
	_, err = file.Read(d)
	if err != nil {
		return "", err
	}

	return "data:" + http.DetectContentType(d) +
		";base64," + base64.StdEncoding.EncodeToString(d), nil
}

// String is a helper function to get the pointer value of a string.
func String(v string) *string { return &v }

Add godoc to Base64EncodeFileName and Base64Encode


package sacloud

// propDiskConnection ディスク接続情報内包型
type propDiskConnection struct {
	Connection      EDiskConnection `json:",omitempty"` // ディスク接続方法
	ConnectionOrder int             `json:",omitempty"` // コネクション順序

}

// GetDiskConnection ディスク接続方法 取得
func (p *propDiskConnection) GetDiskConnection() EDiskConnection {
	return p.Connection
}

// SetDiskConnection ディスク接続方法 設定
func (p *propDiskConnection) SetDiskConnection(conn EDiskConnection) {
	p.Connection = conn
}

// GetDiskConnectionOrder コネクション順序 取得
func (p *propDiskConnection) GetDiskConnectionOrder() int {
	return p.ConnectionOrder
}

package sacloud

// propDiskConnection ディスク接続情報内包型
type propDiskConnection struct {
	Connection      EDiskConnection `json:",omitempty"` // ディスク接続方法
	ConnectionOrder int             `json:",omitempty"` // コネクション順序

}

// GetDiskConnection ディスク接続方法 取得
func (p *propDiskConnection) GetDiskConnection() EDiskConnection {
	return p.Connection
}

// SetDiskConnection ディスク接続方法 設定
func (p *propDiskConnection) SetDiskConnection(conn EDiskConnection) {
	p.Connection = conn
}

// GetDiskConnectionByStr ディスク接続方法 取得
func (p *propDiskConnection) GetDiskConnectionByStr() string {
	return string(p.Connection)
}

// SetDiskConnectionByStr ディスク接続方法 設定
func (p *propDiskConnection) SetDiskConnectionByStr(conn string) {
	p.Connection = EDiskConnection(conn)
}

// GetDiskConnectionOrder コネクション順序 取得
func (p *propDiskConnection) GetDiskConnectionOrder() int {
	return p.ConnectionOrder
}

Add disk connection functions to disk


package main

import (
	"go.skia.org/infra/go/gce"
	"go.skia.org/infra/go/gce/server"
)

func MonitoringBase(name, ipAddress string) *gce.Instance {
	vm := server.Server20170613(name)
	vm.DataDisk.SizeGb = 1000
	vm.DataDisk.Type = gce.DISK_TYPE_PERSISTENT_STANDARD
	vm.ExternalIpAddress = ipAddress
	vm.MachineType = gce.MACHINE_TYPE_HIGHMEM_16
	vm.Metadata["owner_primary"] = "jcgregorio"
	vm.Metadata["owner_secondary"] = "borenet"
	return vm
}

func Prod() *gce.Instance {
	return MonitoringBase("skia-monitoring", "104.154.112.119")
}

func Staging() *gce.Instance {
	return MonitoringBase("skia-monitoring-staging", "104.154.112.117")
}

func main() {
	server.Main(gce.ZONE_DEFAULT, map[string]*gce.Instance{
		"prod":    Prod(),
		"staging": Staging(),
	})
}

package main

import (
	"go.skia.org/infra/go/gce"
	"go.skia.org/infra/go/gce/server"
)

func MonitoringBase(name, ipAddress string) *gce.Instance {
	vm := server.Server20170613(name)
	vm.DataDisk.SizeGb = 1000
	vm.DataDisk.Type = gce.DISK_TYPE_PERSISTENT_STANDARD
	vm.ExternalIpAddress = ipAddress
	vm.MachineType = gce.MACHINE_TYPE_HIGHMEM_16
	vm.Metadata["owner_primary"] = "jcgregorio"
	vm.Metadata["owner_secondary"] = "borenet"
	return vm
}

func Prod() *gce.Instance {
	return MonitoringBase("skia-monitoring", "35.202.138.145" /* Whitelisted in skia-master-db cloud DB */)
}

func Staging() *gce.Instance {
	return MonitoringBase("skia-monitoring-staging", "35.193.5.196")
}

func main() {
	server.Main(gce.ZONE_DEFAULT, map[string]*gce.Instance{
		"prod":    Prod(),
		"staging": Staging(),
	})
}

Use static IPs outside the 104.154.112.0/24 block in skia-monitoring


package cas

import (
	"log"
)

const (
	_ = iota
	DEBUG
	INFO
	WARN
)

// Utility functions for logging messages
func logMessage(actualLogLevel, msgLogLevel, msg string, ) {
	if actualLogLevel <= msgLogLevel {
		log.Printf("[%s] %s", msgLogLevel, msg)
	}
}

// Utility function for logging message
func logMessagef(actualLogLevel, msgLogLevel, format string, msgArgs...interface{} ) {
	if actualLogLevel <= msgLogLevel {
		log.Printf("[%s] " + format, msgLogLevel, msgArgs)
	}
}

package cas

import (
	"log"
	"fmt"
)

const (
	_ = iota
	DEBUG
	INFO
	WARN
)

// Utility functions for logging messages
func logMessage(actualLogLevel, msgLogLevel, msg string, ) {
	if actualLogLevel <= msgLogLevel {
		log.Printf("[%s] %s", msgLogLevel, msg)
	}
}

// Utility function for logging message
func logMessagef(actualLogLevel, msgLogLevel, format string, msgArgs ...interface{}) {
	if actualLogLevel <= msgLogLevel {
		log.Printf("[%s] %s", msgLogLevel, fmt.Sprintf(format, msgArgs...))
	}
}

Fix variadic function call for custom logger


// Copyright 2013 Flo Lauber <dev@qatfy.at>.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// TODO(flo):
//   - support password protected MUC rooms
//   - cleanup signatures of join/leave functions
package xmpp

import (
	"fmt"
)

const (
	nsMUC     = "http://jabber.org/protocol/muc"
	nsMUCUser = "http://jabber.org/protocol/muc#user"
)

// xep-0045 7.2
func (c *Client) JoinMUC(jid, nick string) {
	if nick == "" {
		nick = c.jid
	}
	fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+
		"<x xmlns='%s' />\n"+
		"</presence>",
		xmlEscape(jid), xmlEscape(nick), nsMUC)
}

// xep-0045 7.14
func (c *Client) LeaveMUC(jid string) {
	fmt.Fprintf(c.conn, "<presence from='%s' to='%s' type='unavailable' />",
		c.jid, xmlEscape(jid))
}

// Copyright 2013 Flo Lauber <dev@qatfy.at>.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// TODO(flo):
//   - support password protected MUC rooms
//   - cleanup signatures of join/leave functions
package xmpp

import (
	"fmt"
)

const (
	nsMUC     = "http://jabber.org/protocol/muc"
	nsMUCUser = "http://jabber.org/protocol/muc#user"
)

// xep-0045 7.2
func (c *Client) JoinMUC(jid, nick string) {
	if nick == "" {
		nick = c.jid
	}
	fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+
		"<x xmlns='%s' />\n"+
		"</presence>",
		xmlEscape(jid), xmlEscape(nick), nsMUC)
}

// xep-0045 7.2.6
func (c *Client) JoinProtectedMUC(jid, nick string, password string) {
	if nick == "" {
		nick = c.jid
	}
	fmt.Fprintf(c.conn, "<presence to='%s/%s'>\n"+
		"<x xmlns='%s'>\n"+
		"<password>%s</password>\n"+
		"</x>\n"+
		"</presence>",
		xmlEscape(jid), xmlEscape(nick), nsMUC, xmlEscape(password))
}

// xep-0045 7.14
func (c *Client) LeaveMUC(jid string) {
	fmt.Fprintf(c.conn, "<presence from='%s' to='%s' type='unavailable' />",
		c.jid, xmlEscape(jid))
}

Add ability to join password protected chat rooms


package ref

import (
	"fmt"
	"strings"

	"k8s.io/apimachinery/pkg/api/meta"
	"k8s.io/apimachinery/pkg/runtime"
)

var NodeNotFound = "can not build dialer to"

func IsNodeNotFound(err error) bool {
	return strings.Contains(err.Error(), NodeNotFound)
}

func FromStrings(namespace, name string) string {
	return fmt.Sprintf("%s:%s", namespace, name)
}

func Ref(obj runtime.Object) string {
	objMeta, _ := meta.Accessor(obj)
	if objMeta.GetNamespace() == "" {
		return objMeta.GetName()
	}
	return FromStrings(objMeta.GetNamespace(), objMeta.GetName())
}

func Parse(ref string) (namespace string, name string) {
	parts := strings.SplitN(ref, ":", 2)
	if len(parts) == 1 {
		return "", parts[0]
	}
	return parts[0], parts[1]
}

package ref

import (
	"fmt"
	"strings"

	"k8s.io/apimachinery/pkg/api/meta"
	"k8s.io/apimachinery/pkg/runtime"
)

var NodeNotFound = "can not build dialer to"

func IsNodeNotFound(err error) bool {
	if err == nil {
		return false
	}
	return strings.Contains(err.Error(), NodeNotFound)
}

func FromStrings(namespace, name string) string {
	return fmt.Sprintf("%s:%s", namespace, name)
}

func Ref(obj runtime.Object) string {
	objMeta, _ := meta.Accessor(obj)
	if objMeta.GetNamespace() == "" {
		return objMeta.GetName()
	}
	return FromStrings(objMeta.GetNamespace(), objMeta.GetName())
}

func Parse(ref string) (namespace string, name string) {
	parts := strings.SplitN(ref, ":", 2)
	if len(parts) == 1 {
		return "", parts[0]
	}
	return parts[0], parts[1]
}

Check err not nil before calling clusterDialer


package players

import "errors"
import "github.com/m4rw3r/uuid"
import "golang.org/x/crypto/bcrypt"

//import "fmt"

// The user associated with a player
type User struct {
	Username string `json:"username"`
	password string
	Apikey   string       `json:"apikey"`
	Admin    bool         `json:"admin"`
	Locked   bool         `json:"locked"`
	Settings UserSettings `json:"settings"`
}

// Create a user
func NewUser(player uuid.UUID, userdata *User) (*User, error) {
	p, err := storage.Load(player)
	if err != nil {
		return nil, err
	}
	p.User = *userdata
	err = storage.Store(p)
	if err != nil {
		return nil,
			errors.New(err.Error() + " - Could not write user to storage")
	}
	return &p.User, nil
}

// The user preferences/settings of the user
type UserSettings struct {
	Notifications map[string]bool `json:"notifications"`
}

func UserByName(username string) (*User, error) {
	return storage.LoadUser(username)
}

func AuthUser(username string, password string) bool {
	user, err := storage.LoadUser(username)
	if err != nil {
		return false
	}
	if err := bcrypt.CompareHashAndPassword([]byte(user.password), []byte(password)); err == nil {
		return true
	}
	return false
}

package players

import "errors"
import "github.com/m4rw3r/uuid"
import "golang.org/x/crypto/bcrypt"

//import "fmt"

// The user associated with a player
type User struct {
	Username string `json:"username"`
	password string
	Apikey   string       `json:"apikey"`
	Admin    bool         `json:"admin"`
	Locked   bool         `json:"locked"`
	Settings UserSettings `json:"settings"`
}

// Create a user
func NewUser(player uuid.UUID, userdata *User) (*User, error) {
	p, err := storage.Load(player)
	if err != nil {
		return nil, err
	}
	p.User = *userdata
	err = storage.Store(p)
	if err != nil {
		return nil,
			errors.New(err.Error() + " - Could not write user to storage")
	}
	return &p.User, nil
}

// The user preferences/settings of the user
type UserSettings struct {
	Notifications map[string]bool `json:"notifications"`
}

func UserByName(username string) (*User, error) {
	return storage.LoadUser(username)
}

func AuthUser(username string, password string) bool {
	user, err := storage.LoadUser(username)
	if err != nil {
		return false
	}
	// No error from comparison means the hashes match
	if err := bcrypt.CompareHashAndPassword([]byte(user.password), []byte(password)); err == nil {
		return true
	}
	return false
}

Add comment about strange inverted err check.


package bootstrap

type Size int

const (
	ExtraSmall = iota - 2
	Small
	Medium
	Large
)

type Alignment int

const (
	Left Alignment = iota
	Center
	Right
)

package bootstrap

type Size int

const (
	ExtraSmall = iota - 2
	Small
	Medium
	Large
)

func (s Size) String() string {
	switch s {
	case ExtraSmall:
		return "xs"
	case Small:
		return "sm"
	case Medium:
		return "md"
	case Large:
		return "lg"
	}
	return ""
}

type Alignment int

const (
	Left Alignment = iota
	Center
	Right
)

Implement String() for bootstrap sizes


package plugins

import . "github.com/osmano807/joker/interfaces"

type Imgur struct {
	name string
}

func (p *Imgur) Name() string {
	return p.name
}

func (p *Imgur) Init() {
	p.name = "Imgur"
}

func (p *Imgur) Handle(il *InputLine) (ol *OutputLine) {
	ol = &OutputLine{}

	ol.ChannelId = il.ChannelId

	if il.URL.Host != "i.imgur.com" {
		ol.Result = NO_CHANGE
		return
	}

	ol.Result = NEW_STOREID
	il.URL.Path = removeExtension(il.URL.Path)
	il.URL.Host = JOKER_PREFIX + "/" + il.URL.Host
	ol.StoreId = il.URL.String()

	return
}

package plugins

import . "github.com/osmano807/joker/interfaces"

type Imgur struct {
	name string
}

func (p *Imgur) Name() string {
	return p.name
}

func (p *Imgur) Init() {
	p.name = "Imgur"
}

func (p *Imgur) Handle(il *InputLine) (ol *OutputLine) {
	ol = &OutputLine{}

	ol.ChannelId = il.ChannelId

	if il.URL.Host != "i.imgur.com" {
		ol.Result = NO_CHANGE
		return
	}

	ol.Result = NEW_STOREID
	il.URL.Path = removeExtension(il.URL.Path)
	il.URL.Host = JOKER_PREFIX + "/" + il.URL.Host
	il.URL.RawQuery = ""
	ol.StoreId = il.URL.String()

	return
}

Remove querystring info from Imgur urls


package main

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

func GetUserCacheDirectory() string {
	if baseDir := os.Getenv("XDG_CACHE_HOME"); baseDir != "" {
		return filepath.Join(baseDir, "rfc")
	}

	if user, err := user.Current(); err == nil {
		return filepath.Join(user.HomeDir, ".cache", "rfc")
	}

	if homeDir := os.Getenv("HOME"); homeDir != "" {
		return filepath.Join(homeDir, ".cache", "rfc")
	}

	return ""
}

package main

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

func GetHomeDirectory() string {
	if runtime.GOOS == "windows" {
		return os.Getenv("USERPROFILE")
	}
	return os.Getenv("HOME")
}

func GetUserCacheDirectory() string {
	if baseDir := os.Getenv("XDG_CACHE_HOME"); baseDir != "" {
		return filepath.Join(baseDir, "rfc")
	}

	if user, err := user.Current(); err == nil {
		return filepath.Join(user.HomeDir, ".cache", "rfc")
	}

	if homeDir := GetHomeDirectory(); homeDir != "" {
		return filepath.Join(homeDir, ".cache", "rfc")
	}

	return ""
}

Use separate function for getting home directory


// +build windows

package etc

//go:generate cmd /c go run mkversioninfo.go version.txt version.txt < versioninfo.json > v.json && go run github.com/josephspurrier/goversioninfo/cmd/goversioninfo -icon=nyagos.ico -o ..\nyagos.syso v.json && del v.json

// +build windows

package etc

// for default icon
//go:generate cmd /c go run mkversioninfo.go version.txt version.txt < versioninfo.json > v.json && go run github.com/josephspurrier/goversioninfo/cmd/goversioninfo -icon=nyagos.ico -o ..\nyagos.syso v.json && del v.json

// for second icon (disabled)
////go:generate cmd /c go run mkversioninfo.go version.txt version.txt < versioninfo.json > v.json && go run github.com/josephspurrier/goversioninfo/cmd/goversioninfo -icon=nyagos32x32.ico -icon=nyagos16x16.ico -o ..\nyagos.syso v.json && del v.json

Add go-generate-code for second icon (but disabled)


package rpcd

import (
	"time"

	"github.com/Symantec/Dominator/lib/srpc"
	"github.com/Symantec/Dominator/proto/imageserver"
)

func (t *srpcType) GetImage(conn *srpc.Conn,
	request imageserver.GetImageRequest,
	reply *imageserver.GetImageResponse) error {
	var response imageserver.GetImageResponse
	response.Image = t.imageDataBase.GetImage(request.ImageName)
	*reply = response
	if response.Image != nil || request.Timeout == 0 {
		return nil
	}
	// Image not found yet and willing to wait.
	addCh := t.imageDataBase.RegisterAddNotifier()
	defer func() {
		t.imageDataBase.UnregisterAddNotifier(addCh)
		select {
		case <-addCh:
		default:
		}
	}()
	timer := time.NewTimer(request.Timeout)
	for {
		select {
		case imageName := <-addCh:
			if imageName == request.ImageName {
				if !timer.Stop() {
					<-timer.C
				}
				response.Image = t.imageDataBase.GetImage(request.ImageName)
				*reply = response
				return nil
			}
		case <-timer.C:
			return nil
		}
	}
}

package rpcd

import (
	"time"

	"github.com/Symantec/Dominator/lib/image"
	"github.com/Symantec/Dominator/lib/srpc"
	"github.com/Symantec/Dominator/proto/imageserver"
)

func (t *srpcType) GetImage(conn *srpc.Conn,
	request imageserver.GetImageRequest,
	reply *imageserver.GetImageResponse) error {
	var response imageserver.GetImageResponse
	response.Image = t.getImageNow(request)
	*reply = response
	if response.Image != nil || request.Timeout == 0 {
		return nil
	}
	// Image not found yet and willing to wait.
	addCh := t.imageDataBase.RegisterAddNotifier()
	defer func() {
		t.imageDataBase.UnregisterAddNotifier(addCh)
		select {
		case <-addCh:
		default:
		}
	}()
	timer := time.NewTimer(request.Timeout)
	for {
		select {
		case imageName := <-addCh:
			if imageName == request.ImageName {
				if !timer.Stop() {
					<-timer.C
				}
				response.Image = t.getImageNow(request)
				*reply = response
				return nil
			}
		case <-timer.C:
			return nil
		}
	}
}

func (t *srpcType) getImageNow(
	request imageserver.GetImageRequest) *image.Image {
	img := *t.imageDataBase.GetImage(request.ImageName)
	if request.IgnoreFilesystem {
		img.FileSystem = nil
	}
	return &img
}

Add support for IgnoreFilesystem field to GetImage() SRPC handler.


// +build !windows,!linux

package chrootarchive // import "github.com/docker/docker/pkg/chrootarchive"

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

func chroot(path string) error {
	if err := unix.Chroot(path); err != nil {
		return err
	}
	return unix.Chdir("/")
}

func realChroot(path string) error {
	return chroot(path)
}

Add realChroot for non linux/windows


package instana

import "testing"

// Trace IDs (and Span IDs) are based on Java Signed Long datatype
const MinUint64 = uint64(0)
const MaxUint64 = uint64(18446744073709551615)
const MinInt64 = int64(-9223372036854775808)
const MaxInt64 = int64(9223372036854775807)

func TestIDGeneration(t *testing.T) {
}

package instana

import (
	"testing"

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

// Trace IDs (and Span IDs) are based on Java Signed Long datatype
const MinUint64 = uint64(0)
const MaxUint64 = uint64(18446744073709551615)
const MinInt64 = int64(-9223372036854775808)
const MaxInt64 = int64(9223372036854775807)

func TestGeneratedIDRange(t *testing.T) {

	var count = 10000
	var id = int64(0)
	for index := 0; index < count; index++ {
		id = randomID()

		assert.True(t, id <= 9223372036854775807, "Generated ID is out of bounds (+)")
		assert.True(t, id >= -9223372036854775808, "Generated ID is out of bounds (-)")

	}
}

Test range of generated IDs.


package aws

import (
	"testing"

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

func TestAccAWSIotEndpointDataSource(t *testing.T) {
	resource.Test(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAWSIotEndpointConfig,
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttrSet("data.aws_iot_endpoint.example", "id"),
					resource.TestCheckResourceAttrSet("data.aws_iot_endpoint.example", "endpoint_address"),
				),
			},
		},
	})
}

const testAccAWSIotEndpointConfig = `
data "aws_iot_endpoint" "example" {}
`

package aws

import (
	"testing"

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

func TestAccAWSIotEndpointDataSource(t *testing.T) {
	resource.Test(t, resource.TestCase{
		PreCheck:  func() { testAccPreCheck(t) },
		Providers: testAccProviders,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAWSIotEndpointConfig,
				Check: resource.ComposeTestCheckFunc(
					resource.TestCheckResourceAttrSet("data.aws_iot_endpoint.example", "endpoint_address"),
				),
			},
		},
	})
}

const testAccAWSIotEndpointConfig = `
data "aws_iot_endpoint" "example" {}
`

Remove explicit id attribute check


/*
Copyright 2016 The Kubernetes Authors.

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

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

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

package kubeadm

const (
	DefaultServiceDNSDomain  = "cluster.local"
	DefaultServicesSubnet    = "10.12.0.0/12"
	DefaultKubernetesVersion = "v1.4.1"
	DefaultAPIBindPort       = 6443
	DefaultDiscoveryBindPort = 9898
)

/*
Copyright 2016 The Kubernetes Authors.

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

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

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

package kubeadm

const (
	DefaultServiceDNSDomain  = "cluster.local"
	DefaultServicesSubnet    = "10.12.0.0/12"
	DefaultKubernetesVersion = "v1.4.4"
	DefaultAPIBindPort       = 6443
	DefaultDiscoveryBindPort = 9898
)

Bump kubeadm to use v1.4.4 by default


package containers

import (
	"github.com/fsouza/go-dockerclient"
)

type DockerRuntime struct {
	Client *docker.Client
}

func (r DockerRuntime) isRelated(volume string, container *docker.Container) bool {
	for _, mount := range container.Mounts {
		if mount.Name == volume && mount.Driver == "dvol" {
			return true
		}
	}
	return false
}

func (runtime DockerRuntime) Related(volume string) ([]string, error) {
	containers, _ := runtime.Client.ListContainers(docker.ListContainersOptions{})
	relatedContainers := make([]string, 0)
	for _, c := range containers {
		container, _ := runtime.Client.InspectContainer(c.ID)
		if runtime.isRelated(volume, container) && container.State.Running {
			relatedContainers = append(relatedContainers, container.Name)
		}
	}
	return relatedContainers, nil
}

func (runtime DockerRuntime) Start(volume string) error {
	return nil
}

func (runtime DockerRuntime) Stop(volume string) error {
	return nil
}

func (runtime DockerRuntime) Remove(volume string) error {
	return nil
}

package containers

import (
	"github.com/fsouza/go-dockerclient"
)

type DockerRuntime struct {
	Client *docker.Client
}

func (r DockerRuntime) isRelated(volume string, container *docker.Container) bool {
	for _, mount := range container.Mounts {
		if mount.Name == volume && mount.Driver == "dvol" {
			return true
		}
	}
	return false
}

func (runtime DockerRuntime) Related(volume string) ([]string, error) {
	containers, _ := runtime.Client.ListContainers(docker.ListContainersOptions{})
	relatedContainers := make([]string, 0)
	for _, c := range containers {
		container, err := runtime.Client.InspectContainer(c.ID)
		if err != nil {
			return relatedContainers, err
		}
		if runtime.isRelated(volume, container) && container.State.Running {
			relatedContainers = append(relatedContainers, container.Name)
		}
	}
	return relatedContainers, nil
}

func (runtime DockerRuntime) Start(volume string) error {
	return nil
}

func (runtime DockerRuntime) Stop(volume string) error {
	return nil
}

func (runtime DockerRuntime) Remove(volume string) error {
	return nil
}

Return error if we can't inspect a container


package main

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

	"github.com/sony/gobreaker"
)

var cb *gobreaker.CircuitBreaker

func init() {
	var st gobreaker.Settings
	st.Name = "HTTP GET"
	st.ReadyToTrip = func(counts gobreaker.Counts) bool {
		failureRatio := float64(counts.TotalFailures) / float64(counts.Requests)
		return counts.Requests >= 3 && failureRatio >= 0.6
	}

	cb = gobreaker.NewCircuitBreaker(st)
}

// Get wraps http.Get in CircuitBreaker.
func Get(url string) ([]byte, error) {
	body, err := cb.Execute(func() (interface{}, error) {
		resp, err := http.Get(url)
		if err != nil {
			return nil, err
		}

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

		return body, nil
	})
	if err != nil {
		return nil, err
	}

	return body.([]byte), nil
}

func main() {
	body, err := Get("http://www.google.com/robots.txt")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("%s", string(body))
}

package main

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

	"github.com/sony/gobreaker"
)

var cb *gobreaker.CircuitBreaker

func init() {
	var st gobreaker.Settings
	st.Name = "HTTP GET"
	st.ReadyToTrip = func(counts gobreaker.Counts) bool {
		failureRatio := float64(counts.TotalFailures) / float64(counts.Requests)
		return counts.Requests >= 3 && failureRatio >= 0.6
	}

	cb = gobreaker.NewCircuitBreaker(st)
}

// Get wraps http.Get in CircuitBreaker.
func Get(url string) ([]byte, error) {
	body, err := cb.Execute(func() (interface{}, error) {
		resp, err := http.Get(url)
		if err != nil {
			return nil, err
		}

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

		return body, nil
	})
	if err != nil {
		return nil, err
	}

	return body.([]byte), nil
}

func main() {
	body, err := Get("http://www.google.com/robots.txt")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(body))
}

Remove an unused format string


package maxreader_test

import (
	"io/ioutil"
	"strings"
	"testing"

	"."
)

func Test(t *testing.T) {
	type entry struct {
		s  string
		ok bool
	}

	table := []entry{
		{"", true},
		{"h", true},
		{"hell", true},
		{"hello", true},
		{"hellow", false},
		{"helloworld", false},
	}

	for _, e := range table {
		b, err := ioutil.ReadAll(maxreader.New(strings.NewReader(e.s), 5))

		if e.ok != (err == nil) {
			t.Errorf(`input "%v" -> error %v`, e.s, err)
		}

		if err == nil {
			l := len(e.s)
			if l > 5 {
				l = 5
			}

			if len(b) != l {
				t.Errorf(`input "%v" -> length %v`, e.s, len(b))
			}
		} else if err != maxreader.ErrReadLimit {
			t.Errorf(`input "%v" -> wrong error %v`, e.s, err)
		}
	}
}

package maxreader_test

import (
	"io/ioutil"
	"strings"
	"testing"

	"github.com/ninchat/maxreader"
)

func Test(t *testing.T) {
	type entry struct {
		s  string
		ok bool
	}

	table := []entry{
		{"", true},
		{"h", true},
		{"hell", true},
		{"hello", true},
		{"hellow", false},
		{"helloworld", false},
	}

	for _, e := range table {
		b, err := ioutil.ReadAll(maxreader.New(strings.NewReader(e.s), 5))

		if e.ok != (err == nil) {
			t.Errorf(`input "%v" -> error %v`, e.s, err)
		}

		if err == nil {
			l := len(e.s)
			if l > 5 {
				l = 5
			}

			if len(b) != l {
				t.Errorf(`input "%v" -> length %v`, e.s, len(b))
			}
		} else if err != maxreader.ErrReadLimit {
			t.Errorf(`input "%v" -> wrong error %v`, e.s, err)
		}
	}
}

Use absolute import in test


package server

import (
	"net"
	"net/http"

	"github.com/gorilla/mux"
	"github.com/sirupsen/logrus"
)

// Server provides the web UI for interacting with the application. Users can
// login, post suggestions, and queue items if they have the appropriate
// permissions.
type Server struct {
	listener net.Listener
	log      *logrus.Entry
	stopped  chan bool
}

// New creates a new server with the specified configuration.
func New(cfg *Config) (*Server, error) {
	l, err := net.Listen("tcp", cfg.Addr)
	if err != nil {
		return nil, err
	}
	var (
		router = mux.NewRouter()
		server = http.Server{
			Handler: router,
		}
		s = &Server{
			listener: l,
			log:      logrus.WithField("context", "server"),
			stopped:  make(chan bool),
		}
	)
	go func() {
		defer close(s.stopped)
		defer s.log.Info("web server has stopped")
		s.log.Info("starting web server...")
		if err := server.Serve(l); err != nil {
			s.log.Error(err.Error())
		}
	}()
	return s, nil
}

// Close shuts down the server and waits for it to complete.
func (s *Server) Close() {
	s.listener.Close()
	<-s.stopped
}

package server

import (
	"net"
	"net/http"

	"github.com/gorilla/mux"
	"github.com/sirupsen/logrus"
)

// Server provides the web UI for interacting with the application. Users can
// login, post suggestions, and queue items if they have the appropriate
// permissions.
type Server struct {
	listener net.Listener
	log      *logrus.Entry
	stopped  chan bool
}

// New creates a new server with the specified configuration.
func New(cfg *Config) (*Server, error) {
	l, err := net.Listen("tcp", cfg.Addr)
	if err != nil {
		return nil, err
	}
	var (
		router = mux.NewRouter()
		server = http.Server{
			Handler: router,
		}
		s = &Server{
			listener: l,
			log:      logrus.WithField("context", "server"),
			stopped:  make(chan bool),
		}
	)
	router.PathPrefix("/static").Handler(http.FileServer(HTTP))
	go func() {
		defer close(s.stopped)
		defer s.log.Info("web server has stopped")
		s.log.Info("starting web server...")
		if err := server.Serve(l); err != nil {
			s.log.Error(err.Error())
		}
	}()
	return s, nil
}

// Close shuts down the server and waits for it to complete.
func (s *Server) Close() {
	s.listener.Close()
	<-s.stopped
}

Add route for static files.


package file

import (
	"log"
	"path/filepath"
	"runtime"
	"strings"
)

// Given its relative path with respect to the LXD surce tree, return the full
// path of a file.
func absPath(path string) string {
	// We expect to be called by code within the lxd package itself.
	_, filename, _, _ := runtime.Caller(1)

	elems := strings.Split(filename, string(filepath.Separator))
	for i := len(elems) - 1; i >= 0; i-- {
		if elems[i] == "lxd" {
			elems = append([]string{string(filepath.Separator)}, elems[:i]...)
			elems = append(elems, path)
			return filepath.Join(elems...)
		}
	}

	log.Errorf("Could not found root dir of LXD tree source tree")

	return ""
}

package file

import (
	"log"
	"path/filepath"
	"runtime"
	"strings"
)

// Given its relative path with respect to the LXD surce tree, return the full
// path of a file.
func absPath(path string) string {
	// We expect to be called by code within the lxd package itself.
	_, filename, _, _ := runtime.Caller(1)

	elems := strings.Split(filename, string(filepath.Separator))
	for i := len(elems) - 1; i >= 0; i-- {
		if elems[i] == "lxd" {
			elems = append([]string{string(filepath.Separator)}, elems[:i]...)
			elems = append(elems, path)
			return filepath.Join(elems...)
		}
	}

	log.Fatalf("Could not found root dir of LXD tree source tree")

	return ""
}

Fix regression caused by Fatalf fix


package slackapi

import (
	"encoding/json"
	"testing"
)

func CheckResponse(t *testing.T, x interface{}, y string) {
	out, err := json.Marshal(x)
	if err != nil {
		t.Fatal("json fromat;", err)
	}
	if string(out) != y {
		t.Fatalf("invalid json response;\n- %s\n+ %s\n", y, out)
	}
}

func TestAPITest(t *testing.T) {
	s := New()
	x := s.APITest()
	y := `{"ok":true}`
	CheckResponse(t, x, y)
}

func TestAppsList(t *testing.T) {
	s := New()
	x := s.AppsList()
	y := `{"ok":false,"error":"not_authed","apps":null,"cache_ts":""}`
	CheckResponse(t, x, y)
}

func TestAuthRevoke(t *testing.T) {
	s := New()
	x := s.AuthRevoke()
	y := `{"ok":false,"error":"not_authed","revoked":false}`
	CheckResponse(t, x, y)
}

func TestAuthTest(t *testing.T) {
	s := New()
	x, err := s.AuthTest()
	if err != nil {
		t.Fatal(err)
	}
	y := `{"ok":false,"error":"not_authed","team":"","team_id":"","url":"","user":"","user_id":""}`
	CheckResponse(t, x, y)
}

Remove auth.test unit test due to API uncertanties


// Copyright 2017 Eric Daniels
//
// 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 track

import "net/http"

// HTTPClient wraps an http.Client and tracks reads and writes
type HTTPClient struct {
	*http.Client
	ByteTracker
}

// NewDefaultHTTPClient returns a new HTTPClient based on a default
// http.Client
func NewDefaultHTTPClient() HTTPClient {
	client := http.Client{}
	rt := NewDefaultHTTPRoundTripper()
	client.Transport = NewDefaultHTTPRoundTripper()
	return HTTPClient{
		Client:      &client,
		ByteTracker: rt,
	}
}

// Copyright 2017 Eric Daniels
//
// 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 track

import "net/http"

// HTTPClient wraps an http.Client and tracks reads and writes
type HTTPClient struct {
	*http.Client
	ByteTracker
}

// NewDefaultHTTPClient returns a new HTTPClient based on a default
// http.Client
func NewDefaultHTTPClient() HTTPClient {
	client := http.Client{}
	rt := NewDefaultHTTPRoundTripper()
	client.Transport = rt
	return HTTPClient{
		Client:      &client,
		ByteTracker: rt,
	}
}

Fix bug where ByteTrack in HTTPClient was a different tracker


package main

import (
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	host       = kingpin.Flag("host", "Host to bind webserver to").Default("127.0.0.1").IP()
	port       = kingpin.Flag("port", "Port to bind webserver to").Default("2999").Int()
	production = kingpin.Flag("production", "Run in production mode").Default("false").Bool()
	database   = kingpin.Flag("database", "Database connection string").Default("homestead:secret@tcp(127.0.0.1:33060)/chitchat").String()
)

package main

import (
	"gopkg.in/alecthomas/kingpin.v2"
)

var (
	host       = kingpin.Flag("host", "Host to bind webserver to").Default("127.0.0.1").IP()
	port       = kingpin.Flag("port", "Port to bind webserver to").Default("2015").Int()
	production = kingpin.Flag("production", "Run in production mode").Default("false").Bool()
	database   = kingpin.Flag("database", "Database connection string").Default("homestead:secret@tcp(127.0.0.1:33060)/chitchat").String()
)

Set default port to 2015


package engine

import (
	"encoding/json"
	"fmt"
)

type Dot struct {
	X uint8
	Y uint8
}

// Equals compares two dots
func (d1 Dot) Equals(d2 Dot) bool {
	return d1 == d2 || (d1.X == d2.X && d1.Y == d2.Y)
}

// Implementing json.Marshaler interface
func (d Dot) MarshalJSON() ([]byte, error) {
	return json.Marshal([]uint8{d.X, d.Y})
}

func (d Dot) String() string {
	return fmt.Sprintf("[%d, %d]", d.X, d.Y)
}

// DistanceTo calculates distance between two dots
func (from Dot) DistanceTo(to Dot) (res uint16) {
	if !from.Equals(to) {
		if from.X > to.X {
			res = uint16(from.X - to.X)
		} else {
			res = uint16(to.X - from.X)
		}

		if from.Y > to.Y {
			res += uint16(from.Y - to.Y)
		} else {
			res += uint16(to.Y - from.Y)
		}
	}

	return
}

package engine

import "fmt"

type Dot struct {
	X uint8
	Y uint8
}

// Equals compares two dots
func (d1 Dot) Equals(d2 Dot) bool {
	return d1 == d2 || (d1.X == d2.X && d1.Y == d2.Y)
}

// Implementing json.Marshaler interface
func (d Dot) MarshalJSON() ([]byte, error) {
	return []byte(fmt.Sprintf("[%d,%d]", d.X, d.Y)), nil
}

func (d Dot) String() string {
	return fmt.Sprintf("[%d, %d]", d.X, d.Y)
}

// DistanceTo calculates distance between two dots
func (from Dot) DistanceTo(to Dot) (res uint16) {
	if !from.Equals(to) {
		if from.X > to.X {
			res = uint16(from.X - to.X)
		} else {
			res = uint16(to.X - from.X)
		}

		if from.Y > to.Y {
			res += uint16(from.Y - to.Y)
		} else {
			res += uint16(to.Y - from.Y)
		}
	}

	return
}

Rewrite engine.Dot marshaler to use sprintf instead json.Marshal


// Some utility functions, which are classified to a certain package.
package utils

import "runtime"

var (
	Mac     = "\r"
	Unix    = "\n"
	Windows = "\r\n"
)

var newlines map[string]string

func init() {
	newlines = map[string]string{
		"windows": Windows,
		"darwin":  Mac,
		"linux":   Unix,
		"freebsd": Unix,
	}
}

// Return the newline of the current os. For example, windows' is "\r\n",
// linux's is "\n", Mac's is "\r", etc.
func NewLine() string {
	if v, ok := newlines[runtime.GOOS]; ok {
		return v
	} else {
		return Unix
	}
}

// Package utils supplys some utility functions, which are classified to a certain package.
package utils

import "runtime"

var (
	// MacNL is the newline in Mac.
	MacNL = "\r"

	// UnixNL is the newline in Unix/Linux.
	UnixNL = "\n"

	// WindowsNL is the newline in Windows.
	WindowsNL = "\r\n"
)

var newlines map[string]string

func init() {
	newlines = map[string]string{
		"windows": WindowsNL,
		"darwin":  MacNL,
		"linux":   UnixNL,
		"freebsd": UnixNL,
	}
}

// NewLine returns the newline of the current os. For example, windows' is "\r\n",
// linux's is "\n", Mac's is "\r", etc.
func NewLine() string {
	if v, ok := newlines[runtime.GOOS]; ok {
		return v
	}
	return UnixNL
}

Update the comment of the package utils.


package main

import (
	"fmt"
	"io/ioutil"
	"runtime"

	"github.com/shurcooL/trayhost"
)

func main() {
	runtime.LockOSThread()

	menuItems := trayhost.MenuItems{
		trayhost.MenuItem{
			Title: "Instant Share",
			Handler: func() {
				fmt.Println("TODO: grab content, content-type of clipboard")
				fmt.Println("TODO: request URL")
				fmt.Println("TODO: display/put URL in clipboard")
				fmt.Println("TODO: upload image in background")
			},
		},
		trayhost.SeparatorMenuItem(),
		trayhost.MenuItem{
			Title:   "Quit",
			Handler: trayhost.Exit,
		},
	}

	// TODO: Create a real icon and bake it into the binary.
	iconData, err := ioutil.ReadFile("./icon.png")
	if err != nil {
		panic(err)
	}

	trayhost.Initialize("InstantShare", iconData, menuItems)

	trayhost.EnterLoop()
}

package main

import (
	"fmt"
	"io/ioutil"
	"runtime"

	"github.com/shurcooL/trayhost"
)

func main() {
	runtime.LockOSThread()

	menuItems := []trayhost.MenuItem{
		trayhost.MenuItem{
			Title: "Instant Share",
			Handler: func() {
				fmt.Println("TODO: grab content, content-type of clipboard")
				fmt.Println("TODO: request URL")
				fmt.Println("TODO: display/put URL in clipboard")
				fmt.Println("TODO: upload image in background")
			},
		},
		trayhost.SeparatorMenuItem(),
		trayhost.MenuItem{
			Title:   "Quit",
			Handler: trayhost.Exit,
		},
	}

	// TODO: Create a real icon and bake it into the binary.
	iconData, err := ioutil.ReadFile("./icon.png")
	if err != nil {
		panic(err)
	}

	trayhost.Initialize("InstantShare", iconData, menuItems)

	trayhost.EnterLoop()
}

Update to upstream API change.


package frontend

import (
	"crypto/hmac"
	"crypto/sha1"
)

// ComputeHMAC of a message using a specific key
func ComputeHMAC(message []byte, key string) []byte {
	mac := hmac.New(sha1.New, []byte(key))
	mac.Write(message)
	return mac.Sum(nil)
}

// CheckHMAC of a message
func CheckHMAC(message, messageHMAC []byte, key string) bool {
	return hmac.Equal(messageHMAC, ComputeHMAC(message, key))
}

package frontend

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/hex"
)

// ComputeHMAC of a message using a specific key
func ComputeHMAC(message []byte, key string) []byte {
	mac := hmac.New(sha1.New, []byte(key))
	mac.Write(message)
	return []byte(hex.EncodeToString(mac.Sum(nil)))
}

// CheckHMAC of a message
func CheckHMAC(message, messageHMAC []byte, key string) bool {
	return hmac.Equal(messageHMAC, ComputeHMAC(message, key))
}

Change HMAC computation to match the cvmfs server tools


package main

import (
	"fmt"
	"log"

	"github.com/yofu/dxf"
	"github.com/yofu/dxf/entity"
)

func main() {
	dr, err := dxf.Open("point.dxf")
	if err != nil {
		log.Fatal(err)
	}
	for _, e := range dr.Entities() {
		if p, ok := e.(*entity.Point); ok {
			fmt.Println(p.Coord)
		}
	}
}

package main

import (
	"fmt"
	"log"

	"github.com/yofu/dxf"
	"github.com/yofu/dxf/entity"
)

func main() {
	dr, err := dxf.FromFile("point.dxf")
	if err != nil {
		log.Fatal(err)
	}
	for _, e := range dr.Entities() {
		if p, ok := e.(*entity.Point); ok {
			fmt.Println(p.Coord)
		}
	}
}

Move to new func name


package imgwizard

import (
	"bytes"
	"image"
	"image/png"
	"net/http"

	"github.com/foobaz/lossypng/lossypng"
	"github.com/shifr/vips"
)

func Transform(img_buff *[]byte, ctx *Context) {
	var err error
	buf := new(bytes.Buffer)

	debug("Detecting image type...")
	iType := http.DetectContentType(*img_buff)

	if !stringExists(iType, ResizableImageTypes) {
		warning("Wizard resize doesn't support image type, returning original image")
		return
	}

	*img_buff, err = vips.Resize(*img_buff, ctx.Options)
	if err != nil {
		warning("Can't resize img, reason - %s", err)
		return
	}

	if iType == PNG {
		decoded, _, err := image.Decode(bytes.NewReader(*img_buff))
		if err != nil {
			warning("Can't decode PNG image, reason - %s", err)
		}

		out := lossypng.Compress(decoded, lossypng.NoConversion, 100-ctx.Options.Quality)
		err = png.Encode(buf, out)
		if err != nil {
			warning("Can't encode PNG image, reason - %s", err)
		}

		*img_buff = buf.Bytes()
	}

}

package imgwizard

import (
	"bytes"
	"image"
	"image/png"
	"net/http"

	"github.com/foobaz/lossypng/lossypng"
	"github.com/shifr/vips"
)

func Transform(img_buff *[]byte, ctx *Context) {
	var err error
	buf := new(bytes.Buffer)

	debug("Detecting image type...")
	iType := http.DetectContentType(*img_buff)

	if !stringExists(iType, ResizableImageTypes) {
		warning("Wizard resize doesn't support image type, returning original image")
		return
	}

	*img_buff, err = vips.Resize(*img_buff, ctx.Options)
	if err != nil {
		warning("Can't resize img, reason - %s", err)
		return
	}

	if iType == PNG && !ctx.Options.Webp {
		decoded, _, err := image.Decode(bytes.NewReader(*img_buff))
		if err != nil {
			warning("Can't decode PNG image, reason - %s", err)
		}

		out := lossypng.Compress(decoded, lossypng.NoConversion, 100-ctx.Options.Quality)
		err = png.Encode(buf, out)
		if err != nil {
			warning("Can't encode PNG image, reason - %s", err)
		}

		*img_buff = buf.Bytes()
	}

}

Check if browser accepts Webp instead of .png


package leetcode

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func sumNumbers(root *TreeNode) int {
	if root == nil {
		return 0
	} else if root.Left == nil && root.Right == nil {
		return root.Val
	} else if root.Left == nil {
		return sum(root.Right, root.Val)
	} else if root.Right == nil {
		return sum(root.Left, root.Val)
	}
	return sum(root.Left, root.Val) + sum(root.Right, root.Val)
}

func sum(node *TreeNode, val int) int {
	newVal := val*10 + node.Val
	if node.Left == nil && node.Right == nil {
		return newVal
	} else if node.Left == nil {
		return sum(node.Right, newVal)
	} else if node.Right == nil {
		return sum(node.Left, newVal)
	}

	return sum(node.Left, newVal) + sum(node.Right, newVal)
}

package leetcode

type TreeNode struct {
	Val   int
	Left  *TreeNode
	Right *TreeNode
}

func sumNumbers(root *TreeNode) int {
	if root == nil {
		return 0
	} else if root.Left == nil && root.Right == nil {
		return root.Val
	} else if root.Left == nil {
		return sum(root.Right, root.Val)
	} else if root.Right == nil {
		return sum(root.Left, root.Val)
	}
	return sum(root.Left, root.Val) + sum(root.Right, root.Val)
}

func sum(node *TreeNode, val int) int {
	newVal := val*10 + node.Val
	if node.Left == nil && node.Right == nil {
		return newVal
	} else if node.Left == nil {
		return sum(node.Right, newVal)
	} else if node.Right == nil {
		return sum(node.Left, newVal)
	}

	return sum(node.Left, newVal) + sum(node.Right, newVal)
}

Add TreeNode to fix compile error


// +build darwin freebsd openbsd netbsd
// +build !appengine

package isatty

import (
	"syscall"
	"unsafe"
)

const ioctlReadTermios = syscall.TIOCGETA

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

// +build darwin freebsd openbsd netbsd dragonfly
// +build !appengine

package isatty

import (
	"syscall"
	"unsafe"
)

const ioctlReadTermios = syscall.TIOCGETA

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

Add dragonfly to bsd build


package hal

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

// RenderToString renders the provided data as a json string
func RenderToString(data interface{}, pretty bool) ([]byte, error) {
	if pretty {
		return json.MarshalIndent(data, "", "  ")
	}

	return json.Marshal(data)
}

// Render write data to w, after marshalling to json
func Render(w http.ResponseWriter, data interface{}) {
	js, err := RenderToString(data, true)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/hal+json; charset=utf-8")
	w.Write(js)
}

package hal

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

// RenderToString renders the provided data as a json string
func RenderToString(data interface{}, pretty bool) ([]byte, error) {
	if pretty {
		return json.MarshalIndent(data, "", "  ")
	}

	return json.Marshal(data)
}

// Render write data to w, after marshalling to json
func Render(w http.ResponseWriter, data interface{}) {
	js, err := RenderToString(data, true)

	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Disposition", "inline")
	w.Header().Set("Content-Type", "application/hal+json; charset=utf-8")
	w.Write(js)
}

Add Content-Disposition header for hal responses


package main

import (
	"reflect"
	"testing"
)

var parseIndexesListTests = []struct {
	list    string
	indexes []int
}{
	// Only one index
	{
		list:    "10",
		indexes: []int{10},
	},
	{
		list:    "120",
		indexes: []int{120},
	},

	// Multiple indexes
	{
		list:    "10,120",
		indexes: []int{10, 120},
	},
	{
		list:    "10,120,50",
		indexes: []int{10, 120, 50},
	},
	{
		list:    "3,2,1,0",
		indexes: []int{3, 2, 1, 0},
	},
}

func TestParseIndexesList(t *testing.T) {
	for _, test := range parseIndexesListTests {
		expect := test.indexes
		actual, err := parseIndexesList(test.list)
		if err != nil {
			t.Errorf("parseIndexesList(%q) returns %q, want nil",
				test.list, err)
		}
		if !reflect.DeepEqual(actual, expect) {
			t.Error("parseIndexesList(%q) = %v, want %v",
				test.list, actual, expect)
		}
	}
}

package main

import (
	"reflect"
	"testing"
)

var parseIndexesListTests = []struct {
	list    string
	indexes []int
}{
	// Only one index
	{
		list:    "10",
		indexes: []int{10},
	},
	{
		list:    "120",
		indexes: []int{120},
	},

	// Multiple indexes
	{
		list:    "10,120",
		indexes: []int{10, 120},
	},
	{
		list:    "10,120,50",
		indexes: []int{10, 120, 50},
	},
	{
		list:    "3,2,1,0",
		indexes: []int{3, 2, 1, 0},
	},
}

func TestParseIndexesList(t *testing.T) {
	for _, test := range parseIndexesListTests {
		expect := test.indexes
		actual, err := parseIndexesList(test.list)
		if err != nil {
			t.Errorf("parseIndexesList(%q) returns %q, want nil",
				test.list, err)
		}
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("parseIndexesList(%q) = %v, want %v",
				test.list, actual, expect)
		}
	}
}

Use Errorf instead of Error


package rtp

// Depacketizer depacketizes a RTP payload, removing any RTP specific data from the payload
type Depacketizer interface {
	Unmarshal(packet *Packet) ([]byte, error)
}

package rtp

// Depacketizer depacketizes a RTP payload, removing any RTP specific data from the payload
type Depacketizer interface {
	Unmarshal(packet []byte) ([]byte, error)
}

Update Depacketizer interface to match codecs


package def

import (
	"bytes"

	"github.com/go-yaml/yaml"
	"github.com/ugorji/go/codec"

	"polydawn.net/repeatr/lib/cereal"
)

var codecBounceHandler = &codec.CborHandle{}

func ParseYaml(ser []byte) *Formula {
	// Turn tabs into spaces so that tabs are acceptable inputs.
	ser = cereal.Tab2space(ser)
	// Bounce the serial form into another temporary intermediate form.
	// Yes.  Feel the sadness in your soul.
	// This lets us feed a byte area to ugorji codec that it understands,
	//  because it doesn't have any mechanisms to accept in-memory structs.
	var raw interface{}
	if err := yaml.Unmarshal(ser, &raw); err != nil {
		panic(ConfigError.New("Could not parse formula: %s", err))
	}
	var buf bytes.Buffer
	if err := codec.NewEncoder(&buf, codecBounceHandler).Encode(raw); err != nil {
		panic(ConfigError.New("Could not parse formula (stg2): %s", err))
	}
	// Actually decode with the smart codecs.
	var frm Formula
	if err := codec.NewDecoder(&buf, codecBounceHandler).Decode(&frm); err != nil {
		// one would really hope this is impossible...
		panic(ConfigError.New("Could not parse formula (stg3): %s", err))
	}
	return &frm
}

package def

import (
	"bytes"

	"github.com/go-yaml/yaml"
	"github.com/ugorji/go/codec"

	"polydawn.net/repeatr/lib/cereal"
)

var codecBounceHandler = &codec.CborHandle{}

func ParseYaml(ser []byte) *Formula {
	// Turn tabs into spaces so that tabs are acceptable inputs.
	ser = cereal.Tab2space(ser)
	// Bounce the serial form into another temporary intermediate form.
	// Yes.  Feel the sadness in your soul.
	// This lets us feed a byte area to ugorji codec that it understands,
	//  because it doesn't have any mechanisms to accept in-memory structs.
	var raw interface{}
	if err := yaml.Unmarshal(ser, &raw); err != nil {
		panic(ConfigError.New("Could not parse formula: %s", err))
	}
	var buf bytes.Buffer
	if err := codec.NewEncoder(&buf, codecBounceHandler).Encode(raw); err != nil {
		panic(ConfigError.New("Could not parse formula: %s", err))
	}
	// Actually decode with the smart codecs.
	var frm Formula
	if err := codec.NewDecoder(&buf, codecBounceHandler).Decode(&frm); err != nil {
		panic(ConfigError.New("Could not parse formula: %s", err))
	}
	return &frm
}

Drop mention of what phase of parsing errored.


package main

import (
	"./app/api"
	"./app/controllers"
	"./db"
	"github.com/codegangsta/martini"
	"github.com/codegangsta/martini-contrib/render"
)

/**
 * Connect to database.
 */
func dbConnection() {
	db.Init()
	db.CreateTables()
	db.RunFixtures()
}

/**
 * Load all Controllers.
 */
func loadControllers(app *martini.ClassicMartini) {
	controllers.NewHomeController(app)
}

/**
 * Load all ApiControllers.
 */
func loadApiControllers(app *martini.ClassicMartini) {
	apiControllers.NewUserApiController(app)
}

/**
 * Martini application configuration.
 */
func configuration(app *martini.ClassicMartini) {
	app.Use(martini.Static("public"))
	app.Use(render.Renderer(render.Options{
		Directory:  "app/views",
		Layout:     "layout",
		Charset:    "UTF-8",
		IndentJSON: true,
	}))
}

/**
 * Run martini application.
 */
func main() {
	app := martini.Classic()
	dbConnection()
	configuration(app)
	loadControllers(app)
	loadApiControllers(app)
	app.Run()
}

package main

import (
	"./app/api"
	"./app/controllers"
	"./db"
	"github.com/codegangsta/martini"
	"github.com/codegangsta/martini-contrib/render"
)

/**
 * Connect to database.
 */
func dbConnection() {
	db.Init()
	//db.CreateTables()
	//db.RunFixtures()
	//db.Migrate()
}

/**
 * Load all Controllers.
 */
func loadControllers(app *martini.ClassicMartini) {
	controllers.NewHomeController(app)
}

/**
 * Load all ApiControllers.
 */
func loadApiControllers(app *martini.ClassicMartini) {
	apiControllers.NewUserApiController(app)
}

/**
 * Martini application configuration.
 */
func configuration(app *martini.ClassicMartini) {
	app.Use(martini.Static("public"))
	app.Use(render.Renderer(render.Options{
		Directory:  "app/views",
		Layout:     "layout",
		Charset:    "UTF-8",
		IndentJSON: true,
	}))
}

/**
 * Run martini application.
 */
func main() {
	app := martini.Classic()
	dbConnection()
	configuration(app)
	loadControllers(app)
	loadApiControllers(app)
	app.Run()
}

Prepare and comment all database tasks.


package main

import (
	"fmt"
	"os"

	"github.com/libgit2/git2go"
)

func main() {
	repo, err := git.OpenRepository(".")
	if err != nil {
		fmt.Printf("not a repo: %s\n", err)
		os.Exit(5)
	}

	desc, err := repo.DescribeWorkdir(&git.DescribeOptions{})
	if err != nil {
		fmt.Printf("madness: %s\n", err)
		os.Exit(6)
	}
	fmt.Printf("repo: %s\n", desc)
}

Make some actual main method to play with.


// generated by stringer -type=NodeType; DO NOT EDIT

package parser

import "fmt"

const _NodeType_name = "NodeTypeErrorNodeTypeGlobalModuleNodeTypeFileNodeTypeCommentNodeTypeCustomOpNodeTypeAnnotationNodeTypeParameterNodeTypeDeclarationNodeTypeMemberNodeTypeImplementationNodeTypeTagged"

var _NodeType_index = [...]uint8{0, 13, 33, 45, 60, 76, 94, 111, 130, 144, 166, 180}

func (i NodeType) String() string {
	if i < 0 || i >= NodeType(len(_NodeType_index)-1) {
		return fmt.Sprintf("NodeType(%d)", i)
	}
	return _NodeType_name[_NodeType_index[i]:_NodeType_index[i+1]]
}

// Code generated by "stringer -type=NodeType"; DO NOT EDIT

package parser

import "fmt"

const _NodeType_name = "NodeTypeErrorNodeTypeGlobalModuleNodeTypeGlobalDeclarationNodeTypeFileNodeTypeCommentNodeTypeCustomOpNodeTypeAnnotationNodeTypeParameterNodeTypeDeclarationNodeTypeMemberNodeTypeImplementationNodeTypeTagged"

var _NodeType_index = [...]uint8{0, 13, 33, 58, 70, 85, 101, 119, 136, 155, 169, 191, 205}

func (i NodeType) String() string {
	if i < 0 || i >= NodeType(len(_NodeType_index)-1) {
		return fmt.Sprintf("NodeType(%d)", i)
	}
	return _NodeType_name[_NodeType_index[i]:_NodeType_index[i+1]]
}

Update WebIDL parser node type


package main

import (
	"fmt"
	"github.com/libgit2/git2go"
	"github.com/urfave/cli"
)

func GitSeekretCheck(c *cli.Context) error {
	err := gs.LoadConfig(true)
	if git.IsErrorClass(err, git.ErrClassConfig) {
		return fmt.Errorf("Config not initialised - Try: 'git-seekret config --init'")
	}
	if err != nil {
		return err
	}

	options := map[string]interface{}{
		"commit": false,
		"staged": false,
	}

	if c.IsSet("commit") {
		options["commit"] = true
		options["commitcount"] = c.Int("commit")
	}

	if c.IsSet("staged") {
		options["staged"] = true
	}

	secrets, err := gs.RunCheck(options)
	if err != nil {
		return err
	}
	if secrets != 0 {
		return fmt.Errorf("Please remove discovered secrets")
	}

	return nil
}

package main

import (
	"fmt"
	"github.com/libgit2/git2go"
	"github.com/urfave/cli"
)

func GitSeekretCheck(c *cli.Context) error {
	err := gs.LoadConfig(true)
	if git.IsErrorClass(err, git.ErrClassConfig) {
		return fmt.Errorf("Config not initialised - Try: 'git-seekret config --init'")
	}
	if err != nil {
		return err
	}

	options := map[string]interface{}{
		"commit-files": false,
		"staged-files": false,
	}

	if c.IsSet("commit") {
		options["commit-files"] = true
		options["commit-messages"] = true
		options["commit-count"] = c.Int("commit")
	}

	if c.IsSet("staged") {
		options["staged-files"] = true
	}

	secrets, err := gs.RunCheck(options)
	if err != nil {
		return err
	}
	if secrets != 0 {
		return fmt.Errorf("Please remove discovered secrets")
	}

	return nil
}

Fix options for check subcommand for staged files and commits


package routes

import (
	"github.com/DVI-GI-2017/Jira__backend/handlers"
)

func InitRouter(r *router) {
	r.Post("/signup", handlers.RegisterUser)
	r.Post("/signin", handlers.Login)
}

package routes

import (
	"log"

	"github.com/DVI-GI-2017/Jira__backend/handlers"
)

func InitRouter(r *router) {
	const signup = "/signup"
	err := r.Post(signup, handlers.RegisterUser)
	if err != nil {
		log.Panicf("can not init route '%s': %v", signup, err)
	}

	const signin = "/signin"
	err = r.Post(signin, handlers.Login)
	if err != nil {
		log.Panicf("can not init route '%s': %v", signin, err)
	}
}

Add more verbose check when adding new route.


package server

import (
	"github.com/gocraft/web"
	"runtime"
)

type serverStatus struct {
	*APIContext
}

func SetUpServerStatusRouter(prefix string, router *web.Router) {
	root := router.Subrouter(serverStatus{}, "/runtime_status")
	root.Get("/", (*serverStatus).Index)
}

func (ss *serverStatus) Index(rw web.ResponseWriter, req *web.Request) {
	ss.RenderJSON(map[string]interface{}{
		"num_goroutine": runtime.NumGoroutine(),
		"num_cgo_call":  runtime.NumCgoCall(),
		"gomaxprocs":    runtime.GOMAXPROCS(0),
		"goroot":        runtime.GOROOT(),
		"num_cpu":       runtime.NumCPU(),
		"goversion":     runtime.Version(),
	})
}

package server

import (
	"github.com/gocraft/web"
	"runtime"
)

type serverStatus struct {
	*APIContext
}

func SetUpServerStatusRouter(prefix string, router *web.Router) {
	root := router.Subrouter(serverStatus{}, "")
	root.Get("/runtime_status", (*serverStatus).RuntimeStatus)
}

func (ss *serverStatus) RuntimeStatus(rw web.ResponseWriter, req *web.Request) {
	ss.RenderJSON(map[string]interface{}{
		"num_goroutine": runtime.NumGoroutine(),
		"num_cgo_call":  runtime.NumCgoCall(),
		"gomaxprocs":    runtime.GOMAXPROCS(0),
		"goroot":        runtime.GOROOT(),
		"num_cpu":       runtime.NumCPU(),
		"goversion":     runtime.Version(),
	})
}

Fix Subrouter pathPrefix of serverStatus controller


//
// Use and distribution licensed under the Apache license version 2.
//
// See the COPYING file in the root project directory for full text.
//

package ghw

var (
	KB int64 = 1024
	MB int64 = KB * 1024
	GB int64 = MB * 1024
	TB int64 = GB * 1024
	PB int64 = TB * 1024
	EB int64 = PB * 1024
)

func unitWithString(size int64) (int64, string) {
	switch {
	case size < MB:
		return KB, "KB"
	case size < GB:
		return MB, "MB"
	case size < TB:
		return GB, "GB"
	case size < PB:
		return TB, "TB"
	case size < EB:
		return PB, "PB"
	default:
		return EB, "EB"
	}
}

//
// Use and distribution licensed under the Apache license version 2.
//
// See the COPYING file in the root project directory for full text.
//

package ghw

var (
	KB int64 = 1024
	MB       = KB * 1024
	GB       = MB * 1024
	TB       = GB * 1024
	PB       = TB * 1024
	EB       = PB * 1024
)

func unitWithString(size int64) (int64, string) {
	switch {
	case size < MB:
		return KB, "KB"
	case size < GB:
		return MB, "MB"
	case size < TB:
		return GB, "GB"
	case size < PB:
		return TB, "TB"
	case size < EB:
		return PB, "PB"
	default:
		return EB, "EB"
	}
}

Fix up unit.go lint nits


package adapter

import (
	"errors"

	"github.com/golang/glog"

	kauthorizer "k8s.io/kubernetes/pkg/auth/authorizer"

	oauthorizer "github.com/openshift/origin/pkg/authorization/authorizer"
)

type AdapterAuthorizer struct {
	originAuthorizer oauthorizer.Authorizer
}

// NewAuthorizer adapts an Origin Authorizer interface to a Kubernetes Authorizer interface
func NewAuthorizer(originAuthorizer oauthorizer.Authorizer) (kauthorizer.Authorizer, error) {
	return &AdapterAuthorizer{originAuthorizer}, nil
}

func (z *AdapterAuthorizer) Authorize(kattrs kauthorizer.Attributes) error {
	allowed, reason, err := z.originAuthorizer.Authorize(OriginAuthorizerAttributes(kattrs))

	if err != nil {
		glog.V(5).Infof("evaluation error: %v", err)
		return err
	}

	glog.V(5).Infof("allowed=%v, reason=%s", allowed, reason)
	if allowed {
		return nil
	}

	// Turn the reason into an error so we can reject with the most information possible
	return errors.New(reason)
}

package adapter

import (
	"github.com/golang/glog"

	kauthorizer "k8s.io/kubernetes/pkg/auth/authorizer"

	oauthorizer "github.com/openshift/origin/pkg/authorization/authorizer"
)

type AdapterAuthorizer struct {
	originAuthorizer oauthorizer.Authorizer
}

// NewAuthorizer adapts an Origin Authorizer interface to a Kubernetes Authorizer interface
func NewAuthorizer(originAuthorizer oauthorizer.Authorizer) (kauthorizer.Authorizer, error) {
	return &AdapterAuthorizer{originAuthorizer}, nil
}

func (z *AdapterAuthorizer) Authorize(kattrs kauthorizer.Attributes) (bool, string, error) {
	allowed, reason, err := z.originAuthorizer.Authorize(OriginAuthorizerAttributes(kattrs))

	if err != nil {
		glog.V(5).Infof("evaluation error: %v", err)
		return allowed, reason, err
	}

	glog.V(5).Infof("allowed=%v, reason=%s", allowed, reason)
	return allowed, reason, nil
}

Simplify AuthorizationAdapter now that upstream matches our signature


package migration

import (
	"k8s.io/client-go/kubernetes"

	v1 "github.com/sapcc/kubernikus/pkg/apis/kubernikus/v1"
	"github.com/sapcc/kubernikus/pkg/client/openstack"
	"github.com/sapcc/kubernikus/pkg/util"
	etcd_util "github.com/sapcc/kubernikus/pkg/util/etcd"
)

func CreateEtcdBackupStorageContainer(rawKluster []byte, current *v1.Kluster, client kubernetes.Interface, openstackFactory openstack.SharedOpenstackClientFactory) (err error) {
	secret, err := util.KlusterSecret(client, current)
	if err != nil {
		return err
	}

	adminClient, err := openstackFactory.AdminClient()
	if err != nil {
		return err
	}

	err = adminClient.CreateStorageContainer(
		current.Spec.Openstack.ProjectID,
		etcd_util.DefaultStorageContainer(current),
		secret.Openstack.Username,
		secret.Openstack.DomainName,
	)

	return err
}

package migration

import (
	"errors"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"

	"github.com/sapcc/kubernikus/pkg/apis/kubernikus/v1"
	"github.com/sapcc/kubernikus/pkg/client/openstack"
	etcd_util "github.com/sapcc/kubernikus/pkg/util/etcd"
)

func CreateEtcdBackupStorageContainer(rawKluster []byte, current *v1.Kluster, client kubernetes.Interface, openstackFactory openstack.SharedOpenstackClientFactory) (err error) {
	secret, err := client.CoreV1().Secrets(current.GetNamespace()).Get(current.GetName(), metav1.GetOptions{})
	if err != nil {
		return err
	}

	username, ok := secret.Data["openstack-username"]
	if !ok {
		return errors.New("openstack username secret not set")
	}

	domain, ok := secret.Data["openstack-domain-name"]
	if !ok {
		return errors.New("openstack domain name secret not set")
	}

	adminClient, err := openstackFactory.AdminClient()
	if err != nil {
		return err
	}

	err = adminClient.CreateStorageContainer(
		current.Spec.Openstack.ProjectID,
		etcd_util.DefaultStorageContainer(current),
		string(username),
		string(domain),
	)

	return err
}

Revert migration version 3 to previous state


package keeper

import (
	"fmt"
	"math"

	"github.com/cosmos/cosmos-sdk/codec"
	sdk "github.com/cosmos/cosmos-sdk/types"
	"github.com/tendermint/tendermint/libs/log"
	"github.com/zigbee-alliance/distributed-compliance-ledger/x/validator/types"
)

type (
	Keeper struct {
		cdc      codec.BinaryCodec
		storeKey sdk.StoreKey
		memKey   sdk.StoreKey

		dclauthKeeper types.DclauthKeeper
	}
)

func NewKeeper(
	cdc codec.BinaryCodec,
	storeKey,
	memKey sdk.StoreKey,

	dclauthKeeper types.DclauthKeeper,
) *Keeper {
	return &Keeper{
		cdc:      cdc,
		storeKey: storeKey,
		memKey:   memKey,

		dclauthKeeper: dclauthKeeper,
	}
}

func (k Keeper) Logger(ctx sdk.Context) log.Logger {
	return ctx.Logger().With("module", fmt.Sprintf("x/%s", types.ModuleName))
}

func (k Keeper) DisableValidatorApprovalsCount(ctx sdk.Context) int {
	return int(math.Round(types.DisableValidatorPercent * float64(k.dclauthKeeper.CountAccountsWithRole(ctx, types.VoteForDisableValidatorRole))))
}

func (k Keeper) DisableValidatorRejectApprovalsCount(ctx sdk.Context) int {
	return k.dclauthKeeper.CountAccountsWithRole(ctx, types.VoteForDisableValidatorRole) - k.DisableValidatorApprovalsCount(ctx) + 1
}

Add function for accumulating disable validator reject approvals count


/*
Copyright (c) 2014 VMware, Inc. All Rights Reserved.

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

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

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

package govmomi

import "github.com/vmware/govmomi/vim25/types"

type VirtualMachine struct {
	types.ManagedObjectReference
}

func (d VirtualMachine) Reference() types.ManagedObjectReference {
	return d.ManagedObjectReference
}

/*
Copyright (c) 2014 VMware, Inc. All Rights Reserved.

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

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

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

package govmomi

import (
	"errors"

	"github.com/vmware/govmomi/vim25/tasks"
	"github.com/vmware/govmomi/vim25/types"
)

type VirtualMachine struct {
	types.ManagedObjectReference
}

func (v VirtualMachine) Reference() types.ManagedObjectReference {
	return v.ManagedObjectReference
}

func (v VirtualMachine) waitForTask(t tasks.Task) error {
	info, err := t.Wait()
	if err != nil {
		return err
	}

	if info.Error != nil {
		return errors.New(info.Error.LocalizedMessage)
	}

	return nil
}

func (v VirtualMachine) PowerOn(c *Client) error {
	req := types.PowerOnVM_Task{
		This: v.Reference(),
	}

	task, err := tasks.PowerOnVM(c, &req)
	if err != nil {
		return err
	}

	return v.waitForTask(task)
}

func (v VirtualMachine) PowerOff(c *Client) error {
	req := types.PowerOffVM_Task{
		This: v.Reference(),
	}

	task, err := tasks.PowerOffVM(c, &req)
	if err != nil {
		return err
	}

	return v.waitForTask(task)
}

func (v VirtualMachine) Reset(c *Client) error {
	req := types.ResetVM_Task{
		This: v.Reference(),
	}

	task, err := tasks.ResetVM(c, &req)
	if err != nil {
		return err
	}

	return v.waitForTask(task)
}

Add power on/off and reset functions to VirtualMachine


package main

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

	"github.com/robertkrimen/otto"
	"github.com/robertkrimen/otto/underscore"
)

var flag_underscore *bool = flag.Bool("underscore", true, "Load underscore into the runtime environment")

func readSource(filename string) ([]byte, error) {
	if filename == "" || filename == "-" {
		return ioutil.ReadAll(os.Stdin)
	}
	return ioutil.ReadFile(filename)
}

func main() {
	flag.Parse()

	if !*flag_underscore {
		underscore.Disable()
	}

	err := func() error {
		src, err := readSource(flag.Arg(0))
		if err != nil {
			return err
		}

		vm := otto.New()
		_, err = vm.Run(src)
		return err
	}()
	if err != nil {
		switch err := err.(type) {
		case *otto.Error:
			fmt.Print(err.String())
		default:
			fmt.Println(err)
		}
		os.Exit(64)
	}
}

package main

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

	"github.com/robertkrimen/otto/underscore"
	"github.com/xyproto/otto"
)

var flag_underscore *bool = flag.Bool("underscore", true, "Load underscore into the runtime environment")

func readSource(filename string) ([]byte, error) {
	if filename == "" || filename == "-" {
		return ioutil.ReadAll(os.Stdin)
	}
	return ioutil.ReadFile(filename)
}

func main() {
	flag.Parse()

	if !*flag_underscore {
		underscore.Disable()
	}

	err := func() error {
		src, err := readSource(flag.Arg(0))
		if err != nil {
			return err
		}

		vm := otto.New()
		_, err = vm.Run(src)
		return err
	}()
	if err != nil {
		switch err := err.(type) {
		case *otto.Error:
			fmt.Print(err.String())
		default:
			fmt.Println(err)
		}
		os.Exit(64)
	}
}

Change the utility to use this repo, for testing


package misc

var Schools = map[string][]string{
	"Da Vinci Communications": []string{
		"davinci communications",
	},
	"El Segundo High School": []string{
		"es",
		"eshs",
		"el segundo",
		"gundo",
	},
	"Harbor Teacher Preparation Academy": []string{
		"htpa",
	},
	"Hawthorne Math and Science Academy": []string{
		"hmsa",
		"hms",
	},
	"North High School": []string{
		"north high",
		"north",
	},
	"Palos Verdes High School": []string{
		"pv",
		"palos verdes hs",
	},
	"Palos Verdes Peninsula High School": []string{
		"pvphs",
	},
	"Santa Monica High School": []string{
		"samohi",
		"smhs",
	},
	"South Pasadena High School": []string{
		"sphs",
		"south pasadena high school",
	},
	"Torrance High School": []string{
		"torrance high",
	},
	"West High School": []string{
		"west",
		"west torrance high school",
		"west high sko",
	},
}

package misc

var Schools = map[string][]string{
	"Da Vinci Communications": []string{
		"davinci communications",
	},
	"El Segundo High School": []string{
		"es",
		"eshs",
		"el segundo",
		"gundo",
	},
	"Harbor Teacher Preparation Academy": []string{
		"htpa",
	},
	"Hawthorne Math and Science Academy": []string{
		"hmsa",
		"hms",
	},
	"Lawndale High School": []string{
		"lawndale",
		"lawndale high",
	},
	"North High School": []string{
		"north high",
		"north",
	},
	"Palos Verdes High School": []string{
		"pv",
		"palos verdes hs",
	},
	"Palos Verdes Peninsula High School": []string{
		"pvphs",
	},
	"Santa Monica High School": []string{
		"samohi",
		"smhs",
	},
	"South High School": []string{
		"south high school",
	},
	"South Pasadena High School": []string{
		"sphs",
		"south pasadena high school",
	},
	"Torrance High School": []string{
		"torrance high",
	},
	"West High School": []string{
		"west",
		"west torrance high school",
		"west high sko",
	},
}

Add matchings for Lawndale High and South High.


package infrastructure

import (
	"io/ioutil"

	"gopkg.in/yaml.v2"
)

type Configuration struct {
	Port         string   `yaml:"port"`
	ClientID     string   `yaml:"clientID"`
	ClientSecret string   `yaml:"clientSecret"`
	Scopes       []string `yaml:"scopes,flow"`
}

func GetConfiguration(path string) (*Configuration, error) {

	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	conf := &Configuration{}

	err = yaml.Unmarshal(data, conf)
	if err != nil {
		return nil, err
	}

	return conf, nil

}

package infrastructure

import (
	"io/ioutil"

	"gopkg.in/yaml.v2"
)

type Configuration struct {
	Port         string   `yaml:"port"`
	ClientID     string   `yaml:"clientID"`
	ClientSecret string   `yaml:"clientSecret"`
	Salt         string   `yaml:"salt"`
	Host         string   `yaml:"host"`
	Scopes       []string `yaml:"scopes,flow"`
}

func GetConfiguration(path string) (*Configuration, error) {

	data, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}

	conf := &Configuration{}

	err = yaml.Unmarshal(data, conf)
	if err != nil {
		return nil, err
	}

	return conf, nil

}

Add new necessary configuration fields


// Copyright 2016 Marc-Antoine Ruel. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

// +build go1
// +build !go1.6

package gb

const (
	showGOTRACEBACKBanner = false
)

// Copyright 2016 Marc-Antoine Ruel. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

// +build go1.1
// +build !go1.6

package internal

const (
	showGOTRACEBACKBanner = false
)

Fix build on go <=1.5. (bis)


package reuseport

import (
	"context"
	"net"
	"testing"

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

func testDialFromListeningPort(t *testing.T, network string) {
	lc := net.ListenConfig{
		Control: Control,
	}
	ctx := context.Background()
	l1, err := lc.Listen(ctx, network, "localhost:0")
	require.NoError(t, err)
	l2, err := lc.Listen(ctx, network, "localhost:0")
	require.NoError(t, err)
	d := net.Dialer{
		LocalAddr: l1.Addr(),
		Control:   Control,
	}
	c, err := d.Dial(network, l2.Addr().String())
	require.NoError(t, err)
	c.Close()
}

func TestDialFromListeningPort(t *testing.T) {
	testDialFromListeningPort(t, "tcp")
}

package reuseport

import (
	"context"
	"net"
	"testing"

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

func testDialFromListeningPort(t *testing.T, network string) {
	lc := net.ListenConfig{
		Control: Control,
	}
	ctx := context.Background()
	ll, err := lc.Listen(ctx, network, "localhost:0")
	require.NoError(t, err)
	rl, err := lc.Listen(ctx, network, "localhost:0")
	require.NoError(t, err)
	d := net.Dialer{
		LocalAddr: ll.Addr(),
		Control:   Control,
	}
	c, err := d.Dial(network, rl.Addr().String())
	require.NoError(t, err)
	c.Close()
}

func TestDialFromListeningPort(t *testing.T) {
	testDialFromListeningPort(t, "tcp")
}

func TestDialFromListeningPortTcp6(t *testing.T) {
	testDialFromListeningPort(t, "tcp6")
}

Make test variable names a little more specific


package main

import (
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	ticker := time.NewTicker(10 * time.Second)
	go func() {
		for _ = range ticker.C {
			log.Println("ping google.com -c 5")
			res, err := ping("google.com", 5)
			if err != nil {
				log.Fatal(err)
			}
			log.Printf("Min: %f ms\n", res.Min)
			log.Printf("Avg: %f ms\n", res.Avg)
			log.Printf("Max: %f ms\n", res.Max)
			log.Printf("Mdev: %f ms\n", res.Mdev)
		}
	}()

	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	log.Printf("Received signal: %v\n", <-ch)
	log.Println("Shutting down")
	ticker.Stop()
}

package main

import (
	"container/ring"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	ring := ring.New(10)

	ticker := time.NewTicker(10 * time.Second)
	go func() {
		for _ = range ticker.C {
			log.Println("ping google.com -c 5")
			res, err := ping("google.com", 5)
			if err != nil {
				log.Fatal(err)
			}
			ring.Value = res
			ring.Next()
			log.Printf("Min: %f ms\n", res.Min)
			log.Printf("Avg: %f ms\n", res.Avg)
			log.Printf("Max: %f ms\n", res.Max)
			log.Printf("Mdev: %f ms\n", res.Mdev)
		}
	}()

	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	log.Printf("Received signal: %v\n", <-ch)
	log.Println("Shutting down")
	ticker.Stop()
}

Add ping results to ring buffer


package main

import (
	"os"

	slackreporter "github.com/ariarijp/horenso-reporter-slack/reporter"
	"github.com/bluele/slack"
)

func main() {
	token := os.Getenv("SLACK_TOKEN")
	groupName := os.Getenv("SLACK_GROUP")

	api := slack.New(token)
	r := slackreporter.GetReport([]byte(os.Args[1]))

	slackreporter.NotifyToGroup(*api, r, groupName)
}

package main

import (
	"io/ioutil"
	"os"

	slackreporter "github.com/ariarijp/horenso-reporter-slack/reporter"
	"github.com/bluele/slack"
)

func main() {
	token := os.Getenv("SLACK_TOKEN")
	groupName := os.Getenv("SLACK_GROUP")

	stdin, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		panic(err)
	}

	api := slack.New(token)
	r := slackreporter.GetReport(stdin)

	slackreporter.NotifyToGroup(*api, r, groupName)
}

Fix get the result JSON via STDIN


package main

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

func main() {
	if len(os.Args) == 4 {
		fmt.Println("UNSUPPORTED")
		os.Exit(0)
	} else if len(os.Args) != 3 {
		fmt.Printf("usage: %v <host> <port>\n", os.Args[0])
		os.Exit(1)
	}

	url := "https://" + os.Args[1] + ":" + os.Args[2]

	// Perform an HTTP(S) Request
	_, err := http.Get(url)
	if err != nil {
		fatalError := strings.Contains(err.Error(), "no such host")
		fmt.Println(err.Error())
		if fatalError {
			os.Exit(1)
		}
		fmt.Println("REJECT")
	} else {
		fmt.Println("ACCEPT")
	}
	os.Exit(0)
}

package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

func main() {
	if len(os.Args) < 3 || len(os.Args) > 4 {
		fmt.Printf("usage: %v <host> <port> [cafile]\n", os.Args[0])
		os.Exit(1)
	}

	client := http.DefaultClient
	if len(os.Args) == 4 {
		cadata, err := ioutil.ReadFile(os.Args[3])
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		pool := x509.NewCertPool()
		if !pool.AppendCertsFromPEM(cadata) {
			fmt.Println("Couldn't append certs")
			os.Exit(1)
		}

		client = &http.Client{
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{RootCAs: pool},
			},
		}
	}

	// Perform an HTTPS Request
	_, err := client.Get("https://" + os.Args[1] + ":" + os.Args[2])
	if err != nil {
		fatalError := strings.Contains(err.Error(), "no such host")
		fmt.Println(err.Error())
		if fatalError {
			os.Exit(1)
		}
		fmt.Println("REJECT")
	} else {
		fmt.Println("ACCEPT")
	}
	os.Exit(0)
}

Add cafile support to the go-nethttp stub


package logouthandler

import (
	"net/url"

	"golang.org/x/net/context"

	"github.com/flimzy/jqeventrouter"
	"github.com/flimzy/log"
	"github.com/gopherjs/gopherjs/js"
	"github.com/gopherjs/jquery"

	"github.com/FlashbackSRS/flashback/model"
)

var jQuery = jquery.NewJQuery

// BeforeTransition prepares the logout page before display.
func BeforeTransition(repo *model.Repo) jqeventrouter.HandlerFunc {
	return func(_ *jquery.Event, _ *js.Object, _ url.Values) bool {
		log.Debugf("logout BEFORE\n")

		button := jQuery("#logout")

		button.On("click", func() {
			log.Debugf("Trying to log out now\n")
			if err := repo.Logout(context.TODO()); err != nil {
				log.Printf("Logout failure: %s\n", err)
			}
			jQuery(":mobile-pagecontainer").Call("pagecontainer", "change", "/")
		})
		return true
	}
}

package logouthandler

import (
	"context"
	"net/url"

	"github.com/flimzy/jqeventrouter"
	"github.com/flimzy/log"
	"github.com/gopherjs/gopherjs/js"
	"github.com/gopherjs/jquery"

	"github.com/FlashbackSRS/flashback/model"
)

var jQuery = jquery.NewJQuery

// BeforeTransition prepares the logout page before display.
func BeforeTransition(repo *model.Repo) jqeventrouter.HandlerFunc {
	return func(_ *jquery.Event, _ *js.Object, _ url.Values) bool {
		log.Debugf("logout BEFORE\n")

		button := jQuery("#logout")

		button.On("click", func() {
			log.Debugf("Trying to log out now\n")
			if err := repo.Logout(context.TODO()); err != nil {
				log.Printf("Logout failure: %s\n", err)
			}
			jQuery(":mobile-pagecontainer").Call("pagecontainer", "change", "/")
		})
		return true
	}
}

Switch to proper context pacakge


package checks_test

import (
	. "checks"

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

var _ = Describe("Consul DNS checks", func() {
	It("returns an error when host is not known", func() {
		err := ConsulDnsCheck("host-non-existing.")
		Expect(err).To(MatchError("Failed to resolve consul host host-non-existing.\nlookup host-non-existing.: getaddrinfow: No such host is known."))
	})

	It("does not return an error when host is known", func() {
		Expect(ConsulDnsCheck("localhost")).To(Succeed())
	})
})

package checks_test

import (
	. "checks"

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

var _ = Describe("Consul DNS checks", func() {
	It("returns an error when host is not known", func() {
		err := ConsulDnsCheck("non-existent.example.com.")
		Expect(err.Error()).To(ContainSubstring("Failed to resolve consul host non-existent.example.com."))
	})

	It("does not return an error when host is known", func() {
		Expect(ConsulDnsCheck("localhost")).To(Succeed())
	})
})

Fix consul dns check to not test OS specific messages