<commit_before>package fishfinger

import (
	"testing"

	"github.com/facebookgo/ensure"
)

// -----------------------------------------------------------------------------

func TestCompose_NewCompose(t *testing.T) {
	testCases := []struct {
		name              string
		path              string
		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
	}{
		{"regular", "test/regular/docker-compose.yaml", ensure.Nil},
		{"missingFile", "test/badFormat/missing-file.yaml", ensure.NotNil},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			_, err := NewCompose(tc.path)
			tc.expectedErrorFunc(t, err)
		})
	}
}

func TestCompose_Start(t *testing.T) {
	testCases := []struct {
		name              string
		path              string
		serviceName       string
		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
	}{
		{
			"regular",
			"test/regular/docker-compose.yaml",
			"consul-01",
			ensure.Nil,
		},
		{
			"badFormat",
			"test/badFormat/docker-compose.yaml",
			"consul-01",
			ensure.NotNil,
		},
		{
			"missingService",
			"test/regular/docker-compose.yaml",
			"consulito",
			ensure.NotNil,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c, err := NewCompose(tc.path)
			ensure.Nil(t, err)
			ensure.NotNil(t, c)
			tc.expectedErrorFunc(t, c.Start(tc.serviceName))

			if s, err := c.Status(tc.serviceName); err == nil && s == true {
				ensure.Nil(t, c.Stop(tc.serviceName))
			}
		})
	}
}

func TestCompose_Stop(t *testing.T) {
	testCases := []struct {
		name      string
		path      string
		stopAgain bool
	}{
		{"regular", "test/regular/docker-compose.yaml", false},
		{"alreadyStopped", "test/regular/docker-compose.yaml", true},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c, err := NewCompose(tc.path)
			ensure.Nil(t, err)
			ensure.NotNil(t, c)
			ensure.Nil(t, c.Start("consul-01"))
			ensure.Nil(t, c.Stop("consul-01"))

			if tc.stopAgain == true {
				ensure.Nil(t, c.Stop("consul-01"))
			}
		})
	}
}

func TestCompose_Status(t *testing.T) {
	testCases := []struct {
		name              string
		path              string
		serviceName       string
		activateFunc      func(c *Compose)
		expectedCheckFunc func(ensure.Fataler, bool, ...interface{})
		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
	}{
		{
			"regularUp",
			"test/regular/docker-compose.yaml",
			"consul-01",
			func(c *Compose) { _ = c.Start("consul-01") },
			ensure.True,
			ensure.Nil,
		},
		{
			"regularUpAndDown",
			"test/regular/docker-compose.yaml",
			"consul-01",
			func(c *Compose) {
				_ = c.Start("consul-01")
				_ = c.Stop("consul-01")
			},
			ensure.False,
			ensure.Nil,
		},
		{
			"regularNoUp",
			"test/regular/docker-compose.yaml",
			"consul-01",
			func(c *Compose) { _ = c.Stop("consul-01") },
			ensure.False,
			ensure.Nil,
		},
		{
			"missingService",
			"test/regular/docker-compose.yaml",
			"consulito",
			func(c *Compose) {
				_ = c.Start("consulito")
			},
			ensure.False,
			ensure.NotNil,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c, err := NewCompose(tc.path)
			ensure.Nil(t, err)
			ensure.NotNil(t, c)

			tc.activateFunc(c)
			s, err := c.Status(tc.serviceName)
			tc.expectedCheckFunc(t, s)
			tc.expectedErrorFunc(t, err)
			_ = c.Stop(tc.serviceName)
		})
	}
}

func TestCompose_Port(t *testing.T) {
	testCases := []struct {
		name              string
		path              string
		port              string
		expected          string
		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
	}{
		{
			"regular",
			"test/regular/docker-compose.yaml",
			"8500/tcp",
			"0.0.0.0:5015",
			ensure.Nil,
		},
		{
			"missingPort",
			"test/regular/docker-compose.yaml",
			"5555/tcp",
			"",
			ensure.NotNil,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c, err := NewCompose(tc.path)
			ensure.Nil(t, err)
			ensure.Nil(t, c.Start("consul-01"))

			addr, err := c.Port("consul-01", tc.port)
			tc.expectedErrorFunc(t, err)
			ensure.SameElements(t, addr, tc.expected)
			_ = c.Stop("consul-01")
		})
	}
}

func TestCompose_Env(t *testing.T) {
	testCases := []struct {
		name              string
		path              string
		varName           string
		expected          string
		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
	}{
		{
			"regular",
			"test/regular/docker-compose.yaml",
			"DEBUG",
			"working",
			ensure.Nil,
		},
		{
			"missingVar",
			"test/regular/docker-compose.yaml",
			"MISSING_VAR",
			"",
			ensure.NotNil,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c, err := NewCompose(tc.path)
			ensure.Nil(t, err)
			ensure.Nil(t, c.Start("consul-01"))

			v, err := c.Env("consul-01", tc.varName)
			tc.expectedErrorFunc(t, err)
			ensure.StringContains(t, v, tc.expected)
			_ = c.Stop("consul-01")
		})
	}
}

func TestCompose_Info(t *testing.T) {
	testCases := []struct {
		name              string
		path              string
		startService      bool
		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
		expectedCheckFunc func(ensure.Fataler, bool, ...interface{})
	}{
		{
			"regular",
			"test/regular/docker-compose.yaml",
			true,
			ensure.Nil,
			ensure.True,
		},
		{
			"serviceNotStarted",
			"test/badFormat/docker-compose.yaml",
			false,
			ensure.NotNil,
			ensure.False,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c, err := NewCompose(tc.path)
			ensure.Nil(t, err)
			ensure.NotNil(t, c)
			if tc.startService {
				ensure.Nil(t, c.Start("consul-01"))
			}
			info, err := c.Info("consul-01")
			tc.expectedErrorFunc(t, err)
			tc.expectedCheckFunc(t, len(info) > 0)
			_ = c.Stop("consul-01")
		})
	}
}

// func TestCompose_Startbackoff(t *testing.T) {
// 	testCases := []struct {
// 		name              string
// 		path              string
// 		startService      bool
// 		backOff           func(*Compose, string) error
// 		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
// 	}{
// 		{
// 			"regular",
// 			"test/regular/docker-compose.yaml",
// 		},
// 	}

// 	for _, tc := range testCases {
// 		t.Run(tc.name, func(t *testing.T) {
// 			c, err := NewCompose(tc.path)
// 			ensure.Nil(t, err)
// 			ensure.NotNil(t, c)

// 		})
// 	}
// }
<commit_msg>test(backoff): erase test as backoff test depends on user implementation<commit_after>package fishfinger

import (
	"testing"

	"github.com/facebookgo/ensure"
)

// -----------------------------------------------------------------------------

func TestCompose_NewCompose(t *testing.T) {
	testCases := []struct {
		name              string
		path              string
		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
	}{
		{"regular", "test/regular/docker-compose.yaml", ensure.Nil},
		{"missingFile", "test/badFormat/missing-file.yaml", ensure.NotNil},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			_, err := NewCompose(tc.path)
			tc.expectedErrorFunc(t, err)
		})
	}
}

func TestCompose_Start(t *testing.T) {
	testCases := []struct {
		name              string
		path              string
		serviceName       string
		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
	}{
		{
			"regular",
			"test/regular/docker-compose.yaml",
			"consul-01",
			ensure.Nil,
		},
		{
			"badFormat",
			"test/badFormat/docker-compose.yaml",
			"consul-01",
			ensure.NotNil,
		},
		{
			"missingService",
			"test/regular/docker-compose.yaml",
			"consulito",
			ensure.NotNil,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c, err := NewCompose(tc.path)
			ensure.Nil(t, err)
			ensure.NotNil(t, c)
			tc.expectedErrorFunc(t, c.Start(tc.serviceName))

			if s, err := c.Status(tc.serviceName); err == nil && s == true {
				ensure.Nil(t, c.Stop(tc.serviceName))
			}
		})
	}
}

func TestCompose_Stop(t *testing.T) {
	testCases := []struct {
		name      string
		path      string
		stopAgain bool
	}{
		{"regular", "test/regular/docker-compose.yaml", false},
		{"alreadyStopped", "test/regular/docker-compose.yaml", true},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c, err := NewCompose(tc.path)
			ensure.Nil(t, err)
			ensure.NotNil(t, c)
			ensure.Nil(t, c.Start("consul-01"))
			ensure.Nil(t, c.Stop("consul-01"))

			if tc.stopAgain == true {
				ensure.Nil(t, c.Stop("consul-01"))
			}
		})
	}
}

func TestCompose_Status(t *testing.T) {
	testCases := []struct {
		name              string
		path              string
		serviceName       string
		activateFunc      func(c *Compose)
		expectedCheckFunc func(ensure.Fataler, bool, ...interface{})
		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
	}{
		{
			"regularUp",
			"test/regular/docker-compose.yaml",
			"consul-01",
			func(c *Compose) { _ = c.Start("consul-01") },
			ensure.True,
			ensure.Nil,
		},
		{
			"regularUpAndDown",
			"test/regular/docker-compose.yaml",
			"consul-01",
			func(c *Compose) {
				_ = c.Start("consul-01")
				_ = c.Stop("consul-01")
			},
			ensure.False,
			ensure.Nil,
		},
		{
			"regularNoUp",
			"test/regular/docker-compose.yaml",
			"consul-01",
			func(c *Compose) { _ = c.Stop("consul-01") },
			ensure.False,
			ensure.Nil,
		},
		{
			"missingService",
			"test/regular/docker-compose.yaml",
			"consulito",
			func(c *Compose) {
				_ = c.Start("consulito")
			},
			ensure.False,
			ensure.NotNil,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c, err := NewCompose(tc.path)
			ensure.Nil(t, err)
			ensure.NotNil(t, c)

			tc.activateFunc(c)
			s, err := c.Status(tc.serviceName)
			tc.expectedCheckFunc(t, s)
			tc.expectedErrorFunc(t, err)
			_ = c.Stop(tc.serviceName)
		})
	}
}

func TestCompose_Port(t *testing.T) {
	testCases := []struct {
		name              string
		path              string
		port              string
		expected          string
		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
	}{
		{
			"regular",
			"test/regular/docker-compose.yaml",
			"8500/tcp",
			"0.0.0.0:5015",
			ensure.Nil,
		},
		{
			"missingPort",
			"test/regular/docker-compose.yaml",
			"5555/tcp",
			"",
			ensure.NotNil,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c, err := NewCompose(tc.path)
			ensure.Nil(t, err)
			ensure.Nil(t, c.Start("consul-01"))

			addr, err := c.Port("consul-01", tc.port)
			tc.expectedErrorFunc(t, err)
			ensure.SameElements(t, addr, tc.expected)
			_ = c.Stop("consul-01")
		})
	}
}

func TestCompose_Env(t *testing.T) {
	testCases := []struct {
		name              string
		path              string
		varName           string
		expected          string
		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
	}{
		{
			"regular",
			"test/regular/docker-compose.yaml",
			"DEBUG",
			"working",
			ensure.Nil,
		},
		{
			"missingVar",
			"test/regular/docker-compose.yaml",
			"MISSING_VAR",
			"",
			ensure.NotNil,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c, err := NewCompose(tc.path)
			ensure.Nil(t, err)
			ensure.Nil(t, c.Start("consul-01"))

			v, err := c.Env("consul-01", tc.varName)
			tc.expectedErrorFunc(t, err)
			ensure.StringContains(t, v, tc.expected)
			_ = c.Stop("consul-01")
		})
	}
}

