<commit_before>package main

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

	"github.com/anthonyrego/gosmf/audio"
)

func main() {

	audio.Init()
	defer audio.Cleanup()

	// If sound does not exist, download one
	if _, err := os.Stat("img.jpg"); os.IsNotExist(err) {
		downloadFile("https://archive.org/download/Sound_Effects_3/DOORBELL.WAV", "door.wav")
	}
	sound := audio.LoadWav("door.wav")
	playRequest := sound.Play3D(0, 0, 0, 100)

	for audio.IsPlaying(playRequest) {
		fmt.Print("\rPlaying...")
	}
	fmt.Println("done")
}

func downloadFile(url string, filename string) {
	response, _ := http.Get(url)
	defer response.Body.Close()
	file, err := os.Create(filename)
	if err != nil {
		log.Fatal(err)
	}
	io.Copy(file, response.Body)
	file.Close()
}
<commit_msg>fix audio example<commit_after>package main

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

	"github.com/anthonyrego/gosmf/audio"
)

func main() {

	audio.Init()
	defer audio.Cleanup()

	// If sound does not exist, download one
	if _, err := os.Stat("door.wav"); os.IsNotExist(err) {
		downloadFile("https://archive.org/download/Sound_Effects_3/DOORBELL.WAV", "door.wav")
	}
	sound := audio.LoadWav("door.wav")
	playRequest := sound.Play3D(0, 0, 0, 100)

	for audio.IsPlaying(playRequest) {
		fmt.Print("\rPlaying...")
	}
	fmt.Println("done")
}

func downloadFile(url string, filename string) {
	response, _ := http.Get(url)
	defer response.Body.Close()
	file, err := os.Create(filename)
	if err != nil {
		log.Fatal(err)
	}
	io.Copy(file, response.Body)
	file.Close()
}
<|endoftext|>


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

// This package implements a basic LISP interpretor for embedding in a go program for scripting.
// This file contains the list access primitive functions.

package golisp

import (
	"fmt"
	"math"
)

func RegisterListFunctionsPrimitives() {
	MakePrimitiveFunction("map", ">=2", MapImpl)
	MakePrimitiveFunction("for-each", ">=2", ForEachImpl)
	MakePrimitiveFunction("any", ">=2", AnyImpl)
	MakePrimitiveFunction("every", ">=2", EveryImpl)
	MakePrimitiveFunction("reduce", "3", ReduceImpl)
	MakePrimitiveFunction("filter", "2", FilterImpl)
	MakePrimitiveFunction("remove", "2", RemoveImpl)
	MakePrimitiveFunction("memq", "2", MemqImpl)
	MakePrimitiveFunction("memv", "2", MemqImpl)
	MakePrimitiveFunction("member", "2", MemqImpl)
	MakePrimitiveFunction("memp", "2", FindTailImpl)
	MakePrimitiveFunction("find-tail", "2", FindTailImpl)
	MakePrimitiveFunction("find", "2", FindImpl)
}

func intMin(x, y int64) int64 {
	if x < y {
		return x
	} else {
		return y
	}
}

func MapImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError(fmt.Sprintf("map needs a function as its first argument, but got %s.", String(f)), env)
		return
	}

	var collections []*Data = make([]*Data, 0, Length(args)-1)
	var loopCount int64 = math.MaxInt64
	var col *Data
	for a := Cdr(args); NotNilP(a); a = Cdr(a) {
		col = Car(a)
		if !ListP(col) {
			err = ProcessError(fmt.Sprintf("map needs lists as its other arguments, but got %s.", String(col)), env)
			return
		}
		if NilP(col) || col == nil {
			return
		}
		collections = append(collections, col)
		loopCount = intMin(loopCount, int64(Length(col)))
	}

	if loopCount == math.MaxInt64 {
		return
	}

	var d []*Data = make([]*Data, 0, loopCount)
	var v *Data
	var a *Data
	for index := 1; index <= int(loopCount); index++ {
		mapArgs := make([]*Data, 0, len(collections))
		for _, mapArgCollection := range collections {
			a = Nth(mapArgCollection, index)
			mapArgs = append(mapArgs, a)
		}
		v, err = ApplyWithoutEval(f, ArrayToList(mapArgs), env)
		if err != nil {
			return
		}
		d = append(d, v)
	}

	return ArrayToList(d), nil
}

func ForEachImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError(fmt.Sprintf("foreach needs a function as its first argument, but got %s.", String(f)), env)
		return
	}

	var collections []*Data = make([]*Data, 0, Length(args)-1)
	var loopCount int64 = math.MaxInt64
	var col *Data
	for a := Cdr(args); NotNilP(a); a = Cdr(a) {
		col = Car(a)
		if !ListP(col) {
			err = ProcessError(fmt.Sprintf("foreach needs lists as its other arguments, but got %s.", String(col)), env)
			return
		}
		collections = append(collections, col)
		loopCount = intMin(loopCount, int64(Length(col)))
	}

	if loopCount == math.MaxInt64 {
		return
	}

	var a *Data
	for index := 1; index <= int(loopCount); index++ {
		mapArgs := make([]*Data, 0, len(collections))
		for _, mapArgCollection := range collections {
			a = Nth(mapArgCollection, index)
			mapArgs = append(mapArgs, a)
		}
		_, err = ApplyWithoutEval(f, ArrayToList(mapArgs), env)
		if err != nil {
			return
		}
	}

	return nil, nil
}

func AnyImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError(fmt.Sprintf("any needs a function as its first argument, but got %s.", String(f)), env)
		return
	}

	var collections []*Data = make([]*Data, 0, Length(args)-1)
	var loopCount int64 = math.MaxInt64
	var col *Data
	for a := Cdr(args); NotNilP(a); a = Cdr(a) {
		col = Car(a)
		if !ListP(col) {
			err = ProcessError(fmt.Sprintf("any needs lists as its other arguments, but got %s.", String(col)), env)
			return
		}
		collections = append(collections, col)
		loopCount = intMin(loopCount, int64(Length(col)))
	}

	if loopCount == math.MaxInt64 {
		return
	}

	var a *Data
	var b *Data
	for index := 0; index < int(loopCount); index++ {
		mapArgs := make([]*Data, 0, len(collections))
		for _, mapArgCollection := range collections {
			a = Nth(mapArgCollection, index+1) // Remove the +1 upon merging in v1.1 branch
			mapArgs = append(mapArgs, a)
		}
		b, err = ApplyWithoutEval(f, ArrayToList(mapArgs), env)
		if err != nil {
			return
		}

		if BooleanValue(b) {
			return LispTrue, nil
		}
	}

	return LispFalse, nil
}

func EveryImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError(fmt.Sprintf("every needs a function as its first argument, but got %s.", String(f)), env)
		return
	}

	var collections []*Data = make([]*Data, 0, Length(args)-1)
	var loopCount int64 = math.MaxInt64
	var col *Data
	for a := Cdr(args); NotNilP(a); a = Cdr(a) {
		col = Car(a)
		if !ListP(col) {
			err = ProcessError(fmt.Sprintf("every needs lists as its other arguments, but got %s.", String(col)), env)
			return
		}
		collections = append(collections, col)
		loopCount = intMin(loopCount, int64(Length(col)))
	}

	if loopCount == math.MaxInt64 {
		return
	}

	var a *Data
	var b *Data
	for index := 0; index < int(loopCount); index++ {
		mapArgs := make([]*Data, 0, len(collections))
		for _, mapArgCollection := range collections {
			a = Nth(mapArgCollection, index+1) // Remove the +1 upon merging in the v1.1 branch
			mapArgs = append(mapArgs, a)
		}
		b, err = ApplyWithoutEval(f, ArrayToList(mapArgs), env)
		if err != nil {
			return
		}

		if !BooleanValue(b) {
			return LispFalse, nil
		}
	}

	return LispTrue, nil
}

func ReduceImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError("reduce needs a function as its first argument", env)
		return
	}

	initial := Second(args)
	col := Third(args)

	if !ListP(col) {
		err = ProcessError("map needs a list as its third argument", env)
		return
	}

	if Length(col) == 0 {
		return initial, nil
	}

	if Length(col) == 1 {
		return Car(col), nil
	}

	result = Car(col)
	for c := Cdr(col); NotNilP(c); c = Cdr(c) {
		result, err = ApplyWithoutEval(f, InternalMakeList(result, Car(c)), env)
		if err != nil {
			return
		}
	}

	return
}

func FilterImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError(fmt.Sprintf("filter needs a function as its first argument, but got %s.", String(f)), env)
		return
	}

	col := Second(args)
	if !ListP(col) {
		err = ProcessError(fmt.Sprintf("filter needs a list as its second argument, but got %s.", String(col)), env)
		return
	}

	var d []*Data = make([]*Data, 0, Length(col))
	var v *Data
	for c := col; NotNilP(c); c = Cdr(c) {
		v, err = ApplyWithoutEval(f, Cons(Car(c), nil), env)
		if err != nil {
			return
		}
		if !BooleanP(v) {
			err = ProcessError("filter needs a predicate function as its first argument.", env)
			return
		}

		if BooleanValue(v) {
			d = append(d, Car(c))
		}
	}

	return ArrayToList(d), nil
}

func RemoveImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError(fmt.Sprintf("remove needs a function as its first argument, but got %s.", String(f)), env)
		return
	}

	col := Second(args)
	if !ListP(col) {
		err = ProcessError(fmt.Sprintf("remove needs a list as its second argument, but got %s.", String(col)), env)
		return
	}

	var d []*Data = make([]*Data, 0, Length(col))
	var v *Data
	for c := col; NotNilP(c); c = Cdr(c) {
		v, err = ApplyWithoutEval(f, Cons(Car(c), nil), env)
		if err != nil {
			return
		}
		if !BooleanP(v) {
			err = ProcessError("remove needs a predicate function as its first argument.", env)
			return
		}

		if !BooleanValue(v) {
			d = append(d, Car(c))
		}
	}

	return ArrayToList(d), nil
}

func MemqImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	key := First(args)

	l := Second(args)

	for c := l; NotNilP(c); c = Cdr(c) {
		if IsEqual(key, Car(c)) {
			return c, nil
		}
	}

	return LispFalse, nil
}

func FindTailImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError("find-tail/memp needs a function as its first argument", env)
		return
	}

	l := Second(args)
	if !ListP(l) {
		err = ProcessError(fmt.Sprintf("find-tail needs a list as its second argument, but got %s.", String(l)), env)
		return
	}

	var found *Data
	for c := l; NotNilP(c); c = Cdr(c) {
		found, err = ApplyWithoutEval(f, InternalMakeList(Car(c)), env)

		if !BooleanP(found) {
			err = ProcessError("find-tail needs a predicate function as its first argument.", env)
			return
		}
		if BooleanValue(found) {
			return c, nil
		}
	}

	return LispFalse, nil
}

func FindImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError("find needs a function as its first argument", env)
		return
	}

	l := Second(args)
	if !ListP(l) {
		err = ProcessError(fmt.Sprintf("find needs a list as its second argument, but got %s.", String(l)), env)
		return
	}

	var found *Data
	for c := l; NotNilP(c); c = Cdr(c) {
		found, err = ApplyWithoutEval(f, InternalMakeList(Car(c)), env)
		if !BooleanP(found) {
			err = ProcessError("find needs a predicate function as its first argument.", env)
			return
		}
		if BooleanValue(found) {
			return Car(c), nil
		}
	}

	return LispFalse, nil
}
<commit_msg>optimize map/for-each/any/every. don't re-traverse the list every step<commit_after>// Copyright 2014 SteelSeries ApS.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This package implements a basic LISP interpretor for embedding in a go program for scripting.
// This file contains the list access primitive functions.

package golisp

import (
	"fmt"
	"math"
)

func RegisterListFunctionsPrimitives() {
	MakePrimitiveFunction("map", ">=2", MapImpl)
	MakePrimitiveFunction("for-each", ">=2", ForEachImpl)
	MakePrimitiveFunction("any", ">=2", AnyImpl)
	MakePrimitiveFunction("every", ">=2", EveryImpl)
	MakePrimitiveFunction("reduce", "3", ReduceImpl)
	MakePrimitiveFunction("filter", "2", FilterImpl)
	MakePrimitiveFunction("remove", "2", RemoveImpl)
	MakePrimitiveFunction("memq", "2", MemqImpl)
	MakePrimitiveFunction("memv", "2", MemqImpl)
	MakePrimitiveFunction("member", "2", MemqImpl)
	MakePrimitiveFunction("memp", "2", FindTailImpl)
	MakePrimitiveFunction("find-tail", "2", FindTailImpl)
	MakePrimitiveFunction("find", "2", FindImpl)
}

func intMin(x, y int64) int64 {
	if x < y {
		return x
	} else {
		return y
	}
}

func MapImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError(fmt.Sprintf("map needs a function as its first argument, but got %s.", String(f)), env)
		return
	}

	var collections []*Data = make([]*Data, 0, Length(args)-1)
	var loopCount int64 = math.MaxInt64
	var col *Data
	for a := Cdr(args); NotNilP(a); a = Cdr(a) {
		col = Car(a)
		if !ListP(col) {
			err = ProcessError(fmt.Sprintf("map needs lists as its other arguments, but got %s.", String(col)), env)
			return
		}
		if NilP(col) || col == nil {
			return
		}
		collections = append(collections, col)
		loopCount = intMin(loopCount, int64(Length(col)))
	}

	if loopCount == math.MaxInt64 {
		return
	}

	var d []*Data = make([]*Data, 0, loopCount)
	var v *Data
	var a *Data
	for index := 1; index <= int(loopCount); index++ {
		mapArgs := make([]*Data, 0, len(collections))
		for key, mapArgCollection := range collections {
			a = Car(mapArgCollection)
			collections[key] = Cdr(mapArgCollection)
			mapArgs = append(mapArgs, a)
		}
		v, err = ApplyWithoutEval(f, ArrayToList(mapArgs), env)
		if err != nil {
			return
		}
		d = append(d, v)
	}

	return ArrayToList(d), nil
}

func ForEachImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError(fmt.Sprintf("foreach needs a function as its first argument, but got %s.", String(f)), env)
		return
	}

	var collections []*Data = make([]*Data, 0, Length(args)-1)
	var loopCount int64 = math.MaxInt64
	var col *Data
	for a := Cdr(args); NotNilP(a); a = Cdr(a) {
		col = Car(a)
		if !ListP(col) {
			err = ProcessError(fmt.Sprintf("foreach needs lists as its other arguments, but got %s.", String(col)), env)
			return
		}
		collections = append(collections, col)
		loopCount = intMin(loopCount, int64(Length(col)))
	}

	if loopCount == math.MaxInt64 {
		return
	}

	var a *Data
	for index := 1; index <= int(loopCount); index++ {
		mapArgs := make([]*Data, 0, len(collections))
		for key, mapArgCollection := range collections {
			a = Car(mapArgCollection)
			collections[key] = Cdr(mapArgCollection)
			mapArgs = append(mapArgs, a)
		}
		_, err = ApplyWithoutEval(f, ArrayToList(mapArgs), env)
		if err != nil {
			return
		}
	}

	return nil, nil
}

func AnyImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError(fmt.Sprintf("any needs a function as its first argument, but got %s.", String(f)), env)
		return
	}

	var collections []*Data = make([]*Data, 0, Length(args)-1)
	var loopCount int64 = math.MaxInt64
	var col *Data
	for a := Cdr(args); NotNilP(a); a = Cdr(a) {
		col = Car(a)
		if !ListP(col) {
			err = ProcessError(fmt.Sprintf("any needs lists as its other arguments, but got %s.", String(col)), env)
			return
		}
		collections = append(collections, col)
		loopCount = intMin(loopCount, int64(Length(col)))
	}

	if loopCount == math.MaxInt64 {
		return
	}

	var a *Data
	var b *Data
	for index := 0; index < int(loopCount); index++ {
		mapArgs := make([]*Data, 0, len(collections))
		for key, mapArgCollection := range collections {
			a = Car(mapArgCollection)
			collections[key] = Cdr(mapArgCollection)
			mapArgs = append(mapArgs, a)
		}
		b, err = ApplyWithoutEval(f, ArrayToList(mapArgs), env)
		if err != nil {
			return
		}

		if BooleanValue(b) {
			return LispTrue, nil
		}
	}

	return LispFalse, nil
}

func EveryImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError(fmt.Sprintf("every needs a function as its first argument, but got %s.", String(f)), env)
		return
	}

	var collections []*Data = make([]*Data, 0, Length(args)-1)
	var loopCount int64 = math.MaxInt64
	var col *Data
	for a := Cdr(args); NotNilP(a); a = Cdr(a) {
		col = Car(a)
		if !ListP(col) {
			err = ProcessError(fmt.Sprintf("every needs lists as its other arguments, but got %s.", String(col)), env)
			return
		}
		collections = append(collections, col)
		loopCount = intMin(loopCount, int64(Length(col)))
	}

	if loopCount == math.MaxInt64 {
		return
	}

	var a *Data
	var b *Data
	for index := 0; index < int(loopCount); index++ {
		mapArgs := make([]*Data, 0, len(collections))
		for key, mapArgCollection := range collections {
			a = Car(mapArgCollection)
			collections[key] = Cdr(mapArgCollection)
			mapArgs = append(mapArgs, a)
		}
		b, err = ApplyWithoutEval(f, ArrayToList(mapArgs), env)
		if err != nil {
			return
		}

		if !BooleanValue(b) {
			return LispFalse, nil
		}
	}

	return LispTrue, nil
}

func ReduceImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError("reduce needs a function as its first argument", env)
		return
	}

	initial := Second(args)
	col := Third(args)

	if !ListP(col) {
		err = ProcessError("map needs a list as its third argument", env)
		return
	}

	if Length(col) == 0 {
		return initial, nil
	}

	if Length(col) == 1 {
		return Car(col), nil
	}

	result = Car(col)
	for c := Cdr(col); NotNilP(c); c = Cdr(c) {
		result, err = ApplyWithoutEval(f, InternalMakeList(result, Car(c)), env)
		if err != nil {
			return
		}
	}

	return
}

func FilterImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError(fmt.Sprintf("filter needs a function as its first argument, but got %s.", String(f)), env)
		return
	}

	col := Second(args)
	if !ListP(col) {
		err = ProcessError(fmt.Sprintf("filter needs a list as its second argument, but got %s.", String(col)), env)
		return
	}

	var d []*Data = make([]*Data, 0, Length(col))
	var v *Data
	for c := col; NotNilP(c); c = Cdr(c) {
		v, err = ApplyWithoutEval(f, Cons(Car(c), nil), env)
		if err != nil {
			return
		}
		if !BooleanP(v) {
			err = ProcessError("filter needs a predicate function as its first argument.", env)
			return
		}

		if BooleanValue(v) {
			d = append(d, Car(c))
		}
	}

	return ArrayToList(d), nil
}

func RemoveImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError(fmt.Sprintf("remove needs a function as its first argument, but got %s.", String(f)), env)
		return
	}

	col := Second(args)
	if !ListP(col) {
		err = ProcessError(fmt.Sprintf("remove needs a list as its second argument, but got %s.", String(col)), env)
		return
	}

	var d []*Data = make([]*Data, 0, Length(col))
	var v *Data
	for c := col; NotNilP(c); c = Cdr(c) {
		v, err = ApplyWithoutEval(f, Cons(Car(c), nil), env)
		if err != nil {
			return
		}
		if !BooleanP(v) {
			err = ProcessError("remove needs a predicate function as its first argument.", env)
			return
		}

		if !BooleanValue(v) {
			d = append(d, Car(c))
		}
	}

	return ArrayToList(d), nil
}

func MemqImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	key := First(args)

	l := Second(args)

	for c := l; NotNilP(c); c = Cdr(c) {
		if IsEqual(key, Car(c)) {
			return c, nil
		}
	}

	return LispFalse, nil
}

func FindTailImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError("find-tail/memp needs a function as its first argument", env)
		return
	}

	l := Second(args)
	if !ListP(l) {
		err = ProcessError(fmt.Sprintf("find-tail needs a list as its second argument, but got %s.", String(l)), env)
		return
	}

	var found *Data
	for c := l; NotNilP(c); c = Cdr(c) {
		found, err = ApplyWithoutEval(f, InternalMakeList(Car(c)), env)

		if !BooleanP(found) {
			err = ProcessError("find-tail needs a predicate function as its first argument.", env)
			return
		}
		if BooleanValue(found) {
			return c, nil
		}
	}

	return LispFalse, nil
}

func FindImpl(args *Data, env *SymbolTableFrame) (result *Data, err error) {
	f := First(args)
	if !FunctionOrPrimitiveP(f) {
		err = ProcessError("find needs a function as its first argument", env)
		return
	}

	l := Second(args)
	if !ListP(l) {
		err = ProcessError(fmt.Sprintf("find needs a list as its second argument, but got %s.", String(l)), env)
		return
	}

	var found *Data
	for c := l; NotNilP(c); c = Cdr(c) {
		found, err = ApplyWithoutEval(f, InternalMakeList(Car(c)), env)
		if !BooleanP(found) {
			err = ProcessError("find needs a predicate function as its first argument.", env)
			return
		}
		if BooleanValue(found) {
			return Car(c), nil
		}
	}

	return LispFalse, nil
}
<|endoftext|>


