<commit_before>package chefsolo

import (
	"github.com/mitchellh/packer/packer"
	"io/ioutil"
	"os"
	"testing"
)

func testConfig() map[string]interface{} {
	return map[string]interface{}{}
}

func TestProvisioner_Impl(t *testing.T) {
	var raw interface{}
	raw = &Provisioner{}
	if _, ok := raw.(packer.Provisioner); !ok {
		t.Fatalf("must be a Provisioner")
	}
}

func TestProvisionerPrepare_configTemplate(t *testing.T) {
	var err error
	var p Provisioner

	// Test no config template
	config := testConfig()
	delete(config, "config_template")
	err = p.Prepare(config)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	// Test with a file
	tf, err := ioutil.TempFile("", "packer")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(tf.Name())

	config = testConfig()
	config["config_template"] = tf.Name()
	p = Provisioner{}
	err = p.Prepare(config)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	// Test with a directory
	td, err := ioutil.TempDir("", "packer")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.RemoveAll(td)

	config = testConfig()
	config["config_template"] = td
	p = Provisioner{}
	err = p.Prepare(config)
	if err == nil {
		t.Fatal("should have err")
	}
}

func TestProvisionerPrepare_cookbookPaths(t *testing.T) {
	var p Provisioner

	path1, err := ioutil.TempDir("", "cookbooks_one")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	path2, err := ioutil.TempDir("", "cookbooks_two")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	rolesPath, err := ioutil.TempDir("", "roles")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	dataBagsPath, err := ioutil.TempDir("", "data_bags")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	defer os.Remove(path1)
	defer os.Remove(path2)
	defer os.Remove(rolesPath)
	defer os.Remove(dataBagsPath)

	config := testConfig()
	config["cookbook_paths"] = []string{path1, path2}
	config["roles_path"] = rolesPath
	config["data_bags_path"] = dataBagsPath

	err = p.Prepare(config)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if len(p.config.CookbookPaths) != 2 {
		t.Fatalf("unexpected: %#v", p.config.CookbookPaths)
	}

	if p.config.CookbookPaths[0] != path1 || p.config.CookbookPaths[1] != path2 {
		t.Fatalf("unexpected: %#v", p.config.CookbookPaths)
	}

	if p.config.RolesPath != rolesPath {
		t.Fatalf("unexpected: %#v", p.config.RolesPath)
	}

	if p.config.DataBagsPath != dataBagsPath {
		t.Fatalf("unexpected: %#v", p.config.DataBagsPath)
	}
}

func TestProvisionerPrepare_json(t *testing.T) {
	config := testConfig()
	config["json"] = map[string]interface{}{
		"foo": "{{ user `foo` }}",
	}

	config[packer.UserVariablesConfigKey] = map[string]string{
		"foo": `"bar\baz"`,
	}

	var p Provisioner
	err := p.Prepare(config)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if p.config.Json["foo"] != `"bar\baz"` {
		t.Fatalf("bad: %#v", p.config.Json)
	}
}
<commit_msg>provisioner/chef-solo: one test per test<commit_after>package chefsolo

import (
	"github.com/mitchellh/packer/packer"
	"io/ioutil"
	"os"
	"testing"
)

func testConfig() map[string]interface{} {
	return map[string]interface{}{}
}

func TestProvisioner_Impl(t *testing.T) {
	var raw interface{}
	raw = &Provisioner{}
	if _, ok := raw.(packer.Provisioner); !ok {
		t.Fatalf("must be a Provisioner")
	}
}

func TestProvisionerPrepare_configTemplate(t *testing.T) {
	var err error
	var p Provisioner

	// Test no config template
	config := testConfig()
	delete(config, "config_template")
	err = p.Prepare(config)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	// Test with a file
	tf, err := ioutil.TempFile("", "packer")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(tf.Name())

	config = testConfig()
	config["config_template"] = tf.Name()
	p = Provisioner{}
	err = p.Prepare(config)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	// Test with a directory
	td, err := ioutil.TempDir("", "packer")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.RemoveAll(td)

	config = testConfig()
	config["config_template"] = td
	p = Provisioner{}
	err = p.Prepare(config)
	if err == nil {
		t.Fatal("should have err")
	}
}

func TestProvisionerPrepare_cookbookPaths(t *testing.T) {
	var p Provisioner

	path1, err := ioutil.TempDir("", "cookbooks_one")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	path2, err := ioutil.TempDir("", "cookbooks_two")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	rolesPath, err := ioutil.TempDir("", "roles")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	dataBagsPath, err := ioutil.TempDir("", "data_bags")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	defer os.Remove(path1)
	defer os.Remove(path2)
	defer os.Remove(rolesPath)
	defer os.Remove(dataBagsPath)

	config := testConfig()
	config["cookbook_paths"] = []string{path1, path2}
	config["roles_path"] = rolesPath
	config["data_bags_path"] = dataBagsPath

	err = p.Prepare(config)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if len(p.config.CookbookPaths) != 2 {
		t.Fatalf("unexpected: %#v", p.config.CookbookPaths)
	}

	if p.config.CookbookPaths[0] != path1 || p.config.CookbookPaths[1] != path2 {
		t.Fatalf("unexpected: %#v", p.config.CookbookPaths)
	}

	if p.config.RolesPath != rolesPath {
		t.Fatalf("unexpected: %#v", p.config.RolesPath)
	}

	if p.config.DataBagsPath != dataBagsPath {
		t.Fatalf("unexpected: %#v", p.config.DataBagsPath)
	}
}

func TestProvisionerPrepare_dataBagsPath(t *testing.T) {
	var p Provisioner

	dataBagsPath, err := ioutil.TempDir("", "data_bags")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(dataBagsPath)

	config := testConfig()
	config["data_bags_path"] = dataBagsPath

	err = p.Prepare(config)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if p.config.DataBagsPath != dataBagsPath {
		t.Fatalf("unexpected: %#v", p.config.DataBagsPath)
	}
}

func TestProvisionerPrepare_rolesPath(t *testing.T) {
	var p Provisioner

	rolesPath, err := ioutil.TempDir("", "roles")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Remove(rolesPath)

	config := testConfig()
	config["roles_path"] = rolesPath

	err = p.Prepare(config)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if p.config.RolesPath != rolesPath {
		t.Fatalf("unexpected: %#v", p.config.RolesPath)
	}
}

func TestProvisionerPrepare_json(t *testing.T) {
	config := testConfig()
	config["json"] = map[string]interface{}{
		"foo": "{{ user `foo` }}",
	}

	config[packer.UserVariablesConfigKey] = map[string]string{
		"foo": `"bar\baz"`,
	}

	var p Provisioner
	err := p.Prepare(config)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	if p.config.Json["foo"] != `"bar\baz"` {
		t.Fatalf("bad: %#v", p.config.Json)
	}
}
<|endoftext|>


<commit_before>package models

type Config struct {
    Id                     string `rethink:"id,omitempty"`
    Guild                  string `rethink:"guild"`

    Prefix                 string `rethink:"prefix"`

    CleanupEnabled         bool `rethink:"cleanup_enabled"`

    AutoRepliesEnabled     bool `rethink:"auto_replies_enabled"`
    AutoReplies            map[string]string `rethink:"auto_replies"`

    AnnouncementsEnabled   bool `rethink:"announcements_enabled"`
    AnnouncementsChannel   string `rethink:"announcements_channel"`

    WelcomeNewUsersEnabled bool `rethink:"welcome_new_users_enabled"`
    WelcomeNewUsersText    string `rethink:"welcome_new_users_text"`
}

func (c Config) Default(guild string) Config {
    return Config{
        Guild: guild,

        Prefix: "%",

        CleanupEnabled: false,

        AutoRepliesEnabled: false,
        AutoReplies: make(map[string]string),

        AnnouncementsEnabled: false,
        AnnouncementsChannel: "",

        WelcomeNewUsersEnabled: false,
        WelcomeNewUsersText: "",
    }
}
<commit_msg>Remove autoreplies from db template<commit_after>package models

type Config struct {
    Id                     string `rethink:"id,omitempty"`
    Guild                  string `rethink:"guild"`

    Prefix                 string `rethink:"prefix"`

    CleanupEnabled         bool `rethink:"cleanup_enabled"`

    AnnouncementsEnabled   bool `rethink:"announcements_enabled"`
    AnnouncementsChannel   string `rethink:"announcements_channel"`

    WelcomeNewUsersEnabled bool `rethink:"welcome_new_users_enabled"`
    WelcomeNewUsersText    string `rethink:"welcome_new_users_text"`
}

func (c Config) Default(guild string) Config {
    return Config{
        Guild: guild,

        Prefix: "%",

        CleanupEnabled: false,

        AnnouncementsEnabled: false,
        AnnouncementsChannel: "",

        WelcomeNewUsersEnabled: false,
        WelcomeNewUsersText: "",
    }
}
<|endoftext|>


<commit_before>package models

import (
  "encoding/json"
  "fmt"
  "reflect"
  "strings"
  "sync"

  "github.com/astaxie/beego"
  "github.com/siddontang/ledisdb/config"
  "github.com/siddontang/ledisdb/ledis"

  "github.com/dockercn/wharf/utils"
)

const (
  GLOBAL_USER_INDEX         = "GLOBAL_USER_INDEX"
  GLOBAL_REPOSITORY_INDEX   = "GLOBAL_REPOSITORY_INDEX"
  GLOBAL_ORGANIZATION_INDEX = "GLOBAL_ORGANIZATION_INDEX"
  GLOBAL_TEAM_INDEX         = "GLOBAL_TEAM_INDEX"
  GLOBAL_IMAGE_INDEX        = "GLOBAL_IMAGE_INDEX"
  GLOBAL_TAG_INDEX          = "GLOBAL_TAG_INDEX"
  GLOBAL_COMPOSE_INDEX      = "GLOBAL_COMPOSE_INDEX"
  GLOBAL_ADMIN_INDEX        = "GLOBAL_ADMIN_INDEX"
)

var (
  ledisOnce sync.Once
  nowLedis  *ledis.Ledis
  LedisDB   *ledis.DB
)

func InitDb() {
  initLedisFunc := func() {
    cfg := new(config.Config)
    cfg.DataDir = beego.AppConfig.String("ledisdb::DataDir")
    var err error
    nowLedis, err = ledis.Open(cfg)
    if err != nil {
      println(err.Error())
      panic(err)
    }
  }

  ledisOnce.Do(initLedisFunc)

  db, _ := beego.AppConfig.Int("ledisdb::DB")

  LedisDB, _ = nowLedis.Select(db)
}

func GetUUID(ObjectType, Object string) (UUID []byte, err error) {

  index := ""

  switch strings.TrimSpace(ObjectType) {

  case "user":
    index = GLOBAL_USER_INDEX
  case "repository":
    index = GLOBAL_REPOSITORY_INDEX
  case "organization":
    index = GLOBAL_ORGANIZATION_INDEX
  case "team":
    index = GLOBAL_TEAM_INDEX
  case "image":
    index = GLOBAL_IMAGE_INDEX
  case "tag":
    index = GLOBAL_TAG_INDEX
  case "compose":
    index = GLOBAL_COMPOSE_INDEX
  case "admin":
    index = GLOBAL_ADMIN_INDEX
  default:

  }

  if UUID, err = LedisDB.HGet([]byte(index), []byte(Object)); err != nil {
    return nil, err
  } else {
    return UUID, nil
  }

}

func Save(obj interface{}, key []byte) (err error) {

  s := reflect.TypeOf(obj).Elem()

  for i := 0; i < s.NumField(); i++ {

    value := reflect.ValueOf(obj).Elem().Field(s.Field(i).Index[0])

    switch value.Kind() {

    case reflect.String:
      if _, err := LedisDB.HSet(key, []byte(s.Field(i).Name), []byte(value.String())); err != nil {
        return err
      }

    case reflect.Bool:
      if _, err := LedisDB.HSet(key, []byte(s.Field(i).Name), utils.BoolToBytes(value.Bool())); err != nil {
        return err
      }

    case reflect.Int64:
      if _, err := LedisDB.HSet(key, []byte(s.Field(i).Name), utils.Int64ToBytes(value.Int())); err != nil {
        return err
      }

    case reflect.Slice:
      if "[]string" == value.Type().String() && !value.IsNil() {
        strJson := "["

        for i := 0; i < value.Len(); i++ {
          nowUUID := value.Index(i).String()
          if i != 0 {
            strJson += fmt.Sprintf(`,"%s"`, nowUUID)
          } else {
            strJson += fmt.Sprintf(`"%s"`, nowUUID)
          }
        }

        strJson += "]"

        if _, err := LedisDB.HSet(key, []byte(s.Field(i).Name), []byte(strJson)); err != nil {
          return err
        }
      }

    default:
    }

  }
  return nil
}

func Get(obj interface{}, UUID []byte) (err error) {

  nowTypeElem := reflect.ValueOf(obj).Elem()
  types := nowTypeElem.Type()

  for i := 0; i < nowTypeElem.NumField(); i++ {

    nowField := nowTypeElem.Field(i)
    nowFieldName := types.Field(i).Name

    switch nowField.Kind() {

    case reflect.String:
      nowValue, err := LedisDB.HGet(UUID, []byte(nowFieldName))
      nowField.SetString(string(nowValue))
      if err != nil {
        return err
      }

    case reflect.Bool:
      nowValue, err := LedisDB.HGet(UUID, []byte(nowFieldName))
      nowField.SetBool(utils.BytesToBool(nowValue))
      if err != nil {
        return err
      }

    case reflect.Int64:
      nowValue, err := LedisDB.HGet(UUID, []byte(nowFieldName))
      nowField.SetInt(utils.BytesToInt64(nowValue))
      if err != nil {
        return err
      }

    case reflect.Slice:
      if "[]string" == nowField.Type().String() {
        nowValue, err := LedisDB.HGet(UUID, []byte(nowFieldName))

        var stringSlice []string
        err = json.Unmarshal(nowValue, &stringSlice)

        if err != nil && (len(nowValue) > 0) {
          return err
        }

        sliceValue := reflect.ValueOf(stringSlice)
        nowField.Set(sliceValue)
      }

    default:
    }
  }

  return nil

}
<commit_msg>增加权限常量<commit_after>package models

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strings"
	"sync"

	"github.com/astaxie/beego"
	"github.com/siddontang/ledisdb/config"
	"github.com/siddontang/ledisdb/ledis"

	"github.com/dockercn/wharf/utils"
)