func TestCompose_Info(t *testing.T) {
	testCases := []struct {
		name              string
		path              string
		startService      bool
		expectedErrorFunc func(ensure.Fataler, interface{}, ...interface{})
		expectedCheckFunc func(ensure.Fataler, bool, ...interface{})
	}{
		{
			"regular",
			"test/regular/docker-compose.yaml",
			true,
			ensure.Nil,
			ensure.True,
		},
		{
			"serviceNotStarted",
			"test/badFormat/docker-compose.yaml",
			false,
			ensure.NotNil,
			ensure.False,
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			c, err := NewCompose(tc.path)
			ensure.Nil(t, err)
			ensure.NotNil(t, c)
			if tc.startService {
				ensure.Nil(t, c.Start("consul-01"))
			}
			info, err := c.Info("consul-01")
			tc.expectedErrorFunc(t, err)
			tc.expectedCheckFunc(t, len(info) > 0)
			_ = c.Stop("consul-01")
		})
	}
}
<|endoftext|>


<commit_before>package logger

import (
	"fmt"
	"os"
	"time"

	"github.com/sirupsen/logrus"
)

// Fields logrus.Fields wrapper
type Fields map[string]interface{}

var (
	logConsole *logrus.Logger
	debug      bool
	console    bool
)

// Init init log system
func Init(d bool, c bool, fn string) {
	debug = d
	console = c
	logConsole = logrus.New()

	// log file name
	t := time.Now()
	fileTime := fmt.Sprintf("%d-%d-%d %d-%d-%d", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
	logFn := fmt.Sprintf("../log/%s_%s.log", fileTime, fn)

	file, err := os.OpenFile(logFn, os.O_CREATE|os.O_WRONLY, 0666)
	if err == nil {
		logrus.SetOutput(file)
	} else {
		Warn("Failed to log to file, using default stderr")
	}

	customFormatter := new(logrus.TextFormatter)
	customFormatter.TimestampFormat = "2006-01-02 15:04:05"
	customFormatter.FullTimestamp = true
	logrus.SetFormatter(customFormatter)
	logConsole.SetFormatter(customFormatter)
}

func Trace(v ...interface{}) {
	if console {
		logConsole.Println(v...)
	}

	if debug {
		logrus.Println(v...)
	}
}

func Info(v ...interface{}) {
	if console {
		logConsole.Info(v...)
	}

	if debug {
		logrus.Info(v...)
	}
}

func Warn(v ...interface{}) {
	if console {
		logConsole.Warn(v...)
	}

	logrus.Warn(v...)
}

func Error(v ...interface{}) {
	if console {
		logConsole.Error(v...)
	}

	logrus.Error(v...)
}

func Fatal(v ...interface{}) {
	if console {
		logConsole.Fatal(v...)
	}

	logrus.Fatal(v...)
}

func Print(v ...interface{}) {
	if console {
		logConsole.Println(v...)
	}

	logrus.Println(v...)
}

func WithFieldsTrace(s string, fields Fields) {
	f := make(logrus.Fields)
	for k, v := range fields {
		f[k] = v
	}

	if console {
		logConsole.WithFields(f).Trace(s)
	}

	logrus.WithFields(f).Trace(s)
}

func WithFieldsDebug(s string, fields Fields) {
	f := make(logrus.Fields)
	for k, v := range fields {
		f[k] = v
	}

	if console {
		logConsole.WithFields(f).Debug(s)
	}

	logrus.WithFields(f).Debug(s)
}

func WithFieldsInfo(s string, fields Fields) {
	f := make(logrus.Fields)
	for k, v := range fields {
		f[k] = v
	}

	if console {
		logConsole.WithFields(f).Info(s)
	}

	logrus.WithFields(f).Info(s)
}

func WithFieldsWarn(s string, fields Fields) {
	f := make(logrus.Fields)
	for k, v := range fields {
		f[k] = v
	}

	if console {
		logConsole.WithFields(f).Warn(s)
	}

	logrus.WithFields(f).Warn(s)
}

func WithFieldsError(s string, fields Fields) {
	f := make(logrus.Fields)
	for k, v := range fields {
		f[k] = v
	}

	if console {
		logConsole.WithFields(f).Error(s)
	}

	logrus.WithFields(f).Error(s)
}
<commit_msg>type logger.Fields alias logrus.Fields<commit_after>package logger

import (
	"fmt"
	"os"
	"time"

	"github.com/sirupsen/logrus"
)

// Fields logrus.Fields wrapper
type Fields = logrus.Fields

var (
	logConsole *logrus.Logger
	debug      bool
	console    bool
)

// Init init log system
func Init(d bool, c bool, fn string) {
	debug = d
	console = c
	logConsole = logrus.New()

	// log file name
	t := time.Now()
	fileTime := fmt.Sprintf("%d-%d-%d %d-%d-%d", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second())
	logFn := fmt.Sprintf("../log/%s_%s.log", fileTime, fn)

	file, err := os.OpenFile(logFn, os.O_CREATE|os.O_WRONLY, 0666)
	if err == nil {
		logrus.SetOutput(file)
	} else {
		Warn("Failed to log to file, using default stderr")
	}

	customFormatter := new(logrus.TextFormatter)
	customFormatter.TimestampFormat = "2006-01-02 15:04:05"
	customFormatter.FullTimestamp = true
	logrus.SetFormatter(customFormatter)
	logConsole.SetFormatter(customFormatter)
}

func Trace(v ...interface{}) {
	if console {
		logConsole.Println(v...)
	}

	if debug {
		logrus.Println(v...)
	}
}

func Info(v ...interface{}) {
	if console {
		logConsole.Info(v...)
	}

	if debug {
		logrus.Info(v...)
	}
}

func Warn(v ...interface{}) {
	if console {
		logConsole.Warn(v...)
	}

	logrus.Warn(v...)
}

func Error(v ...interface{}) {
	if console {
		logConsole.Error(v...)
	}

	logrus.Error(v...)
}

func Fatal(v ...interface{}) {
	if console {
		logConsole.Fatal(v...)
	}

	logrus.Fatal(v...)
}

func Print(v ...interface{}) {
	if console {
		logConsole.Println(v...)
	}

	logrus.Println(v...)
}

func WithFieldsTrace(s string, fields Fields) {
	f := make(logrus.Fields)
	for k, v := range fields {
		f[k] = v
	}

	if console {
		logConsole.WithFields(f).Trace(s)
	}

	logrus.WithFields(f).Trace(s)
}

func WithFieldsDebug(s string, fields Fields) {
	f := make(logrus.Fields)
	for k, v := range fields {
		f[k] = v
	}

	if console {
		logConsole.WithFields(f).Debug(s)
	}

	logrus.WithFields(f).Debug(s)
}

func WithFieldsInfo(s string, fields Fields) {
	f := make(logrus.Fields)
	for k, v := range fields {
		f[k] = v
	}

	if console {
		logConsole.WithFields(f).Info(s)
	}

	logrus.WithFields(f).Info(s)
}

func WithFieldsWarn(s string, fields Fields) {
	f := make(logrus.Fields)
	for k, v := range fields {
		f[k] = v
	}

	if console {
		logConsole.WithFields(f).Warn(s)
	}

	logrus.WithFields(f).Warn(s)
}

func WithFieldsError(s string, fields Fields) {
	f := make(logrus.Fields)
	for k, v := range fields {
		f[k] = v
	}

	if console {
		logConsole.WithFields(f).Error(s)
	}

	logrus.WithFields(f).Error(s)
}
<|endoftext|>


<commit_before>package alc

// #cgo darwin  LDFLAGS: -framework OpenAL
// #cgo freebsd LDFLAGS: -lopenal
//
// #ifdef __APPLE__
// #include <OpenAL/al.h>
// #include <OpenAL/alc.h>
// #else
// #include <AL/al.h>
// #include <AL/alc.h>
// #endif
//
// // free()
// #include <stdlib.h>
import "C"
import "unsafe"

// Device represents an OpenAL device.
type Device uintptr

// OpenDevice opens a device by name.
func OpenDevice(name string) Device {
	cName := C.CString(name)
	defer C.free(unsafe.Pointer(cName))
	return GoDevice(C.alcOpenDevice(cName))
}

// OpenDefaultDevice opens the default device.
func OpenDefaultDevice() Device {
	return GoDevice(C.alcOpenDevice(nil))
}

// Close closes device d.
func (d Device) Close() bool {
	return GoBool(C.alcCloseDevice(d.CDevice()))
}

// GoDevice : C device to Go device.
func GoDevice(cDevice *C.ALCdevice) Device {
	return Device(unsafe.Pointer(cDevice))
}

// CDevice : Go device to C device.
func (d Device) CDevice() *C.ALCdevice {
	return (*C.ALCdevice)(unsafe.Pointer(d))
}
<commit_msg>Fixed conventions<commit_after>package alc

// #cgo darwin  LDFLAGS: -framework OpenAL
// #cgo freebsd LDFLAGS: -lopenal
//
// #ifdef __APPLE__
// #include <OpenAL/al.h>
// #include <OpenAL/alc.h>
// #else
// #include <AL/al.h>
// #include <AL/alc.h>
// #endif
//
// // free()
// #include <stdlib.h>
import "C"
import "unsafe"

// Device represents an OpenAL device.
type Device uintptr

// OpenDevice opens a device by name.
func OpenDevice(deviceName string) Device {
	cDeviceName := C.CString(deviceName)
	defer C.free(unsafe.Pointer(cDeviceName))
	return GoDevice(C.alcOpenDevice(cDeviceName))
}

// OpenDefaultDevice opens the default device.
func OpenDefaultDevice() Device {
	return GoDevice(C.alcOpenDevice(nil))
}

// Close closes device d.
func (d Device) Close() bool {
	return GoBool(C.alcCloseDevice(d.CDevice()))
}

// GoDevice : C device to Go device.
func GoDevice(cDevice *C.ALCdevice) Device {
	return Device(unsafe.Pointer(cDevice))
}

// CDevice : Go device to C device.
func (d Device) CDevice() *C.ALCdevice {
	return (*C.ALCdevice)(unsafe.Pointer(d))
}
<|endoftext|>


<commit_before>package main

import (
	"net/http"

	"github.com/gorilla/mux"

	"github.com/lxc/lxd/lxd/resources"
	"github.com/lxc/lxd/lxd/response"
	storagePools "github.com/lxc/lxd/lxd/storage"
	storageDrivers "github.com/lxc/lxd/lxd/storage/drivers"
	"github.com/lxc/lxd/shared/api"
)

var api10ResourcesCmd = APIEndpoint{
	Path: "resources",

	Get: APIEndpointAction{Handler: api10ResourcesGet, AccessHandler: AllowAuthenticated},
}

var storagePoolResourcesCmd = APIEndpoint{
	Path: "storage-pools/{name}/resources",

	Get: APIEndpointAction{Handler: storagePoolResourcesGet, AccessHandler: AllowAuthenticated},
}

// /1.0/resources
// Get system resources
func api10ResourcesGet(d *Daemon, r *http.Request) response.Response {
	// If a target was specified, forward the request to the relevant node.
	resp := ForwardedResponseIfTargetIsRemote(d, r)
	if resp != nil {
		return resp
	}

	// Get the local resource usage
	res, err := resources.GetResources()
	if err != nil {
		return response.SmartError(err)
	}

	return response.SyncResponse(true, res)
}

// /1.0/storage-pools/{name}/resources
// Get resources for a specific storage pool
func storagePoolResourcesGet(d *Daemon, r *http.Request) response.Response {
	// If a target was specified, forward the request to the relevant node.
	resp := ForwardedResponseIfTargetIsRemote(d, r)
	if resp != nil {
		return resp
	}

	// Get the existing storage pool
	poolName := mux.Vars(r)["name"]
	var res *api.ResourcesStoragePool

	// Check if we can load new storage layer for pool driver type.
	pool, err := storagePools.GetPoolByName(d.State(), poolName)
	if err != storageDrivers.ErrUnknownDriver {
		if err != nil {
			return response.InternalError(err)
		}

		res, err = pool.GetResources()
		if err != nil {
			return response.InternalError(err)
		}
	} else { // Fallback to old storage layer.
		s, err := storagePoolInit(d.State(), poolName)
		if err != nil {
			return response.InternalError(err)
		}

		err = s.StoragePoolCheck()
		if err != nil {
			return response.InternalError(err)
		}

		res, err = s.StoragePoolResources()
		if err != nil {
			return response.InternalError(err)
		}
	}

	return response.SyncResponse(true, res)
}
<commit_msg>lxd/resources: Removes old storage loader<commit_after>package main

import (
	"net/http"

	"github.com/gorilla/mux"

	"github.com/lxc/lxd/lxd/resources"
	"github.com/lxc/lxd/lxd/response"
	storagePools "github.com/lxc/lxd/lxd/storage"
	"github.com/lxc/lxd/shared/api"
)

var api10ResourcesCmd = APIEndpoint{
	Path: "resources",

	Get: APIEndpointAction{Handler: api10ResourcesGet, AccessHandler: AllowAuthenticated},
}

var storagePoolResourcesCmd = APIEndpoint{
	Path: "storage-pools/{name}/resources",

	Get: APIEndpointAction{Handler: storagePoolResourcesGet, AccessHandler: AllowAuthenticated},
}

// /1.0/resources
// Get system resources
func api10ResourcesGet(d *Daemon, r *http.Request) response.Response {
	// If a target was specified, forward the request to the relevant node.
	resp := ForwardedResponseIfTargetIsRemote(d, r)
	if resp != nil {
		return resp
	}

	// Get the local resource usage
	res, err := resources.GetResources()
	if err != nil {
		return response.SmartError(err)
	}

	return response.SyncResponse(true, res)
}

// /1.0/storage-pools/{name}/resources
// Get resources for a specific storage pool
func storagePoolResourcesGet(d *Daemon, r *http.Request) response.Response {
	// If a target was specified, forward the request to the relevant node.
	resp := ForwardedResponseIfTargetIsRemote(d, r)
	if resp != nil {
		return resp
	}

	// Get the existing storage pool
	poolName := mux.Vars(r)["name"]
	var res *api.ResourcesStoragePool

	// Check if we can load new storage layer for pool driver type.
	pool, err := storagePools.GetPoolByName(d.State(), poolName)
	if err != nil {
		return response.InternalError(err)
	}

	res, err = pool.GetResources()
	if err != nil {
		return response.InternalError(err)
	}

	return response.SyncResponse(true, res)
}
<|endoftext|>


<commit_before>package sliceops

import "math"

// Returns the minimum value in the slice and the index of
// the minimum value. If the input slice is empty, zero is returned
// as the minimum value and -1 is returned as the index.
// Use: val,ind := sliceops.Min(slice)
func Min(s []float64) (min float64, ind int) {
	if len(s) == 0 {
		return min, -1 // Ind is -1 to make clear it's not the zeroth index.
	}
	min = s[0]
	ind = 0
	for i, val := range s {
		if val < min {
			min = val
			ind = i
		}
	}
	return min, ind
}

// Returns the maximum value in the slice and the location of
// the maximum value. If the input slice is empty, zero is returned
// as the minimum value and -1 is returned as the index.
// Use: val,ind := sliceops.Max(slice)
func Max(s []float64) (max float64, ind int) {
	if len(s) == 0 {
		return max, -1 // Ind is -1 to make clear it's not the zeroth index.
	}
	max = s[0]
	ind = 0
	for i, val := range s {
		if val > max {
			max = val
			ind = i
		}
	}
	return max, ind
}

// Returns the sum of the elements of the slice
func Sum(s []float64) (sum float64) {
	for _, val := range s {
		sum += val
	}
	return
}

// Returns the product of the elements of the slice
// Returns 1 if the input has length zero
func Prod(s []float64) (prod float64) {
	prod = 1
	for _, val := range s {
		prod *= val
	}
	return prod
}

// Returns true if all of the slices have equal length,
// and false otherwise.
// Special case: Returns true if there are no input slices
func HasEqLen(slices ...[]float64) bool {
	if len(slices) == 0 {
		return true
	}
	l := len(slices[0])
	for i := 1; i < len(slices); i++ {
		if len(slices[i]) != l {
			return false
		}
	}
	return true
}

// Returns false if |s1[i] - s2[i]| > tol for any i.
// Assumes that the slices are of equal length. If this
// is in doubt it should be checked with HasEqLen
func Eq(s1, s2 []float64, tol float64) bool {
	for i, val := range s1 {
		if math.Abs(s2[i]-val) > tol {
			return false
		}
	}
	return true
}

// Finds the cumulative sum of the first i elements in
// s and puts them in place into the ith element of the
// receiver. Assumes receiver is at least as long as s
func CumSum(receiver, s []float64) {
	receiver[0] = s[0]
	for i := 1; i < len(s); i++ {
		receiver[i] = receiver[i-1] + s[i]
	}
}

// Finds the cumulative product of the first i elements in
// s and puts them in place into the ith element of the
// receiver. Assumes receiver is at least as long as s
func CumProd(receiver, s []float64) []float64 {
	if receiver == nil {
		receiver = make([]float64, len(s))
	}
	if len(s) == 0 {
		return receiver[:0]
	}
	receiver[0] = s[0]
	for i := 1; i < len(s); i++ {
		receiver[i] = receiver[i-1] * s[i]
	}
	return receiver
}

// Returns the element-wise sum of the last n slices
// and puts them in place into the first argument.
// For computational efficiency, it is assumed that all of
// the variadic arguments have the same length. If this is
// in doubt, EqLengths can be called. If no slices are input,
// the receiver is unchanged.
func ElemSum(receiver []float64, slices ...[]float64) {
	if len(slices) == 0 {
		return
	}
	for i, val := range slices[0] {
		receiver[i] = val
	}
	for i := 1; i < len(slices); i++ {
		for j, val := range slices[i] {
			receiver[j] += val
		}
	}
	return
}

// Returns the L norm of the slice S.
// Special cases:
// L = math.Inf(1) gives the maximum value
// Does not deal with the Zero norm. See Zero norm instead
func Norm(s []float64, L float64) (norm float64) {
	// Should this complain if L is not positive?
	// Should this be done in log space for better numerical stability?
	//	would be more cost
	//	maybe only if L is high?
	if math.IsInf(L, 1) {
		norm, _ = Max(s)
		return norm
	}
	for _, val := range s {
		norm += L * math.Pow(math.Abs(val), L)
	}
	return math.Pow(norm, 1/L)
}

// Adds a constant to all of the values in s
func AddConst(s []float64, c float64) {
	for i := range s {
		s[i] += c
	}
}

// Multiplies every element in s by a constant
func MulConst(s []float64, c float64) {
	for i := range s {
		s[i] *= c
	}
}

// Returns the log of the sum of the exponentials of the values in s
func LogSumExp(s []float64) (logsumexp float64) {
	// Want to do this in a numerically stable way which avoids
	// overflow and underflow
	// TODO: Add in special case for two values

	// First, find the maximum value in the slice.
	minval, _ := Max(s)
	if math.IsInf(minval, 0) {
		// If it's infinity eitherway, the logsumexp will be infinity as well
		// returning now avoids NaNs
		return minval
	}
	// Subtract off the largest value, so the largest value in
	// the new slice is 0
	AddConst(s, -minval)
	defer AddConst(s, minval) // make sure we add it back on at the end

	// compute the sumexp part
	for _, val := range s {
		logsumexp += math.Exp(val)
	}
	// Take the log and add back on the constant taken out
	logsumexp = math.Log(logsumexp) + minval
	return logsumexp
}

// Returns a set of N equally spaced points between l and u, where N
// is equal to the length of the reciever. The first element of the receiver
// is l, the final element of the receiver is u. Will panic if the receiver has
// length < 2
// TODO: Add in examele code here
func Linspace(receiver []float64, l, u float64) {
	n := len(receiver)
	step := (u - l) / float64(n-1)
	for i := range receiver {
		receiver[i] = l + step*float64(i)
	}
}

// Returns a set of N equally spaced points in log space between l and u, where N
// is equal to the length of the reciever. The first element of the receiver
// is l, the final element of the receiver is u. Will panic if the receiver has
// length < 2. Note that this call will recturn NaNs if l or u are negative, and
// zeros if l or u is zero.
func Logspace(receiver []float64, l, u float64) {
	Linspace(receiver, math.Log(l), math.Log(u))
	for i, val := range receiver {
		receiver[i] = math.Exp(val)
	}
}

// Applies a function returning a boolean to the elements of the slice
// and returns a list of indices for which the value is true
func Find(s []float64, f func(float64) bool) (inds []int) {
	// Not sure what an appropriate capacity is here. Don't want to make
	// it the length of the slice because if the slice is large that is
	// a lot of potentially wasted memory
	inds = make([]int, 0)
	for i, val := range s {
		if f(val) {
			inds = append(inds, i)
		}
	}
	return inds
}
<commit_msg>Changed name from MulConst to Scale<commit_after>package sliceops

import "math"

// Returns the minimum value in the slice and the index of
// the minimum value. If the input slice is empty, zero is returned
// as the minimum value and -1 is returned as the index.
// Use: val,ind := sliceops.Min(slice)
func Min(s []float64) (min float64, ind int) {
	if len(s) == 0 {
		return min, -1 // Ind is -1 to make clear it's not the zeroth index.
	}
	min = s[0]
	ind = 0
	for i, val := range s {
		if val < min {
			min = val
			ind = i
		}
	}
	return min, ind
}

// Returns the maximum value in the slice and the location of
// the maximum value. If the input slice is empty, zero is returned
// as the minimum value and -1 is returned as the index.
// Use: val,ind := sliceops.Max(slice)
func Max(s []float64) (max float64, ind int) {
	if len(s) == 0 {
		return max, -1 // Ind is -1 to make clear it's not the zeroth index.
	}
	max = s[0]
	ind = 0
	for i, val := range s {
		if val > max {
			max = val
			ind = i
		}
	}
	return max, ind
}

// Returns the sum of the elements of the slice
func Sum(s []float64) (sum float64) {
	for _, val := range s {
		sum += val
	}
	return
}

// Returns the product of the elements of the slice
// Returns 1 if the input has length zero
func Prod(s []float64) (prod float64) {
	prod = 1
	for _, val := range s {
		prod *= val
	}
	return prod
}

// Returns true if all of the slices have equal length,
// and false otherwise.
// Special case: Returns true if there are no input slices
func HasEqLen(slices ...[]float64) bool {
	if len(slices) == 0 {
		return true
	}
	l := len(slices[0])
	for i := 1; i < len(slices); i++ {
		if len(slices[i]) != l {
			return false
		}
	}
	return true
}

// Returns false if |s1[i] - s2[i]| > tol for any i.
// Assumes that the slices are of equal length. If this
// is in doubt it should be checked with HasEqLen
func Eq(s1, s2 []float64, tol float64) bool {
	for i, val := range s1 {
		if math.Abs(s2[i]-val) > tol {
			return false
		}
	}
	return true
}

// Finds the cumulative sum of the first i elements in
// s and puts them in place into the ith element of the
// receiver. Assumes receiver is at least as long as s
func CumSum(receiver, s []float64) {
	receiver[0] = s[0]
	for i := 1; i < len(s); i++ {
		receiver[i] = receiver[i-1] + s[i]
	}
}

// Finds the cumulative product of the first i elements in
// s and puts them in place into the ith element of the
// receiver. Assumes receiver is at least as long as s
func CumProd(receiver, s []float64) []float64 {
	if receiver == nil {
		receiver = make([]float64, len(s))
	}
	if len(s) == 0 {
		return receiver[:0]
	}
	receiver[0] = s[0]
	for i := 1; i < len(s); i++ {
		receiver[i] = receiver[i-1] * s[i]
	}
	return receiver
}

// Returns the element-wise sum of the last n slices
// and puts them in place into the first argument.
// For computational efficiency, it is assumed that all of
// the variadic arguments have the same length. If this is
// in doubt, EqLengths can be called. If no slices are input,
// the receiver is unchanged.
func ElemSum(receiver []float64, slices ...[]float64) {
	if len(slices) == 0 {
		return
	}
	for i, val := range slices[0] {
		receiver[i] = val
	}
	for i := 1; i < len(slices); i++ {
		for j, val := range slices[i] {
			receiver[j] += val
		}
	}
	return
}

// Returns the L norm of the slice S.
// Special cases:
// L = math.Inf(1) gives the maximum value
// Does not deal with the Zero norm. See Zero norm instead
func Norm(s []float64, L float64) (norm float64) {
	// Should this complain if L is not positive?
	// Should this be done in log space for better numerical stability?
	//	would be more cost
	//	maybe only if L is high?
	if math.IsInf(L, 1) {
		norm, _ = Max(s)
		return norm
	}
	for _, val := range s {
		norm += L * math.Pow(math.Abs(val), L)
	}
	return math.Pow(norm, 1/L)
}

// Adds a constant to all of the values in s
func AddConst(s []float64, c float64) {
	for i := range s {
		s[i] += c
	}
}

// Multiplies every element in s by a constant in place
func Scale(s []float64, c float64) {
	for i := range s {
		s[i] *= c
	}
}

// Returns the log of the sum of the exponentials of the values in s
func LogSumExp(s []float64) (logsumexp float64) {
	// Want to do this in a numerically stable way which avoids
	// overflow and underflow
	// TODO: Add in special case for two values

	// First, find the maximum value in the slice.
	minval, _ := Max(s)
	if math.IsInf(minval, 0) {
		// If it's infinity eitherway, the logsumexp will be infinity as well
		// returning now avoids NaNs
		return minval
	}
	// Subtract off the largest value, so the largest value in
	// the new slice is 0
	AddConst(s, -minval)
	defer AddConst(s, minval) // make sure we add it back on at the end

	// compute the sumexp part
	for _, val := range s {
		logsumexp += math.Exp(val)
	}
	// Take the log and add back on the constant taken out
	logsumexp = math.Log(logsumexp) + minval
	return logsumexp
}

// Returns a set of N equally spaced points between l and u, where N
// is equal to the length of the reciever. The first element of the receiver
// is l, the final element of the receiver is u. Will panic if the receiver has
// length < 2
// TODO: Add in examele code here
func Linspace(receiver []float64, l, u float64) {
	n := len(receiver)
	step := (u - l) / float64(n-1)
	for i := range receiver {
		receiver[i] = l + step*float64(i)
	}
}

// Returns a set of N equally spaced points in log space between l and u, where N
// is equal to the length of the reciever. The first element of the receiver
// is l, the final element of the receiver is u. Will panic if the receiver has
// length < 2. Note that this call will recturn NaNs if l or u are negative, and
// zeros if l or u is zero.
func Logspace(receiver []float64, l, u float64) {
	Linspace(receiver, math.Log(l), math.Log(u))
	for i, val := range receiver {
		receiver[i] = math.Exp(val)
	}
}

// Applies a function returning a boolean to the elements of the slice
// and returns a list of indices for which the value is true
func Find(s []float64, f func(float64) bool) (inds []int) {
	// Not sure what an appropriate capacity is here. Don't want to make
	// it the length of the slice because if the slice is large that is
	// a lot of potentially wasted memory
	inds = make([]int, 0)
	for i, val := range s {
		if f(val) {
			inds = append(inds, i)
		}
	}
	return inds
}

// TODO: Add something like find but returns a float slice? Is?
<|endoftext|>


<commit_before>// Copyright 2014 Simon Zimmermann. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package log

import (
	"strconv"
	"sync/atomic"
)

const (
	LevelFatal Level = iota
	LevelError
	LevelInfo
	LevelDebug
)

// Level is treated as a sync/atomic int32.

// Level specifies a level of verbosity for V logs. *Level implements
// flag.Value; the -v flag is of type Level and should be modified
// only through the flag.Value interface.
type Level int32

// get returns the value of the Level.
func (l *Level) get() Level {
	return Level(atomic.LoadInt32((*int32)(l)))
}

// set sets the value of the Level.
func (l *Level) set(val Level) {
	atomic.StoreInt32((*int32)(l), int32(val))
}

// String is part of the flag.Value interface.
func (l *Level) String() string {
	return strconv.FormatInt(int64(*l), 10)
}

// Get is part of the flag.Value interface.
func (l *Level) Get() interface{} {
	return *l
}

// Set is part of the flag.Value interface.
func (l *Level) Set(value string) error {
	v, err := strconv.Atoi(value)
	if err != nil {
		return err
	}
	l.set(Level(v))
	return nil
}
<commit_msg>set loglevel<commit_after>// Copyright 2014 Simon Zimmermann. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package log

import (
	"strconv"
	"sync/atomic"
)

const (
	LevelFatal Level = iota
	LevelError
	LevelInfo
	LevelDebug
)

// Level is treated as a sync/atomic int32.

// Level specifies a level of verbosity for V logs. *Level implements
// flag.Value; the -v flag is of type Level and should be modified
// only through the flag.Value interface.
type Level int32

// get returns the value of the Level.
func (l *Level) get() Level {
	return Level(atomic.LoadInt32((*int32)(l)))
}

// set sets the value of the Level.
func (l *Level) set(val Level) {
	atomic.StoreInt32((*int32)(l), int32(val))
}

// String is part of the flag.Value interface.
func (l *Level) String() string {
	return strconv.FormatInt(int64(*l), 10)
}

// Get is part of the flag.Value interface.
func (l *Level) Get() interface{} {
	return *l
}

// Set is part of the flag.Value interface.
func (l *Level) Set(value string) error {
	v, err := strconv.Atoi(value)
	if err != nil {
		return err
	}
	l.set(Level(v))
	return nil
}

func (l *Level) SetString(value string) error {
	switch value {
	case "fatal":
		return l.Set("0")
	case "error":
		return l.Set("1")
	case "info":
		return l.Set("2")
	case "debug":
		return l.Set("3")
	default:
		return l.Set("1")
	}
}
<|endoftext|>


<commit_before>// This file definse the logOuter interface and several types of logOuter.
//
// emptyOuter = logOuter where both Out and Outf are noops
// lineOuter = logOuter where a newline is inserted after every call to
//			   Out and Outf
// fatalLineOuter = logOuter that logs message with inserted newline then
//					exits with call to os.EXIT(1)

package golog

import (
	"bytes"
	"fmt"
	"io"
	"strconv"
	"time"
)

type LogLocation struct {
	Package  string
	Function string
	File     string
	Line     int
}

type LogMessage struct {
	Level       int
	Nanoseconds int64
	Message     string
	Location    *LogLocation
}

type LogOuter interface {
	Output(*LogMessage)
}

func renderLogLocation(buf *bytes.Buffer, l *LogLocation) {
	packPresent := len(l.Package) > 0
	funcPresent := len(l.Function) > 0
	filePresent := len(l.Function) > 0
	linePresent := l.Line > 0

	// TODO This logic is terrifying.
	if packPresent {
		buf.WriteString(l.Package)
	}
	if funcPresent {
		if packPresent {
			buf.WriteString(".")
		}
		buf.WriteString(l.Function)
	}
	if (packPresent || funcPresent) && (filePresent || linePresent) {
		buf.WriteString("/")
	}
	if filePresent {
		buf.WriteString(l.File)
	}
	if linePresent {
		if filePresent {
			buf.WriteString(":")
		}
		buf.WriteString(strconv.Itoa(l.Line))
	}
}

func formatLogMessage(m *LogMessage, insertNewline bool) string {
	var buf bytes.Buffer
	buf.WriteString(fmt.Sprintf("L%d", m.Level))
	t := time.NanosecondsToLocalTime(m.Nanoseconds)
	buf.WriteString(t.Format(" 15:04:05.000000"))
	if m.Location != nil {
		buf.WriteString(" ")
		renderLogLocation(&buf, m.Location)
	}
	buf.WriteString("] ")
	buf.WriteString(m.Message)
	if insertNewline {
		buf.WriteString("\n")
	}
	return buf.String()
}

type writerLogOuter struct {
	// TODO Insert mutex?
	io.Writer
}

func (f *writerLogOuter) Output(m *LogMessage) {
	// TODO Grab mutex?
	// Make sure to insert a newline.
	f.Write([]byte(formatLogMessage(m, true)))
}

func NewWriterLogOuter(f io.WriteCloser) LogOuter {
	return &writerLogOuter{f}
}

// We want to allow an abitrary testing framework.
type TestController interface {
	// We will assume that testers insert newlines in manner similar to
	// the FEATURE of testing.T where it inserts extra newlines. >.<
	Log(...interface{})
	FailNow()
}

type testLogOuter struct {
	TestController
}

func (t *testLogOuter) Output(m *LogMessage) {
	// Don't insert an additional log message since the tester inserts them
	// for us.
	t.Log(formatLogMessage(m, false))
}

func NewTestLogOuter(t TestController) LogOuter {
	return &testLogOuter{t}
}
<commit_msg>Add FileLogOuter<commit_after>// This file definse the logOuter interface and several types of logOuter.
//
// emptyOuter = logOuter where both Out and Outf are noops
// lineOuter = logOuter where a newline is inserted after every call to
//			   Out and Outf
// fatalLineOuter = logOuter that logs message with inserted newline then
//					exits with call to os.EXIT(1)

package golog

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"strconv"
	"time"
)

