<commit_before>package nn

import (
	"fmt"
	"math"
)

type FeedForward struct {
	// Number of input, hidden and output nodes
	NInputs, NHiddens, NOutputs int
	// Whether it is regression or not
	Regression bool
	// Activations for nodes
	InputActivations, HiddenActivations, OutputActivations []float64
	// Weights
	InputWeights, OutputWeights [][]float64
	// Last change in weights for momentum
	InputChanges, OutputChanges [][]float64
}

// Initialize the neural network
func (nn *FeedForward) Init(inputs, hiddens, outputs int, regression bool) {
	nn.NInputs = inputs + 1   // +1 for bias
	nn.NHiddens = hiddens + 1 // +1 for bias
	nn.NOutputs = outputs
	nn.Regression = regression

	nn.InputActivations = vector(nn.NInputs, 1.0)
	nn.HiddenActivations = vector(nn.NHiddens, 1.0)
	nn.OutputActivations = vector(nn.NOutputs, 1.0)

	nn.InputWeights = matrix(nn.NInputs, nn.NHiddens)
	nn.OutputWeights = matrix(nn.NHiddens, nn.NOutputs)

	for i := 0; i < nn.NInputs; i++ {
		for j := 0; j < nn.NHiddens; j++ {
			nn.InputWeights[i][j] = random(-1, 1)
		}
	}

	for i := 0; i < nn.NHiddens; i++ {
		for j := 0; j < nn.NOutputs; j++ {
			nn.OutputWeights[i][j] = random(-1, 1)
		}
	}

	nn.InputChanges = matrix(nn.NInputs, nn.NHiddens)
	nn.OutputChanges = matrix(nn.NHiddens, nn.NOutputs)
}

func (nn *FeedForward) Update(inputs []float64) []float64 {
	if len(inputs) != nn.NInputs-1 {
		fmt.Println("Error: wrong number of inputs")
		return []float64{} // should return error
	}

	for i := 0; i < nn.NInputs-1; i++ {
		nn.InputActivations[i] = inputs[i]
	}

	for i := 0; i < nn.NHiddens-1; i++ {
		var sum float64 = 0.0
		for j := 0; j < nn.NInputs; j++ {
			sum += nn.InputActivations[j] * nn.InputWeights[j][i]
		}
		nn.HiddenActivations[i] = sigmoid(sum)
	}

	for i := 0; i < nn.NOutputs; i++ {
		var sum float64 = 0.0
		for j := 0; j < nn.NHiddens; j++ {
			sum += nn.HiddenActivations[j] * nn.OutputWeights[j][i]
		}
		if nn.Regression {
			nn.OutputActivations[i] = sum
		} else {
			nn.OutputActivations[i] = sigmoid(sum)
		}
	}

	return nn.OutputActivations
}

func (nn *FeedForward) BackPropagate(targets []float64, lRate, mFactor float64) float64 {
	if len(targets) != nn.NOutputs {
		fmt.Println("Error: wrong number of target values")
		return 0.0
	}

	output_deltas := vector(nn.NOutputs, 0.0)
	for i := 0; i < nn.NOutputs; i++ {
		output_deltas[i] = targets[i] - nn.OutputActivations[i]

		if !nn.Regression {
			output_deltas[i] = dsigmoid(nn.OutputActivations[i]) * output_deltas[i]
		}
	}

	hidden_deltas := vector(nn.NHiddens, 0.0)
	for i := 0; i < nn.NHiddens; i++ {
		var e float64 = 0.0

		for j := 0; j < nn.NOutputs; j++ {
			e += output_deltas[j] * nn.OutputWeights[i][j]
		}
		hidden_deltas[i] = dsigmoid(nn.HiddenActivations[i]) * e
	}

	for i := 0; i < nn.NHiddens; i++ {
		for j := 0; j < nn.NOutputs; j++ {
			change := output_deltas[j] * nn.HiddenActivations[i]
			nn.OutputWeights[i][j] = nn.OutputWeights[i][j] + lRate*change + mFactor*nn.OutputChanges[i][j]
			nn.OutputChanges[i][j] = change
		}
	}

	for i := 0; i < nn.NInputs; i++ {
		for j := 0; j < nn.NHiddens; j++ {
			change := hidden_deltas[j] * nn.InputActivations[i]
			nn.InputWeights[i][j] = nn.InputWeights[i][j] + lRate*change + mFactor*nn.InputChanges[i][j]
			nn.InputChanges[i][j] = change
		}
	}

	var e float64 = 0.0

	for i := 0; i < len(targets); i++ {
		e += 0.5 * math.Pow(targets[i]-nn.OutputActivations[i], 2)
	}

	return e
}

func (nn *FeedForward) Train(patterns [][][]float64, iterations int, lRate, mFactor float64, debug bool) []float64 {
	errors := make([]float64, iterations)

	for i := 0; i < iterations; i++ {
		var e float64 = 0.0
		for _, p := range patterns {
			nn.Update(p[0])

			tmp := nn.BackPropagate(p[1], lRate, mFactor)
			e += tmp
		}

		errors[i] = e

		if debug && i%1000 == 0 {
			fmt.Println(i, e)
		}
	}

	return errors
}

func (nn *FeedForward) Test(patterns [][][]float64) {
	for _, p := range patterns {
		fmt.Println(p[0], "->", nn.Update(p[0]), " : ", p[1])
	}
}
<commit_msg>fix variables names and use log to display errors<commit_after>package nn

import (
	"log"
	"fmt"
	"math"
)

type FeedForward struct {
	// Number of input, hidden and output nodes
	NInputs, NHiddens, NOutputs int
	// Whether it is regression or not
	Regression bool
	// Activations for nodes
	InputActivations, HiddenActivations, OutputActivations []float64
	// Weights
	InputWeights, OutputWeights [][]float64
	// Last change in weights for momentum
	InputChanges, OutputChanges [][]float64
}

// Initialize the neural network
func (nn *FeedForward) Init(inputs, hiddens, outputs int, regression bool) {
	nn.NInputs = inputs + 1   // +1 for bias
	nn.NHiddens = hiddens + 1 // +1 for bias
	nn.NOutputs = outputs
	nn.Regression = regression

	nn.InputActivations = vector(nn.NInputs, 1.0)
	nn.HiddenActivations = vector(nn.NHiddens, 1.0)
	nn.OutputActivations = vector(nn.NOutputs, 1.0)

	nn.InputWeights = matrix(nn.NInputs, nn.NHiddens)
	nn.OutputWeights = matrix(nn.NHiddens, nn.NOutputs)

	for i := 0; i < nn.NInputs; i++ {
		for j := 0; j < nn.NHiddens; j++ {
			nn.InputWeights[i][j] = random(-1, 1)
		}
	}

	for i := 0; i < nn.NHiddens; i++ {
		for j := 0; j < nn.NOutputs; j++ {
			nn.OutputWeights[i][j] = random(-1, 1)
		}
	}

	nn.InputChanges = matrix(nn.NInputs, nn.NHiddens)
	nn.OutputChanges = matrix(nn.NHiddens, nn.NOutputs)
}

func (nn *FeedForward) Update(inputs []float64) []float64 {
	if len(inputs) != nn.NInputs-1 {
		log.Fatal("Error: wrong number of inputs")
	}

	for i := 0; i < nn.NInputs-1; i++ {
		nn.InputActivations[i] = inputs[i]
	}

	for i := 0; i < nn.NHiddens-1; i++ {
		var sum float64 = 0.0
		for j := 0; j < nn.NInputs; j++ {
			sum += nn.InputActivations[j] * nn.InputWeights[j][i]
		}
		nn.HiddenActivations[i] = sigmoid(sum)
	}

	for i := 0; i < nn.NOutputs; i++ {
		var sum float64 = 0.0
		for j := 0; j < nn.NHiddens; j++ {
			sum += nn.HiddenActivations[j] * nn.OutputWeights[j][i]
		}
		if nn.Regression {
			nn.OutputActivations[i] = sum
		} else {
			nn.OutputActivations[i] = sigmoid(sum)
		}
	}

	return nn.OutputActivations
}

func (nn *FeedForward) BackPropagate(targets []float64, lRate, mFactor float64) float64 {
	if len(targets) != nn.NOutputs {
		log.Fatal("Error: wrong number of target values")
	}

	outputDeltas := vector(nn.NOutputs, 0.0)
	for i := 0; i < nn.NOutputs; i++ {
		outputDeltas[i] = targets[i] - nn.OutputActivations[i]

		if !nn.Regression {
			outputDeltas[i] = dsigmoid(nn.OutputActivations[i]) * outputDeltas[i]
		}
	}

	hiddenDeltas := vector(nn.NHiddens, 0.0)
	for i := 0; i < nn.NHiddens; i++ {
		var e float64 = 0.0

		for j := 0; j < nn.NOutputs; j++ {
			e += outputDeltas[j] * nn.OutputWeights[i][j]
		}
		hiddenDeltas[i] = dsigmoid(nn.HiddenActivations[i]) * e
	}

	for i := 0; i < nn.NHiddens; i++ {
		for j := 0; j < nn.NOutputs; j++ {
			change := outputDeltas[j] * nn.HiddenActivations[i]
			nn.OutputWeights[i][j] = nn.OutputWeights[i][j] + lRate * change + mFactor * nn.OutputChanges[i][j]
			nn.OutputChanges[i][j] = change
		}
	}

	for i := 0; i < nn.NInputs; i++ {
		for j := 0; j < nn.NHiddens; j++ {
			change := hiddenDeltas[j] * nn.InputActivations[i]
			nn.InputWeights[i][j] = nn.InputWeights[i][j] + lRate * change + mFactor * nn.InputChanges[i][j]
			nn.InputChanges[i][j] = change
		}
	}

	var e float64 = 0.0

	for i := 0; i < len(targets); i++ {
		e += 0.5 * math.Pow(targets[i] - nn.OutputActivations[i], 2)
	}

	return e
}

func (nn *FeedForward) Train(patterns [][][]float64, iterations int, lRate, mFactor float64, debug bool) []float64 {
	errors := make([]float64, iterations)

	for i := 0; i < iterations; i++ {
		var e float64 = 0.0
		for _, p := range patterns {
			nn.Update(p[0])

			tmp := nn.BackPropagate(p[1], lRate, mFactor)
			e += tmp
		}

		errors[i] = e

		if debug && i%1000 == 0 {
			fmt.Println(i, e)
		}
	}

	return errors
}

func (nn *FeedForward) Test(patterns [][][]float64) {
	for _, p := range patterns {
		fmt.Println(p[0], "->", nn.Update(p[0]), " : ", p[1])
	}
}
<|endoftext|>


<commit_before>package client

import (
	"os"
	"os/exec"
	"runtime"

	log "github.com/Sirupsen/logrus"
	"github.com/docker/docker/client"
	"github.com/maliceio/go-plugin-utils/utils"
	"github.com/maliceio/malice/config"
	er "github.com/maliceio/malice/malice/errors"
	"golang.org/x/net/context"
)

// NOTE: https://github.com/eris-ltd/eris-cli/blob/master/perform/docker_run.go

// Docker is the Malice docker client
type Docker struct {
	Client *client.Client
	ip     string
	port   string
}

// NewDockerClient creates a new Docker Client
func NewDockerClient() *Docker {
	var docker *client.Client
	var ip, port string
	var err error

	switch os := runtime.GOOS; os {
	case "linux":
		log.Debug("Running inside Docker...")
		log.Debug("Creating NewClient...")
		proto, addr, basePath, err := client.ParseHost("unix:///var/run/docker.sock")
		log.Debug("Proto: ", proto, ", Addr: ", addr, ", BasePath: ", basePath, ", Error: ", err)
		defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
		docker, err = client.NewClient("unix:///var/run/docker.sock", "v1.22", nil, defaultHeaders)
		ip = "localhost"
		port = "2375"
	case "darwin":
		log.Debug("Running inside Docker for Mac...")
		log.Debug("Creating NewClient...")
		proto, addr, basePath, err := client.ParseHost("unix:///var/run/docker.sock")
		log.Debug("Proto: ", proto, ", Addr: ", addr, ", BasePath: ", basePath, ", Error: ", err)
		defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
		docker, err = client.NewClient("unix:///var/run/docker.sock", "v1.22", nil, defaultHeaders)
		ip = "localhost"
		port = "2375"
	case "windows":
		log.Debug("Creating NewEnvClient...")
		docker, err = client.NewEnvClient()
		if err != nil {
			log.Fatal(err)
		}
		ip, port, err = parseDockerEndoint(utils.Getopt("DOCKER_HOST", config.Conf.Docker.EndPoint))
	default:
		log.Debug("Creating NewEnvClient...")
		docker, err = client.NewEnvClient()
		if err != nil {
			log.Fatal(err)
		}
		ip, port, err = parseDockerEndoint(utils.Getopt("DOCKER_HOST", config.Conf.Docker.EndPoint))
	}
	if err != nil {
		log.Fatal(err)
	}
	// Check if client can connect
	log.Debug("Docker Info...")
	if _, err = docker.Info(context.Background()); err != nil {
		log.Debug("Docker Info FAILED...")
		handleClientError(err)
	} else {
		log.WithFields(log.Fields{"ip": ip, "port": port}).Debug("Connected to docker daemon client")
	}

	log.Debug("Docker Info...")
	if _, err = docker.Info(context.Background()); err != nil {
		log.Debug("Docker Info FAILED...")
		handleClientError(err)
	} else {
		log.WithFields(log.Fields{"ip": ip, "port": port}).Debug("Connected to docker daemon client")
	}

	log.Debug("Docker Info2...")
	if _, err = docker.Info(context.Background()); err != nil {
		log.Debug("Docker Info2 FAILED...")
		log.Error(err)
		er.CheckError(err)
		handleClientError(err)
	} else {
		log.WithFields(log.Fields{"ip": ip, "port": port}).Debug("Connected to docker daemon client")
	}

	return &Docker{
		Client: docker,
		ip:     ip,
		port:   port,
	}
}

