<commit_before>package main

import (
	"bufio"
	"fmt"
	"github.com/codegangsta/cli"
	"io"
	"io/ioutil"
	"os"
	"regexp"
	"strings"
)

// getPattern returns the specified pattern or nil.
func getPattern(ctx *cli.Context) (*regexp.Regexp, error) {
	if !ctx.Args().Present() {
		return nil, fmt.Errorf("missing pattern")
	}
	exp := ctx.Args().First()
	// Assemble flags.
	fs := ""
	for _, f := range []string{"i", "m", "s", "U"} {
		if ctx.GlobalBool(f) {
			fs += f
		}
	}
	if fs != "" {
		exp = "(?" + fs + ")" + exp
	}

	return regexp.Compile(exp)
}

// getInput returns the input file or err.
func getInput(ctx *cli.Context, offset int) (io.Reader, error) {
	if len(ctx.Args()) > offset {
		return os.Open(ctx.Args()[offset])
	}
	return os.Stdin, nil
}

func writeln(ms [][]byte, w io.Writer) error {
	for _, m := range ms {
		if _, err := w.Write(m); err != nil {
			return err
		}
		if _, err := w.Write([]byte("\n")); err != nil {
			return err
		}
	}
	return nil
}

func doScan(multiline bool, r io.Reader, w io.Writer, proc func([]byte) [][]byte) error {
	if !multiline {
		// Line-by-line match.
		scn := bufio.NewScanner(r)
		for scn.Scan() {
			if err := writeln(proc(scn.Bytes()), w); err != nil {
				return err
			}
		}
	} else {
		// XXX: We could do a lot better job here.
		buf, err := ioutil.ReadAll(r)
		if err != nil {
			return err
		}
		return writeln(proc(buf), w)
	}
	return nil
}

func match(exp *regexp.Regexp, invert, multiline, onlymatching bool, r io.Reader, w io.Writer) error {
	if invert && onlymatching {
		return fmt.Errorf("incompatible flags: --invert and --onlymatching")
	}
	return doScan(multiline, r, w, func(buf []byte) [][]byte {
		if onlymatching {
			return exp.FindAll(buf, -1)
		} else {
			if onlymatching != exp.Match(buf) {
				return [][]byte{buf}
			}
		}
		return nil
	})
}

func replace(exp *regexp.Regexp, repl string, multiline bool, r io.Reader, w io.Writer) error {
	return doScan(multiline, r, w, func(buf []byte) [][]byte {
		return [][]byte{exp.ReplaceAll(buf, []byte(repl))}
	})
}

func split(exp *regexp.Regexp, fields []int, multiline bool, r io.Reader, w io.Writer) error {
	return doScan(multiline, r, w, func(buf []byte) [][]byte {
		parts := exp.Split(string(buf), -1)
		ms := make([]string, len(fields))
		for i, f := range fields {
			if f < len(parts) {
				ms[i] = parts[f]
			}
		}
		return [][]byte{[]byte(strings.Join(ms, ","))}
	})
}
<commit_msg>Fix newline/multiline issue.<commit_after>package main

import (
	"bufio"
	"fmt"
	"github.com/codegangsta/cli"
	"io"
	"io/ioutil"
	"os"
	"regexp"
	"strings"
)

// getPattern returns the specified pattern or nil.
func getPattern(ctx *cli.Context) (*regexp.Regexp, error) {
	if !ctx.Args().Present() {
		return nil, fmt.Errorf("missing pattern")
	}
	exp := ctx.Args().First()
	// Assemble flags.
	fs := ""
	for _, f := range []string{"i", "m", "s", "U"} {
		if ctx.GlobalBool(f) {
			fs += f
		}
	}
	if fs != "" {
		exp = "(?" + fs + ")" + exp
	}

	return regexp.Compile(exp)
}

// getInput returns the input file or err.
func getInput(ctx *cli.Context, offset int) (io.Reader, error) {
	if len(ctx.Args()) > offset {
		return os.Open(ctx.Args()[offset])
	}
	return os.Stdin, nil
}

func writeln(ms [][]byte, w io.Writer, newline bool) error {
	for _, m := range ms {
		if _, err := w.Write(m); err != nil {
			return err
		}
		if newline {
			if _, err := w.Write([]byte("\n")); err != nil {
				return err
			}
		}
	}
	return nil
}

func doScan(multiline bool, r io.Reader, w io.Writer, proc func([]byte) [][]byte) error {
	if !multiline {
		// Line-by-line match.
		scn := bufio.NewScanner(r)
		for scn.Scan() {
			if err := writeln(proc(scn.Bytes()), w, true); err != nil {
				return err
			}
		}
	} else {
		// XXX: We could do a lot better job here.
		buf, err := ioutil.ReadAll(r)
		if err != nil {
			return err
		}
		return writeln(proc(buf), w, false)
	}
	return nil
}

func match(exp *regexp.Regexp, invert, multiline, onlymatching bool, r io.Reader, w io.Writer) error {
	if invert && onlymatching {
		return fmt.Errorf("incompatible flags: --invert and --onlymatching")
	}
	return doScan(multiline, r, w, func(buf []byte) [][]byte {
		if onlymatching {
			return exp.FindAll(buf, -1)
		} else {
			if onlymatching != exp.Match(buf) {
				return [][]byte{buf}
			}
		}
		return nil
	})
}

func replace(exp *regexp.Regexp, repl string, multiline bool, r io.Reader, w io.Writer) error {
	return doScan(multiline, r, w, func(buf []byte) [][]byte {
		return [][]byte{exp.ReplaceAll(buf, []byte(repl))}
	})
}

func split(exp *regexp.Regexp, fields []int, multiline bool, r io.Reader, w io.Writer) error {
	return doScan(multiline, r, w, func(buf []byte) [][]byte {
		parts := exp.Split(string(buf), -1)
		ms := make([]string, len(fields))
		for i, f := range fields {
			if f < len(parts) {
				ms[i] = parts[f]
			}
		}
		return [][]byte{[]byte(strings.Join(ms, ","))}
	})
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"image"
        "image/color"
	"time"
)

var img []color.NRGBA

// Based on the Rainbow Smoke algorithm by József Fejes.
func Render(height, width, colours int) {

        x_size := width
        y_size := height

        img = make([]color.NRGBA, x_size*y_size)

	colour_list := NewColourList(colours)

	start_pt := PointToFlatIndex(width, image.Pt(width/2, height/2))

	unfilled := make([]int, 0, x_size*y_size)
	unfilled_map := make(map[int]bool)
	filled_map := make(map[int]bool)

	InitNeighbours(height, width)

	start_time := time.Now()

	for i := 0; i < x_size*y_size; i++ {

		if i%256 == 255 {
			fmt.Printf("%d/%d done, open: %d, speed: %d px per sec\n", i, x_size*y_size,
				len(unfilled), int64(i*int(time.Second))/int64(time.Now().Sub(start_time)))
			Save(fmt.Sprintf("rbsmoke%08d.png", i), height, width)
		}

		var curr_pt int

		if len(unfilled) == 0 {
			curr_pt = start_pt
		} else {
			// Expensive!
			curr_pt_index := Select(colour_list[i], unfilled, width)
			curr_pt = unfilled[curr_pt_index]

			// Discard point
			unfilled[len(unfilled)-1], unfilled[curr_pt_index] = unfilled[curr_pt_index], unfilled[len(unfilled)-1]
			unfilled = unfilled[:len(unfilled)-1]
			delete(unfilled_map, curr_pt)
		}

		filled_map[curr_pt] = true

		img[curr_pt] = colour_list[i]

		for _, new_pt := range neighbour_list[curr_pt] {
			if !unfilled_map[new_pt] && !filled_map[new_pt] {
				unfilled = append(unfilled, new_pt)
				unfilled_map[new_pt] = true
			}
		}
	}

	Save(fmt.Sprintf("rbsmoke%08d.png", height*width), height, width)

	fmt.Println("Done!")

}
<commit_msg>Save on a new thread<commit_after>package main

import (
	"fmt"
	"image"
        "image/color"
	"time"
)

var img []color.NRGBA

// Based on the Rainbow Smoke algorithm by József Fejes.
func Render(height, width, colours int) {

        x_size := width
        y_size := height

        img = make([]color.NRGBA, x_size*y_size)

	colour_list := NewColourList(colours)

	start_pt := PointToFlatIndex(width, image.Pt(width/2, height/2))

	unfilled := make([]int, 0, x_size*y_size)
	unfilled_map := make(map[int]bool)
	filled_map := make(map[int]bool)

	InitNeighbours(height, width)

	start_time := time.Now()

	for i := 0; i < x_size*y_size; i++ {

		if i%256 == 255 {
			fmt.Printf("%d/%d done, open: %d, speed: %d px per sec\n", i, x_size*y_size,
				len(unfilled), int64(i*int(time.Second))/int64(time.Now().Sub(start_time)))
			go Save(fmt.Sprintf("rbsmoke%08d.png", i), height, width)
		}

		var curr_pt int

		if len(unfilled) == 0 {
			curr_pt = start_pt
		} else {
			// Expensive!
			curr_pt_index := Select(colour_list[i], unfilled, width)
			curr_pt = unfilled[curr_pt_index]

			// Discard point
			unfilled[len(unfilled)-1], unfilled[curr_pt_index] = unfilled[curr_pt_index], unfilled[len(unfilled)-1]
			unfilled = unfilled[:len(unfilled)-1]
			delete(unfilled_map, curr_pt)
		}

		filled_map[curr_pt] = true

		img[curr_pt] = colour_list[i]

		for _, new_pt := range neighbour_list[curr_pt] {
			if !unfilled_map[new_pt] && !filled_map[new_pt] {
				unfilled = append(unfilled, new_pt)
				unfilled_map[new_pt] = true
			}
		}
	}

	Save(fmt.Sprintf("rbsmoke%08d.png", height*width), height, width)

	fmt.Println("Done!")

}
<|endoftext|>


<commit_before>// Package render is a middleware for Martini that provides easy JSON serialization and HTML template rendering.
//
//  package main
//
//  import (
//    "github.com/codegangsta/martini"
//    "github.com/codegangsta/martini-contrib/render"
//  )
//
//  func main() {
//    m := martini.Classic()
//    m.Use(render.Renderer("templates"))
//
//    m.Get("/html", func(r render.Render) {
//      r.HTML(200, "mytemplate", nil)
//    })
//
//    m.Get("/json", func(r render.Render) {
//      r.JSON(200, "hello world")
//    })
//
//    m.Run()
//  }
package render

import (
	"bytes"
	"encoding/json"
	"github.com/codegangsta/martini"
	"html/template"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
)

const (
	ContentType = "Content-Type"
	ContentJSON = "application/json"
	ContentHTML = "text/html"
)

// Render is a service that can be injected into a Martini handler. Render provides functions for easily writing JSON and
// HTML templates out to a http Response.
type Render interface {
	// JSON writes the given status and JSON serialized version of the given value to the http.ResponseWriter.
	JSON(status int, v interface{})
	// HTML renders a html template specified by the name and writes the result and given status to the http.ResponseWriter.
	HTML(status int, name string, v interface{})
	// Error is a convenience function that writes an http status to the http.ResponseWriter.
	Error(status int)
}

// Renderer is a Middleware that maps a render.Render service into the Martini handler chain. Renderer will compile templates
// globbed in the given dir. Templates must have the .tmpl extension to be compiled.
//
// If MARTINI_ENV is set to "" or "development" then templates will be recompiled on every request. For more performance, set the
// MARTINI_ENV environment variable to "production"
func Renderer(dir string) martini.Handler {
	t := compile(dir)
	return func(res http.ResponseWriter, c martini.Context) {
		// recompile for easy development
		if martini.Env == martini.Dev {
			t = compile(dir)
		}
		c.MapTo(&renderer{res, t}, (*Render)(nil))
	}
}

func compile(dir string) *template.Template {
	t := template.New(dir)

	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		r, err := filepath.Rel(dir, path)
		if err != nil {
			return err
		}

		ext := filepath.Ext(r)
		if ext == ".tmpl" {

			buf, err := ioutil.ReadFile(path)
			if err != nil {
				panic(err)
			}

			name := (r[0 : len(r)-len(ext)])
			tmpl := t.New(filepath.ToSlash(name))
			// Bomb out if parse fails. We don't want any silent server starts.
			template.Must(tmpl.Parse(string(buf)))
		}

		return nil
	})

	return t
}