const (
	GLOBAL_USER_INDEX         = "GLOBAL_USER_INDEX"
	GLOBAL_REPOSITORY_INDEX   = "GLOBAL_REPOSITORY_INDEX"
	GLOBAL_ORGANIZATION_INDEX = "GLOBAL_ORGANIZATION_INDEX"
	GLOBAL_TEAM_INDEX         = "GLOBAL_TEAM_INDEX"
	GLOBAL_IMAGE_INDEX        = "GLOBAL_IMAGE_INDEX"
	GLOBAL_TAG_INDEX          = "GLOBAL_TAG_INDEX"
	GLOBAL_COMPOSE_INDEX      = "GLOBAL_COMPOSE_INDEX"
	GLOBAL_ADMIN_INDEX        = "GLOBAL_ADMIN_INDEX"
	GLOBAL_PRIVILEGE_INDEX    = "GLOBAL_PRIVILEGE_INDEX"
)

var (
	ledisOnce sync.Once
	nowLedis  *ledis.Ledis
	LedisDB   *ledis.DB
)

func InitDb() {
	initLedisFunc := func() {
		cfg := new(config.Config)
		cfg.DataDir = beego.AppConfig.String("ledisdb::DataDir")
		var err error
		nowLedis, err = ledis.Open(cfg)
		if err != nil {
			println(err.Error())
			panic(err)
		}
	}

	ledisOnce.Do(initLedisFunc)

	db, _ := beego.AppConfig.Int("ledisdb::DB")

	LedisDB, _ = nowLedis.Select(db)
}

func GetUUID(ObjectType, Object string) (UUID []byte, err error) {

	index := ""

	switch strings.TrimSpace(ObjectType) {

	case "user":
		index = GLOBAL_USER_INDEX
	case "repository":
		index = GLOBAL_REPOSITORY_INDEX
	case "organization":
		index = GLOBAL_ORGANIZATION_INDEX
	case "team":
		index = GLOBAL_TEAM_INDEX
	case "image":
		index = GLOBAL_IMAGE_INDEX
	case "tag":
		index = GLOBAL_TAG_INDEX
	case "compose":
		index = GLOBAL_COMPOSE_INDEX
	case "admin":
		index = GLOBAL_ADMIN_INDEX
	default:

	}

	if UUID, err = LedisDB.HGet([]byte(index), []byte(Object)); err != nil {
		return nil, err
	} else {
		return UUID, nil
	}

}

func Save(obj interface{}, key []byte) (err error) {

	s := reflect.TypeOf(obj).Elem()

	for i := 0; i < s.NumField(); i++ {

		value := reflect.ValueOf(obj).Elem().Field(s.Field(i).Index[0])

		switch value.Kind() {

		case reflect.String:
			if _, err := LedisDB.HSet(key, []byte(s.Field(i).Name), []byte(value.String())); err != nil {
				return err
			}

		case reflect.Bool:
			if _, err := LedisDB.HSet(key, []byte(s.Field(i).Name), utils.BoolToBytes(value.Bool())); err != nil {
				return err
			}

		case reflect.Int64:
			if _, err := LedisDB.HSet(key, []byte(s.Field(i).Name), utils.Int64ToBytes(value.Int())); err != nil {
				return err
			}

		case reflect.Slice:
			if "[]string" == value.Type().String() && !value.IsNil() {
				strJson := "["

				for i := 0; i < value.Len(); i++ {
					nowUUID := value.Index(i).String()
					if i != 0 {
						strJson += fmt.Sprintf(`,"%s"`, nowUUID)
					} else {
						strJson += fmt.Sprintf(`"%s"`, nowUUID)
					}
				}

				strJson += "]"

				if _, err := LedisDB.HSet(key, []byte(s.Field(i).Name), []byte(strJson)); err != nil {
					return err
				}
			}

		default:
		}

	}
	return nil
}

func Get(obj interface{}, UUID []byte) (err error) {

	nowTypeElem := reflect.ValueOf(obj).Elem()
	types := nowTypeElem.Type()

	for i := 0; i < nowTypeElem.NumField(); i++ {

		nowField := nowTypeElem.Field(i)
		nowFieldName := types.Field(i).Name

		switch nowField.Kind() {

		case reflect.String:
			nowValue, err := LedisDB.HGet(UUID, []byte(nowFieldName))
			nowField.SetString(string(nowValue))
			if err != nil {
				return err
			}

		case reflect.Bool:
			nowValue, err := LedisDB.HGet(UUID, []byte(nowFieldName))
			nowField.SetBool(utils.BytesToBool(nowValue))
			if err != nil {
				return err
			}

		case reflect.Int64:
			nowValue, err := LedisDB.HGet(UUID, []byte(nowFieldName))
			nowField.SetInt(utils.BytesToInt64(nowValue))
			if err != nil {
				return err
			}

		case reflect.Slice:
			if "[]string" == nowField.Type().String() {
				nowValue, err := LedisDB.HGet(UUID, []byte(nowFieldName))

				var stringSlice []string
				err = json.Unmarshal(nowValue, &stringSlice)

				if err != nil && (len(nowValue) > 0) {
					return err
				}

				sliceValue := reflect.ValueOf(stringSlice)
				nowField.Set(sliceValue)
			}

		default:
		}
	}

	return nil

}
<|endoftext|>


<commit_before>package raytracer

import (
	"gmacd/core"
	"gmacd/geom"
)

const MAX_TRACE_DEPTH = 6

func FindNearestIntersection(scene *geom.Scene, ray core.Ray) (prim geom.Primitive, result int, dist float64) {
	dist = 1000000.0

	// Find nearest intersection
	result = core.MISS
	for _, p := range scene.Primitives {
		if pResult, pDist := p.Intersects(ray, dist); pResult != core.MISS {
			prim = p
			result = pResult
			dist = pDist
		}
	}

	return prim, result, dist
}

func Raytrace(scene *geom.Scene, ray core.Ray, acc *core.ColourRGB, depth int, rIndex float64) (prim geom.Primitive, dist float64) {
	if depth > MAX_TRACE_DEPTH {
		return nil, 0.0
	}

	prim, _, dist = FindNearestIntersection(scene, ray)
	if prim == nil {
		return nil, 0
	}

	if prim.IsLight() {
		acc.Set(1.0, 1.0, 1.0)
		return prim, dist
	}

	// Determine intersection point
	intersectionPoint := ray.Origin.Add(ray.Dir.MulScalar(dist))

	// Trace lights
	for _, light := range scene.Primitives {
		if !light.IsLight() {
			continue
		}

		// Calculate diffuse shading
		l := light.LightCentre().Sub(intersectionPoint).Normal()
		n := prim.Normal(intersectionPoint)
		if prim.Material().Diffuse > 0 {
			dot := n.DotProduct(l)
			if dot > 0 {
				diff := dot * prim.Material().Diffuse
				acc.AddTo(prim.Material().Colour.MulScalar(diff).Mul(light.Material().Colour))
			}
		}
	}

	// Calculate reflection
	reflection := prim.Material().Reflection
	if reflection > 0 {
		n := prim.Normal(intersectionPoint)
		r := ray.Dir.Sub(n.MulScalar(2.0 * ray.Dir.DotProduct(n)))
		if depth < MAX_TRACE_DEPTH {
			reflectionRay := core.NewRay(
				intersectionPoint.Add(r.MulScalar(core.EPSILON)), r)
			reflectionColour := core.NewColourRGB(0, 0, 0)

			Raytrace(scene, reflectionRay, &reflectionColour, depth+1, rIndex)
			acc.AddTo(prim.Material().Colour.Mul(reflectionColour).MulScalar(reflection))
		}
	}

	return prim, dist
}
<commit_msg>Specular<commit_after>package raytracer

import (
	"gmacd/core"
	"gmacd/geom"
	"math"
)

const MAX_TRACE_DEPTH = 6

func FindNearestIntersection(scene *geom.Scene, ray core.Ray) (prim geom.Primitive, result int, dist float64) {
	dist = 1000000.0

	// Find nearest intersection
	result = core.MISS
	for _, p := range scene.Primitives {
		if pResult, pDist := p.Intersects(ray, dist); pResult != core.MISS {
			prim = p
			result = pResult
			dist = pDist
		}
	}

	return prim, result, dist
}

func Raytrace(scene *geom.Scene, ray core.Ray, acc *core.ColourRGB, depth int, rIndex float64) (prim geom.Primitive, dist float64) {
	if depth > MAX_TRACE_DEPTH {
		return nil, 0.0
	}

	prim, _, dist = FindNearestIntersection(scene, ray)
	if prim == nil {
		return nil, 0
	}

	if prim.IsLight() {
		acc.Set(1.0, 1.0, 1.0)
		return prim, dist
	}

	// Determine intersection point
	intersectionPoint := ray.Origin.Add(ray.Dir.MulScalar(dist))

	// Trace lights
	for _, light := range scene.Primitives {
		if !light.IsLight() {
			continue
		}

		shade := 1.0

		// Calculate diffuse shading
		l := light.LightCentre().Sub(intersectionPoint).Normal()
		n := prim.Normal(intersectionPoint)
		if prim.Material().Diffuse > 0 {
			dot := n.DotProduct(l)
			if dot > 0 {
				diff := dot * prim.Material().Diffuse
				acc.AddTo(prim.Material().Colour.MulScalar(diff).Mul(light.Material().Colour))
			}
		}

		// Specular
		specular := prim.Material().Specular()
		v := ray.Dir
		r := l.Sub(n.MulScalar(2.0 * l.DotProduct(n)))
		dot := v.DotProduct(r)
		if dot > 0 {
			specular := math.Pow(dot, 20) * specular * shade
			acc.AddTo(light.Material().Colour.MulScalar(specular))
		}
	}

	// Calculate reflection
	reflection := prim.Material().Reflection
	if reflection > 0 {
		n := prim.Normal(intersectionPoint)
		r := ray.Dir.Sub(n.MulScalar(2.0 * ray.Dir.DotProduct(n)))
		if depth < MAX_TRACE_DEPTH {
			reflectionRay := core.NewRay(
				intersectionPoint.Add(r.MulScalar(core.EPSILON)), r)
			reflectionColour := core.NewColourRGB(0, 0, 0)

			Raytrace(scene, reflectionRay, &reflectionColour, depth+1, rIndex)
			acc.AddTo(prim.Material().Colour.Mul(reflectionColour).MulScalar(reflection))
		}
	}

	return prim, dist
}
<|endoftext|>


<commit_before>// Package service uses the registry service
package service

import (
	"context"
	"time"

	"github.com/micro/go-micro/client"
	"github.com/micro/go-micro/registry"
	pb "github.com/micro/go-micro/registry/proto"
)

var (
	// The default service name
	DefaultService = "go.micro.service"
)

type serviceRegistry struct {
	opts registry.Options
	// name of the registry
	name string
	// address
	address []string
	// client to call registry
	client pb.RegistryService
}

func (s *serviceRegistry) callOpts() []client.CallOption {
	var opts []client.CallOption

	// set registry address
	if len(s.address) > 0 {
		opts = append(opts, client.WithAddress(s.address...))
	}

	// set timeout
	if s.opts.Timeout > time.Duration(0) {
		opts = append(opts, client.WithRequestTimeout(s.opts.Timeout))
	}

	return opts
}

func (s *serviceRegistry) Init(opts ...registry.Option) error {
	for _, o := range opts {
		o(&s.opts)
	}
	return nil
}

func (s *serviceRegistry) Options() registry.Options {
	return s.opts
}

func (s *serviceRegistry) Register(srv *registry.Service, opts ...registry.RegisterOption) error {
	var options registry.RegisterOptions
	for _, o := range opts {
		o(&options)
	}

	ctx := context.Background()
	if options.TTL.Nanoseconds() != 0.0 {
		ctx = context.WithValue(ctx, "register_ttl", options.TTL)
	}

	// register the service
	_, err := s.client.Register(ctx, ToProto(srv), s.callOpts()...)
	if err != nil {
		return err
	}

	return nil
}

func (s *serviceRegistry) Deregister(srv *registry.Service) error {
	// deregister the service
	_, err := s.client.Deregister(context.TODO(), ToProto(srv), s.callOpts()...)
	if err != nil {
		return err
	}
	return nil
}

func (s *serviceRegistry) GetService(name string) ([]*registry.Service, error) {
	rsp, err := s.client.GetService(context.TODO(), &pb.GetRequest{
		Service: name,
	}, s.callOpts()...)

	if err != nil {
		return nil, err
	}

	var services []*registry.Service
	for _, service := range rsp.Services {
		services = append(services, ToService(service))
	}
	return services, nil
}

func (s *serviceRegistry) ListServices() ([]*registry.Service, error) {
	rsp, err := s.client.ListServices(context.TODO(), &pb.ListRequest{}, s.callOpts()...)
	if err != nil {
		return nil, err
	}

	var services []*registry.Service
	for _, service := range rsp.Services {
		services = append(services, ToService(service))
	}

	return services, nil
}

func (s *serviceRegistry) Watch(opts ...registry.WatchOption) (registry.Watcher, error) {
	var options registry.WatchOptions
	for _, o := range opts {
		o(&options)
	}

	stream, err := s.client.Watch(context.TODO(), &pb.WatchRequest{
		Service: options.Service,
	}, s.callOpts()...)

	if err != nil {
		return nil, err
	}

	return newWatcher(stream), nil
}

func (s *serviceRegistry) String() string {
	return s.name
}

// NewRegistry returns a new registry service client
func NewRegistry(opts ...registry.Option) registry.Registry {
	var options registry.Options
	for _, o := range opts {
		o(&options)
	}

	// the registry address
	addrs := options.Addrs

	if len(addrs) == 0 {
		addrs = []string{"127.0.0.1:8000"}
	}

	// use mdns as a fall back in case its used
	mReg := registry.NewRegistry()

	// create new client with mdns
	cli := client.NewClient(
		client.Registry(mReg),
	)

	// service name
	// TODO: accept option
	name := DefaultService

	return &serviceRegistry{
		opts:    options,
		name:    name,
		address: addrs,
		client:  pb.NewRegistryService(name, cli),
	}
}
<commit_msg>Set registry TTL properly via protobuf Options<commit_after>// Package service uses the registry service
package service