// GetIP returns IP of docker client
func (docker *Docker) GetIP() string {
	return docker.ip
}

// Ping pings docker client to see if it is up or not by checking Info.
func (docker *Docker) Ping() bool {
	// ctx, cancel := context.WithTimeout(context.Background(), config.Conf.Docker.Timeout*time.Second)
	// defer cancel()

	_, err := docker.Client.Info(context.Background())
	if err != nil {
		er.CheckError(err)
		return false
	}
	return true
}

// TODO: Make this betta MUCHO betta
func handleClientError(dockerError error) {
	if dockerError != nil {
		log.WithFields(log.Fields{"env": config.Conf.Environment.Run}).Error("Unable to connect to docker client")
		switch runtime.GOOS {
		case "darwin":
			if _, err := exec.LookPath("docker-machine"); err != nil {
				log.Info("Please install docker-machine by running: ")
				log.Info(" - brew install docker-machine")
				log.Infof(" - brew install docker-machine\n\tdocker-machine create -d virtualbox %s", config.Conf.Docker.Name)
				log.Infof(" - eval $(docker-machine env %s)", config.Conf.Docker.Name)
			} else {
				log.Info("Please start and source the docker-machine env by running: ")
				log.Infof(" - docker-machine start %s", config.Conf.Docker.Name)
				log.Infof(" - eval $(docker-machine env %s)", config.Conf.Docker.Name)
			}
		case "linux":
			log.Info("Please start the docker daemon.")
		case "windows":
			if _, err := exec.LookPath("docker-machine.exe"); err != nil {
				log.Info("Please install docker-machine - https://www.docker.com/docker-toolbox")
			} else {
				log.Info("Please start and source the docker-machine env by running: ")
				log.Infof(" - docker-machine start %", config.Conf.Docker.Name)
				log.Infof(" - eval $(docker-machine env %s)", config.Conf.Docker.Name)
			}
		}
		// TODO Decide if I want to make docker machines or rely on user to create their own.
		// log.Info("Trying to create new docker-machine: ", "test")
		// MakeDockerMachine("test")
		os.Exit(2)
	}
}
<commit_msg>logging<commit_after>package client

import (
	"os"
	"os/exec"
	"runtime"

	log "github.com/Sirupsen/logrus"
	"github.com/docker/docker/client"
	"github.com/maliceio/go-plugin-utils/utils"
	"github.com/maliceio/malice/config"
	er "github.com/maliceio/malice/malice/errors"
	"golang.org/x/net/context"
)

// NOTE: https://github.com/eris-ltd/eris-cli/blob/master/perform/docker_run.go

// Docker is the Malice docker client
type Docker struct {
	Client *client.Client
	ip     string
	port   string
}

// NewDockerClient creates a new Docker Client
func NewDockerClient() *Docker {
	var docker *client.Client
	var ip, port string
	var err error

	switch os := runtime.GOOS; os {
	case "linux":
		log.Debug("Running inside Docker...")
		log.Debug("Creating NewClient...")
		proto, addr, basePath, err := client.ParseHost("unix:///var/run/docker.sock")
		log.Debug("Proto: ", proto, ", Addr: ", addr, ", BasePath: ", basePath, ", Error: ", err)
		defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
		docker, err = client.NewClient("unix:///var/run/docker.sock", "v1.22", nil, defaultHeaders)
		ip = "localhost"
		port = "2375"
	case "darwin":
		log.Debug("Running inside Docker for Mac...")
		log.Debug("Creating NewClient...")
		proto, addr, basePath, err := client.ParseHost("unix:///var/run/docker.sock")
		log.Debug("Proto: ", proto, ", Addr: ", addr, ", BasePath: ", basePath, ", Error: ", err)
		defaultHeaders := map[string]string{"User-Agent": "engine-api-cli-1.0"}
		docker, err = client.NewClient("unix:///var/run/docker.sock", "v1.22", nil, defaultHeaders)
		ip = "localhost"
		port = "2375"
	case "windows":
		log.Debug("Creating NewEnvClient...")
		docker, err = client.NewEnvClient()
		if err != nil {
			log.Fatal(err)
		}
		ip, port, err = parseDockerEndoint(utils.Getopt("DOCKER_HOST", config.Conf.Docker.EndPoint))
	default:
		log.Debug("Creating NewEnvClient...")
		docker, err = client.NewEnvClient()
		if err != nil {
			log.Fatal(err)
		}
		ip, port, err = parseDockerEndoint(utils.Getopt("DOCKER_HOST", config.Conf.Docker.EndPoint))
	}
	if err != nil {
		log.Fatal(err)
	}
	// Check if client can connect
	log.Debug("Docker Info...")
	if _, err = docker.Info(context.Background()); err != nil {
		log.Debug("Docker Info FAILED...")
		handleClientError(err)
	} else {
		log.WithFields(log.Fields{"ip": ip, "port": port}).Debug("Connected to docker daemon client")
	}

	log.Debug("Docker Info2...")
	if _, err = docker.Info(context.Background()); err != nil {
		log.Debug("Docker Info2 FAILED...")
		log.Error(err)
		er.CheckError(err)
		handleClientError(err)
	} else {
		log.WithFields(log.Fields{"ip": ip, "port": port}).Debug("Connected to docker daemon client")
	}

	log.Debug("Docker Info3...")
	if _, err = docker.Info(context.Background()); err != nil {
		log.Debug("Docker Info3 FAILED...")
		log.Error(err)
		er.CheckError(err)
		handleClientError(err)
	} else {
		log.WithFields(log.Fields{"ip": ip, "port": port}).Debug("Connected to docker daemon client")
	}

	return &Docker{
		Client: docker,
		ip:     ip,
		port:   port,
	}
}

// GetIP returns IP of docker client
func (docker *Docker) GetIP() string {
	return docker.ip
}

// Ping pings docker client to see if it is up or not by checking Info.
func (docker *Docker) Ping() bool {
	// ctx, cancel := context.WithTimeout(context.Background(), config.Conf.Docker.Timeout*time.Second)
	// defer cancel()

	_, err := docker.Client.Info(context.Background())
	if err != nil {
		er.CheckError(err)
		return false
	}
	return true
}

// TODO: Make this betta MUCHO betta
func handleClientError(dockerError error) {
	if dockerError != nil {
		log.WithFields(log.Fields{"env": config.Conf.Environment.Run}).Error("Unable to connect to docker client")
		switch runtime.GOOS {
		case "darwin":
			if _, err := exec.LookPath("docker-machine"); err != nil {
				log.Info("Please install docker-machine by running: ")
				log.Info(" - brew install docker-machine")
				log.Infof(" - brew install docker-machine\n\tdocker-machine create -d virtualbox %s", config.Conf.Docker.Name)
				log.Infof(" - eval $(docker-machine env %s)", config.Conf.Docker.Name)
			} else {
				log.Info("Please start and source the docker-machine env by running: ")
				log.Infof(" - docker-machine start %s", config.Conf.Docker.Name)
				log.Infof(" - eval $(docker-machine env %s)", config.Conf.Docker.Name)
			}
		case "linux":
			log.Info("Please start the docker daemon.")
		case "windows":
			if _, err := exec.LookPath("docker-machine.exe"); err != nil {
				log.Info("Please install docker-machine - https://www.docker.com/docker-toolbox")
			} else {
				log.Info("Please start and source the docker-machine env by running: ")
				log.Infof(" - docker-machine start %", config.Conf.Docker.Name)
				log.Infof(" - eval $(docker-machine env %s)", config.Conf.Docker.Name)
			}
		}
		// TODO Decide if I want to make docker machines or rely on user to create their own.
		// log.Info("Trying to create new docker-machine: ", "test")
		// MakeDockerMachine("test")
		os.Exit(2)
	}
}
<|endoftext|>


<commit_before>package control

import (
	"errors"
	"fmt"
	"sync"
	"time"

	"github.com/emicklei/melrose/core"
	"github.com/emicklei/melrose/notify"
)

type Listen struct {
	mutex           *sync.RWMutex
	ctx             core.Context
	deviceID        int
	variableStore   core.VariableStorage
	variableName    string
	isRunning       bool
	callback        core.Valueable
	notesOn         map[int]int
	noteChangeCount int
}

func NewListen(ctx core.Context, deviceID int, variableName string, target core.Valueable) *Listen {
	return &Listen{
		mutex:           new(sync.RWMutex),
		ctx:             ctx,
		deviceID:        deviceID,
		variableName:    variableName,
		callback:        target,
		notesOn:         map[int]int{},
		noteChangeCount: 0,
	}
}

// Inspect implements Inspectable
func (l *Listen) Inspect(i core.Inspection) {
	i.Properties["running"] = l.isRunning
}

// Target is for replacing functions
func (l *Listen) Target() core.Valueable { return l.callback }

// SetTarget is for replacing functions
func (l *Listen) SetTarget(c core.Valueable) { l.callback = c }

// Play is part of core.Playable
func (l *Listen) Play(ctx core.Context, at time.Time) error {
	if l.isRunning {
		return nil
	}
	if !ctx.Device().HasInputCapability() {
		return errors.New("Input is not available for this device")
	}
	l.isRunning = true
	ctx.Device().Listen(l.deviceID, l, l.isRunning)
	return nil
}

func (l *Listen) Stop(ctx core.Context) error {
	if !l.isRunning {
		return nil
	}
	l.isRunning = false
	ctx.Device().Listen(l.deviceID, l, l.isRunning)
	return nil
}

// NoteOn is part of core.NoteListener
func (l *Listen) NoteOn(n core.Note) {
	l.mutex.Lock()
	if core.IsDebug() {
		notify.Debugf("control.listen ON %v", n)
	}
	l.noteChangeCount++
	countCheck := l.noteChangeCount
	nr := n.MIDI()
	l.notesOn[nr] = countCheck
	l.ctx.Variables().Put(l.variableName, n)

	// release so condition can be evaluated
	l.mutex.Unlock()

	if e, ok := l.callback.Value().(core.Evaluatable); ok {
		// only actually play the note if the hit count matches the check
		cond := func() bool {
			return l.isNoteOnCount(nr, countCheck)
		}
		e.Evaluate(l.ctx.WithCondition(cond))
	}
}

func (l *Listen) isNoteOnCount(nr, countCheck int) bool {
	l.mutex.RLock()
	defer l.mutex.RUnlock()
	// is the note still on?
	count, ok := l.notesOn[nr]
	// is the note on on the count
	return ok && count == countCheck
}

// NoteOff is part of core.NoteListener
func (l *Listen) NoteOff(n core.Note) {
	l.mutex.Lock()
	defer l.mutex.Unlock()
	if core.IsDebug() {
		notify.Debugf("control.listen OFF %v", n)
	}
	delete(l.notesOn, n.MIDI())
}

// Storex is part of core.Storable
func (l *Listen) Storex() string {
	return fmt.Sprintf("listen(%d,%s,%s)", l.deviceID, l.variableName, core.Storex(l.callback))
}
<commit_msg>show device<commit_after>package control

import (
	"errors"
	"fmt"
	"sync"
	"time"

	"github.com/emicklei/melrose/core"
	"github.com/emicklei/melrose/notify"
)

type Listen struct {
	mutex           *sync.RWMutex
	ctx             core.Context
	deviceID        int
	variableStore   core.VariableStorage
	variableName    string
	isRunning       bool
	callback        core.Valueable
	notesOn         map[int]int
	noteChangeCount int
}

func NewListen(ctx core.Context, deviceID int, variableName string, target core.Valueable) *Listen {
	return &Listen{
		mutex:           new(sync.RWMutex),
		ctx:             ctx,
		deviceID:        deviceID,
		variableName:    variableName,
		callback:        target,
		notesOn:         map[int]int{},
		noteChangeCount: 0,
	}
}

// Inspect implements Inspectable
func (l *Listen) Inspect(i core.Inspection) {
	i.Properties["running"] = l.isRunning
	i.Properties["device"] = l.deviceID
}

// Target is for replacing functions
func (l *Listen) Target() core.Valueable { return l.callback }

// SetTarget is for replacing functions
func (l *Listen) SetTarget(c core.Valueable) { l.callback = c }

// Play is part of core.Playable
func (l *Listen) Play(ctx core.Context, at time.Time) error {
	if l.isRunning {
		return nil
	}
	if !ctx.Device().HasInputCapability() {
		return errors.New("Input is not available for this device")
	}
	l.isRunning = true
	ctx.Device().Listen(l.deviceID, l, l.isRunning)
	return nil
}

