<commit_before>package herd

import (
	"fmt"
	"github.com/Symantec/Dominator/lib/constants"
	"github.com/Symantec/Dominator/lib/hash"
	subproto "github.com/Symantec/Dominator/proto/sub"
	"net/rpc"
	"strings"
	"time"
)

func (sub *Sub) tryMakeBusy() bool {
	sub.busyMutex.Lock()
	defer sub.busyMutex.Unlock()
	if sub.busy {
		return false
	}
	sub.busy = true
	return true
}

func (sub *Sub) makeUnbusy() {
	sub.busyMutex.Lock()
	defer sub.busyMutex.Unlock()
	sub.busy = false
}

func (sub *Sub) connectAndPoll() {
	sub.status = statusConnecting
	hostname := strings.SplitN(sub.hostname, "*", 2)[0]
	var err error
	connection, err := rpc.DialHTTP("tcp",
		fmt.Sprintf("%s:%d", hostname, constants.SubPortNumber))
	if err != nil {
		sub.status = statusFailedToConnect
		return
	}
	defer connection.Close()
	sub.status = statusWaitingToPoll
	sub.herd.pollSemaphore <- true
	sub.status = statusPolling
	sub.poll(connection)
	<-sub.herd.pollSemaphore
}

func (sub *Sub) poll(connection *rpc.Client) {
	var request subproto.PollRequest
	request.HaveGeneration = sub.generationCount
	var reply subproto.PollResponse
	err := connection.Call("Subd.Poll", request, &reply)
	if err != nil {
		sub.status = statusFailedToPoll
		fmt.Printf("Error calling\t%s\n", err)
		return
	}
	sub.lastSuccessfulPoll = time.Now()
	if reply.GenerationCount == 0 {
		sub.fileSystem = nil
		sub.generationCount = 0
	}
	if fs := reply.FileSystem; fs != nil {
		fs.RebuildPointers()
		sub.fileSystem = fs
		sub.generationCount = reply.GenerationCount
		// TODO(rgooch): Remove debugging output.
		fmt.Printf("Polled: %s, GenerationCount=%d\n",
			sub.hostname, reply.GenerationCount)
	}
	if sub.fileSystem == nil {
		sub.status = statusSubNotReady
		return
	}
	if reply.FetchInProgress {
		sub.status = statusFetching
		return
	}
	if reply.UpdateInProgress {
		sub.status = statusUpdating
		return
	}
	if sub.generationCountAtChangeStart == sub.generationCount {
		sub.status = statusWaitingForNextPoll
		return
	}
	if idle, status := sub.fetchMissingObjects(connection,
		sub.requiredImage); !idle {
		sub.status = status
		return
	}
	if idle, status := sub.sendUpdate(connection); !idle {
		sub.status = status
		return
	}
	if idle, status := sub.fetchMissingObjects(connection,
		sub.plannedImage); !idle {
		sub.status = status
		return
	}
	sub.status = statusSynced
}

// Returns true if all required objects are available.
func (sub *Sub) fetchMissingObjects(connection *rpc.Client, imageName string) (
	bool, uint) {
	image := sub.herd.getImage(imageName)
	if image == nil {
		return false, statusImageNotReady
	}
	missingObjects := make(map[hash.Hash]bool)
	for _, inode := range image.FileSystem.RegularInodeTable {
		if inode.Size > 0 {
			missingObjects[inode.Hash] = true
		}
	}
	for _, hash := range sub.fileSystem.ObjectCache {
		delete(missingObjects, hash)
	}
	for _, inode := range sub.fileSystem.RegularInodeTable {
		if inode.Size > 0 {
			delete(missingObjects, inode.Hash)
		}
	}
	if len(missingObjects) < 1 {
		return true, statusSynced
	}
	// TODO(rgooch): Remove debugging output.
	fmt.Printf("Objects needing to be fetched: %d\n", len(missingObjects))
	var request subproto.FetchRequest
	var reply subproto.FetchResponse
	request.ServerAddress = sub.herd.imageServerAddress
	for hash, _ := range missingObjects {
		request.Hashes = append(request.Hashes, hash)
	}
	err := connection.Call("Subd.Fetch", request, &reply)
	if err != nil {
		fmt.Printf("Error calling\t%s\n", err)
		return false, statusFailedToFetch
	}
	sub.generationCountAtChangeStart = sub.generationCount
	return false, statusFetching
}

// Returns true if no update needs to be performed.
func (sub *Sub) sendUpdate(connection *rpc.Client) (bool, uint) {
	// TODO(rgooch): Implement this.
	return false, statusUpdating
}
<commit_msg>Switch to logger in Dominator sub handling code.<commit_after>package herd

import (
	"fmt"
	"github.com/Symantec/Dominator/lib/constants"
	"github.com/Symantec/Dominator/lib/hash"
	subproto "github.com/Symantec/Dominator/proto/sub"
	"net/rpc"
	"strings"
	"time"
)

func (sub *Sub) tryMakeBusy() bool {
	sub.busyMutex.Lock()
	defer sub.busyMutex.Unlock()
	if sub.busy {
		return false
	}
	sub.busy = true
	return true
}

func (sub *Sub) makeUnbusy() {
	sub.busyMutex.Lock()
	defer sub.busyMutex.Unlock()
	sub.busy = false
}

func (sub *Sub) connectAndPoll() {
	sub.status = statusConnecting
	hostname := strings.SplitN(sub.hostname, "*", 2)[0]
	var err error
	connection, err := rpc.DialHTTP("tcp",
		fmt.Sprintf("%s:%d", hostname, constants.SubPortNumber))
	if err != nil {
		sub.status = statusFailedToConnect
		return
	}
	defer connection.Close()
	sub.status = statusWaitingToPoll
	sub.herd.pollSemaphore <- true
	sub.status = statusPolling
	sub.poll(connection)
	<-sub.herd.pollSemaphore
}

func (sub *Sub) poll(connection *rpc.Client) {
	var request subproto.PollRequest
	request.HaveGeneration = sub.generationCount
	var reply subproto.PollResponse
	err := connection.Call("Subd.Poll", request, &reply)
	logger := sub.herd.logger
	if err != nil {
		sub.status = statusFailedToPoll
		logger.Printf("Error calling %s.Poll()\t%s\n", sub.hostname, err)
		return
	}
	sub.lastSuccessfulPoll = time.Now()
	if reply.GenerationCount == 0 {
		sub.fileSystem = nil
		sub.generationCount = 0
	}
	if fs := reply.FileSystem; fs != nil {
		fs.RebuildPointers()
		sub.fileSystem = fs
		sub.generationCount = reply.GenerationCount
		// TODO(rgooch): Remove debugging output.
		fmt.Printf("Polled: %s, GenerationCount=%d\n",
			sub.hostname, reply.GenerationCount)
	}
	if sub.fileSystem == nil {
		sub.status = statusSubNotReady
		return
	}
	if reply.FetchInProgress {
		sub.status = statusFetching
		return
	}
	if reply.UpdateInProgress {
		sub.status = statusUpdating
		return
	}
	if sub.generationCountAtChangeStart == sub.generationCount {
		sub.status = statusWaitingForNextPoll
		return
	}
	if idle, status := sub.fetchMissingObjects(connection,
		sub.requiredImage); !idle {
		sub.status = status
		return
	}
	if idle, status := sub.sendUpdate(connection); !idle {
		sub.status = status
		return
	}
	if idle, status := sub.fetchMissingObjects(connection,
		sub.plannedImage); !idle {
		sub.status = status
		return
	}
	sub.status = statusSynced
}

// Returns true if all required objects are available.
func (sub *Sub) fetchMissingObjects(connection *rpc.Client, imageName string) (
	bool, uint) {
	image := sub.herd.getImage(imageName)
	if image == nil {
		return false, statusImageNotReady
	}
	missingObjects := make(map[hash.Hash]bool)
	for _, inode := range image.FileSystem.RegularInodeTable {
		if inode.Size > 0 {
			missingObjects[inode.Hash] = true
		}
	}
	for _, hash := range sub.fileSystem.ObjectCache {
		delete(missingObjects, hash)
	}
	for _, inode := range sub.fileSystem.RegularInodeTable {
		if inode.Size > 0 {
			delete(missingObjects, inode.Hash)
		}
	}
	if len(missingObjects) < 1 {
		return true, statusSynced
	}
	logger := sub.herd.logger
	logger.Printf("Calling %s.Fetch() for: %d objects\n",
		sub.hostname, len(missingObjects))
	var request subproto.FetchRequest
	var reply subproto.FetchResponse
	request.ServerAddress = sub.herd.imageServerAddress
	for hash, _ := range missingObjects {
		request.Hashes = append(request.Hashes, hash)
	}
	err := connection.Call("Subd.Fetch", request, &reply)
	if err != nil {
		logger.Printf("Error calling %s.Fetch()\t%s\n", sub.hostname, err)
		return false, statusFailedToFetch
	}
	sub.generationCountAtChangeStart = sub.generationCount
	return false, statusFetching
}

// Returns true if no update needs to be performed.
func (sub *Sub) sendUpdate(connection *rpc.Client) (bool, uint) {
	// TODO(rgooch): Implement this.
	return false, statusUpdating
}
<|endoftext|>


<commit_before>package engine

import (
	"fmt"

	sm "github.com/Ariemeth/frame-assault-2/engine/shaderManager"
	tm "github.com/Ariemeth/frame-assault-2/engine/textureManager"
	"github.com/go-gl/gl/v4.1-core/gl"
	"github.com/go-gl/mathgl/mgl32"
)

//Model represents a physical entity
type Model struct {
	Entity
	vertices          []float32
	indices           []uint32
	shaders           sm.ShaderManager
	textures          tm.TextureManager
	angle             float64
	model             mgl32.Mat4
	camera            mgl32.Mat4
	projection        mgl32.Mat4
	modelUniform      int32
	projectionUniform int32
	cameraUniform     int32
	textureUniform    int32
	vao               uint32
	currentProgram    uint32
	currentTexture    uint32
}

//NewModel creates a new model
func NewModel(id string, shaders sm.ShaderManager, textures tm.TextureManager, shader string) *Model {
	m := Model{
		Entity:     NewEntity(id),
		shaders:    shaders,
		textures:   textures,
		angle:      0.0,
		model:      mgl32.Ident4(),
		camera:     mgl32.Ident4(),
		projection: mgl32.Ident4(),
		vertices:   iHexVerts,
		indices:    hexIndices,
	}

	program, status := shaders.GetShader(shader)
	if status {
		m.currentProgram = program
	} else {
		fmt.Println("unable to load program ", shader, ": ", program)
	}
	return &m
}

//Update updates the model
func (m *Model) Update(elapsed float64) {
	m.angle += elapsed
	m.model = mgl32.HomogRotate3D(float32(m.angle), mgl32.Vec3{0, 1, 0})
}

//Render renders the model
func (m *Model) Render() {

	gl.UseProgram(m.currentProgram)
	gl.UniformMatrix4fv(m.modelUniform, 1, false, &m.model[0])

	gl.BindVertexArray(m.vao)

	gl.ActiveTexture(gl.TEXTURE0)

	texture, isLoaded := m.textures.GetTexture("square")

	if isLoaded {
		gl.BindTexture(gl.TEXTURE_2D, texture)
	} else {
		fmt.Println("Unable to load texture")
	}

	if m.indices != nil {
		gl.DrawElements(gl.TRIANGLE_FAN, int32(len(m.indices)), gl.UNSIGNED_INT, gl.PtrOffset(0))
	} else {
		gl.DrawArrays(gl.TRIANGLES, 0, int32(len(m.vertices))/5)
	}

	gl.BindVertexArray(0)
}

//Load loads and sets up the model
func (m *Model) Load(isIndexed bool) {
	gl.UseProgram(m.currentProgram)

	m.projection = mgl32.Perspective(mgl32.DegToRad(45.0), float32(windowWidth)/windowHeight, 0.1, 10.0)
	m.projectionUniform = gl.GetUniformLocation(m.currentProgram, gl.Str("projection\x00"))
	gl.UniformMatrix4fv(m.projectionUniform, 1, false, &m.projection[0])

	m.camera = mgl32.LookAtV(mgl32.Vec3{3, 3, 3}, mgl32.Vec3{0, 0, 0}, mgl32.Vec3{0, 1, 0})
	m.cameraUniform = gl.GetUniformLocation(m.currentProgram, gl.Str("camera\x00"))
	gl.UniformMatrix4fv(m.cameraUniform, 1, false, &m.camera[0])

	m.modelUniform = gl.GetUniformLocation(m.currentProgram, gl.Str("model\x00"))
	gl.UniformMatrix4fv(m.modelUniform, 1, false, &m.model[0])

	m.textureUniform = gl.GetUniformLocation(m.currentProgram, gl.Str("tex\x00"))
	gl.Uniform1i(m.textureUniform, 0)

	gl.BindFragDataLocation(m.currentProgram, 0, gl.Str("outputColor\x00"))

	// Load the texture
	m.textures.LoadTexture("assets/textures/square.png", "square")

	// Configure the vertex data
	gl.GenVertexArrays(1, &m.vao)
	gl.BindVertexArray(m.vao)

	var vbo uint32
	gl.GenBuffers(1, &vbo)
	gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
	gl.BufferData(gl.ARRAY_BUFFER, len(m.vertices)*4, gl.Ptr(m.vertices), gl.STATIC_DRAW)

	vertAttrib := uint32(gl.GetAttribLocation(m.currentProgram, gl.Str("vert\x00")))
	gl.EnableVertexAttribArray(vertAttrib)
	gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 3*4, gl.PtrOffset(0)) //5:number of values per vertex, 4:number of bytes in a float32

	texCoordAttrib := uint32(gl.GetAttribLocation(m.currentProgram, gl.Str("vertTexCoord\x00")))
	gl.EnableVertexAttribArray(texCoordAttrib)
	gl.VertexAttribPointer(texCoordAttrib, 2, gl.FLOAT, true, 3*4, gl.PtrOffset(3*4)) //5:number of values per vertex, 4:number of bytes in a float32

	if isIndexed {
		var indices uint32
		gl.GenBuffers(1, &indices)
		gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, indices)
		gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(m.indices)*4, gl.Ptr(m.indices), gl.STATIC_DRAW)
	}

	gl.BindVertexArray(0)
}