import (
	"context"
	"time"

	"github.com/micro/go-micro/client"
	"github.com/micro/go-micro/registry"
	pb "github.com/micro/go-micro/registry/proto"
)

var (
	// The default service name
	DefaultService = "go.micro.service"
)

type serviceRegistry struct {
	opts registry.Options
	// name of the registry
	name string
	// address
	address []string
	// client to call registry
	client pb.RegistryService
}

func (s *serviceRegistry) callOpts() []client.CallOption {
	var opts []client.CallOption

	// set registry address
	if len(s.address) > 0 {
		opts = append(opts, client.WithAddress(s.address...))
	}

	// set timeout
	if s.opts.Timeout > time.Duration(0) {
		opts = append(opts, client.WithRequestTimeout(s.opts.Timeout))
	}

	return opts
}

func (s *serviceRegistry) Init(opts ...registry.Option) error {
	for _, o := range opts {
		o(&s.opts)
	}
	return nil
}

func (s *serviceRegistry) Options() registry.Options {
	return s.opts
}

func (s *serviceRegistry) Register(srv *registry.Service, opts ...registry.RegisterOption) error {
	var options registry.RegisterOptions
	for _, o := range opts {
		o(&options)
	}

	// encode srv into protobuf and pack Register TTL into it
	pbSrv := ToProto(srv)
	pbSrv.Options.Ttl = int64(options.TTL.Seconds())

	// register the service
	_, err := s.client.Register(context.TODO(), pbSrv, s.callOpts()...)
	if err != nil {
		return err
	}

	return nil
}

func (s *serviceRegistry) Deregister(srv *registry.Service) error {
	// deregister the service
	_, err := s.client.Deregister(context.TODO(), ToProto(srv), s.callOpts()...)
	if err != nil {
		return err
	}
	return nil
}

func (s *serviceRegistry) GetService(name string) ([]*registry.Service, error) {
	rsp, err := s.client.GetService(context.TODO(), &pb.GetRequest{
		Service: name,
	}, s.callOpts()...)

	if err != nil {
		return nil, err
	}

	var services []*registry.Service
	for _, service := range rsp.Services {
		services = append(services, ToService(service))
	}
	return services, nil
}

func (s *serviceRegistry) ListServices() ([]*registry.Service, error) {
	rsp, err := s.client.ListServices(context.TODO(), &pb.ListRequest{}, s.callOpts()...)
	if err != nil {
		return nil, err
	}

	var services []*registry.Service
	for _, service := range rsp.Services {
		services = append(services, ToService(service))
	}

	return services, nil
}

func (s *serviceRegistry) Watch(opts ...registry.WatchOption) (registry.Watcher, error) {
	var options registry.WatchOptions
	for _, o := range opts {
		o(&options)
	}

	stream, err := s.client.Watch(context.TODO(), &pb.WatchRequest{
		Service: options.Service,
	}, s.callOpts()...)

	if err != nil {
		return nil, err
	}

	return newWatcher(stream), nil
}

func (s *serviceRegistry) String() string {
	return s.name
}

// NewRegistry returns a new registry service client
func NewRegistry(opts ...registry.Option) registry.Registry {
	var options registry.Options
	for _, o := range opts {
		o(&options)
	}

	// the registry address
	addrs := options.Addrs

	if len(addrs) == 0 {
		addrs = []string{"127.0.0.1:8000"}
	}

	// use mdns as a fall back in case its used
	mReg := registry.NewRegistry()

	// create new client with mdns
	cli := client.NewClient(
		client.Registry(mReg),
	)

	// service name
	// TODO: accept option
	name := DefaultService

	return &serviceRegistry{
		opts:    options,
		name:    name,
		address: addrs,
		client:  pb.NewRegistryService(name, cli),
	}
}
<|endoftext|>


<commit_before>package admin

import (
	"context"
	"flag"
	"fmt"
	log "github.com/golang/glog"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/reflection"
	"google.golang.org/grpc/status"
	"net"
)

var (
	adminPort = flag.Int("adminPort", 9997, "Port of gRPC admin server.")
)

type server struct {
}

func (s *server) AddUser(ctx context.Context, req *AddUserRequest) (*AddUserResponse, error) {
	return nil, status.New(codes.Unimplemented, "not yet implemented").Err()
}

func (s *server) AddFeed(ctx context.Context, req *AddFeedRequest) (*AddFeedResponse, error) {
	return nil, status.New(codes.Unimplemented, "not yet implemented").Err()
}

func newServer() AdminServiceServer {
	s := &server{}
	return s
}

func Start(ctx context.Context) {
	log.Infof("Starting gRPC admin server.")

	s := grpc.NewServer()

	RegisterAdminServiceServer(s, newServer())
	reflection.Register(s)

	go func(s *grpc.Server) {
		select {
		case <-ctx.Done():
			log.Infof("Shutting down admin server.")
			s.GracefulStop()
		}
	}(s)

	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *adminPort))
	if err != nil {
		log.Warningf("failed to listen on admin port: %s", err)
		return
	}

	if err := s.Serve(lis); err != nil {
		log.Infof("%s", err)
	}
}
<commit_msg>core/admin: Minor refactor of stub gRPC implementation.<commit_after>package admin

import (
	"context"
	"flag"
	"fmt"
	log "github.com/golang/glog"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/reflection"
	"google.golang.org/grpc/status"
	"net"
)

var (
	adminPort = flag.Int("adminPort", 9997, "Port of gRPC admin server.")
)

type server struct {
}

func (s *server) AddUser(ctx context.Context, req *AddUserRequest) (*AddUserResponse, error) {
	return nil, status.Error(codes.Unimplemented, "not yet implemented")
}

func (s *server) AddFeed(ctx context.Context, req *AddFeedRequest) (*AddFeedResponse, error) {
	return nil, status.Error(codes.Unimplemented, "not yet implemented")
}

func newServer() AdminServiceServer {
	s := &server{}
	return s
}

func Start(ctx context.Context) {
	log.Infof("Starting gRPC admin server.")

	s := grpc.NewServer()

	RegisterAdminServiceServer(s, newServer())
	reflection.Register(s)

	go func(s *grpc.Server) {
		select {
		case <-ctx.Done():
			log.Infof("Shutting down admin server.")
			s.GracefulStop()
		}
	}(s)

	lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *adminPort))
	if err != nil {
		log.Warningf("failed to listen on admin port: %s", err)
		return
	}

	if err := s.Serve(lis); err != nil {
		log.Infof("%s", err)
	}
}
<|endoftext|>


<commit_before>package spvwallet

import (
	"github.com/btcsuite/btcd/chaincfg/chainhash"
	"github.com/btcsuite/btcd/peer"
	"github.com/btcsuite/btcd/wire"
	"time"
)

var (
	maxHash              *chainhash.Hash
	MAX_UNCONFIRMED_TIME time.Duration = time.Hour * 24 * 7
)

func init() {
	h, err := chainhash.NewHashFromStr("0000000000000000000000000000000000000000000000000000000000000000")
	if err != nil {
		log.Fatal(err)
	}
	maxHash = h
}

func (w *SPVWallet) startChainDownload(p *peer.Peer) {
	w.mutex.Lock()
	defer w.mutex.Unlock()
	if w.blockchain.ChainState() == SYNCING {
		height, _ := w.blockchain.db.Height()
		if height >= uint32(p.LastBlock()) {
			moar := w.PeerManager.CheckForMoreBlocks(height)
			if !moar {
				log.Info("Chain download complete")
				w.blockchain.SetChainState(WAITING)
				w.Rebroadcast()
				close(w.blockQueue)
			}
			return
		}
		gBlocks := wire.NewMsgGetBlocks(maxHash)
		hashes := w.blockchain.GetBlockLocatorHashes()
		gBlocks.BlockLocatorHashes = hashes
		p.QueueMessage(gBlocks, nil)
	}
}

func (w *SPVWallet) onMerkleBlock(p *peer.Peer, m *wire.MsgMerkleBlock) {
	if w.blockchain.ChainState() == SYNCING && w.PeerManager.DownloadPeer() != nil && w.PeerManager.DownloadPeer().ID() == p.ID() {
		queueHash := <-w.blockQueue
		headerHash := m.Header.BlockHash()
		if !headerHash.IsEqual(&queueHash) {
			log.Errorf("Peer%d is sending us blocks out of order", p.ID())
			p.Disconnect()
			return
		}
	}
	txids, err := checkMBlock(m)
	if err != nil {
		log.Errorf("Peer%d sent an invalid MerkleBlock", p.ID())
		p.Disconnect()
		return
	}
	newBlock, reorg, height, err := w.blockchain.CommitHeader(m.Header)
	if err != nil {
		log.Warning(err)
		return
	}
	if !newBlock {
		return
	}

	// We hit a reorg. Rollback the transactions and resync from the reorg point.
	if reorg != nil {
		err := w.txstore.processReorg(reorg.height)
		log.Error(err)
		w.blockchain.SetChainState(SYNCING)
		w.blockchain.db.Put(*reorg, true)
		go w.startChainDownload(p)
		return
	}

	for _, txid := range txids {
		w.mutex.Lock()
		w.toDownload[*txid] = int32(height)
		w.mutex.Unlock()
	}
	log.Debugf("Received Merkle Block %s at height %d\n", m.Header.BlockHash().String(), height)
	if len(w.blockQueue) == 0 && w.blockchain.ChainState() == SYNCING {
		go w.startChainDownload(p)
	}
	if w.blockchain.ChainState() == WAITING {
		txns, err := w.txstore.Txns().GetAll(false)
		if err != nil {
			log.Error(err)
			return
		}
		now := time.Now()
		for _, t := range txns {
			if now.After(t.Timestamp.Add(MAX_UNCONFIRMED_TIME)) && t.Height == int32(0) {
				log.Noticef("Marking tx as dead %s", t.Txid)
				h, err := chainhash.NewHashFromStr(t.Txid)
				if err != nil {
					log.Error(err)
					continue
				}
				err = w.txstore.markAsDead(*h)
				if err != nil {
					log.Error(err)
					continue
				}
			}
		}
	}
}

func (w *SPVWallet) onTx(p *peer.Peer, m *wire.MsgTx) {
	w.mutex.RLock()
	height := w.toDownload[m.TxHash()]
	w.mutex.RUnlock()
	hits, err := w.txstore.Ingest(m, height)
	if err != nil {
		log.Errorf("Error ingesting tx: %s\n", err.Error())
		return
	}
	if hits == 0 {
		log.Debugf("Tx %s from Peer%d had no hits, filter false positive.", m.TxHash().String(), p.ID())
		w.fPositives <- p
		return
	}
	w.updateFilterAndSend(p)
	log.Infof("Tx %s from Peer%d ingested and matches %d utxo/adrs.", m.TxHash().String(), p.ID(), hits)

	// FIXME: right now the hash stays in memory forever. We need to delete it but the way the code works,
	// FIXME: doing so will cause the height to get reset to zero if a peer relays the tx to us again.
}

func (w *SPVWallet) onInv(p *peer.Peer, m *wire.MsgInv) {
	go func() {
		defer func() {
			if err := recover(); err != nil {
				log.Error(err)
			}
		}()
		for _, inv := range m.InvList {
			switch inv.Type {
			case wire.InvTypeBlock:
				// Kind of lame to send separate getData messages but this allows us
				// to take advantage of the timeout on the upper layer. Otherwise we
				// need separate timeout handling.
				inv.Type = wire.InvTypeFilteredBlock
				gData := wire.NewMsgGetData()
				gData.AddInvVect(inv)
				p.QueueMessage(gData, nil)
				if w.blockchain.ChainState() == SYNCING && w.PeerManager.DownloadPeer() != nil && w.PeerManager.DownloadPeer().ID() == p.ID() {
					w.blockQueue <- inv.Hash
				}
			case wire.InvTypeTx:
				gData := wire.NewMsgGetData()
				gData.AddInvVect(inv)
				p.QueueMessage(gData, nil)
			default:
				continue
			}

		}
	}()
}

func (w *SPVWallet) onGetData(p *peer.Peer, m *wire.MsgGetData) {
	log.Debugf("Received getdata request from Peer%d\n", p.ID())
	var sent int32
	for _, thing := range m.InvList {
		if thing.Type == wire.InvTypeTx {
			tx, _, err := w.txstore.Txns().Get(thing.Hash)
			if err != nil {
				log.Errorf("Error getting tx %s: %s", thing.Hash.String(), err.Error())
			}
			p.QueueMessage(tx, nil)
			sent++
			continue
		}
		// didn't match, so it's not something we're responding to
		log.Debugf("We only respond to tx requests, ignoring")

	}
	log.Debugf("Sent %d of %d requested items to Peer%d", sent, len(m.InvList), p.ID())
}

func (w *SPVWallet) fPositiveHandler(quit chan int) {
	for {
		select {
		case peer := <-w.fPositives:
			w.mutex.RLock()
			falsePostives, _ := w.fpAccumulator[peer.ID()]
			w.mutex.RUnlock()
			falsePostives++
			if falsePostives > 7 {
				w.updateFilterAndSend(peer)
				log.Debugf("Reset %d false positives for Peer%d\n", falsePostives, peer.ID())
				// reset accumulator
				falsePostives = 0
			}
			w.mutex.Lock()
			w.fpAccumulator[peer.ID()] = falsePostives
			w.mutex.Unlock()
		case <-quit:
			break
		}
	}
}

func (w *SPVWallet) updateFilterAndSend(p *peer.Peer) {
	filt, err := w.txstore.GimmeFilter()
	if err != nil {
		log.Errorf("Error creating filter: %s\n", err.Error())
		return
	}
	// send filter
	p.QueueMessage(filt.MsgFilterLoad(), nil)
	log.Debugf("Sent filter to Peer%d\n", p.ID())
}