func (l *Listen) Stop(ctx core.Context) error {
	if !l.isRunning {
		return nil
	}
	l.isRunning = false
	ctx.Device().Listen(l.deviceID, l, l.isRunning)
	return nil
}

// NoteOn is part of core.NoteListener
func (l *Listen) NoteOn(n core.Note) {
	l.mutex.Lock()
	if core.IsDebug() {
		notify.Debugf("control.listen ON %v", n)
	}
	l.noteChangeCount++
	countCheck := l.noteChangeCount
	nr := n.MIDI()
	l.notesOn[nr] = countCheck
	l.ctx.Variables().Put(l.variableName, n)

	// release so condition can be evaluated
	l.mutex.Unlock()

	if e, ok := l.callback.Value().(core.Evaluatable); ok {
		// only actually play the note if the hit count matches the check
		cond := func() bool {
			return l.isNoteOnCount(nr, countCheck)
		}
		e.Evaluate(l.ctx.WithCondition(cond))
	}
}

func (l *Listen) isNoteOnCount(nr, countCheck int) bool {
	l.mutex.RLock()
	defer l.mutex.RUnlock()
	// is the note still on?
	count, ok := l.notesOn[nr]
	// is the note on on the count
	return ok && count == countCheck
}

// NoteOff is part of core.NoteListener
func (l *Listen) NoteOff(n core.Note) {
	l.mutex.Lock()
	defer l.mutex.Unlock()
	if core.IsDebug() {
		notify.Debugf("control.listen OFF %v", n)
	}
	delete(l.notesOn, n.MIDI())
}

// Storex is part of core.Storable
func (l *Listen) Storex() string {
	return fmt.Sprintf("listen(%d,%s,%s)", l.deviceID, l.variableName, core.Storex(l.callback))
}
<|endoftext|>


<commit_before>package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/missdeer/KellyWechat/models/wd"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
)

type WDResponseStatus struct {
	StatusCode   int
	StatusReason string
}

type WDResponseShopResult struct {
	ShopName string
	Logo     string
	Note     string
}

type WDResponseShopInfo struct {
	Status WDResponseStatus
	Result WDResponseShopResult
}

type WDController struct {
	beego.Controller
}

func (this *WDController) SubmitWD() {
	id := this.GetString(":id")
	// get shop info
	// http://wd.koudai.com/wd/shop/getPubInfo?param={"userID":215091300,"f_seller_id":""}
	shopInfoUrl := fmt.Sprintf(`http://wd.koudai.com/wd/shop/getPubInfo?param={"userID":%s,"f_seller_id":""}`, id)

	resp, err := http.Get(shopInfoUrl)
	if err != nil {
		beego.Error("read response error: ", err)
		this.Data["json"] = map[string]string{"error": "reading response error"}
		this.ServeJson()
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	var shopInfo WDResponseShopInfo
	json.Unmarshal(body, &shopInfo)
	fmt.Println("shop info: ", shopInfo)
	if shopInfo.Status.StatusCode != 0 ||
		len(shopInfo.Result.ShopName) == 0 ||
		len(shopInfo.Result.Logo) == 0 {
		this.Data["json"] = map[string]string{"error": "seemly an invalid shop"}
		this.ServeJson()
		return
	}
	wdShop := &models.WDShop{}
	wdShop.Uuid, err = strconv.ParseUint(id, 10, 64)
	if err != nil {
		beego.Error("read response error: ", err)
		this.Data["json"] = map[string]string{"error": "reading response error"}
		this.ServeJson()
		return
	}

	if wdShop.Get() != nil {
		endPos := strings.Index(shopInfo.Result.Logo, "?")
		wdShop.Logo = shopInfo.Result.Logo[:endPos]
		wdShop.Name = shopInfo.Result.ShopName
		wdShop.Note = shopInfo.Result.Note
		wdShop.Insert()
	}
	// get item list
	// http://wd.koudai.com/wd/item/getIsTopList?param={"userid":215091300,"pageNum":0,"pageSize":49,"isTop":0,"f_seller_id":""}

	// get item detail
	// http://wd.koudai.com/wd/item/getPubInfo?param={"itemID":310148677,"page":1}

	this.Data["json"] = map[string]string{"ok": "200"}
	this.ServeJson()
}
<commit_msg>(*)can update shop info<commit_after>package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/missdeer/KellyWechat/models/wd"
	"io/ioutil"
	"net/http"
	"strconv"
	"strings"
)

type WDResponseStatus struct {
	StatusCode   int
	StatusReason string
}

type WDResponseShopResult struct {
	ShopName string
	Logo     string
	Note     string
}

type WDResponseShopInfo struct {
	Status WDResponseStatus
	Result WDResponseShopResult
}

type WDController struct {
	beego.Controller
}

func (this *WDController) SubmitWD() {
	id := this.GetString(":id")
	// get shop info
	// http://wd.koudai.com/wd/shop/getPubInfo?param={"userID":215091300,"f_seller_id":""}
	shopInfoUrl := fmt.Sprintf(`http://wd.koudai.com/wd/shop/getPubInfo?param={"userID":%s,"f_seller_id":""}`, id)

	resp, err := http.Get(shopInfoUrl)
	if err != nil {
		beego.Error("read response error: ", err)
		this.Data["json"] = map[string]string{"error": "reading response error"}
		this.ServeJson()
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	var shopInfo WDResponseShopInfo
	json.Unmarshal(body, &shopInfo)
	fmt.Println("shop info: ", shopInfo)
	if shopInfo.Status.StatusCode != 0 ||
		len(shopInfo.Result.ShopName) == 0 ||
		len(shopInfo.Result.Logo) == 0 {
		this.Data["json"] = map[string]string{"error": "seemly an invalid shop"}
		this.ServeJson()
		return
	}
	wdShop := &models.WDShop{}
	wdShop.Uuid, err = strconv.ParseUint(id, 10, 64)
	if err != nil {
		beego.Error("read response error: ", err)
		this.Data["json"] = map[string]string{"error": "reading response error"}
		this.ServeJson()
		return
	}

	if wdShop.Get("uuid") != nil {
		endPos := strings.Index(shopInfo.Result.Logo, "?")
		wdShop.Logo = shopInfo.Result.Logo[:endPos]
		wdShop.Name = shopInfo.Result.ShopName
		wdShop.Note = shopInfo.Result.Note
		beego.Info("do insert shop record")
		wdShop.Insert()
	} else {
		endPos := strings.Index(shopInfo.Result.Logo, "?")
		wdShop.Logo = shopInfo.Result.Logo[:endPos]
		wdShop.Name = shopInfo.Result.ShopName
		wdShop.Note = shopInfo.Result.Note
		beego.Info("do update shop record")
		wdShop.Update("id")
	}

	// get item list
	// http://wd.koudai.com/wd/item/getIsTopList?param={"userid":215091300,"pageNum":0,"pageSize":49,"isTop":0,"f_seller_id":""}

	// get item detail
	// http://wd.koudai.com/wd/item/getPubInfo?param={"itemID":310148677,"page":1}

	this.Data["json"] = map[string]string{"ok": "200"}
	this.ServeJson()
}
<|endoftext|>


<commit_before>package gitgo

import (
	"fmt"
	"io"
)

// scanner functions similarly to bufio.Scanner,
// except that it never reads more input than necessary,
// which allow predictable consumption (and reuse) of readers
type scanner struct {
	r    io.Reader
	data []byte
	err  error
}

func (s *scanner) scan() bool {
	if s.err != nil {
		return false
	}
	s.data = s.read()
	return s.err == nil
}

func (s *scanner) Err() error {
	if s.err == io.EOF {
		return nil
	}
	return s.err
}

func (s *scanner) read() []byte {
	if s.err != nil {
		return nil
	}
	result := make([]byte, 1)
	n, err := s.r.Read(result)
	if err != nil {
		s.err = err
		return nil
	}
	if n == 0 {
		s.err = fmt.Errorf("read zero bytes")
	}
	return result
}

// ScanNullLines is like bufio.ScanLines, except it uses the null character as the delimiter
// instead of a newline
func ScanNullLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, '\x00'); i >= 0 {
		// We have a full null-terminated line.
		return i + 1, data[0:i], nil
	}
	// If we're at EOF, we have a final, non-terminated "line". Return it.
	if atEOF {
		return len(data), data, nil
	}
	// Request more data.
	return 0, nil, nil
}

// ScanLinesNoTrim is exactly like bufio.ScanLines, except it does not trim the newline
func ScanLinesNoTrim(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, '\n'); i >= 0 {
		// We have a full newline-terminated line.
		return i + 1, data[0 : i+1], nil
	}
	// If we're at EOF, we have a final, non-terminated line. Return it.
	if atEOF {
		return len(data), data, nil
	}
	// Request more data.
	return 0, nil, nil
}
<commit_msg>Fix imports<commit_after>package gitgo

import (
	"bytes"
	"fmt"
	"io"
)

// scanner functions similarly to bufio.Scanner,
// except that it never reads more input than necessary,
// which allow predictable consumption (and reuse) of readers
type scanner struct {
	r    io.Reader
	data []byte
	err  error
}

func (s *scanner) scan() bool {
	if s.err != nil {
		return false
	}
	s.data = s.read()
	return s.err == nil
}

func (s *scanner) Err() error {
	if s.err == io.EOF {
		return nil
	}
	return s.err
}

func (s *scanner) read() []byte {
	if s.err != nil {
		return nil
	}
	result := make([]byte, 1)
	n, err := s.r.Read(result)
	if err != nil {
		s.err = err
		return nil
	}
	if n == 0 {
		s.err = fmt.Errorf("read zero bytes")
	}
	return result
}

// ScanNullLines is like bufio.ScanLines, except it uses the null character as the delimiter
// instead of a newline
func ScanNullLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, '\x00'); i >= 0 {
		// We have a full null-terminated line.
		return i + 1, data[0:i], nil
	}
	// If we're at EOF, we have a final, non-terminated "line". Return it.
	if atEOF {
		return len(data), data, nil
	}
	// Request more data.
	return 0, nil, nil
}

// ScanLinesNoTrim is exactly like bufio.ScanLines, except it does not trim the newline
func ScanLinesNoTrim(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if i := bytes.IndexByte(data, '\n'); i >= 0 {
		// We have a full newline-terminated line.
		return i + 1, data[0 : i+1], nil
	}
	// If we're at EOF, we have a final, non-terminated line. Return it.
	if atEOF {
		return len(data), data, nil
	}
	// Request more data.
	return 0, nil, nil
}
<|endoftext|>


<commit_before>package masq

import (
	"bufio"
	"bytes"
	"io"
	"unicode"
)

const eof = rune(0)

type Lexeme struct {
	Type  TokenType
	Value string
}

// Scanner represents a lexical scanner.
type Scanner struct {
	init bool
	r    *bufio.Reader
}

// NewScanner returns a new instance of Scanner.
func NewScanner(r io.Reader) *Scanner {
	return &Scanner{r: bufio.NewReader(r)}
}

// read reads the next rune from the bufferred reader.
// Returns the rune(0) if an error occurs (or io.EOF is returned).
func (s *Scanner) read() rune {
	ch, _, err := s.r.ReadRune()
	if err != nil {
		return eof
	}

	return ch
}

func (s *Scanner) peek() rune {
	r := s.read()
	s.unread()

	return r
}

// scanWhitespace consumes the current rune and all contiguous whitespace.
func (s *Scanner) scanWhitespace() Lexeme {
	// Create a buffer and read the current character into it.
	var buf bytes.Buffer
	buf.WriteRune(s.read())

	// Read every subsequent whitespace character into the buffer.
	// Non-whitespace characters and EOF will cause the loop to exit.
	for {
		if ch := s.read(); ch == eof {
			break
		} else if !isWhitespace(ch) {
			s.unread()
			break
		} else {
			buf.WriteRune(ch)
		}
	}

	return Lexeme{TWhitespace, buf.String()}
}

// unread places the previously read rune back on the reader.
func (s *Scanner) unread() {
	err := s.r.UnreadRune()
	if err != nil {
		panic(err)
	}
}

// Scan returns the next token and literal value.
func (s *Scanner) Scan() Lexeme {
	// Read the next rune.
	ch := s.read()

	if isNewline(ch) || !s.init {
		s.init = true
		s.unread()
		return s.scanNewline()
	} else if isWhitespace(ch) {
		s.unread()
		return s.scanWhitespace()
	} else if isLetter(ch) {
		s.unread()
		return s.scanIdent()
	}

	if ch == '\'' || ch == '"' {
		s.unread()
		return s.scanString()
	}

	// Otherwise read the individual character.
	switch ch {
	case eof:
		return Lexeme{TEof, ""}
	case '*':
		return Lexeme{TAstrisk, string(ch)}
	case '-':
		return Lexeme{TSigned, string(ch)}
	case '=':
		pch := s.peek()
		if pch == '\'' || pch == '"' {
			peq := s.scanString()
			peq.Type = TEqualsString

			return peq
		}

		peq := s.scanIdent()
		peq.Type = TEqualsString

		return peq
	}

	return Lexeme{TIllegal, string(ch)}
}