type renderer struct {
	http.ResponseWriter
	t *template.Template
}

func (r *renderer) JSON(status int, v interface{}) {
	result, err := json.Marshal(v)
	if err != nil {
		http.Error(r, err.Error(), 500)
		return
	}

	// json rendered fine, write out the result
	r.Header().Set(ContentType, ContentJSON)
	r.WriteHeader(status)
	r.Write(result)
}

func (r *renderer) HTML(status int, name string, binding interface{}) {
	var buf bytes.Buffer
	if err := r.t.ExecuteTemplate(&buf, name, binding); err != nil {
		http.Error(r, err.Error(), 500)
		return
	}

	// template rendered fine, write out the result
	r.Header().Set(ContentType, ContentHTML)
	r.WriteHeader(status)
	r.Write(buf.Bytes())
}

func (r *renderer) Error(status int) {
	r.WriteHeader(status)
}
<commit_msg>-n [Migrated] Sketching out some ideas for yield implementation<commit_after>// Package render is a middleware for Martini that provides easy JSON serialization and HTML template rendering.
//
//  package main
//
//  import (
//    "github.com/codegangsta/martini"
//    "github.com/codegangsta/martini-contrib/render"
//  )
//
//  func main() {
//    m := martini.Classic()
//    m.Use(render.Renderer("templates"))
//
//    m.Get("/html", func(r render.Render) {
//      r.HTML(200, "mytemplate", nil)
//    })
//
//    m.Get("/json", func(r render.Render) {
//      r.JSON(200, "hello world")
//    })
//
//    m.Run()
//  }
package render

import (
	"bytes"
	"encoding/json"
	"github.com/codegangsta/martini"
	"html/template"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
)

const (
	ContentType = "Content-Type"
	ContentJSON = "application/json"
	ContentHTML = "text/html"
)

// Render is a service that can be injected into a Martini handler. Render provides functions for easily writing JSON and
// HTML templates out to a http Response.
type Render interface {
	// JSON writes the given status and JSON serialized version of the given value to the http.ResponseWriter.
	JSON(status int, v interface{})
	// HTML renders a html template specified by the name and writes the result and given status to the http.ResponseWriter.
	HTML(status int, name string, v interface{})
	// Error is a convenience function that writes an http status to the http.ResponseWriter.
	Error(status int)
}

// Renderer is a Middleware that maps a render.Render service into the Martini handler chain. Renderer will compile templates
// globbed in the given dir. Templates must have the .tmpl extension to be compiled.
//
// If MARTINI_ENV is set to "" or "development" then templates will be recompiled on every request. For more performance, set the
// MARTINI_ENV environment variable to "production"
func Renderer(dir string) martini.Handler {
	t := compile(dir)
	return func(res http.ResponseWriter, c martini.Context) {
		// recompile for easy development
		if martini.Env == martini.Dev {
			t = compile(dir)
		}
    tc, _ := t.Clone()
		c.MapTo(&renderer{res, tc}, (*Render)(nil))
	}
}

func compile(dir string) *template.Template {
	t := template.New(dir)

	filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		r, err := filepath.Rel(dir, path)
		if err != nil {
			return err
		}

		ext := filepath.Ext(r)
		if ext == ".tmpl" {

			buf, err := ioutil.ReadFile(path)
			if err != nil {
				panic(err)
			}

			name := (r[0 : len(r)-len(ext)])
			tmpl := t.New(filepath.ToSlash(name))

      fm := template.FuncMap {
        "yield" : func() string {
          return "nope"
        },
      }

			// Bomb out if parse fails. We don't want any silent server starts.
			template.Must(tmpl.Funcs(fm).Parse(string(buf)))
		}

		return nil
	})

	return t
}

type renderer struct {
	http.ResponseWriter
	t *template.Template
}

func (r *renderer) JSON(status int, v interface{}) {
	result, err := json.Marshal(v)
	if err != nil {
		http.Error(r, err.Error(), 500)
		return
	}

	// json rendered fine, write out the result
	r.Header().Set(ContentType, ContentJSON)
	r.WriteHeader(status)
	r.Write(result)
}

func (r *renderer) HTML(status int, name string, binding interface{}) {
  fm := template.FuncMap {
    "yield" : func() string {
      var buf bytes.Buffer
      if err := r.t.ExecuteTemplate(&buf, name, binding); err != nil {
        return "nope"
      }
      return buf.String()
    },
  }
  r.t.Funcs(fm)
	var buf bytes.Buffer
	if err := r.t.ExecuteTemplate(&buf, "layout", binding); err != nil {
		http.Error(r, err.Error(), 500)
		return
	}

	// template rendered fine, write out the result
	r.Header().Set(ContentType, ContentHTML)
	r.WriteHeader(status)
	r.Write(buf.Bytes())
}

func (r *renderer) Error(status int) {
	r.WriteHeader(status)
}
<|endoftext|>


<commit_before>package core

import (
	"fmt"
	"bytes"
	"github.com/fire/go-ogre3d"
	"github.com/jmckaskill/go-capnproto"
)

type RenderState struct {
	mouseControl bool
	headNode     ogre.SceneNode
	rotationVectorObj ogre.ManualObject
	rotationVectorNode ogre.SceneNode
}

func parseRenderState(rs *RenderState, srs *SharedRenderState, b *[]byte) {
	var buf bytes.Buffer
	r := bytes.NewReader(*b)
	s, err := capn.ReadFromPackedStream(r, &buf)
	if err != nil {
		fmt.Printf("Read error %v\n", err)
		return
	}
        state := ReadRootRenderStateMsg(s)
	if state.HeadTrigger() {
		if state.FreeSpin() == false {
			rs.mouseControl = false
			rs.rotationVectorNode.SetVisible(false)
		}
		if state.FreeSpin() {
			rs.mouseControl = true
			// Note: Uncomment to visualize the rotation vector
			rs.rotationVectorNode.SetVisible(true)
		}
		// Resume updating render state on next loop
		return
	}

	renderState := ReadRootEmittedRenderState(s)
	srs.gameTime = renderState.Time()
	srs.position.SetX(renderState.Position().X())
	srs.position.SetY(renderState.Position().Y())
	srs.orientation = ogre.CreateQuaternionFromValues(renderState.Orientation().W(), renderState.Orientation().X(), renderState.Orientation().Y(), renderState.Orientation().Z())
	srs.position.SetZ(0.0)
}

func renderInit(params *RenderThreadParams, rs *RenderState, srs *SharedRenderState) {
	fmt.Printf("Render Init:\n")
	rs.mouseControl = false

	mgr := ogre.GetResourceGroupManager()

	mgr.AddResourceLocation("media/models", "FileSystem", "General");
	mgr.AddResourceLocation("media/materials/scripts", "FileSystem", "General")
	mgr.AddResourceLocation("media/materials/textures", "FileSystem", "General")
	mgr.AddResourceLocation("media/materials/programs", "FileSystem", "General")

	mgr.InitialiseAllResourceGroups()

	scene := params.root.CreateSceneManager("ST_GENERIC", "SimpleStaticCheck")
	scene.SetAmbientLight(0.5, 0.5, 0.5)
	head := scene.CreateEntity("head", "ogre.mesh", "head_group")
	rootNode := scene.GetRootSceneNode()
	zero := ogre.CreateVector3()
	zero.Zero()
	rs.headNode = rootNode.CreateChildSceneNode("head_node", zero , ogre.CreateQuaternion())
	rs.headNode.AttachObject(ogre.GetEntityBase(head))
	light := scene.CreateLight("light")
	light.SetPosition(20.0, 80.0, 50.0)
	cam := scene.CreateCamera("cam")
	cam.SetPosition(0,0,90)
	cam.LookAt(0,0,-300)
	cam.SetNearClipDistance(5)

	viewport := params.ogreWindow.AddViewport(cam)
	viewport.SetBackgroundColour(0, 0, 0, 0)

	cam.SetAspectRatio(viewport.GetActualWidth(), viewport.GetActualHeight())

	rs.rotationVectorObj = scene.CreateManualObject("rotation_vector")
	rs.rotationVectorObj.SetDynamic(true)
	rs.rotationVectorObj.Begin("BaseWhiteNoLighting", ogre.OT_LINE_LIST, "head")
	rs.rotationVectorObj.Position(0.0, 0.0, 0.0)
	rs.rotationVectorObj.Position(0.0, 0.0, 0.0)
	rs.rotationVectorObj.Position(0.0, 0.0, 0.0)
	rs.rotationVectorObj.End()
	rot := scene.GetRootSceneNode()
	rs.rotationVectorNode = rot.CreateChildSceneNode("rotation_vector_node", zero, ogre.CreateQuaternion())
	rs.rotationVectorNode.AttachObject(ogre.GetManualObjectBase(rs.rotationVectorObj))
	rs.rotationVectorNode.SetVisible(false)
}

func interpolateAndRender(rsockets *RenderThreadSockets, rs *RenderState,
	ratio float32, previousRender *SharedRenderState, nextRender *SharedRenderState) {
	temp := previousRender.position.MultiplyScalar(1.0 - ratio)
	interpPosition := temp.AddVector3(nextRender.position.MultiplyScalar(ratio))
	rs.headNode.SetPosition(interpPosition.X(), interpPosition.Y(), interpPosition.Z())
	if rs.mouseControl {
		t := capn.NewBuffer(nil)
		inputMouse := NewRootState(t)
		inputMouse.SetMouse(true)
		buf := bytes.Buffer{}
		t.WriteToPacked(&buf)
		rsockets.inputPush.Send(buf.Bytes(), 0)
		fmt.Printf("Render mouse_state requested\n")

		b, err := rsockets.inputMouseSub.Recv(0)
		if err != nil {
			fmt.Printf("%s\n", err)
		}
		b = bytes.TrimPrefix(b, []byte("input.mouse:"))
		var bBuf bytes.Buffer
		bBuf.Read(b)
		r := bytes.NewReader(b)
		fmt.Printf("Bytestring START%sEND\n", bBuf.String())
		var rBuf bytes.Buffer
		s, err := capn.ReadFromPackedStream(r, &rBuf)
		if err != nil {
			fmt.Printf("Read error %v\n", err)
			return
		}
		fmt.Printf("Render mouse_state received\n")
		input := ReadRootInputMouse(s)
		orientation := ogre.CreateQuaternionFromValues(input.W(), input.X(), input.Y(), input.Z())
		// Use latest mouse data to orient the head.
		rs.headNode.SetOrientation(orientation)
		// Update the rotation axis of the head (smoothed over a few frames in the game thread)
		rs.rotationVectorObj.BeginUpdate(0)
		rs.rotationVectorObj.Position(interpPosition.X(), interpPosition.Y(), interpPosition.Z())
		temp := previousRender.smoothedAngular.MultiplyScalar(1.0 - ratio)
		interpSmoothedAngular := temp.AddVector3(nextRender.smoothedAngular.MultiplyScalar(ratio))
		rotationVectorEnd := interpPosition.AddVector3(interpSmoothedAngular.MultiplyScalar(40.0))
		rs.rotationVectorObj.Position(rotationVectorEnd.X(), rotationVectorEnd.Y(), rotationVectorEnd.Z())
		rs.rotationVectorObj.End()
	} else {
		rs.headNode.SetOrientation(ogre.QuaternionSlerp(ratio, previousRender.orientation, nextRender.orientation, false))
	}	}

<commit_msg>Use the correct string for the default scene manager.<commit_after>package core

import (
	"fmt"
	"bytes"
	"github.com/fire/go-ogre3d"
	"github.com/jmckaskill/go-capnproto"
)

type RenderState struct {
	mouseControl bool
	headNode     ogre.SceneNode
	rotationVectorObj ogre.ManualObject
	rotationVectorNode ogre.SceneNode
}

func parseRenderState(rs *RenderState, srs *SharedRenderState, b *[]byte) {
	var buf bytes.Buffer
	r := bytes.NewReader(*b)
	s, err := capn.ReadFromPackedStream(r, &buf)
	if err != nil {
		fmt.Printf("Read error %v\n", err)
		return
	}
        state := ReadRootRenderStateMsg(s)
	if state.HeadTrigger() {
		if state.FreeSpin() == false {
			rs.mouseControl = false
			rs.rotationVectorNode.SetVisible(false)
		}
		if state.FreeSpin() {
			rs.mouseControl = true
			// Note: Uncomment to visualize the rotation vector
			rs.rotationVectorNode.SetVisible(true)
		}
		// Resume updating render state on next loop
		return
	}

	renderState := ReadRootEmittedRenderState(s)
	srs.gameTime = renderState.Time()
	srs.position.SetX(renderState.Position().X())
	srs.position.SetY(renderState.Position().Y())
	srs.orientation = ogre.CreateQuaternionFromValues(renderState.Orientation().W(), renderState.Orientation().X(), renderState.Orientation().Y(), renderState.Orientation().Z())
	srs.position.SetZ(0.0)
}

