<commit_before>package main

import (
	"encoding/json"
	"html/template"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/boltdb/bolt"
	"github.com/vaxx99/xload/xama"
	"github.com/vaxx99/xload/xbdb"
)

type Base struct{ A, B, C, D, E int }
type Frec struct {
	T  string
	A  int
	VA string
	B  int
	VB string
	C  int
	VC string
	D  int
	VD string
}

type Facs struct {
	DT string
	TM string
	AL Base
	Fc []Frec
}

type Srec struct {
	Rcn int
	Rdr string
	Rec xama.Block
	Old xama.Redrec
}

type Logrec struct {
	A string
	B string
	C int
	D string
	E xama.Redrec
}

func Slog(k string, recs *Logrec, db *bolt.DB) {

	e := db.Update(func(tx *bolt.Tx) error {

		bucket, e := tx.CreateBucketIfNotExists([]byte("logs"))
		if e != nil {
			return e
		}
		v, _ := json.Marshal(recs)
		e = bucket.Put([]byte(k), v)

		return nil
	})
	if e != nil {
		log.Fatal(e)
	}
}

func main() {
	go Finder()
	for {
		time.Sleep(time.Second * 5)
	}
}

func Finder() {
	log.Println("Start Finder...")
	http.HandleFunc("/", Stat)
	http.HandleFunc("/call", Call)
	http.HandleFunc("/logs", Logs)
	http.Handle("/xcss/", http.StripPrefix("/xcss/", http.FileServer(http.Dir("xcss"))))
	http.Handle("/xtmp/", http.StripPrefix("/xtmp/", http.FileServer(http.Dir("xtmp"))))
	e := http.ListenAndServe(":4444", nil)
	if e != nil {
		log.Fatal("ListenAndServe: ", e)
	}
}

func Stat(w http.ResponseWriter, req *http.Request) {
	bd := xbdb.Opendb("./db/system.db", 0600)
	defer bd.Close()
	rec := Face(bd)
	tx := template.New("stat")
	tx, _ = template.ParseFiles("./xtmp/stat.tmpl")
	tx.ExecuteTemplate(w, "stat", rec)
}

func Logs(w http.ResponseWriter, req *http.Request) {
	bd := xbdb.Opendb("./db/system.db", 0600)
	defer bd.Close()
	rec := Rlog(bd)
	tx := template.New("logs")
	tx, _ = template.ParseFiles("./xtmp/logs.tmpl")
	tx.ExecuteTemplate(w, "logs", rec)
}

func logtime() string {
	t := time.Now()
	b := t.UnixNano() % 1e6 / 1e3
	c := strconv.FormatInt(b, 10)
	return t.Format("20060102150405") + c
}

func Call(w http.ResponseWriter, r *http.Request) {
	e := r.ParseForm()
	if e != nil {
		return
	}
	t1 := time.Now()
	st := xama.Redrec{}
	rec := xama.Block{}
	Rc := 0
	Rt := "0.0"
	wt := xama.Redrec{Sw: r.FormValue("sw"), Hi: r.FormValue("hi"), Sc: r.FormValue("sc"), Na: r.FormValue("na"), Nb: r.FormValue("nb"),
		Ds: r.FormValue("ds"), De: r.FormValue("de"), Dr: r.FormValue("dr"), Ot: r.FormValue("ot"), It: r.FormValue("it"), Du: r.FormValue("du")}
	if wt != st {
		bd := xbdb.Opendb("./db/system.db", 0600)
		defer bd.Close()
		if fi, bn := xbdb.Bucket(wt, bd); fi {
			db := xbdb.Opendb("./db/"+bn[0:6]+".db", 0600)
			defer db.Close()
			rec = xbdb.Find(bn, wt, db)
			Rc = len(rec)
			Rt = strconv.FormatFloat(time.Now().Sub(t1).Seconds(), 'f', 1, 64)
		}
		Slog(logtime(), &Logrec{time.Now().Format("15:04:05"), r.RemoteAddr, Rc, Rt, wt}, bd)
	}
	if len(rec) > 5000 {
		rec = xama.Block{}
	}
	t := template.New("call")
	t, _ = template.ParseFiles("./xtmp/call.tmpl")
	t.ExecuteTemplate(w, "call", &Srec{Rcn: Rc, Rec: rec, Rdr: Rt, Old: wt})
}

func Face(db *bolt.DB) Facs {
	var s struct{ A, B, C, D int }
	var f Facs
	if e := db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("size"))
		dm := ""
		dt := ""
		mv := map[string]int{}
		iv := map[string]int{}
		if e := b.ForEach(func(k, v []byte) error {
			_ = json.Unmarshal(v, &s)
			dt = string(k)
			if dt[:6] == time.Now().Add(-24*time.Hour).Format("200601") {
				mv["nA"] = s.A
				mv["nB"] = s.B
				mv["nC"] = s.C
				mv["nD"] = s.D
				dm = dt[6:8] + "." + dt[4:6] + "." + dt[:4]
				f.Fc = append(f.Fc, Frec{dm, s.A, UpDn(mv["pA"], mv["nA"]),
					s.B, UpDn(mv["pB"], mv["nB"]),
					s.C, UpDn(mv["pC"], mv["nC"]),
					s.D, UpDn(mv["pD"], mv["nD"])})
				mv["pA"] = s.A
				mv["pB"] = s.B
				mv["pC"] = s.C
				mv["pD"] = s.D
				iv["A"] += s.A
				iv["B"] += s.B
				iv["C"] += s.C
				iv["D"] += s.D
			}
			return nil
		}); e != nil {
			return e
		}
		f.DT = dt[6:8] + "." + dt[4:6] + "." + dt[:4]
		f.TM = time.Now().Format("15:04:05")
		f.AL = Base{iv["A"] + iv["B"] + iv["C"] + iv["D"], iv["A"], iv["B"], iv["C"], iv["D"]}
		return nil
	}); e != nil {
		log.Fatal(e)
	}
	return f
}

func Rlog(db *bolt.DB) []Logrec {
	var lg Logrec
	var lgs []Logrec
	db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("logs"))
		b.ForEach(func(k, v []byte) error {
			if strings.Contains(string(k)[:8], time.Now().Format("20060102")) == true {
				e := json.Unmarshal(v, &lg)
				if e != nil {
					log.Printf("Json logs error: %s", e)
				}
				lgs = append(lgs, lg)
			}
			return nil
		})
		return nil
	})
	return lgs
}

func UpDn(vp, vn int) string {

	if vn > vp {
		return "up"
	} else {
		return "dn"
	}
}
<commit_msg>Update 10.04.2017 - Between<commit_after>package main

import (
	"encoding/json"
	"html/template"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/boltdb/bolt"
	"github.com/vaxx99/xload/xama"
	"github.com/vaxx99/xload/xbdb"
)

type Base struct{ A, B, C, D, E int }
type Frec struct {
	T  string
	A  int
	VA string
	B  int
	VB string
	C  int
	VC string
	D  int
	VD string
}

type Facs struct {
	DT string
	TM string
	AL Base
	Fc []Frec
}

type Srec struct {
	Rcn int
	Rdr string
	Rec xama.Block
	Old xama.Redrec
}

type Logrec struct {
	A string
	B string
	C int
	D string
	E xama.Redrec
}

func Slog(k string, recs *Logrec, db *bolt.DB) {

	e := db.Update(func(tx *bolt.Tx) error {

		bucket, e := tx.CreateBucketIfNotExists([]byte("logs"))
		if e != nil {
			return e
		}
		v, _ := json.Marshal(recs)
		e = bucket.Put([]byte(k), v)

		return nil
	})
	if e != nil {
		log.Fatal(e)
	}
}

func main() {
	go Finder()
	for {
		time.Sleep(time.Second * 5)
	}
}

func Finder() {
	log.Println("Start Finder...")
	http.HandleFunc("/", Stat)
	http.HandleFunc("/call", Call)
	http.HandleFunc("/logs", Logs)
	http.Handle("/xcss/", http.StripPrefix("/xcss/", http.FileServer(http.Dir("xcss"))))
	http.Handle("/xtmp/", http.StripPrefix("/xtmp/", http.FileServer(http.Dir("xtmp"))))
	e := http.ListenAndServe(":4444", nil)
	if e != nil {
		log.Fatal("ListenAndServe: ", e)
	}
}

func Stat(w http.ResponseWriter, req *http.Request) {
	bd := xbdb.Opendb("./db/system.db", 0600)
	defer bd.Close()
	rec := Face(bd)
	tx := template.New("stat")
	tx, _ = template.ParseFiles("./xtmp/stat.tmpl")
	tx.ExecuteTemplate(w, "stat", rec)
}

func Logs(w http.ResponseWriter, req *http.Request) {
	bd := xbdb.Opendb("./db/system.db", 0600)
	defer bd.Close()
	rec := Rlog(bd)
	tx := template.New("logs")
	tx, _ = template.ParseFiles("./xtmp/logs.tmpl")
	tx.ExecuteTemplate(w, "logs", rec)
}

func logtime() string {
	t := time.Now()
	b := t.UnixNano() % 1e6 / 1e3
	c := strconv.FormatInt(b, 10)
	return t.Format("20060102150405") + c
}

func Call(w http.ResponseWriter, r *http.Request) {
	e := r.ParseForm()
	if e != nil {
		return
	}
	t1 := time.Now()
	st := xama.Redrec{}
	rec := xama.Block{}
	Rc := 0
	Rt := "0.0"
	wt := xama.Redrec{Sw: r.FormValue("sw"), Hi: r.FormValue("hi"), Sc: r.FormValue("sc"), Na: r.FormValue("na"), Nb: r.FormValue("nb"),
		Ds: r.FormValue("ds"), De: r.FormValue("de"), Dr: r.FormValue("dr"), Ot: r.FormValue("ot"), It: r.FormValue("it"), Du: r.FormValue("du")}
	if wt != st {
		bd := xbdb.Opendb("./db/system.db", 0600)
		defer bd.Close()
		bw, bn := xbdb.Bucket(wt, bd)
		db := xbdb.Opendb("./db/"+bn[0][0:6]+".db", 0600)
		defer db.Close()
		for _, nb := range bn {
			wf := wt
			if bw {
				wf.Ds = ""
				wf.De = ""
			}
			rc := xbdb.Find(nb, wf, db)
			if len(rc) > 0 {
				for _, rcc := range rc {
					rec = append(rec, rcc)
				}
			}
			Rc = len(rec)
			Rt = strconv.FormatFloat(time.Now().Sub(t1).Seconds(), 'f', 1, 64)
		}
		Slog(logtime(), &Logrec{time.Now().Format("15:04:05"), r.RemoteAddr, Rc, Rt, wt}, bd)
	}
	if len(rec) > 5000 {
		rec = xama.Block{}
	}
	t := template.New("call")
	t, _ = template.ParseFiles("./xtmp/call.tmpl")
	t.ExecuteTemplate(w, "call", &Srec{Rcn: Rc, Rec: rec, Rdr: Rt, Old: wt})
}

func Face(db *bolt.DB) Facs {
	var s struct{ A, B, C, D int }
	var f Facs
	if e := db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("size"))
		dm := ""
		dt := ""
		mv := map[string]int{}
		iv := map[string]int{}
		if e := b.ForEach(func(k, v []byte) error {
			_ = json.Unmarshal(v, &s)
			dt = string(k)
			if dt[:6] == time.Now().Add(-24*time.Hour).Format("200601") {
				mv["nA"] = s.A
				mv["nB"] = s.B
				mv["nC"] = s.C
				mv["nD"] = s.D
				dm = dt[6:8] + "." + dt[4:6] + "." + dt[:4]
				f.Fc = append(f.Fc, Frec{dm, s.A, UpDn(mv["pA"], mv["nA"]),
					s.B, UpDn(mv["pB"], mv["nB"]),
					s.C, UpDn(mv["pC"], mv["nC"]),
					s.D, UpDn(mv["pD"], mv["nD"])})
				mv["pA"] = s.A
				mv["pB"] = s.B
				mv["pC"] = s.C
				mv["pD"] = s.D
				iv["A"] += s.A
				iv["B"] += s.B
				iv["C"] += s.C
				iv["D"] += s.D
			}
			return nil
		}); e != nil {
			return e
		}
		f.DT = dt[6:8] + "." + dt[4:6] + "." + dt[:4]
		f.TM = time.Now().Format("15:04:05")
		f.AL = Base{iv["A"] + iv["B"] + iv["C"] + iv["D"], iv["A"], iv["B"], iv["C"], iv["D"]}
		return nil
	}); e != nil {
		log.Fatal(e)
	}
	return f
}