func (s *Scanner) scanNewline() Lexeme {
	var buf bytes.Buffer

	for {
		nl := s.read()
		buf.WriteRune(nl)

		if nl == eof { // this needs to go here because unreading an EOF is an error.
			return Lexeme{TEof, buf.String()}
		} else if !isNewline(nl) && !isWhitespace(nl) {
			break
		}
	}

	s.unread()
	ch := s.read() // already in buffer

	switch ch {
	case '@':
		return Lexeme{TAtSignHeadingLine, buf.String()}
	case '#':
		return Lexeme{TOctoHeadingLine, buf.String()}
	case '!':
		return Lexeme{TExclaimLine, buf.String()}
	case '?':
		return Lexeme{TQuestionLine, buf.String()}
	case ':':
		return s.scanColonLine()
	case '-':
		return Lexeme{TDashLine, buf.String()}
	}

	return Lexeme{TIllegal, buf.String()}
}

func (s *Scanner) scanString() Lexeme {
	var buf bytes.Buffer

	mark := s.read()
	prev := eof

	for {
		if ch := s.read(); ch == eof {
			break
		} else if ch == mark && prev != '\\' {
			break
		} else {
			buf.WriteRune(ch)
			prev = ch
		}
	}

	return Lexeme{TString, buf.String()}
}

func (s *Scanner) scanColonLine() Lexeme {
	var buf bytes.Buffer

	if isWhitespace(s.peek()) {
		// this works... may just want to trim the result.
		s.scanWhitespace()
	}

	for {
		if ch := s.read(); ch == eof {
			break
		} else if isNewline(ch) {
			s.unread()
			break
		} else {
			buf.WriteRune(ch)
		}
	}

	return Lexeme{TColonLine, buf.String()}
}

func (s *Scanner) scanIdent() Lexeme {
	// Create a buffer and read the current character into it.
	var buf bytes.Buffer
	buf.WriteRune(s.read())

	// Read every subsequent ident character into the buffer.
	// Non-ident characters and EOF will cause the loop to exit.
	for {
		if ch := s.read(); ch == eof {
			break
		} else if !isLetter(ch) && !isDigit(ch) && ch != '_' {
			s.unread()
			break
		} else {
			buf.WriteRune(ch)
		}
	}

	// Otherwise return as a regular identifier.
	return Lexeme{TString, buf.String()}
}

// isWhitespace returns true if the rune is a space, tab, or newline.
func isWhitespace(ch rune) bool {
	return unicode.IsSpace(ch)
}

// isLetter returns true if the rune is a letter.
func isLetter(ch rune) bool {
	return unicode.IsLetter(ch)
}

// isDigit returns true if the rune is a digit.
func isDigit(ch rune) bool {
	// unicode class n includes junk we don't want
	return (ch >= '0' && ch <= '9')
}

func isNewline(ch rune) bool {
	return ch == rune(10) || ch == rune(13)
}
<commit_msg>T_ILLEGAL on EOF mid string<commit_after>package masq

import (
	"bufio"
	"bytes"
	"io"
	"unicode"
)

const eof = rune(0)

type Lexeme struct {
	Type  TokenType
	Value string
}

// Scanner represents a lexical scanner.
type Scanner struct {
	init bool
	r    *bufio.Reader
}

// NewScanner returns a new instance of Scanner.
func NewScanner(r io.Reader) *Scanner {
	return &Scanner{r: bufio.NewReader(r)}
}

// read reads the next rune from the bufferred reader.
// Returns the rune(0) if an error occurs (or io.EOF is returned).
func (s *Scanner) read() rune {
	ch, _, err := s.r.ReadRune()
	if err != nil {
		return eof
	}

	return ch
}

func (s *Scanner) peek() rune {
	r := s.read()
	s.unread()

	return r
}

// scanWhitespace consumes the current rune and all contiguous whitespace.
func (s *Scanner) scanWhitespace() Lexeme {
	// Create a buffer and read the current character into it.
	var buf bytes.Buffer
	buf.WriteRune(s.read())

	// Read every subsequent whitespace character into the buffer.
	// Non-whitespace characters and EOF will cause the loop to exit.
	for {
		if ch := s.read(); ch == eof {
			break
		} else if !isWhitespace(ch) {
			s.unread()
			break
		} else {
			buf.WriteRune(ch)
		}
	}

	return Lexeme{TWhitespace, buf.String()}
}

// unread places the previously read rune back on the reader.
func (s *Scanner) unread() {
	err := s.r.UnreadRune()
	if err != nil {
		panic(err)
	}
}

// Scan returns the next token and literal value.
func (s *Scanner) Scan() Lexeme {
	// Read the next rune.
	ch := s.read()

	if isNewline(ch) || !s.init {
		s.init = true
		s.unread()
		return s.scanNewline()
	} else if isWhitespace(ch) {
		s.unread()
		return s.scanWhitespace()
	} else if isLetter(ch) {
		s.unread()
		return s.scanIdent()
	}

	if ch == '\'' || ch == '"' {
		s.unread()
		return s.scanString()
	}

	// Otherwise read the individual character.
	switch ch {
	case eof:
		return Lexeme{TEof, ""}
	case '*':
		return Lexeme{TAstrisk, string(ch)}
	case '-':
		return Lexeme{TSigned, string(ch)}
	case '=':
		pch := s.peek()
		if pch == '\'' || pch == '"' {
			peq := s.scanString()
			peq.Type = TEqualsString

			return peq
		}

		peq := s.scanIdent()
		peq.Type = TEqualsString

		return peq
	}

	return Lexeme{TIllegal, string(ch)}
}

func (s *Scanner) scanNewline() Lexeme {
	var buf bytes.Buffer

	for {
		nl := s.read()
		buf.WriteRune(nl)

		if nl == eof { // this needs to go here because unreading an EOF is an error.
			return Lexeme{TEof, buf.String()}
		} else if !isNewline(nl) && !isWhitespace(nl) {
			break
		}
	}

	s.unread()
	ch := s.read() // already in buffer

	switch ch {
	case '@':
		return Lexeme{TAtSignHeadingLine, buf.String()}
	case '#':
		return Lexeme{TOctoHeadingLine, buf.String()}
	case '!':
		return Lexeme{TExclaimLine, buf.String()}
	case '?':
		return Lexeme{TQuestionLine, buf.String()}
	case ':':
		return s.scanColonLine()
	case '-':
		return Lexeme{TDashLine, buf.String()}
	}

	return Lexeme{TIllegal, buf.String()}
}

func (s *Scanner) scanString() Lexeme {
	var buf bytes.Buffer

	mark := s.read()
	prev := eof

	for {
		if ch := s.read(); ch == eof {
			return Lexeme{TIllegal, string(ch)}
		} else if ch == mark && prev != '\\' {
			break
		} else {
			buf.WriteRune(ch)
			prev = ch
		}
	}

	return Lexeme{TString, buf.String()}
}

func (s *Scanner) scanColonLine() Lexeme {
	var buf bytes.Buffer

	if isWhitespace(s.peek()) {
		// this works... may just want to trim the result.
		s.scanWhitespace()
	}

	for {
		if ch := s.read(); ch == eof {
			break
		} else if isNewline(ch) {
			s.unread()
			break
		} else {
			buf.WriteRune(ch)
		}
	}

	return Lexeme{TColonLine, buf.String()}
}

func (s *Scanner) scanIdent() Lexeme {
	// Create a buffer and read the current character into it.
	var buf bytes.Buffer
	buf.WriteRune(s.read())

	// Read every subsequent ident character into the buffer.
	// Non-ident characters and EOF will cause the loop to exit.
	for {
		if ch := s.read(); ch == eof {
			break
		} else if !isLetter(ch) && !isDigit(ch) && ch != '_' {
			s.unread()
			break
		} else {
			buf.WriteRune(ch)
		}
	}

	// Otherwise return as a regular identifier.
	return Lexeme{TString, buf.String()}
}

// isWhitespace returns true if the rune is a space, tab, or newline.
func isWhitespace(ch rune) bool {
	return unicode.IsSpace(ch)
}

// isLetter returns true if the rune is a letter.
func isLetter(ch rune) bool {
	return unicode.IsLetter(ch)
}

// isDigit returns true if the rune is a digit.
func isDigit(ch rune) bool {
	// unicode class n includes junk we don't want
	return (ch >= '0' && ch <= '9')
}

func isNewline(ch rune) bool {
	return ch == rune(10) || ch == rune(13)
}
<|endoftext|>


<commit_before>package action

import (
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"github.com/BluePecker/JwtAuth/daemon"
	"os"
	"fmt"
)

type Storage struct {
	Driver string
	Opts   string
}

type TLS struct {
	Key  string
	Cert string
}

type Args struct {
	PidFile  string
	LogFile  string
	LogLevel string
	Version  bool
	SockFile string
	Port     int
	Host     string
	Conf     string
	Secret   string
	Daemon   bool

	TLS     TLS
	Storage Storage
}

type RootCommand struct {
	Args  Args
	Cmd   *cobra.Command
	Viper *viper.Viper
}

var RootCmd *RootCommand = &RootCommand{}

func UsageTemplate() string {
	return `Usage:{{if .Runnable}}{{if .HasAvailableFlags}}
  {{appendIfNotPresent .UseLine "[OPTIONS] COMMAND [arg...]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
  {{ .CommandPath}} [command]
  {{end}}{{if gt .Aliases 0}}
Aliases:{{.NameAndAliases}}
{{end}}{{if .HasExample}}
Examples:{{ .Example }}
{{end}}{{ if .HasAvailableLocalFlags}}
Options:
{{.LocalFlags.FlagUsages | trimRightSpace}}
{{end}}{{ if .HasAvailableSubCommands}}
Commands:{{range .Commands}}{{if .IsAvailableCommand}}
  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}
{{end}}{{ if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}
  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableSubCommands }}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`
}

func init() {
	RootCmd.Viper = viper.GetViper()

	RootCmd.Cmd = &cobra.Command{
		SilenceErrors: true,
		Use:           "jwt",
		Short:         "Jwt auth server",
		Long:          "User login information verification service",
		RunE: func(cmd *cobra.Command, args []string) error {
			if _, err := os.Stat(RootCmd.Args.Conf); err == nil {
				RootCmd.Viper.SetConfigFile(RootCmd.Args.Conf)
				if err := RootCmd.Viper.ReadInConfig(); err != nil {
					return err
				}
			}

			fmt.Println(cmd, "------------", args)

			RootCmd.Args.Port = RootCmd.Viper.GetInt("port")
			RootCmd.Args.Host = RootCmd.Viper.GetString("host")
			RootCmd.Args.PidFile = RootCmd.Viper.GetString("pid")
			RootCmd.Args.LogLevel = RootCmd.Viper.GetString("log-level")
			RootCmd.Args.LogFile = RootCmd.Viper.GetString("log")
			RootCmd.Args.SockFile = RootCmd.Viper.GetString("unix-sock")
			RootCmd.Args.Secret = RootCmd.Viper.GetString("secret")
			RootCmd.Args.Version = RootCmd.Viper.GetBool("version")
			RootCmd.Args.Daemon = RootCmd.Viper.GetBool("daemon")

			RootCmd.Args.Storage.Driver = RootCmd.Viper.GetString("storage.driver")
			RootCmd.Args.Storage.Opts = RootCmd.Viper.GetString("storage.opts")
			RootCmd.Args.TLS.Key = RootCmd.Viper.GetString("tls.key")
			RootCmd.Args.TLS.Cert = RootCmd.Viper.GetString("tls.cert")

			// 开启SERVER服务
			daemon.NewStart(daemon.Options{
				PidFile:  RootCmd.Args.PidFile,
				LogLevel: RootCmd.Args.LogLevel,
				LogFile:  RootCmd.Args.LogFile,
				SockFile: RootCmd.Args.SockFile,
				Port:     RootCmd.Args.Port,
				Host:     RootCmd.Args.Host,
				TLS: daemon.TLS{
					Cert: RootCmd.Args.TLS.Cert,
					Key:  RootCmd.Args.TLS.Key,
				},
				Version: RootCmd.Args.Version,
				Daemon:  RootCmd.Args.Daemon,
				Storage: daemon.Storage{
					Driver: RootCmd.Args.Storage.Driver,
					Opts:   RootCmd.Args.Storage.Opts,
				},
				Secret: RootCmd.Args.Secret,
			})

			return nil
		},
	}
	RootCmd.Cmd.SetUsageTemplate(UsageTemplate())

	var PFlags *pflag.FlagSet = RootCmd.Cmd.Flags()

	PFlags.IntVarP(&RootCmd.Args.Port, "port", "p", 6010, "set the server listening port")
	PFlags.StringVarP(&RootCmd.Args.Host, "host", "", "127.0.0.1", "set the server bind host")
	PFlags.StringVarP(&RootCmd.Args.Conf, "config", "c", "/etc/jwt.json", "set configuration file")
	PFlags.BoolVarP(&RootCmd.Args.Version, "version", "v", false, "print version information and quit")
	PFlags.BoolVarP(&RootCmd.Args.Daemon, "daemon", "d", false, "enable daemon mode")
	PFlags.StringVarP(&RootCmd.Args.Secret, "secret", "s", "", "specify secret for jwt encode")
	PFlags.StringVarP(&RootCmd.Args.PidFile, "pid", "", "/var/run/jwt.pid", "path to use for daemon PID file")
	PFlags.StringVarP(&RootCmd.Args.LogLevel, "log-level", "l", "info", "set the logging level")
	PFlags.StringVarP(&RootCmd.Args.LogFile, "log", "", "/var/log/jwt.log", "path to use for log file")
	PFlags.StringVarP(&RootCmd.Args.SockFile, "unix-sock", "u", "/var/run/jwt.sock", "communication between the client and the daemon")
	PFlags.StringVarP(&RootCmd.Args.Storage.Driver, "storage-driver", "", "redis", "specify the storage driver")
	PFlags.StringVarP(&RootCmd.Args.Storage.Opts, "storage-opts", "", "redis://127.0.0.1:6379/1?PoolSize=20&MaxRetries=3&PoolTimeout=1000", "specify the storage uri")
	PFlags.StringVarP(&RootCmd.Args.TLS.Cert, "tlscert", "", "", "path to TLS certificate file")
	PFlags.StringVarP(&RootCmd.Args.TLS.Key, "tlskey", "", "", "path to TLS key file")

	RootCmd.Viper.BindPFlag("port", PFlags.Lookup("port"))
	RootCmd.Viper.BindPFlag("host", PFlags.Lookup("host"))
	RootCmd.Viper.BindPFlag("version", PFlags.Lookup("version"))
	RootCmd.Viper.BindPFlag("secret", PFlags.Lookup("secret"))
	RootCmd.Viper.BindPFlag("daemon", PFlags.Lookup("daemon"))
	RootCmd.Viper.BindPFlag("pid", PFlags.Lookup("pid"))
	RootCmd.Viper.BindPFlag("log", PFlags.Lookup("log"))
	RootCmd.Viper.BindPFlag("unix-sock", PFlags.Lookup("unix-sock"))
	RootCmd.Viper.BindPFlag("log-level", PFlags.Lookup("log-level"))
	RootCmd.Viper.BindPFlag("storage.driver", PFlags.Lookup("storage-driver"))
	RootCmd.Viper.BindPFlag("storage.opts", PFlags.Lookup("storage-opts"))
	RootCmd.Viper.BindPFlag("tls.cert", PFlags.Lookup("tlscert"))
	RootCmd.Viper.BindPFlag("tls.key", PFlags.Lookup("tlskey"))

	RootCmd.Cmd.AddCommand(StopCmd, TokenCmd, VersionCmd)
}
<commit_msg>remove println<commit_after>package action