type LogLocation struct {
	Package  string
	Function string
	File     string
	Line     int
}

type LogMessage struct {
	Level       int
	Nanoseconds int64
	Message     string
	Location    *LogLocation
}

type LogOuter interface {
	Output(*LogMessage)
}

func renderLogLocation(buf *bytes.Buffer, l *LogLocation) {
	packPresent := len(l.Package) > 0
	funcPresent := len(l.Function) > 0
	filePresent := len(l.Function) > 0
	linePresent := l.Line > 0

	// TODO This logic is terrifying.
	if packPresent {
		buf.WriteString(l.Package)
	}
	if funcPresent {
		if packPresent {
			buf.WriteString(".")
		}
		buf.WriteString(l.Function)
	}
	if (packPresent || funcPresent) && (filePresent || linePresent) {
		buf.WriteString("/")
	}
	if filePresent {
		buf.WriteString(l.File)
	}
	if linePresent {
		if filePresent {
			buf.WriteString(":")
		}
		buf.WriteString(strconv.Itoa(l.Line))
	}
}

func formatLogMessage(m *LogMessage, insertNewline bool) string {
	var buf bytes.Buffer
	buf.WriteString(fmt.Sprintf("L%d", m.Level))
	t := time.NanosecondsToLocalTime(m.Nanoseconds)
	buf.WriteString(t.Format(" 15:04:05.000000"))
	if m.Location != nil {
		buf.WriteString(" ")
		renderLogLocation(&buf, m.Location)
	}
	buf.WriteString("] ")
	buf.WriteString(m.Message)
	if insertNewline {
		buf.WriteString("\n")
	}
	return buf.String()
}