func (w *SPVWallet) Rebroadcast() {
	// get all unconfirmed txs
	invMsg, err := w.txstore.GetPendingInv()
	if err != nil {
		log.Errorf("Rebroadcast error: %s", err.Error())
	}
	if len(invMsg.InvList) == 0 { // nothing to broadcast, so don't
		return
	}
	for _, peer := range w.PeerManager.connectedPeers {
		peer.QueueMessage(invMsg, nil)
	}
}
<commit_msg>Check error before logging<commit_after>package spvwallet

import (
	"github.com/btcsuite/btcd/chaincfg/chainhash"
	"github.com/btcsuite/btcd/peer"
	"github.com/btcsuite/btcd/wire"
	"time"
)

var (
	maxHash              *chainhash.Hash
	MAX_UNCONFIRMED_TIME time.Duration = time.Hour * 24 * 7
)

func init() {
	h, err := chainhash.NewHashFromStr("0000000000000000000000000000000000000000000000000000000000000000")
	if err != nil {
		log.Fatal(err)
	}
	maxHash = h
}

func (w *SPVWallet) startChainDownload(p *peer.Peer) {
	w.mutex.Lock()
	defer w.mutex.Unlock()
	if w.blockchain.ChainState() == SYNCING {
		height, _ := w.blockchain.db.Height()
		if height >= uint32(p.LastBlock()) {
			moar := w.PeerManager.CheckForMoreBlocks(height)
			if !moar {
				log.Info("Chain download complete")
				w.blockchain.SetChainState(WAITING)
				w.Rebroadcast()
				close(w.blockQueue)
			}
			return
		}
		gBlocks := wire.NewMsgGetBlocks(maxHash)
		hashes := w.blockchain.GetBlockLocatorHashes()
		gBlocks.BlockLocatorHashes = hashes
		p.QueueMessage(gBlocks, nil)
	}
}

func (w *SPVWallet) onMerkleBlock(p *peer.Peer, m *wire.MsgMerkleBlock) {
	if w.blockchain.ChainState() == SYNCING && w.PeerManager.DownloadPeer() != nil && w.PeerManager.DownloadPeer().ID() == p.ID() {
		queueHash := <-w.blockQueue
		headerHash := m.Header.BlockHash()
		if !headerHash.IsEqual(&queueHash) {
			log.Errorf("Peer%d is sending us blocks out of order", p.ID())
			p.Disconnect()
			return
		}
	}
	txids, err := checkMBlock(m)
	if err != nil {
		log.Errorf("Peer%d sent an invalid MerkleBlock", p.ID())
		p.Disconnect()
		return
	}
	newBlock, reorg, height, err := w.blockchain.CommitHeader(m.Header)
	if err != nil {
		log.Warning(err)
		return
	}
	if !newBlock {
		return
	}

	// We hit a reorg. Rollback the transactions and resync from the reorg point.
	if reorg != nil {
		err := w.txstore.processReorg(reorg.height)
		if err != nil {
			log.Error(err)
		}
		w.blockchain.SetChainState(SYNCING)
		w.blockchain.db.Put(*reorg, true)
		go w.startChainDownload(p)
		return
	}

	for _, txid := range txids {
		w.mutex.Lock()
		w.toDownload[*txid] = int32(height)
		w.mutex.Unlock()
	}
	log.Debugf("Received Merkle Block %s at height %d\n", m.Header.BlockHash().String(), height)
	if len(w.blockQueue) == 0 && w.blockchain.ChainState() == SYNCING {
		go w.startChainDownload(p)
	}
	if w.blockchain.ChainState() == WAITING {
		txns, err := w.txstore.Txns().GetAll(false)
		if err != nil {
			log.Error(err)
			return
		}
		now := time.Now()
		for _, t := range txns {
			if now.After(t.Timestamp.Add(MAX_UNCONFIRMED_TIME)) && t.Height == int32(0) {
				log.Noticef("Marking tx as dead %s", t.Txid)
				h, err := chainhash.NewHashFromStr(t.Txid)
				if err != nil {
					log.Error(err)
					continue
				}
				err = w.txstore.markAsDead(*h)
				if err != nil {
					log.Error(err)
					continue
				}
			}
		}
	}
}

func (w *SPVWallet) onTx(p *peer.Peer, m *wire.MsgTx) {
	w.mutex.RLock()
	height := w.toDownload[m.TxHash()]
	w.mutex.RUnlock()
	hits, err := w.txstore.Ingest(m, height)
	if err != nil {
		log.Errorf("Error ingesting tx: %s\n", err.Error())
		return
	}
	if hits == 0 {
		log.Debugf("Tx %s from Peer%d had no hits, filter false positive.", m.TxHash().String(), p.ID())
		w.fPositives <- p
		return
	}
	w.updateFilterAndSend(p)
	log.Infof("Tx %s from Peer%d ingested and matches %d utxo/adrs.", m.TxHash().String(), p.ID(), hits)

	// FIXME: right now the hash stays in memory forever. We need to delete it but the way the code works,
	// FIXME: doing so will cause the height to get reset to zero if a peer relays the tx to us again.
}

func (w *SPVWallet) onInv(p *peer.Peer, m *wire.MsgInv) {
	go func() {
		defer func() {
			if err := recover(); err != nil {
				log.Error(err)
			}
		}()
		for _, inv := range m.InvList {
			switch inv.Type {
			case wire.InvTypeBlock:
				// Kind of lame to send separate getData messages but this allows us
				// to take advantage of the timeout on the upper layer. Otherwise we
				// need separate timeout handling.
				inv.Type = wire.InvTypeFilteredBlock
				gData := wire.NewMsgGetData()
				gData.AddInvVect(inv)
				p.QueueMessage(gData, nil)
				if w.blockchain.ChainState() == SYNCING && w.PeerManager.DownloadPeer() != nil && w.PeerManager.DownloadPeer().ID() == p.ID() {
					w.blockQueue <- inv.Hash
				}
			case wire.InvTypeTx:
				gData := wire.NewMsgGetData()
				gData.AddInvVect(inv)
				p.QueueMessage(gData, nil)
			default:
				continue
			}

		}
	}()
}

func (w *SPVWallet) onGetData(p *peer.Peer, m *wire.MsgGetData) {
	log.Debugf("Received getdata request from Peer%d\n", p.ID())
	var sent int32
	for _, thing := range m.InvList {
		if thing.Type == wire.InvTypeTx {
			tx, _, err := w.txstore.Txns().Get(thing.Hash)
			if err != nil {
				log.Errorf("Error getting tx %s: %s", thing.Hash.String(), err.Error())
			}
			p.QueueMessage(tx, nil)
			sent++
			continue
		}
		// didn't match, so it's not something we're responding to
		log.Debugf("We only respond to tx requests, ignoring")

	}
	log.Debugf("Sent %d of %d requested items to Peer%d", sent, len(m.InvList), p.ID())
}

func (w *SPVWallet) fPositiveHandler(quit chan int) {
	for {
		select {
		case peer := <-w.fPositives:
			w.mutex.RLock()
			falsePostives, _ := w.fpAccumulator[peer.ID()]
			w.mutex.RUnlock()
			falsePostives++
			if falsePostives > 7 {
				w.updateFilterAndSend(peer)
				log.Debugf("Reset %d false positives for Peer%d\n", falsePostives, peer.ID())
				// reset accumulator
				falsePostives = 0
			}
			w.mutex.Lock()
			w.fpAccumulator[peer.ID()] = falsePostives
			w.mutex.Unlock()
		case <-quit:
			break
		}
	}
}

func (w *SPVWallet) updateFilterAndSend(p *peer.Peer) {
	filt, err := w.txstore.GimmeFilter()
	if err != nil {
		log.Errorf("Error creating filter: %s\n", err.Error())
		return
	}
	// send filter
	p.QueueMessage(filt.MsgFilterLoad(), nil)
	log.Debugf("Sent filter to Peer%d\n", p.ID())
}

func (w *SPVWallet) Rebroadcast() {
	// get all unconfirmed txs
	invMsg, err := w.txstore.GetPendingInv()
	if err != nil {
		log.Errorf("Rebroadcast error: %s", err.Error())
	}
	if len(invMsg.InvList) == 0 { // nothing to broadcast, so don't
		return
	}
	for _, peer := range w.PeerManager.connectedPeers {
		peer.QueueMessage(invMsg, nil)
	}
}
<|endoftext|>


<commit_before>//
package main

/*
Packages must be imported:
    "core/common/page"
    "core/spider"
Pckages may be imported:
    "core/pipeline": scawler result persistent;
    "github.com/PuerkitoBio/goquery": html dom parser.
*/
import (
    "github.com/PuerkitoBio/goquery"
    "github.com/hu17889/go_spider/core/common/page"
    "github.com/hu17889/go_spider/core/pipeline"
    "github.com/hu17889/go_spider/core/spider"
    "strings"
)

type MyPageProcesser struct {
}

func NewMyPageProcesser() *MyPageProcesser {
    return &MyPageProcesser{}
}

// Parse html dom here and record the parse result that we want to Page.
// Package goquery (http://godoc.org/github.com/PuerkitoBio/goquery) is used to parse html.
func (this *MyPageProcesser) Process(p *page.Page) {
    if !p.IsSucc() {
        println(p.Errormsg())
        return
    }

    query := p.GetHtmlParser()
    var urls []string
    query.Find("h3[class='repo-list-name'] a").Each(func(i int, s *goquery.Selection) {
        href, _ := s.Attr("href")
        urls = append(urls, "http://github.com/"+href)
    })
    // these urls will be saved and crawed by other coroutines.
    p.AddTargetRequests(urls, "html")

    name := query.Find(".entry-title .author").Text()
    name = strings.Trim(name, " \t\n")
    repository := query.Find(".entry-title .js-current-repository").Text()
    repository = strings.Trim(repository, " \t\n")
    //readme, _ := query.Find("#readme").Html()
    if name == "" {
        p.SetSkip(true)
    }
    // the entity we want to save by Pipeline
    p.AddField("author", name)
    p.AddField("project", repository)
    //p.AddField("readme", readme)
}

func main() {
    // Spider input:
    //  PageProcesser ;
    //  Task name used in Pipeline for record;
    spider.NewSpider(NewMyPageProcesser(), "TaskName").
        AddUrl("https://github.com/hu17889?tab=repositories", "html"). // Start url, html is the responce type ("html" or "json" or "jsonp" or "text")
        AddPipeline(pipeline.NewPipelineConsole()).                    // Print result on screen
        SetThreadnum(3).                                               // Crawl request by three Coroutines
        Run()
}
<commit_msg>Update main.go<commit_after>//
package main

/*
Packages must be imported:
    "core/common/page"
    "core/spider"
Pckages may be imported:
    "core/pipeline": scawler result persistent;
    "github.com/PuerkitoBio/goquery": html dom parser.
*/
import (
    "github.com/PuerkitoBio/goquery"
    "github.com/hu17889/go_spider/core/common/page"
    "github.com/hu17889/go_spider/core/pipeline"
    "github.com/hu17889/go_spider/core/spider"
    "strings"
)

type MyPageProcesser struct {
}

func NewMyPageProcesser() *MyPageProcesser {
    return &MyPageProcesser{}
}

// Parse html dom here and record the parse result that we want to Page.
// Package goquery (http://godoc.org/github.com/PuerkitoBio/goquery) is used to parse html.
func (this *MyPageProcesser) Process(p *page.Page) {
    if !p.IsSucc() {
        println(p.Errormsg())
        return
    }

    query := p.GetHtmlParser()
    var urls []string
    query.Find("h3[class='repo-list-name'] a").Each(func(i int, s *goquery.Selection) {
        href, _ := s.Attr("href")
        urls = append(urls, "http://github.com/"+href)
    })
    // these urls will be saved and crawed by other coroutines.
    p.AddTargetRequests(urls, "html")

    name := query.Find(".entry-title .author").Text()
    name = strings.Trim(name, " \t\n")
    repository := query.Find(".entry-title .js-current-repository").Text()
    repository = strings.Trim(repository, " \t\n")
    //readme, _ := query.Find("#readme").Html()
    if name == "" {
        p.SetSkip(true)
    }
    // the entity we want to save by Pipeline
    p.AddField("author", name)
    p.AddField("project", repository)
    //p.AddField("readme", readme)
}

func (this *MyPageProcesser) Finish() {
    fmt.Printf("TODO:before end spider \r\n")
}

func main() {
    // Spider input:
    //  PageProcesser ;
    //  Task name used in Pipeline for record;
    spider.NewSpider(NewMyPageProcesser(), "TaskName").
        AddUrl("https://github.com/hu17889?tab=repositories", "html"). // Start url, html is the responce type ("html" or "json" or "jsonp" or "text")
        AddPipeline(pipeline.NewPipelineConsole()).                    // Print result on screen
        SetThreadnum(3).                                               // Crawl request by three Coroutines
        Run()
}
<|endoftext|>


<commit_before>// Copyright ©2012 The bíogo.external 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 muscle implements interaction with the MUSCLE multiple alignment tool.
// MUSCLE is available from http://www.drive5.com/muscle/
package muscle

import (
	"code.google.com/p/biogo.external"
	"os/exec"
	"text/template"
	"time"
)