func renderInit(params *RenderThreadParams, rs *RenderState, srs *SharedRenderState) {
	fmt.Printf("Render Init:\n")
	rs.mouseControl = false

	mgr := ogre.GetResourceGroupManager()

	mgr.AddResourceLocation("media/models", "FileSystem", "General");
	mgr.AddResourceLocation("media/materials/scripts", "FileSystem", "General")
	mgr.AddResourceLocation("media/materials/textures", "FileSystem", "General")
	mgr.AddResourceLocation("media/materials/programs", "FileSystem", "General")

	mgr.InitialiseAllResourceGroups()

	scene := params.root.CreateSceneManager("DefaultSceneManager", "SimpleStaticCheck")
	scene.SetAmbientLight(0.5, 0.5, 0.5)
	head := scene.CreateEntity("head", "ogre.mesh", "head_group")
	rootNode := scene.GetRootSceneNode()
	zero := ogre.CreateVector3()
	zero.Zero()
	rs.headNode = rootNode.CreateChildSceneNode("head_node", zero , ogre.CreateQuaternion())
	rs.headNode.AttachObject(ogre.GetEntityBase(head))
	light := scene.CreateLight("light")
	light.SetPosition(20.0, 80.0, 50.0)
	cam := scene.CreateCamera("cam")
	cam.SetPosition(0,0,90)
	cam.LookAt(0,0,-300)
	cam.SetNearClipDistance(5)

	viewport := params.ogreWindow.AddViewport(cam)
	viewport.SetBackgroundColour(0, 0, 0, 0)

	cam.SetAspectRatio(viewport.GetActualWidth(), viewport.GetActualHeight())

	rs.rotationVectorObj = scene.CreateManualObject("rotation_vector")
	rs.rotationVectorObj.SetDynamic(true)
	rs.rotationVectorObj.Begin("BaseWhiteNoLighting", ogre.OT_LINE_LIST, "head")
	rs.rotationVectorObj.Position(0.0, 0.0, 0.0)
	rs.rotationVectorObj.Position(0.0, 0.0, 0.0)
	rs.rotationVectorObj.Position(0.0, 0.0, 0.0)
	rs.rotationVectorObj.End()
	rot := scene.GetRootSceneNode()
	rs.rotationVectorNode = rot.CreateChildSceneNode("rotation_vector_node", zero, ogre.CreateQuaternion())
	rs.rotationVectorNode.AttachObject(ogre.GetManualObjectBase(rs.rotationVectorObj))
	rs.rotationVectorNode.SetVisible(false)
}

func interpolateAndRender(rsockets *RenderThreadSockets, rs *RenderState,
	ratio float32, previousRender *SharedRenderState, nextRender *SharedRenderState) {
	temp := previousRender.position.MultiplyScalar(1.0 - ratio)
	interpPosition := temp.AddVector3(nextRender.position.MultiplyScalar(ratio))
	rs.headNode.SetPosition(interpPosition.X(), interpPosition.Y(), interpPosition.Z())
	if rs.mouseControl {
		t := capn.NewBuffer(nil)
		inputMouse := NewRootState(t)
		inputMouse.SetMouse(true)
		buf := bytes.Buffer{}
		t.WriteToPacked(&buf)
		rsockets.inputPush.Send(buf.Bytes(), 0)
		fmt.Printf("Render mouse_state requested\n")

		b, err := rsockets.inputMouseSub.Recv(0)
		if err != nil {
			fmt.Printf("%s\n", err)
		}
		b = bytes.TrimPrefix(b, []byte("input.mouse:"))
		var bBuf bytes.Buffer
		bBuf.Read(b)
		r := bytes.NewReader(b)
		fmt.Printf("Bytestring START%sEND\n", bBuf.String())
		var rBuf bytes.Buffer
		s, err := capn.ReadFromPackedStream(r, &rBuf)
		if err != nil {
			fmt.Printf("Read error %v\n", err)
			return
		}
		fmt.Printf("Render mouse_state received\n")
		input := ReadRootInputMouse(s)
		orientation := ogre.CreateQuaternionFromValues(input.W(), input.X(), input.Y(), input.Z())
		// Use latest mouse data to orient the head.
		rs.headNode.SetOrientation(orientation)
		// Update the rotation axis of the head (smoothed over a few frames in the game thread)
		rs.rotationVectorObj.BeginUpdate(0)
		rs.rotationVectorObj.Position(interpPosition.X(), interpPosition.Y(), interpPosition.Z())
		temp := previousRender.smoothedAngular.MultiplyScalar(1.0 - ratio)
		interpSmoothedAngular := temp.AddVector3(nextRender.smoothedAngular.MultiplyScalar(ratio))
		rotationVectorEnd := interpPosition.AddVector3(interpSmoothedAngular.MultiplyScalar(40.0))
		rs.rotationVectorObj.Position(rotationVectorEnd.X(), rotationVectorEnd.Y(), rotationVectorEnd.Z())
		rs.rotationVectorObj.End()
	} else {
		rs.headNode.SetOrientation(ogre.QuaternionSlerp(ratio, previousRender.orientation, nextRender.orientation, false))
	}	}

<|endoftext|>


<commit_before>// Copyright ©2016 The mediarename 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 main

import (
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
	"unicode"
)

func usage() {
	fmt.Fprintf(os.Stderr, "usage: mediarename [options]\n")
	fmt.Fprintf(os.Stderr, "options:\n")
	flag.PrintDefaults()
	os.Exit(2)
}

func main() {
	log.SetPrefix("mediarename: ")
	log.SetFlags(0)
	var (
		dry    = flag.Bool("n", false, "Dry run")
		prefix = flag.String("p", "", "File name prefix")
		tz     = flag.String("tz", "UTC", "Time zone")
	)
	flag.Usage = usage
	flag.Parse()

	_, err := exec.LookPath("exiftool")
	if err != nil {
		log.Fatal("exiftool not found")
	}

	loc, err := time.LoadLocation(*tz)
	if err != nil {
		log.Fatal(err)
	}

	files, err := ioutil.ReadDir(".")
	if err != nil {
		log.Fatal(err)
	}

	for _, file := range files {
		if file.IsDir() {
			continue
		}

		src := file.Name()
		tags, err := ReadTags(src)
		if err != nil {
			log.Printf("error reading tags from %v (%v)\n", src, err)
			continue
		}
		if tags.FileName == "" {
			tags.FileName = src
		}

		dst, err := tags.ToFileName(loc)
		if err != nil {
			log.Printf("error creating destination file name for %s (%v)\n", src, err)
			continue
		}
		if *prefix != "" {
			dst = *prefix + "_" + dst
		}

		t, err := tags.TimeIn(loc)
		if err != nil {
			log.Printf("error formatting time for %s (%v)\n", src, err)
			continue
		}

		if _, err = os.Stat(dst); err == nil {
			log.Printf("destination file %s exists, skipping.", dst)
			if !*dry {
				os.Chmod(dst, 0644)
				os.Chtimes(dst, t, t)
			}
			continue
		}
		if !*dry {
			os.Rename(src, dst)
			os.Chmod(dst, 0644)
			os.Chtimes(dst, t, t)
		}
		log.Printf("renamed %v to %v", src, dst)
	}
}

func ReadTags(filename string) (*ExifTags, error) {
	out, err := exec.Command("exiftool", "-j", filename).Output()
	if err != nil {
		return nil, errors.New("exiftool error")
	}

	var tags []ExifTags
	err = json.Unmarshal(out, &tags)
	if err != nil {
		return nil, err
	}

	return &tags[0], nil
}

type ExifTags struct {
	DateTimeOriginal string
	CreateDate       string
	MediaCreateDate  string

	FileName   string
	FileNumber string
	Model      string
}

func (tags *ExifTags) TimeIn(loc *time.Location) (time.Time, error) {
	date := tags.DateTimeOriginal
	if date == "" {
		date = tags.CreateDate
	}
	if date == "" {
		date = tags.MediaCreateDate
	}
	if date == "" {
		return time.Time{}, errors.New("no date tag found")
	}

	t, err := time.ParseInLocation("2006:01:02 15:04:05", date, loc)
	if err != nil {
		return time.Time{}, err
	}
	return t, nil
}

func (tags *ExifTags) ToFileName(loc *time.Location) (string, error) {
	t, err := tags.TimeIn(loc)
	if err != nil {
		return "", err
	}

	fields := []string{t.Format(time.RFC3339)}

	if tags.Model != "" {
		fields = append(fields, tags.Model)
	}

	ext := strings.ToLower(filepath.Ext(tags.FileName))
	filenum := tags.FileNumber
	if filenum == "" {
		// FileNumber tag doesn't exist, try to extract a number from
		// the file name.

		base := strings.TrimSuffix(tags.FileName, ext)
		// base without the longest sequence of digits on the right.
		basePrefix := strings.TrimRightFunc(base, func(r rune) bool {
			return unicode.IsDigit(r)
		})
		filenum = strings.TrimPrefix(base, basePrefix)
	}
	if filenum != "" {
		fields = append(fields, filenum)
	}

	filename := strings.Join(fields, "_")
	filename = strings.Replace(filename, ":", ".", -1) // Remove : from the file name because of Windows.
	filename = strings.Replace(filename, " ", "", -1)  // Remove spaces from the filename.
	return filename + ext, nil
}
<commit_msg>Use Information tag if Model tag is absent<commit_after>// Copyright ©2016 The mediarename 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 main

import (
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
	"unicode"
)

func usage() {
	fmt.Fprintf(os.Stderr, "usage: mediarename [options]\n")
	fmt.Fprintf(os.Stderr, "options:\n")
	flag.PrintDefaults()
	os.Exit(2)
}

func main() {
	log.SetPrefix("mediarename: ")
	log.SetFlags(0)
	var (
		dry    = flag.Bool("n", false, "Dry run")
		prefix = flag.String("p", "", "File name prefix")
		tz     = flag.String("tz", "UTC", "Time zone")
	)
	flag.Usage = usage
	flag.Parse()

	_, err := exec.LookPath("exiftool")
	if err != nil {
		log.Fatal("exiftool not found")
	}

	loc, err := time.LoadLocation(*tz)
	if err != nil {
		log.Fatal(err)
	}

	files, err := ioutil.ReadDir(".")
	if err != nil {
		log.Fatal(err)
	}

	for _, file := range files {
		if file.IsDir() {
			continue
		}

		src := file.Name()
		tags, err := ReadTags(src)
		if err != nil {
			log.Printf("error reading tags from %v (%v)\n", src, err)
			continue
		}
		if tags.FileName == "" {
			tags.FileName = src
		}

		dst, err := tags.ToFileName(loc)
		if err != nil {
			log.Printf("error creating destination file name for %s (%v)\n", src, err)
			continue
		}
		if *prefix != "" {
			dst = *prefix + "_" + dst
		}

		t, err := tags.TimeIn(loc)
		if err != nil {
			log.Printf("error formatting time for %s (%v)\n", src, err)
			continue
		}

		if _, err = os.Stat(dst); err == nil {
			log.Printf("destination file %s exists, skipping.", dst)
			if !*dry {
				os.Chmod(dst, 0644)
				os.Chtimes(dst, t, t)
			}
			continue
		}
		if !*dry {
			os.Rename(src, dst)
			os.Chmod(dst, 0644)
			os.Chtimes(dst, t, t)
		}
		log.Printf("renamed %v to %v", src, dst)
	}
}

func ReadTags(filename string) (*ExifTags, error) {
	out, err := exec.Command("exiftool", "-j", filename).Output()
	if err != nil {
		return nil, errors.New("exiftool error")
	}

	var tags []ExifTags
	err = json.Unmarshal(out, &tags)
	if err != nil {
		return nil, err
	}

	return &tags[0], nil
}

type ExifTags struct {
	DateTimeOriginal string
	CreateDate       string
	MediaCreateDate  string

	FileName   string
	FileNumber string

	Model       string
	Information string
}