<commit_before>// My mods to the Go implementation of Conway's Game of Life.
//
// based on https://golang.org/doc/play/life.go
//
package main

import (
	"bytes"
	"flag"
	"fmt"
	"math/rand"
	"os"
	"time"
)

const (
	deadcell = "  "
)

var (
	seed     int64
	gens     int
	skipto   int
	livename string
	livecell []byte
	icon     map[string]string
)

// Field represents a two-dimensional field of cells.
type Field struct {
	s    [][]bool
	w, h int
}

// NewField returns an empty field of the specified width and height.
func NewField(w, h int) *Field {
	s := make([][]bool, h)
	for i := range s {
		s[i] = make([]bool, w)
	}
	return &Field{s: s, w: w, h: h}
}

// Set sets the state of the specified cell to the given value.
func (f *Field) Set(x, y int, b bool) {
	f.s[y][x] = b
}

// Alive reports whether the specified cell is alive.
// If the x or y coordinates are outside the field boundaries they are wrapped
// toroidally. For instance, an x value of -1 is treated as width-1.
func (f *Field) Alive(x, y int) bool {
	x += f.w
	x %= f.w
	y += f.h
	y %= f.h
	return f.s[y][x]
}

// Next returns the state of the specified cell at the next time step.
func (f *Field) Next(x, y int) bool {
	// Count the adjacent cells that are alive.
	alive := 0
	for i := -1; i <= 1; i++ {
		for j := -1; j <= 1; j++ {
			if (j != 0 || i != 0) && f.Alive(x+i, y+j) {
				alive++
			}
		}
	}
	// Return next state according to the game rules:
	//   exactly 3 neighbors: on,
	//   exactly 2 neighbors: maintain current state,
	//   otherwise: off.
	return alive == 3 || alive == 2 && f.Alive(x, y)
}

// Life stores the state of a round of Conway's Game of Life.
type Life struct {
	a, b    *Field
	w, h, g int
}

// NewLife returns a new Life game state with a random initial state.
func NewLife(w, h int) *Life {
	a := NewField(w, h)
	for i := 0; i < (w * h / 4); i++ {
		a.Set(rand.Intn(w), rand.Intn(h), true)
	}
	return &Life{
		a: a, b: NewField(w, h),
		w: w, h: h,
	}
}

// Step advances the game by one instant, recomputing and updating all cells.
func (l *Life) step() {
	// Update the state of the next field (b) from the current field (a).
	for y := 0; y < l.h; y++ {
		for x := 0; x < l.w; x++ {
			l.b.Set(x, y, l.a.Next(x, y))
		}
	}
	// Swap fields a and b.
	l.a, l.b = l.b, l.a

	// increment generation count
	l.g++
}

// String returns the game board as a string.
func (l *Life) String() string {
	var buf bytes.Buffer
	for y := 0; y < l.h; y++ {
		for x := 0; x < l.w; x++ {
			cell := []byte(deadcell)
			if l.a.Alive(x, y) {
				cell = livecell
			}
			buf.Write(cell)
		}
		buf.WriteByte('\n')
	}
	return buf.String()
}

func (l *Life) showGeneration(nth int) {
	fmt.Printf("\n\nGeneration %v (%v of %v):\n\n%v", l.g, nth-skipto, gens, l)
}

func (l *Life) simulate(gens int, delay time.Duration) {

	fmt.Printf("\nConway's Game of Life\n")

	if skipto != 0 {
		fmt.Printf("\nStarting from generation %v...", skipto)
	}

	maxgen := gens + skipto
	skipto--
	for i := 0; i < maxgen; i++ {
		l.step()
		if skipto <= i {
			l.showGeneration(i)
			time.Sleep(delay)
		}
	}

	fmt.Printf("%v generations, %v x %v grid, seed=%v\n\n", l.g, l.h, l.w, seed)
}

func initSeed() {
	if seed == 0 {
		seed = time.Now().UnixNano()
	}
	rand.Seed(seed)
}

func initDisplay() {
	ding, ok := icon[livename]
	if !ok {
		ding = icon["whitedot"]
	}
	livecell = []byte(" " + ding)
}

func checkSkipping() {
	if skipto < 0 {
		skipto = 0
	}
}

func parseflags() (width, height, perSec int) {

	flag.Int64Var(&seed, "seed", 0,
		"seed for initial population (default random)")

	flag.IntVar(&perSec, "d", 5, "delay 1/`N` seconds between generations")
	flag.IntVar(&height, "h", 30, "height of simulation field")
	flag.IntVar(&width, "w", 30, "width of simulation field")
	flag.IntVar(&gens, "n", 20, "display up to `N` generations")
	flag.IntVar(&skipto, "from", 0, "display from generation `N`")
	flag.StringVar(&livename, "icon", "", "`name` of icon to use for live cells (default whitedot)")

	flag.Parse()

	initSeed()
	initDisplay()
	checkSkipping()

	return
}

func addUsageInfo() {

	icon = make(map[string]string)
	icon["aster-1"] = "\u2731"
	icon["aster-2"] = "\u2749"
	icon["bug"] = "\u2603"
	icon["circle-x"] = "\u2A02"
	icon["dot-star"] = "\u272A"
	icon["fat-x"] = "\u2716"
	icon["green-x"] = "\u274E"
	icon["man-dribble"] = "\u26F9"
	icon["man-yellow"] = "\u26B1"
	icon["no-entry"] = "\u26D4"
	icon["redhat"] = "\u26D1"
	icon["skull-x"] = "\u2620"
	icon["snowman"] = "\u26C4"
	icon["star"] = "\u2606"
	icon["whitedot"] = "\u26AA"

	defaultUsage := flag.Usage
	flag.Usage = func() {
		defaultUsage()
		fmt.Fprintf(os.Stderr,
			"\nAvailable icons for live cells:\n\n"+
				"Icon\tName\t\tDescription\n"+
				"----\t--------\t-----------\n"+
				icon["aster-1"]+"\taster-1\t\tAsterisk 1\n"+
				icon["aster-2"]+"\taster-2\t\tAsterisk 2\n"+
				icon["bug"]+"\tbug\t\tBug\n"+
				icon["circle-x"]+"\tcircle-x\tCircle with an X\n"+
				icon["dot-star"]+"\tdot-star\tDot with star\n"+
				icon["fat-x"]+"\tfat-x\t\tFat white X\n"+
				icon["green-x"]+"\tgreen-x\t\tGreen square with white X\n"+
				icon["man-dribble"]+"\tmad-dribble\tMan dribbling ball\n"+
				icon["man-yellow"]+"\tman-yellow\tLittle yellow man\n"+
				icon["no-entry"]+"\tno-entry\tNo entry sign\n"+
				icon["redhat"]+"\tredhat\t\tRed hardhat with white cross\n"+
				icon["skull-x"]+"\tskull-x\t\tSkull and crossbones\n"+
				icon["snowman"]+"\tsnowman\t\tSnowman\n"+
				icon["star"]+"\tstar\t\tStar\n"+
				icon["whitedot"]+"\twhitedot\tWhite dot (default)\n",
		)
	}
}

func main() {

	addUsageInfo()

	width, height, perSec := parseflags()

	NewLife(width, height).simulate(
		gens,
		time.Second/time.Duration(perSec),
	)
}
<commit_msg>More modifications to usage options<commit_after>// My mods to the Go implementation of Conway's Game of Life.
//
// based on https://golang.org/doc/play/life.go
//
package main

import (
	"bytes"
	"flag"
	"fmt"
	"math/rand"
	"os"
	"time"
)

const (
	deadcell = "  "
)

var (
	seed     int64
	gens     int
	skipto   int
	livename string
	livecell []byte
	icon     map[string]string
)

// Field represents a two-dimensional field of cells.
type Field struct {
	s    [][]bool
	w, h int
}

// NewField returns an empty field of the specified width and height.
func NewField(w, h int) *Field {
	s := make([][]bool, h)
	for i := range s {
		s[i] = make([]bool, w)
	}
	return &Field{s: s, w: w, h: h}
}

// Set sets the state of the specified cell to the given value.
func (f *Field) Set(x, y int, b bool) {
	f.s[y][x] = b
}

// Alive reports whether the specified cell is alive.
// If the x or y coordinates are outside the field boundaries they are wrapped
// toroidally. For instance, an x value of -1 is treated as width-1.
func (f *Field) Alive(x, y int) bool {
	x += f.w
	x %= f.w
	y += f.h
	y %= f.h
	return f.s[y][x]
}

// Next returns the state of the specified cell at the next time step.
func (f *Field) Next(x, y int) bool {
	// Count the adjacent cells that are alive.
	alive := 0
	for i := -1; i <= 1; i++ {
		for j := -1; j <= 1; j++ {
			if (j != 0 || i != 0) && f.Alive(x+i, y+j) {
				alive++
			}
		}
	}
	// Return next state according to the game rules:
	//   exactly 3 neighbors: on,
	//   exactly 2 neighbors: maintain current state,
	//   otherwise: off.
	return alive == 3 || alive == 2 && f.Alive(x, y)
}

// Life stores the state of a round of Conway's Game of Life.
type Life struct {
	a, b    *Field
	w, h, g int
}

// NewLife returns a new Life game state with a random initial state.
func NewLife(w, h int) *Life {
	a := NewField(w, h)
	for i := 0; i < (w * h / 4); i++ {
		a.Set(rand.Intn(w), rand.Intn(h), true)
	}
	return &Life{
		a: a, b: NewField(w, h),
		w: w, h: h,
	}
}

// Step advances the game by one instant, recomputing and updating all cells.
func (l *Life) step() {
	// Update the state of the next field (b) from the current field (a).
	for y := 0; y < l.h; y++ {
		for x := 0; x < l.w; x++ {
			l.b.Set(x, y, l.a.Next(x, y))
		}
	}
	// Swap fields a and b.
	l.a, l.b = l.b, l.a

	// increment generation count
	l.g++
}

// String returns the game board as a string.
func (l *Life) String() string {
	var buf bytes.Buffer
	for y := 0; y < l.h; y++ {
		for x := 0; x < l.w; x++ {
			cell := []byte(deadcell)
			if l.a.Alive(x, y) {
				cell = livecell
			}
			buf.Write(cell)
		}
		buf.WriteByte('\n')
	}
	return buf.String()
}

func (l *Life) showGeneration(nth int) {
	fmt.Printf("\n\nGeneration %v (%v of %v):\n\n%v", l.g, nth-skipto, gens, l)
}