import (
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"github.com/BluePecker/JwtAuth/daemon"
	"os"
	"fmt"
)

type Storage struct {
	Driver string
	Opts   string
}

type TLS struct {
	Key  string
	Cert string
}

type Args struct {
	PidFile  string
	LogFile  string
	LogLevel string
	Version  bool
	SockFile string
	Port     int
	Host     string
	Conf     string
	Secret   string
	Daemon   bool

	TLS     TLS
	Storage Storage
}

type RootCommand struct {
	Args  Args
	Cmd   *cobra.Command
	Viper *viper.Viper
}

var RootCmd *RootCommand = &RootCommand{}

func UsageTemplate() string {
	return `Usage:{{if .Runnable}}{{if .HasAvailableFlags}}
  {{appendIfNotPresent .UseLine "[OPTIONS] COMMAND [arg...]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
  {{ .CommandPath}} [command]
  {{end}}{{if gt .Aliases 0}}
Aliases:{{.NameAndAliases}}
{{end}}{{if .HasExample}}
Examples:{{ .Example }}
{{end}}{{ if .HasAvailableLocalFlags}}
Options:
{{.LocalFlags.FlagUsages | trimRightSpace}}
{{end}}{{ if .HasAvailableSubCommands}}
Commands:{{range .Commands}}{{if .IsAvailableCommand}}
  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}
{{end}}{{ if .HasAvailableInheritedFlags}}
Global Flags:
{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}
  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableSubCommands }}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`
}

func init() {
	RootCmd.Viper = viper.GetViper()

	RootCmd.Cmd = &cobra.Command{
		SilenceErrors: true,
		Use:           "jwt",
		Short:         "Jwt auth server",
		Long:          "User login information verification service",
		RunE: func(cmd *cobra.Command, args []string) error {
			if _, err := os.Stat(RootCmd.Args.Conf); err == nil {
				RootCmd.Viper.SetConfigFile(RootCmd.Args.Conf)
				if err := RootCmd.Viper.ReadInConfig(); err != nil {
					return err
				}
			}

			RootCmd.Args.Port = RootCmd.Viper.GetInt("port")
			RootCmd.Args.Host = RootCmd.Viper.GetString("host")
			RootCmd.Args.PidFile = RootCmd.Viper.GetString("pid")
			RootCmd.Args.LogLevel = RootCmd.Viper.GetString("log-level")
			RootCmd.Args.LogFile = RootCmd.Viper.GetString("log")
			RootCmd.Args.SockFile = RootCmd.Viper.GetString("unix-sock")
			RootCmd.Args.Secret = RootCmd.Viper.GetString("secret")
			RootCmd.Args.Version = RootCmd.Viper.GetBool("version")
			RootCmd.Args.Daemon = RootCmd.Viper.GetBool("daemon")

			RootCmd.Args.Storage.Driver = RootCmd.Viper.GetString("storage.driver")
			RootCmd.Args.Storage.Opts = RootCmd.Viper.GetString("storage.opts")
			RootCmd.Args.TLS.Key = RootCmd.Viper.GetString("tls.key")
			RootCmd.Args.TLS.Cert = RootCmd.Viper.GetString("tls.cert")

			// 开启SERVER服务
			daemon.NewStart(daemon.Options{
				PidFile:  RootCmd.Args.PidFile,
				LogLevel: RootCmd.Args.LogLevel,
				LogFile:  RootCmd.Args.LogFile,
				SockFile: RootCmd.Args.SockFile,
				Port:     RootCmd.Args.Port,
				Host:     RootCmd.Args.Host,
				TLS: daemon.TLS{
					Cert: RootCmd.Args.TLS.Cert,
					Key:  RootCmd.Args.TLS.Key,
				},
				Version: RootCmd.Args.Version,
				Daemon:  RootCmd.Args.Daemon,
				Storage: daemon.Storage{
					Driver: RootCmd.Args.Storage.Driver,
					Opts:   RootCmd.Args.Storage.Opts,
				},
				Secret: RootCmd.Args.Secret,
			})

			return nil
		},
	}
	RootCmd.Cmd.SetUsageTemplate(UsageTemplate())

	var PFlags *pflag.FlagSet = RootCmd.Cmd.Flags()

	PFlags.IntVarP(&RootCmd.Args.Port, "port", "p", 6010, "set the server listening port")
	PFlags.StringVarP(&RootCmd.Args.Host, "host", "", "127.0.0.1", "set the server bind host")
	PFlags.StringVarP(&RootCmd.Args.Conf, "config", "c", "/etc/jwt.json", "set configuration file")
	PFlags.BoolVarP(&RootCmd.Args.Version, "version", "v", false, "print version information and quit")
	PFlags.BoolVarP(&RootCmd.Args.Daemon, "daemon", "d", false, "enable daemon mode")
	PFlags.StringVarP(&RootCmd.Args.Secret, "secret", "s", "", "specify secret for jwt encode")
	PFlags.StringVarP(&RootCmd.Args.PidFile, "pid", "", "/var/run/jwt.pid", "path to use for daemon PID file")
	PFlags.StringVarP(&RootCmd.Args.LogLevel, "log-level", "l", "info", "set the logging level")
	PFlags.StringVarP(&RootCmd.Args.LogFile, "log", "", "/var/log/jwt.log", "path to use for log file")
	PFlags.StringVarP(&RootCmd.Args.SockFile, "unix-sock", "u", "/var/run/jwt.sock", "communication between the client and the daemon")
	PFlags.StringVarP(&RootCmd.Args.Storage.Driver, "storage-driver", "", "redis", "specify the storage driver")
	PFlags.StringVarP(&RootCmd.Args.Storage.Opts, "storage-opts", "", "redis://127.0.0.1:6379/1?PoolSize=20&MaxRetries=3&PoolTimeout=1000", "specify the storage uri")
	PFlags.StringVarP(&RootCmd.Args.TLS.Cert, "tlscert", "", "", "path to TLS certificate file")
	PFlags.StringVarP(&RootCmd.Args.TLS.Key, "tlskey", "", "", "path to TLS key file")

	RootCmd.Viper.BindPFlag("port", PFlags.Lookup("port"))
	RootCmd.Viper.BindPFlag("host", PFlags.Lookup("host"))
	RootCmd.Viper.BindPFlag("version", PFlags.Lookup("version"))
	RootCmd.Viper.BindPFlag("secret", PFlags.Lookup("secret"))
	RootCmd.Viper.BindPFlag("daemon", PFlags.Lookup("daemon"))
	RootCmd.Viper.BindPFlag("pid", PFlags.Lookup("pid"))
	RootCmd.Viper.BindPFlag("log", PFlags.Lookup("log"))
	RootCmd.Viper.BindPFlag("unix-sock", PFlags.Lookup("unix-sock"))
	RootCmd.Viper.BindPFlag("log-level", PFlags.Lookup("log-level"))
	RootCmd.Viper.BindPFlag("storage.driver", PFlags.Lookup("storage-driver"))
	RootCmd.Viper.BindPFlag("storage.opts", PFlags.Lookup("storage-opts"))
	RootCmd.Viper.BindPFlag("tls.cert", PFlags.Lookup("tlscert"))
	RootCmd.Viper.BindPFlag("tls.key", PFlags.Lookup("tlskey"))

	RootCmd.Cmd.AddCommand(StopCmd, TokenCmd, VersionCmd)
}
<|endoftext|>


<commit_before>package device

import (
	"bytes"
	"github.com/hemtjanst/hemtjanst/messaging"
	"reflect"
	"testing"
)

func TestNewDevice(t *testing.T) {
	d := NewDevice("test", &messaging.TestingMessenger{})
	if d.Topic != "test" {
		t.Errorf("Expected topic of %s, got %s", "test", d.Topic)
	}

	if d.HasFeature("") {
		t.Error("Expected false, got ", d.HasFeature(""))
	}
}

func TestPublishMeta(t *testing.T) {
	m := &messaging.TestingMessenger{}
	d := NewDevice("lightbulb/kitchen", m)
	err := d.PublishMeta()
	if err != nil {
		t.Error("Expected to successfully publish meta, got ", err)
	}

	if m.Action != "publish" {
		t.Error("Expected to publish, but tried to ", m.Action)
	}
	if !reflect.DeepEqual(m.Topic, []string{"lightbulb/kitchen/meta"}) {
		t.Error("Expected topic to be lightbulb/kitchen/meta, got ", m.Topic)
	}
	if m.Qos != 1 {
		t.Error("Expected QoS of 1, got ", m.Qos)
	}
	if !m.Persist {
		t.Error("Expected persist, got ", m.Persist)
	}
	msg := `{"Topic":"lightbulb/kitchen","name":"","manufacturer":"","model":"","serialNumber":"","type":"","feature":null}`
	if !bytes.Equal(m.Message, []byte(msg)) {
		t.Errorf("Expected %s, got %s", msg, string(m.Message))
	}
}

func TestFeatureSet(t *testing.T) {
	m := &messaging.TestingMessenger{}
	d := NewDevice("lightbulb", m)
	f := &Feature{GetTopic: "lightbulb/on/get", SetTopic: "lightbulb/on/set", devRef: d}
	d.Features = map[string]*Feature{}
	d.Features["on"] = f
	f.Set("1")

	if m.Action != "publish" {
		t.Error("Expected to publish, but instead tried to ", m.Action)
	}
	if !reflect.DeepEqual(m.Topic, []string{"lightbulb/on/set"}) {
		t.Error("Expected topic to be lightbulb/on/set, got ", m.Topic)
	}
	if m.Qos != 1 {
		t.Error("Expected QoS of 1, got ", m.Qos)
	}
	if m.Persist {
		t.Error("Expected message without persist, got ", m.Persist)
	}
	if !bytes.Equal(m.Message, []byte("1")) {
		t.Error("Expected message of 1, got ", string(m.Message))
	}
}

func TestFeatureOnSet(t *testing.T) {
	m := &messaging.TestingMessenger{}
	d := NewDevice("lightbulb", m)
	f := &Feature{GetTopic: "lightbulb/on/get", SetTopic: "lightbulb/on/set", devRef: d}
	d.Features = map[string]*Feature{}
	d.Features["on"] = f

	f.OnSet(func(messaging.Message) {
		return
	})
	if m.Action != "subscribe" {
		t.Error("Expected to subscribe, but instead tried to ", m.Action)
	}
	if !reflect.DeepEqual(m.Topic, []string{"lightbulb/on/set"}) {
		t.Error("Expected topic to be lightbulb/on/set, got ", m.Topic)
	}
	if m.Qos != 1 {
		t.Error("Expected QoS of 1, got ", m.Qos)
	}
	if m.Callback == nil {
		t.Error("Expected a callback, got nil")
	}
}