func (tags *ExifTags) TimeIn(loc *time.Location) (time.Time, error) {
	date := tags.DateTimeOriginal
	if date == "" {
		date = tags.CreateDate
	}
	if date == "" {
		date = tags.MediaCreateDate
	}
	if date == "" {
		return time.Time{}, errors.New("no date tag found")
	}

	t, err := time.ParseInLocation("2006:01:02 15:04:05", date, loc)
	if err != nil {
		return time.Time{}, err
	}
	return t, nil
}

func (tags *ExifTags) ToFileName(loc *time.Location) (string, error) {
	t, err := tags.TimeIn(loc)
	if err != nil {
		return "", err
	}

	fields := []string{t.Format(time.RFC3339)}

	model := tags.Model
	if model == "" {
		// For example MOV files from Ricoh WG-M1 store the model in
		// Information.
		model = tags.Information
	}
	if model != "" {
		fields = append(fields, model)
	}

	ext := strings.ToLower(filepath.Ext(tags.FileName))
	filenum := tags.FileNumber
	if filenum == "" {
		// FileNumber tag doesn't exist, try to extract a number from
		// the file name.

		base := strings.TrimSuffix(tags.FileName, ext)
		// base without the longest sequence of digits on the right.
		basePrefix := strings.TrimRightFunc(base, func(r rune) bool {
			return unicode.IsDigit(r)
		})
		filenum = strings.TrimPrefix(base, basePrefix)
	}
	if filenum != "" {
		fields = append(fields, filenum)
	}

	filename := strings.Join(fields, "_")
	filename = strings.Replace(filename, ":", ".", -1)      // Remove : from the file name because of Windows.
	filename = strings.Replace(filename, " ", "", -1)       // Remove spaces from the filename.
	filename = strings.Replace(filename, string(0), "", -1) // Remove zero bytes.
	return filename + ext, nil
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 The Go Authors. All rights reserved.
// Copyright (c) 2013 memfs 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 memfs_test

import (
	"testing"

	"fmt"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"os/exec"
	"time"

	"github.com/ranveerkunal/memfs"
)

func setUp() string {
	name, err := ioutil.TempDir("/tmp", "memfs")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("temp dir: %s\n", name)
	return name
}

func createBigFile(name string) string {
	bigFile := name + "/big.txt"
	fmt.Printf("writing big file\n")
	cmd := exec.Command("dd", "if=/dev/urandom", "of=" + bigFile, "bs=1048576", "count=100")
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
	return bigFile
}

func startServer(fs http.FileSystem, prefix, addr string) {
	ln, err := net.Listen("tcp", addr)
	if err != nil {
		log.Fatal(err)
	}

	handler := http.NewServeMux()
	handler.Handle(prefix, http.StripPrefix(prefix, http.FileServer(fs)))

	err = http.Serve(ln, handler)
	if err != nil {
		log.Fatal(err)
	}
}

var (
	memFS  http.FileSystem
	diskFS http.FileSystem
	err    error
)

func init() {
	name := setUp()
	createBigFile(name)

	memFS, err = memfs.New(name)
	if err != nil {
		log.Fatal(err)
	}
	go startServer(memFS, "/memfs/", ":6666")

	diskFS = http.Dir(name)
	go startServer(diskFS, "/diskfs/", ":7777")

	time.Sleep(5 * time.Second)
	fmt.Printf("ready to benchmark ...\n")
}

func BenchmarkNonExistentMemFS(b *testing.B) {
	for i := 0; i < b.N; i++ {
		memFS.Open(fmt.Sprintf("./non_existent.%d", i))
	}
}

func BenchmarkNonExistentDiskFS(b *testing.B) {
	for i := 0; i < b.N; i++ {
		diskFS.Open(fmt.Sprintf("./non_existent.%d", i))
	}
}

func BenchmarkBigFileMemFS(b *testing.B) {
	for i := 0; i < b.N; i++ {
		res, err := http.Get("http://localhost:6666/memfs/big.txt")
		if err != nil {
			b.Fatal(err)
		}
		defer res.Body.Close()
		_, err = ioutil.ReadAll(res.Body)
		if err != nil {
			b.Fatal(err)
		}
	}
}

func BenchmarkBigFileDiskFS(b *testing.B) {
	for i := 0; i < b.N; i++ {
		res, err := http.Get("http://localhost:7777/diskfs/big.txt")
		if err != nil {
			b.Fatal(err)
		}
		defer res.Body.Close()
		_, err = ioutil.ReadAll(res.Body)
		if err != nil {
			b.Fatal(err)
		}
	}
}
<commit_msg>Adding benchmarks<commit_after><|endoftext|>


<commit_before>  package main

  import (

    "github.com/tpjg/goriakpbc"
    "fmt"
    "time"
    "strconv"
    "math/rand"
  )

  type MessageBag struct {
    visibleTime int64
    host string
    client *riak.Client
  }

  func main() {
    fmt.Println("In here yo")
    for i := 0; i < 0; i++ {
      go func() {
        messageBag := NewMessageBag()
        for j := 0; j < 1000000; j++ {
          _ = messageBag.Put("test_bucket", "Some simple message")
        }
      }()
    }
    for i := 0; i < 16; i++ {
      go func() {
        fmt.Println("In here yo")
        for j := 0; j < 500; j++ {
          messageBag := NewMessageBag()
          fmt.Println("In here yoz")
          start := time.Now()
          messageBag.Get("test_bucket")
          elapsed := time.Since(start)
          fmt.Printf("Get took %s\n", elapsed)
        }
      }()
    }
    time.Sleep(100 * time.Second)
    fmt.Printf("Complete\n")
  }

  /* Begin Message Bag Def */

  func NewMessageBag() *MessageBag {
    client, host := NewClient()
    return &MessageBag{visibleTime: (1000000000 * 300), host: host, client: client}
  }

  func NewClient() (*riak.Client, string) {
    rand.Seed(time.Now().UnixNano())
    hosts := []string{"10.0.0.86:8087", "10.0.0.212:8087", "10.0.0.187:8087", "10.0.0.30:8087", "10.0.0.208:8087", "10.0.0.97:8087", "10.0.0.71:8087", "10.0.0.155:8087", "10.0.0.47:8087", "10.0.0.108:8087", "10.0.0.165:8087", "10.0.0.253:8087"}
    host := hosts[rand.Intn(12)]
    client := riak.NewClient(host)
    return client, host
  }

  /* Put message into bag */
  func (m *MessageBag) Put(bagName string, message string) string {
    //Grab our bucket
    client := riak.NewClient(m.host)
    err := client.Connect()
    if err == nil {
      bucket, err := client.NewBucket(bagName)
      if err == nil {
        //Retrieve a UUID
        rand.Seed(time.Now().UnixNano())
        randInt := rand.Intn(9999999999999999)
        fmt.Println("Random int ", randInt)
        uuid := strconv.Itoa(randInt)

        messageObj := bucket.NewObject(uuid)
        messageObj.Indexes["id_int"] = []string{uuid}
        messageObj.Data = []byte(message)
        messageObj.Store()
        return uuid
      } else {
        //Actually want to handle this in some other way
        return ""
      }
    } else {
      //Actually want to handle this in some other way
      return ""
    }
  }

  /* Delete messages from bag */
  func (m *MessageBag) Delete(bagName string, id string) string {
    client := riak.NewClient(m.host)
    err := client.Connect()
    if err == nil {
      bucket, err := client.NewBucket(bagName)
      if err == nil {
        bucket.Delete(id)
      }
    }
    return id
  }

  var riakPool chan *riak.Client
  func GetConn() *riak.Client {
    if riakPool == nil {
      riakPool = make(chan *riak.Client, 1000)
      for i := 0; i < 1000; i++ {
        client, _ := NewClient()
        PutConn(client)
      }
    }
    return <- riakPool
  }

  func PutConn(conn *riak.Client) {
    if riakPool == nil {
      riakPool = make(chan *riak.Client, 1000)
    }
    riakPool <- conn
  }

  func (m *MessageBag) GetMulti(bagName string, ids []string) []riak.RObject {
    var rObjects = make(chan riak.RObject, len(ids))
    var rKeys = make(chan string, len(ids))

    start := time.Now()

    for _, key := range ids {
      go func() {
        var riakKey string
        fmt.Println("Getting a conn")
        client := GetConn()
        fmt.Println("Got a con")
        bucket, _ := client.NewBucket(bagName)
        riakKey = <- rKeys
        rObject, _ := bucket.Get(riakKey)
        fmt.Println("Got a key: %v", rObject)
        rObjects <- *rObject
        fmt.Println("Returning client")
        PutConn(client)
      }()
      rKeys <- key
    }
    fmt.Println("Here at return vals")
    returnVals := make([]riak.RObject, len(ids))
    for i:= 0; i < len(ids); i++ {
      fmt.Println("Waiting on an objct")
      var obj = <- rObjects
      returnVals = append(returnVals, obj)
      fmt.Println("At %v with length %v", i, len(ids))
    }
    elapsed := time.Since(start)
    fmt.Printf("Get Multi Took %s\n", elapsed)
    return returnVals
  }

  func (m *MessageBag) Get(bagName string) []riak.RObject {
    messages := make([]riak.RObject, 200)
    client := m.client
    err := client.Connect()
    if err == nil {
      bucket, err := client.NewBucket(bagName)
      if err == nil {
        //now := time.Now()
        //t := now.UnixNano()
        rand.Seed(time.Now().UnixNano())
        baseDec := rand.Float64()
        highDec := baseDec + (1.0 / 512.0)
        if highDec > 1 {
          highDec = 1
        }
        base :=  baseDec * 9999999999999999
        max := highDec * 9999999999999999
        fmt.Println("Base: ", base)
        start := time.Now()
        messageIds, _, err := bucket.IndexQueryRangePage("id_int", strconv.FormatFloat(base, 'f', 0, 32), strconv.FormatFloat(max, 'f', 0, 32), 250, "")
        elapsed := time.Since(start)
        fmt.Printf("id_int query took %s\n", elapsed)
        length := len(messageIds)
        fmt.Println("Length ", length)
        if err == nil {
          messages = m.GetMulti(bagName, messageIds)
        } else {
          fmt.Printf("Error%v", err)
        }
      }
    }
    return messages
  }

  func (m *MessageBag) GetWithInflight(bagName string) []*riak.RObject {
    messages := make([]*riak.RObject, 200)
    client := m.client
    err := client.Connect()
    if err == nil {
      bucket, err := client.NewBucket(bagName)
      if err == nil {
        now := time.Now()
        t := now.UnixNano()
        //Retrieve the inflight IDs
        start := time.Now()
        messageInFlightIds, err := bucket.IndexQueryRange("inflight_int", strconv.FormatInt(t - m.visibleTime, 10), strconv.FormatInt(t, 10))
        elapsed := time.Since(start)
        fmt.Printf("inflight_int query took %s %v\n", elapsed, len(messageInFlightIds))
        //Retrieve inflight + 1 so you guarantee getting something (or nothing, if nothing is available)
        //message_ids  = bag.get_index( 'id_bin', '0'..'z', max_results: (message_inflight_ids.count()+1))
        rand.Seed(time.Now().UnixNano())
        baseDec := rand.Float64()
        highDec := baseDec + (1.0 / 512.0)
        if highDec > 1 {
          highDec = 1
        }
        base :=  baseDec * 9999999999999999
        max := highDec * 9999999999999999
        fmt.Println("Base: ", base)
        start = time.Now()
        messageIds, _, err := bucket.IndexQueryRangePage("id_int", strconv.FormatFloat(base, 'f', 0, 32), strconv.FormatFloat(max, 'f', 0, 32), 250, "")
        elapsed = time.Since(start)
        fmt.Printf("id_int query took %s\n", elapsed)
        length := len(messageIds)
        fmt.Println("Length ", length)
        messageSet := make(map[string]bool)
        targetIds := make([]string, 0, length)
        for i := 0; i < len(messageInFlightIds); i++ {
          messageSet[messageInFlightIds[i]] = true
        }

        for i := 0; i < len(messageIds); i++ {
          _, present := messageSet[messageIds[i]]
          if present == false {
            targetIds = append(targetIds, messageIds[i])
          }
        }
        if err == nil {
          //fmt.Printf("In flight IDs%v\n", messageInFlightIds)
          //fmt.Printf("Message Set IDs%v\n", messageSet)
          //fmt.Printf("Continuation %v\n", continuation)
          fmt.Printf("Target id length %v\n", len(targetIds))
          for _, messageId := range targetIds {
            go func(){
              message, _ := bucket.Get(messageId)
              message.Indexes["inflight_int"] = []string{strconv.FormatInt(t, 10)}
              message.Store()
              messages = append(messages, message)
            }()
          }
        } else {
          fmt.Printf("Error%v", err)
        }
      }
    }
    return messages
  }

  /* End Message Bag Def */<commit_msg>Update to the go test harness<commit_after>package main

import (

  "github.com/tpjg/goriakpbc"
  "fmt"
  "time"
  "strconv"
  "math/rand"
)

type MessageBag struct {
  visibleTime int64
  client *riak.Client
}

func main() {
  //Warm up the conn
  conn := GetConn()
  PutConn(conn)
  for i := 0; i < 0; i++ {
    go func() {
      messageBag := NewMessageBag()
      for j := 0; j < 1000000; j++ {
        _ = messageBag.Put("test_bucket", "Some simple message")
      }
    }()
  }
  for i := 0; i < 1; i++ {
    for j := 0; j < 10000; j++ {
      //go func() {
        messageBag := NewMessageBag()
        start := time.Now()
        fmt.Println("Starting get ", j)
        messageBag.Get("test_bucket")
        elapsed := time.Since(start)
        fmt.Printf("Get took %s for %v\n", elapsed, j)
      //}()
    }
  }
  time.Sleep(100 * time.Second)
  fmt.Printf("Complete\n")
}

/* Begin Message Bag Def */

func NewMessageBag() *MessageBag {
  return &MessageBag{visibleTime: (1000000000 * 60)}
}

func NewClient() (*riak.Client, string) {
  rand.Seed(time.Now().UnixNano())
  hosts := []string{"ec2-54-68-213-20.us-west-2.compute.amazonaws.com:8087", "ec2-54-68-12-138.us-west-2.compute.amazonaws.com:8087", "ec2-54-69-47-53.us-west-2.compute.amazonaws.com:8087", "ec2-54-69-46-124.us-west-2.compute.amazonaws.com:8087", "ec2-54-68-49-228.us-west-2.compute.amazonaws.com:8087", "ec2-54-68-118-225.us-west-2.compute.amazonaws.com:8087", "ec2-54-69-49-89.us-west-2.compute.amazonaws.com:8087", "ec2-54-69-49-183.us-west-2.compute.amazonaws.com:8087", "ec2-54-69-50-238.us-west-2.compute.amazonaws.com:8087", "ec2-54-69-29-87.us-west-2.compute.amazonaws.com:8087", "ec2-54-69-49-114.us-west-2.compute.amazonaws.com:8087", "ec2-54-68-187-187.us-west-2.compute.amazonaws.com:8087"}
  host := hosts[5]
  client := riak.NewClient(host)
  client.SetConnectTimeout(2 * time.Second)
  err := client.Connect()
  if err != nil {
    fmt.Println("Connect error")
    return NewClient()
  } else {
    return client, host
  }
}

/* Put message into bag */
func (m *MessageBag) Put(bagName string, message string) string {
  //Grab our bucket
  client := GetConn()
  defer PutConn(client)
  err := client.Connect()
  if err == nil {
    bucket, err := client.NewBucket(bagName)
    if err == nil {
      //Retrieve a UUID
      rand.Seed(time.Now().UnixNano())
      randInt := rand.Intn(9999999999999999)
      fmt.Println("Random int ", randInt)
      uuid := strconv.Itoa(randInt)

      messageObj := bucket.NewObject(uuid)
      messageObj.Indexes["id_int"] = []string{uuid}
      messageObj.Data = []byte(message)
      messageObj.Store()
      return uuid
    } else {
      //Actually want to handle this in some other way
      return ""
    }
  } else {
    //Actually want to handle this in some other way
    return ""
  }
}

/* Delete messages from bag */
func (m *MessageBag) Delete(bagName string, id string) string {
  client := GetConn()
  defer PutConn(client)
  err := client.Connect()
  if err == nil {
    bucket, err := client.NewBucket(bagName)
    if err == nil {
      bucket.Delete(id)
    }
  }
  return id
}

var riakPool chan *riak.Client
func GetConn() *riak.Client {
  if riakPool == nil {
    fmt.Println("Initializing client pool")
    riakPool = make(chan *riak.Client, 20)
    for i := 0; i < 20; i++ {
      fmt.Println("Initializing client pool ", i)
      client, _ := NewClient()
      client.Ping()
      PutConn(client)
    }
  }
  conn := <- riakPool
  return conn
}

func PutConn(conn *riak.Client) {
  if riakPool == nil {
    riakPool = make(chan *riak.Client, 20)
  }
  fmt.Printf("Conn backlog %v", len(riakPool))
  riakPool <- conn
}

func (m *MessageBag) GetMulti(bagName string, ids []string) []riak.RObject {
  var rObjects = make(chan riak.RObject, len(ids))
  var rKeys = make(chan string, len(ids))

  start := time.Now()
  fmt.Println("In get multi")
  for i:=0; i < len(ids); i++ {
    go func() {
      var riakKey string
      client := GetConn()
      defer PutConn(client)
      fmt.Println("Getting bucket")
      bucket, _ := client.NewBucket(bagName)
      riakKey = <- rKeys
      fmt.Println("Getting value")
      rObject, _ := bucket.Get(riakKey)
      fmt.Println("Returning value")
      rObjects <- *rObject
    }()
    rKeys <- ids[i]
  }
  returnVals := make([]riak.RObject, 0)
  for i:= 0; i < len(ids); i++ {
    var obj = <- rObjects
    returnVals = append(returnVals, obj)
    fmt.Printf("\nGet Completed %v of %v", i, len(ids) - 1)
  }
  elapsed := time.Since(start)
  fmt.Printf("Get Multi Took %s\n", elapsed)
  return returnVals
}

func (m *MessageBag) PutMulti(bagName string, riakObjects []riak.RObject) {
  var rObjectChan = make(chan riak.RObject, len(riakObjects))
  var completions = make(chan bool, len(riakObjects))
  start := time.Now()

  for i:=0; i < len(riakObjects); i++ {
    go func() {
      client := GetConn()
      defer PutConn(client)
      riakObject := <- rObjectChan
      fmt.Printf("Putting riak object %v\n", riakObject)
      riakObject.Store()
      completions <- true
    }()
    rObjectChan <- riakObjects[i]
  }

  for i:= 0; i < len(riakObjects); i++ {
    _ = <- completions
    fmt.Printf("\nPut Completed %v of %v\n", i, len(riakObjects) - 1)
  }
  elapsed := time.Since(start)
  fmt.Printf("\nPut Multi Took %s\n", elapsed)
}

func (m *MessageBag) Get(bagName string) []riak.RObject {
  var messages []riak.RObject
  var returnMessages []riak.RObject
  client := GetConn()
  defer PutConn(client)
  fmt.Println("Getting bucket")
  bucket, err := client.NewBucket(bagName)
  fmt.Println("Bucket retrieved")
  if err == nil {
    //now := time.Now()
    //t := now.UnixNano()
    rand.Seed(time.Now().UnixNano())
    baseDec := rand.Float64()
    highDec := baseDec + (1.0 / 512.0)
    if highDec > 1 {
      highDec = 1
    }
    base :=  baseDec * 9999999999999999
    max := highDec * 9999999999999999
    fmt.Printf("Base: %v & Max: %v\n", base, max)
    start := time.Now()
    fmt.Println("Retrieving messages")
    messageIds, _, err := bucket.IndexQueryRangePage("id_int", strconv.FormatFloat(base, 'f', 0, 32), strconv.FormatFloat(max, 'f', 0, 32), 250, "")
    fmt.Println("Message retrieved ", len(messageIds))
    elapsed := time.Since(start)
    fmt.Printf("id_int query took %s and returned %v messages \n", elapsed, len(messageIds))
    length := len(messageIds)
    fmt.Println("Length ", length)
    if err == nil {
      messages = m.GetMulti(bagName, messageIds)
      for _, message := range messages {
        t := time.Now().UnixNano()
        /* If the inflight time has passed */
        var idxTime int64
        idxTime = 0
        if len(message.Indexes["inflight_int"]) == 1 {
          idxTime, _ = strconv.ParseInt(message.Indexes["inflight_int"][0], 10, 64)
        } else {
          message.Indexes = make(map[string][]string)
        }
        if idxTime < t - m.visibleTime {
          message.Indexes["inflight_int"] = []string{strconv.FormatInt(t, 10)}
          message.Indexes["id_int"] = []string{message.Key}
          returnMessages = append(returnMessages, message)
        } else {
          // NOOP
        }
      }
      m.PutMulti(bagName, returnMessages)
    } else {
      fmt.Printf("Error%v", err)
    }
  }

  return returnMessages
}

func (m *MessageBag) GetWithInflight(bagName string) []*riak.RObject {
  messages := make([]*riak.RObject, 200)
  client := m.client
  err := client.Connect()
  if err == nil {
    bucket, err := client.NewBucket(bagName)
    if err == nil {
      now := time.Now()
      t := now.UnixNano()
      //Retrieve the inflight IDs
      start := time.Now()
      messageInFlightIds, err := bucket.IndexQueryRange("inflight_int", strconv.FormatInt(t - m.visibleTime, 10), strconv.FormatInt(t, 10))
      elapsed := time.Since(start)
      fmt.Printf("inflight_int query took %s %v\n", elapsed, len(messageInFlightIds))
      //Retrieve inflight + 1 so you guarantee getting something (or nothing, if nothing is available)
      //message_ids  = bag.get_index( 'id_bin', '0'..'z', max_results: (message_inflight_ids.count()+1))
      rand.Seed(time.Now().UnixNano())
      baseDec := rand.Float64()
      highDec := baseDec + (1.0 / 512.0)
      if highDec > 1 {
        highDec = 1
      }
      base :=  baseDec * 9999999999999999
      max := highDec * 9999999999999999
      fmt.Println("Base: ", base)
      start = time.Now()
      messageIds, _, err := bucket.IndexQueryRangePage("id_int", strconv.FormatFloat(base, 'f', 0, 32), strconv.FormatFloat(max, 'f', 0, 32), 1, "")
      elapsed = time.Since(start)
      fmt.Printf("id_int query took %s\n", elapsed)
      length := len(messageIds)
      fmt.Println("Length ", length)
      messageSet := make(map[string]bool)
      targetIds := make([]string, 0, length)
      for i := 0; i < len(messageInFlightIds); i++ {
        messageSet[messageInFlightIds[i]] = true
      }

      for i := 0; i < len(messageIds); i++ {
        _, present := messageSet[messageIds[i]]
        if present == false {
          targetIds = append(targetIds, messageIds[i])
        }
      }
      if err == nil {
        //fmt.Printf("In flight IDs%v\n", messageInFlightIds)
        //fmt.Printf("Message Set IDs%v\n", messageSet)
        //fmt.Printf("Continuation %v\n", continuation)
        fmt.Printf("Target id length %v\n", len(targetIds))
        for _, messageId := range targetIds {
          go func(){
            message, _ := bucket.Get(messageId)
            message.Indexes["inflight_int"] = []string{strconv.FormatInt(t, 10)}
            message.Store()
            messages = append(messages, message)
          }()
        }
      } else {
        fmt.Printf("Error%v", err)
      }
    }
  }
  return messages
}

/* End Message Bag Def */<|endoftext|>


<commit_before>/*
Package jsend implements JSend* specification.

You can wrap your http.ResponseWriter:

	jsend.Wrap(w)

Returning object also implements http.ResponseWriter. So you can pass it to your
http middlewares.

Success example:

	jsend.Wrap(w).
		Data(yourData).
		Send()

	// body:
	{
		"status": "success",
		"data": {
			"foo": "bar"
		}
	}

Status field in response body is derived from http status code. Status is "fail"
if code is 4XX, "error" if code is 5XX and "success" otherwise.

Fail:
	jsend.Wrap(w).
		Status(400).
		Data(yourData).
		Send()

	// body:
	{
		"status": "fail",
		"data": {
			"foo": "invalid"
		}
	}

Error:
	jsend.Wrap(w).
		Status(500).
		Message("we are closed").
		Send()

	// body:
	{
		"status": "error",
		"message": "we are closed"
	}

* See http://labs.omniti.com/labs/jsend for jsend spec.
*/
package jsend

import (
	"encoding/json"
	"errors"
	"net/http"
	"sync"
)

// JSend status codes
const (
	StatusSuccess = "success"
	StatusError   = "error"
	StatusFail    = "fail"
)

const (
	fieldMsg    = "message"
	fieldData   = "data"
	fieldStatus = "status"
)

// Wrap wraps given http.ResponseWriter and returns a response object which
// implements JResponseWriter interface.
//
// If given parameter already implements JResponseWriter "Wrap" returns it
// instead of wrapping it again.
func Wrap(w http.ResponseWriter) JResponseWriter {
	if w, ok := w.(JResponseWriter); ok {
		return w
	}

	if w.Header().Get("Content-Type") == "" {
		w.Header().Set("Content-Type", "application/json")
	}

	return &Response{rw: w, fields: make(map[string]interface{})}
}

// A JResponseWriter interface extends http.ResponseWriter of go standard library
// to add utility methods for JSend format.
type JResponseWriter interface {
	http.ResponseWriter

	Data(interface{}) JResponseWriter

	Message(string) JResponseWriter

	Status(int) JResponseWriter

	Field(string, interface{}) JResponseWriter

	Send() (int, error)
}

// Response wraps a http.ResponseWriter type and adds jsend methods. Returning
// type implements JResponseWriter which extends http.ResponseWriter.
//
// Response buffers given data and writes nothing until "Send" is called.
type Response struct {
	rw     http.ResponseWriter
	code   int
	sent   bool
	fields map[string]interface{}
	sync.Mutex
}

// Field method allows you to set custom response fields.
func (r *Response) Field(key string, value interface{}) JResponseWriter {
	r.fields[key] = value
	return r
}

// Data sets response's "data" field with given value.
func (r *Response) Data(data interface{}) JResponseWriter {
	return r.Field(fieldData, data)
}

// Message sets response's "message" field with given value.
func (r *Response) Message(msg string) JResponseWriter {
	return r.Field(fieldMsg, msg)
}

// Status sets http statusCode. It is a shorthand for "WriteHeader" method
// in order to keep method chaining.
func (r *Response) Status(code int) JResponseWriter {
	r.code = code
	return r
}

// Header calls Header method of wrapped http.ResponseWriter.
func (r *Response) Header() http.Header {
	return r.rw.Header()
}

// WriteHeader calls WriteHeader method of wrapped http.ResponseWriter.
func (r *Response) WriteHeader(code int) {
	r.code = code
	r.rw.WriteHeader(code)
}

// Write calls Write method of wrapped http.ResponseWriter.
func (r *Response) Write(data []byte) (int, error) {
	return r.rw.Write(data)
}

var errSentAlready = errors.New("jsend: sent already")

// Send encodes and writes buffered data to underlying http response object.
func (r *Response) Send() (int, error) {
	r.Lock()
	defer r.Unlock()

	if r.sent {
		return 0, errSentAlready
	}
	r.sent = true

	if r.code == 0 {
		r.code = 200
	}
	status := getStatus(r.code)

	r.WriteHeader(r.code)
	r.Field(fieldStatus, status)

	if _, hasMsg := r.fields[fieldMsg]; !hasMsg && status == StatusError {
		r.Message(http.StatusText(r.code))
	}

	if _, hasData := r.fields[fieldData]; !hasData && status != StatusError {
		r.Data([]byte(nil))
	}

	j, err := json.Marshal(r.fields)

	if err != nil {
		return 0, err
	}

	return r.Write(j)
}

func getStatus(code int) string {
	switch {
	case code >= 500:
		return StatusError
	case code >= 400 && code < 500:
		return StatusFail
	}

	return StatusSuccess
}
<commit_msg>Unexpose mutex in Response<commit_after>/*
Package jsend implements JSend* specification.

You can wrap your http.ResponseWriter:

	jsend.Wrap(w)

Returning object also implements http.ResponseWriter. So you can pass it to your
http middlewares.

Success example:

	jsend.Wrap(w).
		Data(yourData).
		Send()

	// body:
	{
		"status": "success",
		"data": {
			"foo": "bar"
		}
	}

Status field in response body is derived from http status code. Status is "fail"
if code is 4XX, "error" if code is 5XX and "success" otherwise.

Fail:
	jsend.Wrap(w).
		Status(400).
		Data(yourData).
		Send()

	// body:
	{
		"status": "fail",
		"data": {
			"foo": "invalid"
		}
	}

Error:
	jsend.Wrap(w).
		Status(500).
		Message("we are closed").
		Send()

	// body:
	{
		"status": "error",
		"message": "we are closed"
	}

* See http://labs.omniti.com/labs/jsend for jsend spec.
*/
package jsend

import (
	"encoding/json"
	"errors"
	"net/http"
	"sync"
)

// JSend status codes
const (
	StatusSuccess = "success"
	StatusError   = "error"
	StatusFail    = "fail"
)

const (
	fieldMsg    = "message"
	fieldData   = "data"
	fieldStatus = "status"
)

// Wrap wraps given http.ResponseWriter and returns a response object which
// implements JResponseWriter interface.
//
// If given parameter already implements JResponseWriter "Wrap" returns it
// instead of wrapping it again.
func Wrap(w http.ResponseWriter) JResponseWriter {
	if w, ok := w.(JResponseWriter); ok {
		return w
	}

	if w.Header().Get("Content-Type") == "" {
		w.Header().Set("Content-Type", "application/json")
	}

	return &Response{rw: w, fields: make(map[string]interface{})}
}

// A JResponseWriter interface extends http.ResponseWriter of go standard library
// to add utility methods for JSend format.
type JResponseWriter interface {
	http.ResponseWriter

	Data(interface{}) JResponseWriter

	Message(string) JResponseWriter

	Status(int) JResponseWriter

	Field(string, interface{}) JResponseWriter

	Send() (int, error)
}

// Response wraps a http.ResponseWriter type and adds jsend methods. Returning
// type implements JResponseWriter which extends http.ResponseWriter.
//
// Response buffers given data and writes nothing until "Send" is called.
type Response struct {
	rw     http.ResponseWriter
	code   int
	sent   bool
	fields map[string]interface{}
	mu     sync.Mutex
}

// Field method allows you to set custom response fields.
func (r *Response) Field(key string, value interface{}) JResponseWriter {
	r.fields[key] = value
	return r
}

// Data sets response's "data" field with given value.
func (r *Response) Data(data interface{}) JResponseWriter {
	return r.Field(fieldData, data)
}

// Message sets response's "message" field with given value.
func (r *Response) Message(msg string) JResponseWriter {
	return r.Field(fieldMsg, msg)
}

// Status sets http statusCode. It is a shorthand for "WriteHeader" method
// in order to keep method chaining.
func (r *Response) Status(code int) JResponseWriter {
	r.code = code
	return r
}

// Header calls Header method of wrapped http.ResponseWriter.
func (r *Response) Header() http.Header {
	return r.rw.Header()
}

// WriteHeader calls WriteHeader method of wrapped http.ResponseWriter.
func (r *Response) WriteHeader(code int) {
	r.code = code
	r.rw.WriteHeader(code)
}

// Write calls Write method of wrapped http.ResponseWriter.
func (r *Response) Write(data []byte) (int, error) {
	return r.rw.Write(data)
}

var errSentAlready = errors.New("jsend: sent already")

// Send encodes and writes buffered data to underlying http response object.
func (r *Response) Send() (int, error) {
	r.mu.Lock()
	defer r.mu.Unlock()

	if r.sent {
		return 0, errSentAlready
	}
	r.sent = true

	if r.code == 0 {
		r.code = 200
	}
	status := getStatus(r.code)

	r.WriteHeader(r.code)
	r.Field(fieldStatus, status)

	if _, hasMsg := r.fields[fieldMsg]; !hasMsg && status == StatusError {
		r.Message(http.StatusText(r.code))
	}

	if _, hasData := r.fields[fieldData]; !hasData && status != StatusError {
		r.Data([]byte(nil))
	}

	j, err := json.Marshal(r.fields)

	if err != nil {
		return 0, err
	}

	return r.Write(j)
}

func getStatus(code int) string {
	switch {
	case code >= 500:
		return StatusError
	case code >= 400 && code < 500:
		return StatusFail
	}

	return StatusSuccess
}
<|endoftext|>


<commit_before>// Copyright 2015 Davis Webb
// Copyright 2015 Guntas Grewal
// Copyright 2015 Luke Shumaker

package store

import (
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
	he "httpentity"
	"httpentity/util"
	"io"
	"strings"
)

var _ he.Entity = &User{}
var _ he.NetEntity = &User{}
var dirUsers he.Entity = newDirUsers()

// Model /////////////////////////////////////////////////////////////

type User struct {
	Id        string
	FullName  string
	PwHash    []byte
	Addresses []UserAddress
}

func (o User) schema(db *gorm.DB) {
	db.CreateTable(&o)
}

type UserAddress struct {
	Id      int64
	UserId  string
	Medium  string
	Address string
}

func (o UserAddress) schema(db *gorm.DB) {
	table := db.CreateTable(&o)
	table.AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
	table.AddForeignKey("medium", "media(id)", "RESTRICT", "RESTRICT")
	table.AddUniqueIndex("uniqueness_idx", "medium", "address")
}

func GetUserById(db *gorm.DB, id string) *User {
	id = strings.ToLower(id)
	var o User
	if result := db.First(&o, "id = ?", id); result.Error != nil {
		if result.RecordNotFound() {
			return nil
		}
		panic(result.Error)
	}
	return &o
}

func GetUserByAddress(db *gorm.DB, medium string, address string) *User {
	var o User
	result := db.Joins("inner join user_addresses on user_addresses.user_id=users.id").Where("user_addresses.medium=? and user_addresses.address=?", medium, address).Find(&o)
	if result.Error != nil {
		if result.RecordNotFound() {
			return nil
		}
		panic(result.Error)
	}
	return &o
}

func (u *User) SetPassword(password string) error {
	hash, err := bcrypt.GenerateFromPassword([]byte(password), -1)
	u.PwHash = hash
	return err
}

func (u *User) CheckPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword(u.PwHash, []byte(password))
	return err == nil
}