func (l *Life) simulate(gens int, delay time.Duration) {

	fmt.Printf("\nConway's Game of Life\n")

	if skipto != 0 {
		fmt.Printf("\nStarting from generation %v...", skipto)
	}

	maxgen := gens + skipto
	skipto--
	for i := 0; i < maxgen; i++ {
		l.step()
		if skipto <= i {
			l.showGeneration(i)
			time.Sleep(delay)
		}
	}

	fmt.Printf("%v generations, %v x %v grid, seed=%v\n\n", l.g, l.h, l.w, seed)
}

func initSeed() {
	if seed == 0 {
		seed = time.Now().UnixNano()
	}
	rand.Seed(seed)
}

func initDisplay() {
	ding, ok := icon[livename]
	if !ok {
		ding = icon["whitedot"]
	}
	livecell = []byte(" " + ding)
}

func checkSkipping() {
	if skipto < 0 {
		skipto = 0
	}
}

func parseflags() (width, height, stepsPerSecond int) {

	flag.Int64Var(&seed, "seed", 0,
		"seed for initial population (default random)")

	flag.IntVar(&height, "y", 30, "height of simulation field")
	flag.IntVar(&width, "x", 30, "width of simulation field")
	flag.IntVar(&gens, "n", 20, "display up to `N` generations")
	flag.IntVar(&stepsPerSecond, "r", 5, "display `N` generations per second")
	flag.IntVar(&skipto, "s", 0, "start displaying from generation `N`")
	flag.StringVar(&livename, "icon", "", "`name` of icon to use for live cells (default whitedot)")

	flag.Parse()

	initSeed()
	initDisplay()
	checkSkipping()

	return
}

func usage() {

	icon = make(map[string]string)
	icon["aster-1"] = "\u2731"
	icon["aster-2"] = "\u2749"
	icon["bug"] = "\u2603"
	icon["circle-x"] = "\u2A02"
	icon["dot-star"] = "\u272A"
	icon["fat-x"] = "\u2716"
	icon["green-x"] = "\u274E"
	icon["man-dribble"] = "\u26F9"
	icon["man-yellow"] = "\u26B1"
	icon["no-entry"] = "\u26D4"
	icon["redhat"] = "\u26D1"
	icon["skull-x"] = "\u2620"
	icon["snowman"] = "\u26C4"
	icon["star"] = "\u2606"
	icon["whitedot"] = "\u26AA"

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: %s [-x] [-y] [-r] [-n] [-s] [-seed] [-icon]\n\nOptions:\n\n",
			os.Args[0])
		flag.PrintDefaults()
		fmt.Fprintf(os.Stderr,
			"\nAvailable icons for live cells:\n\n"+
				"Icon\tName\t\tDescription\n"+
				"----\t--------\t-----------\n"+
				icon["aster-1"]+"\taster-1\t\tAsterisk 1\n"+
				icon["aster-2"]+"\taster-2\t\tAsterisk 2\n"+
				icon["bug"]+"\tbug\t\tBug\n"+
				icon["circle-x"]+"\tcircle-x\tCircle with an X\n"+
				icon["dot-star"]+"\tdot-star\tDot with star\n"+
				icon["fat-x"]+"\tfat-x\t\tFat white X\n"+
				icon["green-x"]+"\tgreen-x\t\tGreen square with white X\n"+
				icon["man-dribble"]+"\tmad-dribble\tMan dribbling ball\n"+
				icon["man-yellow"]+"\tman-yellow\tLittle yellow man\n"+
				icon["no-entry"]+"\tno-entry\tNo entry sign\n"+
				icon["redhat"]+"\tredhat\t\tRed hardhat with white cross\n"+
				icon["skull-x"]+"\tskull-x\t\tSkull and crossbones\n"+
				icon["snowman"]+"\tsnowman\t\tSnowman\n"+
				icon["star"]+"\tstar\t\tStar\n"+
				icon["whitedot"]+"\twhitedot\tWhite dot (default)\n",
		)
	}
}

func main() {

	usage()

	width, height, stepsPerSecond := parseflags()

	NewLife(width, height).simulate(
		gens,
		time.Second/time.Duration(stepsPerSecond),
	)
}
<|endoftext|>


<commit_before>package proxy

import (
	"fmt"
	"log"
	"regexp"
	"strings"

	"github.com/andystanton/proxybastard/util"
	"github.com/clbanning/mxj"
)

func (mavenConfiguration MavenConfiguration) validate() error {
	return nil
}

func (mavenConfiguration MavenConfiguration) isEnabled() bool {
	return mavenConfiguration.Enabled
}

func (mavenConfiguration MavenConfiguration) suggestConfiguration() *Configuration {
	return nil
}

func (mavenConfiguration MavenConfiguration) addProxySettings(proxyHost string, proxyPort string, nonProxyHosts []string) {
	for _, mavenFile := range mavenConfiguration.Files {
		sanitisedPath := util.SanitisePath(mavenFile)
		util.WriteXML(sanitisedPath, addToMavenXML(util.LoadXML(sanitisedPath), proxyHost, proxyPort, nonProxyHosts))
	}
}

func (mavenConfiguration MavenConfiguration) removeProxySettings() {
	for _, mavenFile := range mavenConfiguration.Files {
		sanitisedPath := util.SanitisePath(mavenFile)
		util.WriteXML(sanitisedPath, removeFromMavenXML(util.LoadXML(sanitisedPath)))
	}
}

func addToMavenXML(settingsXML mxj.Map, proxyHost string, proxyPort string, nonProxyHosts []string) mxj.Map {
	proxies, err := buildProxyVars(proxyHost, proxyPort, nonProxyHosts, true).ValuesForPath("proxies")
	if err != nil {
		log.Fatal("Unable to find proxies data in generated xml", err)
	}
	settingsXML.SetValueForPath(proxies[0], "settings.proxies")
	return settingsXML
}

func removeFromMavenXML(settingsXML mxj.Map) mxj.Map {
	settingsXML.Remove("settings.proxies")
	return settingsXML
}

func buildProxyVars(proxyHost string, proxyPort string, nonProxyHosts []string, active bool) mxj.Map {
	shortHost := regexp.MustCompile("^http(s?)://").ReplaceAllString(proxyHost, "")
	nonProxyHostString := strings.Join(nonProxyHosts, ",")

	template := `
<proxies>
	<proxy>
		<id>http://%s:%s</id>
		<protocol>http</protocol>
		<host>%s</host>
		<port>%s</port>
		<nonProxyHosts>%s</nonProxyHosts>
		<active>%t</active>
	</proxy>
	<proxy>
		<id>https://%s:%s</id>
		<protocol>https</protocol>
		<host>%s</host>
		<port>%s</port>
		<nonProxyHosts>%s</nonProxyHosts>
		<active>%t</active>
	</proxy>
</proxies>`

	updated := fmt.Sprintf(template,
		shortHost, proxyPort, shortHost, proxyPort, nonProxyHostString, active,
		shortHost, proxyPort, shortHost, proxyPort, nonProxyHostString, active)

	xml, err := mxj.NewMapXml([]byte(updated))
	if err != nil {
		log.Fatal("Unable to generate required xml", err)
	}

	return xml
}
<commit_msg>add first stab at maven<commit_after>package proxy

import (
	"fmt"
	"log"
	"regexp"
	"strings"

	"github.com/andystanton/proxybastard/util"
	"github.com/clbanning/mxj"
)

func (mavenConfiguration MavenConfiguration) validate() error {
	return nil
}

func (mavenConfiguration MavenConfiguration) isEnabled() bool {
	return mavenConfiguration.Enabled
}

func (mavenConfiguration MavenConfiguration) suggestConfiguration() *Configuration {
	mavenExecutable := "mvn"
	mavenFile := "~/.m2/settings.xml"
	mavenFileSanitised := util.SanitisePath(mavenFile)

	_, err := util.ShellOut("which", []string{mavenExecutable})
	hasMaven := err == nil
	hasMavenFile := util.FileExists(mavenFileSanitised)

	if hasMaven && hasMavenFile {

		contents := util.LoadXML(mavenFileSanitised)
		suggestedProxy, suggestedPort, suggestedNonProxyHosts := extractProxyFromMavenXML(contents)

		return &Configuration{
			ProxyHost:     suggestedProxy,
			ProxyPort:     suggestedPort,
			NonProxyHosts: suggestedNonProxyHosts,
			Targets: &TargetsConfiguration{
				Maven: &MavenConfiguration{
					Enabled: true,
					Files:   []string{mavenFile},
				},
			},
		}
	}
	return nil
}

func (mavenConfiguration MavenConfiguration) addProxySettings(proxyHost string, proxyPort string, nonProxyHosts []string) {
	for _, mavenFile := range mavenConfiguration.Files {
		sanitisedPath := util.SanitisePath(mavenFile)
		util.WriteXML(sanitisedPath, addToMavenXML(util.LoadXML(sanitisedPath), proxyHost, proxyPort, nonProxyHosts))
	}
}

func (mavenConfiguration MavenConfiguration) removeProxySettings() {
	for _, mavenFile := range mavenConfiguration.Files {
		sanitisedPath := util.SanitisePath(mavenFile)
		util.WriteXML(sanitisedPath, removeFromMavenXML(util.LoadXML(sanitisedPath)))
	}
}

func addToMavenXML(settingsXML mxj.Map, proxyHost string, proxyPort string, nonProxyHosts []string) mxj.Map {
	proxies, err := buildProxyVars(proxyHost, proxyPort, nonProxyHosts, true).ValuesForPath("proxies")
	if err != nil {
		log.Fatal("Unable to find proxies data in generated xml", err)
	}
	settingsXML.SetValueForPath(proxies[0], "settings.proxies")
	return settingsXML
}

func removeFromMavenXML(settingsXML mxj.Map) mxj.Map {
	settingsXML.Remove("settings.proxies")
	return settingsXML
}

func buildProxyVars(proxyHost string, proxyPort string, nonProxyHosts []string, active bool) mxj.Map {
	shortHost := regexp.MustCompile("^http(s?)://").ReplaceAllString(proxyHost, "")
	nonProxyHostString := strings.Join(nonProxyHosts, ",")

	template := `
<proxies>
	<proxy>
		<id>http://%s:%s</id>
		<protocol>http</protocol>
		<host>%s</host>
		<port>%s</port>
		<nonProxyHosts>%s</nonProxyHosts>
		<active>%t</active>
	</proxy>
	<proxy>
		<id>https://%s:%s</id>
		<protocol>https</protocol>
		<host>%s</host>
		<port>%s</port>
		<nonProxyHosts>%s</nonProxyHosts>
		<active>%t</active>
	</proxy>
</proxies>`

	updated := fmt.Sprintf(template,
		shortHost, proxyPort, shortHost, proxyPort, nonProxyHostString, active,
		shortHost, proxyPort, shortHost, proxyPort, nonProxyHostString, active)

	xml, err := mxj.NewMapXml([]byte(updated))
	if err != nil {
		log.Fatal("Unable to generate required xml", err)
	}

	return xml
}