func TestFeatureUpdate(t *testing.T) {
	m := &messaging.TestingMessenger{}
	d := NewDevice("lightbulb", m)
	f := &Feature{GetTopic: "lightbulb/on/get", SetTopic: "lightbulb/on/set", devRef: d}
	d.Features = map[string]*Feature{}
	d.Features["on"] = f
	f.Update("1")

	if m.Action != "publish" {
		t.Error("Expected to publish, but instead tried to ", m.Action)
	}
	if !reflect.DeepEqual(m.Topic, []string{"lightbulb/on/get"}) {
		t.Error("Expected topic to be lightbulb/on/get, got ", m.Topic)
	}
	if m.Qos != 1 {
		t.Error("Expected QoS of 1, got ", m.Qos)
	}
	if !m.Persist {
		t.Error("Expected message to persist, got ", m.Persist)
	}
	if !bytes.Equal(m.Message, []byte("1")) {
		t.Error("Expected message of 1, got ", string(m.Message))
	}
}

func TestFeatureOnUpdate(t *testing.T) {
	m := &messaging.TestingMessenger{}
	d := NewDevice("lightbulb", m)
	f := &Feature{GetTopic: "lightbulb/on/get", SetTopic: "lightbulb/on/set", devRef: d}
	d.Features = map[string]*Feature{}
	d.Features["on"] = f

	f.OnUpdate(func(messaging.Message) {
		return
	})
	if m.Action != "subscribe" {
		t.Error("Expected to subscribe, but instead tried to ", m.Action)
	}
	if !reflect.DeepEqual(m.Topic, []string{"lightbulb/on/get"}) {
		t.Error("Expected topic to be lightbulb/on/get, got ", m.Topic)
	}
	if m.Qos != 1 {
		t.Error("Expected QoS of 1, got ", m.Qos)
	}
	if m.Callback == nil {
		t.Error("Expected a callback, got nil")
	}
}
<commit_msg>:microscope: Test error in `device.HasFeature()`<commit_after>package device

import (
	"bytes"
	"github.com/hemtjanst/hemtjanst/messaging"
	"reflect"
	"testing"
)

func TestNewDevice(t *testing.T) {
	d := NewDevice("test", &messaging.TestingMessenger{})
	if d.Topic != "test" {
		t.Errorf("Expected topic of %s, got %s", "test", d.Topic)
	}

	if d.HasFeature("") {
		t.Error("Expected false, got ", d.HasFeature(""))
	}

	f := &Feature{GetTopic: "lightbulb/on/get", SetTopic: "lightbulb/on/set", devRef: d}
	d.Features = map[string]*Feature{}
	d.Features["on"] = f

	if !d.HasFeature("on") {
		t.Error("Expected true, got ", d.HasFeature("on"))
	}
}

func TestPublishMeta(t *testing.T) {
	m := &messaging.TestingMessenger{}
	d := NewDevice("lightbulb/kitchen", m)
	err := d.PublishMeta()
	if err != nil {
		t.Error("Expected to successfully publish meta, got ", err)
	}

	if m.Action != "publish" {
		t.Error("Expected to publish, but tried to ", m.Action)
	}
	if !reflect.DeepEqual(m.Topic, []string{"lightbulb/kitchen/meta"}) {
		t.Error("Expected topic to be lightbulb/kitchen/meta, got ", m.Topic)
	}
	if m.Qos != 1 {
		t.Error("Expected QoS of 1, got ", m.Qos)
	}
	if !m.Persist {
		t.Error("Expected persist, got ", m.Persist)
	}
	msg := `{"Topic":"lightbulb/kitchen","name":"","manufacturer":"","model":"","serialNumber":"","type":"","feature":null}`
	if !bytes.Equal(m.Message, []byte(msg)) {
		t.Errorf("Expected %s, got %s", msg, string(m.Message))
	}
}

func TestFeatureSet(t *testing.T) {
	m := &messaging.TestingMessenger{}
	d := NewDevice("lightbulb", m)
	f := &Feature{GetTopic: "lightbulb/on/get", SetTopic: "lightbulb/on/set", devRef: d}
	d.Features = map[string]*Feature{}
	d.Features["on"] = f
	f.Set("1")

	if m.Action != "publish" {
		t.Error("Expected to publish, but instead tried to ", m.Action)
	}
	if !reflect.DeepEqual(m.Topic, []string{"lightbulb/on/set"}) {
		t.Error("Expected topic to be lightbulb/on/set, got ", m.Topic)
	}
	if m.Qos != 1 {
		t.Error("Expected QoS of 1, got ", m.Qos)
	}
	if m.Persist {
		t.Error("Expected message without persist, got ", m.Persist)
	}
	if !bytes.Equal(m.Message, []byte("1")) {
		t.Error("Expected message of 1, got ", string(m.Message))
	}
}

func TestFeatureOnSet(t *testing.T) {
	m := &messaging.TestingMessenger{}
	d := NewDevice("lightbulb", m)
	f := &Feature{GetTopic: "lightbulb/on/get", SetTopic: "lightbulb/on/set", devRef: d}
	d.Features = map[string]*Feature{}
	d.Features["on"] = f

	f.OnSet(func(messaging.Message) {
		return
	})
	if m.Action != "subscribe" {
		t.Error("Expected to subscribe, but instead tried to ", m.Action)
	}
	if !reflect.DeepEqual(m.Topic, []string{"lightbulb/on/set"}) {
		t.Error("Expected topic to be lightbulb/on/set, got ", m.Topic)
	}
	if m.Qos != 1 {
		t.Error("Expected QoS of 1, got ", m.Qos)
	}
	if m.Callback == nil {
		t.Error("Expected a callback, got nil")
	}
}

func TestFeatureUpdate(t *testing.T) {
	m := &messaging.TestingMessenger{}
	d := NewDevice("lightbulb", m)
	f := &Feature{GetTopic: "lightbulb/on/get", SetTopic: "lightbulb/on/set", devRef: d}
	d.Features = map[string]*Feature{}
	d.Features["on"] = f
	f.Update("1")

	if m.Action != "publish" {
		t.Error("Expected to publish, but instead tried to ", m.Action)
	}
	if !reflect.DeepEqual(m.Topic, []string{"lightbulb/on/get"}) {
		t.Error("Expected topic to be lightbulb/on/get, got ", m.Topic)
	}
	if m.Qos != 1 {
		t.Error("Expected QoS of 1, got ", m.Qos)
	}
	if !m.Persist {
		t.Error("Expected message to persist, got ", m.Persist)
	}
	if !bytes.Equal(m.Message, []byte("1")) {
		t.Error("Expected message of 1, got ", string(m.Message))
	}
}

func TestFeatureOnUpdate(t *testing.T) {
	m := &messaging.TestingMessenger{}
	d := NewDevice("lightbulb", m)
	f := &Feature{GetTopic: "lightbulb/on/get", SetTopic: "lightbulb/on/set", devRef: d}
	d.Features = map[string]*Feature{}
	d.Features["on"] = f

	f.OnUpdate(func(messaging.Message) {
		return
	})
	if m.Action != "subscribe" {
		t.Error("Expected to subscribe, but instead tried to ", m.Action)
	}
	if !reflect.DeepEqual(m.Topic, []string{"lightbulb/on/get"}) {
		t.Error("Expected topic to be lightbulb/on/get, got ", m.Topic)
	}
	if m.Qos != 1 {
		t.Error("Expected QoS of 1, got ", m.Qos)
	}
	if m.Callback == nil {
		t.Error("Expected a callback, got nil")
	}
}
<|endoftext|>


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

package recursion

// genPowerSet generates a power set of s[i:] into the ps.
func genPowerSet(i int, s, branch []interface{}, ps *[][]interface{}) {
	if i == len(s) {
		*ps = append(*ps, append([]interface{}(nil), branch...))
	} else {
		genPowerSet(i+1, s, append(branch, s[i]), ps) // Generate all subset that contain s[i].
		genPowerSet(i+1, s, branch, ps)               // Generate all subset that do not contain s[i].
	}
}

// PowerSetRec returns a power set of s (it uses recursion to generate the set).
// The time complexity is O(n*(2**n)). The space complexity is O(2**n)
// The returned boolean value is always true.
func PowerSetRec(s []interface{}) (ps [][]interface{}, ok bool) {
	genPowerSet(0, s, []interface{}(nil), &ps)
	return ps, true
}

// PowerSetItr returns a power set of s (it uses mapping to integer bits to generate the set).
// The time complexity is O(n*(2**n)). The space complexity is O(2**n)
// The nil, false is returned if the length of s is equal or bigger
// then size of int of actual architecture.
func PowerSetItr(s []interface{}) (ps [][]interface{}, ok bool) {
	if len(s) >= intSize {
		return ps, false
	}

	for i := 0; i < (1 << uint(len(s))); i++ {
		var ss []interface{}
		// x == 0 indicates sub-set end.
		// x &= (x - 1) ensures that the iteration count will be the same as number of bits set to 1 in x.
		for x := i; x > 0; x &= (x - 1) {
			lsb, i := x&-x, 0                    // x&-x is same as x&^(x - 1).
			for p := 1; lsb&p == 0; p = p << 1 { // lsb must always be greater then 0, which is always true 'cause x > 0.
				i++ // Compute the index of x's least significant bit.
			}
			ss = append(ss, s[i])
		}
		ps = append(ps, ss)
	}

	return ps, true
}
<commit_msg>Make recursion.PowerSetRec function more readable<commit_after>// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.

package recursion

// genPowerSet generates a power set of s[i:] into the ps.
func genPowerSet(i int, s, branch []interface{}, ps [][]interface{}) [][]interface{} {
	if i == len(s) {
		return append(ps, append([]interface{}(nil), branch...))
	}
	ps = genPowerSet(i+1, s, append(branch, s[i]), ps) // Generate all subset that contain s[i].
	ps = genPowerSet(i+1, s, branch, ps)               // Generate all subset that do not contain s[i].
	return ps
}

// PowerSetRec returns a power set of s (it uses recursion to generate the set).
// The time complexity is O(n*(2**n)). The space complexity is O(2**n)
// The returned boolean value is always true.
func PowerSetRec(s []interface{}) (ps [][]interface{}, ok bool) {
	return genPowerSet(0, s, nil, nil), true
}

// PowerSetItr returns a power set of s (it uses mapping to integer bits to generate the set).
// The time complexity is O(n*(2**n)). The space complexity is O(2**n)
// The nil, false is returned if the length of s is equal or bigger
// then size of int of actual architecture.
func PowerSetItr(s []interface{}) (ps [][]interface{}, ok bool) {
	if len(s) >= intSize {
		return ps, false
	}

	for i := 0; i < (1 << uint(len(s))); i++ {
		var ss []interface{}
		// x == 0 indicates sub-set end.
		// x &= (x - 1) ensures that the iteration count will be the same as number of bits set to 1 in x.
		for x := i; x > 0; x &= (x - 1) {
			lsb, i := x&-x, 0                    // x&-x is same as x&^(x - 1).
			for p := 1; lsb&p == 0; p = p << 1 { // lsb must always be greater then 0, which is always true 'cause x > 0.
				i++ // Compute the index of x's least significant bit.
			}
			ss = append(ss, s[i])
		}
		ps = append(ps, ss)
	}

	return ps, true
}
<|endoftext|>


<commit_before>// Copyright 2018 The ACH Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.

package ach

import (
	"testing"
)

// mockAddenda18 creates a mock Addenda18 record
func mockAddenda18() *Addenda18 {
	addenda18 := NewAddenda18()
	addenda18.ForeignCorrespondentBankName = "Bank of Germany"
	addenda18.ForeignCorrespondentBankIDNumberQualifier = "01"
	addenda18.ForeignCorrespondentBankIDNumber = "987987987654654"
	addenda18.ForeignCorrespondentBankBranchCountryCode = "DE"
	addenda18.SequenceNumber = 1
	addenda18.EntryDetailSequenceNumber = 0000001
	return addenda18
}

func mockAddenda18B() *Addenda18 {
	addenda18 := NewAddenda18()
	addenda18.ForeignCorrespondentBankName = "Bank of Spain"
	addenda18.ForeignCorrespondentBankIDNumberQualifier = "01"
	addenda18.ForeignCorrespondentBankIDNumber = "987987987123123"
	addenda18.ForeignCorrespondentBankBranchCountryCode = "ES"
	addenda18.SequenceNumber = 2
	addenda18.EntryDetailSequenceNumber = 0000002
	return addenda18
}

func mockAddenda18C() *Addenda18 {
	addenda18 := NewAddenda18()
	addenda18.ForeignCorrespondentBankName = "Bank of France"
	addenda18.ForeignCorrespondentBankIDNumberQualifier = "01"
	addenda18.ForeignCorrespondentBankIDNumber = "456456456987987"
	addenda18.ForeignCorrespondentBankBranchCountryCode = "FR"
	addenda18.SequenceNumber = 2
	addenda18.EntryDetailSequenceNumber = 0000003
	return addenda18
}