var cubeVertices = []float32{
	//  X, Y, Z, U, V
	// Bottom
	-1.0, -1.0, -1.0, 0.0, 0.0,
	1.0, -1.0, -1.0, 1.0, 0.0,
	-1.0, -1.0, 1.0, 0.0, 1.0,
	1.0, -1.0, -1.0, 1.0, 0.0,
	1.0, -1.0, 1.0, 1.0, 1.0,
	-1.0, -1.0, 1.0, 0.0, 1.0,

	// Top
	-1.0, 1.0, -1.0, 0.0, 0.0,
	-1.0, 1.0, 1.0, 0.0, 1.0,
	1.0, 1.0, -1.0, 1.0, 0.0,
	1.0, 1.0, -1.0, 1.0, 0.0,
	-1.0, 1.0, 1.0, 0.0, 1.0,
	1.0, 1.0, 1.0, 1.0, 1.0,

	// Front
	-1.0, -1.0, 1.0, 1.0, 0.0,
	1.0, -1.0, 1.0, 0.0, 0.0,
	-1.0, 1.0, 1.0, 1.0, 1.0,
	1.0, -1.0, 1.0, 0.0, 0.0,
	1.0, 1.0, 1.0, 0.0, 1.0,
	-1.0, 1.0, 1.0, 1.0, 1.0,

	// Back
	-1.0, -1.0, -1.0, 0.0, 0.0,
	-1.0, 1.0, -1.0, 0.0, 1.0,
	1.0, -1.0, -1.0, 1.0, 0.0,
	1.0, -1.0, -1.0, 1.0, 0.0,
	-1.0, 1.0, -1.0, 0.0, 1.0,
	1.0, 1.0, -1.0, 1.0, 1.0,

	// Left
	-1.0, -1.0, 1.0, 0.0, 1.0,
	-1.0, 1.0, -1.0, 1.0, 0.0,
	-1.0, -1.0, -1.0, 0.0, 0.0,
	-1.0, -1.0, 1.0, 0.0, 1.0,
	-1.0, 1.0, 1.0, 1.0, 1.0,
	-1.0, 1.0, -1.0, 1.0, 0.0,

	// Right
	1.0, -1.0, 1.0, 1.0, 1.0,
	1.0, -1.0, -1.0, 1.0, 0.0,
	1.0, 1.0, -1.0, 0.0, 0.0,
	1.0, -1.0, 1.0, 1.0, 1.0,
	1.0, 1.0, -1.0, 0.0, 0.0,
	1.0, 1.0, 1.0, 0.0, 1.0,
}

type point struct {
	X float32
	Y float32
	Z float32
	U float32
	V float32
}

var (
	Center = point{0.0, 0.0, 0.0, 0.5, 0.5}
	P1     = point{0.0, 1.0, 0.0, 0.5, 0.0}
	P2     = point{-1.0, 0.5, 0.0, 0.0, 0.25}
	P3     = point{-1.0, -0.5, 0.0, 0.0, 0.75}
	P4     = point{0.0, -1.0, 0.0, 0.5, 1.0}
	P5     = point{1.0, -0.5, 0.0, 1.0, 0.75}
	P6     = point{1.0, 0.5, 0.0, 1.0, 0.25}
)

var iHexVerts = []float32{
	// X, Y, Z
	// Top
	Center.X, Center.Y, Center.Z,
	P1.X, P1.Y, P1.Z,
	P2.X, P2.Y, P2.Z,
	P3.X, P3.Y, P3.Z,
	P4.X, P4.Y, P4.Z,
	P5.X, P5.Y, P5.Z,
	P6.X, P6.Y, P6.Z,
}

var iHexVerts2 = []float32{
	// X, Y, Z
	// Top
	Center.X, Center.Y, Center.Z,
	P1.X, P1.Y, P1.Z, P1.U, P1.V,
	P2.X, P2.Y, P2.Z, P2.U, P2.V,
	P3.X, P3.Y, P3.Z, P3.U, P3.V,
	P4.X, P4.Y, P4.Z, P4.U, P4.V,
	P5.X, P5.Y, P5.Z, P5.U, P5.V,
	P6.X, P6.Y, P6.Z, P6.U, P6.V,
}

var hexIndices = []uint32{
	0, 1, 2, 3, 4, 5, 6, 1,
}

var hexVertices = []float32{
	//  X, Y, Z, U, V
	// Bottom
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P1.X, P1.Y, P1.Z, P1.U, P1.V,
	P2.X, P2.Y, P2.Z, P2.U, P2.V,
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P2.X, P2.Y, P2.Z, P2.U, P2.V,
	P3.X, P3.Y, P3.Z, P3.U, P3.V,
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P3.X, P3.Y, P3.Z, P3.U, P3.V,
	P4.X, P4.Y, P4.Z, P4.U, P4.V,
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P4.X, P4.Y, P4.Z, P4.U, P4.V,
	P5.X, P5.Y, P5.Z, P5.U, P5.V,
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P5.X, P5.Y, P5.Z, P5.U, P5.V,
	P6.X, P6.Y, P6.Z, P6.U, P6.V,
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P6.X, P6.Y, P6.Z, P6.U, P6.V,
	P1.X, P1.Y, P1.Z, P1.U, P1.V,

	// Top

	// Front

	// Back

	// Left

	// Right

}
<commit_msg>Fixed rendering of hexagon with UV coords<commit_after>package engine

import (
	"fmt"

	sm "github.com/Ariemeth/frame-assault-2/engine/shaderManager"
	tm "github.com/Ariemeth/frame-assault-2/engine/textureManager"
	"github.com/go-gl/gl/v4.1-core/gl"
	"github.com/go-gl/mathgl/mgl32"
)

//Model represents a physical entity
type Model struct {
	Entity
	vertices          []float32
	indices           []uint32
	shaders           sm.ShaderManager
	textures          tm.TextureManager
	angle             float64
	model             mgl32.Mat4
	camera            mgl32.Mat4
	projection        mgl32.Mat4
	modelUniform      int32
	projectionUniform int32
	cameraUniform     int32
	textureUniform    int32
	vao               uint32
	currentProgram    uint32
	currentTexture    uint32
}

//NewModel creates a new model
func NewModel(id string, shaders sm.ShaderManager, textures tm.TextureManager, shader string) *Model {
	m := Model{
		Entity:     NewEntity(id),
		shaders:    shaders,
		textures:   textures,
		angle:      0.0,
		model:      mgl32.Ident4(),
		camera:     mgl32.Ident4(),
		projection: mgl32.Ident4(),
		vertices:   iHexVerts2,
		indices:    hexIndices,
	}

	program, status := shaders.GetShader(shader)
	if status {
		m.currentProgram = program
	} else {
		fmt.Println("unable to load program ", shader, ": ", program)
	}
	return &m
}

//Update updates the model
func (m *Model) Update(elapsed float64) {
	m.angle += elapsed
	m.model = mgl32.HomogRotate3D(float32(m.angle), mgl32.Vec3{0, 1, 0})
}

//Render renders the model
func (m *Model) Render() {

	gl.UseProgram(m.currentProgram)
	gl.UniformMatrix4fv(m.modelUniform, 1, false, &m.model[0])

	gl.BindVertexArray(m.vao)

	gl.ActiveTexture(gl.TEXTURE0)

	texture, isLoaded := m.textures.GetTexture("square")

	if isLoaded {
		gl.BindTexture(gl.TEXTURE_2D, texture)
	} else {
		fmt.Println("Unable to load texture")
	}

	if m.indices != nil {
		gl.DrawElements(gl.TRIANGLE_FAN, int32(len(m.indices)), gl.UNSIGNED_INT, gl.PtrOffset(0))
	} else {
		gl.DrawArrays(gl.TRIANGLES, 0, int32(len(m.vertices))/5)
	}

	gl.BindVertexArray(0)
}

//Load loads and sets up the model
func (m *Model) Load(isIndexed bool) {
	gl.UseProgram(m.currentProgram)

	m.projection = mgl32.Perspective(mgl32.DegToRad(45.0), float32(windowWidth)/windowHeight, 0.1, 10.0)
	m.projectionUniform = gl.GetUniformLocation(m.currentProgram, gl.Str("projection\x00"))
	gl.UniformMatrix4fv(m.projectionUniform, 1, false, &m.projection[0])

	m.camera = mgl32.LookAtV(mgl32.Vec3{3, 3, 3}, mgl32.Vec3{0, 0, 0}, mgl32.Vec3{0, 1, 0})
	m.cameraUniform = gl.GetUniformLocation(m.currentProgram, gl.Str("camera\x00"))
	gl.UniformMatrix4fv(m.cameraUniform, 1, false, &m.camera[0])

	m.modelUniform = gl.GetUniformLocation(m.currentProgram, gl.Str("model\x00"))
	gl.UniformMatrix4fv(m.modelUniform, 1, false, &m.model[0])

	m.textureUniform = gl.GetUniformLocation(m.currentProgram, gl.Str("tex\x00"))
	gl.Uniform1i(m.textureUniform, 0)

	gl.BindFragDataLocation(m.currentProgram, 0, gl.Str("outputColor\x00"))

	// Load the texture
	m.textures.LoadTexture("assets/textures/square.png", "square")

	// Configure the vertex data
	gl.GenVertexArrays(1, &m.vao)
	gl.BindVertexArray(m.vao)

	var vbo uint32
	gl.GenBuffers(1, &vbo)
	gl.BindBuffer(gl.ARRAY_BUFFER, vbo)
	gl.BufferData(gl.ARRAY_BUFFER, len(m.vertices)*4, gl.Ptr(m.vertices), gl.STATIC_DRAW)

	vertAttrib := uint32(gl.GetAttribLocation(m.currentProgram, gl.Str("vert\x00")))
	gl.EnableVertexAttribArray(vertAttrib)
	gl.VertexAttribPointer(vertAttrib, 3, gl.FLOAT, false, 5*4, gl.PtrOffset(0)) //5:number of values per vertex, 4:number of bytes in a float32

	texCoordAttrib := uint32(gl.GetAttribLocation(m.currentProgram, gl.Str("vertTexCoord\x00")))
	gl.EnableVertexAttribArray(texCoordAttrib)
	gl.VertexAttribPointer(texCoordAttrib, 2, gl.FLOAT, true, 5*4, gl.PtrOffset(3*4)) //5:number of values per vertex, 4:number of bytes in a float32

	if isIndexed {
		var indices uint32
		gl.GenBuffers(1, &indices)
		gl.BindBuffer(gl.ELEMENT_ARRAY_BUFFER, indices)
		gl.BufferData(gl.ELEMENT_ARRAY_BUFFER, len(m.indices)*4, gl.Ptr(m.indices), gl.STATIC_DRAW)
	}

	gl.BindVertexArray(0)
}

var cubeVertices = []float32{
	//  X, Y, Z, U, V
	// Bottom
	-1.0, -1.0, -1.0, 0.0, 0.0,
	1.0, -1.0, -1.0, 1.0, 0.0,
	-1.0, -1.0, 1.0, 0.0, 1.0,
	1.0, -1.0, -1.0, 1.0, 0.0,
	1.0, -1.0, 1.0, 1.0, 1.0,
	-1.0, -1.0, 1.0, 0.0, 1.0,

	// Top
	-1.0, 1.0, -1.0, 0.0, 0.0,
	-1.0, 1.0, 1.0, 0.0, 1.0,
	1.0, 1.0, -1.0, 1.0, 0.0,
	1.0, 1.0, -1.0, 1.0, 0.0,
	-1.0, 1.0, 1.0, 0.0, 1.0,
	1.0, 1.0, 1.0, 1.0, 1.0,

	// Front
	-1.0, -1.0, 1.0, 1.0, 0.0,
	1.0, -1.0, 1.0, 0.0, 0.0,
	-1.0, 1.0, 1.0, 1.0, 1.0,
	1.0, -1.0, 1.0, 0.0, 0.0,
	1.0, 1.0, 1.0, 0.0, 1.0,
	-1.0, 1.0, 1.0, 1.0, 1.0,

	// Back
	-1.0, -1.0, -1.0, 0.0, 0.0,
	-1.0, 1.0, -1.0, 0.0, 1.0,
	1.0, -1.0, -1.0, 1.0, 0.0,
	1.0, -1.0, -1.0, 1.0, 0.0,
	-1.0, 1.0, -1.0, 0.0, 1.0,
	1.0, 1.0, -1.0, 1.0, 1.0,

	// Left
	-1.0, -1.0, 1.0, 0.0, 1.0,
	-1.0, 1.0, -1.0, 1.0, 0.0,
	-1.0, -1.0, -1.0, 0.0, 0.0,
	-1.0, -1.0, 1.0, 0.0, 1.0,
	-1.0, 1.0, 1.0, 1.0, 1.0,
	-1.0, 1.0, -1.0, 1.0, 0.0,

	// Right
	1.0, -1.0, 1.0, 1.0, 1.0,
	1.0, -1.0, -1.0, 1.0, 0.0,
	1.0, 1.0, -1.0, 0.0, 0.0,
	1.0, -1.0, 1.0, 1.0, 1.0,
	1.0, 1.0, -1.0, 0.0, 0.0,
	1.0, 1.0, 1.0, 0.0, 1.0,
}

type point struct {
	X float32
	Y float32
	Z float32
	U float32
	V float32
}

var (
	Center = point{0.0, 0.0, 0.0, 0.5, 0.5}
	P1     = point{0.0, 1.0, 0.0, 0.5, 0.0}
	P2     = point{-1.0, 0.5, 0.0, 0.0, 0.25}
	P3     = point{-1.0, -0.5, 0.0, 0.0, 0.75}
	P4     = point{0.0, -1.0, 0.0, 0.5, 1.0}
	P5     = point{1.0, -0.5, 0.0, 1.0, 0.75}
	P6     = point{1.0, 0.5, 0.0, 1.0, 0.25}
)

var iHexVerts = []float32{
	// X, Y, Z
	// Top
	Center.X, Center.Y, Center.Z,
	P1.X, P1.Y, P1.Z,
	P2.X, P2.Y, P2.Z,
	P3.X, P3.Y, P3.Z,
	P4.X, P4.Y, P4.Z,
	P5.X, P5.Y, P5.Z,
	P6.X, P6.Y, P6.Z,
}