func extractProxyFromMavenXML(settingsXML mxj.Map) (string, string, []string) {
	var suggestedProxy string
	var suggestedPort string
	var suggestedNonProxyHosts []string

	if settingsXML.Exists("settings.proxies.proxy") {
		proxyElements, err := settingsXML.ValuesForPath("settings.proxies.proxy")
		if err == nil {
			for _, proxyElement := range proxyElements {
				if proxyElementMap, ok := proxyElement.(map[string]interface{}); ok {
					suggestedProxy = proxyElementMap["host"].(string)
					suggestedPort = proxyElementMap["port"].(string)
					suggestedNonProxyHosts = strings.Split(proxyElementMap["nonProxyHosts"].(string), ",")
				}
			}
		}
	}

	return suggestedProxy, suggestedPort, suggestedNonProxyHosts
}
<|endoftext|>


<commit_before>package core

type RecordBlockAdapter interface {
	Utilization() uint16
	Add(recordID uint32, data []byte) (uint16, uint16)
	ReadRecordData(localID uint16) string
}

const RECORD_HEADER_SIZE = uint16(12)

type recordBlockAdapter struct {
	block *DataBlock
}

type recordHeader struct {
	localID  uint16
	recordID uint32
	startsAt uint16
	size     uint16
}

func newRecordBlockAdapter(block *DataBlock) RecordBlockAdapter {
	return &recordBlockAdapter{block}
}

func (rba *recordBlockAdapter) Add(recordID uint32, data []byte) (uint16, uint16) {
	utilization := rba.Utilization()
	recordSize := uint16(len(data))

	// Records present on the block
	totalRecords := rba.block.ReadUint16(DATABLOCK_SIZE - 4)

	// Calculate where the record starts
	var recordPtr int
	if totalRecords == 0 {
		recordPtr = 0
	} else {
		lastHeaderPtr := DATABLOCK_SIZE - 8 - int(totalRecords*RECORD_HEADER_SIZE) - 1
		// Starts where the last record ends
		// FIXME: This will fail once we have deletion implemented
		recordPtr = int(rba.block.ReadUint16(lastHeaderPtr+4) + rba.block.ReadUint16(lastHeaderPtr+6))
	}

	// Header
	// 2 for utilization, 2 for total records, 4 for next / prev block pointers
	newHeaderPtr := (DATABLOCK_SIZE - 1) - 8
	newHeaderPtr -= int((totalRecords + 1) * RECORD_HEADER_SIZE)

	// Le ID
	rba.block.Write(newHeaderPtr, recordID)
	newHeaderPtr += 4

	// Where the record starts
	rba.block.Write(newHeaderPtr, uint16(recordPtr))
	newHeaderPtr += 2

	// Record size
	rba.block.Write(newHeaderPtr, recordSize)
	newHeaderPtr += 2

	// TODO: 4 bytes for chained rows

	// Le data
	rba.block.Write(recordPtr, data)
	totalRecords += 1
	utilization += RECORD_HEADER_SIZE + recordSize
	rba.block.Write(DATABLOCK_SIZE-2, utilization)
	rba.block.Write(DATABLOCK_SIZE-4, totalRecords)

	// Used as the rowid
	localID := totalRecords - 1
	bytesWritten := recordSize
	return bytesWritten, localID
}

func (rba *recordBlockAdapter) Utilization() uint16 {
	// A datablock will have at least 2 bytes to store its utilization, if it
	// is currently zero, it means it is a brand new block
	utilization := rba.block.ReadUint16(DATABLOCK_SIZE - 2)
	if utilization == 0 {
		utilization = 2
	}
	return utilization
}

func (rba *recordBlockAdapter) ReadRecordData(localID uint16) string {
	headerPtr := DATABLOCK_SIZE - 9
	headerPtr -= int((localID + 1) * RECORD_HEADER_SIZE)
	start := rba.block.ReadUint16(headerPtr + 4)
	end := start + rba.block.ReadUint16(headerPtr+6)
	return string(rba.block.Data[start:end])
}

// HACK: Temporary, meant to be around while we don't have a btree in place
func (rba *recordBlockAdapter) IDs() []uint32 {
	totalRecords := rba.block.ReadUint16(DATABLOCK_SIZE - 4)
	ids := []uint32{}

	for i := uint16(0); i < totalRecords; i++ {
		headerPtr := DATABLOCK_SIZE - 8
		headerPtr -= int((i+1)*RECORD_HEADER_SIZE) + 1
		ids = append(ids, rba.block.ReadUint32(headerPtr))
	}

	return ids
}
<commit_msg>Less magic numbers<commit_after>package core

type RecordBlockAdapter interface {
	Utilization() uint16
	Add(recordID uint32, data []byte) (uint16, uint16)
	ReadRecordData(localID uint16) string
}

const (
	HEADER_OFFSET_RECORD_ID    = 0
	HEADER_OFFSET_RECORD_START = 4
	HEADER_OFFSET_RECORD_SIZE  = HEADER_OFFSET_RECORD_START + 2
	RECORD_HEADER_SIZE         = uint16(12)

	POS_UTILIZATION   = DATABLOCK_SIZE - 2
	POS_TOTAL_RECORDS = POS_UTILIZATION - 2
	POS_NEXT_BLOCK    = POS_TOTAL_RECORDS - 2
	POS_PREV_BLOCK    = POS_NEXT_BLOCK - 2
	POS_FIRST_HEADER  = POS_PREV_BLOCK - RECORD_HEADER_SIZE - 1
)

type recordBlockAdapter struct {
	block *DataBlock
}

type recordHeader struct {
	localID  uint16
	recordID uint32
	startsAt uint16
	size     uint16
}

func newRecordBlockAdapter(block *DataBlock) RecordBlockAdapter {
	return &recordBlockAdapter{block}
}

func (rba *recordBlockAdapter) Add(recordID uint32, data []byte) (uint16, uint16) {
	utilization := rba.Utilization()
	recordSize := uint16(len(data))

	// Records present on the block
	totalRecords := rba.block.ReadUint16(POS_TOTAL_RECORDS)

	// Calculate where the record starts
	var recordPtr int
	if totalRecords == 0 {
		recordPtr = 0
	} else {
		// Starts where the last record ends
		lastHeaderPtr := int(POS_FIRST_HEADER) - int((totalRecords-1)*RECORD_HEADER_SIZE)
		// FIXME: This will fail once we have deletion implemented
		recordPtr = int(rba.block.ReadUint16(lastHeaderPtr+4) + rba.block.ReadUint16(lastHeaderPtr+6))
	}

	// Header
	newHeaderPtr := int(POS_FIRST_HEADER - totalRecords*RECORD_HEADER_SIZE)

	// Le ID
	rba.block.Write(newHeaderPtr+HEADER_OFFSET_RECORD_ID, recordID)

	// Where the record starts
	rba.block.Write(newHeaderPtr+HEADER_OFFSET_RECORD_START, uint16(recordPtr))

	// Record size
	rba.block.Write(newHeaderPtr+HEADER_OFFSET_RECORD_SIZE, recordSize)

	// TODO: 4 bytes for chained rows

	// Le data
	rba.block.Write(recordPtr, data)
	totalRecords += 1
	utilization += RECORD_HEADER_SIZE + recordSize
	rba.block.Write(POS_UTILIZATION, utilization)
	rba.block.Write(POS_TOTAL_RECORDS, totalRecords)

	// Used as the rowid
	localID := totalRecords - 1
	bytesWritten := recordSize
	return bytesWritten, localID
}

func (rba *recordBlockAdapter) Utilization() uint16 {
	// A datablock will have at least 2 bytes to store its utilization, if it
	// is currently zero, it means it is a brand new block
	utilization := rba.block.ReadUint16(POS_UTILIZATION)
	if utilization == 0 {
		utilization = 2
	}
	return utilization
}

func (rba *recordBlockAdapter) ReadRecordData(localID uint16) string {
	headerPtr := int(POS_FIRST_HEADER) - int(localID*RECORD_HEADER_SIZE)
	start := rba.block.ReadUint16(headerPtr + HEADER_OFFSET_RECORD_START)
	end := start + rba.block.ReadUint16(headerPtr+HEADER_OFFSET_RECORD_SIZE)
	return string(rba.block.Data[start:end])
}

// HACK: Temporary, meant to be around while we don't have a btree in place
func (rba *recordBlockAdapter) IDs() []uint32 {
	totalRecords := rba.block.ReadUint16(DATABLOCK_SIZE - 4)
	ids := []uint32{}

	for i := uint16(0); i < totalRecords; i++ {
		headerPtr := DATABLOCK_SIZE - 8
		headerPtr -= int((i+1)*RECORD_HEADER_SIZE) + 1
		ids = append(ids, rba.block.ReadUint32(headerPtr))
	}

	return ids
}
<|endoftext|>


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

package casbin

import (
	"strings"
	"sync"
)

// CachedEnforcer wraps Enforcer and provides decision cache
type CachedEnforcer struct {
	*Enforcer
	m           map[string]bool
	enableCache bool
	locker      *sync.RWMutex
}

// NewCachedEnforcer creates a cached enforcer via file or DB.
func NewCachedEnforcer(params ...interface{}) (*CachedEnforcer, error) {
	e := &CachedEnforcer{}
	var err error
	e.Enforcer, err = NewEnforcer(params...)
	if err != nil {
		return nil, err
	}

	e.enableCache = true
	e.m = make(map[string]bool)
	e.locker = new(sync.RWMutex)
	return e, nil
}

// EnableCache determines whether to enable cache on Enforce(). When enableCache is enabled, cached result (true | false) will be returned for previous decisions.
func (e *CachedEnforcer) EnableCache(enableCache bool) {
	e.enableCache = enableCache
}

// Enforce decides whether a "subject" can access a "object" with the operation "action", input parameters are usually: (sub, obj, act).
// if rvals is not string , ingore the cache
func (e *CachedEnforcer) Enforce(rvals ...interface{}) (bool, error) {
	if !e.enableCache {
		return e.Enforcer.Enforce(rvals...)
	}

	var key strings.Builder
	for _, rval := range rvals {
		if val, ok := rval.(string); ok {
			key.WriteString(val)
			key.WriteString("$$")
		} else {
			return e.Enforcer.Enforce(rvals...)
		}
	}

	if res, ok := e.getCachedResult(key.String()); ok {
		return res, nil
	}
	res, err := e.Enforcer.Enforce(rvals...)
	if err != nil {
		return false, err
	}

	e.setCachedResult(key.String(), res)
	return res, nil
}

func (e *CachedEnforcer) getCachedResult(key string) (res bool, ok bool) {
	e.locker.RLock()
	defer e.locker.RUnlock()
	res, ok = e.m[key]
	return
}