func NewUser(db *gorm.DB, name string, password string, email string) *User {
	o := User{
		Id:        name,
		FullName:  "",
		Addresses: []UserAddress{{Medium: "email", Address: email}},
	}
	if err := o.SetPassword(password); err != nil {
		panic(err)
	}
	if err := db.Create(&o).Error; err != nil {
		panic(err)
	}
	return &o
}

func (o *User) Save(db *gorm.DB) {
	if err := db.Save(o).Error; err != nil {
		panic(err)
	}
}

func (o *User) Subentity(name string, req he.Request) he.Entity {
	return nil
}

func (o *User) Methods() map[string]func(he.Request) he.Response {
	return map[string]func(he.Request) he.Response{
		"GET": func(req he.Request) he.Response {
			return req.StatusOK(o)
		},
		"PUT": func(req he.Request) he.Response {
			panic("TODO: API: (*User).Methods()[\"PUT\"]")
		},
		"PATCH": func(req he.Request) he.Response {
			panic("TODO: API: (*User).Methods()[\"PATCH\"]")
		},
		"DELETE": func(req he.Request) he.Response {
			panic("TODO: API: (*User).Methods()[\"DELETE\"]")
		},
	}
}

// View //////////////////////////////////////////////////////////////

func (o *User) Encoders() map[string]func(io.Writer) error {
	return defaultEncoders(o)
}