type writerLogOuter struct {
	// TODO Insert mutex?
	io.Writer
}

func (f *writerLogOuter) Output(m *LogMessage) {
	// TODO Grab mutex?
	// Make sure to insert a newline.
	f.Write([]byte(formatLogMessage(m, true)))
}

func NewWriterLogOuter(f io.WriteCloser) LogOuter {
	return &writerLogOuter{f}
}

func NewFileLogOuter(filename string) (LogOuter, os.Error) {
	if file, err := os.Create(filename); err != nil {
		return nil, err
	} else {
		return NewWriterLogOuter(file), nil
	}

	panic("Code never reaches here, this mollifies the compiler.")
}

// We want to allow an abitrary testing framework.
type TestController interface {
	// We will assume that testers insert newlines in manner similar to
	// the FEATURE of testing.T where it inserts extra newlines. >.<
	Log(...interface{})
	FailNow()
}

type testLogOuter struct {
	TestController
}

func (t *testLogOuter) Output(m *LogMessage) {
	// Don't insert an additional log message since the tester inserts them
	// for us.
	t.Log(formatLogMessage(m, false))
}

func NewTestLogOuter(t TestController) LogOuter {
	return &testLogOuter{t}
}
<|endoftext|>


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

package cmd

import (
	"log"
	"os"

	"fmt"

	"io"
	"strings"

	"github.com/mitchellh/go-homedir"
	"github.com/spf13/cobra"
	"io/ioutil"
)

