<commit_before>/*
The uuid package provides implementation of Universally Unique Identifier (UUID) structure
with functions for generating versions 1, 3, 4 and 5 as specified in RFC 4122
*/
package uuid

import (
	"crypto/md5"
	"crypto/rand"
	"crypto/sha1"
	"encoding/binary"
	"fmt"
	"hash"
	"net"
	"time"
)

// UUID layout variants.
const (
	VariantNCS = iota
	VariantRFC4122
	VariantMicrosoft
	VariantFuture
)

// Difference in 100-nanosecond intervals between
// UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970).
const epochStart = 122192928000000000

// Clock sequence storage
var clockSequence uint16

// UUID representation compliant with specification
// described in RFC 4122.
type UUID [16]byte

// Predefined namespace UUIDs.
var (
	NamespaceDNS  = UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
	NamespaceURL  = UUID{0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
	NamespaceOID  = UUID{0x6b, 0xa7, 0xb8, 0x12, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
	NamespaceX500 = UUID{0x6b, 0xa7, 0xb8, 0x14, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
)

// Returns algorithm version used to generate UUID.
// RFC 4122 describes version 1, 3, 4 and 5.
func (u *UUID) Version() uint {
	return uint(u[6] >> 4)
}

// Returns UUID layout variant.
func (u *UUID) Variant() uint {
	switch {
	case (u[8] & 0x80) == 0x00:
		return VariantNCS
	case (u[8]&0xc0)|0x80 == 0x80:
		return VariantRFC4122
	case (u[8]&0xe0)|0xc0 == 0xc0:
		return VariantMicrosoft
	}
	return VariantFuture
}

// Returns canonical string representation of UUID:
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
func (u *UUID) String() string {
	return fmt.Sprintf("%x-%x-%x-%x-%x",
		u[:4], u[4:6], u[6:8], u[8:10], u[10:])
}

// Sets version bits.
func (u *UUID) setVersion(v byte) {
	u[6] = (u[6] & 0x0f) | (v << 4)
}

// Sets variant bits as described in RFC 4122.
func (u *UUID) setVariant() {
	u[8] = (u[8] & 0xbf) | 0x80
}

// Returns UUID based on current timestamp and MAC address.
func NewV1() (u *UUID, err error) {
	u = new(UUID)

	time_now := epochStart + uint64(time.Now().UnixNano()/100)

	binary.BigEndian.PutUint32(u[0:], uint32(time_now))
	binary.BigEndian.PutUint16(u[4:], uint16(time_now>>32))
	binary.BigEndian.PutUint16(u[6:], uint16(time_now>>48))

	if clockSequence == 0 {
		buf := make([]byte, 2)
		_, err = rand.Read(buf)
		clockSequence = binary.BigEndian.Uint16(buf)
	}

	binary.BigEndian.PutUint16(u[8:], clockSequence)

	interfaces, _ := net.Interfaces()
	for _, iface := range interfaces {
		if len(iface.HardwareAddr) >= 6 {
			copy(u[10:], iface.HardwareAddr)
			break
		}
	}

	u.setVersion(1)
	u.setVariant()
	return
}

// Returns UUID based on MD5 hash of namespace UUID and name.
func NewV3(ns UUID, name string) (u *UUID, err error) {
	u, err = newFromHash(md5.New(), ns, name)
	if err != nil {
		return
	}
	u.setVersion(3)
	u.setVariant()
	return
}

// Returns random generated UUID.
func NewV4() (u *UUID, err error) {
	u = new(UUID)
	_, err = rand.Read(u[:])
	if err != nil {
		return
	}
	u.setVersion(4)
	u.setVariant()
	return
}

// Returns UUID based on SHA-1 hash of namespace UUID and name.
func NewV5(ns UUID, name string) (u *UUID, err error) {
	u, err = newFromHash(sha1.New(), ns, name)
	if err != nil {
		return
	}
	u.setVersion(5)
	u.setVariant()
	return
}

// Returns UUID based on hashing of namespace UUID and name.
func newFromHash(h hash.Hash, ns UUID, name string) (u *UUID, err error) {
	u = new(UUID)
	h.Write(ns[:])
	h.Write([]byte(name))
	copy(u[:], h.Sum(nil))
	return
}
<commit_msg>predefined namespace UUIDs as pointers<commit_after>/*
The uuid package provides implementation of Universally Unique Identifier (UUID) structure
with functions for generating versions 1, 3, 4 and 5 as specified in RFC 4122
*/
package uuid

import (
	"crypto/md5"
	"crypto/rand"
	"crypto/sha1"
	"encoding/binary"
	"fmt"
	"hash"
	"net"
	"time"
)

// UUID layout variants.
const (
	VariantNCS = iota
	VariantRFC4122
	VariantMicrosoft
	VariantFuture
)

// Difference in 100-nanosecond intervals between
// UUID epoch (October 15, 1582) and Unix epoch (January 1, 1970).
const epochStart = 122192928000000000

// Clock sequence storage
var clockSequence uint16

// UUID representation compliant with specification
// described in RFC 4122.
type UUID [16]byte

// Predefined namespace UUIDs.
var (
	NamespaceDNS  = &UUID{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
	NamespaceURL  = &UUID{0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
	NamespaceOID  = &UUID{0x6b, 0xa7, 0xb8, 0x12, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
	NamespaceX500 = &UUID{0x6b, 0xa7, 0xb8, 0x14, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}
)

// Returns algorithm version used to generate UUID.
// RFC 4122 describes version 1, 3, 4 and 5.
func (u *UUID) Version() uint {
	return uint(u[6] >> 4)
}

// Returns UUID layout variant.
func (u *UUID) Variant() uint {
	switch {
	case (u[8] & 0x80) == 0x00:
		return VariantNCS
	case (u[8]&0xc0)|0x80 == 0x80:
		return VariantRFC4122
	case (u[8]&0xe0)|0xc0 == 0xc0:
		return VariantMicrosoft
	}
	return VariantFuture
}

// Returns canonical string representation of UUID:
// xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
func (u *UUID) String() string {
	return fmt.Sprintf("%x-%x-%x-%x-%x",
		u[:4], u[4:6], u[6:8], u[8:10], u[10:])
}

// Sets version bits.
func (u *UUID) setVersion(v byte) {
	u[6] = (u[6] & 0x0f) | (v << 4)
}

// Sets variant bits as described in RFC 4122.
func (u *UUID) setVariant() {
	u[8] = (u[8] & 0xbf) | 0x80
}

// Returns UUID based on current timestamp and MAC address.
func NewV1() (u *UUID, err error) {
	u = new(UUID)

	time_now := epochStart + uint64(time.Now().UnixNano()/100)

	binary.BigEndian.PutUint32(u[0:], uint32(time_now))
	binary.BigEndian.PutUint16(u[4:], uint16(time_now>>32))
	binary.BigEndian.PutUint16(u[6:], uint16(time_now>>48))

	if clockSequence == 0 {
		buf := make([]byte, 2)
		_, err = rand.Read(buf)
		clockSequence = binary.BigEndian.Uint16(buf)
	}

	binary.BigEndian.PutUint16(u[8:], clockSequence)

	interfaces, _ := net.Interfaces()
	for _, iface := range interfaces {
		if len(iface.HardwareAddr) >= 6 {
			copy(u[10:], iface.HardwareAddr)
			break
		}
	}

	u.setVersion(1)
	u.setVariant()
	return
}

// Returns UUID based on MD5 hash of namespace UUID and name.
func NewV3(ns *UUID, name string) (u *UUID, err error) {
	u, err = newFromHash(md5.New(), ns, name)
	if err != nil {
		return
	}
	u.setVersion(3)
	u.setVariant()
	return
}

// Returns random generated UUID.
func NewV4() (u *UUID, err error) {
	u = new(UUID)
	_, err = rand.Read(u[:])
	if err != nil {
		return
	}
	u.setVersion(4)
	u.setVariant()
	return
}

// Returns UUID based on SHA-1 hash of namespace UUID and name.
func NewV5(ns *UUID, name string) (u *UUID, err error) {
	u, err = newFromHash(sha1.New(), ns, name)
	if err != nil {
		return
	}
	u.setVersion(5)
	u.setVariant()
	return
}

// Returns UUID based on hashing of namespace UUID and name.
func newFromHash(h hash.Hash, ns *UUID, name string) (u *UUID, err error) {
	u = new(UUID)
	h.Write(ns[:])
	h.Write([]byte(name))
	copy(u[:], h.Sum(nil))
	return
}
<|endoftext|>


<commit_before>package main

import "testing"

var INPUT = []string{
	"a", "a", "a", "a",
	"b", "b", "b", "b", "b",
	"c", "c", "c", "c", "c", "c",
	"d", "d", "d", "d", "d", "d", "d", "d",
	"e", "e", "e", "e", "e", "e", "e", "e", "e",
	"f", "f", "f", "f", "f", "f", "f", "f", "f", "f",
	"g", "g", "g", "g", "g", "g", "g", "g", "g", "g", "g",
	"h", "h", "h", "h", "h", "h", "h", "h", "h", "h", "h", "h",
}

func BenchmarkDedupAppend(b *testing.B) {
	for i := 0; i < b.N; i++ {
		dedupAppend(INPUT)
	}
}

func BenchmarkDedupCopy(b *testing.B) {
	for i := 0; i < b.N; i++ {
		dedupCopy(INPUT)
	}
}
<commit_msg>Addded two tests for task 4.5<commit_after>package main

import "testing"

var INPUT = []string{
	"a", "a", "a", "a",
	"b", "b", "b", "b", "b",
	"c", "c", "c", "c", "c", "c",
	"d", "d", "d", "d", "d", "d", "d", "d",
	"e", "e", "e", "e", "e", "e", "e", "e", "e",
	"f", "f", "f", "f", "f", "f", "f", "f", "f", "f",
	"g", "g", "g", "g", "g", "g", "g", "g", "g", "g", "g",
	"h", "h", "h", "h", "h", "h", "h", "h", "h", "h", "h", "h",
}

var OUTPUT = []string{"a", "b", "c", "d", "e", "f", "g", "h"}

func TestDedupDiff(t *testing.T) {
	var result []string

	result = dedup(INPUT)
	if len(OUTPUT) != len(result) {
		t.Errorf("got len %d, but expected %d", len(result), len(OUTPUT))
	}
	for i, s := range OUTPUT {
		if s != result[i] {
			t.Errorf("got str %s, but expected %s", result[i], s)
		}
	}
}

func TestDedupSame(t *testing.T) {
	var result []string

	result = dedup(OUTPUT)
	if len(OUTPUT) != len(result) {
		t.Errorf("got len %d, but expected %d", len(result), len(OUTPUT))
	}
	for i, s := range OUTPUT {
		if s != result[i] {
			t.Errorf("got str %s, but expected %s", result[i], s)
		}
	}
}

func BenchmarkDedupAppend(b *testing.B) {
	for i := 0; i < b.N; i++ {
		dedupAppend(INPUT)
	}
}

func BenchmarkDedupCopy(b *testing.B) {
	for i := 0; i < b.N; i++ {
		dedupCopy(INPUT)
	}
}
<|endoftext|>


<commit_before>/*
 *    Copyright (C) 2015 Stefan Luecke
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as published
 *    by the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Authors: Stefan Luecke <glaxx@glaxx.net>
 */

package backend

import (
	log "github.com/Sirupsen/logrus"
	"github.com/emicklei/go-restful"
	"html/template"
	"net/http"
	"strconv"
	//"strings"
)

type User struct {
	ID   uint64
	Name string
}

func NewUserService() *restful.WebService {
	service := new(restful.WebService)
	service.
		Path("/user").
		Consumes(restful.MIME_JSON, restful.MIME_XML).
		Produces(restful.MIME_JSON, restful.MIME_XML)

	service.Route(service.GET("/{id}").To(GetUserById))
	service.Route(service.GET("").To(ListUser))
	service.Route(service.PUT("").To(UpdateUser))
	service.Route(service.PUT("/{id}").To(UpdateUser))
	service.Route(service.POST("").To(CreateUser))
	service.Route(service.DELETE("/{id}").To(DeleteUser))
	return service
}

func GetUserById(request *restful.Request, response *restful.Response) {
	sid := request.PathParameter("id")
	id, err := strconv.ParseUint(sid, 10, 64)
	if err != nil {
		response.WriteErrorString(http.StatusBadRequest, ERROR_INVALID_ID)
		log.WithFields(log.Fields{"Error Msg": err}).Info(ERROR_INVALID_ID)
		return
	}
	user, err := getUserById(id)
	if err != nil || user.ID == 0 {
		response.WriteErrorString(http.StatusBadRequest, ERROR_INVALID_ID)
		log.WithFields(log.Fields{"Error Msg": err}).
			Info(ERROR_INVALID_ID)
		return
	}
	response.WriteEntity(user)
}

func getUserById(id uint64) (User, error) {
	stmt, err := db.Prepare("SELECT * FROM user WHERE id=?;")
	if err != nil {
		log.WithFields(log.Fields{"Error Msg": err}).
			Fatal(ERROR_STMT_PREPARE)
	}
	defer stmt.Close()
	row := stmt.QueryRow(id)
	user := new(User)
	err = row.Scan(&user.ID, &user.Name)
	if err != nil {
		log.WithFields(log.Fields{"Error Msg": err}).
			Warn("Scan Error")
	}
	return *user, nil
}

func ListUser(request *restful.Request, response *restful.Response) {
	usr, err := listUser()
	if err != nil {
		response.WriteErrorString(http.StatusInternalServerError, ERROR_INTERNAL)
		log.WithFields(log.Fields{"Error Msg": err}).Warn(ERROR_INTERNAL)
		return
	}
	response.WriteEntity(usr)
}

func listUser() ([]User, error) {
	stmt, err := db.Prepare("SELECT * FROM user;")
	if err != nil {
		log.WithFields(log.Fields{"Error Msg": err}).Fatal(ERROR_STMT_PREPARE)
		return nil, err
	}
	defer stmt.Close()
	rows, err := stmt.Query()
	if err != nil {
		log.WithFields(log.Fields{"Error Msg": err}).Warn(ERROR_INTERNAL)
		return nil, err
	}
	result := make([]User, 0)
	for rows.Next() {
		temp := new(User)
		rows.Scan(&temp.ID, &temp.Name)
		result = append(result, *temp)
	}

	return result, nil
}

func UpdateUser(request *restful.Request, response *restful.Response) {
	usr := new(User)
	err := request.ReadEntity(usr)
	if err != nil {
		response.WriteErrorString(http.StatusInternalServerError, ERROR_INTERNAL)
		log.WithFields(log.Fields{"Error Msg": err}).Warn(ERROR_INTERNAL)
		return
	}
	stmt, err := db.Prepare(`
		SELECT * FROM user ORDER BY id DESC LIMIT 0, 1;`)
	if err != nil {
		response.WriteErrorString(http.StatusInternalServerError, ERROR_INTERNAL)
		log.WithFields(log.Fields{"Error Msg": err}).Warn(ERROR_INTERNAL)
		return
	}
	defer stmt.Close()
	row := stmt.QueryRow()
	var id uint64
	temp := new(User)
	err = row.Scan(&id, &temp.Name)
	if err != nil {
		response.WriteErrorString(http.StatusInternalServerError, ERROR_INTERNAL)
		log.WithFields(log.Fields{"Error Msg": err}).Warn(ERROR_INTERNAL)
		return
	}

	log.WithFields(log.Fields{"Id": id}).Debug("Highest ID")

	if usr.ID <= id {
		err := updateUser(usr)
		if err != nil {
			response.WriteErrorString(http.StatusInternalServerError, ERROR_INTERNAL)
			return
		} else {
			response.WriteEntity(true)
		}
	} else {
		CreateUser(request, response)
	}
}

func updateUser(usr *User) error {
	stmt, err := db.Prepare(`UPDATE user SET name=? WHERE id=?;`)
	if err != nil {
		return err
	}
	defer stmt.Close()
	_, err = stmt.Exec(template.HTMLEscapeString(usr.Name), usr.ID)
	if err != nil {
		return err
	}
	return nil
}

func CreateUser(request *restful.Request, response *restful.Response) {
	usr := new(User)
	err := request.ReadEntity(usr)
	if err != nil {
		response.WriteErrorString(http.StatusBadRequest, ERROR_INVALID_INPUT)
		log.WithFields(log.Fields{"Error Msg": err}).Info(ERROR_INVALID_INPUT)
		return
	}

	id, err := createUser(usr)
	if err != nil {
		response.WriteErrorString(http.StatusInternalServerError, ERROR_INTERNAL)
		log.WithFields(log.Fields{"Error Msg": err}).Warn(ERROR_INTERNAL)
		return
	}
	response.WriteEntity("/user/" + strconv.FormatUint(id, 10))
}

func createUser(usr *User) (uint64, error) {
	stmt, err := db.Prepare(`
		INSERT INTO user ('name') VALUES (?);`)
	if err != nil {
		log.WithFields(log.Fields{"Error Msg": err}).Fatal(ERROR_STMT_PREPARE)
		return 0, err
	}
	defer stmt.Close()
	res, err := stmt.Exec(template.HTMLEscapeString(usr.Name))
	if err != nil {
		log.WithFields(log.Fields{"Error Msg": err}).Warn(ERROR_INSERT)
		return 0, err
	}
	id, err := res.LastInsertId()
	if err != nil {
		log.WithFields(log.Fields{"Error Msg": err}).Warn(ERROR_QUERY)
		return 0, err
	}
	return uint64(id), nil
}

func DeleteUser(request *restful.Request, response *restful.Response) {
	sid := request.PathParameter("id")
	id, err := strconv.ParseUint(sid, 10, 64)
	if err != nil {
		log.WithFields(log.Fields{"Error Msg": err}).Info(ERROR_INVALID_ID)
		response.WriteErrorString(http.StatusBadRequest, ERROR_INVALID_ID)
		return
	}

	err = deleteUser(id)
	if err != nil {
		log.WithFields(log.Fields{"Error Msg": err}).Info(ERROR_INTERNAL)
		response.WriteErrorString(http.StatusInternalServerError, ERROR_INTERNAL)
		return
	}
	response.WriteEntity(true)
}

func deleteUser(id uint64) error {
	stmt, err := db.Prepare("DELETE FROM user WHERE id=?;")
	if err != nil {
		return err
	}
	defer stmt.Close()
	_, err = stmt.Exec(id)
	if err != nil {
		return err
	}
	return nil
}
<commit_msg>user.go: Use mongo db instead of sqlite<commit_after>/*
 *    Copyright (C) 2015 Stefan Luecke
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU Affero General Public License as published
 *    by the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU Affero General Public License for more details.
 *
 *    You should have received a copy of the GNU Affero General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    Authors: Stefan Luecke <glaxx@glaxx.net>
 */

package backend

import (
	log "github.com/Sirupsen/logrus"
	"github.com/emicklei/go-restful"
	//"html/template"
	"net/http"
	//"strconv"
	//"strings"
	"gopkg.in/mgo.v2/bson"
)

type User struct {
	ID    bson.ObjectId `bson:"_id,omitempty" json:"-"`
	Name  string
	EMail string
}

func NewUserService() *restful.WebService {
	service := new(restful.WebService)
	service.
		Path("/user").
		Consumes(restful.MIME_JSON, restful.MIME_XML).
		Produces(restful.MIME_JSON, restful.MIME_XML)

	service.Route(service.GET("/{name}").To(GetUserByName))
	service.Route(service.GET("").To(ListUser))
	service.Route(service.PUT("").To(UpdateUser))
	service.Route(service.POST("").To(CreateUser))
	service.Route(service.DELETE("/{name}").To(DeleteUser))
	return service
}

func GetUserByName(request *restful.Request, response *restful.Response) {
	name := request.PathParameter("name")
	user, err := getUserByName(name)
	if err != nil {
		response.WriteErrorString(http.StatusBadRequest, ERROR_INVALID_ID)
		log.WithFields(log.Fields{"Error Msg": err}).
			Info(ERROR_INVALID_ID)
		return
	}
	response.WriteEntity(user)
}

func getUserByName(name string) (User, error) {
	res := User{}
	err := uCol.Find(bson.M{"name": name}).One(&res)
	return res, err
}

func ListUser(request *restful.Request, response *restful.Response) {
	usr, err := listUser()
	if err != nil {
		response.WriteErrorString(http.StatusInternalServerError, ERROR_INTERNAL)
		log.WithFields(log.Fields{"Error Msg": err}).Warn(ERROR_INTERNAL)
		return
	}
	response.WriteEntity(usr)
}

func listUser() ([]User, error) {
	usr := make([]User, 0)
	err := uCol.Find(nil).All(&usr)
	return usr, err
}

func UpdateUser(request *restful.Request, response *restful.Response) {
	usr := new(User)
	err := request.ReadEntity(usr)
	if err != nil {
		response.WriteErrorString(http.StatusBadRequest, ERROR_INVALID_INPUT)
		log.WithFields(log.Fields{"Error Msg": err}).Warn(ERROR_INVALID_INPUT)
		return
	}
	ex := checkUserExistance(usr)
	if ex {
		err = updateUser(usr)
		if err != nil {
			response.WriteErrorString(http.StatusInternalServerError, ERROR_INTERNAL)
			log.WithFields(log.Fields{"Err": err}).Warn("Error while updating User")
			return
		}
		response.WriteEntity(true)
		return
	} else {
		response.WriteErrorString(http.StatusNotFound, "User not found. Please register first")
		return
	}
}

func updateUser(usr *User) error {
	return uCol.Update(bson.M{"name": usr.Name}, usr)
}

func CreateUser(request *restful.Request, response *restful.Response) {
	usr := new(User)
	err := request.ReadEntity(usr)
	log.WithFields(log.Fields{"Username": usr.Name}).Info("Attempted user registration")
	if err != nil {
		response.WriteErrorString(http.StatusBadRequest, ERROR_INVALID_INPUT)
		log.WithFields(log.Fields{"Error Msg": err}).Info(ERROR_INVALID_INPUT)
		return
	}

	ex := checkUserExistance(usr)

	if ex {
		response.WriteErrorString(http.StatusUnauthorized, "This username is not available")
		return
	}

	err = createUser(usr)
	if err != nil {
		response.WriteErrorString(http.StatusInternalServerError, ERROR_INTERNAL)
		log.WithFields(log.Fields{"Error Msg": err}).Warn(ERROR_INTERNAL)
		return
	}
	response.WriteEntity("/user/" + usr.Name)
}

func checkUserExistance(usr *User) bool {
	temp := User{}
	err := uCol.Find(bson.M{"name": usr.Name}).One(&temp)
	if err != nil {
		if err.Error() == "not found" {
			return false
		} else {
			log.WithFields(log.Fields{"Err": err}).
				Debug("TODO: check more error codes here")
			return true // if something strange in the neighbourhood …
			// what you gonna do? - do not register a new user!
		}
	} else {
		return true
	}
	return true
}

func createUser(usr *User) error {
	return uCol.Insert(usr)
}

func DeleteUser(request *restful.Request, response *restful.Response) {
	name := request.PathParameter("name")
	log.WithFields(log.Fields{"Name": name}).Info("Got user DELETE request")
	err := deleteUser(name)
	if err != nil {
		log.WithFields(log.Fields{"Error Msg": err}).Info(ERROR_INTERNAL)
		response.WriteErrorString(http.StatusInternalServerError, ERROR_INTERNAL)
		return
	}
	response.WriteEntity(true)
}

func deleteUser(name string) error {
	return uCol.Remove(bson.M{"name": name})
}
<|endoftext|>


<commit_before>// Package vec3 contains a 3D float32 vector type T and functions.
package vec3

import (
	"fmt"

	math "github.com/barnex/fmath"
	"github.com/ungerik/go3d/generic"
)

var (
	// Zero holds a zero vector.
	Zero = T{}

	// UnitX holds a vector with X set to one.
	UnitX = T{1, 0, 0}
	// UnitY holds a vector with Y set to one.
	UnitY = T{0, 1, 0}
	// UnitZ holds a vector with Z set to one.
	UnitZ = T{0, 0, 1}
	// UnitXYZ holds a vector with X, Y, Z set to one.
	UnitXYZ = T{1, 1, 1}

	// Red holds the color red.
	Red = T{1, 0, 0}
	// Green holds the color green.
	Green = T{0, 1, 0}
	// Blue holds the color black.
	Blue = T{0, 0, 1}
	// Black holds the color black.
	Black = T{0, 0, 0}
	// White holds the color white.
	White = T{1, 1, 1}

	// MinVal holds a vector with the smallest possible component values.
	MinVal = T{-math.MaxFloat32, -math.MaxFloat32, -math.MaxFloat32}
	// MaxVal holds a vector with the highest possible component values.
	MaxVal = T{+math.MaxFloat32, +math.MaxFloat32, +math.MaxFloat32}
)

// T represents a 3D vector.
type T [3]float32

// From copies a T from a generic.T implementation.
func From(other generic.T) T {
	switch other.Size() {
	case 2:
		return T{other.Get(0, 0), other.Get(0, 1), 0}
	case 3, 4:
		return T{other.Get(0, 0), other.Get(0, 1), other.Get(0, 2)}
	default:
		panic("Unsupported type")
	}
}

// Parse parses T from a string. See also String()
func Parse(s string) (r T, err error) {
	_, err = fmt.Sscan(s, &r[0], &r[1], &r[2])
	return r, err
}

// String formats T as string. See also Parse().
func (vec *T) String() string {
	return fmt.Sprint(vec[0], vec[1], vec[2])
}

// Rows returns the number of rows of the vector.
func (vec *T) Rows() int {
	return 3
}

// Cols returns the number of columns of the vector.
func (vec *T) Cols() int {
	return 1
}

// Size returns the number elements of the vector.
func (vec *T) Size() int {
	return 3
}

// Slice returns the elements of the vector as slice.
func (vec *T) Slice() []float32 {
	return vec[:]
}

// Get returns one element of the vector.
func (vec *T) Get(col, row int) float32 {
	return vec[row]
}

// IsZero checks if all elements of the vector are zero.
func (vec *T) IsZero() bool {
	return vec[0] == 0 && vec[1] == 0 && vec[2] == 0
}

// Length returns the length of the vector.
// See also LengthSqr and Normalize.
func (vec *T) Length() float32 {
	return float32(math.Sqrt(vec.LengthSqr()))
}

// LengthSqr returns the squared length of the vector.
// See also Length and Normalize.
func (vec *T) LengthSqr() float32 {
	return vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]
}

// Scale multiplies all element of the vector by f and returns vec.
func (vec *T) Scale(f float32) {
	vec[0] *= f
	vec[1] *= f
	vec[2] *= f
}

// Scaled returns a copy of vec with all elements multiplies by f.
func (vec *T) Scaled(f float32) T {
	return T{vec[0] * f, vec[1] * f, vec[2] * f}
}

// Invert inverts the vector.
func (vec *T) Invert() *T {
	vec[0] = -vec[0]
	vec[1] = -vec[1]
	vec[2] = -vec[2]
	return vec
}

// Inverted returns an inverted copy of the vector.
func (vec *T) Inverted() T {
	return T{-vec[0], -vec[1], -vec[2]}
}

// Abs sets every component of the vector to its absolute value.
func (vec *T) Abs() *T {
	vec[0] = math.Abs(vec[0])
	vec[1] = math.Abs(vec[1])
	vec[2] = math.Abs(vec[2])
	return vec
}

// Absed returns a copy of the vector containing the absolute values.
func (vec *T) Absed() T {
	return T{math.Abs(vec[0]), math.Abs(vec[1]), math.Abs(vec[2])}
}

// Normalize normalizes the vector to unit length.
func (vec *T) Normalize() *T {
	sl := vec.LengthSqr()
	if sl == 0 || sl == 1 {
		return vec
	}
	vec.Scale(1 / math.Sqrt(sl))
	return vec
}

// Normalized returns a unit length normalized copy of the vector.
func (vec *T) Normalized() T {
	v := *vec
	v.Normalize()
	return v
}

// Normal returns an orthogonal vector.
func (vec *T) Normal() T {
	n := Cross(vec, &UnitZ)
	if n.IsZero() {
		return UnitX
	}
	return n.Normalized()
}

// Add adds another vector to vec.
func (vec *T) Add(v *T) *T {
	vec[0] += v[0]
	vec[1] += v[1]
	vec[2] += v[2]
	return vec
}

// Sub subtracts another vector from vec.
func (vec *T) Sub(v *T) *T {
	vec[0] -= v[0]
	vec[1] -= v[1]
	vec[2] -= v[2]
	return vec
}

// Mul multiplies the components of the vector with the respective components of v.
func (vec *T) Mul(v *T) *T {
	vec[0] *= v[0]
	vec[1] *= v[1]
	vec[2] *= v[2]
	return vec
}

// Add returns the sum of two vectors.
func Add(a, b *T) T {
	return T{a[0] + b[0], a[1] + b[1], a[2] + b[2]}
}

// Squared Distance between two vectors
func SquareDistance(a, b *T) float32 {
	d := Sub(a, b)
	return d.LengthSqr()
}

// Distance between two vectors
func Distance(a, b *T) float32 {
	d := Sub(a, b)
	return d.Length()
}

// Sub returns the difference of two vectors.
func Sub(a, b *T) T {
	return T{a[0] - b[0], a[1] - b[1], a[2] - b[2]}
}

// Mul returns the component wise product of two vectors.
func Mul(a, b *T) T {
	return T{a[0] * b[0], a[1] * b[1], a[2] * b[2]}
}

// Dot returns the dot product of two vectors.
func Dot(a, b *T) float32 {
	return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
}

// Cross returns the cross product of two vectors.
func Cross(a, b *T) T {
	return T{
		a[1]*b[2] - a[2]*b[1],
		a[2]*b[0] - a[0]*b[2],
		a[0]*b[1] - a[1]*b[0],
	}
}

// Angle returns the angle between two vectors.
func Angle(a, b *T) float32 {
	return math.Acos(Dot(a, b))
}

// Min returns the component wise minimum of two vectors.
func Min(a, b *T) T {
	min := *a
	if b[0] < min[0] {
		min[0] = b[0]
	}
	if b[1] < min[1] {
		min[1] = b[1]
	}
	if b[2] < min[2] {
		min[2] = b[2]
	}
	return min
}

// Max returns the component wise maximum of two vectors.
func Max(a, b *T) T {
	max := *a
	if b[0] > max[0] {
		max[0] = b[0]
	}
	if b[1] > max[1] {
		max[1] = b[1]
	}
	if b[2] > max[2] {
		max[2] = b[2]
	}
	return max
}

// Interpolate interpolates between a and b at t (0,1).
func Interpolate(a, b *T, t float32) T {
	t1 := 1 - t
	return T{
		a[0]*t1 + b[0]*t,
		a[1]*t1 + b[1]*t,
		a[2]*t1 + b[2]*t,
	}
}

// Clamp clamps the vector's components to be in the range of min to max.
func (vec *T) Clamp(min, max *T) *T {
	for i := range vec {
		if vec[i] < min[i] {
			vec[i] = min[i]
		} else if vec[i] > max[i] {
			vec[i] = max[i]
		}
	}
	return vec
}

// Clamped returns a copy of the vector with the components clamped to be in the range of min to max.
func (vec *T) Clamped(min, max *T) T {
	result := *vec
	result.Clamp(min, max)
	return result
}

// Clamp01 clamps the vector's components to be in the range of 0 to 1.
func (vec *T) Clamp01() *T {
	return vec.Clamp(&Zero, &UnitXYZ)
}

// Clamped01 returns a copy of the vector with the components clamped to be in the range of 0 to 1.
func (vec *T) Clamped01() T {
	result := *vec
	result.Clamp01()
	return result
}
<commit_msg>Allow chaining from vec3.T.Scale()<commit_after>// Package vec3 contains a 3D float32 vector type T and functions.
package vec3

import (
	"fmt"

	math "github.com/barnex/fmath"
	"github.com/ungerik/go3d/generic"
)

var (
	// Zero holds a zero vector.
	Zero = T{}

	// UnitX holds a vector with X set to one.
	UnitX = T{1, 0, 0}
	// UnitY holds a vector with Y set to one.
	UnitY = T{0, 1, 0}
	// UnitZ holds a vector with Z set to one.
	UnitZ = T{0, 0, 1}
	// UnitXYZ holds a vector with X, Y, Z set to one.
	UnitXYZ = T{1, 1, 1}

	// Red holds the color red.
	Red = T{1, 0, 0}
	// Green holds the color green.
	Green = T{0, 1, 0}
	// Blue holds the color black.
	Blue = T{0, 0, 1}
	// Black holds the color black.
	Black = T{0, 0, 0}
	// White holds the color white.
	White = T{1, 1, 1}

	// MinVal holds a vector with the smallest possible component values.
	MinVal = T{-math.MaxFloat32, -math.MaxFloat32, -math.MaxFloat32}
	// MaxVal holds a vector with the highest possible component values.
	MaxVal = T{+math.MaxFloat32, +math.MaxFloat32, +math.MaxFloat32}
)

// T represents a 3D vector.
type T [3]float32

// From copies a T from a generic.T implementation.
func From(other generic.T) T {
	switch other.Size() {
	case 2:
		return T{other.Get(0, 0), other.Get(0, 1), 0}
	case 3, 4:
		return T{other.Get(0, 0), other.Get(0, 1), other.Get(0, 2)}
	default:
		panic("Unsupported type")
	}
}

// Parse parses T from a string. See also String()
func Parse(s string) (r T, err error) {
	_, err = fmt.Sscan(s, &r[0], &r[1], &r[2])
	return r, err
}

// String formats T as string. See also Parse().
func (vec *T) String() string {
	return fmt.Sprint(vec[0], vec[1], vec[2])
}

// Rows returns the number of rows of the vector.
func (vec *T) Rows() int {
	return 3
}

// Cols returns the number of columns of the vector.
func (vec *T) Cols() int {
	return 1
}

// Size returns the number elements of the vector.
func (vec *T) Size() int {
	return 3
}

// Slice returns the elements of the vector as slice.
func (vec *T) Slice() []float32 {
	return vec[:]
}

// Get returns one element of the vector.
func (vec *T) Get(col, row int) float32 {
	return vec[row]
}

// IsZero checks if all elements of the vector are zero.
func (vec *T) IsZero() bool {
	return vec[0] == 0 && vec[1] == 0 && vec[2] == 0
}

// Length returns the length of the vector.
// See also LengthSqr and Normalize.
func (vec *T) Length() float32 {
	return float32(math.Sqrt(vec.LengthSqr()))
}

// LengthSqr returns the squared length of the vector.
// See also Length and Normalize.
func (vec *T) LengthSqr() float32 {
	return vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2]
}

// Scale multiplies all element of the vector by f and returns vec.
func (vec *T) Scale(f float32) *T {
	vec[0] *= f
	vec[1] *= f
	vec[2] *= f

	return vec
}

// Scaled returns a copy of vec with all elements multiplies by f.
func (vec *T) Scaled(f float32) T {
	return T{vec[0] * f, vec[1] * f, vec[2] * f}
}

// Invert inverts the vector.
func (vec *T) Invert() *T {
	vec[0] = -vec[0]
	vec[1] = -vec[1]
	vec[2] = -vec[2]
	return vec
}

// Inverted returns an inverted copy of the vector.
func (vec *T) Inverted() T {
	return T{-vec[0], -vec[1], -vec[2]}
}

// Abs sets every component of the vector to its absolute value.
func (vec *T) Abs() *T {
	vec[0] = math.Abs(vec[0])
	vec[1] = math.Abs(vec[1])
	vec[2] = math.Abs(vec[2])
	return vec
}

// Absed returns a copy of the vector containing the absolute values.
func (vec *T) Absed() T {
	return T{math.Abs(vec[0]), math.Abs(vec[1]), math.Abs(vec[2])}
}

// Normalize normalizes the vector to unit length.
func (vec *T) Normalize() *T {
	sl := vec.LengthSqr()
	if sl == 0 || sl == 1 {
		return vec
	}
	vec.Scale(1 / math.Sqrt(sl))
	return vec
}

// Normalized returns a unit length normalized copy of the vector.
func (vec *T) Normalized() T {
	v := *vec
	v.Normalize()
	return v
}

// Normal returns an orthogonal vector.
func (vec *T) Normal() T {
	n := Cross(vec, &UnitZ)
	if n.IsZero() {
		return UnitX
	}
	return n.Normalized()
}

// Add adds another vector to vec.
func (vec *T) Add(v *T) *T {
	vec[0] += v[0]
	vec[1] += v[1]
	vec[2] += v[2]
	return vec
}

// Sub subtracts another vector from vec.
func (vec *T) Sub(v *T) *T {
	vec[0] -= v[0]
	vec[1] -= v[1]
	vec[2] -= v[2]
	return vec
}

// Mul multiplies the components of the vector with the respective components of v.
func (vec *T) Mul(v *T) *T {
	vec[0] *= v[0]
	vec[1] *= v[1]
	vec[2] *= v[2]
	return vec
}

// Add returns the sum of two vectors.
func Add(a, b *T) T {
	return T{a[0] + b[0], a[1] + b[1], a[2] + b[2]}
}

// Squared Distance between two vectors
func SquareDistance(a, b *T) float32 {
	d := Sub(a, b)
	return d.LengthSqr()
}

// Distance between two vectors
func Distance(a, b *T) float32 {
	d := Sub(a, b)
	return d.Length()
}

// Sub returns the difference of two vectors.
func Sub(a, b *T) T {
	return T{a[0] - b[0], a[1] - b[1], a[2] - b[2]}
}

// Mul returns the component wise product of two vectors.
func Mul(a, b *T) T {
	return T{a[0] * b[0], a[1] * b[1], a[2] * b[2]}
}

// Dot returns the dot product of two vectors.
func Dot(a, b *T) float32 {
	return a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
}

// Cross returns the cross product of two vectors.
func Cross(a, b *T) T {
	return T{
		a[1]*b[2] - a[2]*b[1],
		a[2]*b[0] - a[0]*b[2],
		a[0]*b[1] - a[1]*b[0],
	}
}

// Angle returns the angle between two vectors.
func Angle(a, b *T) float32 {
	return math.Acos(Dot(a, b))
}

// Min returns the component wise minimum of two vectors.
func Min(a, b *T) T {
	min := *a
	if b[0] < min[0] {
		min[0] = b[0]
	}
	if b[1] < min[1] {
		min[1] = b[1]
	}
	if b[2] < min[2] {
		min[2] = b[2]
	}
	return min
}

// Max returns the component wise maximum of two vectors.
func Max(a, b *T) T {
	max := *a
	if b[0] > max[0] {
		max[0] = b[0]
	}
	if b[1] > max[1] {
		max[1] = b[1]
	}
	if b[2] > max[2] {
		max[2] = b[2]
	}
	return max
}

// Interpolate interpolates between a and b at t (0,1).
func Interpolate(a, b *T, t float32) T {
	t1 := 1 - t
	return T{
		a[0]*t1 + b[0]*t,
		a[1]*t1 + b[1]*t,
		a[2]*t1 + b[2]*t,
	}
}

// Clamp clamps the vector's components to be in the range of min to max.
func (vec *T) Clamp(min, max *T) *T {
	for i := range vec {
		if vec[i] < min[i] {
			vec[i] = min[i]
		} else if vec[i] > max[i] {
			vec[i] = max[i]
		}
	}
	return vec
}

// Clamped returns a copy of the vector with the components clamped to be in the range of min to max.
func (vec *T) Clamped(min, max *T) T {
	result := *vec
	result.Clamp(min, max)
	return result
}

// Clamp01 clamps the vector's components to be in the range of 0 to 1.
func (vec *T) Clamp01() *T {
	return vec.Clamp(&Zero, &UnitXYZ)
}

// Clamped01 returns a copy of the vector with the components clamped to be in the range of 0 to 1.
func (vec *T) Clamped01() T {
	result := *vec
	result.Clamp01()
	return result
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Matt Jibson <matt.jibson@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package goon

import (
	"appengine/datastore"
	"reflect"
)

// Count returns the number of results for the query.
func (g *Goon) Count(q *datastore.Query) (int, error) {
	return q.Count(g.context)
}

// GetAll runs the query in the given context and returns all keys that match
// that query, as well as appending the values to dst.
//
// If q is not a "keys-only" query, GetAll sets the goon key fields of dst and
// caches returned data in memory.
//
// See: https://developers.google.com/appengine/docs/go/datastore/reference#Query.GetAll
func (g *Goon) GetAll(q *datastore.Query, dst interface{}) ([]*datastore.Key, error) {
	keys, err := q.GetAll(g.context, dst)
	if err != nil {
		g.error(err)
		return nil, err
	}

	keysOnly := dst == nil

	var v reflect.Value
	var t reflect.Type
	if !keysOnly {
		v = reflect.Indirect(reflect.ValueOf(dst))
		t = v.Type()

		// try to detect a keys-only query
		if t.Kind() != reflect.Slice || v.Len() != len(keys) {
			keysOnly = true
		}
	}

	if keysOnly {
		return keys, err
	}

	for i, k := range keys {
		e := v.Index(i).Interface()
		setStructKey(&e, k)

		if !g.inTransaction {
			g.cache[memkey(k)] = &e
		}
	}

	return keys, err
}

func (g *Goon) Run(q *datastore.Query) *Iterator {
	return &Iterator{
		g: g,
		i: q.Run(g.context),
	}
}

// Iterator is the result of running a query.
type Iterator struct {
	g *Goon
	i *datastore.Iterator
}

// Cursor returns a cursor for the iterator's current location.
func (t *Iterator) Cursor() (datastore.Cursor, error) {
	return t.i.Cursor()
}

// Next returns the entity of the next result. When there are no more results,
// datastore.Done is returned as the error. If dst is null (for a keys-only
// query), nil is returned as the entity.
//
// If the query is not keys only and dst is non-nil, it also loads the entity
// stored for that key into the struct pointer dst, with the same semantics
// and possible errors as for the Get function. This is returned as an Entity
// and cached in memory.
//
// If the query is keys only, dst must be passed as nil. Otherwise the cache
// will be populated with empty entities since there is no way to detect the
// case of a keys-only query.
//
// Refer to appengine/datastore.Iterator.Next:
// https://developers.google.com/appengine/docs/go/datastore/reference#Iterator.Next
func (t *Iterator) Next(dst interface{}) (*datastore.Key, error) {
	k, err := t.i.Next(dst)
	if err != nil {
		return nil, err
	}

	if !t.g.inTransaction && dst != nil {
		t.g.cache[memkey(k)] = dst
	}

	// Before returning, update the struct to have correct key info
	if dst != nil {
		setStructKey(dst, k)
	}

	return k, err
}
<commit_msg>Just return whatever we get back<commit_after>/*
 * Copyright (c) 2012 Matt Jibson <matt.jibson@gmail.com>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package goon

import (
	"appengine/datastore"
	"reflect"
)

// Count returns the number of results for the query.
func (g *Goon) Count(q *datastore.Query) (int, error) {
	return q.Count(g.context)
}

// GetAll runs the query in the given context and returns all keys that match
// that query, as well as appending the values to dst.
//
// If q is not a "keys-only" query, GetAll sets the goon key fields of dst and
// caches returned data in memory.
//
// See: https://developers.google.com/appengine/docs/go/datastore/reference#Query.GetAll
func (g *Goon) GetAll(q *datastore.Query, dst interface{}) ([]*datastore.Key, error) {
	keys, err := q.GetAll(g.context, dst)
	if err != nil {
		g.error(err)
		return nil, err
	}

	keysOnly := dst == nil

	var v reflect.Value
	var t reflect.Type
	if !keysOnly {
		v = reflect.Indirect(reflect.ValueOf(dst))
		t = v.Type()

		// try to detect a keys-only query
		if t.Kind() != reflect.Slice || v.Len() != len(keys) {
			keysOnly = true
		}
	}

	if keysOnly {
		return keys, err
	}

	for i, k := range keys {
		e := v.Index(i).Interface()
		setStructKey(&e, k)

		if !g.inTransaction {
			g.cache[memkey(k)] = &e
		}
	}

	return keys, err
}

func (g *Goon) Run(q *datastore.Query) *Iterator {
	return &Iterator{
		g: g,
		i: q.Run(g.context),
	}
}

// Iterator is the result of running a query.
type Iterator struct {
	g *Goon
	i *datastore.Iterator
}

// Cursor returns a cursor for the iterator's current location.
func (t *Iterator) Cursor() (datastore.Cursor, error) {
	return t.i.Cursor()
}

// Next returns the entity of the next result. When there are no more results,
// datastore.Done is returned as the error. If dst is null (for a keys-only
// query), nil is returned as the entity.
//
// If the query is not keys only and dst is non-nil, it also loads the entity
// stored for that key into the struct pointer dst, with the same semantics
// and possible errors as for the Get function. This is returned as an Entity
// and cached in memory.
//
// If the query is keys only, dst must be passed as nil. Otherwise the cache
// will be populated with empty entities since there is no way to detect the
// case of a keys-only query.
//
// Refer to appengine/datastore.Iterator.Next:
// https://developers.google.com/appengine/docs/go/datastore/reference#Iterator.Next
func (t *Iterator) Next(dst interface{}) (*datastore.Key, error) {
	k, err := t.i.Next(dst)
	if err != nil {
		return k, err
	}

	if !t.g.inTransaction && dst != nil {
		t.g.cache[memkey(k)] = dst
	}

	// Before returning, update the struct to have correct key info
	if dst != nil {
		setStructKey(dst, k)
	}

	return k, err
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"errors"
	"log"
	"math"
	"sort"
	"strconv"
	"strings"
	"time"
)

type QueryDesc struct {
	Columns    []ColumnDesc `json:"columns,omitempty"`
	TimeRange  TimeRange    `json:"time_range"`
	GroupBy    []string     `json:"group_by,omitempty"`
	Filters    []Filter     `json:"filters,omitempty"`
	PointSize  int64        `json:"point_size,omitempty"`
	OrderBy    []string     `json:"order_by,omitempty"`
	Descending bool         `json:"descending"`
	Limit      int          `json:"limit,omitempty"`
}

type ColumnDesc struct {
	Name      string `json:"name"`
	Aggregate string `json:"aggregate,omitempty"`
}

type TimeRange struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

type Filter struct {
	Column    string      `json:"column"`
	Condition string      `json:"condition"`
	Value     interface{} `json:"value"`
}

type QueryResult struct {
	Summary []Event     `json:"summary,omitempty"`
	Series  []Event     `json:"series,omitempty"`
	Events  []Event     `json:"events,omitempty"`
	Query   interface{} `json:"query"`
}

type ByTimestamp []Event

func (t ByTimestamp) Len() int      { return len(t) }
func (t ByTimestamp) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
func (t ByTimestamp) Less(i, j int) bool {
	return t[i]["_ts"].(time.Time).Before(t[j]["_ts"].(time.Time))
}

type OrderBy struct {
	columns []string
	events  []Event
}

func (o OrderBy) Len() int      { return len(o.events) }
func (o OrderBy) Swap(i, j int) { o.events[i], o.events[j] = o.events[j], o.events[i] }
func (o OrderBy) Less(i, j int) bool {
	for _, col := range o.columns {
		if compareInterfaces(o.events[i][col], o.events[j][col]) >= 0 {
			return false
		}
	}
	return true
}

func (c *EventCollection) Query(desc QueryDesc) (*QueryResult, error) {
	c.lock.RLock()
	defer c.lock.RUnlock()

	if desc.TimeRange.Start.Before(minTimestamp) {
		desc.TimeRange.Start = minTimestamp
	}
	if desc.TimeRange.End.Before(minTimestamp) {
		desc.TimeRange.End = minTimestamp
	}

	if desc.TimeRange.Start == minTimestamp && desc.TimeRange.End == minTimestamp {
		desc.TimeRange.End = fromMicrosecondTime(math.MaxInt64)
	}

	cur, err := c.col.NewCursor()
	if err != nil {
		return nil, err
	}

	formattedStartTs := formatTs(toMicrosecondTime(desc.TimeRange.Start))
	formattedEndTs := formatTs(toMicrosecondTime(desc.TimeRange.End))

	startKey := string(eventKeyPrefix) + string(formattedStartTs[:])
	endKey := string(eventKeyPrefix) + string(formattedEndTs[:]) + "\xff"

	summaryRows := map[string][]float64{}
	summaryRowsByTime := map[int64]map[string][]float64{}
	resultEvents := []Event{}

	cur.Seek(startKey)

CursorLoop:
	for cur.Next() {
		if cur.Key() > endKey {
			break
		}

		if (cur.Key())[0] == '_' {
			continue
		}

		// Extract event
		id := cur.Key()
		val := cur.Value()
		ts, keyTag, hash, err := splitCollectionID(id)
		if err != nil {
			log.Println(err)
			return nil, err
		}

		if ts < toMicrosecondTime(desc.TimeRange.Start) {
			continue CursorLoop
		}

		event := Event{}
		valBytes := []byte(val)
		err = json.Unmarshal(valBytes, &event)
		if err != nil {
			log.Println(err)
			return nil, err
		}

		eventID := strconv.FormatInt(ts, 10) + "|" + keyTag
		event["_ts"] = ts
		event["_tag"] = keyTag
		if len(hash) > 0 {
			event["_hash"] = hash
			eventID += "|" + hash
		}
		event["_id"] = eventID

		// Apply filters
		for _, filter := range desc.Filters {
			if colValue, ok := event[filter.Column]; ok {
				filterResult := false
				switch filter.Condition {
				case "eq":
					filterResult = checkEquals(colValue, filter.Value)
				case "neq":
					filterResult = !checkEquals(colValue, filter.Value)
				default:
					return nil, errors.New("invalid filter condition")
				}

				if !filterResult {
					continue CursorLoop
				}
			} else {
				continue CursorLoop
			}
		}

		if len(desc.GroupBy) == 0 && len(desc.Columns) == 0 && desc.PointSize <= 0 {
			// No group by or aggregates
			event["_ts"] = fromMicrosecondTime(ts)
			resultEvents = append(resultEvents, event)
			if desc.Limit > 0 && len(resultEvents) == desc.Limit {
				break
			}
			continue
		}

		// Figure out the row key for grouping
		rowKey := ""
		if len(desc.GroupBy) > 0 {
			rowKeyParts := []string{}
			for _, groupCol := range desc.GroupBy {
				groupColVal := event[groupCol]
				if groupColVal == nil {
					continue CursorLoop
				}
				marshaledColVal, err := json.Marshal(groupColVal)
				if err != nil {
					continue CursorLoop
				}
				rowKeyParts = append(rowKeyParts, string(marshaledColVal))
			}
			rowKey = strings.Join(rowKeyParts, "\x00")
		}

		// Do the aggregations.

		updateRows := func(rowKey string, rows map[string][]float64) {
			rowAggregates, ok := rows[rowKey]
			if !ok {
				rowAggregates = make([]float64, len(desc.Columns))
				for i := range rowAggregates {
					rowAggregates[i] = math.NaN()
				}
			}

			for i, columnDesc := range desc.Columns {
				floatVal := 0.0
				columnVal := event[columnDesc.Name]
				switch columnVal.(type) {
				case int:
					floatVal = float64(columnVal.(int))
				case float64:
					floatVal = columnVal.(float64)
				}
				switch columnDesc.Aggregate {
				case "sum":
					if math.IsNaN(rowAggregates[i]) {
						rowAggregates[i] = 0
					}
					rowAggregates[i] += floatVal
				case "count":
					if math.IsNaN(rowAggregates[i]) {
						rowAggregates[i] = 0
					}
					rowAggregates[i] += 1
				case "min":
					if rowAggregates[i] > floatVal || math.IsNaN(rowAggregates[i]) {
						rowAggregates[i] = floatVal
					}
				case "max":
					if rowAggregates[i] < floatVal || math.IsNaN(rowAggregates[i]) {
						rowAggregates[i] = floatVal
					}
				}
			}

			rows[rowKey] = rowAggregates
		}

		if len(desc.Columns) > 0 {
			updateRows(rowKey, summaryRows)
		}

		if desc.PointSize > 0 {
			timeGroup := ts / desc.PointSize
			var rows map[string][]float64
			var ok bool
			if rows, ok = summaryRowsByTime[timeGroup]; !ok {
				rows = map[string][]float64{}
				summaryRowsByTime[timeGroup] = rows
			}
			updateRows(rowKey, rows)
		}
	} // Event cursor loop

	if err = cur.Err(); err != nil {
		return nil, err
	}

	summaryEvents := []Event{}
	for rowKey, rowAggregates := range summaryRows {
		event := Event{}
		if len(desc.GroupBy) > 0 {
			parts := strings.Split(rowKey, "\x00")
			for i, part := range parts {
				if desc.GroupBy[i] == "_ts" {
					ts, _ := strconv.Atoi(part)
					event["_ts"] = fromMicrosecondTime(int64(ts))
					continue
				}
				var val interface{}
				dec := json.NewDecoder(strings.NewReader(part))
				dec.UseNumber()
				dec.Decode(&val)
				event[desc.GroupBy[i]] = val
			}
		}
		for i, columnDesc := range desc.Columns {
			fieldName := columnDesc.Aggregate + "(" + columnDesc.Name + ")"
			event[fieldName] = rowAggregates[i]
		}
		summaryEvents = append(summaryEvents, event)
	}

	if len(desc.OrderBy) != 0 {
		var ordering sort.Interface = OrderBy{
			columns: desc.OrderBy,
			events:  summaryEvents,
		}
		if desc.Descending {
			ordering = sort.Reverse(ordering)
		}
		sort.Stable(ordering)
	}

	if desc.Limit > 0 && len(summaryEvents) > desc.Limit {
		summaryEvents = summaryEvents[:desc.Limit]
	}

	seriesEvents := []Event{}
	if desc.PointSize > 0 {
		for ts, rows := range summaryRowsByTime {
			for rowKey, rowAggregates := range rows {
				event := Event{
					"_ts": fromMicrosecondTime(ts * desc.PointSize),
				}
				if len(desc.GroupBy) > 0 {
					parts := strings.Split(rowKey, "\x00")
					for i, part := range parts {
						if desc.GroupBy[i] == "_ts" {
							continue
						}
						var val interface{}
						dec := json.NewDecoder(strings.NewReader(part))
						dec.UseNumber()
						dec.Decode(&val)
						event[desc.GroupBy[i]] = val
					}
				}
				for i, columnDesc := range desc.Columns {
					fieldName := columnDesc.Aggregate + "(" + columnDesc.Name + ")"
					event[fieldName] = rowAggregates[i]
				}
				seriesEvents = append(seriesEvents, event)
			}
		}

		sort.Sort(ByTimestamp(seriesEvents))
	}

	return &QueryResult{Summary: summaryEvents, Series: seriesEvents, Events: resultEvents, Query: desc}, nil
}

func splitCollectionID(id string) (int64, string, string, error) {
	if len(id) < 1 {
		return 0, "", "", errors.New("invalid ID 2")
	}
	if id[0] != eventKeyPrefix {
		return 0, "", "", errors.New("invalid ID prefix")
	}
	id = id[1:]

	if len(id) < 8+2 {
		return 0, "", "", errors.New("invalid ID 3")
	}

	formattedTs := [8]byte{
		id[0],
		id[1],
		id[2],
		id[3],
		id[4],
		id[5],
		id[6],
		id[7],
	}

	ts := parseTs(formattedTs)

	id = id[8:]

	if id[0] != '|' {
		return 0, "", "", errors.New("invalid ID 4")
	}

	id = id[1:]

	parts := strings.Split(id, "|")

	if len(parts) != 2 {
		return 0, "", "", errors.New("invalid ID 5")
	}

	return ts, parts[0], parts[1], nil
}

func checkEquals(a, b interface{}) bool {
	return compareInterfaces(a, b) == 0
}

func compareInterfaces(a, b interface{}) int {
	switch a.(type) {
	case int:
		aInt := a.(int)
		if bInt, ok := b.(int); ok {
			return aInt - bInt
		}
	case float64:
		aFloat := a.(float64)
		if bFloat, ok := b.(float64); ok {
			if aFloat == bFloat {
				return 0
			} else if aFloat < bFloat {
				return -1
			} else {
				return 1
			}
		}
	case string:
		aString := a.(string)
		if bString, ok := b.(string); ok {
			if aString == bString {
				return 0
			} else if aString < bString {
				return -1
			} else {
				return 1
			}
		}
	case json.Number:
		aFloat, _ := strconv.ParseFloat(string(a.(json.Number)), 64)
		if bNumber, ok := b.(json.Number); ok {
			bFloat, _ := strconv.ParseFloat(string(bNumber), 64)
			if aFloat == bFloat {
				return 0
			} else if aFloat < bFloat {
				return -1
			} else {
				return 1
			}
		}
	}
	return -1
}
<commit_msg>add group IDs to query results; #70 (#76)<commit_after>package main

import (
	"crypto/md5"
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"math"
	"sort"
	"strconv"
	"strings"
	"time"
)

type QueryDesc struct {
	Columns    []ColumnDesc `json:"columns,omitempty"`
	TimeRange  TimeRange    `json:"time_range"`
	GroupBy    []string     `json:"group_by,omitempty"`
	Filters    []Filter     `json:"filters,omitempty"`
	PointSize  int64        `json:"point_size,omitempty"`
	OrderBy    []string     `json:"order_by,omitempty"`
	Descending bool         `json:"descending"`
	Limit      int          `json:"limit,omitempty"`
}

type ColumnDesc struct {
	Name      string `json:"name"`
	Aggregate string `json:"aggregate,omitempty"`
}

type TimeRange struct {
	Start time.Time `json:"start"`
	End   time.Time `json:"end"`
}

type Filter struct {
	Column    string      `json:"column"`
	Condition string      `json:"condition"`
	Value     interface{} `json:"value"`
}

type QueryResult struct {
	Summary []Event     `json:"summary,omitempty"`
	Series  []Event     `json:"series,omitempty"`
	Events  []Event     `json:"events,omitempty"`
	Query   interface{} `json:"query"`
}

type ByTimestamp []Event

func (t ByTimestamp) Len() int      { return len(t) }
func (t ByTimestamp) Swap(i, j int) { t[i], t[j] = t[j], t[i] }
func (t ByTimestamp) Less(i, j int) bool {
	return t[i]["_ts"].(time.Time).Before(t[j]["_ts"].(time.Time))
}

type OrderBy struct {
	columns []string
	events  []Event
}

func (o OrderBy) Len() int      { return len(o.events) }
func (o OrderBy) Swap(i, j int) { o.events[i], o.events[j] = o.events[j], o.events[i] }
func (o OrderBy) Less(i, j int) bool {
	for _, col := range o.columns {
		if compareInterfaces(o.events[i][col], o.events[j][col]) >= 0 {
			return false
		}
	}
	return true
}

func (c *EventCollection) Query(desc QueryDesc) (*QueryResult, error) {
	c.lock.RLock()
	defer c.lock.RUnlock()

	if desc.TimeRange.Start.Before(minTimestamp) {
		desc.TimeRange.Start = minTimestamp
	}
	if desc.TimeRange.End.Before(minTimestamp) {
		desc.TimeRange.End = minTimestamp
	}

	if desc.TimeRange.Start == minTimestamp && desc.TimeRange.End == minTimestamp {
		desc.TimeRange.End = fromMicrosecondTime(math.MaxInt64)
	}

	cur, err := c.col.NewCursor()
	if err != nil {
		return nil, err
	}

	formattedStartTs := formatTs(toMicrosecondTime(desc.TimeRange.Start))
	formattedEndTs := formatTs(toMicrosecondTime(desc.TimeRange.End))

	startKey := string(eventKeyPrefix) + string(formattedStartTs[:])
	endKey := string(eventKeyPrefix) + string(formattedEndTs[:]) + "\xff"

	summaryRows := map[string][]float64{}
	summaryRowsByTime := map[int64]map[string][]float64{}
	resultEvents := []Event{}

	cur.Seek(startKey)

CursorLoop:
	for cur.Next() {
		if cur.Key() > endKey {
			break
		}

		if (cur.Key())[0] == '_' {
			continue
		}

		// Extract event
		id := cur.Key()
		val := cur.Value()
		ts, keyTag, hash, err := splitCollectionID(id)
		if err != nil {
			log.Println(err)
			return nil, err
		}

		if ts < toMicrosecondTime(desc.TimeRange.Start) {
			continue CursorLoop
		}

		event := Event{}
		valBytes := []byte(val)
		err = json.Unmarshal(valBytes, &event)
		if err != nil {
			log.Println(err)
			return nil, err
		}

		eventID := strconv.FormatInt(ts, 10) + "|" + keyTag
		event["_ts"] = ts
		event["_tag"] = keyTag
		if len(hash) > 0 {
			event["_hash"] = hash
			eventID += "|" + hash
		}
		event["_id"] = eventID

		// Apply filters
		for _, filter := range desc.Filters {
			if colValue, ok := event[filter.Column]; ok {
				filterResult := false
				switch filter.Condition {
				case "eq":
					filterResult = checkEquals(colValue, filter.Value)
				case "neq":
					filterResult = !checkEquals(colValue, filter.Value)
				default:
					return nil, errors.New("invalid filter condition")
				}

				if !filterResult {
					continue CursorLoop
				}
			} else {
				continue CursorLoop
			}
		}

		if len(desc.GroupBy) == 0 && len(desc.Columns) == 0 && desc.PointSize <= 0 {
			// No group by or aggregates
			event["_ts"] = fromMicrosecondTime(ts)
			resultEvents = append(resultEvents, event)
			if desc.Limit > 0 && len(resultEvents) == desc.Limit {
				break
			}
			continue
		}

		// Figure out the row key for grouping
		rowKey := ""
		if len(desc.GroupBy) > 0 {
			rowKeyParts := []string{}
			for _, groupCol := range desc.GroupBy {
				groupColVal := event[groupCol]
				if groupColVal == nil {
					continue CursorLoop
				}
				marshaledColVal, err := json.Marshal(groupColVal)
				if err != nil {
					continue CursorLoop
				}
				rowKeyParts = append(rowKeyParts, string(marshaledColVal))
			}
			rowKey = strings.Join(rowKeyParts, "\x00")
		}

		// Do the aggregations.

		updateRows := func(rowKey string, rows map[string][]float64) {
			rowAggregates, ok := rows[rowKey]
			if !ok {
				rowAggregates = make([]float64, len(desc.Columns))
				for i := range rowAggregates {
					rowAggregates[i] = math.NaN()
				}
			}

			for i, columnDesc := range desc.Columns {
				floatVal := 0.0
				columnVal := event[columnDesc.Name]
				switch columnVal.(type) {
				case int:
					floatVal = float64(columnVal.(int))
				case float64:
					floatVal = columnVal.(float64)
				}
				switch columnDesc.Aggregate {
				case "sum":
					if math.IsNaN(rowAggregates[i]) {
						rowAggregates[i] = 0
					}
					rowAggregates[i] += floatVal
				case "count":
					if math.IsNaN(rowAggregates[i]) {
						rowAggregates[i] = 0
					}
					rowAggregates[i] += 1
				case "min":
					if rowAggregates[i] > floatVal || math.IsNaN(rowAggregates[i]) {
						rowAggregates[i] = floatVal
					}
				case "max":
					if rowAggregates[i] < floatVal || math.IsNaN(rowAggregates[i]) {
						rowAggregates[i] = floatVal
					}
				}
			}

			rows[rowKey] = rowAggregates
		}

		if len(desc.Columns) > 0 {
			updateRows(rowKey, summaryRows)
		}

		if desc.PointSize > 0 {
			timeGroup := ts / desc.PointSize
			var rows map[string][]float64
			var ok bool
			if rows, ok = summaryRowsByTime[timeGroup]; !ok {
				rows = map[string][]float64{}
				summaryRowsByTime[timeGroup] = rows
			}
			updateRows(rowKey, rows)
		}
	} // Event cursor loop

	if err = cur.Err(); err != nil {
		return nil, err
	}

	summaryEvents := []Event{}
	for rowKey, rowAggregates := range summaryRows {
		event := Event{}
		if len(desc.GroupBy) > 0 {
			parts := strings.Split(rowKey, "\x00")
			for i, part := range parts {
				if desc.GroupBy[i] == "_ts" {
					ts, _ := strconv.Atoi(part)
					event["_ts"] = fromMicrosecondTime(int64(ts))
					continue
				}
				var val interface{}
				dec := json.NewDecoder(strings.NewReader(part))
				dec.UseNumber()
				dec.Decode(&val)
				event[desc.GroupBy[i]] = val
			}
		}
		for i, columnDesc := range desc.Columns {
			fieldName := columnDesc.Aggregate + "(" + columnDesc.Name + ")"
			event[fieldName] = rowAggregates[i]
		}
		rowKeyHash := md5.Sum([]byte(rowKey))
		event["_group_id"] = fmt.Sprintf("%x", rowKeyHash[:8])
		summaryEvents = append(summaryEvents, event)
	}

	if len(desc.OrderBy) != 0 {
		var ordering sort.Interface = OrderBy{
			columns: desc.OrderBy,
			events:  summaryEvents,
		}
		if desc.Descending {
			ordering = sort.Reverse(ordering)
		}
		sort.Stable(ordering)
	}

	if desc.Limit > 0 && len(summaryEvents) > desc.Limit {
		summaryEvents = summaryEvents[:desc.Limit]
	}

	seriesEvents := []Event{}
	if desc.PointSize > 0 {
		for ts, rows := range summaryRowsByTime {
			for rowKey, rowAggregates := range rows {
				event := Event{
					"_ts": fromMicrosecondTime(ts * desc.PointSize),
				}
				if len(desc.GroupBy) > 0 {
					parts := strings.Split(rowKey, "\x00")
					for i, part := range parts {
						if desc.GroupBy[i] == "_ts" {
							continue
						}
						var val interface{}
						dec := json.NewDecoder(strings.NewReader(part))
						dec.UseNumber()
						dec.Decode(&val)
						event[desc.GroupBy[i]] = val
					}
				}
				for i, columnDesc := range desc.Columns {
					fieldName := columnDesc.Aggregate + "(" + columnDesc.Name + ")"
					event[fieldName] = rowAggregates[i]
				}
				rowKeyHash := md5.Sum([]byte(rowKey))
				event["_group_id"] = fmt.Sprintf("%x", rowKeyHash[:8])
				seriesEvents = append(seriesEvents, event)
			}
		}

		sort.Sort(ByTimestamp(seriesEvents))
	}

	return &QueryResult{Summary: summaryEvents, Series: seriesEvents, Events: resultEvents, Query: desc}, nil
}

func splitCollectionID(id string) (int64, string, string, error) {
	if len(id) < 1 {
		return 0, "", "", errors.New("invalid ID 2")
	}
	if id[0] != eventKeyPrefix {
		return 0, "", "", errors.New("invalid ID prefix")
	}
	id = id[1:]

	if len(id) < 8+2 {
		return 0, "", "", errors.New("invalid ID 3")
	}

	formattedTs := [8]byte{
		id[0],
		id[1],
		id[2],
		id[3],
		id[4],
		id[5],
		id[6],
		id[7],
	}

	ts := parseTs(formattedTs)

	id = id[8:]

	if id[0] != '|' {
		return 0, "", "", errors.New("invalid ID 4")
	}

	id = id[1:]

	parts := strings.Split(id, "|")

	if len(parts) != 2 {
		return 0, "", "", errors.New("invalid ID 5")
	}

	return ts, parts[0], parts[1], nil
}

func checkEquals(a, b interface{}) bool {
	return compareInterfaces(a, b) == 0
}

func compareInterfaces(a, b interface{}) int {
	switch a.(type) {
	case int:
		aInt := a.(int)
		if bInt, ok := b.(int); ok {
			return aInt - bInt
		}
	case float64:
		aFloat := a.(float64)
		if bFloat, ok := b.(float64); ok {
			if aFloat == bFloat {
				return 0
			} else if aFloat < bFloat {
				return -1
			} else {
				return 1
			}
		}
	case string:
		aString := a.(string)
		if bString, ok := b.(string); ok {
			if aString == bString {
				return 0
			} else if aString < bString {
				return -1
			} else {
				return 1
			}
		}
	case json.Number:
		aFloat, _ := strconv.ParseFloat(string(a.(json.Number)), 64)
		if bNumber, ok := b.(json.Number); ok {
			bFloat, _ := strconv.ParseFloat(string(bNumber), 64)
			if aFloat == bFloat {
				return 0
			} else if aFloat < bFloat {
				return -1
			} else {
				return 1
			}
		}
	}
	return -1
}
<|endoftext|>


<commit_before>package aws

import (
	"fmt"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/lambda"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSCloudwatchLogSubscriptionFilter_basic(t *testing.T) {
	var conf lambda.GetFunctionOutput

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckCloudwatchLogSubscriptionFilterDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAWSCloudwatchLogSubscriptionFilterConfig,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsCloudwatchLogSubscriptionFilterExists("aws_cloudwatch_log_subscription_filter.test_lambdafunction_logfilter", &conf),
					testAccCheckAWSCloudwatchLogSubscriptionFilterAttributes(&conf),
				),
			},
		},
	})
}

func testAccCheckCloudwatchLogSubscriptionFilterDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).lambdaconn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_cloudwatch_log_subscription_filter" {
			continue
		}

		_, err := conn.GetFunction(&lambda.GetFunctionInput{
			FunctionName: aws.String(rs.Primary.ID),
		})

		if err == nil {
			return fmt.Errorf("Lambda Function still exists")
		}

	}

	return nil

}

func testAccCheckAwsCloudwatchLogSubscriptionFilterExists(n string, function *lambda.GetFunctionOutput) resource.TestCheckFunc {
	// Wait for IAM role
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Lambda function not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("Lambda function ID not set")
		}

		conn := testAccProvider.Meta().(*AWSClient).lambdaconn

		params := &lambda.GetFunctionInput{
			FunctionName: aws.String("example_lambda_name"),
		}

		getFunction, err := conn.GetFunction(params)
		if err != nil {
			return err
		}

		*function = *getFunction

		return nil
	}
}

func testAccCheckAWSCloudwatchLogSubscriptionFilterAttributes(function *lambda.GetFunctionOutput) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		c := function.Configuration
		const expectedName = "example_lambda_name"
		if *c.FunctionName != expectedName {
			return fmt.Errorf("Expected function name %s, got %s", expectedName, *c.FunctionName)
		}

		if *c.FunctionArn == "" {
			return fmt.Errorf("Could not read Lambda Function's ARN")
		}

		return nil
	}
}

const testAccAWSCloudwatchLogSubscriptionFilterConfig = `
resource "aws_cloudwatch_log_subscription_filter" "test_lambdafunction_logfilter" {
  name            = "test_lambdafunction_logfilter"
  log_group_name  = "example_lambda_name"
  filter_pattern  = "logtype test"
  destination_arn = "${aws_lambda_function.test_lambdafunction.arn}"
}

resource "aws_lambda_function" "test_lambdafunction" {
  filename      = "test-fixtures/lambdatest.zip"
  function_name = "example_lambda_name"
  role          = "${aws_iam_role.iam_for_lambda.arn}"
  handler       = "exports.handler"
}

resource "aws_cloudwatch_log_group" "logs" {
  name              = "example_lambda_name"
  retention_in_days = 1
}

resource "aws_lambda_permission" "allow_cloudwatch_logs" {
  statement_id  = "AllowExecutionFromCloudWatchLogs"
  action        = "lambda:*"
  function_name = "${aws_lambda_function.test_lambdafunction.arn}"
  principal     = "logs.us-west-2.amazonaws.com"
}

resource "aws_iam_role" "iam_for_lambda" {
  name = "test_lambdafuntion_iam_role"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_role_policy" "test_lambdafunction_iam_policy" {
  name = "test_lambdafunction_iam_policy"
  role = "${aws_iam_role.iam_for_lambda.id}"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1441111030000",
      "Effect": "Allow",
      "Action": [
        "dynamodb:*"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}
EOF
}
`
<commit_msg>provider/aws: randomiz names in TestAccAWSCloudwatchLogSubscriptionFilter_basic<commit_after>package aws

import (
	"fmt"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/lambda"
	"github.com/hashicorp/terraform/helper/acctest"
	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSCloudwatchLogSubscriptionFilter_basic(t *testing.T) {
	var conf lambda.GetFunctionOutput

	rstring := acctest.RandString(5)

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckCloudwatchLogSubscriptionFilterDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAWSCloudwatchLogSubscriptionFilterConfig(rstring),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckAwsCloudwatchLogSubscriptionFilterExists("aws_cloudwatch_log_subscription_filter.test_lambdafunction_logfilter", &conf, rstring),
					testAccCheckAWSCloudwatchLogSubscriptionFilterAttributes(&conf, rstring),
				),
			},
		},
	})
}

func testAccCheckCloudwatchLogSubscriptionFilterDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).lambdaconn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_cloudwatch_log_subscription_filter" {
			continue
		}

		_, err := conn.GetFunction(&lambda.GetFunctionInput{
			FunctionName: aws.String(rs.Primary.ID),
		})

		if err == nil {
			return fmt.Errorf("Lambda Function still exists")
		}

	}

	return nil

}

func testAccCheckAwsCloudwatchLogSubscriptionFilterExists(n string, function *lambda.GetFunctionOutput, rstring string) resource.TestCheckFunc {
	// Wait for IAM role
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Lambda function not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("Lambda function ID not set")
		}

		conn := testAccProvider.Meta().(*AWSClient).lambdaconn

		params := &lambda.GetFunctionInput{
			FunctionName: aws.String("example_lambda_name_" + rstring),
		}

		getFunction, err := conn.GetFunction(params)
		if err != nil {
			return err
		}

		*function = *getFunction

		return nil
	}
}

func testAccCheckAWSCloudwatchLogSubscriptionFilterAttributes(function *lambda.GetFunctionOutput, rstring string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		c := function.Configuration
		expectedName := fmt.Sprintf("example_lambda_name_%s", rstring)
		if *c.FunctionName != expectedName {
			return fmt.Errorf("Expected function name %s, got %s", expectedName, *c.FunctionName)
		}

		if *c.FunctionArn == "" {
			return fmt.Errorf("Could not read Lambda Function's ARN")
		}

		return nil
	}
}

func testAccAWSCloudwatchLogSubscriptionFilterConfig(rstring string) string {
	return fmt.Sprintf(`
resource "aws_cloudwatch_log_subscription_filter" "test_lambdafunction_logfilter" {
  name            = "test_lambdafunction_logfilter"
  log_group_name  = "example_lambda_name"
  filter_pattern  = "logtype test"
  destination_arn = "${aws_lambda_function.test_lambdafunction.arn}"
}

resource "aws_lambda_function" "test_lambdafunction" {
  filename      = "test-fixtures/lambdatest.zip"
  function_name = "example_lambda_name_%s"
  role          = "${aws_iam_role.iam_for_lambda.arn}"
  handler       = "exports.handler"
}

resource "aws_cloudwatch_log_group" "logs" {
  name              = "example_lambda_name"
  retention_in_days = 1
}

resource "aws_lambda_permission" "allow_cloudwatch_logs" {
  statement_id  = "AllowExecutionFromCloudWatchLogs"
  action        = "lambda:*"
  function_name = "${aws_lambda_function.test_lambdafunction.arn}"
  principal     = "logs.us-west-2.amazonaws.com"
}

resource "aws_iam_role" "iam_for_lambda" {
  name = "test_lambdafuntion_iam_role_%s"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    }
  ]
}
EOF
}

resource "aws_iam_role_policy" "test_lambdafunction_iam_policy" {
  name = "test_lambdafunction_iam_policy"
  role = "${aws_iam_role.iam_for_lambda.id}"

  policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1441111030000",
      "Effect": "Allow",
      "Action": [
        "dynamodb:*"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}
EOF
}
`, rstring, rstring)
}
<|endoftext|>


<commit_before>package jp

import (
	"bytes"
	"encoding/json"
	"log"
	"os/exec"
)

type VerbSimpleConjugation struct {
	KForm, Conjugated string
}

type VerbComplexConjugation struct {
	CForm, Politeness, Polarity, Conjugated string
}

type japkatResult struct {
	basic   []VerbSimpleConjugation
	complex []VerbComplexConjugation
}

type Verb struct {
	Raw string
}

func NewVerb(verb string) Verb {
	return Verb{Raw: verb}
}

func (verb *Verb) conjugate() (error, []VerbSimpleConjugation, []VerbComplexConjugation) {
	cmd := exec.Command("JapKatsuyouCLI", verb.Raw)
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}

	result := japkatResult{}
	err = json.Unmarshal(out.Bytes(), &result)
	if err != nil {
		log.Fatal(err)
	}

	return err, result.basic, result.complex
}
<commit_msg>same fix as last<commit_after>package jp

import (
	"bytes"
	"encoding/json"
	"log"
	"os/exec"
)

type VerbSimpleConjugation struct {
	KForm, Conjugated string
}

type VerbComplexConjugation struct {
	CForm, Politeness, Polarity, Conjugated string
}

type japkatResult struct {
	basic   []VerbSimpleConjugation
	complex []VerbComplexConjugation
}

type Verb struct {
	Raw string
}

func NewVerb(verb string) Verb {
	return Verb{Raw: verb}
}

func (verb *Verb) Conjugate() (error, []VerbSimpleConjugation, []VerbComplexConjugation) {
	cmd := exec.Command("JapKatsuyouCLI", verb.Raw)
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}

	result := japkatResult{}
	err = json.Unmarshal(out.Bytes(), &result)
	if err != nil {
		log.Fatal(err)
	}

	return err, result.basic, result.complex
}
<|endoftext|>


<commit_before>package main
import (
	"github.com/nsf/termbox-go"
	"github.com/mattn/go-runewidth"
	"fmt"
	"strings"
)

type View struct {
	Quit   bool
	width  int
	height int
	top    int
	ptr    int
	live   *NicoLive
	komes  []Kome
	cmd    []rune
}

func NewView(live *NicoLive) *View {
	w, h := termbox.Size()
	return &View {
		width:  w,
		height: h,
		top:    0,
		ptr:    0,
		live:   live,
	}
}

func (v *View) UpdateEvent(ev termbox.Event) {
	switch ev.Type {
	case termbox.EventResize:
		v.width, v.height = ev.Width, ev.Height
		v.fixPtr()
	case termbox.EventKey:
		if len(v.cmd) != 0 {
			// cmd now
			switch ev.Key {
			case termbox.KeyEnter:
				v.execCommand()
			case termbox.KeyBackspace, termbox.KeyBackspace2:
				v.cmd = v.cmd[0:len(v.cmd)-1]
			case termbox.KeySpace:
				v.cmd = append(v.cmd, ' ')
			default:
				if ev.Ch != 0 {
					v.cmd = append(v.cmd, ev.Ch)
				}
			}
			return
		}

		switch ev.Ch {
		case 'i', ':', '/':
			v.cmd = append(v.cmd, ev.Ch)
		case 'j':
			v.ptr++
			v.fixPtr()
		case 'k':
			v.ptr--
			v.fixPtr()
		case 'G':
			v.ptr = len(v.komes) - 1
			v.fixPtr()
		}
	}
}

func (v *View) calcEnd() int {
	end := v.top + (v.height - 2)
	if end > len(v.komes) {
		end = len(v.komes)
	}
	return end
}

func (v *View) fixPtr() {
	if v.ptr < 0 {
		v.ptr = 0
	}
	if v.ptr >= len(v.komes) {
		v.ptr = len(v.komes) - 1
	}

	if v.ptr < v.top {
		v.top = v.ptr
		return
	}

	end := v.calcEnd()
	if v.ptr >= end {
		v.top += v.ptr - end + 1
		return
	}
}

func (v *View) execCommand() {
	defer func(){
		v.cmd = nil
	}()

	cmd := string(v.cmd)
	if cmd == ":q" {
		v.Quit = true
		return
	}

	if strings.HasPrefix(cmd, "i184 ") {
		comment := cmd[5:]
		v.live.SendKome(comment, true)
		return
	}
	if strings.HasPrefix(cmd, "i ") {
		comment := cmd[2:]
		v.live.SendKome(comment, false)
		return
	}
}

func (v *View) UpdateKome(kome Kome) {
	end := v.calcEnd()
	if end == len(v.komes) {
		if end - v.top + 1 > v.height - 2 {
			v.top++
			if v.ptr < v.top {
				v.ptr = v.top
			}
		}
	}

	v.komes = append(v.komes, kome)
}

func (v *View) UpdateView() {
	termbox.HideCursor()
	nowCmd := len(v.cmd) != 0

	// line view
	if len(v.komes) > 0 && v.height > 2 {
		end := v.calcEnd()

		noPadFormat := func() string {
			last := v.komes[end - 1]
			noStr := fmt.Sprintf("%d", last.No)
			return fmt.Sprintf("%%0%dd", len(noStr))
		}()
		maxUserIDLen := func() int {
			maxLen := 0
			for _, kome := range v.komes[v.top:end] {
				l := len(kome.UserID)
				if kome.Is184Comment() {
					l = 3
				}
				if l > maxLen {
					maxLen = l
				}
			}
			return maxLen
		}()

		y := 0
		for i := v.top; i < end; i++ {
			bg := termbox.ColorDefault
			if i == v.ptr {
				bg = termbox.ColorGreen
			}

			x := 0
			{
				// no
				fg := termbox.ColorBlue
				if i == v.ptr {
					fg = termbox.ColorDefault
				}

				no := fmt.Sprintf(noPadFormat, v.komes[i].No)
				for _, c := range no {
					termbox.SetCell(x, y, c, fg, bg)
					x++
				}
			}

			termbox.SetCell(x, y, ' ', termbox.ColorDefault, bg)
			x++

			{
				// userID
				fg := termbox.ColorGreen
				userID := v.komes[i].UserID

				if v.komes[i].Is184Comment() {
					fg = termbox.ColorYellow
					userID = "184"
				}
				if i == v.ptr {
					fg = termbox.ColorDefault
				}

				for len(userID) < maxUserIDLen {
					userID += " "
				}
				for _, c := range userID {
					termbox.SetCell(x, y, c, fg, bg)
					x++
				}
			}

			termbox.SetCell(x, y, ' ', termbox.ColorDefault, bg)
			x++

			for _, c := range v.komes[i].Comment {
				termbox.SetCell(x, y, c, termbox.ColorDefault, bg)
				x += width(c)
			}
			for ;x < v.width; x++ {
				termbox.SetCell(x, y, ' ', termbox.ColorDefault, bg)
			}

			if i == v.ptr && !nowCmd {
				termbox.SetCursor(v.width - 1, y)
			}
			y++
		}
		for ; y < v.height - 2; y++ {
			for x := 0; x < v.width; x++ {
				termbox.SetCell(x, y, ' ', termbox.ColorDefault, termbox.ColorDefault)
			}
		}
	}

	// info view
	if v.height > 1 {
		left := fmt.Sprintf("[%s] %s", v.live.LiveID, v.live.Status.Stream.Title)

		par := 0
		if len(v.komes) > 0 {
			par = v.calcEnd() * 100 / len(v.komes)
		}
		right := fmt.Sprintf("%d%%", par)

		y := v.height - 2
		x := 0
		for _, c := range left {
			termbox.SetCell(x, y, c, termbox.ColorDefault, termbox.ColorBlue)
			x += width(c)
		}

		mid := v.width - x - len(right)
		if mid > 0 {
			for i := 0; i < mid; i++ {
				termbox.SetCell(x, y, ' ', termbox.ColorDefault, termbox.ColorBlue)
				x++
			}
			for _, c := range right {
				termbox.SetCell(x, y, c, termbox.ColorDefault, termbox.ColorBlue)
				x++
			}
		}

		for ; x < v.width; x++ {
			termbox.SetCell(x, y, ' ', termbox.ColorDefault, termbox.ColorBlue)
		}
	}

	// cmd view
	if v.height > 0 {
		y := v.height - 1
		x := 0
		for _, c := range v.cmd {
			termbox.SetCell(x, y, c, termbox.ColorGreen, termbox.ColorDefault)
			x += width(c)
		}
		if nowCmd {
			termbox.SetCursor(x, y)
		}
		for ; x < v.width; x++ {
			termbox.SetCell(x, y, ' ', termbox.ColorDefault, termbox.ColorDefault)
		}
	}

	termbox.Flush()
}

func width(c rune) int {
	w := runewidth.RuneWidth(c)
	if w == 0 || w == 2 && runewidth.IsAmbiguousWidth(c) {
		w = 1
	}
	return w
}<commit_msg>コマンド追加<commit_after>package main
import (
	"github.com/nsf/termbox-go"
	"github.com/mattn/go-runewidth"
	"fmt"
	"strings"
	"time"
	"strconv"
)

const chainThreshold = 500 * 1000 * 1000

type View struct {
	Quit   bool
	width  int
	height int
	top    int
	ptr    int
	live   *NicoLive
	komes  []Kome
	cmd    []rune
	prev   int64
	chain  []rune
}

func NewView(live *NicoLive) *View {
	w, h := termbox.Size()
	return &View {
		width:  w,
		height: h,
		top:    0,
		ptr:    0,
		live:   live,
	}
}

func (v *View) UpdateEvent(ev termbox.Event) {
	switch ev.Type {
	case termbox.EventResize:
		v.width, v.height = ev.Width, ev.Height
		v.fixPtr()
	case termbox.EventKey:
		now := time.Now().UnixNano()
		switch {
		case ev.Ch == 0:
			v.chain = nil
			v.prev = 0
		case now - v.prev > chainThreshold:
			v.chain = []rune{ ev.Ch }
			v.prev = now
		default:
			v.chain = append(v.chain, ev.Ch)
			v.prev = now
		}

		if len(v.cmd) != 0 {
			// cmd now
			switch ev.Key {
			case termbox.KeyEsc:
				v.cmd = nil
			case termbox.KeyEnter:
				v.execCommand()
			case termbox.KeyBackspace, termbox.KeyBackspace2:
				if len(v.cmd) > 1 || v.cmd[0] != 'i' {
					v.cmd = v.cmd[0:len(v.cmd)-1]
				}
			case termbox.KeySpace:
				v.cmd = append(v.cmd, ' ')
			default:
				if ev.Ch != 0 {
					v.cmd = append(v.cmd, ev.Ch)
				}
			}
			return
		}

		switch ev.Ch {
		case 'i', ':':
			v.cmd = append(v.cmd, ev.Ch)
		case 'j':
			v.ptr++
			v.fixPtr()
		case 'k':
			v.ptr--
			v.fixPtr()
		case 'G':
			v.ptr = len(v.komes) - 1

			c := string(v.chain)
			if len(c) > 1 && c[len(c) - 1] == 'G' {
				n, err := strconv.ParseInt(c[0:len(c)-1], 10, 32)
				if err == nil && 1 <= n && n <= int64(len(v.komes)) {
					v.ptr = int(n - 1)
				}
			}

			v.fixPtr()
		case 'g':
			if string(v.chain) == "gg" {
				v.ptr = 0
				v.fixPtr()
			}
		}
	}
}

func (v *View) calcEnd() int {
	end := v.top + (v.height - 2)
	if end > len(v.komes) {
		end = len(v.komes)
	}
	return end
}

func (v *View) fixPtr() {
	if v.ptr < 0 {
		v.ptr = 0
	}
	if v.ptr >= len(v.komes) {
		v.ptr = len(v.komes) - 1
	}

	if v.ptr < v.top {
		v.top = v.ptr
		return
	}

	end := v.calcEnd()
	if v.ptr >= end {
		v.top += v.ptr - end + 1
		return
	}
}

func (v *View) execCommand() {
	defer func(){
		v.cmd = nil
	}()

	cmd := string(v.cmd)

	// quit
	if cmd == ":q" {
		v.Quit = true
		return
	}

	// send 184 kome
	if strings.HasPrefix(cmd, ":184 ") {
		comment := cmd[5:]
		v.live.SendKome(comment, true)
		return
	}

	// send raw kome
	if strings.HasPrefix(cmd, "i") {
		comment := cmd[1:]
		v.live.SendKome(comment, false)
		return
	}

	// :23 -> jump to 23kome
	n, err := strconv.ParseInt(cmd[1:], 10, 32)
	if err == nil && 1 <= n && n <= int64(len(v.komes)) {
		v.ptr = int(n - 1)
		v.fixPtr()
		return
	}
}

func (v *View) UpdateKome(kome Kome) {
	end := v.calcEnd()
	if end == len(v.komes) {
		if end - v.top + 1 > v.height - 2 {
			v.top++
			if v.ptr < v.top {
				v.ptr = v.top
			}
		}
	}

	v.komes = append(v.komes, kome)
}

func (v *View) UpdateView() {
	termbox.HideCursor()
	nowCmd := len(v.cmd) != 0

	// line view
	if len(v.komes) > 0 && v.height > 2 {
		end := v.calcEnd()

		noPadFormat := func() string {
			last := v.komes[end - 1]
			noStr := fmt.Sprintf("%d", last.No)
			return fmt.Sprintf("%%0%dd", len(noStr))
		}()
		maxUserIDLen := func() int {
			maxLen := 0
			for _, kome := range v.komes[v.top:end] {
				l := len(kome.UserID)
				if kome.Is184Comment() {
					l = 3
				}
				if l > maxLen {
					maxLen = l
				}
			}
			return maxLen
		}()

		y := 0
		for i := v.top; i < end; i++ {
			bg := termbox.ColorDefault
			if i == v.ptr {
				bg = termbox.ColorGreen
			}

			x := 0
			{
				// no
				fg := termbox.ColorBlue
				if i == v.ptr {
					fg = termbox.ColorDefault
				}

				no := fmt.Sprintf(noPadFormat, v.komes[i].No)
				for _, c := range no {
					termbox.SetCell(x, y, c, fg, bg)
					x++
				}
			}

			termbox.SetCell(x, y, ' ', termbox.ColorDefault, bg)
			x++

			{
				// userID
				fg := termbox.ColorGreen
				userID := v.komes[i].UserID

				if v.komes[i].Is184Comment() {
					fg = termbox.ColorYellow
					userID = "184"
				}
				if i == v.ptr {
					fg = termbox.ColorDefault
				}

				for len(userID) < maxUserIDLen {
					userID += " "
				}
				for _, c := range userID {
					termbox.SetCell(x, y, c, fg, bg)
					x++
				}
			}

			termbox.SetCell(x, y, ' ', termbox.ColorDefault, bg)
			x++

			for _, c := range v.komes[i].Comment {
				termbox.SetCell(x, y, c, termbox.ColorDefault, bg)
				x += width(c)
			}
			for ;x < v.width; x++ {
				termbox.SetCell(x, y, ' ', termbox.ColorDefault, bg)
			}

			if i == v.ptr && !nowCmd {
				termbox.SetCursor(v.width - 1, y)
			}
			y++
		}
		for ; y < v.height - 2; y++ {
			for x := 0; x < v.width; x++ {
				termbox.SetCell(x, y, ' ', termbox.ColorDefault, termbox.ColorDefault)
			}
		}
	}

	// info view
	if v.height > 1 {
		left := fmt.Sprintf("[%s] %s", v.live.LiveID, v.live.Status.Stream.Title)

		par := 0
		if len(v.komes) > 0 {
			par = v.calcEnd() * 100 / len(v.komes)
		}
		right := fmt.Sprintf("%d%%", par)

		y := v.height - 2
		x := 0
		for _, c := range left {
			termbox.SetCell(x, y, c, termbox.ColorDefault, termbox.ColorBlue)
			x += width(c)
		}

		mid := v.width - x - len(right)
		if mid > 0 {
			for i := 0; i < mid; i++ {
				termbox.SetCell(x, y, ' ', termbox.ColorDefault, termbox.ColorBlue)
				x++
			}
			for _, c := range right {
				termbox.SetCell(x, y, c, termbox.ColorDefault, termbox.ColorBlue)
				x++
			}
		}

		for ; x < v.width; x++ {
			termbox.SetCell(x, y, ' ', termbox.ColorDefault, termbox.ColorBlue)
		}
	}

	// cmd view
	if v.height > 0 {
		y := v.height - 1
		x := 0

		cmd := v.cmd
		if len(cmd) > 0 && cmd[0] == 'i' {
			c := []rune("send: ")
			c = append(c, cmd[1:]...)
			cmd = c
		}
		for _, c := range cmd {
			termbox.SetCell(x, y, c, termbox.ColorGreen, termbox.ColorDefault)
			x += width(c)
		}
		if nowCmd {
			termbox.SetCursor(x, y)
		}
		for ; x < v.width; x++ {
			termbox.SetCell(x, y, ' ', termbox.ColorDefault, termbox.ColorDefault)
		}
	}

	termbox.Flush()
}

func width(c rune) int {
	w := runewidth.RuneWidth(c)
	if w == 0 || w == 2 && runewidth.IsAmbiguousWidth(c) {
		w = 1
	}
	return w
}<|endoftext|>


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

package testing

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

	"go.uber.org/yarpc/api/transport"
	"go.uber.org/yarpc/internal/examples/protobuf/example"
	"go.uber.org/yarpc/internal/examples/protobuf/examplepb"
	"go.uber.org/yarpc/internal/examples/protobuf/exampleutil"
	"go.uber.org/yarpc/internal/grpcctx"
	"go.uber.org/yarpc/internal/testutils"
	"google.golang.org/grpc/grpclog"
)

func init() {
	log.SetOutput(ioutil.Discard)
	grpclog.SetLogger(log.New(ioutil.Discard, "", 0))
}

func BenchmarkIntegrationYARPC(b *testing.B) {
	for _, transportType := range testutils.AllTransportTypes {
		b.Run(transportType.String(), func(b *testing.B) {
			benchmarkForTransportType(b, transportType, func(clients *exampleutil.Clients) error {
				benchmarkIntegrationYARPC(b, clients.KeyValueYARPCClient)
				return nil
			})
		})
	}
}

func BenchmarkIntegrationGRPC(b *testing.B) {
	benchmarkForTransportType(b, testutils.TransportTypeGRPC, func(clients *exampleutil.Clients) error {
		benchmarkIntegrationGRPC(b, clients.KeyValueGRPCClient, clients.ContextWrapper)
		return nil
	})
}

func benchmarkForTransportType(b *testing.B, transportType testutils.TransportType, f func(*exampleutil.Clients) error) {
	keyValueYARPCServer := example.NewKeyValueYARPCServer()
	sinkYARPCServer := example.NewSinkYARPCServer(false)
	fooYARPCServer := example.NewFooYARPCServer(transport.NewHeaders())
	exampleutil.WithClients(transportType, keyValueYARPCServer, sinkYARPCServer, fooYARPCServer, nil, f)
}

func benchmarkIntegrationYARPC(b *testing.B, keyValueYARPCClient examplepb.KeyValueYARPCClient) {
	b.Run("Get", func(b *testing.B) {
		setValue(keyValueYARPCClient, "foo", "bar")
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			getValue(keyValueYARPCClient, "foo")
		}
	})
}

func benchmarkIntegrationGRPC(b *testing.B, keyValueClient examplepb.KeyValueClient, contextWrapper *grpcctx.ContextWrapper) {
	b.Run("Get", func(b *testing.B) {
		setValueGRPC(keyValueClient, contextWrapper, "foo", "bar")
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			getValueGRPC(keyValueClient, contextWrapper, "foo")
		}
	})
}
<commit_msg>grpc-go client and server benchmark for protobuf (#1455)<commit_after>// Copyright (c) 2018 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package testing

import (
	"io/ioutil"
	"log"
	"net"
	"testing"

	"go.uber.org/yarpc/api/transport"
	"go.uber.org/yarpc/internal/examples/protobuf/example"
	"go.uber.org/yarpc/internal/examples/protobuf/examplepb"
	"go.uber.org/yarpc/internal/examples/protobuf/exampleutil"
	"go.uber.org/yarpc/internal/grpcctx"
	"go.uber.org/yarpc/internal/testutils"
	"google.golang.org/grpc"
	"google.golang.org/grpc/grpclog"
)

func init() {
	log.SetOutput(ioutil.Discard)
	grpclog.SetLogger(log.New(ioutil.Discard, "", 0))
}

func BenchmarkIntegrationYARPC(b *testing.B) {
	for _, transportType := range testutils.AllTransportTypes {
		b.Run(transportType.String(), func(b *testing.B) {
			benchmarkForTransportType(b, transportType, func(clients *exampleutil.Clients) error {
				benchmarkIntegrationYARPC(b, clients.KeyValueYARPCClient)
				return nil
			})
		})
	}
}

func BenchmarkIntegrationGRPCClient(b *testing.B) {
	benchmarkForTransportType(b, testutils.TransportTypeGRPC, func(clients *exampleutil.Clients) error {
		benchmarkIntegrationGRPC(b, clients.KeyValueGRPCClient, clients.ContextWrapper)
		return nil
	})
}

func BenchmarkIntegrationGRPCAll(b *testing.B) {
	server := grpc.NewServer()
	examplepb.RegisterKeyValueServer(server, example.NewKeyValueYARPCServer())
	listener, err := net.Listen("tcp", "0.0.0.0:1234")
	if err != nil {
		b.Fatal(err.Error())
	}
	go func() { _ = server.Serve(listener) }()
	defer server.Stop()
	grpcClientConn, err := grpc.Dial("0.0.0.0:1234", grpc.WithInsecure())
	if err != nil {
		b.Fatal(err.Error())
	}
	benchmarkIntegrationGRPC(b, examplepb.NewKeyValueClient(grpcClientConn), grpcctx.NewContextWrapper())
}

func benchmarkForTransportType(b *testing.B, transportType testutils.TransportType, f func(*exampleutil.Clients) error) {
	keyValueYARPCServer := example.NewKeyValueYARPCServer()
	sinkYARPCServer := example.NewSinkYARPCServer(false)
	fooYARPCServer := example.NewFooYARPCServer(transport.NewHeaders())
	exampleutil.WithClients(transportType, keyValueYARPCServer, sinkYARPCServer, fooYARPCServer, nil, f)
}

func benchmarkIntegrationYARPC(b *testing.B, keyValueYARPCClient examplepb.KeyValueYARPCClient) {
	b.Run("Get", func(b *testing.B) {
		setValue(keyValueYARPCClient, "foo", "bar")
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			getValue(keyValueYARPCClient, "foo")
		}
	})
}

func benchmarkIntegrationGRPC(b *testing.B, keyValueClient examplepb.KeyValueClient, contextWrapper *grpcctx.ContextWrapper) {
	b.Run("Get", func(b *testing.B) {
		setValueGRPC(keyValueClient, contextWrapper, "foo", "bar")
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			getValueGRPC(keyValueClient, contextWrapper, "foo")
		}
	})
}
<|endoftext|>