func Rlog(db *bolt.DB) []Logrec {
	var lg Logrec
	var lgs []Logrec
	db.View(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("logs"))
		b.ForEach(func(k, v []byte) error {
			if strings.Contains(string(k)[:8], time.Now().Format("20060102")) == true {
				e := json.Unmarshal(v, &lg)
				if e != nil {
					log.Printf("Json logs error: %s", e)
				}
				lgs = append(lgs, lg)
			}
			return nil
		})
		return nil
	})
	return lgs
}

func UpDn(vp, vn int) string {

	if vn > vp {
		return "up"
	} else {
		return "dn"
	}
}
<|endoftext|>


<commit_before>package server

import (
	"strings"
	"testing"

	"github.com/pachyderm/pachyderm/src/client"
	"github.com/pachyderm/pachyderm/src/client/pkg/require"
)

func TestPutGet(t *testing.T) {
	c := getPachClient(t)
	object, err := c.PutObject(strings.NewReader("foo"))
	require.NoError(t, err)
	value, err := c.ReadObject(object.Hash)
	require.NoError(t, err)
	require.Equal(t, []byte("foo"), value)
	objectInfo, err := c.InspectObject(object.Hash)
	require.NoError(t, err)
	require.Equal(t, uint64(3), objectInfo.BlockRef.Range.Upper-objectInfo.BlockRef.Range.Lower)
}

func TestTags(t *testing.T) {
	c := getPachClient(t)
	object, err := c.PutObject(strings.NewReader("foo"), "bar", "fizz")
	require.NoError(t, err)
	require.NoError(t, c.TagObject(object.Hash, "buzz"))
	value, err := c.ReadTag("bar")
	require.NoError(t, err)
	require.Equal(t, []byte("foo"), value)
	value, err = c.ReadTag("fizz")
	require.NoError(t, err)
	require.Equal(t, []byte("foo"), value)
	value, err = c.ReadTag("buzz")
	require.NoError(t, err)
	require.Equal(t, []byte("foo"), value)
}

func TestManyObjects(t *testing.T) {
	c := getPachClient(t)
	var objects []string
	for i := 0; i < 25; i++ {
		object, err := c.PutObject(strings.NewReader(string(i)), string(i))
		require.NoError(t, err)
		objects = append(objects, object.Hash)
	}
	require.NoError(t, c.Compact())
	for i, hash := range objects {
		value, err := c.ReadObject(hash)
		require.NoError(t, err)
		require.Equal(t, []byte(string(i)), value)
		value, err = c.ReadTag(string(i))
		require.NoError(t, err)
		require.Equal(t, []byte(string(i)), value)
	}
}

func getPachClient(t testing.TB) *client.APIClient {
	client, err := client.NewFromAddress("0.0.0.0:30650")
	require.NoError(t, err)
	return client
}
<commit_msg>Adds a test that puts a large object.<commit_after>package server

import (
	"math/rand"
	"strings"
	"testing"
	"time"

	"github.com/pachyderm/pachyderm/src/client"
	"github.com/pachyderm/pachyderm/src/client/pkg/require"
	"github.com/pachyderm/pachyderm/src/server/pkg/workload"
)

func TestPutGet(t *testing.T) {
	c := getPachClient(t)
	object, err := c.PutObject(strings.NewReader("foo"))
	require.NoError(t, err)
	value, err := c.ReadObject(object.Hash)
	require.NoError(t, err)
	require.Equal(t, []byte("foo"), value)
	objectInfo, err := c.InspectObject(object.Hash)
	require.NoError(t, err)
	require.Equal(t, uint64(3), objectInfo.BlockRef.Range.Upper-objectInfo.BlockRef.Range.Lower)
}

func TestTags(t *testing.T) {
	c := getPachClient(t)
	object, err := c.PutObject(strings.NewReader("foo"), "bar", "fizz")
	require.NoError(t, err)
	require.NoError(t, c.TagObject(object.Hash, "buzz"))
	value, err := c.ReadTag("bar")
	require.NoError(t, err)
	require.Equal(t, []byte("foo"), value)
	value, err = c.ReadTag("fizz")
	require.NoError(t, err)
	require.Equal(t, []byte("foo"), value)
	value, err = c.ReadTag("buzz")
	require.NoError(t, err)
	require.Equal(t, []byte("foo"), value)
}

func TestManyObjects(t *testing.T) {
	c := getPachClient(t)
	var objects []string
	for i := 0; i < 25; i++ {
		object, err := c.PutObject(strings.NewReader(string(i)), string(i))
		require.NoError(t, err)
		objects = append(objects, object.Hash)
	}
	require.NoError(t, c.Compact())
	for i, hash := range objects {
		value, err := c.ReadObject(hash)
		require.NoError(t, err)
		require.Equal(t, []byte(string(i)), value)
		value, err = c.ReadTag(string(i))
		require.NoError(t, err)
		require.Equal(t, []byte(string(i)), value)
	}
}

func TestBigObject(t *testing.T) {
	c := getPachClient(t)
	r := workload.NewReader(rand.New(rand.NewSource(time.Now().UnixNano())), 50*1024*1024)
	object, err := c.PutObject(r)
	require.NoError(t, err)
	value, err := c.ReadObject(object.Hash)
	require.NoError(t, err)
	require.Equal(t, 50*1024*1024, len(value))
	value, err = c.ReadObject(object.Hash)
	require.NoError(t, err)
	require.Equal(t, 50*1024*1024, len(value))
}

func getPachClient(t testing.TB) *client.APIClient {
	client, err := client.NewFromAddress("0.0.0.0:30650")
	require.NoError(t, err)
	return client
}
<|endoftext|>


<commit_before>package gist7480523

import (
	"go/build"
	"strings"

	"github.com/shurcooL/go/exp/12"

	. "github.com/shurcooL/go/gists/gist5504644"
	. "github.com/shurcooL/go/gists/gist7519227"
	. "github.com/shurcooL/go/gists/gist7802150"
)

type GoPackageStringer func(*GoPackage) string

// A GoPackage describes a single package found in a directory.
// This is partially a copy of "cmd/go".Package, except it can be imported and reused. =.=
// https://code.google.com/p/go/source/browse/src/cmd/go/pkg.go?name=release#24
type GoPackage struct {
	Bpkg     *build.Package
	BpkgErr  error
	Standard bool // is this package part of the standard Go library?

	Dir *exp12.Directory
}

func GoPackageFromImportPathFound(importPathFound ImportPathFound) *GoPackage {
	bpkg, err := BuildPackageFromSrcDir(importPathFound.FullPath())
	return goPackageFromBuildPackage(bpkg, err)
}

func GoPackageFromImportPath(importPath string) *GoPackage {
	bpkg, err := BuildPackageFromImportPath(importPath)
	return goPackageFromBuildPackage(bpkg, err)
}

func goPackageFromBuildPackage(bpkg *build.Package, bpkgErr error) *GoPackage {
	if bpkgErr != nil {
		if _, noGo := bpkgErr.(*build.NoGoError); noGo || bpkg.Dir == "" {
			return nil
		}
	}

	if bpkg.ConflictDir != "" {
		return nil
	}

	goPackage := &GoPackage{
		Bpkg:     bpkg,
		BpkgErr:  bpkgErr,
		Standard: bpkg.Goroot && bpkg.ImportPath != "" && !strings.Contains(bpkg.ImportPath, "."), // https://code.google.com/p/go/source/browse/src/cmd/go/pkg.go?name=release#110

		Dir: exp12.LookupDirectory(bpkg.Dir),
	}

	/*if goPackage.Bpkg.Goroot == false { // Optimization that assume packages under Goroot are not under vcs
		// TODO: markAsNotNeedToUpdate() because of external insight?
	}*/

	return goPackage
}

// This is okay to call concurrently (a mutex is used internally).
// Actually, not completely okay because MakeUpdated technology is not thread-safe.
func (this *GoPackage) UpdateVcs() {
	if this.Bpkg.Goroot == false { // Optimization that assume packages under Goroot are not under vcs
		MakeUpdated(this.Dir)
	}
}

func (this *GoPackage) UpdateVcsFields() {
	if this.Dir.Repo != nil {
		MakeUpdated(this.Dir.Repo.VcsLocal)
		MakeUpdated(this.Dir.Repo.VcsRemote)
	}
}

func GetRepoImportPath(repoPath, srcRoot string) (repoImportPath string) {
	return strings.TrimPrefix(repoPath, srcRoot+"/")
}
func GetRepoImportPathPattern(repoPath, srcRoot string) (repoImportPathPattern string) {
	return GetRepoImportPath(repoPath, srcRoot) + "/..."
}

func (this *GoPackage) String() string {
	return this.Bpkg.ImportPath
}
<commit_msg>Add GoPackageRepo.<commit_after>package gist7480523

import (
	"go/build"
	"strings"

	"github.com/shurcooL/go/exp/12"

	. "github.com/shurcooL/go/gists/gist5504644"
	. "github.com/shurcooL/go/gists/gist7519227"
	. "github.com/shurcooL/go/gists/gist7802150"
)

type GoPackageStringer func(*GoPackage) string

// A GoPackage describes a single package found in a directory.
// This is partially a copy of "cmd/go".Package, except it can be imported and reused. =.=
// https://code.google.com/p/go/source/browse/src/cmd/go/pkg.go?name=release#24
type GoPackage struct {
	Bpkg     *build.Package
	BpkgErr  error
	Standard bool // is this package part of the standard Go library?

	Dir *exp12.Directory
}

func GoPackageFromImportPathFound(importPathFound ImportPathFound) *GoPackage {
	bpkg, err := BuildPackageFromSrcDir(importPathFound.FullPath())
	return goPackageFromBuildPackage(bpkg, err)
}

func GoPackageFromImportPath(importPath string) *GoPackage {
	bpkg, err := BuildPackageFromImportPath(importPath)
	return goPackageFromBuildPackage(bpkg, err)
}

func goPackageFromBuildPackage(bpkg *build.Package, bpkgErr error) *GoPackage {
	if bpkgErr != nil {
		if _, noGo := bpkgErr.(*build.NoGoError); noGo || bpkg.Dir == "" {
			return nil
		}
	}

	if bpkg.ConflictDir != "" {
		return nil
	}

	goPackage := &GoPackage{
		Bpkg:     bpkg,
		BpkgErr:  bpkgErr,
		Standard: bpkg.Goroot && bpkg.ImportPath != "" && !strings.Contains(bpkg.ImportPath, "."), // https://code.google.com/p/go/source/browse/src/cmd/go/pkg.go?name=release#110

		Dir: exp12.LookupDirectory(bpkg.Dir),
	}

	/*if goPackage.Bpkg.Goroot == false { // Optimization that assume packages under Goroot are not under vcs
		// TODO: markAsNotNeedToUpdate() because of external insight?
	}*/

	return goPackage
}

// This is okay to call concurrently (a mutex is used internally).
// Actually, not completely okay because MakeUpdated technology is not thread-safe.
func (this *GoPackage) UpdateVcs() {
	if this.Bpkg.Goroot == false { // Optimization that assume packages under Goroot are not under vcs
		MakeUpdated(this.Dir)
	}
}

func (this *GoPackage) UpdateVcsFields() {
	if this.Dir.Repo != nil {
		MakeUpdated(this.Dir.Repo.VcsLocal)
		MakeUpdated(this.Dir.Repo.VcsRemote)
	}
}

func GetRepoImportPath(repoPath, srcRoot string) (repoImportPath string) {
	return strings.TrimPrefix(repoPath, srcRoot+"/")
}
func GetRepoImportPathPattern(repoPath, srcRoot string) (repoImportPathPattern string) {
	return GetRepoImportPath(repoPath, srcRoot) + "/..."
}

func (this *GoPackage) String() string {
	return this.Bpkg.ImportPath
}

// =====

// GoPackageRepo represents a collection of Go packages contained by one VCS repository.
type GoPackageRepo struct {
	rootPath   string
	goPackages []*GoPackage
}

func NewGoPackageRepo(rootPath string, goPackages []*GoPackage) GoPackageRepo {
	return GoPackageRepo{rootPath, goPackages}
}

// ImportPathPattern returns an import path pattern that matches all of the Go packages in this repo.
// E.g.,
//
//	"github.com/owner/repo/..."
func (repo GoPackageRepo) ImportPathPattern() string {
	return GetRepoImportPathPattern(repo.rootPath, repo.goPackages[0].Bpkg.SrcRoot)
}