var (

	// Home is the package variable to store the location of the config files.
	Home string

	// sites_php_template_data is the data for sites.php file.
	// it was taken from the templates folder and serves as a backup
	// when that file isn't available (not a go get install).
	sites_php_template_data = `
<?php

/**
 * @file
 * Configuration file for Drupal's multi-site directory aliasing feature.
 */

 $sites['default'] = '{{ .Name }}';
 $sites['{{ .Alias }}'] = '{{ .Name }}';

?>
`

	// drush_alias_template is the data for drush alias file.
	// it was taken from the templates folder and serves as a backup
	// when that file isn't available (not a go get install).
	drush_alias_template = `
<?php
	$aliases['{{ .Alias }}'] = array(
		'root' => '{{ .Root }}',
		'uri' => '{{ .Domain }}',
		'path-aliases' => array(
			'%files' => 'sites/{{ .Name }}/files',
			'%private' => 'sites/{{ .Name }}/private',
		),
	);
?>
`
	// vhost_template_data is the data for an nginx virtualhost config.
	// nginx is the default configured webserver, so other web server
	// templates will need to be added/changed as required.
	// it was taken from the templates folder and serves as a backup
	// when that file isn't available (not a go get install).
	vhost_template_data = `
server {
    listen 80;

    server_name {{ .Domain }}
    error_log /var/log/nginx/error.log info;
    root {{ .Root }};
    index index.php index.html index.htm;

    location / {
        # Don't touch PHP for static content.
        try_files $uri @rewrite;
    }

    # Don't allow direct access to PHP files in the vendor directory.
    location ~ /vendor/.*\.php$ {
        deny all;
        return 404;
    }

    # Use fastcgi for all php files.
    location ~ \.php$ {
        # Secure *.php files.
        try_files $uri = 404;
        include /etc/nginx/fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_index index.php;
        # fastcgi_pass unix:/var/run/php/php5.6-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_read_timeout 120;
    }

    location @rewrite {
        # For D7 and above:
        rewrite ^ /index.php;

        # For Drupal 6 and below:
        #rewrite ^/(.*)$ /index.php?q=$1;
    }

    location ~ ^/sites/.*/files/styles/ {
        try_files $uri @rewrite;
    }

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location ~ (^|/)\. {
        return 403;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }

    gzip on;
    gzip_proxied any;
    gzip_static on;
    gzip_http_version 1.0;
    gzip_disable "MSIE [1-6]\.";
    gzip_vary on;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/xml+rss
        application/xhtml+xml
        application/x-font-ttf
        application/x-font-opentype
        image/svg+xml
        image/x-icon;
    gzip_buffers 16 8k;
    gzip_min_length 512;
}
`

	// config_yml_template_data is the data for sites.php file.
	// it was taken from the templates folder and serves as a backup
	// when that file isn't available (not a go get install).
	config_yml_template_data = `
---

db_user: root
db_pass: root
db_host: localhost
db_port: 3306

webserver: nginx
alias_template: $HOME/alias.tmpl
sites_php_template: $HOME/sites.php.tmpl
virtualhost_template: $HOME/vhost.tmpl

virtualhost_path: /etc/nginx/sites-enabled/
`
)

func WriteStringToFile(filepath, s string) error {
	fo, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer fo.Close()

	_, err = io.Copy(fo, strings.NewReader(s))
	if err != nil {
		return err
	}

	return nil
}

// syncCmd represents the backup command
var initCmd = &cobra.Command{
	Use:   "init",
	Short: "Initialise a set of templates in the provided destination path",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {

		home, err := homedir.Dir()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		} else {
			Home = home
		}

		// Get the current working directory.
		dir, err := os.Getwd()
		if err != nil {
			log.Fatal(err)
		}

		var r string
		if global {
			r = strings.Join([]string{Home, "drubuild", ""}, string(os.PathSeparator))
		} else {
			r = strings.Join([]string{dir, "drubuild", ""}, string(os.PathSeparator))
			m := strings.Join([]string{Home, "drubuild", ""}, string(os.PathSeparator))

			// Alias template
			{
				c, d := ioutil.ReadFile(m + "alias.tmpl")
				if d != nil {
					panic("could not read alias template, initialise and try again.")
				}
				drush_alias_template = string(c)
			}
			// Sites.php template
			{
				c, d := ioutil.ReadFile(m + "sites.php.tmpl")
				if d != nil {
					panic("could not read sites template, initialise and try again.")
				}
				sites_php_template_data = string(c)
			}
			// Vhost template
			{
				c, d := ioutil.ReadFile(m + "vhost.tmpl")
				if d != nil {
					panic("could not read vhost template, initialise and try again.")
				}
				vhost_template_data = string(c)
			}
		}

		if _, s := os.Stat(r); s != nil {
			e := os.Mkdir(r, 0755)
			if e != nil {
				log.Fatalf("error in creating directory %v\n%v", r, e)
			}
		}

		config_yml_template_data = strings.Replace(config_yml_template_data, "$HOME", r, -1)
		config_yml_template_data = strings.Replace(config_yml_template_data, "//", string(os.PathSeparator), -1)

		if global {
			log.Printf("Templating %vconfig.yml from defaults.", r)
			WriteStringToFile(r+"config.yml", config_yml_template_data)
			log.Printf("Templating %vsites.php.tmpl from defaults.", r)
			WriteStringToFile(r+"sites.php.tmpl", sites_php_template_data)
			log.Printf("Templating %valias.tmpl from defaults.", r)
			WriteStringToFile(r+"alias.tmpl", drush_alias_template)
			log.Printf("Templating %vvhost.tmpl from defaults.", r)
			WriteStringToFile(r+"vhost.tmpl", vhost_template_data)
		} else {
			rn := strings.Join([]string{Home, "drubuild", ""}, string(os.PathSeparator))
			log.Printf("Templating %vconfig.yml from defaults.", r)
			WriteStringToFile(r+"config.yml", config_yml_template_data)
			log.Printf("Replacing %vsites.php.tmpl with %v.", r, rn+"sites.php.tmpl")
			WriteStringToFile(r+"sites.php.tmpl", sites_php_template_data)
			log.Printf("Replacing %valias.tmpl with %v.", r, rn+"alias.tmpl")
			WriteStringToFile(r+"alias.tmpl", drush_alias_template)
			log.Printf("Replacing %vvhost.tmpl with %v.", r, rn+"vhost.tmpl")
			WriteStringToFile(r+"vhost.tmpl", vhost_template_data)
		}
	},
}

func init() {
	RootCmd.AddCommand(initCmd)
	initCmd.Flags().BoolVarP(&global, "global", "g", false, "Establish global initialisation, instead of localized ($PWD).")
}
<commit_msg>Ensure default configs are used for local configs, when global configs are unavailable.<commit_after>// Copyright © 2017 Karl Hepworth <Karl.Hepworth@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
	"log"
	"os"

	"fmt"

	"io"
	"strings"

	"github.com/mitchellh/go-homedir"
	"github.com/spf13/cobra"
	"io/ioutil"
)

var (

	// Home is the package variable to store the location of the config files.
	Home string

	// sites_php_template_data is the data for sites.php file.
	// it was taken from the templates folder and serves as a backup
	// when that file isn't available (not a go get install).
	sites_php_template_data = `
<?php

/**
 * @file
 * Configuration file for Drupal's multi-site directory aliasing feature.
 */

 $sites['default'] = '{{ .Name }}';
 $sites['{{ .Alias }}'] = '{{ .Name }}';

?>
`

	// drush_alias_template is the data for drush alias file.
	// it was taken from the templates folder and serves as a backup
	// when that file isn't available (not a go get install).
	drush_alias_template = `
<?php
	$aliases['{{ .Alias }}'] = array(
		'root' => '{{ .Root }}',
		'uri' => '{{ .Domain }}',
		'path-aliases' => array(
			'%files' => 'sites/{{ .Name }}/files',
			'%private' => 'sites/{{ .Name }}/private',
		),
	);
?>
`
	// vhost_template_data is the data for an nginx virtualhost config.
	// nginx is the default configured webserver, so other web server
	// templates will need to be added/changed as required.
	// it was taken from the templates folder and serves as a backup
	// when that file isn't available (not a go get install).
	vhost_template_data = `
server {
    listen 80;

    server_name {{ .Domain }}
    error_log /var/log/nginx/error.log info;
    root {{ .Root }};
    index index.php index.html index.htm;

    location / {
        # Don't touch PHP for static content.
        try_files $uri @rewrite;
    }

    # Don't allow direct access to PHP files in the vendor directory.
    location ~ /vendor/.*\.php$ {
        deny all;
        return 404;
    }

    # Use fastcgi for all php files.
    location ~ \.php$ {
        # Secure *.php files.
        try_files $uri = 404;
        include /etc/nginx/fastcgi_params;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_index index.php;
        # fastcgi_pass unix:/var/run/php/php5.6-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_read_timeout 120;
    }

    location @rewrite {
        # For D7 and above:
        rewrite ^ /index.php;

        # For Drupal 6 and below:
        #rewrite ^/(.*)$ /index.php?q=$1;
    }

    location ~ ^/sites/.*/files/styles/ {
        try_files $uri @rewrite;
    }

    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }

    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    location ~ (^|/)\. {
        return 403;
    }

    location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
        expires max;
        log_not_found off;
    }

    gzip on;
    gzip_proxied any;
    gzip_static on;
    gzip_http_version 1.0;
    gzip_disable "MSIE [1-6]\.";
    gzip_vary on;
    gzip_comp_level 6;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/xml+rss
        application/xhtml+xml
        application/x-font-ttf
        application/x-font-opentype
        image/svg+xml
        image/x-icon;
    gzip_buffers 16 8k;
    gzip_min_length 512;
}
`

	// config_yml_template_data is the data for sites.php file.
	// it was taken from the templates folder and serves as a backup
	// when that file isn't available (not a go get install).
	config_yml_template_data = `
---

db_user: root
db_pass: root
db_host: localhost
db_port: 3306

webserver: nginx
alias_template: $HOME/alias.tmpl
sites_php_template: $HOME/sites.php.tmpl
virtualhost_template: $HOME/vhost.tmpl

virtualhost_path: /etc/nginx/sites-enabled/
`
)