func (e *CachedEnforcer) setCachedResult(key string, res bool) {
	e.locker.Lock()
	defer e.locker.Unlock()
	e.m[key] = res
}

// InvalidateCache deletes all the existing cached decisions.
func (e *CachedEnforcer) InvalidateCache() {
	e.m = make(map[string]bool)
}
<commit_msg>fix: Make CachedEnforcer actually thread-safe<commit_after>// Copyright 2018 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package casbin

import (
	"strings"
	"sync"
	"sync/atomic"
)

// CachedEnforcer wraps Enforcer and provides decision cache
type CachedEnforcer struct {
	*Enforcer
	m           map[string]bool
	enableCache int32
	locker      *sync.RWMutex
}

// NewCachedEnforcer creates a cached enforcer via file or DB.
func NewCachedEnforcer(params ...interface{}) (*CachedEnforcer, error) {
	e := &CachedEnforcer{}
	var err error
	e.Enforcer, err = NewEnforcer(params...)
	if err != nil {
		return nil, err
	}

	e.enableCache = 1
	e.m = make(map[string]bool)
	e.locker = new(sync.RWMutex)
	return e, nil
}

// EnableCache determines whether to enable cache on Enforce(). When enableCache is enabled, cached result (true | false) will be returned for previous decisions.
func (e *CachedEnforcer) EnableCache(enableCache bool) {
	var enabled int32
	if enableCache {
		enabled = 1
	}
	atomic.StoreInt32(&e.enableCache, enabled)
}

// Enforce decides whether a "subject" can access a "object" with the operation "action", input parameters are usually: (sub, obj, act).
// if rvals is not string , ingore the cache
func (e *CachedEnforcer) Enforce(rvals ...interface{}) (bool, error) {
	if atomic.LoadInt32(&e.enableCache) == 0 {
		return e.Enforcer.Enforce(rvals...)
	}

	var key strings.Builder
	for _, rval := range rvals {
		if val, ok := rval.(string); ok {
			key.WriteString(val)
			key.WriteString("$$")
		} else {
			return e.Enforcer.Enforce(rvals...)
		}
	}

	if res, ok := e.getCachedResult(key.String()); ok {
		return res, nil
	}
	res, err := e.Enforcer.Enforce(rvals...)
	if err != nil {
		return false, err
	}

	e.setCachedResult(key.String(), res)
	return res, nil
}

func (e *CachedEnforcer) getCachedResult(key string) (res bool, ok bool) {
	e.locker.RLock()
	defer e.locker.RUnlock()
	res, ok = e.m[key]
	return
}

func (e *CachedEnforcer) setCachedResult(key string, res bool) {
	e.locker.Lock()
	defer e.locker.Unlock()
	e.m[key] = res
}

// InvalidateCache deletes all the existing cached decisions.
func (e *CachedEnforcer) InvalidateCache() {
	e.locker.Lock()
	defer e.locker.Unlock()
	e.m = make(map[string]bool)
}
<|endoftext|>


<commit_before>package openstack

import (
	"fmt"
	"log"

	"github.com/hashicorp/terraform/helper/schema"
	"github.com/rackspace/gophercloud"
	"github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules"
)

func resourceFWRuleV2() *schema.Resource {
	return &schema.Resource{
		Create: resourceFirewallRuleCreate,
		Read:   resourceFirewallRuleRead,
		Update: resourceFirewallRuleUpdate,
		Delete: resourceFirewallRuleDelete,

		Schema: map[string]*schema.Schema{
			"region": &schema.Schema{
				Type:        schema.TypeString,
				Required:    true,
				ForceNew:    true,
				DefaultFunc: envDefaultFunc("OS_REGION_NAME"),
			},
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
			"description": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
			"protocol": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
			},
			"action": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
			},
			"ip_version": &schema.Schema{
				Type:     schema.TypeInt,
				Optional: true,
				Default:  4,
			},
			"source_ip_address": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
			"destination_ip_address": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
			"source_port": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
			"destination_port": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
			"enabled": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Default:  true,
			},
			"tenant_id": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},
		},
	}
}

func resourceFirewallRuleCreate(d *schema.ResourceData, meta interface{}) error {

	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	enabled := d.Get("enabled").(bool)

	ruleConfiguration := rules.CreateOpts{
		Name:                 d.Get("name").(string),
		Description:          d.Get("description").(string),
		Protocol:             d.Get("protocol").(string),
		Action:               d.Get("action").(string),
		IPVersion:            d.Get("ip_version").(int),
		SourceIPAddress:      d.Get("source_ip_address").(string),
		DestinationIPAddress: d.Get("destination_ip_address").(string),
		SourcePort:           d.Get("source_port").(string),
		DestinationPort:      d.Get("destination_port").(string),
		Enabled:              &enabled,
		TenantID:             d.Get("tenant_id").(string),
	}

	log.Printf("[DEBUG] Create firewall rule: %#v", ruleConfiguration)

	rule, err := rules.Create(networkingClient, ruleConfiguration).Extract()

	if err != nil {
		return err
	}

	log.Printf("[DEBUG] Firewall rule with id %s : %#v", rule.ID, rule)

	d.SetId(rule.ID)

	return nil
}

func resourceFirewallRuleRead(d *schema.ResourceData, meta interface{}) error {
	log.Printf("[DEBUG] Retrieve information about firewall rule: %s", d.Id())

	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	rule, err := rules.Get(networkingClient, d.Id()).Extract()

	if err != nil {
		httpError, ok := err.(*gophercloud.UnexpectedResponseCodeError)
		if !ok {
			return err
		}
		if httpError.Actual == 404 {
			d.SetId("")
			return nil
		}
		return err
	}

	d.Set("name", rule.Name)
	d.Set("description", rule.Description)
	d.Set("protocol", rule.Protocol)
	d.Set("action", rule.Action)
	d.Set("ip_version", rule.IPVersion)
	d.Set("source_ip_address", rule.SourceIPAddress)
	d.Set("destination_ip_address", rule.DestinationIPAddress)
	d.Set("source_port", rule.SourcePort)
	d.Set("destination_port", rule.DestinationPort)
	d.Set("enabled", rule.Enabled)

	return nil
}

func resourceFirewallRuleUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	opts := rules.UpdateOpts{}

	if d.HasChange("name") {
		opts.Name = d.Get("name").(string)
	}
	if d.HasChange("description") {
		opts.Description = d.Get("description").(string)
	}
	if d.HasChange("protocol") {
		opts.Protocol = d.Get("protocol").(string)
	}
	if d.HasChange("action") {
		opts.Action = d.Get("action").(string)
	}
	if d.HasChange("ip_version") {
		opts.IPVersion = d.Get("ip_version").(int)
	}
	if d.HasChange("source_ip_address") {
		sourceIPAddress := d.Get("source_ip_address").(string)
		opts.SourceIPAddress = &sourceIPAddress
	}
	if d.HasChange("destination_ip_address") {
		destinationIPAddress := d.Get("destination_ip_address").(string)
		opts.DestinationIPAddress = &destinationIPAddress
	}
	if d.HasChange("source_port") {
		sourcePort := d.Get("source_port").(string)
		opts.SourcePort = &sourcePort
	}
	if d.HasChange("destination_port") {
		destinationPort := d.Get("destination_port").(string)
		opts.DestinationPort = &destinationPort
	}
	if d.HasChange("enabled") {
		enabled := d.Get("enabled").(bool)
		opts.Enabled = &enabled
	}

	log.Printf("[DEBUG] Updating firewall rules: %#v", opts)

	return rules.Update(networkingClient, d.Id(), opts).Err
}

func resourceFirewallRuleDelete(d *schema.ResourceData, meta interface{}) error {
	log.Printf("[DEBUG] Destroy firewall rule: %s", d.Id())

	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}
	return rules.Delete(networkingClient, d.Id()).Err
}
<commit_msg>Unassociate firewall rule from policy before delete<commit_after>package openstack

import (
	"fmt"
	"log"

	"github.com/hashicorp/terraform/helper/schema"
	"github.com/rackspace/gophercloud"
	"github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/policies"
	"github.com/rackspace/gophercloud/openstack/networking/v2/extensions/fwaas/rules"
)

func resourceFWRuleV2() *schema.Resource {
	return &schema.Resource{
		Create: resourceFirewallRuleCreate,
		Read:   resourceFirewallRuleRead,
		Update: resourceFirewallRuleUpdate,
		Delete: resourceFirewallRuleDelete,

		Schema: map[string]*schema.Schema{
			"region": &schema.Schema{
				Type:        schema.TypeString,
				Required:    true,
				ForceNew:    true,
				DefaultFunc: envDefaultFunc("OS_REGION_NAME"),
			},
			"name": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
			"description": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
			"protocol": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
			},
			"action": &schema.Schema{
				Type:     schema.TypeString,
				Required: true,
			},
			"ip_version": &schema.Schema{
				Type:     schema.TypeInt,
				Optional: true,
				Default:  4,
			},
			"source_ip_address": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
			"destination_ip_address": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
			"source_port": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
			"destination_port": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
			},
			"enabled": &schema.Schema{
				Type:     schema.TypeBool,
				Optional: true,
				Default:  true,
			},
			"tenant_id": &schema.Schema{
				Type:     schema.TypeString,
				Optional: true,
				ForceNew: true,
			},
		},
	}
}

func resourceFirewallRuleCreate(d *schema.ResourceData, meta interface{}) error {

	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	enabled := d.Get("enabled").(bool)

	ruleConfiguration := rules.CreateOpts{
		Name:                 d.Get("name").(string),
		Description:          d.Get("description").(string),
		Protocol:             d.Get("protocol").(string),
		Action:               d.Get("action").(string),
		IPVersion:            d.Get("ip_version").(int),
		SourceIPAddress:      d.Get("source_ip_address").(string),
		DestinationIPAddress: d.Get("destination_ip_address").(string),
		SourcePort:           d.Get("source_port").(string),
		DestinationPort:      d.Get("destination_port").(string),
		Enabled:              &enabled,
		TenantID:             d.Get("tenant_id").(string),
	}

	log.Printf("[DEBUG] Create firewall rule: %#v", ruleConfiguration)

	rule, err := rules.Create(networkingClient, ruleConfiguration).Extract()

	if err != nil {
		return err
	}

	log.Printf("[DEBUG] Firewall rule with id %s : %#v", rule.ID, rule)

	d.SetId(rule.ID)

	return nil
}