var iHexVerts2 = []float32{
	// X, Y, Z
	// Top
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P1.X, P1.Y, P1.Z, P1.U, P1.V,
	P2.X, P2.Y, P2.Z, P2.U, P2.V,
	P3.X, P3.Y, P3.Z, P3.U, P3.V,
	P4.X, P4.Y, P4.Z, P4.U, P4.V,
	P5.X, P5.Y, P5.Z, P5.U, P5.V,
	P6.X, P6.Y, P6.Z, P6.U, P6.V,
}

var hexIndices = []uint32{
	0, 1, 2, 3, 4, 5, 6, 1,
}

var hexVertices = []float32{
	//  X, Y, Z, U, V
	// Bottom
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P1.X, P1.Y, P1.Z, P1.U, P1.V,
	P2.X, P2.Y, P2.Z, P2.U, P2.V,
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P2.X, P2.Y, P2.Z, P2.U, P2.V,
	P3.X, P3.Y, P3.Z, P3.U, P3.V,
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P3.X, P3.Y, P3.Z, P3.U, P3.V,
	P4.X, P4.Y, P4.Z, P4.U, P4.V,
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P4.X, P4.Y, P4.Z, P4.U, P4.V,
	P5.X, P5.Y, P5.Z, P5.U, P5.V,
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P5.X, P5.Y, P5.Z, P5.U, P5.V,
	P6.X, P6.Y, P6.Z, P6.U, P6.V,
	Center.X, Center.Y, Center.Z, Center.U, Center.V,
	P6.X, P6.Y, P6.Z, P6.U, P6.V,
	P1.X, P1.Y, P1.Z, P1.U, P1.V,

	// Top

	// Front

	// Back

	// Left

	// Right

}
<|endoftext|>


<commit_before>package main

import sp "lib/services"

func startup() {

	go signalHandler()

	// init services discovery
	sp.Init("game", "snowflake")
}
<commit_msg>update agent<commit_after>package main

import sp "lib/services"

func startup() {

	go signalHandler()

	// init services discovery
	sp.Init("game", "auth", "snowflake")
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2021 The GoPlus Authors (goplus.org). 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 env

import (
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
)

const (
	sep = string(os.PathSeparator)
)

func TestGopMod(t *testing.T) {
	file, err := GOPMOD("")
	if err != nil {
		t.Fatal("GOPMOD failed:", err)
	}
	if !strings.HasSuffix(file, "gop"+sep+"go.mod") {
		t.Fatal("GOPMOD failed:", file)
	}
	file, err = GOPMOD("./modtest")
	if err != nil {
		t.Fatal("GOPMOD modtest failed:", err)
	}
	if !strings.HasSuffix(file, "env/modtest/gop.mod") {
		t.Fatal("GOPMOD modtest failed:", file)
	}
}

func TestGOPATH(t *testing.T) {
	os.Setenv("GOPATH", "")
	gopath := GOPATH()
	home := HOME()
	expect := filepath.Join(home, "go")
	if expect == filepath.Clean(runtime.GOROOT()) {
		if gopath != "" {
			t.Fatal("TestGOPATH failed:", gopath)
		}
	} else if gopath != expect {
		t.Fatal("TestGOPATH failed:", gopath)
	}
	const ugopath = "/abc/work"
	os.Setenv("GOPATH", ugopath)
	gopath = GOPATH()
	if gopath != ugopath {
		t.Fatal("TestGOPATH failed:", gopath)
	}

	os.Setenv("GOPATH", "")
	os.Setenv(envHOME, "")
	defer os.Setenv(envHOME, home)
	if gopath := GOPATH(); gopath != "" {
		t.Fatal("TestGOPATH failed:", gopath)
	}
}

func TestGOMODCACHE(t *testing.T) {
	gopath := GOPATH()
	os.Setenv("GOMODCACHE", "")
	modcache := GOMODCACHE()
	if filepath.Join(gopath, "pkg/mod") != modcache {
		t.Fatal("TestGOMODCACHE failed:", modcache)
	}
	const umodcache = "/abc/mod"
	os.Setenv("GOMODCACHE", umodcache)
	modcache = GOMODCACHE()
	if modcache != umodcache {
		t.Fatal("TestGOMODCACHE (umodcache) failed:", modcache)
	}
	/* TODO:
	os.Setenv("GOMODCACHE", "")
	os.Setenv("GOPATH", "")
	home := HOME()
	defer os.Setenv(envHOME, home)
	os.Setenv(envHOME, strings.TrimRight(runtime.GOROOT(), "go"))
	modcache = GOMODCACHE()
	if modcache != "" {
		t.Fatal("TestGOMODCACHE (GOROOT) failed:", modcache)
	}
	*/
}
<commit_msg>TestGopMod fix windows<commit_after>/*
 * Copyright (c) 2021 The GoPlus Authors (goplus.org). 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 env

import (
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"testing"
)

const (
	sep = string(os.PathSeparator)
)

func TestGopMod(t *testing.T) {
	file, err := GOPMOD("")
	if err != nil {
		t.Fatal("GOPMOD failed:", err)
	}
	if !strings.HasSuffix(file, "gop"+sep+"go.mod") {
		t.Fatal("GOPMOD failed:", file)
	}
	file, err = GOPMOD("./modtest")
	if err != nil {
		t.Fatal("GOPMOD modtest failed:", err)
	}
	if !strings.HasSuffix(filepath.ToSlash(file), "env/modtest/gop.mod") {
		t.Fatal("GOPMOD modtest failed:", file)
	}
}

func TestGOPATH(t *testing.T) {
	os.Setenv("GOPATH", "")
	gopath := GOPATH()
	home := HOME()
	expect := filepath.Join(home, "go")
	if expect == filepath.Clean(runtime.GOROOT()) {
		if gopath != "" {
			t.Fatal("TestGOPATH failed:", gopath)
		}
	} else if gopath != expect {
		t.Fatal("TestGOPATH failed:", gopath)
	}
	const ugopath = "/abc/work"
	os.Setenv("GOPATH", ugopath)
	gopath = GOPATH()
	if gopath != ugopath {
		t.Fatal("TestGOPATH failed:", gopath)
	}

	os.Setenv("GOPATH", "")
	os.Setenv(envHOME, "")
	defer os.Setenv(envHOME, home)
	if gopath := GOPATH(); gopath != "" {
		t.Fatal("TestGOPATH failed:", gopath)
	}
}

func TestGOMODCACHE(t *testing.T) {
	gopath := GOPATH()
	os.Setenv("GOMODCACHE", "")
	modcache := GOMODCACHE()
	if filepath.Join(gopath, "pkg/mod") != modcache {
		t.Fatal("TestGOMODCACHE failed:", modcache)
	}
	const umodcache = "/abc/mod"
	os.Setenv("GOMODCACHE", umodcache)
	modcache = GOMODCACHE()
	if modcache != umodcache {
		t.Fatal("TestGOMODCACHE (umodcache) failed:", modcache)
	}
	/* TODO:
	os.Setenv("GOMODCACHE", "")
	os.Setenv("GOPATH", "")
	home := HOME()
	defer os.Setenv(envHOME, home)
	os.Setenv(envHOME, strings.TrimRight(runtime.GOROOT(), "go"))
	modcache = GOMODCACHE()
	if modcache != "" {
		t.Fatal("TestGOMODCACHE (GOROOT) failed:", modcache)
	}
	*/
}
<|endoftext|>


<commit_before>package lbricks

import (
	"github.com/Rubentxu/lbricks/engi"
	"github.com/Rubentxu/lbricks/goflow"
)

type EventSystem struct {
	stepChan	 []chan *StepEvent
	mouseChan    []chan *MouseEvent
	keyboardChan []chan *KeyboardEvent
}

func (g *EventSystem) RegisterInputChannel(input flow.Port) {
	switch input.Port {
	case "StepEvent" :
		append(g.stepChan, input.Channel)
	case "MouseEvent" :
		append(g.mouseChan, input.Channel)
	case "KeyboardEvent" :
		append(g.keyboardChan, input.Channel)
	}
}

func (g *EventSystem) Preload() {}
func (g *EventSystem) Setup() {}
func (g *EventSystem) Close() {}
func (g *EventSystem) Update(dt float32) {}
func (g *EventSystem) Step(step float64, numStep uint32) {}
func (g *EventSystem) Render() {}
func (g *EventSystem) Resize(w, h int) {}

func (g *EventSystem) Mouse(x, y float32, action engi.MouseAction) {
	EventPacket := &EventPacket{1, &MouseEvent{x, y, 0.0, action}}
	for _, e := range g.mouseChan {
		e <- EventPacket
	}
}

func (g *EventSystem) Scroll(amount float32) {}

func (g *EventSystem) Key(key engi.Key, modifier engi.Modifier, action engi.KeyAction) {
	if key == engi.Escape {
		engi.Exit()
	}
	EventPacket := &EventPacket{1, &KeyboardEvent{key, modifier, action}}
	for _, e := range g.keyboardChan {
		e <- EventPacket
	}
}

func (g *EventSystem) Type(char rune) {}
<commit_msg>añadido nuevos eventos en event_system<commit_after>package lbricks

import (
	"github.com/Rubentxu/lbricks/engi"
	"github.com/Rubentxu/lbricks/goflow"
)

type EventSystem struct {
	preloadChannnels	 []chan *PreloadEvent
	setupEventChannels	 []chan *SetupEvent
	closeEventChannels	 []chan *CloseEvent
	updateEventChannels	 []chan *UpdateEvent
	renderEventChannels	 []chan *RenderEvent
	resizeEventChannels	 []chan *ResizeEvent
	stepChannels []chan *StepEvent
	mouseChannels []chan *MouseEvent
	scrollEventChannels	 []chan *ScrollEvent
	keyChannels []chan *KeyEvent
	typeKeyEventChannels []chan *TypeKeyEvent
}

func (g *EventSystem) RegisterInputChannel(input flow.Port) {
	switch input.Port {
	case "PreloadEvent" :
		append(g.preloadChannnels, input.Channel)
	case "SetupEvent" :
		append(g.setupEventChannels, input.Channel)
	case "CloseEvent" :
		append(g.closeEventChannels, input.Channel)
	case "UpdateEvent" :
		append(g.updateEventChannels, input.Channel)
	case "RenderEvent" :
		append(g.renderEventChannels, input.Channel)
	case "ResizeEvent" :
		append(g.resizeEventChannels, input.Channel)
	case "StepEvent" :
		append(g.stepChannels, input.Channel)
	case "MouseEvent" :
		append(g.mouseChannels, input.Channel)
		append(g.scrollEventChannels, input.Channel)
	case "KeyboardEvent" :
		append(g.keyChannels, input.Channel)
		append(g.typeKeyEventChannels, input.Channel)
	}
}

func (g *EventSystem) Preload() {
	event := &PreloadEvent{}
	for _, e := range g.preloadChannnels {
		e <- event
	}
}

func (g *EventSystem) Setup() {
	event := &SetupEvent{}
	for _, e := range g.setupEventChannels {
		e <- event
	}
}

func (g *EventSystem) Close() {
	event := &CloseEvent{}
	for _, e := range g.closeEventChannels {
		e <- event
	}
}

func (g *EventSystem) Update(dt float32) {
	event := &UpdateEvent{dt}
	for _, e := range g.updateEventChannels {
		e <- event
	}
}

func (g *EventSystem) Step(step float64, numStep uint32) {
	event := &StepEvent{step, numStep}
	for _, e := range g.stepChannels {
		e <- event
	}
}

func (g *EventSystem) Render() {
	event := &RenderEvent{}
	for _, e := range g.renderEventChannels {
		e <- event
	}
}

func (g *EventSystem) Resize(w, h int) {
	event := &ResizeEvent{w, h}
	for _, e := range g.resizeEventChannels {
		e <- event
	}
}

func (g *EventSystem) Mouse(x, y float32, action engi.MouseAction) {
	event := &MouseEvent{x, y, 0.0, action}
	for _, e := range g.mouseChannels {
		e <- event
	}
}

func (g *EventSystem) Scroll(amount float32) {
	var action engi.MouseAction = engi.WHEEL_UP
	if amount < 0 {
		action = engi.WHEEL_DOWN
	}
	event := &MouseEvent{0, 0, amount, action}
	for _, e := range g.scrollEventChannels {
		e <- event
	}
}

func (g *EventSystem) Key(key engi.Key, modifier engi.Modifier, action engi.KeyAction) {
	if key == engi.Escape {
		engi.Exit()
	}
	event := &KeyEvent{key, modifier, action}
	for _, e := range g.keyChannels {
		e <- event
	}
}

func (g *EventSystem) Type(char rune) {
	event := &TypeKeyEvent{rune}
	for _, e := range g.typeKeyEventChannels {
		e <- event
	}
}
<|endoftext|>


<commit_before>// +build go1.5

package events

import (
	"reflect"
	"unsafe"
)

func cloneValue(v interface{}) interface{} {
	// Some sub-packages use optimizations that hack the type system by sharing
	// pointers to avoid generated calls to runtime.convT2E, this functions
	// basically does the opposite and ensures that runtime.convT2E is called
	// to generate new values to ensure no more pointers are shared by cloned
	// events.
	rv := reflect.ValueOf(v)
	nv := reflect.New(rv.Type()).Elem()
	nv.Set(rv)
	return nv.Interface()
}

func bytesToString(b []byte) string {
	// The conversion of a byte slice ot a string is ensured not to cause a
	// dynamic memory allocation.
	if len(b) == 0 {
		return ""
	}
	return *(*string)(unsafe.Pointer(&reflect.StringHeader{
		Data: uintptr(unsafe.Pointer(&b[0])),
		Len:  len(b),
	}))
}

func noescape(a []interface{}) (b []interface{}) {
	// The use of unsafe.Pointer tricks the compiler into thinking that the
	// content of the input slice doesn't escape, so we can prevent dynamic
	// memory allocations that would otherwise happen for each argument of
	// a log message.
	*(*reflect.SliceHeader)(unsafe.Pointer(&b)) = *(*reflect.SliceHeader)(unsafe.Pointer(&a))
	return
}
<commit_msg>[skip ci] update comment<commit_after>// +build go1.5