func WriteStringToFile(filepath, s string) error {
	fo, err := os.Create(filepath)
	if err != nil {
		return err
	}
	defer fo.Close()

	_, err = io.Copy(fo, strings.NewReader(s))
	if err != nil {
		return err
	}

	return nil
}

// syncCmd represents the backup command
var initCmd = &cobra.Command{
	Use:   "init",
	Short: "Initialise a set of templates in the provided destination path",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {

		home, err := homedir.Dir()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		} else {
			Home = home
		}

		// Get the current working directory.
		dir, err := os.Getwd()
		if err != nil {
			log.Fatal(err)
		}

		var r string
		if global {
			r = strings.Join([]string{Home, "drubuild", ""}, string(os.PathSeparator))
		} else {
			r = strings.Join([]string{dir, "drubuild", ""}, string(os.PathSeparator))
			m := strings.Join([]string{Home, "drubuild", ""}, string(os.PathSeparator))

			// Alias template
			{
				c, d := ioutil.ReadFile(m + "alias.tmpl")
				if d != nil {
					fmt.Println("could not read alias template, using defaults.")
				} else {
					drush_alias_template = string(c)
				}
			}
			// Sites.php template
			{
				c, d := ioutil.ReadFile(m + "sites.php.tmpl")
				if d != nil {
					fmt.Println("could not read sites template, using defaults.")
				} else {
					sites_php_template_data = string(c)
				}
			}
			// Vhost template
			{
				c, d := ioutil.ReadFile(m + "vhost.tmpl")
				if d != nil {
					fmt.Println("could not read vhost template, using defaults.")
				} else {
					vhost_template_data = string(c)
				}
			}
		}

		if _, s := os.Stat(r); s != nil {
			e := os.Mkdir(r, 0755)
			if e != nil {
				log.Fatalf("error in creating directory %v\n%v", r, e)
			}
		}

		config_yml_template_data = strings.Replace(config_yml_template_data, "$HOME", r, -1)
		config_yml_template_data = strings.Replace(config_yml_template_data, "//", string(os.PathSeparator), -1)

		if global {
			log.Printf("Templating %vconfig.yml from defaults.", r)
			WriteStringToFile(r+"config.yml", config_yml_template_data)
			log.Printf("Templating %vsites.php.tmpl from defaults.", r)
			WriteStringToFile(r+"sites.php.tmpl", sites_php_template_data)
			log.Printf("Templating %valias.tmpl from defaults.", r)
			WriteStringToFile(r+"alias.tmpl", drush_alias_template)
			log.Printf("Templating %vvhost.tmpl from defaults.", r)
			WriteStringToFile(r+"vhost.tmpl", vhost_template_data)
		} else {
			rn := strings.Join([]string{Home, "drubuild", ""}, string(os.PathSeparator))
			if _, s := os.Stat(rn); s == nil {
				log.Printf("Templating %vconfig.yml from defaults.", r)
				WriteStringToFile(r+"config.yml", config_yml_template_data)
				log.Printf("Replacing %vsites.php.tmpl with %v.", r, rn+"sites.php.tmpl")
				WriteStringToFile(r+"sites.php.tmpl", sites_php_template_data)
				log.Printf("Replacing %valias.tmpl with %v.", r, rn+"alias.tmpl")
				WriteStringToFile(r+"alias.tmpl", drush_alias_template)
				log.Printf("Replacing %vvhost.tmpl with %v.", r, rn+"vhost.tmpl")
				WriteStringToFile(r+"vhost.tmpl", vhost_template_data)
			} else {
				log.Printf("Templating %vconfig.yml from defaults.", r)
				WriteStringToFile(r+"config.yml", config_yml_template_data)
				log.Printf("Replacing %vsites.php.tmpl with defaults.", r)
				WriteStringToFile(r+"sites.php.tmpl", sites_php_template_data)
				log.Printf("Replacing %valias.tmpl with defaults.", r)
				WriteStringToFile(r+"alias.tmpl", drush_alias_template)
				log.Printf("Replacing %vvhost.tmpl with defaults.", r)
				WriteStringToFile(r+"vhost.tmpl", vhost_template_data)
			}
		}
	},
}

func init() {
	RootCmd.AddCommand(initCmd)
	initCmd.Flags().BoolVarP(&global, "global", "g", false, "Establish global initialisation, instead of localized ($PWD).")
}
<|endoftext|>


<commit_before>// Package logentrus acts as a Logentries (https://logentries.com) hook
// for Logrus (https://github.com/Sirupsen/logrus)
package logentrus

import (
	"crypto/tls"
	"fmt"
	"net"
	"os"
	"time"

	"github.com/Sirupsen/logrus"
)

// Hook used to send logs to logentries
type Hook struct {
	levels    []logrus.Level
	token     string
	formatter *logrus.JSONFormatter
	tlsConfig *tls.Config
	conn      net.Conn
}

const (
	host       = "data.logentries.com"
	port       = 443
	retryCount = 3
)

// New creates and returns a new hook for use in Logrus
func New(token, timestampFormat string, priority logrus.Level, config *tls.Config) (hook *Hook, err error) {
	if token == "" {
		err = fmt.Errorf("Unable to create new LogentriesHook since a Token is required")
	} else {
		hook = &Hook{
			levels:    logrus.AllLevels[:priority+1], // Include all levels at or within the provided priority
			token:     token,
			tlsConfig: config,
			formatter: &logrus.JSONFormatter{
				TimestampFormat: timestampFormat,
			},
		}

		err = hook.dial()
	}
	return
}

// Fire formats and sends JSON entry to Logentries service
func (hook *Hook) Fire(entry *logrus.Entry) (err error) {
	line, err := hook.format(entry)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to read entry | err: %v | entry: %+v\n", err, entry)
		return err
	}

	if err = hook.write(line); err != nil { // First write attempt
		for i := 0; i < retryCount; i++ {
			time.Sleep(time.Second) // Rest 1 second between retries
			fmt.Fprintf(os.Stderr, "WARNING: Trouble writing to conn; retrying %d of %d | err: %v\n", i, retryCount, err)
			if dialErr := hook.dial(); dialErr != nil { // Problem with write, so dial new connection and retry if possible
				fmt.Fprintf(os.Stderr, "ERROR: Unable to dial new connection | dialErr: %v\n", dialErr)
				return err
			}
			if err = hook.write(line); err == nil { // Retry write
				break
			}
		}
	}

	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: Unable to write to conn | err: %v | line: %s\n", err, line)
	}

	return
}

func (hook *Hook) dial() (err error) {
	hook.conn, err = tls.Dial("tcp", fmt.Sprintf("%s:%d", host, port), hook.tlsConfig)
	return
}

func (hook Hook) write(line string) (err error) {
	_, err = hook.conn.Write([]byte(hook.token + line))
	return
}

func (hook Hook) format(entry *logrus.Entry) (string, error) {
	serialized, err := hook.formatter.Format(entry)
	if err != nil {
		return "", err
	}
	str := string(serialized)
	return str, nil
}

// Levels returns the log levels supported by this hook
func (hook *Hook) Levels() []logrus.Level {
	return hook.levels
}
<commit_msg>Update Fire to close and output error (testing)<commit_after>// Package logentrus acts as a Logentries (https://logentries.com) hook
// for Logrus (https://github.com/Sirupsen/logrus)
package logentrus

import (
	"crypto/tls"
	"fmt"
	"net"
	"os"
	"time"

	"github.com/Sirupsen/logrus"
)

// Hook used to send logs to logentries
type Hook struct {
	levels    []logrus.Level
	token     string
	formatter *logrus.JSONFormatter
	tlsConfig *tls.Config
	conn      net.Conn
}

const (
	host       = "data.logentries.com"
	port       = 443
	retryCount = 3
)

// New creates and returns a new hook for use in Logrus
func New(token, timestampFormat string, priority logrus.Level, config *tls.Config) (hook *Hook, err error) {
	if token == "" {
		err = fmt.Errorf("Unable to create new LogentriesHook since a Token is required")
	} else {
		hook = &Hook{
			levels:    logrus.AllLevels[:priority+1], // Include all levels at or within the provided priority
			token:     token,
			tlsConfig: config,
			formatter: &logrus.JSONFormatter{
				TimestampFormat: timestampFormat,
			},
		}

		err = hook.dial()
	}
	return
}

// Fire formats and sends JSON entry to Logentries service
func (hook *Hook) Fire(entry *logrus.Entry) (err error) {
	line, err := hook.format(entry)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to read entry | err: %v | entry: %+v\n", err, entry)
		return err
	}

	if err = hook.write(line); err != nil { // First write attempt
		for i := 0; i < retryCount; i++ {
			time.Sleep(time.Second) // Rest 1 second between retries
			fmt.Fprintf(os.Stderr, "WARNING: Trouble writing to conn; retrying %d of %d | err: %v\n", i, retryCount, err)
			fmt.Fprintf(os.Stderr, ">>> hook.conn.Close() err: %v\n", hook.conn.Close())
			if dialErr := hook.dial(); dialErr != nil { // Problem with write, so dial new connection and retry if possible
				fmt.Fprintf(os.Stderr, "ERROR: Unable to dial new connection | dialErr: %v\n", dialErr)
				return err
			}
			if err = hook.write(line); err == nil { // Retry write
				break
			}
		}
	}

	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: Unable to write to conn | err: %v | line: %s\n", err, line)
	}

	return
}

func (hook *Hook) dial() (err error) {
	hook.conn, err = tls.Dial("tcp", fmt.Sprintf("%s:%d", host, port), hook.tlsConfig)
	return
}

func (hook Hook) write(line string) (err error) {
	_, err = hook.conn.Write([]byte(hook.token + line))
	return
}

func (hook Hook) format(entry *logrus.Entry) (string, error) {
	serialized, err := hook.formatter.Format(entry)
	if err != nil {
		return "", err
	}
	str := string(serialized)
	return str, nil
}