func mockAddenda18D() *Addenda18 {
	addenda18 := NewAddenda18()
	addenda18.ForeignCorrespondentBankName = "Bank of Turkey"
	addenda18.ForeignCorrespondentBankIDNumberQualifier = "01"
	addenda18.ForeignCorrespondentBankIDNumber = "12312345678910"
	addenda18.ForeignCorrespondentBankBranchCountryCode = "TR"
	addenda18.SequenceNumber = 2
	addenda18.EntryDetailSequenceNumber = 0000004
	return addenda18
}

func mockAddenda18E() *Addenda18 {
	addenda18 := NewAddenda18()
	addenda18.ForeignCorrespondentBankName = "Bank of United Kingdom"
	addenda18.ForeignCorrespondentBankIDNumberQualifier = "01"
	addenda18.ForeignCorrespondentBankIDNumber = "1234567890123456789012345678901234"
	addenda18.ForeignCorrespondentBankBranchCountryCode = "GB"
	addenda18.SequenceNumber = 2
	addenda18.EntryDetailSequenceNumber = 0000005
	return addenda18
}

// TestMockAddenda18 validates mockAddenda18
func TestMockAddenda18(t *testing.T) {
	addenda18 := mockAddenda18()
	if err := addenda18.Validate(); err != nil {
		t.Error("mockAddenda18 does not validate and will break other tests")
	}
	if addenda18.ForeignCorrespondentBankName != "Bank of Germany" {
		t.Error("ForeignCorrespondentBankName dependent default value has changed")
	}
	if addenda18.ForeignCorrespondentBankIDNumberQualifier != "01" {
		t.Error("ForeignCorrespondentBankIDNumberQualifier dependent default value has changed")
	}
	if addenda18.ForeignCorrespondentBankIDNumber != "987987987654654" {
		t.Error("ForeignCorrespondentBankIDNumber dependent default value has changed")
	}
	if addenda18.ForeignCorrespondentBankBranchCountryCode != "DE" {
		t.Error("ForeignCorrespondentBankBranchCountryCode dependent default value has changed")
	}
	if addenda18.EntryDetailSequenceNumber != 0000001 {
		t.Error("EntryDetailSequenceNumber dependent default value has changed")
	}
}

// ToDo: Add parse logic

// testAddenda18String validates that a known parsed file can be return to a string of the same value
func testAddenda18String(t testing.TB) {
	addenda18 := NewAddenda18()
	var line = "718Bank of United Kingdom             011234567890123456789012345678901234GB       00010000001"
	addenda18.Parse(line)

	if addenda18.String() != line {
		t.Errorf("Strings do not match")
	}
}

// TestAddenda18 String tests validating that a known parsed file can be return to a string of the same value
func TestAddenda18String(t *testing.T) {
	testAddenda18String(t)
}

// BenchmarkAddenda18 String benchmarks validating that a known parsed file can be return to a string of the same value
func BenchmarkAddenda18String(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18String(b)
	}
}

func TestValidateAddenda18RecordType(t *testing.T) {
	addenda18 := mockAddenda18()
	addenda18.recordType = "63"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "recordType" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

func TestAddenda18TypeCodeFieldInclusion(t *testing.T) {
	addenda18 := mockAddenda18()
	addenda18.typeCode = ""
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "TypeCode" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

func TestAddenda18FieldInclusion(t *testing.T) {
	addenda18 := mockAddenda18()
	addenda18.EntryDetailSequenceNumber = 0
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "EntryDetailSequenceNumber" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

func TestAddenda18FieldInclusionRecordType(t *testing.T) {
	addenda18 := mockAddenda18()
	addenda18.recordType = ""
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.Msg != msgFieldInclusion {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

//testAddenda18ForeignCorrespondentBankNameAlphaNumeric validates ForeignCorrespondentBankName is alphanumeric
func testAddenda18ForeignCorrespondentBankNameAlphaNumeric(t testing.TB) {
	addenda18 := mockAddenda18()
	addenda18.ForeignCorrespondentBankName = "®©"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "ForeignCorrespondentBankName" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

// TestAddenda18ForeignCorrespondentBankNameAlphaNumeric tests validating ForeignCorrespondentBankName is alphanumeric
func TestAddenda18ForeignCorrespondentBankNameAlphaNumeric(t *testing.T) {
	testAddenda18ForeignCorrespondentBankNameAlphaNumeric(t)

}

// BenchmarkAddenda18ForeignCorrespondentBankNameAlphaNumeric benchmarks ForeignCorrespondentBankName is alphanumeric
func BenchmarkAddenda18ForeignCorrespondentBankNameAlphaNumeric(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18ForeignCorrespondentBankNameAlphaNumeric(b)
	}
}

//testAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric validates ForeignCorrespondentBankIDNumberQualifier is alphanumeric
func testAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric(t testing.TB) {
	addenda18 := mockAddenda18()
	addenda18.ForeignCorrespondentBankIDNumberQualifier = "®©"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "ForeignCorrespondentBankIDNumberQualifier" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

// TestAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric tests validating ForeignCorrespondentBankIDNumberQualifier is alphanumeric
func TestAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric(t *testing.T) {
	testAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric(t)
}

// BenchmarkAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric benchmarks ForeignCorrespondentBankIDNumberQualifier is alphanumeric
func BenchmarkAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric(b)
	}
}

//testAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric validates ForeignCorrespondentBankBranchCountryCode is alphanumeric
func testAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric(t testing.TB) {
	addenda18 := mockAddenda18()
	addenda18.ForeignCorrespondentBankBranchCountryCode = "®©"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "ForeignCorrespondentBankBranchCountryCode" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

// TestAddenda18ForeignCorrespondentBankBranchCountryCodeNumeric tests validating ForeignCorrespondentBankBranchCountryCode is alphanumeric
func TestAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric(t *testing.T) {
	testAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric(t)
}

// BenchmarkAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric benchmarks ForeignCorrespondentBankBranchCountryCode is alphanumeric
func BenchmarkAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric(b)
	}
}

//testAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric validates ForeignCorrespondentBankIDNumber is alphanumeric
func testAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric(t testing.TB) {
	addenda18 := mockAddenda18()
	addenda18.ForeignCorrespondentBankIDNumber = "®©"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "ForeignCorrespondentBankIDNumber" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

// TestAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric tests validating ForeignCorrespondentBankIDNumber is alphanumeric
func TestAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric(t *testing.T) {
	testAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric(t)
}

// BenchmarkAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric benchmarks ForeignCorrespondentBankIDNumber is alphanumeric
func BenchmarkAddendaForeignCorrespondentBankIDNumberAlphaNumeric(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric(b)
	}
}

// testAddenda18ValidTypeCode validates Addenda18 TypeCode
func testAddenda18ValidTypeCode(t testing.TB) {
	addenda18 := mockAddenda18()
	addenda18.typeCode = "65"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "TypeCode" {
				t.Errorf("%T: %s", err, err)
			}
		} else {
			t.Errorf("%T: %s", err, err)
		}
	}
}

// TestAddenda18ValidTypeCode tests validating Addenda18 TypeCode
func TestAddenda18ValidTypeCode(t *testing.T) {
	testAddenda18ValidTypeCode(t)
}

// BenchmarkAddenda18ValidTypeCode benchmarks validating Addenda18 TypeCode
func BenchmarkAddenda18ValidTypeCode(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18ValidTypeCode(b)
	}
}

// testAddenda18TypeCode18 TypeCode is 18 if typeCode is a valid TypeCode
func testAddenda18TypeCode18(t testing.TB) {
	addenda18 := mockAddenda18()
	addenda18.typeCode = "05"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "TypeCode" {
				t.Errorf("%T: %s", err, err)
			}
		} else {
			t.Errorf("%T: %s", err, err)
		}
	}
}

// TestAddenda18TypeCode18 tests TypeCode is 18 if typeCode is a valid TypeCode
func TestAddenda18TypeCode18(t *testing.T) {
	testAddenda18TypeCode18(t)
}

// BenchmarkAddenda18TypeCode18 benchmarks TypeCode is 18 if typeCode is a valid TypeCode
func BenchmarkAddenda18TypeCode18(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18TypeCode18(b)
	}
}
<commit_msg>#211 gofmt and govet<commit_after>// Copyright 2018 The ACH Authors
// Use of this source code is governed by an Apache License
// license that can be found in the LICENSE file.

package ach

import (
	"testing"
)

// mockAddenda18 creates a mock Addenda18 record
func mockAddenda18() *Addenda18 {
	addenda18 := NewAddenda18()
	addenda18.ForeignCorrespondentBankName = "Bank of Germany"
	addenda18.ForeignCorrespondentBankIDNumberQualifier = "01"
	addenda18.ForeignCorrespondentBankIDNumber = "987987987654654"
	addenda18.ForeignCorrespondentBankBranchCountryCode = "DE"
	addenda18.SequenceNumber = 1
	addenda18.EntryDetailSequenceNumber = 0000001
	return addenda18
}

func mockAddenda18B() *Addenda18 {
	addenda18 := NewAddenda18()
	addenda18.ForeignCorrespondentBankName = "Bank of Spain"
	addenda18.ForeignCorrespondentBankIDNumberQualifier = "01"
	addenda18.ForeignCorrespondentBankIDNumber = "987987987123123"
	addenda18.ForeignCorrespondentBankBranchCountryCode = "ES"
	addenda18.SequenceNumber = 2
	addenda18.EntryDetailSequenceNumber = 0000002
	return addenda18
}

func mockAddenda18C() *Addenda18 {
	addenda18 := NewAddenda18()
	addenda18.ForeignCorrespondentBankName = "Bank of France"
	addenda18.ForeignCorrespondentBankIDNumberQualifier = "01"
	addenda18.ForeignCorrespondentBankIDNumber = "456456456987987"
	addenda18.ForeignCorrespondentBankBranchCountryCode = "FR"
	addenda18.SequenceNumber = 2
	addenda18.EntryDetailSequenceNumber = 0000003
	return addenda18
}

func mockAddenda18D() *Addenda18 {
	addenda18 := NewAddenda18()
	addenda18.ForeignCorrespondentBankName = "Bank of Turkey"
	addenda18.ForeignCorrespondentBankIDNumberQualifier = "01"
	addenda18.ForeignCorrespondentBankIDNumber = "12312345678910"
	addenda18.ForeignCorrespondentBankBranchCountryCode = "TR"
	addenda18.SequenceNumber = 2
	addenda18.EntryDetailSequenceNumber = 0000004
	return addenda18
}

func mockAddenda18E() *Addenda18 {
	addenda18 := NewAddenda18()
	addenda18.ForeignCorrespondentBankName = "Bank of United Kingdom"
	addenda18.ForeignCorrespondentBankIDNumberQualifier = "01"
	addenda18.ForeignCorrespondentBankIDNumber = "1234567890123456789012345678901234"
	addenda18.ForeignCorrespondentBankBranchCountryCode = "GB"
	addenda18.SequenceNumber = 2
	addenda18.EntryDetailSequenceNumber = 0000005
	return addenda18
}

// TestMockAddenda18 validates mockAddenda18
func TestMockAddenda18(t *testing.T) {
	addenda18 := mockAddenda18()
	if err := addenda18.Validate(); err != nil {
		t.Error("mockAddenda18 does not validate and will break other tests")
	}
	if addenda18.ForeignCorrespondentBankName != "Bank of Germany" {
		t.Error("ForeignCorrespondentBankName dependent default value has changed")
	}
	if addenda18.ForeignCorrespondentBankIDNumberQualifier != "01" {
		t.Error("ForeignCorrespondentBankIDNumberQualifier dependent default value has changed")
	}
	if addenda18.ForeignCorrespondentBankIDNumber != "987987987654654" {
		t.Error("ForeignCorrespondentBankIDNumber dependent default value has changed")
	}
	if addenda18.ForeignCorrespondentBankBranchCountryCode != "DE" {
		t.Error("ForeignCorrespondentBankBranchCountryCode dependent default value has changed")
	}
	if addenda18.EntryDetailSequenceNumber != 0000001 {
		t.Error("EntryDetailSequenceNumber dependent default value has changed")
	}
}

// ToDo: Add parse logic

// testAddenda18String validates that a known parsed file can be return to a string of the same value
func testAddenda18String(t testing.TB) {
	addenda18 := NewAddenda18()
	var line = "718Bank of United Kingdom             011234567890123456789012345678901234GB       00010000001"
	addenda18.Parse(line)

	if addenda18.String() != line {
		t.Errorf("Strings do not match")
	}
}

// TestAddenda18 String tests validating that a known parsed file can be return to a string of the same value
func TestAddenda18String(t *testing.T) {
	testAddenda18String(t)
}

// BenchmarkAddenda18 String benchmarks validating that a known parsed file can be return to a string of the same value
func BenchmarkAddenda18String(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18String(b)
	}
}