type Log struct {
	File   string
	Append bool
}
type Muscle struct {
	// Usage: muscle -in <inputfile> -out <outputfile>
	//
	// Common options (for a complete list please see the User Guide):
	//
	//     -in <inputfile>    Input file in FASTA format (default stdin)
	//     -out <outputfile>  Output alignment in FASTA format (default stdout)
	//     -diags             Find diagonals (faster for similar sequences)
	//     -maxiters <n>      Maximum number of iterations (integer, default 16)
	//     -maxhours <h>      Maximum time to iterate in hours (default no limit)
	//     -html              Write output in HTML format (default FASTA)
	//     -msf               Write output in GCG MSF format (default FASTA)
	//     -clw               Write output in CLUSTALW format (default FASTA)
	//     -clwstrict         As -clw, with 'CLUSTAL W (1.81)' header
	//     -log[a] <logfile>  Log to file (append if -loga, overwrite if -log)
	//     -quiet             Do not write progress messages to stderr
	//     -version           Display version information and exit
	//
	// Without refinement (very fast, avg accuracy similar to T-Coffee): -maxiters 2
	// Fastest possible (amino acids): -maxiters 1 -diags -sv -distance1 kbit20_3
	// Fastest possible (nucleotides): -maxiters 1 -diags
	Cmd string `buildarg:"{{if .}}{{.}}{{else}}muscle{{end}}"` // muscle

	// Files:
	InFile  string `buildarg:"{{if .}}-in{{split}}{{.}}{{end}}"`                                // -in <inputfile>
	OutFile string `buildarg:"{{if .}}-out{{split}}{{.}}{{end}}"`                               // -out <outputfile>
	Log     Log    `buildarg:"{{if .File}}-log{{if .Append}}a{{end}}{{split}}{{.File}}{{end}}"` // -log[a] <logfile>
	Quiet   bool   `buildarg:"{{if .}}-quiet{{end}}"`                                           // -quiet

	// Formatting:
	Html          bool `buildarg:"{{if .}}-html{{end}}"`      // -html
	Msf           bool `buildarg:"{{if .}}-msf{{end}}"`       // -msf
	Clustal       bool `buildarg:"{{if .}}-clw{{end}}"`       // -clw
	ClustalStrict bool `buildarg:"{{if .}}-clwstrict{{end}}"` // -clwstrict

	// Common options:
	FindDiagonals bool          `buildarg:"{{if .}}-diags{{end}}"`                        // -diags
	MaxIterations int           `buildarg:"{{if .}}-maxiters{{split}}{{.}}{{end}}"`       // -maxiters <n>
	MaxDuration   time.Duration `buildarg:"{{if .}}-maxhours{{split}}{{hours .}}{{end}}"` // -maxhours <h>

	// Other value options (see MUSCLE user guide):
	// Gleaned from user guide - may not reflect reality.
	AnchorSpacing   int     `buildarg:"{{if .}}-anchorspacing{{split}}{{.}}{{end}}"`   // -anchorspacing <n>
	Center          float64 `buildarg:"{{if .}}-center{{split}}{{.}}{{end}}"`          // -center <f.>
	Cluster1        string  `buildarg:"{{if .}}-cluster1{{split}}{{.}}{{end}}"`        // -cluster1 "upgma|upgma|neighborjoining"
	Cluster2        string  `buildarg:"{{if .}}-cluster2{{split}}{{.}}{{end}}"`        // -cluster2 "upgma|upgma|neighborjoining"
	ClustalOut      string  `buildarg:"{{if .}}-clwout{{split}}{{.}}{{end}}"`          // -clwout <file>
	DiagonalBreak   int     `buildarg:"{{if .}}-diagbreak{{split}}{{.}}{{end}}"`       // -diagbreak <n>
	DiagonalLength  int     `buildarg:"{{if .}}-diaglength{{split}}{{.}}{{end}}"`      // -diaglength <n>
	DiagonalMargin  int     `buildarg:"{{if .}}-diagmargin{{split}}{{.}}{{end}}"`      // -diagmargin <n>
	Distance1       string  `buildarg:"{{if .}}-distance1{{split}}{{.}}{{end}}"`       // -distance1 "kmer6_6|kmer20_3|kmer20_4|kbit20_3|kmer4_6"
	Distance2       string  `buildarg:"{{if .}}-distance2{{split}}{{.}}{{end}}"`       // -distance2 "pctid_kimura|pctid_log"
	FastaOut        string  `buildarg:"{{if .}}-fastaout{{split}}{{.}}{{end}}"`        // -fastaout <file>
	GapOpen         float64 `buildarg:"{{if .}}-gapopen{{split}}{{.}}{{end}}"`         // -gapopen <f.>
	GapExtend       float64 `buildarg:"{{if .}}-gapextend{{split}}{{.}}{{end}}"`       // -gapextend <f.>
	HydroWindow     int     `buildarg:"{{if .}}-hydro{{split}}{{.}}{{end}}"`           // -hydro <n>
	HydroFactor     float64 `buildarg:"{{if .}}-hydrofactor{{split}}{{.}}{{end}}"`     // -hydrofactor <f.>
	In1             string  `buildarg:"{{if .}}-in1{{split}}{{.}}{{end}}"`             // -in1 <file>
	In2             string  `buildarg:"{{if .}}-in2{{split}}{{.}}{{end}}"`             // -in2 <file>
	Matrix          string  `buildarg:"{{if .}}-matrix{{split}}{{.}}{{end}}"`          // -matrix <file>
	MaxTrees        int     `buildarg:"{{if .}}-maxtrees{{split}}{{.}}{{end}}"`        // -maxtrees <n>
	MinBestColScore float64 `buildarg:"{{if .}}-minbestcolscore{{split}}{{.}}{{end}}"` // -minbestcolscore <f.>
	MinSmoothScore  float64 `buildarg:"{{if .}}-minsmoothscore{{split}}{{.}}{{end}}"`  // -minsmoothscore <f.>
	MsaOut          string  `buildarg:"{{if .}}-msaout{{split}}{{.}}{{end}}"`          // -msaout <file>
	ObjectiveScore  string  `buildarg:"{{if .}}-objscore{{split}}{{.}}{{end}}"`        // -objscore "sp|ps|dp|xp|spf|spm"
	PhyInterOut     string  `buildarg:"{{if .}}-phyiout{{split}}{{.}}{{end}}"`         // -phyiout <file>
	PhySequenOut    string  `buildarg:"{{if .}}-physout{{split}}{{.}}{{end}}"`         // -physout <file>
	RefineWindow    int     `buildarg:"{{if .}}-refinewindow{{split}}{{.}}{{end}}"`    // -refinewindow <n>
	Root1           string  `buildarg:"{{if .}}-root1{{split}}{{.}}{{end}}"`           // -root1 "pseudo|midlongestspan|minavgleafdist"
	Root2           string  `buildarg:"{{if .}}-root2{{split}}{{.}}{{end}}"`           // -root2 "pseudo|midlongestspan|minavgleafdist"
	ScoreFile       string  `buildarg:"{{if .}}-scorefile{{split}}{{.}}{{end}}"`       // -scorefile <file>
	SeqType         string  `buildarg:"{{if .}}-seqtype{{split}}{{.}}{{end}}"`         // -seqtype "protein|nucleo|auto"
	SmoothScoreCeil float64 `buildarg:"{{if .}}-smoothscoreceil{{split}}{{.}}{{end}}"` // -smoothscoreceil <f.>
	SmoothWindow    int     `buildarg:"{{if .}}-smoothwindow{{split}}{{.}}{{end}}"`    // -smoothwindow <n>
	SpScore         string  `buildarg:"{{if .}}-spscore{{split}}{{.}}{{end}}"`         // -spscore <file>
	Tree1           string  `buildarg:"{{if .}}-tree1{{split}}{{.}}{{end}}"`           // -tree1 <file>
	Tree2           string  `buildarg:"{{if .}}-tree2{{split}}{{.}}{{end}}"`           // -tree2 <file>
	UseTree         string  `buildarg:"{{if .}}-usetree{{split}}{{.}}{{end}}"`         // -usetree <file>
	Weight1         string  `buildarg:"{{if .}}-weight1{{split}}{{.}}{{end}}"`         // -weight1 "none|henikoff|henikoffpb|gsc|clustalw|threeway"
	Weight2         string  `buildarg:"{{if .}}-weight2{{split}}{{.}}{{end}}"`         // -weight2 "none|henikoff|henikoffpb|gsc|clustalw|threeway"

	// Other flag options (see MUSCLE user guide):
	// Gleaned from user guide - may not reflect reality.
	Anchors        bool `buildarg:"{{if .}}-anchors{{end}}"`   // -anchors
	Brenner        bool `buildarg:"{{if .}}-brenner{{end}}"`   // -brenner
	Cluster        bool `buildarg:"{{if .}}-cluster{{end}}"`   // -cluster
	Dimer          bool `buildarg:"{{if .}}-dimer{{end}}"`     // -dimer
	Core           bool `buildarg:"{{if .}}-core{{end}}"`      // -core
	Diags1         bool `buildarg:"{{if .}}-diags1{{end}}"`    // -diags1
	Diags2         bool `buildarg:"{{if .}}-diags2{{end}}"`    // -diags2
	Fasta          bool `buildarg:"{{if .}}-fasta{{end}}"`     // -fasta
	Group          bool `buildarg:"{{if .}}-group{{end}}"`     // -group
	LogExpectation bool `buildarg:"{{if .}}-le{{end}}"`        // -le
	NoAnchors      bool `buildarg:"{{if .}}-noanchors{{end}}"` // -noanchors
	NoCore         bool `buildarg:"{{if .}}-nocore{{end}}"`    // -nocore
	PhylipInter    bool `buildarg:"{{if .}}-phyi{{end}}"`      // -phyi
	PhylipSequen   bool `buildarg:"{{if .}}-phys{{end}}"`      // -phys
	Profile        bool `buildarg:"{{if .}}-profile{{end}}"`   // -profile
	Refine         bool `buildarg:"{{if .}}-refine{{end}}"`    // -refine
	RefineByWindow bool `buildarg:"{{if .}}-refinew{{end}}"`   // -refinew
	SumOfPairsProt bool `buildarg:"{{if .}}-sp{{end}}"`        // -sp
	PPScore        bool `buildarg:"{{if .}}-ppscore{{end}}"`   // -ppscore
	SumOfPairsNuc  bool `buildarg:"{{if .}}-spn{{end}}"`       // -spn
	SumOfPairsProf bool `buildarg:"{{if .}}-sv{{end}}"`        // -sv
	verbose        bool `buildarg:"{{if .}}-verbose{{end}}"`   // -verbose
}

func hours(d time.Duration) float64 {
	return d.Hours()
}

func (m Muscle) BuildCommand() (*exec.Cmd, error) {
	cl := external.Must(external.Build(m, template.FuncMap{"hours": hours}))
	return exec.Command(cl[0], cl[1:]...), nil
}
<commit_msg>Option should be exported<commit_after>// Copyright ©2012 The bíogo.external 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 muscle implements interaction with the MUSCLE multiple alignment tool.
// MUSCLE is available from http://www.drive5.com/muscle/
package muscle

import (
	"code.google.com/p/biogo.external"
	"os/exec"
	"text/template"
	"time"
)