// Levels returns the log levels supported by this hook
func (hook *Hook) Levels() []logrus.Level {
	return hook.levels
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"time"

	"github.com/toomore/gogrs/twse"
	"github.com/toomore/gogrs/utils"
)

var stock = twse.NewTWSE("2329", time.Date(2015, 3, 20, 0, 0, 0, 0, time.Local))

// ShowAll is lazy to show all XD.
func ShowAll(stock *twse.Data) {
	fmt.Println(stock.RawData)
	fmt.Println(stock.MA(6))
	fmt.Println(stock.MAV(6))
	fmt.Println(stock.GetPriceList())
	fmt.Println(utils.ThanPastFloat64(stock.GetPriceList(), 3, true))
	fmt.Println(utils.ThanPastFloat64(stock.GetPriceList(), 3, false))
	fmt.Println(stock.GetVolumeList())
	fmt.Println(utils.ThanPastUint64(stock.GetVolumeList(), 3, true))
	fmt.Println(utils.ThanPastUint64(stock.GetVolumeList(), 3, false))
	fmt.Println(stock.GetRangeList())
	fmt.Println(stock.IsRed())
}

func main() {
	stock.Get()
	ShowAll(stock)
	fmt.Println("-----------------------------")
	stock.PlusData()
	ShowAll(stock)
}
<commit_msg>Add IsOpen into main.<commit_after>package main

import (
	"fmt"
	"time"

	"github.com/toomore/gogrs/tradingdays"
	"github.com/toomore/gogrs/twse"
	"github.com/toomore/gogrs/utils"
)

var stock = twse.NewTWSE("2329", time.Date(2015, 3, 20, 0, 0, 0, 0, time.Local))

// ShowAll is lazy to show all XD.
func ShowAll(stock *twse.Data) {
	fmt.Println(stock.RawData)
	fmt.Println(stock.MA(6))
	fmt.Println(stock.MAV(6))
	fmt.Println(stock.GetPriceList())
	fmt.Println(utils.ThanPastFloat64(stock.GetPriceList(), 3, true))
	fmt.Println(utils.ThanPastFloat64(stock.GetPriceList(), 3, false))
	fmt.Println(stock.GetVolumeList())
	fmt.Println(utils.ThanPastUint64(stock.GetVolumeList(), 3, true))
	fmt.Println(utils.ThanPastUint64(stock.GetVolumeList(), 3, false))
	fmt.Println(stock.GetRangeList())
	fmt.Println(stock.IsRed())
}

func main() {
	stock.Get()
	ShowAll(stock)
	fmt.Println("-----------------------------")
	stock.PlusData()
	ShowAll(stock)
	fmt.Println(tradingdays.IsOpen(2015, 4, 25, utils.TaipeiTimeZone))
}
<|endoftext|>


<commit_before>// Copyright c 2017 tadaken3 <k.tanaka6057@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package cmd

import (
	"fmt"
	"os"
	"runtime"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string
var message string
var token string

var RootCmd = &cobra.Command{
	Use:   "notify",
	Short: `This application can notify any chat serviece`,
	Long:  `This application is a simple CLI tool. You can quickly notify to any chat serviece`,

	//Run: func(cmd *cobra.Command, args []string) {
	//	fmt.Printf("Usage: notify <command> [<args>]")
	//	},
}

func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)
	RootCmd.PersistentFlags().StringVarP(&message, "message", "m", "This message is from notify", "message")
	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.notify.yaml)")
	RootCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "access token")
	//viper.BindPFlag("token", RootCmd.PersistentFlags().Lookup("token"))
	//RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

func initConfig() {
	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".notify")
	if runtime.GOOS == "windows" {
		viper.AddConfigPath(os.Getenv("HOMEPATH"))
	} else {
		viper.AddConfigPath(os.Getenv("HOME"))
	}

	viper.AutomaticEnv()

	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}
<commit_msg>:put_litter_in_its_place:<commit_after>// Copyright c 2017 tadaken3 <k.tanaka6057@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package cmd

import (
	"fmt"
	"os"
	"runtime"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string
var message string
var token string

var RootCmd = &cobra.Command{
	Use:   "notify",
	Short: `This application can notify any chat serviece`,
	Long:  `This application is a simple CLI tool. You can quickly notify to any chat serviece`,

}

func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)
	RootCmd.PersistentFlags().StringVarP(&message, "message", "m", "This message is from notify", "message")
	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.notify.yaml)")
	RootCmd.PersistentFlags().StringVarP(&token, "token", "t", "", "access token")
}

func initConfig() {
	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName(".notify")
	if runtime.GOOS == "windows" {
		viper.AddConfigPath(os.Getenv("HOMEPATH"))
	} else {
		viper.AddConfigPath(os.Getenv("HOME"))
	}

	viper.AutomaticEnv()

	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}
<|endoftext|>


<commit_before>package cmd

import (
	"context"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"time"

	"github.com/hashicorp/go-multierror"
	"github.com/hashicorp/hcl"
	"github.com/spf13/cobra"
	"golang.org/x/oauth2/google"
	"google.golang.org/api/compute/v1"
)

type Config struct {
	Project map[string]Project    `hcl:"project"`
	Ruleset map[string]RawRuleset `hcl:"ruleset"`
}

type Ruleset struct {
	StartTime time.Time
	StopTime  time.Time
	Timezone  *time.Location
	Days      []int
	Instances []Instance

	rawRuleset RawRuleset
}

type RawRuleset struct {
	StartTime string `hcl:"startTime"`
	StopTime  string `hcl:"stopTime"`
	Timezone  string `hcl:"timezone"`
	Days      []int  `hcl:"days"`
}

type Instance struct {
	Name    string
	Project string
	Zone    string
	Status  string
}

type Project struct {
	Zones []string `hcl:"zones"`
}

func newRuleset(r RawRuleset) (rs Ruleset, err error) {
	logPrintlnVerbose("Creating new ruleset")

	rs.rawRuleset = r

	timezone, locationErr := time.LoadLocation(r.Timezone)
	if locationErr != nil {
		err = multierror.Append(err, errors.New("timezone is not valid"))
	}

	rs.Timezone = timezone

	if r.StartTime == "" {
		err = multierror.Append(err, errors.New("startTime cannot be blank"))
	}

	if r.StopTime == "" {
		err = multierror.Append(err, errors.New("stopTime cannot be blank"))
	}

	if locationErr == nil {
		startTime, startTimeErr := time.ParseInLocation("15:04", r.StartTime, timezone)
		if startTimeErr != nil {
			err = multierror.Append(err, errors.New("startTime is not in valid 24 hour HH:mm format"))
		}

		rs.StartTime = startTime

		stopTime, stopTimeErr := time.ParseInLocation("15:04", r.StopTime, timezone)
		if stopTimeErr != nil {
			err = multierror.Append(err, errors.New("stopTime is not in valid 24 hour HH:mm format"))
		}

		rs.StopTime = stopTime
	}

	if len(r.Days) > 7 {
		err = multierror.Append(err, errors.New("days must be valid"))
	}

	for _, day := range r.Days {
		if day > 7 || day < 1 {
			err = multierror.Append(err, errors.New("days must be an int between 1 and 7"))
		}
	}
	rs.Days = r.Days

	return
}

var RootCmd = &cobra.Command{
	Use:   "gce-sleep",
	Short: "gce-sleep is a tool for shutting down/starting up Google Cloud Engine instances based on tags for savings costs when not in use.",
	Run: func(cmd *cobra.Command, args []string) {
		logPrintlnVerbose("Starting gce-sleep")

		now := time.Now()

		logPrintlnVerbose("Basing time on:", now)

		configContent, err := ioutil.ReadFile(configLocation)
		if err != nil {
			log.Fatal(err)
		}

		var config Config
		err = hcl.Unmarshal(configContent, &config)
		if err != nil {
			log.Fatal(err)
		}

		activeRules := make(map[string]Ruleset)
		for index, rawRuleset := range config.Ruleset {
			ruleset, err := newRuleset(rawRuleset)
			if err != nil {
				log.Fatal(err)
			} else {
				activeRules[index] = ruleset
			}
		}

		logPrintlnVerbose("Active rulesets:", activeRules)

		ctx := context.Background()

		client, err := google.DefaultClient(ctx, compute.CloudPlatformScope)
		if err != nil {
			log.Fatal(err)
		}

		computeService, err := compute.New(client)
		if err != nil {
			log.Fatal(err)
		}

		filter := fmt.Sprintf("labels.%s eq on", labelName)
		logPrintlnVerbose(fmt.Sprintf("Filter defined as: %q", filter))

		for projectName, project := range config.Project {
			logPrintlnVerbose(fmt.Sprintf("Checking project %q", projectName))

			for _, zoneName := range project.Zones {
				logPrintlnVerbose(fmt.Sprintf("Checking zone %q", zoneName))

				instancesReq := computeService.Instances.List(projectName, zoneName).Filter(filter)
				if err := instancesReq.Pages(ctx, func(page *compute.InstanceList) error {
					for _, instance := range page.Items {
						logPrintlnVerbose(fmt.Sprintf("Checking instance %q", instance.Name))
						for _, metadata := range instance.Metadata.Items {
							if metadata.Key == "gce-sleep-group" {
								logPrintlnVerbose(fmt.Sprintf("Instance %q qualifies", instance.Name))

								actionableInstances := activeRules[*metadata.Value]
								actionableInstances.Instances = append(actionableInstances.Instances, Instance{
									Project: projectName,
									Zone:    zoneName,
									Name:    instance.Name,
									Status:  instance.Status,
								})
								activeRules[*metadata.Value] = actionableInstances
							}
						}
					}

					return nil
				}); err != nil {
					log.Fatal(err)
				}
			}
		}

		for rulesetName, ruleset := range activeRules {
			nowTimezone := now.In(ruleset.Timezone)
			shouldBeRunning := shouldBeRunning(nowTimezone, ruleset.StartTime, ruleset.StopTime)

			logPrintlnVerbose(fmt.Sprintf("Total %d instances to be evaluated in ruleset %q", len(ruleset.Instances), rulesetName))

			for _, instance := range ruleset.Instances {
				logPrintlnVerbose(fmt.Sprintf("Evaluating instance %q", instance.Name))

				if shouldBeRunning && instance.Status == "TERMINATED" {
					logPrintlnVerbose(fmt.Sprintf("Instance %q currently stopped, starting", instance.Name))

					call := computeService.Instances.Start(instance.Project, instance.Zone, instance.Name)
					_, err := call.Do()
					if err != nil {
						log.Fatal(err)
					} else {
						log.Println(fmt.Sprintf("Instance %q starting", instance.Name))
					}
				} else if !shouldBeRunning && instance.Status == "RUNNING" {
					logPrintlnVerbose(fmt.Sprintf("Instance %q currently starting, stopped", instance.Name))

					call := computeService.Instances.Stop(instance.Project, instance.Zone, instance.Name)
					_, err := call.Do()
					if err != nil {
						log.Fatal(err)
					} else {
						log.Println(fmt.Sprintf("Instance %q stopping", instance.Name))
					}
				} else {
					logPrintlnVerbose(fmt.Sprintf("Instance %q does not meet critera (%s <=, %s >=)", instance.Name, ruleset.rawRuleset.StartTime, ruleset.rawRuleset.StopTime))
				}
			}
		}

		logPrintlnVerbose("Stopping gce-sleep")
	},
}