// Directory ("Controller") //////////////////////////////////////////

type t_dirUsers struct {
	methods map[string]func(he.Request) he.Response
}

func newDirUsers() t_dirUsers {
	r := t_dirUsers{}
	r.methods = map[string]func(he.Request) he.Response{
		"POST": func(req he.Request) he.Response {
			db := req.Things["db"].(*gorm.DB)
			badbody := req.StatusBadRequest(heutil.NetString("submitted body not what expected"))
			hash, ok := req.Entity.(map[string]interface{}); if !ok { return badbody }
			username, ok := hash["username"].(string)      ; if !ok { return badbody }
			email   , ok := hash["email"].(string)         ; if !ok { return badbody }
			password, ok := hash["password"].(string)      ; if !ok { return badbody }

			if password2, ok := hash["password_verification"].(string); ok {
				if password != password2 {
					// Passwords don't match
					return req.StatusConflict(heutil.NetString("password and password_verification don't match"))
				}
			}

			username = strings.ToLower(username)

			user := NewUser(db, username, password, email)
			if user == nil {
				return req.StatusConflict(heutil.NetString("either that username or password is already taken"))
			} else {
				return req.StatusCreated(r, username)
			}
		},
	}
	return r
}

func (d t_dirUsers) Methods() map[string]func(he.Request) he.Response {
	return d.methods
}