func TestValidateAddenda18RecordType(t *testing.T) {
	addenda18 := mockAddenda18()
	addenda18.recordType = "63"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "recordType" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

func TestAddenda18TypeCodeFieldInclusion(t *testing.T) {
	addenda18 := mockAddenda18()
	addenda18.typeCode = ""
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "TypeCode" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

func TestAddenda18FieldInclusion(t *testing.T) {
	addenda18 := mockAddenda18()
	addenda18.EntryDetailSequenceNumber = 0
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "EntryDetailSequenceNumber" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

func TestAddenda18FieldInclusionRecordType(t *testing.T) {
	addenda18 := mockAddenda18()
	addenda18.recordType = ""
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.Msg != msgFieldInclusion {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

//testAddenda18ForeignCorrespondentBankNameAlphaNumeric validates ForeignCorrespondentBankName is alphanumeric
func testAddenda18ForeignCorrespondentBankNameAlphaNumeric(t testing.TB) {
	addenda18 := mockAddenda18()
	addenda18.ForeignCorrespondentBankName = "®©"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "ForeignCorrespondentBankName" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

// TestAddenda18ForeignCorrespondentBankNameAlphaNumeric tests validating ForeignCorrespondentBankName is alphanumeric
func TestAddenda18ForeignCorrespondentBankNameAlphaNumeric(t *testing.T) {
	testAddenda18ForeignCorrespondentBankNameAlphaNumeric(t)

}

// BenchmarkAddenda18ForeignCorrespondentBankNameAlphaNumeric benchmarks ForeignCorrespondentBankName is alphanumeric
func BenchmarkAddenda18ForeignCorrespondentBankNameAlphaNumeric(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18ForeignCorrespondentBankNameAlphaNumeric(b)
	}
}

//testAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric validates ForeignCorrespondentBankIDNumberQualifier is alphanumeric
func testAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric(t testing.TB) {
	addenda18 := mockAddenda18()
	addenda18.ForeignCorrespondentBankIDNumberQualifier = "®©"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "ForeignCorrespondentBankIDNumberQualifier" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

// TestAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric tests validating ForeignCorrespondentBankIDNumberQualifier is alphanumeric
func TestAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric(t *testing.T) {
	testAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric(t)
}

// BenchmarkAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric benchmarks ForeignCorrespondentBankIDNumberQualifier is alphanumeric
func BenchmarkAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18ForeignCorrespondentBankIDQualifierAlphaNumeric(b)
	}
}

//testAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric validates ForeignCorrespondentBankBranchCountryCode is alphanumeric
func testAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric(t testing.TB) {
	addenda18 := mockAddenda18()
	addenda18.ForeignCorrespondentBankBranchCountryCode = "®©"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "ForeignCorrespondentBankBranchCountryCode" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

// TestAddenda18ForeignCorrespondentBankBranchCountryCodeNumeric tests validating ForeignCorrespondentBankBranchCountryCode is alphanumeric
func TestAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric(t *testing.T) {
	testAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric(t)
}

// BenchmarkAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric benchmarks ForeignCorrespondentBankBranchCountryCode is alphanumeric
func BenchmarkAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18ForeignCorrespondentBankBranchCountryCodeAlphaNumeric(b)
	}
}

//testAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric validates ForeignCorrespondentBankIDNumber is alphanumeric
func testAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric(t testing.TB) {
	addenda18 := mockAddenda18()
	addenda18.ForeignCorrespondentBankIDNumber = "®©"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "ForeignCorrespondentBankIDNumber" {
				t.Errorf("%T: %s", err, err)
			}
		}
	}
}

// TestAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric tests validating ForeignCorrespondentBankIDNumber is alphanumeric
func TestAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric(t *testing.T) {
	testAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric(t)
}

// BenchmarkAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric benchmarks ForeignCorrespondentBankIDNumber is alphanumeric
func BenchmarkAddendaForeignCorrespondentBankIDNumberAlphaNumeric(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18ForeignCorrespondentBankIDNumberAlphaNumeric(b)
	}
}

// testAddenda18ValidTypeCode validates Addenda18 TypeCode
func testAddenda18ValidTypeCode(t testing.TB) {
	addenda18 := mockAddenda18()
	addenda18.typeCode = "65"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "TypeCode" {
				t.Errorf("%T: %s", err, err)
			}
		} else {
			t.Errorf("%T: %s", err, err)
		}
	}
}

// TestAddenda18ValidTypeCode tests validating Addenda18 TypeCode
func TestAddenda18ValidTypeCode(t *testing.T) {
	testAddenda18ValidTypeCode(t)
}

// BenchmarkAddenda18ValidTypeCode benchmarks validating Addenda18 TypeCode
func BenchmarkAddenda18ValidTypeCode(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18ValidTypeCode(b)
	}
}

// testAddenda18TypeCode18 TypeCode is 18 if typeCode is a valid TypeCode
func testAddenda18TypeCode18(t testing.TB) {
	addenda18 := mockAddenda18()
	addenda18.typeCode = "05"
	if err := addenda18.Validate(); err != nil {
		if e, ok := err.(*FieldError); ok {
			if e.FieldName != "TypeCode" {
				t.Errorf("%T: %s", err, err)
			}
		} else {
			t.Errorf("%T: %s", err, err)
		}
	}
}

// TestAddenda18TypeCode18 tests TypeCode is 18 if typeCode is a valid TypeCode
func TestAddenda18TypeCode18(t *testing.T) {
	testAddenda18TypeCode18(t)
}

// BenchmarkAddenda18TypeCode18 benchmarks TypeCode is 18 if typeCode is a valid TypeCode
func BenchmarkAddenda18TypeCode18(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		testAddenda18TypeCode18(b)
	}
}
<|endoftext|>


<commit_before>// +build !windows,!plan9

package tty

import (
	"os"
	"testing"
	"time"

	"github.com/elves/elvish/edit/ui"
)

// timeout is the longest time the tests wait between writing something on
// the writer and reading it from the reader before declaring that the
// reader has a bug.
const timeoutInterval = 100 * time.Millisecond

func timeout() <-chan time.Time {
	return time.After(timeoutInterval)
}

var (
	theWriter   *os.File
	innerReader *os.File
	theReader   *reader
)

func TestMain(m *testing.M) {
	r, w, err := os.Pipe()
	if err != nil {
		panic("os.Pipe returned error, something is seriously wrong")
	}
	defer r.Close()
	defer w.Close()
	theWriter = w
	innerReader = r
	theReader = newReader(r)
	theReader.Start()
	defer theReader.Stop()

	os.Exit(m.Run())
}

var keyTests = []struct {
	input string
	want  Event
}{
	// Simple graphical key.
	{"x", KeyEvent{'x', 0}},
	{"X", KeyEvent{'X', 0}},
	{" ", KeyEvent{' ', 0}},

	// Ctrl key.
	{"\001", KeyEvent{'A', ui.Ctrl}},
	{"\033", KeyEvent{'[', ui.Ctrl}},

	// Ctrl-ish keys, but not thought as Ctrl keys by our reader.
	{"\n", KeyEvent{'\n', 0}},
	{"\t", KeyEvent{'\t', 0}},
	{"\x7f", KeyEvent{'\x7f', 0}}, // backspace

	// Alt plus simple graphical key.
	{"\033a", KeyEvent{'a', ui.Alt}},
	{"\033[", KeyEvent{'[', ui.Alt}},

	// G3-style key.
	{"\033OA", KeyEvent{ui.Up, 0}},
	{"\033OH", KeyEvent{ui.Home, 0}},

	// CSI-sequence key identified by the ending rune.
	{"\033[A", KeyEvent{ui.Up, 0}},
	{"\033[H", KeyEvent{ui.Home, 0}},
	// Test for all possible modifier
	{"\033[1;2A", KeyEvent{ui.Up, ui.Shift}},

	// CSI-sequence key with one argument, always ending in '~'.
	{"\033[1~", KeyEvent{ui.Home, 0}},
	{"\033[11~", KeyEvent{ui.F1, 0}},

	// CSI-sequence key with three arguments and ending in '~'. The first
	// argument is always 27, the second identifies the modifier and the last
	// identifies the key.
	{"\033[27;4;63~", KeyEvent{';', ui.Shift | ui.Alt}},
}

func TestKey(t *testing.T) {
	for _, test := range keyTests {
		theWriter.WriteString(test.input)
		select {
		case event := <-theReader.EventChan():
			if event != test.want {
				t.Errorf("Reader reads event %v, want %v", event, test.want)
			}
		case <-timeout():
			t.Errorf("Reader timed out")
		}
	}
}

// TestStopMakesUnderlyingFileAvailable tests that after calling Stop, the
// Reader no longer attempts to read from the underlying file, so it is
// available for use by others.
func TestStopMakesUnderlyingFileAvailable(t *testing.T) {
	theReader.Stop()
	defer theReader.Start()

	s := "lorem ipsum"
	theWriter.WriteString(s)
	gotChan := make(chan string)
	go func() {
		var buf [32]byte
		nr, err := innerReader.Read(buf[:])
		if err != nil {
			t.Errorf("inner.Read returns error: %v", err)
		}
		gotChan <- string(buf[:nr])
	}()
	select {
	case got := <-gotChan:
		if got != s {
			t.Errorf("got %q, want %q", got, s)
		}
	case <-time.After(time.Second):
		t.Error("inner.Read times out")
	}
}
<commit_msg>edit/tty: Add a test case for a race condition of Reader.<commit_after>// +build !windows,!plan9

package tty

import (
	"os"
	"testing"
	"time"

	"github.com/elves/elvish/edit/ui"
)

// timeout is the longest time the tests wait between writing something on
// the writer and reading it from the reader before declaring that the
// reader has a bug.
const timeoutInterval = 100 * time.Millisecond

func timeout() <-chan time.Time {
	return time.After(timeoutInterval)
}

var (
	theWriter   *os.File
	innerReader *os.File
	theReader   *reader
)

func TestMain(m *testing.M) {
	r, w, err := os.Pipe()
	if err != nil {
		panic("os.Pipe returned error, something is seriously wrong")
	}
	defer r.Close()
	defer w.Close()
	theWriter = w
	innerReader = r
	theReader = newReader(r)
	theReader.Start()
	defer theReader.Stop()

	os.Exit(m.Run())
}

var keyTests = []struct {
	input string
	want  Event
}{
	// Simple graphical key.
	{"x", KeyEvent{'x', 0}},
	{"X", KeyEvent{'X', 0}},
	{" ", KeyEvent{' ', 0}},

	// Ctrl key.
	{"\001", KeyEvent{'A', ui.Ctrl}},
	{"\033", KeyEvent{'[', ui.Ctrl}},

	// Ctrl-ish keys, but not thought as Ctrl keys by our reader.
	{"\n", KeyEvent{'\n', 0}},
	{"\t", KeyEvent{'\t', 0}},
	{"\x7f", KeyEvent{'\x7f', 0}}, // backspace

	// Alt plus simple graphical key.
	{"\033a", KeyEvent{'a', ui.Alt}},
	{"\033[", KeyEvent{'[', ui.Alt}},

	// G3-style key.
	{"\033OA", KeyEvent{ui.Up, 0}},
	{"\033OH", KeyEvent{ui.Home, 0}},

	// CSI-sequence key identified by the ending rune.
	{"\033[A", KeyEvent{ui.Up, 0}},
	{"\033[H", KeyEvent{ui.Home, 0}},
	// Test for all possible modifier
	{"\033[1;2A", KeyEvent{ui.Up, ui.Shift}},

	// CSI-sequence key with one argument, always ending in '~'.
	{"\033[1~", KeyEvent{ui.Home, 0}},
	{"\033[11~", KeyEvent{ui.F1, 0}},

	// CSI-sequence key with three arguments and ending in '~'. The first
	// argument is always 27, the second identifies the modifier and the last
	// identifies the key.
	{"\033[27;4;63~", KeyEvent{';', ui.Shift | ui.Alt}},
}

func TestKey(t *testing.T) {
	for _, test := range keyTests {
		theWriter.WriteString(test.input)
		select {
		case event := <-theReader.EventChan():
			if event != test.want {
				t.Errorf("Reader reads event %v, want %v", event, test.want)
			}
		case <-timeout():
			t.Errorf("Reader timed out")
		}
	}
}

// TestStopMakesUnderlyingFileAvailable tests that after calling Stop, the
// Reader no longer attempts to read from the underlying file, so it is
// available for use by others.
func TestStopMakesUnderlyingFileAvailable(t *testing.T) {
	theReader.Stop()
	defer theReader.Start()

	s := "lorem ipsum"
	theWriter.WriteString(s)
	gotChan := make(chan string)
	go func() {
		var buf [32]byte
		nr, err := innerReader.Read(buf[:])
		if err != nil {
			t.Errorf("inner.Read returns error: %v", err)
		}
		gotChan <- string(buf[:nr])
	}()
	select {
	case got := <-gotChan:
		if got != s {
			t.Errorf("got %q, want %q", got, s)
		}
	case <-time.After(time.Second):
		t.Error("inner.Read times out")
	}
}

// TestStartAfterStopIndeedStarts tests that calling Start very shortly after
// Stop puts the Reader the correct started state.
func TestStartAfterStopIndeedStarts(t *testing.T) {
	for i := 0; i < 100; i++ {
		theReader.Stop()
		theReader.Start()

		theWriter.WriteString("a")
		select {
		case event := <-theReader.EventChan():
			wantEvent := KeyEvent(ui.Key{'a', 0})
			if event != wantEvent {
				t.Errorf("After Stop and Start, Reader reads %v, want %v", event, wantEvent)
			}
		case <-timeout():
			t.Errorf("After Stop and Start, Reader timed out")
		}
	}
}
<|endoftext|>