package events

import (
	"reflect"
	"unsafe"
)

func cloneValue(v interface{}) interface{} {
	// Some sub-packages use optimizations that hack the type system by sharing
	// pointers to avoid generated calls to runtime.convT2E, this functions
	// basically does the opposite and ensures that runtime.convT2E is called
	// to generate new values to ensure no more pointers are shared by cloned
	// events.
	rv := reflect.ValueOf(v)
	nv := reflect.New(rv.Type()).Elem()
	nv.Set(rv)
	return nv.Interface()
}

func bytesToString(b []byte) string {
	// The conversion of a byte slice ot a string is ensured not to cause a
	// dynamic memory allocation.
	if len(b) == 0 {
		return ""
	}
	return *(*string)(unsafe.Pointer(&reflect.StringHeader{
		Data: uintptr(unsafe.Pointer(&b[0])),
		Len:  len(b),
	}))
}

func noescape(a []interface{}) (b []interface{}) {
	// The use of reflect.SliceHeader tricks the compiler into thinking that the
	// content of the input slice doesn't escape, so we can prevent dynamic
	// memory allocations that would otherwise happen for each argument of a log
	// message.
	*(*reflect.SliceHeader)(unsafe.Pointer(&b)) = *(*reflect.SliceHeader)(unsafe.Pointer(&a))
	return
}
<|endoftext|>


<commit_before>package alfred

import "fmt"

// FilterResult is the final result of an Alfred script filter,
// to be rendered as JSON.
type FilterResult struct {
	Items     Items      `json:"items"`
	Rerun     float64    `json:"rerun,omitempty"`
	Variables *Variables `json:"variables,omitempty"`
}

// NewFilterResult provides an initialized FilterResult that contains the
// required (but empty) Items list
func NewFilterResult() *FilterResult {
	return &FilterResult{Items: Items{}}
}

// Items is a list of Item pointers.
type Items []*Item

func (is Items) String() string {
	s := "[\n"
	for _, i := range is {
		s += fmt.Sprintf("%#v\n", i)
	}
	s += "]\n"
	return s
}

// Variables is a map of string to string variables for alfred to pass on to a
// subsquent iteration of a script filter
type Variables map[string]string

// Item is an Alfred result item
type Item struct {
	UID          string `json:"uid,omitempty"`          // optional unique identifier for alfred to learn from
	Title        string `json:"title"`                  // title displayed in the result row
	Subtitle     string `json:"subtitle,omitempty"`     // optional subtitle displayed in the result row
	Arg          string `json:"arg,omitempty"`          // recommended string argument to pass through to output action
	Icon         *Icon  `json:"icon,omitempty"`         // optional icon argument
	Valid        bool   `json:"valid"`                  // valid means "actionable", false means "populate autocomplete text"
	Autocomplete string `json:"autocomplete,omitempty"` // recommended string to autocomplete with tab key
	// Type string // "default", "file", "file:skipcheck" to treat the result as a file
	Mods *Mods `json:"mods,omitempty"` // optional modifier keys arguments
	Text *Text `json:"text,omitempty"` // optional text if copied to clipboard or displayed as large text
	// Quicklook string // optional url for quicklook
}

// AppendItems is shorthand for adding more items to a FilterResult's Items list
func (result *FilterResult) AppendItems(items ...*Item) {
	result.Items = append(result.Items, items...)
}

// SetVariable to set a variable in the result output
func (result *FilterResult) SetVariable(name, value string) {
	if result.Variables == nil {
		result.Variables = &Variables{name: value}
	} else {
		(*result.Variables)[name] = value
	}
}

// Icon is a custom icon for an item
type Icon struct {
	Path string `json:"path"`           // the path to a file
	Type string `json:"type,omitempty"` // optional, "fileicon" for a path, "filetype" for a specific file
}

// Text defines copy text and/or large type display
type Text struct {
	Copy      string `json:"copy,omitempty"`
	LargeType string `json:"largetype,omitempty"`
}

// ModItem defines an alternate action for an item
type ModItem struct {
	Valid    bool   `json:"valid"`
	Arg      string `json:"arg,omitempty"`
	Subtitle string `json:"subtitle,omitempty"`
}

// Mods define alternate actions for an item, with alt or cmd held down
type Mods struct {
	Alt *ModItem `json:"alt,omitempty"`
	Cmd *ModItem `json:"cmd,omitempty"`
}

func (t *Text) String() string {
	return fmt.Sprintf("%#v", *t)
}
<commit_msg>Add mods String() representations<commit_after>package alfred

import "fmt"

// FilterResult is the final result of an Alfred script filter,
// to be rendered as JSON.
type FilterResult struct {
	Items     Items      `json:"items"`
	Rerun     float64    `json:"rerun,omitempty"`
	Variables *Variables `json:"variables,omitempty"`
}

// NewFilterResult provides an initialized FilterResult that contains the
// required (but empty) Items list
func NewFilterResult() *FilterResult {
	return &FilterResult{Items: Items{}}
}

// Items is a list of Item pointers.
type Items []*Item

func (is Items) String() string {
	s := "[\n"
	for _, i := range is {
		s += fmt.Sprintf("%#v\n", i)
	}
	s += "]\n"
	return s
}

// Variables is a map of string to string variables for alfred to pass on to a
// subsquent iteration of a script filter
type Variables map[string]string

// Item is an Alfred result item
type Item struct {
	UID          string `json:"uid,omitempty"`          // optional unique identifier for alfred to learn from
	Title        string `json:"title"`                  // title displayed in the result row
	Subtitle     string `json:"subtitle,omitempty"`     // optional subtitle displayed in the result row
	Arg          string `json:"arg,omitempty"`          // recommended string argument to pass through to output action
	Icon         *Icon  `json:"icon,omitempty"`         // optional icon argument
	Valid        bool   `json:"valid"`                  // valid means "actionable", false means "populate autocomplete text"
	Autocomplete string `json:"autocomplete,omitempty"` // recommended string to autocomplete with tab key
	// Type string // "default", "file", "file:skipcheck" to treat the result as a file
	Mods *Mods `json:"mods,omitempty"` // optional modifier keys arguments
	Text *Text `json:"text,omitempty"` // optional text if copied to clipboard or displayed as large text
	// Quicklook string // optional url for quicklook
}

// AppendItems is shorthand for adding more items to a FilterResult's Items list
func (result *FilterResult) AppendItems(items ...*Item) {
	result.Items = append(result.Items, items...)
}

// SetVariable to set a variable in the result output
func (result *FilterResult) SetVariable(name, value string) {
	if result.Variables == nil {
		result.Variables = &Variables{name: value}
	} else {
		(*result.Variables)[name] = value
	}
}

// Icon is a custom icon for an item
type Icon struct {
	Path string `json:"path"`           // the path to a file
	Type string `json:"type,omitempty"` // optional, "fileicon" for a path, "filetype" for a specific file
}

// Text defines copy text and/or large type display
type Text struct {
	Copy      string `json:"copy,omitempty"`
	LargeType string `json:"largetype,omitempty"`
}

// ModItem defines an alternate action for an item
type ModItem struct {
	Valid    bool   `json:"valid"`
	Arg      string `json:"arg,omitempty"`
	Subtitle string `json:"subtitle,omitempty"`
}

// Mods define alternate actions for an item, with alt or cmd held down
type Mods struct {
	Alt *ModItem `json:"alt,omitempty"`
	Cmd *ModItem `json:"cmd,omitempty"`
}

func (t *Text) String() string {
	return fmt.Sprintf("%#v", *t)
}

func (m *Mods) String() string {
	return fmt.Sprintf("%#v", *m)
}

func (m *ModItem) String() string {
	return fmt.Sprintf("%#v", *m)
}
<|endoftext|>


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

package fdm

import (
	"github.com/cpmech/gosl/la"
)

// InitK11andK12 initialises the two triplets
func InitK11andK12(K11, K12 *la.Triplet, e *Equations) {
	K11.Init(e.N1, e.N1, e.N1*5)
	K12.Init(e.N1, e.N2, e.N1*5)
}

// AssemblePoisson2d assembles K11 and K12 corresponding to the Poisson problem in 2D
//   Solving:
//                 ∂²u        ∂²u
//            - kx ———  -  ky ———  =  s(x,y)
//                 ∂x²        ∂y²
//  Input:
//    kx and ky -- the diffusion coefficients
//    src -- the source term function s(x,y) (may be nil)
//    g -- the 2D grid
//    e -- the Equation numbers
//  Output:
//    K11, K12 and F1 are assembled (must be pre-allocated)
func AssemblePoisson2d(K11, K12 *la.Triplet, F1 []float64, kx, ky float64, src Cb_src, g *Grid2d, e *Equations) {
	K11.Start()
	K12.Start()
	la.VecFill(F1, 0.0)
	alp, bet, gam := 2.0*(kx/g.Dxx+ky/g.Dyy), -kx/g.Dxx, -ky/g.Dyy
	mol := []float64{alp, bet, bet, gam, gam}
	for i, I := range e.RF1 {
		col, row := I%g.Nx, I/g.Nx
		nodes := []int{I, I - 1, I + 1, I - g.Nx, I + g.Nx} // I, left, right, bottom, top
		if col == 0 {
			nodes[1] = nodes[2]
		}
		if col == g.Nx-1 {
			nodes[2] = nodes[1]
		}
		if row == 0 {
			nodes[3] = nodes[4]
		}
		if row == g.Ny-1 {
			nodes[4] = nodes[3]
		}
		for k, J := range nodes {
			j1, j2 := e.FR1[J], e.FR2[J] // 1 or 2?
			if j1 > -1 {                 // 11
				K11.Put(i, j1, mol[k])
			} else { // 12
				K12.Put(i, j2, mol[k])
			}
		}
		if src != nil {
			x := float64(col) * g.Dx
			y := float64(row) * g.Dy
			F1[i] += src(x, y)
		}
	}
}

// JoinVecs joins U1 and U2 by placing their components at the right place in U
func JoinVecs(U, U1, U2 []float64, e *Equations) {
	for I := 0; I < e.N; I++ {
		i1, i2 := e.FR1[I], e.FR2[I] // 1 or 2?
		if i1 > -1 {
			U[I] = U1[i1]
		} else {
			U[I] = U2[i2]
		}
	}
}
<commit_msg>Fix fdm after changes in la<commit_after>// Copyright 2016 The Gosl Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fdm

import (
	"github.com/cpmech/gosl/la"
)

// InitK11andK12 initialises the two triplets
func InitK11andK12(K11, K12 *la.Triplet, e *Equations) {
	K11.Init(e.N1, e.N1, e.N1*5)
	K12.Init(e.N1, e.N2, e.N1*5)
}

// AssemblePoisson2d assembles K11 and K12 corresponding to the Poisson problem in 2D
//   Solving:
//                 ∂²u        ∂²u
//            - kx ———  -  ky ———  =  s(x,y)
//                 ∂x²        ∂y²
//  Input:
//    kx and ky -- the diffusion coefficients
//    src -- the source term function s(x,y) (may be nil)
//    g -- the 2D grid
//    e -- the Equation numbers
//  Output:
//    K11, K12 and F1 are assembled (must be pre-allocated)
func AssemblePoisson2d(K11, K12 *la.Triplet, F1 la.Vector, kx, ky float64, src Cb_src, g *Grid2d, e *Equations) {
	K11.Start()
	K12.Start()
	F1.Fill(0)
	alp, bet, gam := 2.0*(kx/g.Dxx+ky/g.Dyy), -kx/g.Dxx, -ky/g.Dyy
	mol := []float64{alp, bet, bet, gam, gam}
	for i, I := range e.RF1 {
		col, row := I%g.Nx, I/g.Nx
		nodes := []int{I, I - 1, I + 1, I - g.Nx, I + g.Nx} // I, left, right, bottom, top
		if col == 0 {
			nodes[1] = nodes[2]
		}
		if col == g.Nx-1 {
			nodes[2] = nodes[1]
		}
		if row == 0 {
			nodes[3] = nodes[4]
		}
		if row == g.Ny-1 {
			nodes[4] = nodes[3]
		}
		for k, J := range nodes {
			j1, j2 := e.FR1[J], e.FR2[J] // 1 or 2?
			if j1 > -1 {                 // 11
				K11.Put(i, j1, mol[k])
			} else { // 12
				K12.Put(i, j2, mol[k])
			}
		}
		if src != nil {
			x := float64(col) * g.Dx
			y := float64(row) * g.Dy
			F1[i] += src(x, y)
		}
	}
}

// JoinVecs joins U1 and U2 by placing their components at the right place in U
func JoinVecs(U, U1, U2 []float64, e *Equations) {
	for I := 0; I < e.N; I++ {
		i1, i2 := e.FR1[I], e.FR2[I] // 1 or 2?
		if i1 > -1 {
			U[I] = U1[i1]
		} else {
			U[I] = U2[i2]
		}
	}
}
<|endoftext|>


<commit_before>package apig

import (
	"bytes"
	"fmt"
	"text/template"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"sync"

	"github.com/wantedly/apig/util"
)

func generateSkeleton(detail *Detail, outDir string) error {
	ch := make(chan error)
	go func() {
		var wg sync.WaitGroup
		r := regexp.MustCompile(`_templates/skeleton/*`)
		for _, skeleton := range AssetNames() {
			wg.Add(1)
			go func(s string) {
				defer wg.Done()
				if !r.MatchString(s) {
					return
				}

				trim := strings.Replace(s, "_templates/skeleton/", "", 1)
				path := strings.Replace(trim, ".tmpl", "", 1)
				dstPath := filepath.Join(outDir, path)

				body, err := Asset(s)

				if err != nil {
					ch <- err
				}

				tmpl, err := template.New("complex").Parse(string(body))

				if err != nil {
					ch <- err
				}

				var buf bytes.Buffer

				if err := tmpl.Execute(&buf, detail); err != nil {
					ch <- err
				}

				if !util.FileExists(filepath.Dir(dstPath)) {
					if err := util.Mkdir(filepath.Dir(dstPath)); err != nil {
						ch <- err
					}
				}

				if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
					ch <- err
				}

				fmt.Printf("\t\x1b[32m%s\x1b[0m %s\n", "create", dstPath)
			}(skeleton)
		}
		wg.Wait()
		ch <- nil
	}()

	err := <-ch
	if err != nil {
		return err
	}

	return nil
}