type Log struct {
	File   string
	Append bool
}
type Muscle struct {
	// Usage: muscle -in <inputfile> -out <outputfile>
	//
	// Common options (for a complete list please see the User Guide):
	//
	//     -in <inputfile>    Input file in FASTA format (default stdin)
	//     -out <outputfile>  Output alignment in FASTA format (default stdout)
	//     -diags             Find diagonals (faster for similar sequences)
	//     -maxiters <n>      Maximum number of iterations (integer, default 16)
	//     -maxhours <h>      Maximum time to iterate in hours (default no limit)
	//     -html              Write output in HTML format (default FASTA)
	//     -msf               Write output in GCG MSF format (default FASTA)
	//     -clw               Write output in CLUSTALW format (default FASTA)
	//     -clwstrict         As -clw, with 'CLUSTAL W (1.81)' header
	//     -log[a] <logfile>  Log to file (append if -loga, overwrite if -log)
	//     -quiet             Do not write progress messages to stderr
	//     -version           Display version information and exit
	//
	// Without refinement (very fast, avg accuracy similar to T-Coffee): -maxiters 2
	// Fastest possible (amino acids): -maxiters 1 -diags -sv -distance1 kbit20_3
	// Fastest possible (nucleotides): -maxiters 1 -diags
	Cmd string `buildarg:"{{if .}}{{.}}{{else}}muscle{{end}}"` // muscle

	// Files:
	InFile  string `buildarg:"{{if .}}-in{{split}}{{.}}{{end}}"`                                // -in <inputfile>
	OutFile string `buildarg:"{{if .}}-out{{split}}{{.}}{{end}}"`                               // -out <outputfile>
	Log     Log    `buildarg:"{{if .File}}-log{{if .Append}}a{{end}}{{split}}{{.File}}{{end}}"` // -log[a] <logfile>
	Quiet   bool   `buildarg:"{{if .}}-quiet{{end}}"`                                           // -quiet

	// Formatting:
	Html          bool `buildarg:"{{if .}}-html{{end}}"`      // -html
	Msf           bool `buildarg:"{{if .}}-msf{{end}}"`       // -msf
	Clustal       bool `buildarg:"{{if .}}-clw{{end}}"`       // -clw
	ClustalStrict bool `buildarg:"{{if .}}-clwstrict{{end}}"` // -clwstrict

	// Common options:
	FindDiagonals bool          `buildarg:"{{if .}}-diags{{end}}"`                        // -diags
	MaxIterations int           `buildarg:"{{if .}}-maxiters{{split}}{{.}}{{end}}"`       // -maxiters <n>
	MaxDuration   time.Duration `buildarg:"{{if .}}-maxhours{{split}}{{hours .}}{{end}}"` // -maxhours <h>

	// Other value options (see MUSCLE user guide):
	// Gleaned from user guide - may not reflect reality.
	AnchorSpacing   int     `buildarg:"{{if .}}-anchorspacing{{split}}{{.}}{{end}}"`   // -anchorspacing <n>
	Center          float64 `buildarg:"{{if .}}-center{{split}}{{.}}{{end}}"`          // -center <f.>
	Cluster1        string  `buildarg:"{{if .}}-cluster1{{split}}{{.}}{{end}}"`        // -cluster1 "upgma|upgma|neighborjoining"
	Cluster2        string  `buildarg:"{{if .}}-cluster2{{split}}{{.}}{{end}}"`        // -cluster2 "upgma|upgma|neighborjoining"
	ClustalOut      string  `buildarg:"{{if .}}-clwout{{split}}{{.}}{{end}}"`          // -clwout <file>
	DiagonalBreak   int     `buildarg:"{{if .}}-diagbreak{{split}}{{.}}{{end}}"`       // -diagbreak <n>
	DiagonalLength  int     `buildarg:"{{if .}}-diaglength{{split}}{{.}}{{end}}"`      // -diaglength <n>
	DiagonalMargin  int     `buildarg:"{{if .}}-diagmargin{{split}}{{.}}{{end}}"`      // -diagmargin <n>
	Distance1       string  `buildarg:"{{if .}}-distance1{{split}}{{.}}{{end}}"`       // -distance1 "kmer6_6|kmer20_3|kmer20_4|kbit20_3|kmer4_6"
	Distance2       string  `buildarg:"{{if .}}-distance2{{split}}{{.}}{{end}}"`       // -distance2 "pctid_kimura|pctid_log"
	FastaOut        string  `buildarg:"{{if .}}-fastaout{{split}}{{.}}{{end}}"`        // -fastaout <file>
	GapOpen         float64 `buildarg:"{{if .}}-gapopen{{split}}{{.}}{{end}}"`         // -gapopen <f.>
	GapExtend       float64 `buildarg:"{{if .}}-gapextend{{split}}{{.}}{{end}}"`       // -gapextend <f.>
	HydroWindow     int     `buildarg:"{{if .}}-hydro{{split}}{{.}}{{end}}"`           // -hydro <n>
	HydroFactor     float64 `buildarg:"{{if .}}-hydrofactor{{split}}{{.}}{{end}}"`     // -hydrofactor <f.>
	In1             string  `buildarg:"{{if .}}-in1{{split}}{{.}}{{end}}"`             // -in1 <file>
	In2             string  `buildarg:"{{if .}}-in2{{split}}{{.}}{{end}}"`             // -in2 <file>
	Matrix          string  `buildarg:"{{if .}}-matrix{{split}}{{.}}{{end}}"`          // -matrix <file>
	MaxTrees        int     `buildarg:"{{if .}}-maxtrees{{split}}{{.}}{{end}}"`        // -maxtrees <n>
	MinBestColScore float64 `buildarg:"{{if .}}-minbestcolscore{{split}}{{.}}{{end}}"` // -minbestcolscore <f.>
	MinSmoothScore  float64 `buildarg:"{{if .}}-minsmoothscore{{split}}{{.}}{{end}}"`  // -minsmoothscore <f.>
	MsaOut          string  `buildarg:"{{if .}}-msaout{{split}}{{.}}{{end}}"`          // -msaout <file>
	ObjectiveScore  string  `buildarg:"{{if .}}-objscore{{split}}{{.}}{{end}}"`        // -objscore "sp|ps|dp|xp|spf|spm"
	PhyInterOut     string  `buildarg:"{{if .}}-phyiout{{split}}{{.}}{{end}}"`         // -phyiout <file>
	PhySequenOut    string  `buildarg:"{{if .}}-physout{{split}}{{.}}{{end}}"`         // -physout <file>
	RefineWindow    int     `buildarg:"{{if .}}-refinewindow{{split}}{{.}}{{end}}"`    // -refinewindow <n>
	Root1           string  `buildarg:"{{if .}}-root1{{split}}{{.}}{{end}}"`           // -root1 "pseudo|midlongestspan|minavgleafdist"
	Root2           string  `buildarg:"{{if .}}-root2{{split}}{{.}}{{end}}"`           // -root2 "pseudo|midlongestspan|minavgleafdist"
	ScoreFile       string  `buildarg:"{{if .}}-scorefile{{split}}{{.}}{{end}}"`       // -scorefile <file>
	SeqType         string  `buildarg:"{{if .}}-seqtype{{split}}{{.}}{{end}}"`         // -seqtype "protein|nucleo|auto"
	SmoothScoreCeil float64 `buildarg:"{{if .}}-smoothscoreceil{{split}}{{.}}{{end}}"` // -smoothscoreceil <f.>
	SmoothWindow    int     `buildarg:"{{if .}}-smoothwindow{{split}}{{.}}{{end}}"`    // -smoothwindow <n>
	SpScore         string  `buildarg:"{{if .}}-spscore{{split}}{{.}}{{end}}"`         // -spscore <file>
	Tree1           string  `buildarg:"{{if .}}-tree1{{split}}{{.}}{{end}}"`           // -tree1 <file>
	Tree2           string  `buildarg:"{{if .}}-tree2{{split}}{{.}}{{end}}"`           // -tree2 <file>
	UseTree         string  `buildarg:"{{if .}}-usetree{{split}}{{.}}{{end}}"`         // -usetree <file>
	Weight1         string  `buildarg:"{{if .}}-weight1{{split}}{{.}}{{end}}"`         // -weight1 "none|henikoff|henikoffpb|gsc|clustalw|threeway"
	Weight2         string  `buildarg:"{{if .}}-weight2{{split}}{{.}}{{end}}"`         // -weight2 "none|henikoff|henikoffpb|gsc|clustalw|threeway"

	// Other flag options (see MUSCLE user guide):
	// Gleaned from user guide - may not reflect reality.
	Anchors        bool `buildarg:"{{if .}}-anchors{{end}}"`   // -anchors
	Brenner        bool `buildarg:"{{if .}}-brenner{{end}}"`   // -brenner
	Cluster        bool `buildarg:"{{if .}}-cluster{{end}}"`   // -cluster
	Dimer          bool `buildarg:"{{if .}}-dimer{{end}}"`     // -dimer
	Core           bool `buildarg:"{{if .}}-core{{end}}"`      // -core
	Diags1         bool `buildarg:"{{if .}}-diags1{{end}}"`    // -diags1
	Diags2         bool `buildarg:"{{if .}}-diags2{{end}}"`    // -diags2
	Fasta          bool `buildarg:"{{if .}}-fasta{{end}}"`     // -fasta
	Group          bool `buildarg:"{{if .}}-group{{end}}"`     // -group
	LogExpectation bool `buildarg:"{{if .}}-le{{end}}"`        // -le
	NoAnchors      bool `buildarg:"{{if .}}-noanchors{{end}}"` // -noanchors
	NoCore         bool `buildarg:"{{if .}}-nocore{{end}}"`    // -nocore
	PhylipInter    bool `buildarg:"{{if .}}-phyi{{end}}"`      // -phyi
	PhylipSequen   bool `buildarg:"{{if .}}-phys{{end}}"`      // -phys
	Profile        bool `buildarg:"{{if .}}-profile{{end}}"`   // -profile
	Refine         bool `buildarg:"{{if .}}-refine{{end}}"`    // -refine
	RefineByWindow bool `buildarg:"{{if .}}-refinew{{end}}"`   // -refinew
	SumOfPairsProt bool `buildarg:"{{if .}}-sp{{end}}"`        // -sp
	PPScore        bool `buildarg:"{{if .}}-ppscore{{end}}"`   // -ppscore
	SumOfPairsNuc  bool `buildarg:"{{if .}}-spn{{end}}"`       // -spn
	SumOfPairsProf bool `buildarg:"{{if .}}-sv{{end}}"`        // -sv
	Verbose        bool `buildarg:"{{if .}}-verbose{{end}}"`   // -verbose
}

func hours(d time.Duration) float64 {
	return d.Hours()
}

func (m Muscle) BuildCommand() (*exec.Cmd, error) {
	cl := external.Must(external.Build(m, template.FuncMap{"hours": hours}))
	return exec.Command(cl[0], cl[1:]...), nil
}
<|endoftext|>


<commit_before>package slackapi

import (
	"encoding/json"
	"testing"
)

func CheckResponse(t *testing.T, x interface{}, y string) {
	out, err := json.Marshal(x)
	if err != nil {
		t.Fatal("json fromat;", err)
	}
	if string(out) != y {
		t.Fatalf("invalid json response;\n- %s\n+ %s\n", y, out)
	}
}

func TestAPITest(t *testing.T) {
	s := New()
	x := s.APITest()
	y := `{"ok":true}`
	CheckResponse(t, x, y)
}

func TestAppsList(t *testing.T) {
	s := New()
	x := s.AppsList()
	y := `{"ok":false,"error":"not_authed","apps":null,"cache_ts":""}`
	CheckResponse(t, x, y)
}

func TestAuthRevoke(t *testing.T) {
	s := New()
	x := s.AuthRevoke()
	y := `{"ok":false,"error":"not_authed","revoked":false}`
	CheckResponse(t, x, y)
}

func TestAuthTest(t *testing.T) {
	s := New()
	x, err := s.AuthTest()
	if err != nil {
		t.Fatal(err)
	}
	y := `{"ok":false,"error":"not_authed","team":"","team_id":"","url":"","user":"","user_id":""}`
	CheckResponse(t, x, y)
}

func TestBotsInfo(t *testing.T) {
	s := New()
	x := s.BotsInfo("user")
	y := `{"ok":false,"error":"not_authed","bot":{"id":"","deleted":false,"name":"","icons":null}}`
	CheckResponse(t, x, y)
}

func TestChannelsID(t *testing.T) {
	s := New()
	x := s.ChannelsID("channel")
	y := `"channel"`
	CheckResponse(t, x, y)
}

func TestChannelsMyHistory(t *testing.T) {
	s := New()
	x := s.ChannelsMyHistory("channel", "1234567890")
	y := `{"Filtered":0,"Latest":"","Messages":null,"Oldest":"","Total":0,"Username":""}`
	CheckResponse(t, x, y)
}

func TestChannelsPurgeHistory(t *testing.T) {
	s := New()
	x := s.ChannelsPurgeHistory("channel", "1234567890", true)
	y := `{"Deleted":0,"NotDeleted":0,"Messages":null}`
	CheckResponse(t, x, y)
}

func TestChannelsSetRetention(t *testing.T) {
	s := New()
	x := s.ChannelsSetRetention("channel", 1)
	y := `{"ok":false,"error":"not_authed"}`
	CheckResponse(t, x, y)
}

func TestChannelsSuggestions(t *testing.T) {
	s := New()
	x := s.ChannelsSuggestions()
	y := `{"ok":false,"error":"not_authed","status":{"ok":false},"suggestion_types_tried":null}`
	CheckResponse(t, x, y)
}

func TestChatDelete(t *testing.T) {
	s := New()
	x := s.ChatDelete(MessageArgs{})
	y := `{"ok":false,"error":"not_authed","channel":"","text":"","ts":""}`
	CheckResponse(t, x, y)
}

func TestChatMeMessage(t *testing.T) {
	s := New()
	x := s.ChatMeMessage(MessageArgs{})
	y := `{"ok":false,"error":"not_authed","channel":"","text":"","ts":""}`
	CheckResponse(t, x, y)
}

func TestChatPostMessage(t *testing.T) {
	s := New()
	x := s.ChatPostMessage(MessageArgs{})
	y := `{"ok":false,"error":"not_authed","channel":"","ts":"","message":{"display_as_bot":false}}`
	CheckResponse(t, x, y)
}

func TestChatUpdate(t *testing.T) {
	s := New()
	x := s.ChatUpdate(MessageArgs{})
	y := `{"ok":false,"error":"not_authed","channel":"","ts":"","message":{"display_as_bot":false}}`
	CheckResponse(t, x, y)
}

func TestConversationsArchive(t *testing.T) {
	s := New()
	x := s.ConversationsArchive("channel")
	y := `{"ok":false,"error":"not_authed"}`
	CheckResponse(t, x, y)
}

func TestConversationsCreate(t *testing.T) {
	s := New()
	x := s.ConversationsCreate("channel")
	y := `{"ok":false,"error":"not_authed","channel":{"created":0,"creator":"","id":"","is_archived":false,"is_channel":false,"is_general":false,"is_group":false,"is_member":false,"is_mpim":false,"is_open":false,"last_read":"","latest":{"text":"","ts":"","type":"","user":""},"members":null,"name":"","name_normalized":"","num_members":0,"purpose":{"creator":"","last_set":0,"value":""},"topic":{"creator":"","last_set":0,"value":""},"unread_count":0,"unread_count_display":0}}`
	CheckResponse(t, x, y)
}

func TestConversationsHistory(t *testing.T) {
	s := New()
	x := s.ConversationsHistory(ConversationsHistoryInput{Channel: "channel", Latest: "1234567890"})
	y := `{"ok":false,"error":"not_authed","messages":null,"has_more":false,"pin_count":0,"unread_count_display":0,"response_metadata":{"next_cursor":""}}`
	CheckResponse(t, x, y)
}

func TestConversationsInfo(t *testing.T) {
	s := New()
	x := s.ConversationsInfo("channel")
	y := `{"ok":false,"error":"not_authed","channel":{"created":0,"creator":"","id":"","is_archived":false,"is_channel":false,"is_general":false,"is_group":false,"is_member":false,"is_mpim":false,"is_open":false,"last_read":"","latest":{"text":"","ts":"","type":"","user":""},"members":null,"name":"","name_normalized":"","num_members":0,"purpose":{"creator":"","last_set":0,"value":""},"topic":{"creator":"","last_set":0,"value":""},"unread_count":0,"unread_count_display":0}}`
	CheckResponse(t, x, y)
}

func TestConversationsJoin(t *testing.T) {
	s := New()
	x := s.ConversationsJoin("channel")
	y := `{"ok":false,"error":"not_authed","channel":{"created":0,"creator":"","id":"","is_archived":false,"is_channel":false,"is_general":false,"is_group":false,"is_member":false,"is_mpim":false,"is_open":false,"last_read":"","latest":{"text":"","ts":"","type":"","user":""},"members":null,"name":"","name_normalized":"","num_members":0,"purpose":{"creator":"","last_set":0,"value":""},"topic":{"creator":"","last_set":0,"value":""},"unread_count":0,"unread_count_display":0}}`
	CheckResponse(t, x, y)
}

func TestConversationsInvite(t *testing.T) {
	s := New()
	x := s.ConversationsInvite("channel", "user1", "user2", "user3")
	y := `{"ok":false,"error":"not_authed","channel":{"created":0,"creator":"","id":"","is_archived":false,"is_channel":false,"is_general":false,"is_group":false,"is_member":false,"is_mpim":false,"is_open":false,"last_read":"","latest":{"text":"","ts":"","type":"","user":""},"members":null,"name":"","name_normalized":"","num_members":0,"purpose":{"creator":"","last_set":0,"value":""},"topic":{"creator":"","last_set":0,"value":""},"unread_count":0,"unread_count_display":0}}`
	CheckResponse(t, x, y)
}

func TestConversationsKick(t *testing.T) {
	s := New()
	x := s.ConversationsKick("channel", "user")
	y := `{"ok":false,"error":"not_authed"}`
	CheckResponse(t, x, y)
}

func TestConversationsLeave(t *testing.T) {
	s := New()
	x := s.ConversationsLeave("channel")
	y := `{"ok":false,"error":"not_authed"}`
	CheckResponse(t, x, y)
}