func resourceFirewallRuleRead(d *schema.ResourceData, meta interface{}) error {
	log.Printf("[DEBUG] Retrieve information about firewall rule: %s", d.Id())

	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	rule, err := rules.Get(networkingClient, d.Id()).Extract()

	if err != nil {
		httpError, ok := err.(*gophercloud.UnexpectedResponseCodeError)
		if !ok {
			return err
		}
		if httpError.Actual == 404 {
			d.SetId("")
			return nil
		}
		return err
	}

	d.Set("name", rule.Name)
	d.Set("description", rule.Description)
	d.Set("protocol", rule.Protocol)
	d.Set("action", rule.Action)
	d.Set("ip_version", rule.IPVersion)
	d.Set("source_ip_address", rule.SourceIPAddress)
	d.Set("destination_ip_address", rule.DestinationIPAddress)
	d.Set("source_port", rule.SourcePort)
	d.Set("destination_port", rule.DestinationPort)
	d.Set("enabled", rule.Enabled)

	return nil
}

func resourceFirewallRuleUpdate(d *schema.ResourceData, meta interface{}) error {
	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	opts := rules.UpdateOpts{}

	if d.HasChange("name") {
		opts.Name = d.Get("name").(string)
	}
	if d.HasChange("description") {
		opts.Description = d.Get("description").(string)
	}
	if d.HasChange("protocol") {
		opts.Protocol = d.Get("protocol").(string)
	}
	if d.HasChange("action") {
		opts.Action = d.Get("action").(string)
	}
	if d.HasChange("ip_version") {
		opts.IPVersion = d.Get("ip_version").(int)
	}
	if d.HasChange("source_ip_address") {
		sourceIPAddress := d.Get("source_ip_address").(string)
		opts.SourceIPAddress = &sourceIPAddress
	}
	if d.HasChange("destination_ip_address") {
		destinationIPAddress := d.Get("destination_ip_address").(string)
		opts.DestinationIPAddress = &destinationIPAddress
	}
	if d.HasChange("source_port") {
		sourcePort := d.Get("source_port").(string)
		opts.SourcePort = &sourcePort
	}
	if d.HasChange("destination_port") {
		destinationPort := d.Get("destination_port").(string)
		opts.DestinationPort = &destinationPort
	}
	if d.HasChange("enabled") {
		enabled := d.Get("enabled").(bool)
		opts.Enabled = &enabled
	}

	log.Printf("[DEBUG] Updating firewall rules: %#v", opts)

	return rules.Update(networkingClient, d.Id(), opts).Err
}

func resourceFirewallRuleDelete(d *schema.ResourceData, meta interface{}) error {
	log.Printf("[DEBUG] Destroy firewall rule: %s", d.Id())

	config := meta.(*Config)
	networkingClient, err := config.networkingV2Client(d.Get("region").(string))
	if err != nil {
		return fmt.Errorf("Error creating OpenStack networking client: %s", err)
	}

	rule, err := rules.Get(networkingClient, d.Id()).Extract()
	if err != nil {
		return err
	}

	if rule.PolicyID != "" {
		err := policies.RemoveRule(networkingClient, rule.PolicyID, rule.ID)
		if err != nil {
			return err
		}
	}

	return rules.Delete(networkingClient, d.Id()).Err
}
<|endoftext|>


<commit_before>package modelhelper

import (
	"fmt"
	"koding/db/models"

	"gopkg.in/mgo.v2/bson"
)

// FetchAdminAccounts fetches the admin accounts from database
func FetchAdminAccounts(groupName string) ([]models.Account, error) {
	group, err := GetGroup(groupName)
	if err != nil {
		return nil, err
	}

	selector := Selector{
		"sourceId":   group.Id,
		"sourceName": "JGroup",
		"as":         "admin",
	}

	rels, err := GetAllRelationships(selector)
	if err != nil {
		return nil, err
	}

	ids := make([]bson.ObjectId, len(rels))
	for i, rel := range rels {
		ids[i] = rel.TargetId
	}

	return GetAccountsByIds(ids)
}

// IsAdmin checks if the given username is an admin of the given groupName
func IsAdmin(username, groupName string) (bool, error) {
	group, err := GetGroup(groupName)
	if err != nil {
		return false, fmt.Errorf("getGroup(%s) err: %s", groupName, err)
	}

	account, err := GetAccount(username)
	if err != nil {
		return false, fmt.Errorf("getAccount(%s) err: %s", username, err)
	}

	selector := Selector{
		"sourceId":   group.Id,
		"sourceName": "JGroup",
		"targetId":   account.Id,
		"targetName": "JAccount",
		"as":         "admin",
	}

	count, err := RelationshipCount(selector)
	if err != nil {
		return false, fmt.Errorf("checkAdminRelationship err: %s", err)
	}

	return count == 1, nil
}

// FetchAccountGroups lists the group memberships of a given username
func FetchAccountGroups(username string) ([]string, error) {
	account, err := GetAccount(username)
	if err != nil {
		return nil, fmt.Errorf("getAccount(%s) err: %s", username, err)
	}

	selector := Selector{
		"sourceName": "JGroup",
		"targetId":   account.Id,
		"targetName": "JAccount",
		"as":         bson.M{"$in": []string{"owner", "admin", "member"}},
	}

	rels, err := GetAllRelationships(selector)
	if err != nil {
		return nil, err
	}

	if len(rels) == 0 {
		return nil, nil
	}

	var ids []string
	for _, rel := range rels {
		ids = append(ids, rel.SourceId.Hex())
	}

	groups, err := GetGroupFieldsByIds(ids, []string{"slug"})
	if err != nil {
		return nil, err
	}

	// unify the list
	slugs := make(map[string]struct{})
	for _, group := range groups {
		slugs[group.Slug] = struct{}{}
	}

	var slugList []string
	for slug := range slugs {
		slugList = append(slugList, slug)
	}

	return slugList, nil
}
<commit_msg>go: return errors without modifying it<commit_after>package modelhelper

import (
	"fmt"
	"koding/db/models"

	"gopkg.in/mgo.v2/bson"
)

// FetchAdminAccounts fetches the admin accounts from database
func FetchAdminAccounts(groupName string) ([]models.Account, error) {
	group, err := GetGroup(groupName)
	if err != nil {
		return nil, err
	}

	selector := Selector{
		"sourceId":   group.Id,
		"sourceName": "JGroup",
		"as":         "admin",
	}

	rels, err := GetAllRelationships(selector)
	if err != nil {
		return nil, err
	}

	ids := make([]bson.ObjectId, len(rels))
	for i, rel := range rels {
		ids[i] = rel.TargetId
	}

	return GetAccountsByIds(ids)
}

// IsAdmin checks if the given username is an admin of the given groupName
func IsAdmin(username, groupName string) (bool, error) {
	group, err := GetGroup(groupName)
	if err != nil {
		return false, fmt.Errorf("getGroup(%s) err: %s", groupName, err)
	}

	account, err := GetAccount(username)
	if err != nil {
		return false, fmt.Errorf("getAccount(%s) err: %s", username, err)
	}

	selector := Selector{
		"sourceId":   group.Id,
		"sourceName": "JGroup",
		"targetId":   account.Id,
		"targetName": "JAccount",
		"as":         "admin",
	}

	count, err := RelationshipCount(selector)
	if err != nil {
		return false, fmt.Errorf("checkAdminRelationship err: %s", err)
	}

	return count == 1, nil
}

// FetchAccountGroups lists the group memberships of a given username
func FetchAccountGroups(username string) ([]string, error) {
	account, err := GetAccount(username)
	if err != nil {
		return nil, err
	}

	selector := Selector{
		"sourceName": "JGroup",
		"targetId":   account.Id,
		"targetName": "JAccount",
		"as":         bson.M{"$in": []string{"owner", "admin", "member"}},
	}

	rels, err := GetAllRelationships(selector)
	if err != nil {
		return nil, err
	}

	if len(rels) == 0 {
		return nil, nil
	}

	var ids []string
	for _, rel := range rels {
		ids = append(ids, rel.SourceId.Hex())
	}

	groups, err := GetGroupFieldsByIds(ids, []string{"slug"})
	if err != nil {
		return nil, err
	}

	// unify the list
	slugs := make(map[string]struct{})
	for _, group := range groups {
		slugs[group.Slug] = struct{}{}
	}

	var slugList []string
	for slug := range slugs {
		slugList = append(slugList, slug)
	}

	return slugList, nil
}
<|endoftext|>


<commit_before>package db

import (
	"database/sql"
	"encoding/hex"
	"github.com/OpenBazaar/spvwallet"
	"github.com/btcsuite/btcd/chaincfg/chainhash"
	"github.com/btcsuite/btcd/wire"
	"strconv"
	"strings"
	"sync"
)

type StxoDB struct {
	db   *sql.DB
	lock *sync.Mutex
}