func Skeleton(gopath, vcs, username, project string) int {
	detail := &Detail{VCS: vcs, User: username, Project: project}
	outDir := filepath.Join(gopath, "src", detail.VCS, detail.User, detail.Project)
	if util.FileExists(outDir) {
		fmt.Fprintf(os.Stderr, "%s is already exists", outDir)
		return 1
	}
	if err := generateSkeleton(detail, outDir); err != nil {
		fmt.Fprintln(os.Stderr, err)
		return 1
	}

	fmt.Fprintf(os.Stdout, `===> Created %s
`, outDir)
	return 0
}
<commit_msg>Generate skeleton from .tmpl files only<commit_after>package apig

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"sync"
	"text/template"

	"github.com/wantedly/apig/util"
)

func generateSkeleton(detail *Detail, outDir string) error {
	ch := make(chan error)
	go func() {
		var wg sync.WaitGroup
		r := regexp.MustCompile(`_templates/skeleton/.*\.tmpl$`)
		for _, skeleton := range AssetNames() {
			wg.Add(1)
			go func(s string) {
				defer wg.Done()
				if !r.MatchString(s) {
					return
				}

				trim := strings.Replace(s, "_templates/skeleton/", "", 1)
				path := strings.Replace(trim, ".tmpl", "", 1)
				dstPath := filepath.Join(outDir, path)

				body, err := Asset(s)

				if err != nil {
					ch <- err
				}

				tmpl, err := template.New("complex").Parse(string(body))

				if err != nil {
					ch <- err
				}

				var buf bytes.Buffer

				if err := tmpl.Execute(&buf, detail); err != nil {
					ch <- err
				}

				if !util.FileExists(filepath.Dir(dstPath)) {
					if err := util.Mkdir(filepath.Dir(dstPath)); err != nil {
						ch <- err
					}
				}

				if err := ioutil.WriteFile(dstPath, buf.Bytes(), 0644); err != nil {
					ch <- err
				}

				fmt.Printf("\t\x1b[32m%s\x1b[0m %s\n", "create", dstPath)
			}(skeleton)
		}
		wg.Wait()
		ch <- nil
	}()

	err := <-ch
	if err != nil {
		return err
	}

	return nil
}

func Skeleton(gopath, vcs, username, project string) int {
	detail := &Detail{VCS: vcs, User: username, Project: project}
	outDir := filepath.Join(gopath, "src", detail.VCS, detail.User, detail.Project)
	if util.FileExists(outDir) {
		fmt.Fprintf(os.Stderr, "%s is already exists", outDir)
		return 1
	}
	if err := generateSkeleton(detail, outDir); err != nil {
		fmt.Fprintln(os.Stderr, err)
		return 1
	}

	fmt.Fprintf(os.Stdout, `===> Created %s
`, outDir)
	return 0
}
<|endoftext|>


<commit_before>package flame

import (
	"time"

	"github.com/256dpi/fire/coal"

	"golang.org/x/crypto/bcrypt"
	"gopkg.in/mgo.v2/bson"
)

// TokenData is used to carry token related information.
type TokenData struct {
	Scope           []string
	ExpiresAt       time.Time
	ClientID        bson.ObjectId
	ResourceOwnerID *bson.ObjectId
}

// A TokenDescription is returned by a Token model to specify some details about
// its implementation.
type TokenDescription struct {
	ClientIDField  string
	ExpiresAtField string
}

// Token is the interface that must be implemented to provide a custom access
// token and refresh token.
type Token interface {
	coal.Model

	// DescribeToken should return a TokenDescription.
	DescribeToken() TokenDescription

	// GetTokenData should collect and return the tokens data.
	GetTokenData() *TokenData

	// SetTokenData should set the specified token data.
	SetTokenData(*TokenData)
}

// AccessToken is the built-in model used to store access tokens.
type AccessToken struct {
	coal.Base       `json:"-" bson:",inline" coal:"access-tokens:access_tokens"`
	ExpiresAt       time.Time      `json:"expires-at" valid:"required" bson:"expires_at"`
	Scope           []string       `json:"scope" valid:"required" bson:"scope"`
	ClientID        bson.ObjectId  `json:"client-id" valid:"-" bson:"client_id"`
	ResourceOwnerID *bson.ObjectId `json:"resource-owner-id" valid:"-" bson:"resource_owner_id"`
}

// DescribeToken implements the Token interface.
func (t *AccessToken) DescribeToken() TokenDescription {
	return TokenDescription{
		ClientIDField:  "ClientID",
		ExpiresAtField: "ExpiresAt",
	}
}

// GetTokenData implements the Token interface.
func (t *AccessToken) GetTokenData() *TokenData {
	return &TokenData{
		Scope:           t.Scope,
		ExpiresAt:       t.ExpiresAt,
		ClientID:        t.ClientID,
		ResourceOwnerID: t.ResourceOwnerID,
	}
}

// SetTokenData implements the Token interface.
func (t *AccessToken) SetTokenData(data *TokenData) {
	t.Scope = data.Scope
	t.ExpiresAt = data.ExpiresAt
	t.ClientID = data.ClientID
	t.ResourceOwnerID = data.ResourceOwnerID
}

// RefreshToken is the built-in model used to store refresh tokens.
type RefreshToken struct {
	coal.Base       `json:"-" bson:",inline" coal:"refresh-tokens:refresh_tokens"`
	ExpiresAt       time.Time      `json:"expires-at" valid:"required" bson:"expires_at"`
	Scope           []string       `json:"scope" valid:"required" bson:"scope"`
	ClientID        bson.ObjectId  `json:"client-id" valid:"-" bson:"client_id"`
	ResourceOwnerID *bson.ObjectId `json:"resource-owner-id" valid:"-" bson:"resource_owner_id"`
}

// DescribeToken implements the Token interface.
func (t *RefreshToken) DescribeToken() TokenDescription {
	return TokenDescription{
		ClientIDField:  "ClientID",
		ExpiresAtField: "ExpiresAt",
	}
}

// GetTokenData implements the Token interface.
func (t *RefreshToken) GetTokenData() *TokenData {
	return &TokenData{
		Scope:           t.Scope,
		ExpiresAt:       t.ExpiresAt,
		ClientID:        t.ClientID,
		ResourceOwnerID: t.ResourceOwnerID,
	}
}

// SetTokenData implements the Token interface.
func (t *RefreshToken) SetTokenData(data *TokenData) {
	t.Scope = data.Scope
	t.ExpiresAt = data.ExpiresAt
	t.ClientID = data.ClientID
	t.ResourceOwnerID = data.ResourceOwnerID
}

// A ClientDescription is returned by a Client model to specify some details about
// its implementation.
type ClientDescription struct {
	IdentifierField string
}

// Client is the interface that must be implemented to provide a custom client.
type Client interface {
	coal.Model

	// DescribeClient should return a ClientDescription.
	DescribeClient() ClientDescription

	// ValidRedirectURI should return whether the specified redirect uri can be
	// used by this client.
	//
	// Note: In order to increases security the callback should only allow
	// pre-registered redirect uris.
	ValidRedirectURI(string) bool

	// ValidSecret should determine whether the specified plain text secret
	// matches the hashed secret.
	ValidSecret(string) bool
}

// Application is the built-in model used to store clients.
type Application struct {
	coal.Base   `json:"-" bson:",inline" coal:"applications"`
	Name        string `json:"name" valid:"required"`
	Key         string `json:"key" valid:"required"`
	SecretHash  []byte `json:"-" valid:"required"`
	RedirectURI string `json:"redirect_uri" valid:"required"`
}

// DescribeClient implements the Client interface.
func (a *Application) DescribeClient() ClientDescription {
	return ClientDescription{
		IdentifierField: "Key",
	}
}

// ValidRedirectURI implements the Client interface.
func (a *Application) ValidRedirectURI(uri string) bool {
	return uri == a.RedirectURI
}

// ValidSecret implements the Client interface.
func (a *Application) ValidSecret(secret string) bool {
	return bcrypt.CompareHashAndPassword(a.SecretHash, []byte(secret)) == nil
}

// A ResourceOwnerDescription is returned by a ResourceOwner model to specify
// some details about its implementation.
type ResourceOwnerDescription struct {
	IdentifierField string
}

// ResourceOwner is the interface that must be implemented to provide a custom
// resource owner.
type ResourceOwner interface {
	coal.Model

	// DescribeResourceOwner should return a ResourceOwnerDescription.
	DescribeResourceOwner() ResourceOwnerDescription

	// ValidSecret should determine whether the specified plain text password
	// matches the hashed password.
	ValidPassword(string) bool
}

// User is the built-in model used to store resource owners.
type User struct {
	coal.Base    `json:"-" bson:",inline" coal:"users"`
	Name         string `json:"name" valid:"required"`
	Email        string `json:"email" valid:"required"`
	PasswordHash []byte `json:"-" valid:"required"`
}

// DescribeResourceOwner implements the ResourceOwner interface.
func (u *User) DescribeResourceOwner() ResourceOwnerDescription {
	return ResourceOwnerDescription{
		IdentifierField: "Email",
	}
}

// ValidPassword implements the ResourceOwner interface.
func (u *User) ValidPassword(password string) bool {
	return bcrypt.CompareHashAndPassword(u.PasswordHash, []byte(password)) == nil
}
<commit_msg>updated docs<commit_after>package flame

import (
	"time"

	"github.com/256dpi/fire/coal"

	"golang.org/x/crypto/bcrypt"
	"gopkg.in/mgo.v2/bson"
)

// TokenData is used to carry token related information.
type TokenData struct {
	Scope           []string
	ExpiresAt       time.Time
	ClientID        bson.ObjectId
	ResourceOwnerID *bson.ObjectId
}

// A TokenDescription is returned by a Token model to specify some details about
// its implementation.
type TokenDescription struct {
	ClientIDField  string
	ExpiresAtField string
}

// Token is the interface that must be implemented to provide a custom access
// token and refresh token.
type Token interface {
	coal.Model

	// DescribeToken should return a TokenDescription.
	DescribeToken() TokenDescription

	// GetTokenData should collect and return the tokens data.
	GetTokenData() *TokenData

	// SetTokenData should set the specified token data.
	SetTokenData(*TokenData)
}

// AccessToken is the built-in model used to store access tokens.
type AccessToken struct {
	coal.Base       `json:"-" bson:",inline" coal:"access-tokens:access_tokens"`
	ExpiresAt       time.Time      `json:"expires-at" valid:"required" bson:"expires_at"`
	Scope           []string       `json:"scope" valid:"required" bson:"scope"`
	ClientID        bson.ObjectId  `json:"client-id" valid:"-" bson:"client_id"`
	ResourceOwnerID *bson.ObjectId `json:"resource-owner-id" valid:"-" bson:"resource_owner_id"`
}

// DescribeToken implements the Token interface.
func (t *AccessToken) DescribeToken() TokenDescription {
	return TokenDescription{
		ClientIDField:  "ClientID",
		ExpiresAtField: "ExpiresAt",
	}
}

// GetTokenData implements the Token interface.
func (t *AccessToken) GetTokenData() *TokenData {
	return &TokenData{
		Scope:           t.Scope,
		ExpiresAt:       t.ExpiresAt,
		ClientID:        t.ClientID,
		ResourceOwnerID: t.ResourceOwnerID,
	}
}

// SetTokenData implements the Token interface.
func (t *AccessToken) SetTokenData(data *TokenData) {
	t.Scope = data.Scope
	t.ExpiresAt = data.ExpiresAt
	t.ClientID = data.ClientID
	t.ResourceOwnerID = data.ResourceOwnerID
}

// RefreshToken is the built-in model used to store refresh tokens.
type RefreshToken struct {
	coal.Base       `json:"-" bson:",inline" coal:"refresh-tokens:refresh_tokens"`
	ExpiresAt       time.Time      `json:"expires-at" valid:"required" bson:"expires_at"`
	Scope           []string       `json:"scope" valid:"required" bson:"scope"`
	ClientID        bson.ObjectId  `json:"client-id" valid:"-" bson:"client_id"`
	ResourceOwnerID *bson.ObjectId `json:"resource-owner-id" valid:"-" bson:"resource_owner_id"`
}

// DescribeToken implements the Token interface.
func (t *RefreshToken) DescribeToken() TokenDescription {
	return TokenDescription{
		ClientIDField:  "ClientID",
		ExpiresAtField: "ExpiresAt",
	}
}

// GetTokenData implements the Token interface.
func (t *RefreshToken) GetTokenData() *TokenData {
	return &TokenData{
		Scope:           t.Scope,
		ExpiresAt:       t.ExpiresAt,
		ClientID:        t.ClientID,
		ResourceOwnerID: t.ResourceOwnerID,
	}
}

// SetTokenData implements the Token interface.
func (t *RefreshToken) SetTokenData(data *TokenData) {
	t.Scope = data.Scope
	t.ExpiresAt = data.ExpiresAt
	t.ClientID = data.ClientID
	t.ResourceOwnerID = data.ResourceOwnerID
}

// A ClientDescription is returned by a Client model to specify some details about
// its implementation.
type ClientDescription struct {
	IdentifierField string
}

// Client is the interface that must be implemented to provide a custom client.
type Client interface {
	coal.Model

	// DescribeClient should return a ClientDescription.
	DescribeClient() ClientDescription

	// ValidRedirectURI should return whether the specified redirect uri can be
	// used by this client.
	//
	// Note: In order to increases security the callback should only allow
	// pre-registered redirect uris.
	ValidRedirectURI(string) bool

	// ValidSecret should determine whether the specified plain text secret
	// matches the stored hashed secret.
	ValidSecret(string) bool
}

// Application is the built-in model used to store clients.
type Application struct {
	coal.Base   `json:"-" bson:",inline" coal:"applications"`
	Name        string `json:"name" valid:"required"`
	Key         string `json:"key" valid:"required"`
	SecretHash  []byte `json:"-" valid:"required"`
	RedirectURI string `json:"redirect_uri" valid:"required"`
}