func (d t_dirUsers) Subentity(name string, req he.Request) he.Entity {
	sess := req.Things["session"].(*Session)
	if sess == nil || sess.UserId != name {
		return nil
	}
	db := req.Things["db"].(*gorm.DB)
	return GetUserById(db, name)
}
<commit_msg>fixed user sign up<commit_after>// Copyright 2015 Davis Webb
// Copyright 2015 Guntas Grewal
// Copyright 2015 Luke Shumaker

package store

import (
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
	he "httpentity"
	"httpentity/util"
	"io"
	"strings"
)

var _ he.Entity = &User{}
var _ he.NetEntity = &User{}
var dirUsers he.Entity = newDirUsers()

// Model /////////////////////////////////////////////////////////////

type User struct {
	Id        string
	FullName  string
	PwHash    []byte
	Addresses []UserAddress
}

func (o User) schema(db *gorm.DB) {
	db.CreateTable(&o)
}

type UserAddress struct {
	Id      int64
	UserId  string
	Medium  string
	Address string
}

func (o UserAddress) schema(db *gorm.DB) {
	table := db.CreateTable(&o)
	table.AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
	table.AddForeignKey("medium", "media(id)", "RESTRICT", "RESTRICT")
	table.AddUniqueIndex("uniqueness_idx", "medium", "address")
}

func GetUserById(db *gorm.DB, id string) *User {
	id = strings.ToLower(id)
	var o User
	if result := db.First(&o, "id = ?", id); result.Error != nil {
		if result.RecordNotFound() {
			return nil
		}
		panic(result.Error)
	}
	return &o
}

func GetUserByAddress(db *gorm.DB, medium string, address string) *User {
	var o User
	result := db.Joins("inner join user_addresses on user_addresses.user_id=users.id").Where("user_addresses.medium=? and user_addresses.address=?", medium, address).Find(&o)
	if result.Error != nil {
		if result.RecordNotFound() {
			return nil
		}
		panic(result.Error)
	}
	return &o
}

func (u *User) SetPassword(password string) error {
	hash, err := bcrypt.GenerateFromPassword([]byte(password), -1)
	u.PwHash = hash
	return err
}

func (u *User) CheckPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword(u.PwHash, []byte(password))
	return err == nil
}

func NewUser(db *gorm.DB, name string, password string, email string) *User {
	o := User{
		Id:        name,
		FullName:  "",
		Addresses: []UserAddress{{Medium: "email", Address: email}},
	}
	if err := o.SetPassword(password); err != nil {
		panic(err)
	}
	if err := db.Create(&o).Error; err != nil {
		panic(err)
	}
	return &o
}

func (o *User) Save(db *gorm.DB) {
	if err := db.Save(o).Error; err != nil {
		panic(err)
	}
}

func (o *User) Subentity(name string, req he.Request) he.Entity {
	return nil
}

func (o *User) Methods() map[string]func(he.Request) he.Response {
	return map[string]func(he.Request) he.Response{
		"GET": func(req he.Request) he.Response {
			return req.StatusOK(o)
		},
		"PUT": func(req he.Request) he.Response {
			panic("TODO: API: (*User).Methods()[\"PUT\"]")
		},
		"PATCH": func(req he.Request) he.Response {
			panic("TODO: API: (*User).Methods()[\"PATCH\"]")
		},
		"DELETE": func(req he.Request) he.Response {
			panic("TODO: API: (*User).Methods()[\"DELETE\"]")
		},
	}
}

// View //////////////////////////////////////////////////////////////

func (o *User) Encoders() map[string]func(io.Writer) error {
	return defaultEncoders(o)
}

// Directory ("Controller") //////////////////////////////////////////

type t_dirUsers struct {
	methods map[string]func(he.Request) he.Response
}

func newDirUsers() t_dirUsers {
	r := t_dirUsers{}
	r.methods = map[string]func(he.Request) he.Response{
		"POST": func(req he.Request) he.Response {
			db := req.Things["db"].(*gorm.DB)
			badbody := req.StatusBadRequest(heutil.NetString("submitted body not what expected"))
			hash, ok := req.Entity.(map[string]interface{}); if !ok { return badbody }
			username, ok := hash["username"].(string)      ; if !ok { return badbody }
			email   , ok := hash["email"].(string)         ; if !ok { return badbody }
			password, ok := hash["password"].(string)      ; if !ok { return badbody }

			if password2, ok := hash["password_verification"].(string); ok {
				if password != password2 {
					// Passwords don't match
					return req.StatusConflict(heutil.NetString("password and password_verification don't match"))
				}
			}

			username = strings.ToLower(username)

			user := NewUser(db, username, password, email)
			if user == nil {
				return req.StatusConflict(heutil.NetString("either that username or password is already taken"))
			} else {
				return req.StatusCreated(r, username)
			}
		},
	}
	return r
}

func (d t_dirUsers) Methods() map[string]func(he.Request) he.Response {
	return d.methods
}

func (d t_dirUsers) Subentity(name string, req he.Request) he.Entity {
	sess := req.Things["session"].(*Session)
	if sess == nil {
		db := req.Things["db"].(*gorm.DB)
                hash, ok := req.Entity.(map[string]interface{}); if !ok { return nil }
		username, ok := hash["username"].(string)      ; if !ok { return nil }
                password, ok := hash["password"].(string)      ; if !ok { return nil }
                var user *User
		user = GetUserById(db, username)
		if !user.CheckPassword(password) {
			return nil
		} else {
			return user
		}
	} else if sess.UserId != name {
		return nil
	}
	db := req.Things["db"].(*gorm.DB)
	return GetUserById(db, name)
}
<|endoftext|>


<commit_before>package junos

import (
	"encoding/xml"
	"errors"
	"fmt"
	"github.com/Juniper/go-netconf/netconf"
	"log"
)

// Session holds the connection information to our Junos device.
type Session struct {
	Conn *netconf.Session
}

// RollbackXML parses our configuration after requesting it via rollback.
type RollbackXML struct {
	XMLName xml.Name `xml:"rollback-information"`
	Config  string   `xml:"configuration-information>configuration-output"`
}

// NewSession establishes a new connection to a Junos device that we will use
// to run our commands against.
func NewSession(host, user, password string) *Session {
	s, err := netconf.DialSSH(host, netconf.SSHConfigPassword(user, password))
	if err != nil {
		log.Fatal(err)
	}

	return &Session{
		Conn: s,
	}
}

// Lock locks the candidate configuration.
func (s *Session) Lock() {
	lockRPC := "<rpc><lock><target><candidate/></target></lock></rpc>"
	resp, _ := s.Conn.Exec(lockRPC)
	// if err != nil {
	// log.Fatal(err)
	// }

	if resp.Ok == false {
		for _, m := range resp.Errors {
			fmt.Printf("%s\n", m.Message)
		}
	}
}

// Unlock unlocks the candidate configuration.
func (s *Session) Unlock() {
	unlockRPC := "<rpc><unlock><target><candidate/></target></unlock></rpc>"
	resp, _ := s.Conn.Exec(unlockRPC)
	// if err != nil {
	// fmt.Printf("Error: %+v\n", err)
	// }

	if resp.Ok == false {
		for _, m := range resp.Errors {
			fmt.Printf("%s\n", m.Message)
		}
	}
}

// GetRollbackConfig returns the configuration of the given rollback state.
func (s *Session) GetRollbackConfig(number int) (string, error) {
	rb := &RollbackXML{}
	rpcCommand := fmt.Sprintf("<rpc><get-rollback-information><rollback>%d</rollback><format>text</format></get-rollback-information></rpc>", number)
	reply, err := s.Conn.Exec(rpcCommand)

    if err != nil {
        log.Fatal(err)
    }

	if reply.Ok == false {
		for _, m := range reply.Errors {
			return "", errors.New(m.Message)
		}
	}

	err = xml.Unmarshal([]byte(reply.Data), rb)
	if err != nil {
		log.Fatal(err)
	}

	return rb.Config, nil
}

// Close disconnects and closes the session to our Junos device.
func (s *Session) Close() {
	s.Conn.Close()
}
<commit_msg>Added more functions.<commit_after>package junos

import (
	"encoding/xml"
	"errors"
	"fmt"
	"github.com/Juniper/go-netconf/netconf"
	"log"
)

// Session holds the connection information to our Junos device.
type Session struct {
	Conn *netconf.Session
}

// RollbackXML parses our rollback configuration.
type RollbackXML struct {
	XMLName xml.Name `xml:"rollback-information"`
	Config  string   `xml:"configuration-information>configuration-output"`
}

// RescueXML parses our rescue configuration.
type RescueXML struct {
	XMLName xml.Name `xml:"rescue-information"`
	Config  string   `xml:"configuration-information>configuration-output"`
}

// NewSession establishes a new connection to a Junos device that we will use
// to run our commands against.
func NewSession(host, user, password string) *Session {
	s, err := netconf.DialSSH(host, netconf.SSHConfigPassword(user, password))
	if err != nil {
		log.Fatal(err)
	}

	return &Session{
		Conn: s,
	}
}

// Lock locks the candidate configuration.
func (s *Session) Lock() error {
	lockRPC := "<rpc><lock><target><candidate/></target></lock></rpc>"
	resp, err := s.Conn.Exec(lockRPC)
	if err != nil {
        log.Fatal(err)
	}

	if resp.Ok == false {
		for _, m := range resp.Errors {
			return errors.New(m.Message)
		}
	}

    return nil
}

// Unlock unlocks the candidate configuration.
func (s *Session) Unlock() error {
	unlockRPC := "<rpc><unlock><target><candidate/></target></unlock></rpc>"
	resp, err := s.Conn.Exec(unlockRPC)
	if err != nil {
        log.Fatal(err)
	}

	if resp.Ok == false {
		for _, m := range resp.Errors {
			return errors.New(m.Message)
		}
	}

    return nil
}

// GetRollbackConfig returns the configuration of the given rollback state.
func (s *Session) GetRollbackConfig(number int) (string, error) {
	rb := &RollbackXML{}
	rpcCommand := fmt.Sprintf("<rpc><get-rollback-information><rollback>%d</rollback><format>text</format></get-rollback-information></rpc>", number)
	reply, err := s.Conn.Exec(rpcCommand)

    if err != nil {
        log.Fatal(err)
    }

	if reply.Ok == false {
		for _, m := range reply.Errors {
			return "", errors.New(m.Message)
		}
	}

	err = xml.Unmarshal([]byte(reply.Data), rb)
	if err != nil {
		log.Fatal(err)
	}

	return rb.Config, nil
}

// RollbackDiff compares the current active configuration to a given rollback configuration.
func (s *Session) RollbackDiff(compare int) (string, error) {
	rb := &RollbackXML{}
	rpcCommand := fmt.Sprintf("<rpc><get-rollback-information><rollback>0</rollback><compare>%d</compare><format>text</format></get-rollback-information></rpc>", compare)
	reply, err := s.Conn.Exec(rpcCommand)

    if err != nil {
        log.Fatal(err)
    }

	if reply.Ok == false {
		for _, m := range reply.Errors {
			return "", errors.New(m.Message)
		}
	}

	err = xml.Unmarshal([]byte(reply.Data), rb)
	if err != nil {
		log.Fatal(err)
	}

	return rb.Config, nil
}

// GetRescueConfig returns the rescue configuration.
func (s *Session) GetRescueConfig() (string, error) {
	rescue := &RescueXML{}
	rpcCommand := fmt.Sprintf("<rpc><get-rescue-information><format>text</format></get-rescue-information></rpc>")
	reply, err := s.Conn.Exec(rpcCommand)

    if err != nil {
        log.Fatal(err)
    }

	if reply.Ok == false {
		for _, m := range reply.Errors {
			return "", errors.New(m.Message)
		}
	}

	err = xml.Unmarshal([]byte(reply.Data), rescue)
	if err != nil {
		log.Fatal(err)
	}

    if rescue.Config == "" {
        return "No rescue configuration set.", nil
    }

	return rescue.Config, nil
}

// Close disconnects and closes the session to our Junos device.
func (s *Session) Close() {
	s.Conn.Close()
}
<|endoftext|>


<commit_before>// Copyright 2011 The Go 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 ast