func (s *StxoDB) Put(stxo spvwallet.Stxo) error {
	s.lock.Lock()
	defer s.lock.Unlock()
	tx, _ := s.db.Begin()
	stmt, err := tx.Prepare("insert or replace into stxos(outpoint, value, height, scriptPubKey, watchOnly, spendHeight, spendTxid) values(?,?,?,?,?,?,?)")
	defer stmt.Close()
	if err != nil {
		tx.Rollback()
		return err
	}
	watchOnly := 0
	if stxo.Utxo.WatchOnly {
		watchOnly = 1
	}
	outpoint := stxo.Utxo.Op.Hash.String() + ":" + strconv.Itoa(int(stxo.Utxo.Op.Index))
	_, err = stmt.Exec(outpoint, int(stxo.Utxo.Value), int(stxo.Utxo.AtHeight), hex.EncodeToString(stxo.Utxo.ScriptPubkey), watchOnly, int(stxo.SpendHeight), stxo.SpendTxid.String())
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

func (s *StxoDB) GetAll() ([]spvwallet.Stxo, error) {
	s.lock.Lock()
	defer s.lock.Unlock()
	var ret []spvwallet.Stxo
	stm := "select outpoint, value, height, scriptPubKey, watchOnly, spendHeight, spendTxid from stxos"
	rows, err := s.db.Query(stm)
	defer rows.Close()
	if err != nil {
		return ret, err
	}
	for rows.Next() {
		var outpoint string
		var value int
		var height int
		var scriptPubKey string
		var watchOnlyInt int
		var spendHeight int
		var spendTxid string
		if err := rows.Scan(&outpoint, &value, &height, &scriptPubKey, &watchOnlyInt, &spendHeight, &spendTxid); err != nil {
			continue
		}
		s := strings.Split(outpoint, ":")
		if err != nil {
			continue
		}
		shaHash, err := chainhash.NewHashFromStr(s[0])
		if err != nil {
			continue
		}
		index, err := strconv.Atoi(s[1])
		if err != nil {
			continue
		}
		watchOnly := false
		if watchOnly > 0 {
			watchOnly = true
		}
		scriptBytes, err := hex.DecodeString(scriptPubKey)
		if err != nil {
			continue
		}
		spentHash, err := chainhash.NewHashFromStr(spendTxid)
		if err != nil {
			continue
		}
		utxo := spvwallet.Utxo{
			Op:           *wire.NewOutPoint(shaHash, uint32(index)),
			AtHeight:     int32(height),
			Value:        int64(value),
			ScriptPubkey: scriptBytes,
			WatchOnly:    watchOnly,
		}
		ret = append(ret, spvwallet.Stxo{
			Utxo:        utxo,
			SpendHeight: int32(spendHeight),
			SpendTxid:   *spentHash,
		})
	}
	return ret, nil
}

func (s *StxoDB) Delete(stxo spvwallet.Stxo) error {
	s.lock.Lock()
	defer s.lock.Unlock()
	outpoint := stxo.Utxo.Op.Hash.String() + ":" + strconv.Itoa(int(stxo.Utxo.Op.Index))
	_, err := s.db.Exec("delete from stxos where outpoint=?", outpoint)
	if err != nil {
		return err
	}
	return nil
}
<commit_msg>Fix stxo db example<commit_after>package db

import (
	"database/sql"
	"encoding/hex"
	"github.com/OpenBazaar/spvwallet"
	"github.com/btcsuite/btcd/chaincfg/chainhash"
	"github.com/btcsuite/btcd/wire"
	"strconv"
	"strings"
	"sync"
)

type StxoDB struct {
	db   *sql.DB
	lock *sync.Mutex
}

func (s *StxoDB) Put(stxo spvwallet.Stxo) error {
	s.lock.Lock()
	defer s.lock.Unlock()
	tx, _ := s.db.Begin()
	stmt, err := tx.Prepare("insert or replace into stxos(outpoint, value, height, scriptPubKey, watchOnly, spendHeight, spendTxid) values(?,?,?,?,?,?,?)")
	defer stmt.Close()
	if err != nil {
		tx.Rollback()
		return err
	}
	watchOnly := 0
	if stxo.Utxo.WatchOnly {
		watchOnly = 1
	}
	outpoint := stxo.Utxo.Op.Hash.String() + ":" + strconv.Itoa(int(stxo.Utxo.Op.Index))
	_, err = stmt.Exec(outpoint, int(stxo.Utxo.Value), int(stxo.Utxo.AtHeight), hex.EncodeToString(stxo.Utxo.ScriptPubkey), watchOnly, int(stxo.SpendHeight), stxo.SpendTxid.String())
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

func (s *StxoDB) GetAll() ([]spvwallet.Stxo, error) {
	s.lock.Lock()
	defer s.lock.Unlock()
	var ret []spvwallet.Stxo
	stm := "select outpoint, value, height, scriptPubKey, watchOnly, spendHeight, spendTxid from stxos"
	rows, err := s.db.Query(stm)
	defer rows.Close()
	if err != nil {
		return ret, err
	}
	for rows.Next() {
		var outpoint string
		var value int
		var height int
		var scriptPubKey string
		var watchOnlyInt int
		var spendHeight int
		var spendTxid string
		if err := rows.Scan(&outpoint, &value, &height, &scriptPubKey, &watchOnlyInt, &spendHeight, &spendTxid); err != nil {
			continue
		}
		s := strings.Split(outpoint, ":")
		if err != nil {
			continue
		}
		shaHash, err := chainhash.NewHashFromStr(s[0])
		if err != nil {
			continue
		}
		index, err := strconv.Atoi(s[1])
		if err != nil {
			continue
		}
		watchOnly := false
		if watchOnlyInt > 0 {
			watchOnly = true
		}
		scriptBytes, err := hex.DecodeString(scriptPubKey)
		if err != nil {
			continue
		}
		spentHash, err := chainhash.NewHashFromStr(spendTxid)
		if err != nil {
			continue
		}
		utxo := spvwallet.Utxo{
			Op:           *wire.NewOutPoint(shaHash, uint32(index)),
			AtHeight:     int32(height),
			Value:        int64(value),
			ScriptPubkey: scriptBytes,
			WatchOnly:    watchOnly,
		}
		ret = append(ret, spvwallet.Stxo{
			Utxo:        utxo,
			SpendHeight: int32(spendHeight),
			SpendTxid:   *spentHash,
		})
	}
	return ret, nil
}

func (s *StxoDB) Delete(stxo spvwallet.Stxo) error {
	s.lock.Lock()
	defer s.lock.Unlock()
	outpoint := stxo.Utxo.Op.Hash.String() + ":" + strconv.Itoa(int(stxo.Utxo.Op.Index))
	_, err := s.db.Exec("delete from stxos where outpoint=?", outpoint)
	if err != nil {
		return err
	}
	return nil
}
<|endoftext|>


<commit_before>/*
Copyright 2017 The Kubernetes Authors.

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

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

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

package framework

import (
	"fmt"
	"path"
	"strings"
	"time"

	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/apimachinery/pkg/version"
	"k8s.io/kubernetes/pkg/client/clientset_generated/clientset"
)

// RealVersion turns a version constants into a version string deployable on
// GKE.  See hack/get-build.sh for more information.
func RealVersion(s string) (string, error) {
	Logf("Getting real version for %q", s)
	v, _, err := RunCmd(path.Join(TestContext.RepoRoot, "hack/get-build.sh"), "-v", s)
	if err != nil {
		return v, err
	}
	Logf("Version for %q is %q", s, v)
	return strings.TrimPrefix(strings.TrimSpace(v), "v"), nil
}

func CheckMasterVersion(c clientset.Interface, want string) error {
	Logf("Checking master version")
	var err error
	var v *version.Info
	waitErr := wait.PollImmediate(5*time.Second, 2*time.Minute, func() (bool, error) {
		v, err = c.Discovery().ServerVersion()
		return err != nil, nil
	})
	if waitErr != nil {
		return fmt.Errorf("CheckMasterVersion() couldn't get the master version: %v", err)
	}
	// We do prefix trimming and then matching because:
	// want looks like:  0.19.3-815-g50e67d4
	// got  looks like: v0.19.3-815-g50e67d4034e858-dirty
	got := strings.TrimPrefix(v.GitVersion, "v")
	if !strings.HasPrefix(got, want) {
		return fmt.Errorf("master had kube-apiserver version %s which does not start with %s",
			got, want)
	}
	Logf("Master is at version %s", want)
	return nil
}

func CheckNodesVersions(cs clientset.Interface, want string) error {
	l := GetReadySchedulableNodesOrDie(cs)
	for _, n := range l.Items {
		// We do prefix trimming and then matching because:
		// want   looks like:  0.19.3-815-g50e67d4
		// kv/kvp look  like: v0.19.3-815-g50e67d4034e858-dirty
		kv, kpv := strings.TrimPrefix(n.Status.NodeInfo.KubeletVersion, "v"),
			strings.TrimPrefix(n.Status.NodeInfo.KubeProxyVersion, "v")
		if !strings.HasPrefix(kv, want) {
			return fmt.Errorf("node %s had kubelet version %s which does not start with %s",
				n.ObjectMeta.Name, kv, want)
		}
		if !strings.HasPrefix(kpv, want) {
			return fmt.Errorf("node %s had kube-proxy version %s which does not start with %s",
				n.ObjectMeta.Name, kpv, want)
		}
	}
	return nil
}
<commit_msg>Add traceroute logging on connection failure<commit_after>/*
Copyright 2017 The Kubernetes Authors.

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

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

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

package framework

import (
	"fmt"
	"os/exec"
	"path"
	"strings"
	"time"

	"k8s.io/apimachinery/pkg/util/wait"
	"k8s.io/apimachinery/pkg/version"
	"k8s.io/kubernetes/pkg/client/clientset_generated/clientset"
)

// RealVersion turns a version constants into a version string deployable on
// GKE.  See hack/get-build.sh for more information.
func RealVersion(s string) (string, error) {
	Logf("Getting real version for %q", s)
	v, _, err := RunCmd(path.Join(TestContext.RepoRoot, "hack/get-build.sh"), "-v", s)
	if err != nil {
		return v, err
	}
	Logf("Version for %q is %q", s, v)
	return strings.TrimPrefix(strings.TrimSpace(v), "v"), nil
}

func traceRouteToMaster() {
	path, err := exec.LookPath("traceroute")
	if err != nil {
		Logf("Could not find traceroute program")
		return
	}

	cmd := exec.Command(path, "-I", GetMasterHost())
	out, err := cmd.Output()
	if len(out) != 0 {
		Logf(string(out))
	}
	if exiterr, ok := err.(*exec.ExitError); err != nil && ok {
		Logf("error while running traceroute: %s", exiterr.Stderr)
	}
}

func CheckMasterVersion(c clientset.Interface, want string) error {
	Logf("Checking master version")
	var err error
	var v *version.Info
	waitErr := wait.PollImmediate(5*time.Second, 2*time.Minute, func() (bool, error) {
		v, err = c.Discovery().ServerVersion()
		if err != nil {
			traceRouteToMaster()
			return false, nil
		}
		return true, nil
	})
	if waitErr != nil {
		return fmt.Errorf("CheckMasterVersion() couldn't get the master version: %v", err)
	}
	// We do prefix trimming and then matching because:
	// want looks like:  0.19.3-815-g50e67d4
	// got  looks like: v0.19.3-815-g50e67d4034e858-dirty
	got := strings.TrimPrefix(v.GitVersion, "v")
	if !strings.HasPrefix(got, want) {
		return fmt.Errorf("master had kube-apiserver version %s which does not start with %s",
			got, want)
	}
	Logf("Master is at version %s", want)
	return nil
}

func CheckNodesVersions(cs clientset.Interface, want string) error {
	l := GetReadySchedulableNodesOrDie(cs)
	for _, n := range l.Items {
		// We do prefix trimming and then matching because:
		// want   looks like:  0.19.3-815-g50e67d4
		// kv/kvp look  like: v0.19.3-815-g50e67d4034e858-dirty
		kv, kpv := strings.TrimPrefix(n.Status.NodeInfo.KubeletVersion, "v"),
			strings.TrimPrefix(n.Status.NodeInfo.KubeProxyVersion, "v")
		if !strings.HasPrefix(kv, want) {
			return fmt.Errorf("node %s had kubelet version %s which does not start with %s",
				n.ObjectMeta.Name, kv, want)
		}
		if !strings.HasPrefix(kpv, want) {
			return fmt.Errorf("node %s had kube-proxy version %s which does not start with %s",
				n.ObjectMeta.Name, kpv, want)
		}
	}
	return nil
}
<|endoftext|>


<commit_before>package request

type NewGame struct {
	Map        string
	MaxPlayers int
}

type RegisterGame struct {
	MachineId int
	Port      int
}

type RegisterMachine struct {
	Port int
}
<commit_msg>authentication request<commit_after>package request

type NewGame struct {
	Map        string
	MaxPlayers int
}

type RegisterGame struct {
	MachineId int
	Port      int
}

type RegisterMachine struct {
	Port int
}

type Authentication struct {
	Username string
	Password string
}
<|endoftext|>