// DescribeClient implements the Client interface.
func (a *Application) DescribeClient() ClientDescription {
	return ClientDescription{
		IdentifierField: "Key",
	}
}

// ValidRedirectURI implements the Client interface.
func (a *Application) ValidRedirectURI(uri string) bool {
	return uri == a.RedirectURI
}

// ValidSecret implements the Client interface.
func (a *Application) ValidSecret(secret string) bool {
	return bcrypt.CompareHashAndPassword(a.SecretHash, []byte(secret)) == nil
}

// A ResourceOwnerDescription is returned by a ResourceOwner model to specify
// some details about its implementation.
type ResourceOwnerDescription struct {
	IdentifierField string
}

// ResourceOwner is the interface that must be implemented to provide a custom
// resource owner.
type ResourceOwner interface {
	coal.Model

	// DescribeResourceOwner should return a ResourceOwnerDescription.
	DescribeResourceOwner() ResourceOwnerDescription

	// ValidSecret should determine whether the specified plain text password
	// matches the stored hashed password.
	ValidPassword(string) bool
}

// User is the built-in model used to store resource owners.
type User struct {
	coal.Base    `json:"-" bson:",inline" coal:"users"`
	Name         string `json:"name" valid:"required"`
	Email        string `json:"email" valid:"required"`
	PasswordHash []byte `json:"-" valid:"required"`
}

// DescribeResourceOwner implements the ResourceOwner interface.
func (u *User) DescribeResourceOwner() ResourceOwnerDescription {
	return ResourceOwnerDescription{
		IdentifierField: "Email",
	}
}

// ValidPassword implements the ResourceOwner interface.
func (u *User) ValidPassword(password string) bool {
	return bcrypt.CompareHashAndPassword(u.PasswordHash, []byte(password)) == nil
}
<|endoftext|>


<commit_before>package kvexpress

import (
	"fmt"
	consulapi "github.com/hashicorp/consul/api"
	"log"
	"strings"
)

func Get(key string, server string, token string, direction string) string {
	var value string
	config := consulapi.DefaultConfig()
	config.Address = server
	if token != "" {
		config.Token = token
	}
	consul, err := consulapi.NewClient(config)
	kv := consul.KV()
	pair, _, err := kv.Get(key, nil)
	if err != nil {
		panic(err)
	} else {
		if pair != nil {
			value = string(pair.Value[:])
		} else {
			value = ""
		}
		cleanedToken := cleanupToken(token)
		log.Print(direction, ": key='", key, "' address='", server, "' token='", cleanedToken, "'")
	}
	return value
}

func cleanupToken(token string) string {
	first := strings.Split(token, "-")
	firstString := fmt.Sprintf("%s", first[0:1])
	return firstString
}

func Set(key string, value string, server string, token string, direction string) bool {
	config := consulapi.DefaultConfig()
	config.Address = server
	if token != "" {
		config.Token = token
	}
	consul, err := consulapi.NewClient(config)
	kv := consul.KV()
	p := &consulapi.KVPair{Key: key, Value: []byte(value)}
	_, err = kv.Put(p, nil)
	if err != nil {
		panic(err)
	} else {
		return true
	}
}
<commit_msg>Only do the cleanup if there's an actual token - otherwise leave it blank.<commit_after>package kvexpress

import (
	"fmt"
	consulapi "github.com/hashicorp/consul/api"
	"log"
	"strings"
)

func Get(key string, server string, token string, direction string) string {
	var value string
	var cleanedToken = ""
	config := consulapi.DefaultConfig()
	config.Address = server
	if token != "" {
		config.Token = token
		cleanedToken = cleanupToken(token)
	}
	consul, err := consulapi.NewClient(config)
	kv := consul.KV()
	pair, _, err := kv.Get(key, nil)
	if err != nil {
		panic(err)
	} else {
		if pair != nil {
			value = string(pair.Value[:])
		} else {
			value = ""
		}
		log.Print(direction, ": key='", key, "' address='", server, "' token='", cleanedToken, "'")
	}
	return value
}

func cleanupToken(token string) string {
	first := strings.Split(token, "-")
	firstString := fmt.Sprintf("%s", first[0:1])
	return firstString
}

func Set(key string, value string, server string, token string, direction string) bool {
	config := consulapi.DefaultConfig()
	config.Address = server
	if token != "" {
		config.Token = token
	}
	consul, err := consulapi.NewClient(config)
	kv := consul.KV()
	p := &consulapi.KVPair{Key: key, Value: []byte(value)}
	_, err = kv.Put(p, nil)
	if err != nil {
		panic(err)
	} else {
		return true
	}
}
<|endoftext|>


<commit_before>package libkb

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"strings"

	keybase1 "github.com/keybase/client/protocol/go"
	jsonw "github.com/keybase/go-jsonw"
)

// type UID keybase1.UID

func UidFromHex(s string) (keybase1.UID, error) {
	u, err := keybase1.UIDFromString(s)
	if err != nil {
		return "", err
	}
	return keybase1.UID(u), nil
}

func GetUID(w *jsonw.Wrapper) (keybase1.UID, error) {
	s, err := w.GetString()
	if err != nil {
		return "", err
	}
	return UidFromHex(s)
}

func GetUidVoid(w *jsonw.Wrapper, u *keybase1.UID, e *error) {
	uid, err := GetUID(w)
	if err == nil {
		*u = uid
	} else if e != nil && *e == nil {
		*e = err
	}
}

const (
	UID_LEN      = keybase1.UID_LEN
	UID_SUFFIX   = keybase1.UID_SUFFIX
	UID_SUFFIX_2 = keybase1.UID_SUFFIX_2
)

// UsernameToUID works for users created after "Fri Feb  6 19:33:08 EST 2015"
func UsernameToUID(s string) keybase1.UID {
	h := sha256.Sum256([]byte(strings.ToLower(s)))
	var uid [keybase1.UID_LEN]byte
	copy(uid[:], h[0:UID_LEN-1])
	uid[UID_LEN-1] = UID_SUFFIX_2
	return keybase1.UID(hex.EncodeToString(uid[:]))
}

func CheckUIDAgainstUsername(uid keybase1.UID, username string) (err error) {
	u2 := UsernameToUID(username)
	if uid != u2 {
		err = UidMismatchError{fmt.Sprintf("%s != %s (via %s)", uid, u2, username)}
	}
	return
}
<commit_msg>cleanup<commit_after>package libkb

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"strings"

	keybase1 "github.com/keybase/client/protocol/go"
	jsonw "github.com/keybase/go-jsonw"
)

func UidFromHex(s string) (keybase1.UID, error) {
	u, err := keybase1.UIDFromString(s)
	if err != nil {
		return "", err
	}
	return u, nil
}

func GetUID(w *jsonw.Wrapper) (keybase1.UID, error) {
	s, err := w.GetString()
	if err != nil {
		return "", err
	}
	return UidFromHex(s)
}

func GetUidVoid(w *jsonw.Wrapper, u *keybase1.UID, e *error) {
	uid, err := GetUID(w)
	if err == nil {
		*u = uid
	} else if e != nil && *e == nil {
		*e = err
	}
}

const (
	UID_LEN      = keybase1.UID_LEN
	UID_SUFFIX   = keybase1.UID_SUFFIX
	UID_SUFFIX_2 = keybase1.UID_SUFFIX_2
)

// UsernameToUID works for users created after "Fri Feb  6 19:33:08 EST 2015"
func UsernameToUID(s string) keybase1.UID {
	h := sha256.Sum256([]byte(strings.ToLower(s)))
	var uid [keybase1.UID_LEN]byte
	copy(uid[:], h[0:UID_LEN-1])
	uid[UID_LEN-1] = UID_SUFFIX_2
	return keybase1.UID(hex.EncodeToString(uid[:]))
}

func CheckUIDAgainstUsername(uid keybase1.UID, username string) (err error) {
	u2 := UsernameToUID(username)
	if uid != u2 {
		err = UidMismatchError{fmt.Sprintf("%s != %s (via %s)", uid, u2, username)}
	}
	return
}
<|endoftext|>


<commit_before>package gxutil

import (
	"errors"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	sh "github.com/ipfs/go-ipfs-api"
	manet "github.com/jbenet/go-multiaddr-net"
	ma "github.com/jbenet/go-multiaddr-net/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
)

func NewShell() *sh.Shell {
	if apivar := os.Getenv("IPFS_API"); apivar != "" {
		return sh.NewShell(apivar)
	}

	ash, err := getLocalApiShell()
	if err == nil {
		return ash
	}

	return sh.NewShell("https://ipfs.io")
}

func getLocalApiShell() (*sh.Shell, error) {
	ipath := os.Getenv("IPFS_PATH")
	if ipath == "" {
		home := os.Getenv("HOME")
		if home == "" {
			return nil, errors.New("neither IPFS_PATH nor home dir set")
		}

		ipath = filepath.Join(home, ".ipfs")
	}

	apifile := filepath.Join(ipath, "api")

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

	addr := strings.Trim(string(data), "\n\t ")

	host, err := multiaddrToNormal(addr)
	if err != nil {
		return nil, err
	}

	return sh.NewShell(host), nil
}

func multiaddrToNormal(addr string) (string, error) {
	maddr, err := ma.NewMultiaddr(addr)
	if err != nil {
		return "", err
	}

	_, host, err := manet.DialArgs(maddr)
	if err != nil {
		return "", err
	}

	return host, nil
}
<commit_msg>log which api endpoint is being used<commit_after>package gxutil

import (
	"errors"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"

	sh "github.com/ipfs/go-ipfs-api"
	manet "github.com/jbenet/go-multiaddr-net"
	ma "github.com/jbenet/go-multiaddr-net/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	log "github.com/whyrusleeping/stump"
)

func NewShell() *sh.Shell {
	if apivar := os.Getenv("IPFS_API"); apivar != "" {
		log.VLog("using '%s' from IPFS_API env as api endpoint.", apivar)
		return sh.NewShell(apivar)
	}

	ash, err := getLocalApiShell()
	if err == nil {
		return ash
	}

	log.VLog("using global ipfs gateways as api endpoint")
	return sh.NewShell("https://ipfs.io")
}

func getLocalApiShell() (*sh.Shell, error) {
	ipath := os.Getenv("IPFS_PATH")
	if ipath == "" {
		home := os.Getenv("HOME")
		if home == "" {
			return nil, errors.New("neither IPFS_PATH nor home dir set")
		}

		ipath = filepath.Join(home, ".ipfs")
	}

	apifile := filepath.Join(ipath, "api")

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

	addr := strings.Trim(string(data), "\n\t ")

	host, err := multiaddrToNormal(addr)
	if err != nil {
		return nil, err
	}

	return sh.NewShell(host), nil
}

func multiaddrToNormal(addr string) (string, error) {
	maddr, err := ma.NewMultiaddr(addr)
	if err != nil {
		return "", err
	}

	_, host, err := manet.DialArgs(maddr)
	if err != nil {
		return "", err
	}

	return host, nil
}
<|endoftext|>


<commit_before>package execute

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

	"github.com/nu7hatch/gouuid"
	"github.com/pivotal-golang/lager"

	"github.com/concourse/turbine"
	"github.com/concourse/turbine/scheduler"
)

type handler struct {
	logger lager.Logger

	scheduler       scheduler.Scheduler
	turbineEndpoint string
}

func NewHandler(
	logger lager.Logger,
	scheduler scheduler.Scheduler,
	turbineEndpoint string,
) http.Handler {
	return &handler{
		logger: logger,

		scheduler:       scheduler,
		turbineEndpoint: turbineEndpoint,
	}
}

func (handler *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var build turbine.Build
	err := json.NewDecoder(r.Body).Decode(&build)
	if err != nil {
		handler.logger.Error("malformed-request", err)
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(err.Error()))
		return
	}

	log := handler.logger.Session("execute", lager.Data{
		"guid": build.Guid,
	})

	guid, err := uuid.NewV4()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte(err.Error()))
		return
	}

	build.Guid = guid.String()

	log.Info("scheduling", lager.Data{
		"build": build,
	})

	handler.scheduler.Start(build)

	w.Header().Add("X-Turbine-Endpoint", handler.turbineEndpoint)
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(build)
}
<commit_msg>fix logging<commit_after>package execute

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

	"github.com/nu7hatch/gouuid"
	"github.com/pivotal-golang/lager"

	"github.com/concourse/turbine"
	"github.com/concourse/turbine/scheduler"
)

type handler struct {
	logger lager.Logger

	scheduler       scheduler.Scheduler
	turbineEndpoint string
}

func NewHandler(
	logger lager.Logger,
	scheduler scheduler.Scheduler,
	turbineEndpoint string,
) http.Handler {
	return &handler{
		logger: logger,

		scheduler:       scheduler,
		turbineEndpoint: turbineEndpoint,
	}
}

func (handler *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var build turbine.Build
	err := json.NewDecoder(r.Body).Decode(&build)
	if err != nil {
		handler.logger.Error("malformed-request", err)
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(err.Error()))
		return
	}

	guid, err := uuid.NewV4()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte(err.Error()))
		return
	}

	build.Guid = guid.String()

	log := handler.logger.Session("execute", lager.Data{
		"guid": build.Guid,
	})

	log.Info("scheduling", lager.Data{
		"build": build,
	})

	handler.scheduler.Start(build)

	w.Header().Add("X-Turbine-Endpoint", handler.turbineEndpoint)
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(build)
}
<|endoftext|>


<commit_before>package version

// Version of Functions
var Version = "0.3.128"
<commit_msg>functions: 0.3.129 release [skip ci]<commit_after>package version

// Version of Functions
var Version = "0.3.129"
<|endoftext|>


<commit_before>package version

// Version of Functions
var Version = "0.3.328"
<commit_msg>fnserver: 0.3.329 release [skip ci]<commit_after>package version

// Version of Functions
var Version = "0.3.329"
<|endoftext|>


<commit_before>package version

// Version of Functions
var Version = "0.3.48"
<commit_msg>functions: 0.3.49 release [skip ci]<commit_after>package version

// Version of Functions
var Version = "0.3.49"
<|endoftext|>


<commit_before>package controllers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"github.com/takonews/takonews-api/app/models"
	"github.com/takonews/takonews-api/db"
)