func TestConversationsList(t *testing.T) {
	s := New()
	x := s.ConversationsList(ConversationsListInput{})
	y := `{"ok":false,"error":"not_authed","channels":null}`
	CheckResponse(t, x, y)
}

func TestConversationsRename(t *testing.T) {
	s := New()
	x := s.ConversationsRename("channel", "lennahc")
	y := `{"ok":false,"error":"not_authed","channel":{"created":0,"creator":"","id":"","is_archived":false,"is_channel":false,"is_general":false,"is_group":false,"is_member":false,"is_mpim":false,"is_open":false,"last_read":"","latest":{"text":"","ts":"","type":"","user":""},"members":null,"name":"","name_normalized":"","num_members":0,"purpose":{"creator":"","last_set":0,"value":""},"topic":{"creator":"","last_set":0,"value":""},"unread_count":0,"unread_count_display":0}}`
	CheckResponse(t, x, y)
}

func TestConversationsReplies(t *testing.T) {
	s := New()
	x := s.ConversationsReplies(ConversationsRepliesInput{Channel: "general", Timestamp: "1234567890.123456"})
	y := `{"ok":false,"error":"not_authed","messages":null,"has_more":false,"pin_count":0,"unread_count_display":0,"response_metadata":{"next_cursor":""}}`
	CheckResponse(t, x, y)
}

func TestConversationsSetPurpose(t *testing.T) {
	s := New()
	x := s.ConversationsSetPurpose("channel", "purpose")
	y := `{"ok":false,"error":"not_authed","purpose":""}`
	CheckResponse(t, x, y)
}

func TestConversationsSetTopic(t *testing.T) {
	s := New()
	x := s.ConversationsSetTopic("channel", "topic")
	y := `{"ok":false,"error":"not_authed","topic":""}`
	CheckResponse(t, x, y)
}

func TestConversationsUnarchive(t *testing.T) {
	s := New()
	x := s.ConversationsUnarchive("channel")
	y := `{"ok":false,"error":"not_authed"}`
	CheckResponse(t, x, y)
}

func TestDNDEndDnd(t *testing.T) {
	s := New()
	x := s.DNDEndDnd()
	y := `{"ok":false,"error":"not_authed"}`
	CheckResponse(t, x, y)
}

func TestDNDEndSnooze(t *testing.T) {
	s := New()
	x := s.DNDEndSnooze()
	y := `{"ok":false,"error":"not_authed","dnd_enabled":false,"next_dnd_start_ts":0,"next_dnd_end_ts":0,"snooze_debug":{}}`
	CheckResponse(t, x, y)
}
<commit_msg>Remove dnd.endSnooze unit test due to API uncertanties<commit_after>package slackapi

import (
	"encoding/json"
	"testing"
)

func CheckResponse(t *testing.T, x interface{}, y string) {
	out, err := json.Marshal(x)
	if err != nil {
		t.Fatal("json fromat;", err)
	}
	if string(out) != y {
		t.Fatalf("invalid json response;\n- %s\n+ %s\n", y, out)
	}
}

func TestAPITest(t *testing.T) {
	s := New()
	x := s.APITest()
	y := `{"ok":true}`
	CheckResponse(t, x, y)
}

func TestAppsList(t *testing.T) {
	s := New()
	x := s.AppsList()
	y := `{"ok":false,"error":"not_authed","apps":null,"cache_ts":""}`
	CheckResponse(t, x, y)
}

func TestAuthRevoke(t *testing.T) {
	s := New()
	x := s.AuthRevoke()
	y := `{"ok":false,"error":"not_authed","revoked":false}`
	CheckResponse(t, x, y)
}

func TestAuthTest(t *testing.T) {
	s := New()
	x, err := s.AuthTest()
	if err != nil {
		t.Fatal(err)
	}
	y := `{"ok":false,"error":"not_authed","team":"","team_id":"","url":"","user":"","user_id":""}`
	CheckResponse(t, x, y)
}

func TestBotsInfo(t *testing.T) {
	s := New()
	x := s.BotsInfo("user")
	y := `{"ok":false,"error":"not_authed","bot":{"id":"","deleted":false,"name":"","icons":null}}`
	CheckResponse(t, x, y)
}

func TestChannelsID(t *testing.T) {
	s := New()
	x := s.ChannelsID("channel")
	y := `"channel"`
	CheckResponse(t, x, y)
}

func TestChannelsMyHistory(t *testing.T) {
	s := New()
	x := s.ChannelsMyHistory("channel", "1234567890")
	y := `{"Filtered":0,"Latest":"","Messages":null,"Oldest":"","Total":0,"Username":""}`
	CheckResponse(t, x, y)
}

func TestChannelsPurgeHistory(t *testing.T) {
	s := New()
	x := s.ChannelsPurgeHistory("channel", "1234567890", true)
	y := `{"Deleted":0,"NotDeleted":0,"Messages":null}`
	CheckResponse(t, x, y)
}

func TestChannelsSetRetention(t *testing.T) {
	s := New()
	x := s.ChannelsSetRetention("channel", 1)
	y := `{"ok":false,"error":"not_authed"}`
	CheckResponse(t, x, y)
}

func TestChannelsSuggestions(t *testing.T) {
	s := New()
	x := s.ChannelsSuggestions()
	y := `{"ok":false,"error":"not_authed","status":{"ok":false},"suggestion_types_tried":null}`
	CheckResponse(t, x, y)
}

func TestChatDelete(t *testing.T) {
	s := New()
	x := s.ChatDelete(MessageArgs{})
	y := `{"ok":false,"error":"not_authed","channel":"","text":"","ts":""}`
	CheckResponse(t, x, y)
}

func TestChatMeMessage(t *testing.T) {
	s := New()
	x := s.ChatMeMessage(MessageArgs{})
	y := `{"ok":false,"error":"not_authed","channel":"","text":"","ts":""}`
	CheckResponse(t, x, y)
}

func TestChatPostMessage(t *testing.T) {
	s := New()
	x := s.ChatPostMessage(MessageArgs{})
	y := `{"ok":false,"error":"not_authed","channel":"","ts":"","message":{"display_as_bot":false}}`
	CheckResponse(t, x, y)
}

func TestChatUpdate(t *testing.T) {
	s := New()
	x := s.ChatUpdate(MessageArgs{})
	y := `{"ok":false,"error":"not_authed","channel":"","ts":"","message":{"display_as_bot":false}}`
	CheckResponse(t, x, y)
}

func TestConversationsArchive(t *testing.T) {
	s := New()
	x := s.ConversationsArchive("channel")
	y := `{"ok":false,"error":"not_authed"}`
	CheckResponse(t, x, y)
}

func TestConversationsCreate(t *testing.T) {
	s := New()
	x := s.ConversationsCreate("channel")
	y := `{"ok":false,"error":"not_authed","channel":{"created":0,"creator":"","id":"","is_archived":false,"is_channel":false,"is_general":false,"is_group":false,"is_member":false,"is_mpim":false,"is_open":false,"last_read":"","latest":{"text":"","ts":"","type":"","user":""},"members":null,"name":"","name_normalized":"","num_members":0,"purpose":{"creator":"","last_set":0,"value":""},"topic":{"creator":"","last_set":0,"value":""},"unread_count":0,"unread_count_display":0}}`
	CheckResponse(t, x, y)
}

func TestConversationsHistory(t *testing.T) {
	s := New()
	x := s.ConversationsHistory(ConversationsHistoryInput{Channel: "channel", Latest: "1234567890"})
	y := `{"ok":false,"error":"not_authed","messages":null,"has_more":false,"pin_count":0,"unread_count_display":0,"response_metadata":{"next_cursor":""}}`
	CheckResponse(t, x, y)
}

func TestConversationsInfo(t *testing.T) {
	s := New()
	x := s.ConversationsInfo("channel")
	y := `{"ok":false,"error":"not_authed","channel":{"created":0,"creator":"","id":"","is_archived":false,"is_channel":false,"is_general":false,"is_group":false,"is_member":false,"is_mpim":false,"is_open":false,"last_read":"","latest":{"text":"","ts":"","type":"","user":""},"members":null,"name":"","name_normalized":"","num_members":0,"purpose":{"creator":"","last_set":0,"value":""},"topic":{"creator":"","last_set":0,"value":""},"unread_count":0,"unread_count_display":0}}`
	CheckResponse(t, x, y)
}

func TestConversationsJoin(t *testing.T) {
	s := New()
	x := s.ConversationsJoin("channel")
	y := `{"ok":false,"error":"not_authed","channel":{"created":0,"creator":"","id":"","is_archived":false,"is_channel":false,"is_general":false,"is_group":false,"is_member":false,"is_mpim":false,"is_open":false,"last_read":"","latest":{"text":"","ts":"","type":"","user":""},"members":null,"name":"","name_normalized":"","num_members":0,"purpose":{"creator":"","last_set":0,"value":""},"topic":{"creator":"","last_set":0,"value":""},"unread_count":0,"unread_count_display":0}}`
	CheckResponse(t, x, y)
}

func TestConversationsInvite(t *testing.T) {
	s := New()
	x := s.ConversationsInvite("channel", "user1", "user2", "user3")
	y := `{"ok":false,"error":"not_authed","channel":{"created":0,"creator":"","id":"","is_archived":false,"is_channel":false,"is_general":false,"is_group":false,"is_member":false,"is_mpim":false,"is_open":false,"last_read":"","latest":{"text":"","ts":"","type":"","user":""},"members":null,"name":"","name_normalized":"","num_members":0,"purpose":{"creator":"","last_set":0,"value":""},"topic":{"creator":"","last_set":0,"value":""},"unread_count":0,"unread_count_display":0}}`
	CheckResponse(t, x, y)
}

func TestConversationsKick(t *testing.T) {
	s := New()
	x := s.ConversationsKick("channel", "user")
	y := `{"ok":false,"error":"not_authed"}`
	CheckResponse(t, x, y)
}

func TestConversationsLeave(t *testing.T) {
	s := New()
	x := s.ConversationsLeave("channel")
	y := `{"ok":false,"error":"not_authed"}`
	CheckResponse(t, x, y)
}

func TestConversationsList(t *testing.T) {
	s := New()
	x := s.ConversationsList(ConversationsListInput{})
	y := `{"ok":false,"error":"not_authed","channels":null}`
	CheckResponse(t, x, y)
}

func TestConversationsRename(t *testing.T) {
	s := New()
	x := s.ConversationsRename("channel", "lennahc")
	y := `{"ok":false,"error":"not_authed","channel":{"created":0,"creator":"","id":"","is_archived":false,"is_channel":false,"is_general":false,"is_group":false,"is_member":false,"is_mpim":false,"is_open":false,"last_read":"","latest":{"text":"","ts":"","type":"","user":""},"members":null,"name":"","name_normalized":"","num_members":0,"purpose":{"creator":"","last_set":0,"value":""},"topic":{"creator":"","last_set":0,"value":""},"unread_count":0,"unread_count_display":0}}`
	CheckResponse(t, x, y)
}

func TestConversationsReplies(t *testing.T) {
	s := New()
	x := s.ConversationsReplies(ConversationsRepliesInput{Channel: "general", Timestamp: "1234567890.123456"})
	y := `{"ok":false,"error":"not_authed","messages":null,"has_more":false,"pin_count":0,"unread_count_display":0,"response_metadata":{"next_cursor":""}}`
	CheckResponse(t, x, y)
}

func TestConversationsSetPurpose(t *testing.T) {
	s := New()
	x := s.ConversationsSetPurpose("channel", "purpose")
	y := `{"ok":false,"error":"not_authed","purpose":""}`
	CheckResponse(t, x, y)
}

func TestConversationsSetTopic(t *testing.T) {
	s := New()
	x := s.ConversationsSetTopic("channel", "topic")
	y := `{"ok":false,"error":"not_authed","topic":""}`
	CheckResponse(t, x, y)
}

func TestConversationsUnarchive(t *testing.T) {
	s := New()
	x := s.ConversationsUnarchive("channel")
	y := `{"ok":false,"error":"not_authed"}`
	CheckResponse(t, x, y)
}

func TestDNDEndDnd(t *testing.T) {
	s := New()
	x := s.DNDEndDnd()
	y := `{"ok":false,"error":"not_authed"}`
	CheckResponse(t, x, y)
}
<|endoftext|>


<commit_before>package bitio

import (
	"bytes"
	"fmt"
	"reflect"
	"testing"
)

type TestBitioIntByte struct {
	Val1 int `byte:"1"`
	Val2 int `byte:"2"`
	Val3 int `byte:"3"`
}

type TestBitioIntBit struct {
	Val1 int `bit:"3"`
	Val2 int `bit:"4"`
}

type TestBitioIntBitBorder struct {
	Val1 int `bit:"1"`
	Val2 int `bit:"14"`
	Val3 int `bit:"1"`
}

type TestBitioStringByte struct {
	Val1 int    `byte:"1"`
	Val2 string `byte:"3"`
}

type TestBitioStringBorder struct {
	Val1 int    `bit:"4"`
	Val2 string `byte:"1"`
	Val3 int    `bit:"4"`
}

type TestBitioSlice struct {
	Val1 []int `bit:"4" len:"2"`
	Val2 []int `bit:"4" len:"2"`
}

type readTester struct {
	src []byte
	dst interface{}
	ans map[string]interface{}
}

var readtests = []readTester{
	{
		src: []byte{0x0a, 0xff, 0x1c, 0xff, 0x01, 0x1c},
		dst: &TestBitioIntByte{},
		ans: map[string]interface{}{
			"Val1": 0x0a,
			"Val2": 0x1cff,
			"Val3": 0x1c01ff,
		},
	},
	{
		src: []byte{0xfa}, // 1111_1010
		dst: &TestBitioIntBit{},
		ans: map[string]interface{}{
			"Val1": 0x7, // 111
			"Val2": 0xd, // 1101
		},
	},
	{
		src: []byte{0x97, 0x97}, // 1001_0111 1001_0111
		dst: &TestBitioIntBitBorder{},
		ans: map[string]interface{}{
			"Val1": 0x1,    // 1
			"Val2": 0x0b2f, // 0010_1111 0010_11 [Little endian]
			"Val3": 0x1,    // 1
		},
	},
	{
		src: []byte{0x01, 'a', 'b', 'c'},
		dst: &TestBitioStringByte{},
		ans: map[string]interface{}{
			"Val1": 0x1,
			"Val2": "abc",
		},
	},
	{
		src: []byte{0x16, 0x11},
		dst: &TestBitioStringBorder{},
		ans: map[string]interface{}{
			"Val1": 0x1,
			"Val2": "a",
			"Val3": 0x1,
		},
	},
	{
		src: []byte{0xca, 0xca},
		dst: &TestBitioSlice{},
		ans: map[string]interface{}{
			"Val1": []int{0x0c, 0x0a},
			"Val2": []int{0x0c, 0x0a},
		},
	},
}