import (
	"bytes"
	"strings"
	"testing"
)

var tests = []struct {
	x interface{} // x is printed as s
	s string
}{
	// basic types
	{nil, "0  nil"},
	{true, "0  true"},
	{42, "0  42"},
	{3.14, "0  3.14"},
	{1 + 2.718i, "0  (1+2.718i)"},
	{"foobar", "0  \"foobar\""},

	// maps
	{map[string]int{"a": 1, "b": 2},
		`0  map[string] int (len = 2) {
		1  .  "a": 1
		2  .  "b": 2
		3  }`},

	// pointers
	{new(int), "0  *0"},

	// slices
	{[]int{1, 2, 3},
		`0  []int (len = 3) {
		1  .  0: 1
		2  .  1: 2
		3  .  2: 3
		4  }`},

	// structs
	{struct{ X, Y int }{42, 991},
		`0  struct { X int; Y int } {
		1  .  X: 42
		2  .  Y: 991
		3  }`},
}

// Split s into lines, trim whitespace from all lines, and return
// the concatenated non-empty lines.
func trim(s string) string {
	lines := strings.Split(s, "\n")
	i := 0
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line != "" {
			lines[i] = line
			i++
		}
	}
	return strings.Join(lines[0:i], "\n")
}

func TestPrint(t *testing.T) {
	var buf bytes.Buffer
	for _, test := range tests {
		buf.Reset()
		if _, err := Fprint(&buf, nil, test.x, nil); err != nil {
			t.Errorf("Fprint failed: %s", err)
		}
		if s, ts := trim(buf.String()), trim(test.s); s != ts {
			t.Errorf("got:\n%s\nexpected:\n%s\n", s, ts)
		}
	}
}
<commit_msg>go/ast: use single-element map in test<commit_after>// Copyright 2011 The Go 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 ast

import (
	"bytes"
	"strings"
	"testing"
)

var tests = []struct {
	x interface{} // x is printed as s
	s string
}{
	// basic types
	{nil, "0  nil"},
	{true, "0  true"},
	{42, "0  42"},
	{3.14, "0  3.14"},
	{1 + 2.718i, "0  (1+2.718i)"},
	{"foobar", "0  \"foobar\""},

	// maps
	{map[string]int{"a": 1},
		`0  map[string] int (len = 1) {
		1  .  "a": 1
		2  }`},

	// pointers
	{new(int), "0  *0"},

	// slices
	{[]int{1, 2, 3},
		`0  []int (len = 3) {
		1  .  0: 1
		2  .  1: 2
		3  .  2: 3
		4  }`},

	// structs
	{struct{ X, Y int }{42, 991},
		`0  struct { X int; Y int } {
		1  .  X: 42
		2  .  Y: 991
		3  }`},
}

// Split s into lines, trim whitespace from all lines, and return
// the concatenated non-empty lines.
func trim(s string) string {
	lines := strings.Split(s, "\n")
	i := 0
	for _, line := range lines {
		line = strings.TrimSpace(line)
		if line != "" {
			lines[i] = line
			i++
		}
	}
	return strings.Join(lines[0:i], "\n")
}

func TestPrint(t *testing.T) {
	var buf bytes.Buffer
	for _, test := range tests {
		buf.Reset()
		if _, err := Fprint(&buf, nil, test.x, nil); err != nil {
			t.Errorf("Fprint failed: %s", err)
		}
		if s, ts := trim(buf.String()), trim(test.s); s != ts {
			t.Errorf("got:\n%s\nexpected:\n%s\n", s, ts)
		}
	}
}
<|endoftext|>


<commit_before>// Copyright 2011 The Go 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 template (html/template) implements data-driven templates for
generating HTML output safe against code injection. It provides the
same interface as package text/template and should be used instead of
text/template whenever the output is HTML.

The documentation here focuses on the security features of the package.
For information about how to program the templates themselves, see the
documentation for text/template.

Introduction

This package wraps package text/template so you can share its template API
to parse and execute HTML templates safely.

  tmpl, err := template.New("name").Parse(...)
  // Error checking elided
  err = tmpl.Execute(out, "Foo", data)

If successful, tmpl will now be injection-safe. Otherwise, err is an error
defined in the docs for ErrorCode.

HTML templates treat data values as plain text which should be encoded so they
can be safely embedded in an HTML document. The escaping is contextual, so
actions can appear within JavaScript, CSS, and URI contexts.

The security model used by this package assumes that template authors are
trusted, while text/template Execute's data parameter is not. More details are
provided below.

Example

  import "text/template"
  ...
  t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
  err = t.ExecuteTemplate(out, "T", "")

produces

  Hello, !

but the contextual autoescaping in html/template

  import "html/template"
  ...
  t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
  err = t.ExecuteTemplate(out, "T", "")

produces safe, escaped HTML output

  Hello, <script>alert('you have been pwned')</script>!

Contexts

This package understands HTML, CSS, JavaScript, and URIs. It adds sanitizing
functions to each simple action pipeline, so given the excerpt

  {{.}}

At parse time each {{.}} is overwritten to add escaping functions as necessary.
In this case it becomes

  {{. | html}}

Errors

See the documentation of ErrorCode for details.

A fuller picture

The rest of this package comment may be skipped on first reading; it includes
details necessary to understand escaping contexts and error messages. Most users
will not need to understand these details.

Contexts

Assuming {{.}} is `O'Reilly: How are <i>you</i>?`, the table below shows
how {{.}} appears when used in the context to the left.

  Context                          {{.}} After
  {{.}}                            O'Reilly: How are <i>you</i>?
                  O'Reilly: How are you?
                  O'Reilly: How are %3ci%3eyou%3c/i%3e?
                O'Reilly%3a%20How%20are%3ci%3e...%3f
               O\x27Reilly: How are \x3ci\x3eyou...?
                 "O\x27Reilly: How are \x3ci\x3eyou...?"
       O\x27Reilly: How are \x3ci\x3eyou...\x3f

If used in an unsafe context, then the value might be filtered out:

  Context                          {{.}} After
                   #ZgotmplZ

since "O'Reilly:" is not an allowed protocol like "http:".

If {{.}} is the innocuous word, `left`, then it can appear more widely,

  Context                              {{.}} After
  {{.}}                                left
                      left
                       left
                      left
                  left
          left
               left
         left
    left
     left

Non-string values can be used in JavaScript contexts.
If {{.}} is

  []struct{A,B string}{ "foo", "bar" }

in the escaped template

then the template output is

See package json to understand how non-string content is marshalled for
embedding in JavaScript contexts.

Typed Strings

By default, this package assumes that all pipelines produce a plain text string.
It adds escaping pipeline stages necessary to correctly and safely embed that
plain text string in the appropriate context.

When a data value is not plain text, you can make sure it is not over-escaped
by marking it with its type.

Types HTML, JS, URL, and others from content.go can carry safe content that is
exempted from escaping.

The template

  Hello, {{.}}!

can be invoked with

  tmpl.Execute(out, HTML(`<b>World</b>`))

to produce

  Hello, World!

instead of the

  Hello, <b>World<b>!

that would have been produced if {{.}} was a regular string.

Security Model

http://js-quasis-libraries-and-repl.googlecode.com/svn/trunk/safetemplate.html#problem_definition defines "safe" as used by this package.

This package assumes that template authors are trusted, that Execute's data
parameter is not, and seeks to preserve the properties below in the face
of untrusted data:

Structure Preservation Property
"... when a template author writes an HTML tag in a safe templating language,
the browser will interpret the corresponding portion of the output as a tag
regardless of the values of untrusted data, and similarly for other structures
such as attribute boundaries and JS and CSS string boundaries."

Code Effect Property
"... only code specified by the template author should run as a result of
injecting the template output into a page and all code specified by the
template author should run as a result of the same."

Least Surprise Property
"A developer (or code reviewer) familiar with HTML, CSS, and JavaScript, who
knows that contextual autoescaping happens should be able to look at a {{.}}
and correctly infer what sanitization happens."
*/
package template
<commit_msg>html/template: minor tweak to docs to improve HTML typography.<commit_after>// Copyright 2011 The Go 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 template (html/template) implements data-driven templates for
generating HTML output safe against code injection. It provides the
same interface as package text/template and should be used instead of
text/template whenever the output is HTML.

The documentation here focuses on the security features of the package.
For information about how to program the templates themselves, see the
documentation for text/template.

Introduction

This package wraps package text/template so you can share its template API
to parse and execute HTML templates safely.

  tmpl, err := template.New("name").Parse(...)
  // Error checking elided
  err = tmpl.Execute(out, "Foo", data)

If successful, tmpl will now be injection-safe. Otherwise, err is an error
defined in the docs for ErrorCode.

HTML templates treat data values as plain text which should be encoded so they
can be safely embedded in an HTML document. The escaping is contextual, so
actions can appear within JavaScript, CSS, and URI contexts.

The security model used by this package assumes that template authors are
trusted, while text/template Execute's data parameter is not. More details are
provided below.

Example

  import "text/template"
  ...
  t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
  err = t.ExecuteTemplate(out, "T", "")

produces

  Hello, !

but the contextual autoescaping in html/template

  import "html/template"
  ...
  t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
  err = t.ExecuteTemplate(out, "T", "")

produces safe, escaped HTML output

  Hello, <script>alert('you have been pwned')</script>!

Contexts

This package understands HTML, CSS, JavaScript, and URIs. It adds sanitizing
functions to each simple action pipeline, so given the excerpt

  {{.}}

At parse time each {{.}} is overwritten to add escaping functions as necessary.
In this case it becomes

  {{. | html}}

Errors

See the documentation of ErrorCode for details.

A fuller picture

The rest of this package comment may be skipped on first reading; it includes
details necessary to understand escaping contexts and error messages. Most users
will not need to understand these details.

Contexts

Assuming {{.}} is `O'Reilly: How are <i>you</i>?`, the table below shows
how {{.}} appears when used in the context to the left.

  Context                          {{.}} After
  {{.}}                            O'Reilly: How are <i>you</i>?
                  O'Reilly: How are you?
                  O'Reilly: How are %3ci%3eyou%3c/i%3e?
                O'Reilly%3a%20How%20are%3ci%3e...%3f
               O\x27Reilly: How are \x3ci\x3eyou...?
                 "O\x27Reilly: How are \x3ci\x3eyou...?"
       O\x27Reilly: How are \x3ci\x3eyou...\x3f

If used in an unsafe context, then the value might be filtered out:

  Context                          {{.}} After
                   #ZgotmplZ

since "O'Reilly:" is not an allowed protocol like "http:".

If {{.}} is the innocuous word, `left`, then it can appear more widely,

  Context                              {{.}} After
  {{.}}                                left
                      left
                       left
                      left
                  left
          left
               left
         left
    left
     left

Non-string values can be used in JavaScript contexts.
If {{.}} is

  []struct{A,B string}{ "foo", "bar" }

in the escaped template

then the template output is

See package json to understand how non-string content is marshalled for
embedding in JavaScript contexts.

Typed Strings

By default, this package assumes that all pipelines produce a plain text string.
It adds escaping pipeline stages necessary to correctly and safely embed that
plain text string in the appropriate context.

When a data value is not plain text, you can make sure it is not over-escaped
by marking it with its type.

Types HTML, JS, URL, and others from content.go can carry safe content that is
exempted from escaping.

The template

  Hello, {{.}}!

can be invoked with

  tmpl.Execute(out, HTML(`<b>World</b>`))

to produce

  Hello, World!

instead of the

  Hello, <b>World<b>!

that would have been produced if {{.}} was a regular string.

Security Model

http://js-quasis-libraries-and-repl.googlecode.com/svn/trunk/safetemplate.html#problem_definition defines "safe" as used by this package.

This package assumes that template authors are trusted, that Execute's data
parameter is not, and seeks to preserve the properties below in the face
of untrusted data:

Structure Preservation Property:
"... when a template author writes an HTML tag in a safe templating language,
the browser will interpret the corresponding portion of the output as a tag
regardless of the values of untrusted data, and similarly for other structures
such as attribute boundaries and JS and CSS string boundaries."

Code Effect Property:
"... only code specified by the template author should run as a result of
injecting the template output into a page and all code specified by the
template author should run as a result of the same."

Least Surprise Property:
"A developer (or code reviewer) familiar with HTML, CSS, and JavaScript, who
knows that contextual autoescaping happens should be able to look at a {{.}}
and correctly infer what sanitization happens."
*/
package template
<|endoftext|>