// RootPath returns the path to the root workdir folder of the repository.
func (repo GoPackageRepo) RootPath() string         { return repo.rootPath }
func (repo GoPackageRepo) GoPackages() []*GoPackage { return repo.goPackages }

// ImportPaths returns a newline separated list of all import paths.
func (repo GoPackageRepo) ImportPaths() string {
	var importPaths []string
	for _, goPackage := range repo.goPackages {
		importPaths = append(importPaths, goPackage.Bpkg.ImportPath)
	}
	return strings.Join(importPaths, "\n")
}
<|endoftext|>


<commit_before>package data

import (
	"time"

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

type Memeber struct {
	ID        bson.ObjectId `bson:"_id"`
	ProjectID bson.ObjectId `bson:"project_id"`
	AccountID bson.ObjectId `bson:"account_id"`
	InviterID bson.ObjectId `bson:"inviter_id"`
	InvitedAt time.Time     `bson:"invited_at"`

	ModifiedAt time.Time `bson:"modified_at"`
	CreatedAt  time.Time `bson:"created_at"`
}

func GetMember(id bson.ObjectId) (*Memeber, error) {
	mem := Memeber{}
	err := sess.DB("").C(memberC).FindId(id).One(&mem)
	if err == mgo.ErrNotFound {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return &mem, nil
}

func ListMembersProject(projectID bson.ObjectId, skip, limit int) ([]Memeber, error) {
	mems := []Memeber{}
	err := sess.DB("").C(memberC).
		Find(bson.M{"project_id": projectID}).
		Skip(skip).
		Limit(limit).
		Sort("-created_at").
		All(&mems)
	if err != nil {
		return nil, err
	}
	return mems, nil
}

func (m *Memeber) Account() (*Account, error) {
	return GetAccount(m.AccountID)
}

func (m *Memeber) Inviter() (*Account, error) {
	return GetAccount(m.InviterID)
}

func (m *Memeber) Put() error {
	m.ModifiedAt = time.Now()

	if m.ID == "" {
		m.ID = bson.NewObjectId()
		m.CreatedAt = m.ModifiedAt
	}
	_, err := sess.DB("").C(memberC).UpsertId(m.ID, m)
	return err
}
<commit_msg>Implement Project method in member<commit_after>package data

import (
	"time"

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

type Memeber struct {
	ID        bson.ObjectId `bson:"_id"`
	ProjectID bson.ObjectId `bson:"project_id"`
	AccountID bson.ObjectId `bson:"account_id"`
	InviterID bson.ObjectId `bson:"inviter_id"`
	InvitedAt time.Time     `bson:"invited_at"`

	ModifiedAt time.Time `bson:"modified_at"`
	CreatedAt  time.Time `bson:"created_at"`
}

func GetMember(id bson.ObjectId) (*Memeber, error) {
	mem := Memeber{}
	err := sess.DB("").C(memberC).FindId(id).One(&mem)
	if err == mgo.ErrNotFound {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return &mem, nil
}

func ListMembersProject(projectID bson.ObjectId, skip, limit int) ([]Memeber, error) {
	mems := []Memeber{}
	err := sess.DB("").C(memberC).
		Find(bson.M{"project_id": projectID}).
		Skip(skip).
		Limit(limit).
		Sort("-created_at").
		All(&mems)
	if err != nil {
		return nil, err
	}
	return mems, nil
}

func (m *Memeber) Account() (*Account, error) {
	return GetAccount(m.AccountID)
}

func (m *Memeber) Inviter() (*Account, error) {
	return GetAccount(m.InviterID)
}

func (m *Memeber) Project() (*Project, error) {
	return GetProject(m.ProjectID)
}

func (m *Memeber) Put() error {
	m.ModifiedAt = time.Now()

	if m.ID == "" {
		m.ID = bson.NewObjectId()
		m.CreatedAt = m.ModifiedAt
	}
	_, err := sess.DB("").C(memberC).UpsertId(m.ID, m)
	return err
}
<|endoftext|>


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

package oglemock_test

import (
	. "github.com/jacobsa/oglematchers"
	. "github.com/jacobsa/ogletest"
	"github.com/jacobsa/oglemock"
	"math"
	"reflect"
	"testing"
)

////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////

var someInt int = 17

type ReturnTest struct {
}

func init()                     { RegisterTestSuite(&ReturnTest{}) }
func TestOgletest(t *testing.T) { RunTests(t) }

type returnTestCase struct {
	suppliedVal interface{}
	expectedVal interface{}
	expectedCheckTypeResult bool
	expectedCheckTypeErrorSubstring string
}

func (t *ReturnTest) runTestCases(signature reflect.Type, cases []returnTestCase) {
	for i, c := range cases {
		a := oglemock.Return(c.suppliedVal)

		// CheckType
		err := a.CheckType(signature)
		if c.expectedCheckTypeResult {
			ExpectEq(nil, err, "Test case %d: %v", i, c)
		} else {
			ExpectThat(err, Error(HasSubstr(c.expectedCheckTypeErrorSubstring)),
				"Test case %d: %v", i, c)
			continue
		}

		// Invoke
		res := a.Invoke([]interface{}{})
		AssertThat(res, ElementsAre(Any()))
		ExpectThat(res[0], IdenticalTo(c.expectedVal), "Test case %d: %v", i, c)
	}
}

////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////

func (t *ReturnTest) NoReturnValues() {
	sig := reflect.TypeOf(func() {})
	var a oglemock.Action
	var err error
	var vals []interface{}

	// No values.
	a = oglemock.Return()
	err = a.CheckType(sig)
	AssertEq(nil, err)

	vals = a.Invoke([]interface{}{})
	ExpectThat(vals, ElementsAre())

	// One value.
	a = oglemock.Return(17)
	err = a.CheckType(sig)
	ExpectThat(err, Error(HasSubstr("given 1 val")))
	ExpectThat(err, Error(HasSubstr("expected 0")))

	// Two values.
	a = oglemock.Return(17, 19)
	err = a.CheckType(sig)
	ExpectThat(err, Error(HasSubstr("given 2 vals")))
	ExpectThat(err, Error(HasSubstr("expected 0")))
}

func (t *ReturnTest) MultipleReturnValues() {
	sig := reflect.TypeOf(func() (int, string) { return 0, "" })
	var a oglemock.Action
	var err error
	var vals []interface{}

	// No values.
	a = oglemock.Return()
	err = a.CheckType(sig)
	ExpectThat(err, Error(HasSubstr("given 0 vals")))
	ExpectThat(err, Error(HasSubstr("expected 2")))

	// One value.
	a = oglemock.Return(17)
	err = a.CheckType(sig)
	ExpectThat(err, Error(HasSubstr("given 1 val")))
	ExpectThat(err, Error(HasSubstr("expected 2")))

	// Two values.
	a = oglemock.Return(17, "taco")
	err = a.CheckType(sig)
	AssertEq(nil, err)

	vals = a.Invoke([]interface{}{})
	ExpectThat(vals, ElementsAre(IdenticalTo(int(17)), "taco"))
}

func (t *ReturnTest) Bool() {
	type namedType bool

	sig := reflect.TypeOf(func() bool { return false })
	cases := []returnTestCase{
		// Identical types.
		{ bool(true), bool(true), true, "" },
		{ bool(false), bool(false), true, "" },

		// Named version of same underlying type.
		{ namedType(true), bool(true), true, "" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int16(1), nil, false, "given int" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Int() {
	type namedType int

	sig := reflect.TypeOf(func() int { return 0 })
	cases := []returnTestCase{
		// Identical types.
		{ int(0), int(0), true, "" },
		{ int(math.MaxInt32), int(math.MaxInt32), true, "" },

		// Named version of same underlying type.
		{ namedType(17), int(17), true, "" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int16(1), nil, false, "given int16" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Int8() {
	type namedType int8

	sig := reflect.TypeOf(func() int8 { return 0 })
	cases := []returnTestCase{
		// Identical types.
		{ int8(0), int8(0), true, "" },
		{ int8(math.MaxInt8), int8(math.MaxInt8), true, "" },

		// Named version of same underlying type.
		{ namedType(17), int8(17), true, "" },

		// In-range ints.
		{ int(17), int8(17), true, "" },
		{ int(math.MaxInt8), int8(math.MaxInt8), true, "" },

		// Out of range ints.
		{ int(math.MaxInt8 + 1), nil, false, "out of range" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int16(1), nil, false, "given int16" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Int16() {
	type namedType int16

	sig := reflect.TypeOf(func() int16 { return 0 })
	cases := []returnTestCase{
		// Identical types.
		{ int16(0), int16(0), true, "" },
		{ int16(math.MaxInt16), int16(math.MaxInt16), true, "" },

		// Named version of same underlying type.
		{ namedType(17), int16(17), true, "" },

		// In-range ints.
		{ int(17), int16(17), true, "" },
		{ int(math.MaxInt16), int16(math.MaxInt16), true, "" },

		// Out of range ints.
		{ int(math.MaxInt16 + 1), nil, false, "out of range" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int8(1), nil, false, "given int8" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Int32() {
	type namedType int32

	sig := reflect.TypeOf(func() int32 { return 0 })
	cases := []returnTestCase{
		// Identical types.
		{ int32(0), int32(0), true, "" },
		{ int32(math.MaxInt32), int32(math.MaxInt32), true, "" },

		// Named version of same underlying type.
		{ namedType(17), int32(17), true, "" },

		// In-range ints.
		{ int(17), int32(17), true, "" },
		{ int(math.MaxInt32), int32(math.MaxInt32), true, "" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int16(1), nil, false, "given int16" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Rune() {
	type namedType rune

	sig := reflect.TypeOf(func() rune { return 0 })
	cases := []returnTestCase{
		// Identical types.
		{ rune(0), rune(0), true, "" },
		{ rune(math.MaxInt32), rune(math.MaxInt32), true, "" },

		// Named version of same underlying type.
		{ namedType(17), rune(17), true, "" },

		// Aliased version of type.
		{ int32(17), rune(17), true, "" },

		// In-range ints.
		{ int(17), rune(17), true, "" },
		{ int(math.MaxInt32), rune(math.MaxInt32), true, "" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int16(1), nil, false, "given int16" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Int64() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Uint() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Uint8() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Byte() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Uint16() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Uint32() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Uint64() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Uintptr() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Float32() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Float64() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Complex64() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Complex128() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) ArrayOfInt() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) ChanOfInt() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Func() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Interface() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) MapFromStringToInt() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) PointerToString() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) SliceOfInts() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) String() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Struct() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) UnsafePointer() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) NamedNumericType() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) NamedNonNumericType() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) NamedChannelType() {
	ExpectTrue(false, "TODO")
}
<commit_msg>ReturnTest.Int64<commit_after>// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package oglemock_test

import (
	. "github.com/jacobsa/oglematchers"
	. "github.com/jacobsa/ogletest"
	"github.com/jacobsa/oglemock"
	"math"
	"reflect"
	"testing"
)

////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////

var someInt int = 17

type ReturnTest struct {
}

func init()                     { RegisterTestSuite(&ReturnTest{}) }
func TestOgletest(t *testing.T) { RunTests(t) }

type returnTestCase struct {
	suppliedVal interface{}
	expectedVal interface{}
	expectedCheckTypeResult bool
	expectedCheckTypeErrorSubstring string
}

func (t *ReturnTest) runTestCases(signature reflect.Type, cases []returnTestCase) {
	for i, c := range cases {
		a := oglemock.Return(c.suppliedVal)

		// CheckType
		err := a.CheckType(signature)
		if c.expectedCheckTypeResult {
			ExpectEq(nil, err, "Test case %d: %v", i, c)
		} else {
			ExpectThat(err, Error(HasSubstr(c.expectedCheckTypeErrorSubstring)),
				"Test case %d: %v", i, c)
			continue
		}

		// Invoke
		res := a.Invoke([]interface{}{})
		AssertThat(res, ElementsAre(Any()))
		ExpectThat(res[0], IdenticalTo(c.expectedVal), "Test case %d: %v", i, c)
	}
}

////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////

func (t *ReturnTest) NoReturnValues() {
	sig := reflect.TypeOf(func() {})
	var a oglemock.Action
	var err error
	var vals []interface{}

	// No values.
	a = oglemock.Return()
	err = a.CheckType(sig)
	AssertEq(nil, err)

	vals = a.Invoke([]interface{}{})
	ExpectThat(vals, ElementsAre())

	// One value.
	a = oglemock.Return(17)
	err = a.CheckType(sig)
	ExpectThat(err, Error(HasSubstr("given 1 val")))
	ExpectThat(err, Error(HasSubstr("expected 0")))

	// Two values.
	a = oglemock.Return(17, 19)
	err = a.CheckType(sig)
	ExpectThat(err, Error(HasSubstr("given 2 vals")))
	ExpectThat(err, Error(HasSubstr("expected 0")))
}

func (t *ReturnTest) MultipleReturnValues() {
	sig := reflect.TypeOf(func() (int, string) { return 0, "" })
	var a oglemock.Action
	var err error
	var vals []interface{}

	// No values.
	a = oglemock.Return()
	err = a.CheckType(sig)
	ExpectThat(err, Error(HasSubstr("given 0 vals")))
	ExpectThat(err, Error(HasSubstr("expected 2")))

	// One value.
	a = oglemock.Return(17)
	err = a.CheckType(sig)
	ExpectThat(err, Error(HasSubstr("given 1 val")))
	ExpectThat(err, Error(HasSubstr("expected 2")))

	// Two values.
	a = oglemock.Return(17, "taco")
	err = a.CheckType(sig)
	AssertEq(nil, err)

	vals = a.Invoke([]interface{}{})
	ExpectThat(vals, ElementsAre(IdenticalTo(int(17)), "taco"))
}

func (t *ReturnTest) Bool() {
	type namedType bool

	sig := reflect.TypeOf(func() bool { return false })
	cases := []returnTestCase{
		// Identical types.
		{ bool(true), bool(true), true, "" },
		{ bool(false), bool(false), true, "" },

		// Named version of same underlying type.
		{ namedType(true), bool(true), true, "" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int16(1), nil, false, "given int" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Int() {
	type namedType int

	sig := reflect.TypeOf(func() int { return 0 })
	cases := []returnTestCase{
		// Identical types.
		{ int(0), int(0), true, "" },
		{ int(math.MaxInt32), int(math.MaxInt32), true, "" },

		// Named version of same underlying type.
		{ namedType(17), int(17), true, "" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int16(1), nil, false, "given int16" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Int8() {
	type namedType int8

	sig := reflect.TypeOf(func() int8 { return 0 })
	cases := []returnTestCase{
		// Identical types.
		{ int8(0), int8(0), true, "" },
		{ int8(math.MaxInt8), int8(math.MaxInt8), true, "" },

		// Named version of same underlying type.
		{ namedType(17), int8(17), true, "" },

		// In-range ints.
		{ int(17), int8(17), true, "" },
		{ int(math.MaxInt8), int8(math.MaxInt8), true, "" },

		// Out of range ints.
		{ int(math.MaxInt8 + 1), nil, false, "out of range" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int16(1), nil, false, "given int16" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Int16() {
	type namedType int16

	sig := reflect.TypeOf(func() int16 { return 0 })
	cases := []returnTestCase{
		// Identical types.
		{ int16(0), int16(0), true, "" },
		{ int16(math.MaxInt16), int16(math.MaxInt16), true, "" },

		// Named version of same underlying type.
		{ namedType(17), int16(17), true, "" },

		// In-range ints.
		{ int(17), int16(17), true, "" },
		{ int(math.MaxInt16), int16(math.MaxInt16), true, "" },

		// Out of range ints.
		{ int(math.MaxInt16 + 1), nil, false, "out of range" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int8(1), nil, false, "given int8" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Int32() {
	type namedType int32

	sig := reflect.TypeOf(func() int32 { return 0 })
	cases := []returnTestCase{
		// Identical types.
		{ int32(0), int32(0), true, "" },
		{ int32(math.MaxInt32), int32(math.MaxInt32), true, "" },

		// Named version of same underlying type.
		{ namedType(17), int32(17), true, "" },

		// In-range ints.
		{ int(17), int32(17), true, "" },
		{ int(math.MaxInt32), int32(math.MaxInt32), true, "" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int16(1), nil, false, "given int16" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Rune() {
	type namedType rune

	sig := reflect.TypeOf(func() rune { return 0 })
	cases := []returnTestCase{
		// Identical types.
		{ rune(0), rune(0), true, "" },
		{ rune(math.MaxInt32), rune(math.MaxInt32), true, "" },

		// Named version of same underlying type.
		{ namedType(17), rune(17), true, "" },

		// Aliased version of type.
		{ int32(17), rune(17), true, "" },

		// In-range ints.
		{ int(17), rune(17), true, "" },
		{ int(math.MaxInt32), rune(math.MaxInt32), true, "" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int16(1), nil, false, "given int16" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Int64() {
	type namedType int64

	sig := reflect.TypeOf(func() int64 { return 0 })
	cases := []returnTestCase{
		// Identical types.
		{ int64(0), int64(0), true, "" },
		{ int64(math.MaxInt64), int64(math.MaxInt64), true, "" },

		// Named version of same underlying type.
		{ namedType(17), int64(17), true, "" },

		// In-range ints.
		{ int(17), int64(17), true, "" },
		{ int(math.MaxInt32), int64(math.MaxInt32), true, "" },

		// Wrong types.
		{ nil, nil, false, "given <nil>" },
		{ int16(1), nil, false, "given int16" },
		{ float64(1), nil, false, "given float64" },
		{ complex128(1), nil, false, "given complex128" },
		{ &someInt, nil, false, "given *int" },
		{ make(chan int), nil, false, "given chan int" },
	}

	t.runTestCases(sig, cases)
}

func (t *ReturnTest) Uint() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Uint8() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Byte() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Uint16() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Uint32() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Uint64() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Uintptr() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Float32() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Float64() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Complex64() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Complex128() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) ArrayOfInt() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) ChanOfInt() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Func() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Interface() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) MapFromStringToInt() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) PointerToString() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) SliceOfInts() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) String() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) Struct() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) UnsafePointer() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) NamedNumericType() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) NamedNonNumericType() {
	ExpectTrue(false, "TODO")
}

func (t *ReturnTest) NamedChannelType() {
	ExpectTrue(false, "TODO")
}
<|endoftext|>


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

package reviewer

import (
	"errors"
	"strings"
	"net/http"

	"github.com/google/go-github/github"
	"github.com/spf13/viper"
	"golang.org/x/oauth2"
)

// GetString contains the function used to lookup environment variables.
var GetString = viper.GetString

// ForgeClient is an interface for forge clients.
type ForgeClient interface {}

// GHClient is the wrapper around github.Client.
type GHClient struct {
	Client *github.Client
}

// NewGHClient is the constructor for GHClient.
func NewGHClient(httpClient *http.Client) *GHClient {
	client := &GHClient{
		Client: github.NewClient(httpClient),
	}
	return client
}

// PullRequestInfo contains the id, title, and CR score of a pull request.
type PullRequestInfo struct {
	Number int // id of the pull request
	Title  string
	Score  int
}

// PullRequestInfoList contains a list of PullRequestInfos.
type PullRequestInfoList []PullRequestInfo

// GetClient returns a github.Client authenticated.
func GetClient() (*GHClient, error) {
	token := GetString("authorization.token")
	if token == "" {
		return nil, errors.New("An error occurred getting REVIEWER_TOKEN environment variable\n")
	}
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)

	return NewGHClient(tc), nil
}

// getCommentSuccesScore returns the score for the Comment.
func getCommentSuccessScore(comment string) int {
	score := 0
	if strings.Contains(comment, "+1") {
		score++
	}
	if strings.Contains(comment, "-1") {
		score--
	}
	return score
}

// GetPullRequestInfos returns the list of pull requests and the CR success score based on comments
func GetPullRequestInfos(client *GHClient, owner string, repo string) (*PullRequestInfoList, error) {
	//TODO: At this moment if there's a lot of PR, does not returns the full list, needs pagination.
	//      Also maybe we need to take care about how much requests are done in order to not exceed
	//      the quota.

	pullRequests, _, err := client.Client.PullRequests.List(owner, repo, nil)
	if err != nil {
		return nil, err
	}
	pris := make(PullRequestInfoList, len(pullRequests))
	for n, pullRequest := range pullRequests {
		pris[n].Number = *pullRequest.Number
		pris[n].Title = *pullRequest.Title
		comments, _, err := client.Client.Issues.ListComments(owner, repo, *pullRequest.Number, nil)
		if err != nil {
			return nil, err
		}
		for _, comment := range comments {
			if comment.Body == nil {
				continue
			}
			pris[n].Score += getCommentSuccessScore(*comment.Body)
		}
	}
	return &pris, nil
}
<commit_msg>Makes GHClient.Client private (GHCLient.client)<commit_after>// Copyright © 2016 See CONTRIBUTORS <ignasi.fosch@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package reviewer

import (
	"errors"
	"strings"
	"net/http"

	"github.com/google/go-github/github"
	"github.com/spf13/viper"
	"golang.org/x/oauth2"
)

// GetString contains the function used to lookup environment variables.
var GetString = viper.GetString

// ForgeClient is an interface for forge clients.
type ForgeClient interface {}

// GHClient is the wrapper around github.Client.
type GHClient struct {
	client *github.Client
}

// NewGHClient is the constructor for GHClient.
func NewGHClient(httpClient *http.Client) *GHClient {
	client := &GHClient{
		client: github.NewClient(httpClient),
	}
	return client
}

// PullRequestInfo contains the id, title, and CR score of a pull request.
type PullRequestInfo struct {
	Number int // id of the pull request
	Title  string
	Score  int
}

// PullRequestInfoList contains a list of PullRequestInfos.
type PullRequestInfoList []PullRequestInfo

// GetClient returns a github.Client authenticated.
func GetClient() (*GHClient, error) {
	token := GetString("authorization.token")
	if token == "" {
		return nil, errors.New("An error occurred getting REVIEWER_TOKEN environment variable\n")
	}
	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: token},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)

	return NewGHClient(tc), nil
}

// getCommentSuccesScore returns the score for the Comment.
func getCommentSuccessScore(comment string) int {
	score := 0
	if strings.Contains(comment, "+1") {
		score++
	}
	if strings.Contains(comment, "-1") {
		score--
	}
	return score
}

// GetPullRequestInfos returns the list of pull requests and the CR success score based on comments
func GetPullRequestInfos(client *GHClient, owner string, repo string) (*PullRequestInfoList, error) {
	//TODO: At this moment if there's a lot of PR, does not returns the full list, needs pagination.
	//      Also maybe we need to take care about how much requests are done in order to not exceed
	//      the quota.

	pullRequests, _, err := client.client.PullRequests.List(owner, repo, nil)
	if err != nil {
		return nil, err
	}
	pris := make(PullRequestInfoList, len(pullRequests))
	for n, pullRequest := range pullRequests {
		pris[n].Number = *pullRequest.Number
		pris[n].Title = *pullRequest.Title
		comments, _, err := client.client.Issues.ListComments(owner, repo, *pullRequest.Number, nil)
		if err != nil {
			return nil, err
		}
		for _, comment := range comments {
			if comment.Body == nil {
				continue
			}
			pris[n].Score += getCommentSuccessScore(*comment.Body)
		}
	}
	return &pris, nil
}
<|endoftext|>


<commit_before>// Copyright 2017 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 sym

import (
	"cmd/internal/objabi"
	"cmd/internal/sys"
	"debug/elf"
)

// Reloc is a relocation.
//
// The typical Reloc rewrites part of a symbol at offset Off to address Sym.
// A Reloc is stored in a slice on the Symbol it rewrites.
//
// Relocations are generated by the compiler as the type
// cmd/internal/obj.Reloc, which is encoded into the object file wire
// format and decoded by the linker into this type. A separate type is
// used to hold linker-specific state about the relocation.
//
// Some relocations are created by cmd/link.
type Reloc struct {
	Off     int32            // offset to rewrite
	Siz     uint8            // number of bytes to rewrite, 1, 2, or 4
	Done    bool             // set to true when relocation is complete
	Variant RelocVariant     // variation on Type
	Type    objabi.RelocType // the relocation type
	Add     int64            // addend
	Xadd    int64            // addend passed to external linker
	Sym     *Symbol          // symbol the relocation addresses
	Xsym    *Symbol          // symbol passed to external linker
}

// RelocVariant is a linker-internal variation on a relocation.
type RelocVariant uint8

const (
	RV_NONE RelocVariant = iota
	RV_POWER_LO
	RV_POWER_HI
	RV_POWER_HA
	RV_POWER_DS

	// RV_390_DBL is a s390x-specific relocation variant that indicates that
	// the value to be placed into the relocatable field should first be
	// divided by 2.
	RV_390_DBL

	RV_CHECK_OVERFLOW RelocVariant = 1 << 7
	RV_TYPE_MASK      RelocVariant = RV_CHECK_OVERFLOW - 1
)

func RelocName(arch *sys.Arch, r objabi.RelocType) string {
	// We didn't have some relocation types at Go1.4.
	// Uncomment code when we include those in bootstrap code.

	switch {
	case r >= 512: // Mach-O
		// nr := (r - 512)>>1
		// switch ctxt.Arch.Family {
		// case sys.AMD64:
		// 	return macho.RelocTypeX86_64(nr).String()
		// case sys.ARM:
		// 	return macho.RelocTypeARM(nr).String()
		// case sys.ARM64:
		// 	return macho.RelocTypeARM64(nr).String()
		// case sys.I386:
		// 	return macho.RelocTypeGeneric(nr).String()
		// default:
		// 	panic("unreachable")
		// }
	case r >= 256: // ELF
		nr := r - 256
		switch arch.Family {
		case sys.AMD64:
			return elf.R_X86_64(nr).String()
		case sys.ARM:
			return elf.R_ARM(nr).String()
		case sys.ARM64:
			return elf.R_AARCH64(nr).String()
		case sys.I386:
			return elf.R_386(nr).String()
		case sys.MIPS, sys.MIPS64:
			// return elf.R_MIPS(nr).String()
		case sys.PPC64:
			// return elf.R_PPC64(nr).String()
		case sys.S390X:
			// return elf.R_390(nr).String()
		default:
			panic("unreachable")
		}
	}

	return r.String()
}

// RelocByOff implements sort.Interface for sorting relocations by offset.
type RelocByOff []Reloc

func (x RelocByOff) Len() int { return len(x) }

func (x RelocByOff) Swap(i, j int) { x[i], x[j] = x[j], x[i] }

func (x RelocByOff) Less(i, j int) bool {
	a := &x[i]
	b := &x[j]
	if a.Off < b.Off {
		return true
	}
	if a.Off > b.Off {
		return false
	}
	return false
}
<commit_msg>cmd/link/internal/sym: uncomment code for ELF cases in RelocName<commit_after>// Copyright 2017 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 sym

import (
	"cmd/internal/objabi"
	"cmd/internal/sys"
	"debug/elf"
)

// Reloc is a relocation.
//
// The typical Reloc rewrites part of a symbol at offset Off to address Sym.
// A Reloc is stored in a slice on the Symbol it rewrites.
//
// Relocations are generated by the compiler as the type
// cmd/internal/obj.Reloc, which is encoded into the object file wire
// format and decoded by the linker into this type. A separate type is
// used to hold linker-specific state about the relocation.
//
// Some relocations are created by cmd/link.
type Reloc struct {
	Off     int32            // offset to rewrite
	Siz     uint8            // number of bytes to rewrite, 1, 2, or 4
	Done    bool             // set to true when relocation is complete
	Variant RelocVariant     // variation on Type
	Type    objabi.RelocType // the relocation type
	Add     int64            // addend
	Xadd    int64            // addend passed to external linker
	Sym     *Symbol          // symbol the relocation addresses
	Xsym    *Symbol          // symbol passed to external linker
}

// RelocVariant is a linker-internal variation on a relocation.
type RelocVariant uint8

const (
	RV_NONE RelocVariant = iota
	RV_POWER_LO
	RV_POWER_HI
	RV_POWER_HA
	RV_POWER_DS

	// RV_390_DBL is a s390x-specific relocation variant that indicates that
	// the value to be placed into the relocatable field should first be
	// divided by 2.
	RV_390_DBL

	RV_CHECK_OVERFLOW RelocVariant = 1 << 7
	RV_TYPE_MASK      RelocVariant = RV_CHECK_OVERFLOW - 1
)

func RelocName(arch *sys.Arch, r objabi.RelocType) string {
	// We didn't have some relocation types at Go1.4.
	// Uncomment code when we include those in bootstrap code.

	switch {
	case r >= 512: // Mach-O
		// nr := (r - 512)>>1
		// switch ctxt.Arch.Family {
		// case sys.AMD64:
		// 	return macho.RelocTypeX86_64(nr).String()
		// case sys.ARM:
		// 	return macho.RelocTypeARM(nr).String()
		// case sys.ARM64:
		// 	return macho.RelocTypeARM64(nr).String()
		// case sys.I386:
		// 	return macho.RelocTypeGeneric(nr).String()
		// default:
		// 	panic("unreachable")
		// }
	case r >= 256: // ELF
		nr := r - 256
		switch arch.Family {
		case sys.AMD64:
			return elf.R_X86_64(nr).String()
		case sys.ARM:
			return elf.R_ARM(nr).String()
		case sys.ARM64:
			return elf.R_AARCH64(nr).String()
		case sys.I386:
			return elf.R_386(nr).String()
		case sys.MIPS, sys.MIPS64:
			return elf.R_MIPS(nr).String()
		case sys.PPC64:
			return elf.R_PPC64(nr).String()
		case sys.S390X:
			return elf.R_390(nr).String()
		default:
			panic("unreachable")
		}
	}

	return r.String()
}

// RelocByOff implements sort.Interface for sorting relocations by offset.
type RelocByOff []Reloc

func (x RelocByOff) Len() int { return len(x) }

func (x RelocByOff) Swap(i, j int) { x[i], x[j] = x[j], x[i] }

func (x RelocByOff) Less(i, j int) bool {
	a := &x[i]
	b := &x[j]
	if a.Off < b.Off {
		return true
	}
	if a.Off > b.Off {
		return false
	}
	return false
}
<|endoftext|>


<commit_before>// Package server provides a sample HTTP/Websocket server which registers
// itself in consul using one or more url prefixes to demonstrate and
// test the automatic fabio routing table update.
//
// During startup the server performs the following steps:
//
// * Add a handler for each prefix which provides a unique
//   response for that instance and endpoint
// * Add a `/health` handler for the consul health check
// * Register the service in consul with the listen address,
//   a health check under the given name and with one `urlprefix-`
//   tag per prefix
// * Install a signal handler to deregister the service on exit
//
// If the protocol is set to "ws" the registered endpoints function
// as websocket echo servers.
//
// Example:
//
//   # http server
//   ./server -addr 127.0.0.1:5000 -name svc-a -prefix /foo,/bar
//   ./server -addr 127.0.0.1:5001 -name svc-b -prefix /baz,/bar
//
//   # websocket server
//   ./server -addr 127.0.0.1:6000 -name ws-a -prefix /echo1,/echo2 -proto ws
//
package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/eBay/fabio/_third_party/github.com/hashicorp/consul/api"
	"github.com/eBay/fabio/_third_party/golang.org/x/net/websocket"
)

func main() {
	var addr, consul, name, prefix, proto string
	flag.StringVar(&addr, "addr", "127.0.0.1:5000", "host:port of the service")
	flag.StringVar(&consul, "consul", "127.0.0.1:8500", "host:port of the consul agent")
	flag.StringVar(&name, "name", filepath.Base(os.Args[0]), "name of the service")
	flag.StringVar(&prefix, "prefix", "", "comma-sep list of host/path prefixes to register")
	flag.StringVar(&proto, "proto", "http", "protocol for endpoints: http or ws")
	flag.Parse()

	if prefix == "" {
		flag.Usage()
		os.Exit(1)
	}

	// register prefixes
	prefixes := strings.Split(prefix, ",")
	for _, p := range prefixes {
		switch proto {
		case "http":
			http.HandleFunc(p, func(w http.ResponseWriter, r *http.Request) {
				fmt.Fprintf(w, "Serving %s from %s on %s\n", r.RequestURI, name, addr)
			})
		case "ws":
			http.Handle(p, websocket.Handler(EchoServer))
		default:
			log.Fatal("Invalid protocol ", proto)
		}
	}

	// start http server
	go func() {
		log.Printf("Listening on %s serving %s", addr, prefix)
		if err := http.ListenAndServe(addr, nil); err != nil {
			log.Fatal(err)
		}
	}()

	// register consul health check endpoint
	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "OK")
	})

	// build urlprefix-host/path tag list
	// e.g. urlprefix-/foo, urlprefix-/bar, ...
	var tags []string
	for _, p := range prefixes {
		tags = append(tags, "urlprefix-"+p)
	}

	// get host and port as string/int
	host, portstr, err := net.SplitHostPort(addr)
	if err != nil {
		log.Fatal(err)
	}
	port, err := strconv.Atoi(portstr)
	if err != nil {
		log.Fatal(err)
	}

	// register service with health check
	serviceID := name + "-" + addr
	service := &api.AgentServiceRegistration{
		ID:      serviceID,
		Name:    name,
		Port:    port,
		Address: host,
		Tags:    tags,
		Check: &api.AgentServiceCheck{
			HTTP:     "http://" + addr + "/health",
			Interval: "1s",
			Timeout:  "1s",
		},
	}

	config := &api.Config{Address: consul, Scheme: "http"}
	client, err := api.NewClient(config)
	if err != nil {
		log.Fatal(err)
	}

	if err := client.Agent().ServiceRegister(service); err != nil {
		log.Fatal(err)
	}
	log.Printf("Registered service %q in consul with tags %q", name, strings.Join(tags, ","))

	// run until we get a signal
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt, os.Kill)
	<-quit

	// deregister service
	if err := client.Agent().ServiceDeregister(serviceID); err != nil {
		log.Fatal(err)
	}
	log.Printf("Deregistered service %q in consul", name)
}

func EchoServer(ws *websocket.Conn) {
	addr := ws.LocalAddr().String()
	pfx := []byte("[" + addr + "] ")

	log.Printf("ws connect on %s", addr)

	// the following could be done with io.Copy(ws, ws)
	// but I want to add some meta data
	var msg = make([]byte, 1024)
	for {
		n, err := ws.Read(msg)
		if err != nil && err != io.EOF {
			log.Printf("ws error on %s. %s", addr, err)
			break
		}
		_, err = ws.Write(append(pfx, msg[:n]...))
		if err != nil && err != io.EOF {
			log.Printf("ws error on %s. %s", addr, err)
			break
		}
	}
	log.Printf("ws disconnect on %s", addr)
}
<commit_msg>Issue #37: add support for consul ACL token to demo server<commit_after>// Package server provides a sample HTTP/Websocket server which registers
// itself in consul using one or more url prefixes to demonstrate and
// test the automatic fabio routing table update.
//
// During startup the server performs the following steps:
//
// * Add a handler for each prefix which provides a unique
//   response for that instance and endpoint
// * Add a `/health` handler for the consul health check
// * Register the service in consul with the listen address,
//   a health check under the given name and with one `urlprefix-`
//   tag per prefix
// * Install a signal handler to deregister the service on exit
//
// If the protocol is set to "ws" the registered endpoints function
// as websocket echo servers.
//
// Example:
//
//   # http server
//   ./server -addr 127.0.0.1:5000 -name svc-a -prefix /foo,/bar
//   ./server -addr 127.0.0.1:5001 -name svc-b -prefix /baz,/bar
//
//   # websocket server
//   ./server -addr 127.0.0.1:6000 -name ws-a -prefix /echo1,/echo2 -proto ws
//
package main

import (
	"flag"
	"fmt"
	"io"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/eBay/fabio/_third_party/github.com/hashicorp/consul/api"
	"github.com/eBay/fabio/_third_party/golang.org/x/net/websocket"
)

func main() {
	var addr, consul, name, prefix, proto, token string
	flag.StringVar(&addr, "addr", "127.0.0.1:5000", "host:port of the service")
	flag.StringVar(&consul, "consul", "127.0.0.1:8500", "host:port of the consul agent")
	flag.StringVar(&name, "name", filepath.Base(os.Args[0]), "name of the service")
	flag.StringVar(&prefix, "prefix", "", "comma-sep list of host/path prefixes to register")
	flag.StringVar(&proto, "proto", "http", "protocol for endpoints: http or ws")
	flag.StringVar(&token, "token", "", "consul ACL token")
	flag.Parse()

	if prefix == "" {
		flag.Usage()
		os.Exit(1)
	}

	// register prefixes
	prefixes := strings.Split(prefix, ",")
	for _, p := range prefixes {
		switch proto {
		case "http":
			http.HandleFunc(p, func(w http.ResponseWriter, r *http.Request) {
				fmt.Fprintf(w, "Serving %s from %s on %s\n", r.RequestURI, name, addr)
			})
		case "ws":
			http.Handle(p, websocket.Handler(EchoServer))
		default:
			log.Fatal("Invalid protocol ", proto)
		}
	}

	// start http server
	go func() {
		log.Printf("Listening on %s serving %s", addr, prefix)
		if err := http.ListenAndServe(addr, nil); err != nil {
			log.Fatal(err)
		}
	}()

	// register consul health check endpoint
	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "OK")
	})

	// build urlprefix-host/path tag list
	// e.g. urlprefix-/foo, urlprefix-/bar, ...
	var tags []string
	for _, p := range prefixes {
		tags = append(tags, "urlprefix-"+p)
	}

	// get host and port as string/int
	host, portstr, err := net.SplitHostPort(addr)
	if err != nil {
		log.Fatal(err)
	}
	port, err := strconv.Atoi(portstr)
	if err != nil {
		log.Fatal(err)
	}

	// register service with health check
	serviceID := name + "-" + addr
	service := &api.AgentServiceRegistration{
		ID:      serviceID,
		Name:    name,
		Port:    port,
		Address: host,
		Tags:    tags,
		Check: &api.AgentServiceCheck{
			HTTP:     "http://" + addr + "/health",
			Interval: "1s",
			Timeout:  "1s",
		},
	}

	config := &api.Config{Address: consul, Scheme: "http", Token:token}
	client, err := api.NewClient(config)
	if err != nil {
		log.Fatal(err)
	}

	if err := client.Agent().ServiceRegister(service); err != nil {
		log.Fatal(err)
	}
	log.Printf("Registered service %q in consul with tags %q", name, strings.Join(tags, ","))

	// run until we get a signal
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt, os.Kill)
	<-quit

	// deregister service
	if err := client.Agent().ServiceDeregister(serviceID); err != nil {
		log.Fatal(err)
	}
	log.Printf("Deregistered service %q in consul", name)
}

func EchoServer(ws *websocket.Conn) {
	addr := ws.LocalAddr().String()
	pfx := []byte("[" + addr + "] ")

	log.Printf("ws connect on %s", addr)

	// the following could be done with io.Copy(ws, ws)
	// but I want to add some meta data
	var msg = make([]byte, 1024)
	for {
		n, err := ws.Read(msg)
		if err != nil && err != io.EOF {
			log.Printf("ws error on %s. %s", addr, err)
			break
		}
		_, err = ws.Write(append(pfx, msg[:n]...))
		if err != nil && err != io.EOF {
			log.Printf("ws error on %s. %s", addr, err)
			break
		}
	}
	log.Printf("ws disconnect on %s", addr)
}
<|endoftext|>


<commit_before>package tagbbs

import "sort"

type SortedString []string

func (s SortedString) Len() int      { return len(s) }
func (s SortedString) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s SortedString) Less(i, j int) bool {
	if len(s[i]) == len(s[j]) {
		return s[i] < s[j]
	}
	return len(s[i]) < len(s[j])
}
func (s SortedString) Sort() {
	sort.Sort(s)
}
func (s *SortedString) Unique() {
	i := 0
	for j := 1; j < len(*s); j++ {
		if (*s)[i] != (*s)[j] {
			i++
		}
		(*s)[i] = (*s)[j]
	}
	(*s) = (*s)[:i+1]
}
func (s *SortedString) Insert(val string) bool {
	if i := sort.StringSlice(*s).Search(val); i < len(*s) && (*s)[i] == val {
		return false
	} else {
		*s = append((*s)[:i], append([]string{val}, (*s)[i:]...)...)
		return true
	}
}
func (s *SortedString) Delete(val string) bool {
	if i := sort.StringSlice(*s).Search(val); i < len(*s) && (*s)[i] == val {
		*s = append((*s)[:i], (*s)[i+1:]...)
		return true
	} else {
		return false
	}
}
<commit_msg>sortedstring: fix insert/delete<commit_after>package tagbbs

import "sort"

type SortedString []string

func strcmp(a, b string) bool {
	if len(a) == len(b) {
		return a < b
	}
	return len(a) < len(b)

}

func (s SortedString) Len() int           { return len(s) }
func (s SortedString) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s SortedString) Less(i, j int) bool { return strcmp(s[i], s[j]) }
func (s SortedString) Sort() {
	sort.Sort(s)
}
func (s SortedString) Search(v string) int {
	return sort.Search(len(s), func(i int) bool { return !strcmp(s[i], v) })
}
func (s *SortedString) Unique() {
	i := 0
	for j := 1; j < len(*s); j++ {
		if (*s)[i] != (*s)[j] {
			i++
		}
		(*s)[i] = (*s)[j]
	}
	(*s) = (*s)[:i+1]
}
func (s *SortedString) Insert(val string) bool {
	if i := s.Search(val); i < len(*s) && (*s)[i] == val {
		return false
	} else {
		*s = append((*s)[:i], append([]string{val}, (*s)[i:]...)...)
		return true
	}
}
func (s *SortedString) Delete(val string) bool {
	if i := s.Search(val); i < len(*s) && (*s)[i] == val {
		*s = append((*s)[:i], (*s)[i+1:]...)
		return true
	} else {
		return false
	}
}
<|endoftext|>


<commit_before>package market

import (
	"errors"
	"fmt"
	"path/filepath"
	"strings"

	"github.com/nzai/stockrecorder/config"
	"github.com/nzai/stockrecorder/io"
)

const (
	companiesFileName = "companies.txt"
)

//	公司
type Company struct {
	Name string
	Code string
}

//	公司列表
type CompanyList []Company

func (l CompanyList) Len() int {
	return len(l)
}
func (l CompanyList) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}
func (l CompanyList) Less(i, j int) bool {
	return l[i].Code < l[j].Code
}

//	上市公司列表保存路径
func storePath(market Market) string {
	return filepath.Join(config.Get().DataDir, market.Name(), companiesFileName)
}

//	保存上市公司列表到文件
func (l CompanyList) Save(market Market) error {
	lines := make([]string, 0)
	companies := ([]Company)(l)
	for _, company := range companies {
		lines = append(lines, fmt.Sprintf("%s\t%s\n", company.Code, company.Name))
	}

	return io.WriteLines(storePath(market), lines)
}

//	从存档读取上市公司列表
func (l *CompanyList) Load(market Market) error {
	lines, err := io.ReadLines(storePath(market))
	if err != nil {
		return err
	}

	companies := make([]Company, 0)
	for _, line := range lines {
		parts := strings.Split(line, "\t")
		if len(parts) != 2 {
			return errors.New("错误的上市公司列表格式")
		}

		companies = append(companies, Company{Code: parts[0], Name: parts[1]})
	}

	cl := CompanyList(companies)
	l = &cl

	return nil
}
<commit_msg>上市公司增加所属市场属性，并将上市公司保存到数据库中<commit_after>package market

import (
	"fmt"

	"github.com/nzai/stockrecorder/db"
	"gopkg.in/mgo.v2/bson"
)

const (
	companiesFileName = "companies.txt"
)

//	公司
type Company struct {
	Market string
	Name   string
	Code   string
}

//	公司列表
type CompanyList []Company

func (l CompanyList) Len() int {
	return len(l)
}
func (l CompanyList) Swap(i, j int) {
	l[i], l[j] = l[j], l[i]
}
func (l CompanyList) Less(i, j int) bool {
	return l[i].Code < l[j].Code
}

//	保存上市公司列表到文件
func (l CompanyList) Save(market Market) error {

	//	连接数据库
	session, err := db.Get()
	if err != nil {
		return fmt.Errorf("[DB]\t获取数据库连接失败:%s", err.Error())
	}
	defer session.Close()

	companies := ([]Company)(l)
	list := make([]interface{}, 0)
	for _, company := range companies {
		list = append(list, company)
	}

	collection := session.DB("stock").C("Company")

	//	删除原有记录
	_, err = collection.RemoveAll(bson.M{"market": market.Name()})
	if err != nil {
		return fmt.Errorf("[DB]\t删除原有上市公司发生错误: %s", err.Error())
	}

	return collection.Insert(list...)
}

//	从存档读取上市公司列表
func (l *CompanyList) Load(market Market) error {
	//	连接数据库
	session, err := db.Get()
	if err != nil {
		return fmt.Errorf("[DB]\t获取数据库连接失败:%s", err.Error())
	}
	defer session.Close()

	var companies []Company
	err = session.DB("stock").C("Company").Find(bson.M{"market": market.Name()}).Sort("code").All(&companies)
	if err != nil {
		return fmt.Errorf("[DB]\t查询上市公司发生错误: %s", err.Error())
	}

	cl := CompanyList(companies)
	l = &cl

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"time"

	"github.com/jessevdk/go-flags"
)

func loadImageList(jsonFilePath string) (buildsData, error) {
	var builds buildsData
	rawData, err := ioutil.ReadFile(jsonFilePath)
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal(rawData, &builds)
	if err != nil {
		return nil, err
	}

	return builds, nil
}

func checkIfTokensPresent() {
	if len(os.Getenv("TOKEN_PLATFORM")) == 0 {
		log.Fatal("TOKEN_PLATFORM is not set")
	}

	if len(os.Getenv("TOKEN_PROTONET")) == 0 {
		log.Fatal("TOKEN_PROTONET is not set")
	}
}

func updateJSON(dir, releaseNotesURL, tagTimestamp, isoTimestamp, targetChannel string, newBuildNumber int32, oldBuilds buildsData, commit bool) error {
	newBuilds := []buildsDatum{oldBuilds[0]}
	newBuilds[0].Build = newBuildNumber
	newBuilds[0].PublishedAt = isoTimestamp
	newBuilds[0].URL = releaseNotesURL

	for k := range newBuilds[0].Images {
		newBuilds[0].Images[k] = tagTimestamp
	}

	log.Printf("Old build version: %d", oldBuilds[0].Build)
	log.Printf("New build version: %d", newBuilds[0].Build)

	data, err := json.MarshalIndent(&newBuilds, "", "  ")
	if err != nil {
		return err
	}

	if commit == true {
		jsonFilePath := fmt.Sprintf("%s/%s.json", dir, targetChannel)
		jsonFileName := fmt.Sprintf("%s.json", targetChannel)
		err = ioutil.WriteFile(jsonFilePath, data, 0644)
		if err != nil {
			return err
		}

		commitMessage := fmt.Sprintf("release on channel '%s' at %s", targetChannel, isoTimestamp)
		err := addAndCommit(dir, jsonFileName, commitMessage)
		if err != nil {
			return err
		}

		err = pushRepo(dir)
		if err != nil {
			return err
		}
		log.Println("Push successful")
	} else {
		log.Printf("New JSON:\n%s\n", string(data))
	}

	return nil
}

func main() {
	var opts struct {
		Commit    bool   `short:"c" long:"commit" default:"false" description:"Commit the changes. Will make a dry run without this flag."`
		Build     int32  `short:"b" long:"build" required:"true" description:"Specify the build number to be placed inside the JSON."`
		SourceTag string `short:"s" long:"source-tag" default:"development" description:"Registry tag to be retagging from."`
		TargetTag string `short:"t" long:"target-tag" default:"soul3" description:"Registry tag to be retagging to."`
		URL       string `short:"u" long:"url" required:"true" description:"Release notes URL"`
	}

	_, err := flags.Parse(&opts)
	if err != nil {
		os.Exit(1)
	}

	currentTime := time.Now().UTC()
	tagTimestamp := currentTime.Format("2006-01-02-1504")
	isoTimestamp := currentTime.Format("2006-01-02T15:04:05Z")

	dir, err := prepareRepo()
	if err != nil {
		log.Fatalf("Failed to clone the builds repo: %s", err.Error())
	}
	log.Printf("Working in directory '%s'", dir)
	defer os.RemoveAll(dir)

	jsonFilePath := fmt.Sprintf("%s/%s.json", dir, opts.SourceTag)
	builds, err := loadImageList(jsonFilePath)
	if err != nil {
		log.Fatalf("Failed to load build data from '%s'", jsonFilePath)
	}

	fmt.Printf("Tag timestamp: %s\n", tagTimestamp)
	fmt.Printf("ISO timestamp: %s\n", isoTimestamp)

	if opts.Commit == true {
		checkIfTokensPresent()

		err := retagAll(builds[0].Images, opts.SourceTag, tagTimestamp)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		log.Printf("Dry run. Would otherwise retag following images from '%s' to '%s' and update channel '%s':\n", opts.SourceTag, tagTimestamp, opts.TargetTag)
		for k := range builds[0].Images {
			log.Printf(" * %s\n", k)
		}
	}

	err = updateJSON(dir, opts.URL, tagTimestamp, isoTimestamp, opts.TargetTag, opts.Build, builds, opts.Commit)
	if err != nil {
		log.Fatal(err)
	}
}
<commit_msg>tagger: fix flag declarations<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"time"

	"github.com/jessevdk/go-flags"
)

func loadImageList(jsonFilePath string) (buildsData, error) {
	var builds buildsData
	rawData, err := ioutil.ReadFile(jsonFilePath)
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal(rawData, &builds)
	if err != nil {
		return nil, err
	}

	return builds, nil
}

func checkIfTokensPresent() {
	if len(os.Getenv("TOKEN_PLATFORM")) == 0 {
		log.Fatal("TOKEN_PLATFORM is not set")
	}

	if len(os.Getenv("TOKEN_PROTONET")) == 0 {
		log.Fatal("TOKEN_PROTONET is not set")
	}
}

func updateJSON(dir, releaseNotesURL, tagTimestamp, isoTimestamp, targetChannel string, newBuildNumber int32, oldBuilds buildsData, commit bool) error {
	newBuilds := []buildsDatum{oldBuilds[0]}
	newBuilds[0].Build = newBuildNumber
	newBuilds[0].PublishedAt = isoTimestamp
	newBuilds[0].URL = releaseNotesURL

	for k := range newBuilds[0].Images {
		newBuilds[0].Images[k] = tagTimestamp
	}

	log.Printf("Old build version: %d", oldBuilds[0].Build)
	log.Printf("New build version: %d", newBuilds[0].Build)

	data, err := json.MarshalIndent(&newBuilds, "", "  ")
	if err != nil {
		return err
	}

	if commit == true {
		jsonFilePath := fmt.Sprintf("%s/%s.json", dir, targetChannel)
		jsonFileName := fmt.Sprintf("%s.json", targetChannel)
		err = ioutil.WriteFile(jsonFilePath, data, 0644)
		if err != nil {
			return err
		}

		commitMessage := fmt.Sprintf("release on channel '%s' at %s", targetChannel, isoTimestamp)
		err := addAndCommit(dir, jsonFileName, commitMessage)
		if err != nil {
			return err
		}

		err = pushRepo(dir)
		if err != nil {
			return err
		}
		log.Println("Push successful")
	} else {
		log.Printf("New JSON:\n%s\n", string(data))
	}

	return nil
}

func main() {
	var opts struct {
		Commit    bool   `short:"c" long:"commit" description:"Commit the changes. Will make a dry run without this flag."`
		Build     int32  `short:"b" long:"build" required:"true" description:"Specify the build number to be placed inside the JSON."`
		SourceTag string `short:"s" long:"source-tag" default:"development" description:"Registry tag to be retagging from."`
		TargetTag string `short:"t" long:"target-tag" default:"soul3" description:"Registry tag to be retagging to."`
		URL       string `short:"u" long:"url" required:"true" description:"Release notes URL"`
	}

	_, err := flags.Parse(&opts)
	if err != nil {
		os.Exit(1)
	}

	currentTime := time.Now().UTC()
	tagTimestamp := currentTime.Format("2006-01-02-1504")
	isoTimestamp := currentTime.Format("2006-01-02T15:04:05Z")

	dir, err := prepareRepo()
	if err != nil {
		log.Fatalf("Failed to clone the builds repo: %s", err.Error())
	}
	log.Printf("Working in directory '%s'", dir)
	defer os.RemoveAll(dir)

	jsonFilePath := fmt.Sprintf("%s/%s.json", dir, opts.SourceTag)
	builds, err := loadImageList(jsonFilePath)
	if err != nil {
		log.Fatalf("Failed to load build data from '%s'", jsonFilePath)
	}

	fmt.Printf("Tag timestamp: %s\n", tagTimestamp)
	fmt.Printf("ISO timestamp: %s\n", isoTimestamp)

	if opts.Commit == true {
		checkIfTokensPresent()

		err := retagAll(builds[0].Images, opts.SourceTag, tagTimestamp)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		log.Printf("Dry run. Would otherwise retag following images from '%s' to '%s' and update channel '%s':\n", opts.SourceTag, tagTimestamp, opts.TargetTag)
		for k := range builds[0].Images {
			log.Printf(" * %s\n", k)
		}
	}

	err = updateJSON(dir, opts.URL, tagTimestamp, isoTimestamp, opts.TargetTag, opts.Build, builds, opts.Commit)
	if err != nil {
		log.Fatal(err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"text/tabwriter"

	"github.com/GaryBoone/GoStats/stats"
	"github.com/topher200/baseutil"
)

type criterionCalculationFunction func(teams []Team) Score
type PlayerFilter func(player Player) bool
type criterion struct {
	name      string                       // human readable name
	calculate criterionCalculationFunction // how to calculate the raw score
	filter    PlayerFilter                 // cull down to players that match
	weight    int                          // how much weight to give this score
	// worstCase is calculated at runtime to be the absolute worst score we can
	// see this criterion getting
	worstCase Score
}

var criteriaToScore = [...]criterion{
	criterion{"number of players", playerCountDifference, nil, 10, 0},
	criterion{"number of males", playerCountDifference, IsMale, 9, 0},
	criterion{"number of females", playerCountDifference, IsFemale, 9, 0},
	criterion{"average rating", ratingDifference, nil, 8, 0},
	criterion{"std dev of team ratings", ratingStdDev, nil, 5, 0},
	criterion{"matching baggages", baggagesMatch, nil, 2, 0},
}

func playerCountDifference(teams []Team) Score {
	teamLengths := make([]int, numTeams)
	for i, team := range teams {
		teamLengths[i] = len(team.players)
	}
	return Score(baseutil.StandardDeviationInt(teamLengths))
}

func ratingDifference(teams []Team) Score {
	teamAverageRatings := make([]float64, numTeams)
	for i, team := range teams {
		teamAverageRatings[i] = float64(AverageRating(team))
	}
	return Score(stats.StatsSampleStandardDeviation(teamAverageRatings))
}

func ratingStdDev(teams []Team) Score {
	teamRatingsStdDev := make([]float64, numTeams)
	for i, team := range teams {
		playerRatings := make([]float64, len(team.players))
		for j, player := range team.players {
			playerRatings[j] = float64(player.rating)
		}
		teamRatingsStdDev[i] = stats.StatsSampleStandardDeviation(playerRatings)
	}
	return Score(stats.StatsSampleStandardDeviation(teamRatingsStdDev))
}

func baggagesMatch(teams []Team) Score {
	score := Score(0)
	for _, team := range teams {
		for _, player := range team.players {
			if !HasBaggage(player) {
				continue
			}
			_, err := FindPlayer(team.players, player.baggage)
			if err != nil {
				// Player desired a baggage, but they're not on the team
				score += 1
			}
		}
	}
	return score
}

func AverageRating(team Team) Score {
	sum := float32(0.0)
	for _, player := range team.players {
		sum += player.rating
	}
	return Score(sum / float32(len(team.players)))
}

func Filter(players []Player, filter PlayerFilter) (filteredPlayers []Player) {
	for _, player := range players {
		if filter == nil || filter(player) {
			filteredPlayers = append(filteredPlayers, player)
		}
	}
	return
}

// runCriterion by filtering the input teams and running the criterion function
func runCriterion(
	c criterion, teams []Team) (rawScore Score, weightedScore Score) {
	filteredTeams := make([]Team, len(teams))
	for i, _ := range teams {
		filteredTeams[i].players = Filter(teams[i].players, c.filter)
	}

	rawScore = c.calculate(filteredTeams)
	// We normalize our weighted scores based on the worst case scenario
	weightedScore = (rawScore / c.worstCase) * Score(c.weight)
	return rawScore, weightedScore
}

func maxScore(a, b Score) Score {
	if a > b {
		return a
	} else {
		return b
	}
}

// PopulateWorstCases calculates the worst case of each criterion.
//
// The function has the side effect of filling in the worstCase param for each
// criterion in criteriaToScore.
func PopulateWorstCases(solutions []Solution) {
	for _, solution := range solutions {
		_, rawScores := ScoreSolution(solution.players)
		for i, criterion := range criteriaToScore {
			criteriaToScore[i].worstCase = maxScore(
				criterion.worstCase, rawScores[i])
		}
	}
}

// Score a solution based on all known criteria.
//
// Returns the total score for the solution, as well as the raw score found for
// each of the criteriaToScore.
func ScoreSolution(players []Player) (totalScore Score, rawScores []Score) {
	teams := splitIntoTeams(players)
	rawScores = make([]Score, len(criteriaToScore))
	for i, criterion := range criteriaToScore {
		rawScore, weightedScore := runCriterion(criterion, teams)
		rawScores[i] = rawScore
		totalScore += weightedScore
	}
	return totalScore, rawScores
}

func PrintSolutionScoring(solution Solution) {
	teams := splitIntoTeams(solution.players)
	totalScore := Score(0)
	writer := new(tabwriter.Writer)
	writer.Init(os.Stdout, 0, 0, 1, ' ', 0)
	for _, criterion := range criteriaToScore {
		rawScore, weightedScore := runCriterion(criterion, teams)
		totalScore += weightedScore
		fmt.Fprintf(
			writer,
			"Balancing %s.\tWeighted score %.02f.\tRaw score %.02f (worst case %.02f).\tRunning total: %.02f\n",
			criterion.name, weightedScore, rawScore, criterion.worstCase, totalScore)
	}
	writer.Flush()
}
<commit_msg>print normalized, pre-weighted, score<commit_after>package main

import (
	"fmt"
	"os"
	"text/tabwriter"

	"github.com/GaryBoone/GoStats/stats"
	"github.com/topher200/baseutil"
)

type criterionCalculationFunction func(teams []Team) Score
type PlayerFilter func(player Player) bool
type criterion struct {
	name      string                       // human readable name
	calculate criterionCalculationFunction // how to calculate the raw score
	filter    PlayerFilter                 // cull down to players that match
	weight    int                          // how much weight to give this score
	// worstCase is calculated at runtime to be the absolute worst score we can
	// see this criterion getting
	worstCase Score
}

var criteriaToScore = [...]criterion{
	criterion{"number of players", playerCountDifference, nil, 10, 0},
	criterion{"number of males", playerCountDifference, IsMale, 9, 0},
	criterion{"number of females", playerCountDifference, IsFemale, 9, 0},
	criterion{"average rating", ratingDifference, nil, 8, 0},
	criterion{"std dev of team ratings", ratingStdDev, nil, 5, 0},
	criterion{"matching baggages", baggagesMatch, nil, 2, 0},
}

func playerCountDifference(teams []Team) Score {
	teamLengths := make([]int, numTeams)
	for i, team := range teams {
		teamLengths[i] = len(team.players)
	}
	return Score(baseutil.StandardDeviationInt(teamLengths))
}

func ratingDifference(teams []Team) Score {
	teamAverageRatings := make([]float64, numTeams)
	for i, team := range teams {
		teamAverageRatings[i] = float64(AverageRating(team))
	}
	return Score(stats.StatsSampleStandardDeviation(teamAverageRatings))
}

func ratingStdDev(teams []Team) Score {
	teamRatingsStdDev := make([]float64, numTeams)
	for i, team := range teams {
		playerRatings := make([]float64, len(team.players))
		for j, player := range team.players {
			playerRatings[j] = float64(player.rating)
		}
		teamRatingsStdDev[i] = stats.StatsSampleStandardDeviation(playerRatings)
	}
	return Score(stats.StatsSampleStandardDeviation(teamRatingsStdDev))
}

func baggagesMatch(teams []Team) Score {
	score := Score(0)
	for _, team := range teams {
		for _, player := range team.players {
			if !HasBaggage(player) {
				continue
			}
			_, err := FindPlayer(team.players, player.baggage)
			if err != nil {
				// Player desired a baggage, but they're not on the team
				score += 1
			}
		}
	}
	return score
}

func AverageRating(team Team) Score {
	sum := float32(0.0)
	for _, player := range team.players {
		sum += player.rating
	}
	return Score(sum / float32(len(team.players)))
}

func Filter(players []Player, filter PlayerFilter) (filteredPlayers []Player) {
	for _, player := range players {
		if filter == nil || filter(player) {
			filteredPlayers = append(filteredPlayers, player)
		}
	}
	return
}

// runCriterion by filtering the input teams and running the criterion function
func runCriterion(c criterion, teams []Team) (
	rawScore Score, normalizedScore Score, weightedScore Score) {
	filteredTeams := make([]Team, len(teams))
	for i, _ := range teams {
		filteredTeams[i].players = Filter(teams[i].players, c.filter)
	}

	rawScore = c.calculate(filteredTeams)
	normalizedScore = rawScore / c.worstCase
	weightedScore = normalizedScore * Score(c.weight)
	return rawScore, normalizedScore, weightedScore
}

func maxScore(a, b Score) Score {
	if a > b {
		return a
	} else {
		return b
	}
}

// PopulateWorstCases calculates the worst case of each criterion.
//
// The function has the side effect of filling in the worstCase param for each
// criterion in criteriaToScore.
func PopulateWorstCases(solutions []Solution) {
	for _, solution := range solutions {
		_, rawScores := ScoreSolution(solution.players)
		for i, criterion := range criteriaToScore {
			criteriaToScore[i].worstCase = maxScore(
				criterion.worstCase, rawScores[i])
		}
	}
}

// Score a solution based on all known criteria.
//
// Returns the total score for the solution, as well as the raw score found for
// each of the criteriaToScore.
func ScoreSolution(players []Player) (totalScore Score, rawScores []Score) {
	teams := splitIntoTeams(players)
	rawScores = make([]Score, len(criteriaToScore))
	for i, criterion := range criteriaToScore {
		rawScore, _, weightedScore := runCriterion(criterion, teams)
		rawScores[i] = rawScore
		totalScore += weightedScore
	}
	return totalScore, rawScores
}

func PrintSolutionScoring(solution Solution) {
	teams := splitIntoTeams(solution.players)
	totalScore := Score(0)
	writer := new(tabwriter.Writer)
	writer.Init(os.Stdout, 0, 0, 1, ' ', 0)
	for _, criterion := range criteriaToScore {
		rawScore, normalizedScore, weightedScore := runCriterion(
			criterion, teams)
		totalScore += weightedScore
		fmt.Fprintf(
			writer,
			"Balancing %s.\tScore: %.02f\t(= normalized score %.02f * weight %d)\traw score %0.2f, worst case %.02f)\tRunning total: %.02f\n",
			criterion.name, weightedScore, normalizedScore, criterion.weight,
			rawScore, criterion.worstCase, totalScore)
	}
	writer.Flush()
}
<|endoftext|>


<commit_before>package release

import (
	"archive/tar"
	"compress/gzip"
	"io"
	"log"
	"os"
	"os/user"
	"path"
	"strconv"
	"time"
)

const (
	tarIsDir = 040000
)

func CreateTarball(name string, topLevelFolder string, srcFilenames []string) {
	log.Print("[release] Creating tarball")
	targetFile, err := os.Create(name)
	if err != nil {
		log.Fatal(err)
	}
	gz := gzip.NewWriter(targetFile)
	tarball := tar.NewWriter(gz)
	defer func() {
		if err := tarball.Close(); err != nil {
			log.Fatal(err)
		}
		if err := gz.Close(); err != nil {
			log.Fatal(err)
		}
		if err := targetFile.Close(); err != nil {
			log.Fatal(err)
		}
	}()

	log.Print("[release] Writing fake top level directory to tarball")
	writeAppDir(tarball, topLevelFolder)

	log.Print("[release] Adding requested files to archive")
	for _, f := range srcFilenames {
		finfo, err := os.Stat(f)
		if err != nil {
			log.Fatal(err)
		}
		dir := path.Dir(f)
		archiveFiles(tarball, []os.FileInfo{finfo}, dir, topLevelFolder)
	}
}

func writeAppDir(tarball *tar.Writer, appDir string) {
	user, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	uid, err := strconv.Atoi(user.Uid)
	if err != nil {
		log.Fatal(err)
	}
	gid, err := strconv.Atoi(user.Gid)
	if err != nil {
		log.Fatal(err)
	}
	now := time.Now()
	header := &tar.Header{
		// "./" needs to preceed all files in a heroku slug.
		Name:       "./" + appDir,
		Mode:       int64(os.ModePerm | tarIsDir),
		Uid:        uid,
		Gid:        gid,
		ModTime:    now,
		AccessTime: now,
		ChangeTime: now,
		Typeflag:   tar.TypeDir,
	}
	tarball.WriteHeader(header)
}

func archiveFiles(tarball *tar.Writer, srcFiles []os.FileInfo, directory string, destPrefix string) {
	for _, finfo := range srcFiles {
		srcName := finfo.Name()
		if directory != "" {
			srcName = path.Join(directory, srcName)
		}
		dstName := path.Join(destPrefix, srcName)

		src, err := os.Open(srcName)
		if err != nil {
			log.Fatal(err)
		}
		defer src.Close()

		tarHeader, err := tar.FileInfoHeader(finfo, "")
		if err != nil {
			log.Fatal(err)
		}
		// As in writeAppDir, "./" always needs to preceed entries in a
		// heroku slug.
		tarHeader.Name = "./" + path.Join(destPrefix, tarHeader.Name)
		tarball.WriteHeader(tarHeader)
		io.Copy(tarball, src)

		if finfo.IsDir() {
			contents, err := src.Readdir(0)
			if err != nil {
				log.Fatal(err)
			}
			archiveFiles(tarball, contents, srcName, dstName)
		}
	}
}
<commit_msg>Removed redundant dest prefix<commit_after>package release

import (
	"archive/tar"
	"compress/gzip"
	"io"
	"log"
	"os"
	"os/user"
	"path"
	"strconv"
	"time"
)

const (
	tarIsDir = 040000
)

func CreateTarball(name string, topLevelFolder string, srcFilenames []string) {
	log.Print("[release] Creating tarball")
	targetFile, err := os.Create(name)
	if err != nil {
		log.Fatal(err)
	}
	gz := gzip.NewWriter(targetFile)
	tarball := tar.NewWriter(gz)
	defer func() {
		if err := tarball.Close(); err != nil {
			log.Fatal(err)
		}
		if err := gz.Close(); err != nil {
			log.Fatal(err)
		}
		if err := targetFile.Close(); err != nil {
			log.Fatal(err)
		}
	}()

	log.Print("[release] Writing fake top level directory to tarball")
	writeAppDir(tarball, topLevelFolder)

	log.Print("[release] Adding requested files to archive")
	for _, f := range srcFilenames {
		finfo, err := os.Stat(f)
		if err != nil {
			log.Fatal(err)
		}
		dir := path.Dir(f)
		archiveFiles(tarball, []os.FileInfo{finfo}, dir, topLevelFolder)
	}
}

func writeAppDir(tarball *tar.Writer, appDir string) {
	user, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	uid, err := strconv.Atoi(user.Uid)
	if err != nil {
		log.Fatal(err)
	}
	gid, err := strconv.Atoi(user.Gid)
	if err != nil {
		log.Fatal(err)
	}
	now := time.Now()
	header := &tar.Header{
		// "./" needs to preceed all files in a heroku slug.
		Name:       "./" + appDir,
		Mode:       int64(os.ModePerm | tarIsDir),
		Uid:        uid,
		Gid:        gid,
		ModTime:    now,
		AccessTime: now,
		ChangeTime: now,
		Typeflag:   tar.TypeDir,
	}
	tarball.WriteHeader(header)
}

func archiveFiles(tarball *tar.Writer, srcFiles []os.FileInfo, directory string, destPrefix string) {
	for _, finfo := range srcFiles {
		srcName := finfo.Name()
		if directory != "" {
			srcName = path.Join(directory, srcName)
		}

		src, err := os.Open(srcName)
		if err != nil {
			log.Fatal(err)
		}
		defer src.Close()

		tarHeader, err := tar.FileInfoHeader(finfo, "")
		if err != nil {
			log.Fatal(err)
		}
		// As in writeAppDir, "./" always needs to preceed entries in a
		// heroku slug.
		tarHeader.Name = "./" + path.Join(destPrefix, tarHeader.Name)
		tarball.WriteHeader(tarHeader)
		io.Copy(tarball, src)

		if finfo.IsDir() {
			contents, err := src.Readdir(0)
			if err != nil {
				log.Fatal(err)
			}
			archiveFiles(tarball, contents, srcName, destPrefix)
		}
	}
}
<|endoftext|>


<commit_before>package logging

import (
	"fmt"
	"net/url"

	"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
	"github.com/cloudfoundry-incubator/cf-test-helpers/generator"
	"github.com/cloudfoundry-incubator/cf-test-helpers/helpers"
	"github.com/cloudfoundry/cf-smoke-tests/smoke"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("Etcd Cluster Check:", func() {
	var testConfig = smoke.GetConfig()
	var appName string

	Describe("etcd cluster checking", func() {
		BeforeEach(func() {
			if testConfig.EnableEtcdClusterCheckTests != true {
				Skip("Skipping because EnableEtcdClusterCheckTests flag set to false")
			}
			appName = generator.PrefixedRandomName("SMOKES", "APP")
			Eventually(cf.Cf(
				"push", appName,
				"-p", CURLER_RUBY_APP_BITS_PATH,
				"--no-start",
				"-b", "ruby_buildpack",
				"-d", testConfig.AppsDomain,
				"-i", "1"),
				CF_PUSH_TIMEOUT_IN_SECONDS,
			).Should(Exit(0))
			smoke.SetBackend(appName)
			Expect(cf.Cf("start", appName).Wait(CF_PUSH_TIMEOUT_IN_SECONDS)).To(Exit(0))
		})

		It("does not allow apps to directly modify etcd", func() {
			// Post to the app, which triggers a POST to etcd
			p := url.Values{}
			p.Add("host", testConfig.EtcdIpAddress)
			p.Add("path", "/v2/keys/foo")
			p.Add("port", "4001")
			p.Add("data", "value=updated_value")
			curlCmd := helpers.CurlSkipSSL(true, fmt.Sprintf("https://%s.%s/put/?%s", appName, testConfig.AppsDomain, p.Encode())).Wait(CF_TIMEOUT_IN_SECONDS)
			Expect(curlCmd).To(Exit(0))
			Expect(string(curlCmd.Out.Contents())).To(ContainSubstring("Connection refused"))
		})

		AfterEach(func() {
			smoke.AppReport(appName, CF_TIMEOUT_IN_SECONDS)
			if testConfig.Cleanup {
				Expect(cf.Cf("delete", appName, "-f", "-r").Wait(CF_TIMEOUT_IN_SECONDS)).To(Exit(0))
			}
		})
	})
})
<commit_msg>Improve failure message when etcd cluster is configured insecurely<commit_after>package logging

import (
	"fmt"
	"net/url"

	"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
	"github.com/cloudfoundry-incubator/cf-test-helpers/generator"
	"github.com/cloudfoundry-incubator/cf-test-helpers/helpers"
	"github.com/cloudfoundry/cf-smoke-tests/smoke"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("Etcd Cluster Check:", func() {
	var testConfig = smoke.GetConfig()
	var appName string

	Describe("etcd cluster checking", func() {
		BeforeEach(func() {
			if testConfig.EnableEtcdClusterCheckTests != true {
				Skip("Skipping because EnableEtcdClusterCheckTests flag set to false")
			}
			appName = generator.PrefixedRandomName("SMOKES", "APP")
			Eventually(cf.Cf(
				"push", appName,
				"-p", CURLER_RUBY_APP_BITS_PATH,
				"--no-start",
				"-b", "ruby_buildpack",
				"-d", testConfig.AppsDomain,
				"-i", "1"),
				CF_PUSH_TIMEOUT_IN_SECONDS,
			).Should(Exit(0))
			smoke.SetBackend(appName)
			Expect(cf.Cf("start", appName).Wait(CF_PUSH_TIMEOUT_IN_SECONDS)).To(Exit(0))
		})

		It("does not allow apps to directly modify etcd", func() {
			// Post to the app, which triggers a POST to etcd
			p := url.Values{}
			p.Add("host", testConfig.EtcdIpAddress)
			p.Add("path", "/v2/keys/foo")
			p.Add("port", "4001")
			p.Add("data", "value=updated_value")
			curlCmd := helpers.CurlSkipSSL(true, fmt.Sprintf("https://%s.%s/put/?%s", appName, testConfig.AppsDomain, p.Encode()))
			errorMsg := fmt.Sprintf("Connections from application containers to internal IP addresses such as etcd node <%s> were not rejected. Please review the documentation on Application Security Groups to disallow traffic from application containers to internal IP addresses: https://docs.cloudfoundry.org/adminguide/app-sec-groups.html", testConfig.EtcdIpAddress)
			Eventually(curlCmd, CF_TIMEOUT_IN_SECONDS).Should(Exit(0), errorMsg)
			Expect(string(curlCmd.Out.Contents())).To(ContainSubstring("Connection refused"), errorMsg)
		})

		AfterEach(func() {
			smoke.AppReport(appName, CF_TIMEOUT_IN_SECONDS)
			if testConfig.Cleanup {
				Expect(cf.Cf("delete", appName, "-f", "-r").Wait(CF_TIMEOUT_IN_SECONDS)).To(Exit(0))
			}
		})
	})
})
<|endoftext|>