// ArticleIndex show articles
// Available Query Parameters
// * sort
// * fields
// * filter
func ArticleIndex(c *gin.Context) {
	// parameters
	var sort []string
	var fields []string
	var startDate time.Time
	var endDate time.Time
	var title string

	sort = strings.Split(c.Query("sort"), ",")
	fields = strings.Split(c.Query("fields"), ",")
	loc, err := time.LoadLocation("Asia/Tokyo")
	if err != nil {
		panic(err)
	}
	now := time.Now().In(loc)
	if c.Query("start-date") == "" { // default: today:00:00:00
		startDate = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
	} else {
		startDate, err = time.Parse("2006-01-02", c.Query("start-date"))
		startDate = startDate.Add(-9 * time.Hour).In(loc)
	}
	if c.Query("end-date") == "" { // default: tomorrow:00:00:00
		endDate = time.Date(now.Year(), now.Month(), now.Day(), 24, 0, 0, 0, loc)
	} else {
		endDate, err = time.Parse("2006-01-02", c.Query("end-date"))
		endDate = endDate.Add((-9 + 24) * time.Hour).In(loc)
	}
	title = c.Query("title")

	/*
		DB processing
	*/
	articles := []models.Article{}
	sql := db.DB

	// filter
	sql = sql.Where("published_at BETWEEN ? AND ?", startDate, endDate)
	sql = sql.Where("title LIKE ?", "%"+title+"%")

	// sort
	sql, err = OrderArticles(sql, sort...)

	if err != nil {
		c.Status(http.StatusBadRequest)
		errorResp := ErrorResponse{Message: "wrong sort param"}
		encoder := json.NewEncoder(c.Writer)
		err = encoder.Encode(errorResp)
		if err != nil {
			panic(err)
		}
		return
	}

	// find
	sql.Find(&articles)

	/*
		select output field
	*/
	results := SelectArticles(&articles, fields...)

	// set header
	c.Writer.Header().Set("Link", "<page=3>; rel=\"next\", <page=1>; rel=\"prev\", <page=5>; rel=\"last\"")
	c.Status(http.StatusOK)

	// write response
	b, err := json.MarshalIndent(results, "", " ")
	if err != nil {
		panic(err)
	}
	_, err = c.Writer.WriteString(string(b))
	if err != nil {
		panic(err)
	}
}

// ArticleShow show article details
func ArticleShow(c *gin.Context) {
	// params
	// articlesID := c.Param("articles_id")
	articles := []models.Article{}
	db.DB.Find(&articles).Order("created_at desc")

	// set header
	c.Writer.Header().Set("Link", "<page=3>; rel=\"next\", <page=1>; rel=\"prev\", <page=5>; rel=\"last\"")
	c.Status(http.StatusOK)

	// write response
	encoder := json.NewEncoder(c.Writer)
	err := encoder.Encode(articles)
	if err != nil {
		c.Status(http.StatusBadRequest)
		errorResp := ErrorResponse{Message: "wrong sort param"}
		encoder := json.NewEncoder(c.Writer)
		err = encoder.Encode(errorResp)
		if err != nil {
			panic(err)
		}
	}
}

// SelectArticles extends gorm.DB.Select function
func SelectArticles(articles *[]models.Article, fields ...string) (results []map[string]interface{}) {
	for _, v := range *articles {
		if len(fields) > 1 || (len(fields) == 1 && fields[0] != "") {
			results = append(results, (&v).SelectFields(fields...))
		} else {
			results = append(results, (&v).SelectFields(
				"id",
				"title",
				"news_site_id",
				"published_at",
				"url",
			))
		}
	}

	return results
}

// OrderArticles extends gorm.DB.Order function
func OrderArticles(db *gorm.DB, sorts ...string) (*gorm.DB, error) {
	var dbRet = db
	var err error

	for i, v := range sorts {
		if v == "" {
			if i == 0 { // /articles /articles?sort= /articles?sort=,hoge
				dbRet = dbRet.Order("published_at desc")
			} else { // /articles?sort=hoge,
				return nil, err
			}
		} else if string(v[0]) == "-" { // sort=-hoge
			dbRet = dbRet.Order(v[1:] + " desc")
		} else { // sort=hoge
			dbRet = dbRet.Order(v + " asc")
		}
	}

	return dbRet, nil
}
<commit_msg>Update api.go<commit_after>package controllers

import (
	"encoding/json"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"github.com/takonews/takonews-api/app/models"
	"github.com/takonews/takonews-api/db"
)

// ArticleIndex show articles
// Available Query Parameters
// * sort
// * fields
// * filter
func ArticleIndex(c *gin.Context) {
	// parameters
	var sort []string
	var fields []string
	var startDate time.Time
	var endDate time.Time
	var title string

	sort = strings.Split(c.Query("sort"), ",")
	fields = strings.Split(c.Query("fields"), ",")
	loc, err := time.LoadLocation("Asia/Tokyo")
	if err != nil {
		panic(err)
	}
	now := time.Now().In(loc)
	if c.Query("start-date") == "" { // default: today:00:00:00
		startDate = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
	} else {
		startDate, err = time.Parse("2006-01-02", c.Query("start-date"))
		startDate = startDate.Add(-9 * time.Hour).In(loc)
	}
	if c.Query("end-date") == "" { // default: tomorrow:00:00:00
		endDate = time.Date(now.Year(), now.Month(), now.Day(), 24, 0, 0, 0, loc)
	} else {
		endDate, err = time.Parse("2006-01-02", c.Query("end-date"))
		endDate = endDate.Add((-9 + 24) * time.Hour).In(loc)
	}
	title = c.Query("title")

	/*
		DB processing
	*/
	articles := []models.Article{}
	sql := db.DB

	// filter
	sql = sql.Where("published_at BETWEEN ? AND ?", startDate, endDate)
	sql = sql.Where("title LIKE ?", "%"+title+"%")

	// sort
	sql, err = OrderArticles(sql, sort...)

	if err != nil {
		c.Status(http.StatusBadRequest)
		errorResp := ErrorResponse{Message: "wrong sort param"}
		encoder := json.NewEncoder(c.Writer)
		err = encoder.Encode(errorResp)
		if err != nil {
			panic(err)
		}
		return
	}

	// find
	sql.Find(&articles)

	/*
		select output field
	*/
	results := SelectArticles(&articles, fields...)

	// set header
	c.Writer.Header().Set("Link", "<page=3>; rel=\"next\", <page=1>; rel=\"prev\", <page=5>; rel=\"last\"")
	c.Status(http.StatusOK)

	// write response
	b, err := json.MarshalIndent(results, "", " ")
	if err != nil {
		panic(err)
	}
	_, err = c.Writer.WriteString(string(b))
	if err != nil {
		panic(err)
	}
}

// ArticleShow show article details
func ArticleShow(c *gin.Context) {
	// params
	// articlesID := c.Param("articles_id")
	articles := []models.Article{}
	db.DB.Find(&articles).Order("created_at desc")

	// set header
	c.Writer.Header().Set("Link", "<page=3>; rel=\"next\", <page=1>; rel=\"prev\", <page=5>; rel=\"last\"")
	c.Status(http.StatusOK)

	// write response
	encoder := json.NewEncoder(c.Writer)
	err := encoder.Encode(articles)
	if err != nil {
		c.Status(http.StatusBadRequest)
		errorResp := ErrorResponse{Message: "wrong sort param"}
		encoder := json.NewEncoder(c.Writer)
		err = encoder.Encode(errorResp)
		if err != nil {
			panic(err)
		}
	}
}

// SelectArticles extends gorm.DB.Select function
func SelectArticles(articles *[]models.Article, fields ...string) (results []map[string]interface{}) {
	for _, v := range *articles {
		if len(fields) > 1 || (len(fields) == 1 && fields[0] != "") {
			results = append(results, (&v).SelectFields(fields...))
		} else {
			results = append(results, (&v).SelectFields(
				"id",
				"title",
				"news_site_id",
				"published_at",
				"url",
			))
		}
	}

	return results
}

// OrderArticles extends gorm.DB.Order function
func OrderArticles(db *gorm.DB, sorts ...string) (*gorm.DB, error) {
	var dbRet = db
	var err error

	for i, v := range sorts {
		if v == "" {
			if i == 0 { // /articles /articles?sort= /articles?sort=,hoge
				dbRet = dbRet.Order("published_at desc")
			} else { // /articles?sort=hoge,
				return nil, err
			}
		} else if string(v[0]) == "-" { // sort=-hoge
			dbRet = dbRet.Order(v[1:] + " desc")
		} else { // sort=hoge
			dbRet = dbRet.Order(v + " asc")
		}
	}

	return dbRet, nil
}
<|endoftext|>


<commit_before>package controllers

import (
	"github.com/PacketFire/goqdb/app/models"
	"github.com/PacketFire/goqdb/app/routes"
	"github.com/robfig/revel"
	"strings"
	"time"
)

type App struct {
	GorpController
}

func (c App) Index(search string, size, page int) revel.Result {
	if page == 0 {
		page = 1
	}

	if size <= 0 {
		size = 5
	}

	// for pagination
	size += 1
	nextPage := page + 1
	prevPage := page - 1

	search = strings.TrimSpace(search)

	var entries []*models.QdbEntry

	if search == "" {
		entries = loadEntries(c.Txn.Select(models.QdbEntry{},
			`SELECT * FROM QdbEntry ORDER BY QuoteId DESC LIMIT ?, ?`, (page-1)*(size-1), size))
	} else {
		search = strings.ToLower(search)
		entries = loadEntries(c.Txn.Select(models.QdbEntry{},
			`SELECT * FROM QdbEntry WHERE LOWER(Quote) LIKE ? ORDER BY QuoteId LIMIT ?, ?`, "%"+search+"%", (page-1)*(size), size))

	}

	hasPrevPage := page > 1
	hasNextPage := len(entries) == size
	if hasNextPage {
		entries = entries[:len(entries)-1]
	}

	return c.Render(entries, search, size, page, hasPrevPage, prevPage, hasNextPage, nextPage)
}

func loadEntries(results []interface{}, err error) []*models.QdbEntry {
	if err != nil {
		panic(err)
	}

	var entries []*models.QdbEntry

	for _, r := range results {
		entries = append(entries, r.(*models.QdbEntry))
	}

	return entries
}

func (c App) Post() revel.Result {
	var quote models.QdbEntry

	quote.Created = time.Now().Unix()
	quote.Rating = 0

	c.Params.Bind(&quote.Author, "author")
	c.Params.Bind(&quote.Quote, "quote")

	quote.Validate(c.Validation)

	if c.Validation.HasErrors() {
		c.Validation.Keep()
		c.FlashParams()
		return c.Redirect(routes.App.Index("", 0, 0))
	}
	c.Txn.Insert(&quote)
	return c.Redirect(routes.App.Index("", 0, 0))
}

func (c App) RatingUp (id int) revel.Result {
	_, err := c.Txn.Exec("UPDATE QdbEntry SET Rating = Rating + 1 WHERE QuoteId = ?", id)

	if err != nil {
	}

	return c.Redirect(routes.App.Index("", 0, 0))
}

func (c App) RatingDown (id int) revel.Result {
	_, err := c.Txn.Exec("UPDATE QdbEntry SET Rating = Rating - 1 WHERE QuoteId = ?", id)

	if err != nil {
	}

	return c.Redirect(routes.App.Index("", 0, 0))
}

func (c App) One(id int) revel.Result {
	var entries []*models.QdbEntry
	entries = loadEntries(c.Txn.Select(models.QdbEntry{},
		`SELECT * FROM QdbEntry WHERE QuoteId = ? ORDER BY QuoteId DESC LIMIT 1`, id))
	if len(entries) == 0 {
		c.Flash.Error("no such id")
	}
	quote := entries[0]
	return c.RenderText(quote.Quote)
}
<commit_msg>dont put crap in the query when redirecting<commit_after>package controllers

import (
	"github.com/PacketFire/goqdb/app/models"
	"github.com/PacketFire/goqdb/app/routes"
	"github.com/robfig/revel"
	"strings"
	"time"
)

type App struct {
	GorpController
}

func (c App) Index() revel.Result {
	var search string
	var size, page int

	c.Params.Bind(&search, "search")
	c.Params.Bind(&size, "size")
	c.Params.Bind(&page, "page")

	if page == 0 {
		page = 1
	}

	if size <= 0 {
		size = 5
	}

	// for pagination
	size += 1
	nextPage := page + 1
	prevPage := page - 1

	search = strings.TrimSpace(search)

	var entries []*models.QdbEntry

	if search == "" {
		entries = loadEntries(c.Txn.Select(models.QdbEntry{},
			`SELECT * FROM QdbEntry ORDER BY QuoteId DESC LIMIT ?, ?`, (page-1)*(size-1), size))
	} else {
		search = strings.ToLower(search)
		entries = loadEntries(c.Txn.Select(models.QdbEntry{},
			`SELECT * FROM QdbEntry WHERE LOWER(Quote) LIKE ? ORDER BY QuoteId LIMIT ?, ?`, "%"+search+"%", (page-1)*(size), size))

	}

	hasPrevPage := page > 1
	hasNextPage := len(entries) == size
	if hasNextPage {
		entries = entries[:len(entries)-1]
	}

	return c.Render(entries, search, size, page, hasPrevPage, prevPage, hasNextPage, nextPage)
}

func loadEntries(results []interface{}, err error) []*models.QdbEntry {
	if err != nil {
		panic(err)
	}

	var entries []*models.QdbEntry

	for _, r := range results {
		entries = append(entries, r.(*models.QdbEntry))
	}

	return entries
}

func (c App) Post() revel.Result {
	var quote models.QdbEntry

	quote.Created = time.Now().Unix()
	quote.Rating = 0

	c.Params.Bind(&quote.Author, "author")
	c.Params.Bind(&quote.Quote, "quote")

	quote.Validate(c.Validation)

	if c.Validation.HasErrors() {
		c.Validation.Keep()
		c.FlashParams()
		return c.Redirect(routes.App.Index())
	}
	c.Txn.Insert(&quote)
	return c.Redirect(routes.App.Index())
}