func TestReader(t *testing.T) {
	for _, test := range readtests {
		dst := test.dst
		if err := Read(dst, bytes.NewReader(test.src)); err != nil {
			t.Fatal("Read error:", err)
		}

		rv := reflect.ValueOf(dst).Elem()
		rt := rv.Type()

		for i := 0; i < rv.NumField(); i++ {
			v := rv.Field(i)
			f := rt.Field(i)
			if f.PkgPath != "" {
				continue
			}

			name := f.Name
			if tostrCompare(v, test.ans[name]) == false {
				t.Fatalf("%s read %v, want %v", name, v, test.ans[name])
			}
		}
	}
}

func tostrCompare(a, b interface{}) bool {
	as := fmt.Sprintf("%v", a)
	bs := fmt.Sprintf("%v", b)
	return as == bs
}
<commit_msg>testcase: clarify test error message<commit_after>package bitio

import (
	"bytes"
	"fmt"
	"reflect"
	"testing"
)

type TestBitioIntByte struct {
	Val1 int `byte:"1"`
	Val2 int `byte:"2"`
	Val3 int `byte:"3"`
}

type TestBitioIntBit struct {
	Val1 int `bit:"3"`
	Val2 int `bit:"4"`
}

type TestBitioIntBitBorder struct {
	Val1 int `bit:"1"`
	Val2 int `bit:"14"`
	Val3 int `bit:"1"`
}

type TestBitioStringByte struct {
	Val1 int    `byte:"1"`
	Val2 string `byte:"3"`
}

type TestBitioStringBorder struct {
	Val1 int    `bit:"4"`
	Val2 string `byte:"1"`
	Val3 int    `bit:"4"`
}

type TestBitioSlice struct {
	Val1 []int `bit:"4" len:"2"`
	Val2 []int `bit:"4" len:"2"`
}

type readTester struct {
	src []byte
	dst interface{}
	ans map[string]interface{}
}

var readtests = []readTester{
	{
		src: []byte{0x0a, 0xff, 0x1c, 0xff, 0x01, 0x1c},
		dst: &TestBitioIntByte{},
		ans: map[string]interface{}{
			"Val1": 0x0a,
			"Val2": 0x1cff,
			"Val3": 0x1c01ff,
		},
	},
	{
		src: []byte{0xfa}, // 1111_1010
		dst: &TestBitioIntBit{},
		ans: map[string]interface{}{
			"Val1": 0x7, // 111
			"Val2": 0xd, // 1101
		},
	},
	{
		src: []byte{0x97, 0x97}, // 1001_0111 1001_0111
		dst: &TestBitioIntBitBorder{},
		ans: map[string]interface{}{
			"Val1": 0x1,    // 1
			"Val2": 0x0b2f, // 0010_1111 0010_11 [Little endian]
			"Val3": 0x1,    // 1
		},
	},
	{
		src: []byte{0x01, 'a', 'b', 'c'},
		dst: &TestBitioStringByte{},
		ans: map[string]interface{}{
			"Val1": 0x1,
			"Val2": "abc",
		},
	},
	{
		src: []byte{0x16, 0x11},
		dst: &TestBitioStringBorder{},
		ans: map[string]interface{}{
			"Val1": 0x1,
			"Val2": "a",
			"Val3": 0x1,
		},
	},
	{
		src: []byte{0xca, 0xca},
		dst: &TestBitioSlice{},
		ans: map[string]interface{}{
			"Val1": []int{0x0c, 0x0a},
			"Val2": []int{0x0c, 0x0a},
		},
	},
}

func TestReader(t *testing.T) {
	for _, test := range readtests {
		dst := test.dst
		if err := Read(dst, bytes.NewReader(test.src)); err != nil {
			rt := reflect.TypeOf(test.dst)
			t.Fatalf("Read %v error: %v", rt, err)
		}

		rv := reflect.ValueOf(dst).Elem()
		rt := rv.Type()

		for i := 0; i < rv.NumField(); i++ {
			v := rv.Field(i)
			f := rt.Field(i)
			if f.PkgPath != "" {
				continue
			}

			name := f.Name
			if tostrCompare(v, test.ans[name]) == false {
				rt := reflect.TypeOf(test.dst)
				t.Fatalf("%v %s read %v, want %v", rt, name, v, test.ans[name])
			}
		}
	}
}

func tostrCompare(a, b interface{}) bool {
	as := fmt.Sprintf("%v", a)
	bs := fmt.Sprintf("%v", b)
	return as == bs
}
<|endoftext|>


<commit_before>package bitio

import (
	"bytes"
	"testing"
)

type TestStruct1 struct {
	Val1 int `byte:"1"`
	Val2 int `byte:"2"`
	Val3 int `byte:"3"`
}

func TestReader(t *testing.T) {
	data := []byte{0x0a, 0xff, 0x1c, 0xff, 0x01, 0x1c}
	vals := TestStruct1{}
	if err := Read(&vals, bytes.NewReader(data)); err != nil {
		t.Fatal("Read error:", err)
	}

	if vals.Val1 != 0x0a {
		t.Fatalf("Read got %x, want %x ", vals.Val1, 0x0a)
	}
	if vals.Val2 != 0x1cff {
		t.Fatalf("Read got %x, want %x ", vals.Val1, 0x1cff)
	}
	if vals.Val3 != 0x1c01ff {
		t.Fatalf("Read got %x, want %x ", vals.Val1, 0x1c01ff)
	}
}
<commit_msg>testcase cool update<commit_after>package bitio

import (
	"bytes"
	"fmt"
	"reflect"
	"testing"
)

type TestStruct1 struct {
	Val1 int `byte:"1"`
	Val2 int `byte:"2"`
	Val3 int `byte:"3"`
}

type readTester struct {
	src []byte
	dst interface{}
	ans map[string]interface{}
}

var readtests = []readTester{
	{
		src: []byte{0x0a, 0xff, 0x1c, 0xff, 0x01, 0x1c},
		dst: &TestStruct1{},
		ans: map[string]interface{}{
			"Val1": 0x0a,
			"Val2": 0x1cff,
			"Val3": 0x1c01ff,
		},
	},
}

func TestReader(t *testing.T) {
	for _, test := range readtests {
		dst := test.dst
		if err := Read(dst, bytes.NewReader(test.src)); err != nil {
			t.Fatal("Read error:", err)
		}

		rv := reflect.ValueOf(dst).Elem()
		rt := rv.Type()

		for i := 0; i < rv.NumField(); i++ {
			v := rv.Field(i)
			f := rt.Field(i)
			if f.PkgPath != "" {
				continue
			}

			name := f.Name
			if tostrCompare(v, test.ans[name]) == false {
				t.Fatalf("%s read %v, want %v", name, v, test.ans[name])
			}
		}
	}
}

func tostrCompare(a, b interface{}) bool {
	as := fmt.Sprintf("%v", a)
	bs := fmt.Sprintf("%v", b)
	return as == bs
}
<|endoftext|>


<commit_before>package testconfig

// A test configuration management package for loading
// and executing test data and expects data that can be
// configured for various test target environments.
import (
	"encoding/json"
	"io/ioutil"
	"os"

	"github.com/docker/machine/libmachine/log"
)

//
// test case objects
//  see testcases.go for test case methods
// { "name" : "PROTEST",
//   "cases": [
//      {
//        ...
//      },
// ]
//}
type TestConfig struct {
	Cases []TestCases `json:"cases,omitempty"` // "cases":[]
	Name  string      `json:"name,omitempty"`  // "name": "PROTEST",
}

// setup Testing
func (tc *TestConfig) NewTestConfig() *TestConfig {
	return &TestConfig{Name: "",
		Cases: []TestCases{}}
}

// UnMarshall json to data
func (tc *TestConfig) UnMarshallTestingConfig(json_data []byte) {
	tc.Cases = []TestCases{}
	if err := json.Unmarshal(json_data, &tc); err != nil {
		log.Errorf("Error with un-marshalling test config data: %s", err)
		os.Exit(1)
	}
}

// get config for testing
// Examples
// cv := tc.GetExpectsData("TestGetAPIVersion", "CurrentVersion")
// log.Infof("tc test_data -> %s\n", tc.EqualFaceI(cv, 120))
// log.Infof("2 tc compare s -> %s\n", tc.GetExpectsData("TestGetAPIVersion", "FakeData") == "foo")
// log.Infof("tc compare s -> %s\n", tc.EqualFaceS(tc.GetExpectsData("TestGetAPIVersion", "FakeData"), "foo"))
// log.Infof("get no test data -> %+v \n", tc.GetTestData("TestGetAPIVersion", "Surprise"))
// log.Infof("is test enabled -> %+v \n", tc.IsTestEnabled("TestGetAPIVersion"))
//
func (tc *TestConfig) GetTestingConfiguration(config_name string) {
	var (
		package_root  string
		Pkg           PackageInfo
		test_data_dir string
	)
	if os.Getenv("ONEVIEW_DEBUG") == "true" {
		log.IsDebug = true
	}
	package_root = os.Getenv("TESTCONFIG_PACKAGE_ROOT_PATH")
	if found, package_full_dir := Pkg.GetPackageRootDir(package_root); found == true {
		test_data_dir = Pkg.JoinPath([]string{package_full_dir,
			os.Getenv("TESTCONFIG_JSON_DATA_DIR")})
		if found, _ := Pkg.DirExists(test_data_dir); found == true {
			files, _ := ioutil.ReadDir(test_data_dir)
			for _, f := range files {
				log.Debugf("working on f -> %+v", f)
				data, err := ioutil.ReadFile(Pkg.JoinPath([]string{test_data_dir, f.Name()}))
				if err != nil {
					log.Errorf("File error : %v\n", err)
					os.Exit(1)
				}
				tc.UnMarshallTestingConfig(data)
				if tc.Name == config_name {
					log.Debugf("Found test data, %s \n", tc.Name)
					log.Debugf("tc -> %+v \n", tc)
					return
				}
			}
		} else {
			log.Errorf("No configuration found in %s, %s \n", test_data_dir, config_name)
		}
	}
	log.Errorf("No configuration found in %s, %s \n", package_root, config_name)
	os.Exit(1)
	return
}
<commit_msg>drop IsDebug for SetDebug for new logrus way<commit_after>package testconfig

// A test configuration management package for loading
// and executing test data and expects data that can be
// configured for various test target environments.
import (
	"encoding/json"
	"io/ioutil"
	"os"

	"github.com/docker/machine/libmachine/log"
)

//
// test case objects
//  see testcases.go for test case methods
// { "name" : "PROTEST",
//   "cases": [
//      {
//        ...
//      },
// ]
//}
type TestConfig struct {
	Cases []TestCases `json:"cases,omitempty"` // "cases":[]
	Name  string      `json:"name,omitempty"`  // "name": "PROTEST",
}

// setup Testing
func (tc *TestConfig) NewTestConfig() *TestConfig {
	return &TestConfig{Name: "",
		Cases: []TestCases{}}
}

// UnMarshall json to data
func (tc *TestConfig) UnMarshallTestingConfig(json_data []byte) {
	tc.Cases = []TestCases{}
	if err := json.Unmarshal(json_data, &tc); err != nil {
		log.Errorf("Error with un-marshalling test config data: %s", err)
		os.Exit(1)
	}
}

// get config for testing
// Examples
// cv := tc.GetExpectsData("TestGetAPIVersion", "CurrentVersion")
// log.Infof("tc test_data -> %s\n", tc.EqualFaceI(cv, 120))
// log.Infof("2 tc compare s -> %s\n", tc.GetExpectsData("TestGetAPIVersion", "FakeData") == "foo")
// log.Infof("tc compare s -> %s\n", tc.EqualFaceS(tc.GetExpectsData("TestGetAPIVersion", "FakeData"), "foo"))
// log.Infof("get no test data -> %+v \n", tc.GetTestData("TestGetAPIVersion", "Surprise"))
// log.Infof("is test enabled -> %+v \n", tc.IsTestEnabled("TestGetAPIVersion"))
//
func (tc *TestConfig) GetTestingConfiguration(config_name string) {
	var (
		package_root  string
		Pkg           PackageInfo
		test_data_dir string
	)
	if os.Getenv("ONEVIEW_DEBUG") == "true" {
		log.SetDebug(true)
	}
	package_root = os.Getenv("TESTCONFIG_PACKAGE_ROOT_PATH")
	if found, package_full_dir := Pkg.GetPackageRootDir(package_root); found == true {
		test_data_dir = Pkg.JoinPath([]string{package_full_dir,
			os.Getenv("TESTCONFIG_JSON_DATA_DIR")})
		if found, _ := Pkg.DirExists(test_data_dir); found == true {
			files, _ := ioutil.ReadDir(test_data_dir)
			for _, f := range files {
				log.Debugf("working on f -> %+v", f)
				data, err := ioutil.ReadFile(Pkg.JoinPath([]string{test_data_dir, f.Name()}))
				if err != nil {
					log.Errorf("File error : %v\n", err)
					os.Exit(1)
				}
				tc.UnMarshallTestingConfig(data)
				if tc.Name == config_name {
					log.Debugf("Found test data, %s \n", tc.Name)
					log.Debugf("tc -> %+v \n", tc)
					return
				}
			}
		} else {
			log.Errorf("No configuration found in %s, %s \n", test_data_dir, config_name)
		}
	}
	log.Errorf("No configuration found in %s, %s \n", package_root, config_name)
	os.Exit(1)
	return
}
<|endoftext|>