func shouldBeRunning(now, startTime, stopTime time.Time) bool {
	if startTime.Hour() > now.Hour() || stopTime.Hour() < now.Hour() {
		return false
	}

	if startTime.Hour() == now.Hour() && startTime.Minute() > now.Minute() {
		return false
	}

	if stopTime.Hour() == now.Hour() && stopTime.Minute() < now.Minute() {
		return false
	}

	return true
}
<commit_msg>Fixing spelling errors<commit_after>package cmd

import (
	"context"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"time"

	"github.com/hashicorp/go-multierror"
	"github.com/hashicorp/hcl"
	"github.com/spf13/cobra"
	"golang.org/x/oauth2/google"
	"google.golang.org/api/compute/v1"
)

type Config struct {
	Project map[string]Project    `hcl:"project"`
	Ruleset map[string]RawRuleset `hcl:"ruleset"`
}

type Ruleset struct {
	StartTime time.Time
	StopTime  time.Time
	Timezone  *time.Location
	Days      []int
	Instances []Instance

	rawRuleset RawRuleset
}

type RawRuleset struct {
	StartTime string `hcl:"startTime"`
	StopTime  string `hcl:"stopTime"`
	Timezone  string `hcl:"timezone"`
	Days      []int  `hcl:"days"`
}

type Instance struct {
	Name    string
	Project string
	Zone    string
	Status  string
}

type Project struct {
	Zones []string `hcl:"zones"`
}

func newRuleset(r RawRuleset) (rs Ruleset, err error) {
	logPrintlnVerbose("Creating new ruleset")

	rs.rawRuleset = r

	timezone, locationErr := time.LoadLocation(r.Timezone)
	if locationErr != nil {
		err = multierror.Append(err, errors.New("timezone is not valid"))
	}

	rs.Timezone = timezone

	if r.StartTime == "" {
		err = multierror.Append(err, errors.New("startTime cannot be blank"))
	}

	if r.StopTime == "" {
		err = multierror.Append(err, errors.New("stopTime cannot be blank"))
	}

	if locationErr == nil {
		startTime, startTimeErr := time.ParseInLocation("15:04", r.StartTime, timezone)
		if startTimeErr != nil {
			err = multierror.Append(err, errors.New("startTime is not in valid 24 hour HH:mm format"))
		}

		rs.StartTime = startTime

		stopTime, stopTimeErr := time.ParseInLocation("15:04", r.StopTime, timezone)
		if stopTimeErr != nil {
			err = multierror.Append(err, errors.New("stopTime is not in valid 24 hour HH:mm format"))
		}

		rs.StopTime = stopTime
	}

	if len(r.Days) > 7 {
		err = multierror.Append(err, errors.New("days must be valid"))
	}

	for _, day := range r.Days {
		if day > 7 || day < 1 {
			err = multierror.Append(err, errors.New("days must be an int between 1 and 7"))
		}
	}
	rs.Days = r.Days

	return
}

var RootCmd = &cobra.Command{
	Use:   "gce-sleep",
	Short: "gce-sleep is a tool for shutting down/starting up Google Cloud Engine instances based on tags for savings costs when not in use.",
	Run: func(cmd *cobra.Command, args []string) {
		logPrintlnVerbose("Starting gce-sleep")

		now := time.Now()

		logPrintlnVerbose("Basing time on:", now)

		configContent, err := ioutil.ReadFile(configLocation)
		if err != nil {
			log.Fatal(err)
		}

		var config Config
		err = hcl.Unmarshal(configContent, &config)
		if err != nil {
			log.Fatal(err)
		}

		activeRules := make(map[string]Ruleset)
		for index, rawRuleset := range config.Ruleset {
			ruleset, err := newRuleset(rawRuleset)
			if err != nil {
				log.Fatal(err)
			} else {
				activeRules[index] = ruleset
			}
		}

		logPrintlnVerbose("Active rulesets:", activeRules)

		ctx := context.Background()

		client, err := google.DefaultClient(ctx, compute.CloudPlatformScope)
		if err != nil {
			log.Fatal(err)
		}

		computeService, err := compute.New(client)
		if err != nil {
			log.Fatal(err)
		}

		filter := fmt.Sprintf("labels.%s eq on", labelName)
		logPrintlnVerbose(fmt.Sprintf("Filter defined as: %q", filter))

		for projectName, project := range config.Project {
			logPrintlnVerbose(fmt.Sprintf("Checking project %q", projectName))

			for _, zoneName := range project.Zones {
				logPrintlnVerbose(fmt.Sprintf("Checking zone %q", zoneName))

				instancesReq := computeService.Instances.List(projectName, zoneName).Filter(filter)
				if err := instancesReq.Pages(ctx, func(page *compute.InstanceList) error {
					for _, instance := range page.Items {
						logPrintlnVerbose(fmt.Sprintf("Checking instance %q", instance.Name))
						for _, metadata := range instance.Metadata.Items {
							if metadata.Key == "gce-sleep-group" {
								logPrintlnVerbose(fmt.Sprintf("Instance %q qualifies", instance.Name))

								actionableInstances := activeRules[*metadata.Value]
								actionableInstances.Instances = append(actionableInstances.Instances, Instance{
									Project: projectName,
									Zone:    zoneName,
									Name:    instance.Name,
									Status:  instance.Status,
								})
								activeRules[*metadata.Value] = actionableInstances
							}
						}
					}

					return nil
				}); err != nil {
					log.Fatal(err)
				}
			}
		}

		for rulesetName, ruleset := range activeRules {
			nowTimezone := now.In(ruleset.Timezone)
			shouldBeRunning := shouldBeRunning(nowTimezone, ruleset.StartTime, ruleset.StopTime)

			logPrintlnVerbose(fmt.Sprintf("Total %d instances to be evaluated in ruleset %q", len(ruleset.Instances), rulesetName))

			for _, instance := range ruleset.Instances {
				logPrintlnVerbose(fmt.Sprintf("Evaluating instance %q", instance.Name))

				if shouldBeRunning && instance.Status == "TERMINATED" {
					logPrintlnVerbose(fmt.Sprintf("Instance %q currently stopped, starting", instance.Name))

					call := computeService.Instances.Start(instance.Project, instance.Zone, instance.Name)
					_, err := call.Do()
					if err != nil {
						log.Fatal(err)
					} else {
						log.Println(fmt.Sprintf("Instance %q starting", instance.Name))
					}
				} else if !shouldBeRunning && instance.Status == "RUNNING" {
					logPrintlnVerbose(fmt.Sprintf("Instance %q currently starting, stopped", instance.Name))

					call := computeService.Instances.Stop(instance.Project, instance.Zone, instance.Name)
					_, err := call.Do()
					if err != nil {
						log.Fatal(err)
					} else {
						log.Println(fmt.Sprintf("Instance %q stopping", instance.Name))
					}
				} else {
					logPrintlnVerbose(fmt.Sprintf("Instance %q does not meet criteria (%s <=, %s >=)", instance.Name, ruleset.rawRuleset.StartTime, ruleset.rawRuleset.StopTime))
				}
			}
		}

		logPrintlnVerbose("Stopping gce-sleep")
	},
}

func shouldBeRunning(now, startTime, stopTime time.Time) bool {
	if startTime.Hour() > now.Hour() || stopTime.Hour() < now.Hour() {
		return false
	}

	if startTime.Hour() == now.Hour() && startTime.Minute() > now.Minute() {
		return false
	}

	if stopTime.Hour() == now.Hour() && stopTime.Minute() < now.Minute() {
		return false
	}

	return true
}
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// 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 cmd

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

	"github.com/spf13/cobra"
)

func init() {
	validateCmd.PersistentFlags().BoolVar(&flags.verbose, "verbose", false, "Log output to stderr")

	validateCmd.Flags().StringVar(&flags.validate.policyPath, "policy-path", "", "Path to directory containing validation policies")
	validateCmd.MarkFlagRequired("policy-path")
	validateCmd.Flags().StringVar(&flags.validate.project, "project", "", "Provider project override")

	convertCmd.Flags().StringVar(&flags.convert.project, "project", "", "Provider project override")

	validateCmd.Flags().BoolVar(&flags.validate.outputJSON, "output-json", false, "Print violations as JSON")

	rootCmd.AddCommand(convertCmd)
	rootCmd.AddCommand(validateCmd)
	rootCmd.AddCommand(listSupportedResourcesCmd)
}

// NOTE: We use a pkg-level var here instead of github.com/spf13/viper
// to establish a pattern of passing down config rather than accessing it
// globally.
var flags struct {
	// Common flags
	verbose bool

	// flags that correspond to subcommands:
	convert struct {
		project string
	}
	validate struct {
		project    string
		policyPath string
		outputJSON bool
	}
	listSupportedResources struct{}
}

// Execute is the entry-point for all commands.
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		os.Exit(1)
	}
}

var rootCmd = &cobra.Command{
	Use:   "terraform-validator",
	Short: "Validate terraform plans using Forseti Config Validator.",
	Long: `Validate terraform plans by converting terraform resources
to their Google CAI (Cloud Asset Inventory) format and passing them through
Forseti Config Validator.`,
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		if !flags.verbose {
			// Suppress chatty packages.
			log.SetOutput(ioutil.Discard)
		}
	},
}
<commit_msg>Update --project doc<commit_after>// Copyright 2019 Google LLC
//
// 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 cmd

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

	"github.com/spf13/cobra"
)

func init() {
	validateCmd.PersistentFlags().BoolVar(&flags.verbose, "verbose", false, "Log output to stderr")

	validateCmd.Flags().StringVar(&flags.validate.policyPath, "policy-path", "", "Path to directory containing validation policies")
	validateCmd.MarkFlagRequired("policy-path")
	validateCmd.Flags().StringVar(&flags.validate.project, "project", "", "Provider project override (override the default project configuration assigned to the google terraform provider when validating resources)")

	convertCmd.Flags().StringVar(&flags.convert.project, "project", "", "Provider project override (override the default project configuration assigned to the google terraform provider when converting resources)")

	validateCmd.Flags().BoolVar(&flags.validate.outputJSON, "output-json", false, "Print violations as JSON")

	rootCmd.AddCommand(convertCmd)
	rootCmd.AddCommand(validateCmd)
	rootCmd.AddCommand(listSupportedResourcesCmd)
}

// NOTE: We use a pkg-level var here instead of github.com/spf13/viper
// to establish a pattern of passing down config rather than accessing it
// globally.
var flags struct {
	// Common flags
	verbose bool

	// flags that correspond to subcommands:
	convert struct {
		project string
	}
	validate struct {
		project    string
		policyPath string
		outputJSON bool
	}
	listSupportedResources struct{}
}

// Execute is the entry-point for all commands.
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		os.Exit(1)
	}
}

var rootCmd = &cobra.Command{
	Use:   "terraform-validator",
	Short: "Validate terraform plans using Forseti Config Validator.",
	Long: `Validate terraform plans by converting terraform resources
to their Google CAI (Cloud Asset Inventory) format and passing them through
Forseti Config Validator.`,
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		if !flags.verbose {
			// Suppress chatty packages.
			log.SetOutput(ioutil.Discard)
		}
	},
}
<|endoftext|>


<commit_before>package config

const (
	AuthName = "login" // The name of the Auth cookie\
)
<commit_msg>Revert "Removed an unused config for administration."<commit_after>package config

const (
	AuthName = "login"                // The name of the Auth cookie
	AuthLoc  = DataDirectory + "auth" // Authorization for the blog
)
<|endoftext|>