func (c App) RatingUp (id int) revel.Result {
	_, err := c.Txn.Exec("UPDATE QdbEntry SET Rating = Rating + 1 WHERE QuoteId = ?", id)

	if err != nil {
	}

	return c.Redirect(routes.App.Index())
}

func (c App) RatingDown (id int) revel.Result {
	_, err := c.Txn.Exec("UPDATE QdbEntry SET Rating = Rating - 1 WHERE QuoteId = ?", id)

	if err != nil {
	}

	return c.Redirect(routes.App.Index())
}

func (c App) One(id int) revel.Result {
	var entries []*models.QdbEntry
	entries = loadEntries(c.Txn.Select(models.QdbEntry{},
		`SELECT * FROM QdbEntry WHERE QuoteId = ? ORDER BY QuoteId DESC LIMIT 1`, id))
	if len(entries) == 0 {
		c.Flash.Error("no such id")
	}
	quote := entries[0]
	return c.RenderText(quote.Quote)
}
<|endoftext|>


<commit_before>package irc

import (
	"crypto/sha1"
	"fmt"
	"math/rand"
	"reflect"
	"strconv"
	"strings"
	"time"
)

// Register a callback to a connection and event code. A callback is a function
// which takes only an Event pointer as parameter. Valid event codes are all
// IRC/CTCP commands and error/response codes. This function returns the ID of
// the registered callback for later management.
func (irc *Connection) AddCallback(eventcode string, callback func(*Event)) string {
	eventcode = strings.ToUpper(eventcode)

	if _, ok := irc.events[eventcode]; !ok {
		irc.events[eventcode] = make(map[string]func(*Event))
	}
	h := sha1.New()
	rawId := []byte(fmt.Sprintf("%v%d", reflect.ValueOf(callback).Pointer(), rand.Int63()))
	h.Write(rawId)
	id := fmt.Sprintf("%x", h.Sum(nil))
	irc.events[eventcode][id] = callback
	return id
}

// Remove callback i (ID) from the given event code. This functions returns
// true upon success, false if any error occurs.
func (irc *Connection) RemoveCallback(eventcode string, i string) bool {
	eventcode = strings.ToUpper(eventcode)

	if event, ok := irc.events[eventcode]; ok {
		if _, ok := event[i]; ok {
			delete(irc.events[eventcode], i)
			return true
		}
		irc.Log.Printf("Event found, but no callback found at id %s\n", i)
		return false
	}

	irc.Log.Println("Event not found")
	return false
}

// Remove all callbacks from a given event code. It returns true
// if given event code is found and cleared.
func (irc *Connection) ClearCallback(eventcode string) bool {
	eventcode = strings.ToUpper(eventcode)

	if _, ok := irc.events[eventcode]; ok {
		irc.events[eventcode] = make(map[string]func(*Event))
		return true
	}

	irc.Log.Println("Event not found")
	return false
}

// Replace callback i (ID) associated with a given event code with a new callback function.
func (irc *Connection) ReplaceCallback(eventcode string, i string, callback func(*Event)) {
	eventcode = strings.ToUpper(eventcode)

	if event, ok := irc.events[eventcode]; ok {
		if _, ok := event[i]; ok {
			event[i] = callback
			return
		}
		irc.Log.Printf("Event found, but no callback found at id %s\n", i)
	}
	irc.Log.Printf("Event not found. Use AddCallBack\n")
}

// Execute all callbacks associated with a given event.
func (irc *Connection) RunCallbacks(event *Event) {
	msg := event.Message()
	if event.Code == "PRIVMSG" && len(msg) > 0 && msg[0] == '\x01' {
		event.Code = "CTCP" //Unknown CTCP

		if i := strings.LastIndex(msg, "\x01"); i > -1 {
			msg = msg[1:i]
		}

		if msg == "VERSION" {
			event.Code = "CTCP_VERSION"

		} else if msg == "TIME" {
			event.Code = "CTCP_TIME"

		} else if strings.HasPrefix(msg, "PING") {
			event.Code = "CTCP_PING"

		} else if msg == "USERINFO" {
			event.Code = "CTCP_USERINFO"

		} else if msg == "CLIENTINFO" {
			event.Code = "CTCP_CLIENTINFO"

		} else if strings.HasPrefix(msg, "ACTION") {
			event.Code = "CTCP_ACTION"
			msg = msg[7:]
		}

		event.Arguments[len(event.Arguments)-1] = msg
	}

	if callbacks, ok := irc.events[event.Code]; ok {
		if irc.VerboseCallbackHandler {
			irc.Log.Printf("%v (%v) >> %#v\n", event.Code, len(callbacks), event)
		}

		for _, callback := range callbacks {
			go callback(event)
		}
	} else if irc.VerboseCallbackHandler {
		irc.Log.Printf("%v (0) >> %#v\n", event.Code, event)
	}

	if callbacks, ok := irc.events["*"]; ok {
		if irc.VerboseCallbackHandler {
			irc.Log.Printf("Wildcard %v (%v) >> %#v\n", event.Code, len(callbacks), event)
		}

		for _, callback := range callbacks {
			go callback(event)
		}
	}
}

// Set up some initial callbacks to handle the IRC/CTCP protocol.
func (irc *Connection) setupCallbacks() {
	irc.events = make(map[string]map[string]func(*Event))

	//Handle error events
	irc.AddCallback("ERROR", func(e *Event) { irc.Disconnect() })

	//Handle ping events
	irc.AddCallback("PING", func(e *Event) { irc.SendRaw("PONG :" + e.Message()) })

	//Version handler
	irc.AddCallback("CTCP_VERSION", func(e *Event) {
		irc.SendRawf("NOTICE %s :\x01VERSION %s\x01", e.Nick, irc.Version)
	})

	irc.AddCallback("CTCP_USERINFO", func(e *Event) {
		irc.SendRawf("NOTICE %s :\x01USERINFO %s\x01", e.Nick, irc.user)
	})

	irc.AddCallback("CTCP_CLIENTINFO", func(e *Event) {
		irc.SendRawf("NOTICE %s :\x01CLIENTINFO PING VERSION TIME USERINFO CLIENTINFO\x01", e.Nick)
	})

	irc.AddCallback("CTCP_TIME", func(e *Event) {
		ltime := time.Now()
		irc.SendRawf("NOTICE %s :\x01TIME %s\x01", e.Nick, ltime.String())
	})

	irc.AddCallback("CTCP_PING", func(e *Event) { irc.SendRawf("NOTICE %s :\x01%s\x01", e.Nick, e.Message()) })

	irc.AddCallback("437", func(e *Event) {
		irc.nickcurrent = irc.nickcurrent + "_"
		irc.SendRawf("NICK %s", irc.nickcurrent)
	})

	irc.AddCallback("433", func(e *Event) {
		if len(irc.nickcurrent) > 8 {
			irc.nickcurrent = "_" + irc.nickcurrent

		} else {
			irc.nickcurrent = irc.nickcurrent + "_"
		}
		irc.SendRawf("NICK %s", irc.nickcurrent)
	})

	irc.AddCallback("PONG", func(e *Event) {
		ns, _ := strconv.ParseInt(e.Message(), 10, 64)
		delta := time.Duration(time.Now().UnixNano() - ns)
		if irc.Debug {
			irc.Log.Printf("Lag: %vs\n", delta)
		}
	})

	irc.AddCallback("NICK", func(e *Event) {
		if e.Nick == irc.nick {
			irc.nickcurrent = e.Message()
		}
	})

	irc.AddCallback("001", func(e *Event) {
		irc.nickcurrent = e.Arguments[0]
	})
}
<commit_msg>Check for invalid event<commit_after>package irc

import (
	"crypto/sha1"
	"fmt"
	"math/rand"
	"reflect"
	"strconv"
	"strings"
	"time"
)

// Register a callback to a connection and event code. A callback is a function
// which takes only an Event pointer as parameter. Valid event codes are all
// IRC/CTCP commands and error/response codes. This function returns the ID of
// the registered callback for later management.
func (irc *Connection) AddCallback(eventcode string, callback func(*Event)) string {
	eventcode = strings.ToUpper(eventcode)

	if _, ok := irc.events[eventcode]; !ok {
		irc.events[eventcode] = make(map[string]func(*Event))
	}
	h := sha1.New()
	rawId := []byte(fmt.Sprintf("%v%d", reflect.ValueOf(callback).Pointer(), rand.Int63()))
	h.Write(rawId)
	id := fmt.Sprintf("%x", h.Sum(nil))
	irc.events[eventcode][id] = callback
	return id
}

// Remove callback i (ID) from the given event code. This functions returns
// true upon success, false if any error occurs.
func (irc *Connection) RemoveCallback(eventcode string, i string) bool {
	eventcode = strings.ToUpper(eventcode)

	if event, ok := irc.events[eventcode]; ok {
		if _, ok := event[i]; ok {
			delete(irc.events[eventcode], i)
			return true
		}
		irc.Log.Printf("Event found, but no callback found at id %s\n", i)
		return false
	}

	irc.Log.Println("Event not found")
	return false
}

// Remove all callbacks from a given event code. It returns true
// if given event code is found and cleared.
func (irc *Connection) ClearCallback(eventcode string) bool {
	eventcode = strings.ToUpper(eventcode)

	if _, ok := irc.events[eventcode]; ok {
		irc.events[eventcode] = make(map[string]func(*Event))
		return true
	}

	irc.Log.Println("Event not found")
	return false
}

// Replace callback i (ID) associated with a given event code with a new callback function.
func (irc *Connection) ReplaceCallback(eventcode string, i string, callback func(*Event)) {
	eventcode = strings.ToUpper(eventcode)

	if event, ok := irc.events[eventcode]; ok {
		if _, ok := event[i]; ok {
			event[i] = callback
			return
		}
		irc.Log.Printf("Event found, but no callback found at id %s\n", i)
	}
	irc.Log.Printf("Event not found. Use AddCallBack\n")
}

// Execute all callbacks associated with a given event.
func (irc *Connection) RunCallbacks(event *Event) {
	msg := event.Message()
	if event.Code == "PRIVMSG" && len(msg) > 0 && msg[0] == '\x01' {
		event.Code = "CTCP" //Unknown CTCP

		if i := strings.LastIndex(msg, "\x01"); i > -1 {
			msg = msg[1:i]
		}

		if msg == "VERSION" {
			event.Code = "CTCP_VERSION"

		} else if msg == "TIME" {
			event.Code = "CTCP_TIME"

		} else if strings.HasPrefix(msg, "PING") {
			event.Code = "CTCP_PING"

		} else if msg == "USERINFO" {
			event.Code = "CTCP_USERINFO"

		} else if msg == "CLIENTINFO" {
			event.Code = "CTCP_CLIENTINFO"

		} else if strings.HasPrefix(msg, "ACTION") {
			event.Code = "CTCP_ACTION"
			msg = msg[7:]
		}

		// Invalid event!
		irc.Log.Printf("Invalid event in RunCallbacks: %#v", event)
		if event.Arguments == nil || len(event.Arguments) == 0 {
			return
		}

		event.Arguments[len(event.Arguments)-1] = msg
	}

	if callbacks, ok := irc.events[event.Code]; ok {
		if irc.VerboseCallbackHandler {
			irc.Log.Printf("%v (%v) >> %#v\n", event.Code, len(callbacks), event)
		}

		for _, callback := range callbacks {
			go callback(event)
		}
	} else if irc.VerboseCallbackHandler {
		irc.Log.Printf("%v (0) >> %#v\n", event.Code, event)
	}

	if callbacks, ok := irc.events["*"]; ok {
		if irc.VerboseCallbackHandler {
			irc.Log.Printf("Wildcard %v (%v) >> %#v\n", event.Code, len(callbacks), event)
		}

		for _, callback := range callbacks {
			go callback(event)
		}
	}
}

// Set up some initial callbacks to handle the IRC/CTCP protocol.
func (irc *Connection) setupCallbacks() {
	irc.events = make(map[string]map[string]func(*Event))

	//Handle error events
	irc.AddCallback("ERROR", func(e *Event) { irc.Disconnect() })

	//Handle ping events
	irc.AddCallback("PING", func(e *Event) { irc.SendRaw("PONG :" + e.Message()) })

	//Version handler
	irc.AddCallback("CTCP_VERSION", func(e *Event) {
		irc.SendRawf("NOTICE %s :\x01VERSION %s\x01", e.Nick, irc.Version)
	})

	irc.AddCallback("CTCP_USERINFO", func(e *Event) {
		irc.SendRawf("NOTICE %s :\x01USERINFO %s\x01", e.Nick, irc.user)
	})

	irc.AddCallback("CTCP_CLIENTINFO", func(e *Event) {
		irc.SendRawf("NOTICE %s :\x01CLIENTINFO PING VERSION TIME USERINFO CLIENTINFO\x01", e.Nick)
	})

	irc.AddCallback("CTCP_TIME", func(e *Event) {
		ltime := time.Now()
		irc.SendRawf("NOTICE %s :\x01TIME %s\x01", e.Nick, ltime.String())
	})

	irc.AddCallback("CTCP_PING", func(e *Event) { irc.SendRawf("NOTICE %s :\x01%s\x01", e.Nick, e.Message()) })

	irc.AddCallback("437", func(e *Event) {
		irc.nickcurrent = irc.nickcurrent + "_"
		irc.SendRawf("NICK %s", irc.nickcurrent)
	})

	irc.AddCallback("433", func(e *Event) {
		if len(irc.nickcurrent) > 8 {
			irc.nickcurrent = "_" + irc.nickcurrent

		} else {
			irc.nickcurrent = irc.nickcurrent + "_"
		}
		irc.SendRawf("NICK %s", irc.nickcurrent)
	})

	irc.AddCallback("PONG", func(e *Event) {
		ns, _ := strconv.ParseInt(e.Message(), 10, 64)
		delta := time.Duration(time.Now().UnixNano() - ns)
		if irc.Debug {
			irc.Log.Printf("Lag: %vs\n", delta)
		}
	})

	irc.AddCallback("NICK", func(e *Event) {
		if e.Nick == irc.nick {
			irc.nickcurrent = e.Message()
		}
	})

	irc.AddCallback("001", func(e *Event) {
		irc.nickcurrent = e.Arguments[0]
	})
}
<|endoftext|>