<commit_before>package main

import (
	"bytes"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

	"github.com/cespare/goproc/procnet"
	termbox "github.com/nsf/termbox-go"
)

var (
	rawKeys = [][2]string{
		{"Tcp", "CurrEstab"},
	}
	deltaKeys = [][2]string{
		{"Tcp", "ActiveOpens"},
		{"Tcp", "PassiveOpens"},
		{"Tcp", "InErrs"},
		{"Udp", "InDatagrams"},
		{"Udp", "OutDatagrams"},
	}

	freqString    = flag.String("freq", "1s", "Poll frequency")
	bucketsString = flag.String("buckets", "2s,10s", "List of bucket sizes to show (must be multiples of freq)")
	freq          time.Duration
	buckets       []time.Duration
	bucketBufs    = make(map[[2]string][]*CircBuf)
)

func init() {
	flag.Parse()
	var err error
	freq, err = time.ParseDuration(*freqString)
	if err != nil {
		fatal(err)
	}
	for _, bucketString := range strings.Split(*bucketsString, ",") {
		bucket, err := time.ParseDuration(bucketString)
		if err != nil {
			fatalf("Error parsing buckets: %s\n", err)
		}
		buckets = append(buckets, bucket)
	}
	if len(buckets) == 0 {
		fatal("Require at least one bucket")
	}
	for _, bucket := range buckets {
		if bucket%freq != 0 {
			fatalf("Bucket size (%v) is not a multiple of frequency (%v)\n", bucket, freq)
		}
		mul := int(bucket / freq)
		for _, key := range deltaKeys {
			// mul+1 is because we want to know mul intervals into the past (need a point at both ends).
			bufs := bucketBufs[key]
			bufs = append(bufs, NewCircBuf(mul+1))
			bucketBufs[key] = bufs
		}
	}
}

func main() {
	if err := termbox.Init(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer termbox.Close()
	termbox.HideCursor()

	done := make(chan os.Signal, 1)
	signal.Notify(done, syscall.SIGINT, syscall.SIGABRT)
	ticker := time.NewTicker(freq)
	defer ticker.Stop()

	input := make(chan rune, 10)
	go func() {
		for {
			if event := termbox.PollEvent(); event.Type == termbox.EventKey {
				input <- event.Ch
			}
		}
	}()

	printStats()
	for {
		select {
		case <-ticker.C:
			printStats()
		case <-done:
			return
		case c := <-input:
			if c == 'q' {
				return
			}
		}
	}
}

var (
	curX, curY int
)

func printStats() {
	stats, err := procnet.ReadNetStats()
	if err != nil {
		fatal(err)
	}
	curX = 0
	curY = 0
	if err := termbox.Clear(termbox.ColorDefault, termbox.ColorDefault); err != nil {
		fatal(err)
	}
	for _, key := range rawKeys {
		value := get(stats, key)
		tbPrintf(termbox.ColorWhite, "%s ", name(key))
		tbPrint(termbox.ColorGreen, value)
		tbNewline()
	}
	tbNewline()

	// Delta section header
	tbPrintf(termbox.ColorDefault, "%-20s", "")
	for i, d := range buckets {
		tbPrint(termbox.ColorWhite, centerString(fmt.Sprintf("last %s", d), 15))
		if i < len(buckets)-1 {
			tbPrint(termbox.ColorBlue, " │ ")
		}
	}
	tbNewline()

	for _, key := range deltaKeys {
		value := get(stats, key)
		for _, buf := range bucketBufs[key] {
			buf.Append(value)
		}
		tbFormatBufs(name(key), bucketBufs[key])
		tbNewline()
	}

	tbNewline()
	tbPrint(termbox.ColorWhite, "Press q to quit.")

	if err := termbox.Flush(); err != nil {
		fatal(err)
	}
}

func centerString(s string, size int) string {
	if len(s) >= size {
		return s
	}
	prefix := (size - len(s)) / 2
	buf := &bytes.Buffer{}
	for i := 0; i < prefix; i++ {
		buf.WriteRune(' ')
	}
	buf.WriteString(s)
	for i := 0; i < size-prefix-len(s); i++ {
		buf.WriteRune(' ')
	}
	return buf.String()
}

func tbFormatBufs(name string, bufs []*CircBuf) {
	tbPrintf(termbox.ColorWhite, "%-20s", name)
	for i, d := range buckets {
		value := fmt.Sprintf("%6s", "?")
		perSecond := fmt.Sprintf("%9s", "?")
		circBuf := bufs[i]
		if circBuf.Full() {
			delta := circBuf.Delta()
			deltaPerSecond := float64(delta) / d.Seconds()
			value = fmt.Sprintf("%6d", delta)
			perSecond = fmt.Sprintf("%7.1f/s", deltaPerSecond)
		}
		tbPrintf(termbox.ColorGreen, "%s%s", value, perSecond)
		if i < len(buckets)-1 {
			tbPrint(termbox.ColorBlue, " │ ")
		}
	}
}

func tbPrintf(fg termbox.Attribute, format string, args ...interface{}) {
	tbPrint(fg, fmt.Sprintf(format, args...))
}

func tbPrint(fg termbox.Attribute, args ...interface{}) {
	for _, r := range []rune(fmt.Sprint(args...)) {
		termbox.SetCell(curX, curY, r, fg, termbox.ColorDefault)
		curX++
	}
}

func tbNewline() {
	curY++
	curX = 0
}

func name(key [2]string) string { return key[0] + "." + key[1] }

func get(m map[string]map[string]int64, key [2]string) int64 {
	if m1, ok := m[key[0]]; ok {
		if v, ok := m1[key[1]]; ok {
			return v
		}
	}
	fatal("Cannot find key " + name(key))
	panic("unreached")
}

func fatal(args ...interface{}) {
	termbox.Close()
	fmt.Fprintln(os.Stderr, args...)
	os.Exit(1)
}

func fatalf(format string, args ...interface{}) {
	termbox.Close()
	fmt.Fprintf(os.Stderr, format, args...)
	os.Exit(1)
}
<commit_msg>nwstat spacing<commit_after>package main

import (
	"bytes"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

	"github.com/cespare/goproc/procnet"
	termbox "github.com/nsf/termbox-go"
)

var (
	rawKeys = [][2]string{
		{"Tcp", "CurrEstab"},
	}
	deltaKeys = [][2]string{
		{"Tcp", "ActiveOpens"},
		{"Tcp", "PassiveOpens"},
		{"Tcp", "InErrs"},
		{"Udp", "InDatagrams"},
		{"Udp", "OutDatagrams"},
	}

	freqString    = flag.String("freq", "1s", "Poll frequency")
	bucketsString = flag.String("buckets", "2s,10s", "List of bucket sizes to show (must be multiples of freq)")
	freq          time.Duration
	buckets       []time.Duration
	bucketBufs    = make(map[[2]string][]*CircBuf)
)

func init() {
	flag.Parse()
	var err error
	freq, err = time.ParseDuration(*freqString)
	if err != nil {
		fatal(err)
	}
	for _, bucketString := range strings.Split(*bucketsString, ",") {
		bucket, err := time.ParseDuration(bucketString)
		if err != nil {
			fatalf("Error parsing buckets: %s\n", err)
		}
		buckets = append(buckets, bucket)
	}
	if len(buckets) == 0 {
		fatal("Require at least one bucket")
	}
	for _, bucket := range buckets {
		if bucket%freq != 0 {
			fatalf("Bucket size (%v) is not a multiple of frequency (%v)\n", bucket, freq)
		}
		mul := int(bucket / freq)
		for _, key := range deltaKeys {
			// mul+1 is because we want to know mul intervals into the past (need a point at both ends).
			bufs := bucketBufs[key]
			bufs = append(bufs, NewCircBuf(mul+1))
			bucketBufs[key] = bufs
		}
	}
}

func main() {
	if err := termbox.Init(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	defer termbox.Close()
	termbox.HideCursor()

	done := make(chan os.Signal, 1)
	signal.Notify(done, syscall.SIGINT, syscall.SIGABRT)
	ticker := time.NewTicker(freq)
	defer ticker.Stop()

	input := make(chan rune, 10)
	go func() {
		for {
			if event := termbox.PollEvent(); event.Type == termbox.EventKey {
				input <- event.Ch
			}
		}
	}()

	printStats()
	for {
		select {
		case <-ticker.C:
			printStats()
		case <-done:
			return
		case c := <-input:
			if c == 'q' {
				return
			}
		}
	}
}

var (
	curX, curY int
)

func printStats() {
	stats, err := procnet.ReadNetStats()
	if err != nil {
		fatal(err)
	}
	curX = 0
	curY = 0
	if err := termbox.Clear(termbox.ColorDefault, termbox.ColorDefault); err != nil {
		fatal(err)
	}
	for _, key := range rawKeys {
		value := get(stats, key)
		tbPrintf(termbox.ColorWhite, "%s ", name(key))
		tbPrint(termbox.ColorGreen, value)
		tbNewline()
	}
	tbNewline()

	// Delta section header
	tbPrintf(termbox.ColorDefault, "%-20s", "")
	for i, d := range buckets {
		tbPrint(termbox.ColorWhite, centerString(fmt.Sprintf("last %s", d), 17))
		if i < len(buckets)-1 {
			tbPrint(termbox.ColorBlue, " │ ")
		}
	}
	tbNewline()

	for _, key := range deltaKeys {
		value := get(stats, key)
		for _, buf := range bucketBufs[key] {
			buf.Append(value)
		}
		tbFormatBufs(name(key), bucketBufs[key])
		tbNewline()
	}

	tbNewline()
	tbPrint(termbox.ColorWhite, "Press q to quit.")

	if err := termbox.Flush(); err != nil {
		fatal(err)
	}
}

func centerString(s string, size int) string {
	if len(s) >= size {
		return s
	}
	prefix := (size - len(s)) / 2
	buf := &bytes.Buffer{}
	for i := 0; i < prefix; i++ {
		buf.WriteRune(' ')
	}
	buf.WriteString(s)
	for i := 0; i < size-prefix-len(s); i++ {
		buf.WriteRune(' ')
	}
	return buf.String()
}

func tbFormatBufs(name string, bufs []*CircBuf) {
	tbPrintf(termbox.ColorWhite, "%-20s", name)
	for i, d := range buckets {
		value := fmt.Sprintf("%7s", "?")
		perSecond := fmt.Sprintf("%10s", "?")
		circBuf := bufs[i]
		if circBuf.Full() {
			delta := circBuf.Delta()
			deltaPerSecond := float64(delta) / d.Seconds()
			value = fmt.Sprintf("%7d", delta)
			perSecond = fmt.Sprintf("%8.1f/s", deltaPerSecond)
		}
		tbPrintf(termbox.ColorGreen, "%s%s", value, perSecond)
		if i < len(buckets)-1 {
			tbPrint(termbox.ColorBlue, " │ ")
		}
	}
}

func tbPrintf(fg termbox.Attribute, format string, args ...interface{}) {
	tbPrint(fg, fmt.Sprintf(format, args...))
}

func tbPrint(fg termbox.Attribute, args ...interface{}) {
	for _, r := range []rune(fmt.Sprint(args...)) {
		termbox.SetCell(curX, curY, r, fg, termbox.ColorDefault)
		curX++
	}
}

func tbNewline() {
	curY++
	curX = 0
}

func name(key [2]string) string { return key[0] + "." + key[1] }

func get(m map[string]map[string]int64, key [2]string) int64 {
	if m1, ok := m[key[0]]; ok {
		if v, ok := m1[key[1]]; ok {
			return v
		}
	}
	fatal("Cannot find key " + name(key))
	panic("unreached")
}

func fatal(args ...interface{}) {
	termbox.Close()
	fmt.Fprintln(os.Stderr, args...)
	os.Exit(1)
}

func fatalf(format string, args ...interface{}) {
	termbox.Close()
	fmt.Fprintf(os.Stderr, format, args...)
	os.Exit(1)
}
<|endoftext|>


<commit_before>package manager

import (
	"errors"
	"fmt"
	"net"
	"os"
	"path"

	"github.com/Symantec/Dominator/lib/json"
	proto "github.com/Symantec/Dominator/proto/hypervisor"
)

func (m *Manager) addAddressesToPool(addresses []proto.Address,
	lock bool) error {
	for index := range addresses {
		addresses[index].Shrink()
	}
	if lock {
		m.mutex.Lock()
		defer m.mutex.Unlock()
	}
	for _, address := range addresses {
		ipAddr := address.IpAddress
		if ipAddr != nil && m.getMatchingSubnet(ipAddr) == "" {
			return fmt.Errorf("no subnet matching %s", address.IpAddress)
		}
	}
	m.addressPool = append(m.addressPool, addresses...)
	return json.WriteToFile(path.Join(m.StateDir, "address-pool.json"),
		publicFilePerms, "    ", m.addressPool)
}

func (m *Manager) loadAddressPool() error {
	var addressPool []proto.Address
	err := json.ReadFromFile(path.Join(m.StateDir, "address-pool.json"),
		&addressPool)
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	for index := range addressPool {
		addressPool[index].Shrink()
	}
	m.addressPool = addressPool
	return nil
}

func (m *Manager) getFreeAddress(subnetId string) (proto.Address, error) {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	if len(m.addressPool) < 1 {
		return proto.Address{}, errors.New("no free addresses in pool")
	}
	if subnetId == "" {
		err := json.WriteToFile(path.Join(m.StateDir, "address-pool.json"),
			publicFilePerms, "    ", m.addressPool[1:])
		if err != nil {
			return proto.Address{}, err
		}
		address := m.addressPool[0]
		copy(m.addressPool, m.addressPool[1:])
		m.addressPool = m.addressPool[:len(m.addressPool)-1]
		return address, nil
	}
	subnet, ok := m.subnets[subnetId]
	if !ok {
		return proto.Address{}, fmt.Errorf("no such subnet: %s", subnetId)
	}
	subnetMask := net.IPMask(subnet.IpMask)
	subnetAddr := subnet.IpGateway.Mask(subnetMask)
	foundPos := -1
	for index, address := range m.addressPool {
		if address.IpAddress.Mask(subnetMask).Equal(subnetAddr) {
			foundPos = index
			break
		}
	}
	if foundPos < 0 {
		return proto.Address{},
			fmt.Errorf("no free address in subnet: %s", subnetId)
	}
	addressPool := make([]proto.Address, 0, len(m.addressPool)-1)
	for index, address := range m.addressPool {
		if index == foundPos {
			break
		}
		addressPool = append(addressPool, address)
	}
	err := json.WriteToFile(path.Join(m.StateDir, "address-pool.json"),
		publicFilePerms, "    ", addressPool)
	if err != nil {
		return proto.Address{}, err
	}
	address := m.addressPool[foundPos]
	m.addressPool = addressPool
	return address, nil
}

func (m *Manager) listAvailableAddresses() []proto.Address {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	addresses := make([]proto.Address, 0, len(m.addressPool))
	for _, address := range m.addressPool {
		addresses = append(addresses, address)
	}
	return addresses
}
<commit_msg>Reject adding duplicate addresses to hypervisor address pool.<commit_after>package manager

import (
	"errors"
	"fmt"
	"net"
	"os"
	"path"

	"github.com/Symantec/Dominator/lib/json"
	proto "github.com/Symantec/Dominator/proto/hypervisor"
)

func (m *Manager) addAddressesToPool(addresses []proto.Address,
	lock bool) error {
	for index := range addresses {
		addresses[index].Shrink()
	}
	if lock {
		m.mutex.Lock()
		defer m.mutex.Unlock()
	}
	existingIpAddresses := make(map[string]struct{})
	existingMacAddresses := make(map[string]struct{})
	for _, address := range m.addressPool {
		if address.IpAddress != nil {
			existingIpAddresses[address.IpAddress.String()] = struct{}{}
		}
		existingMacAddresses[address.MacAddress] = struct{}{}
	}
	for _, address := range addresses {
		ipAddr := address.IpAddress
		if ipAddr != nil {
			if m.getMatchingSubnet(ipAddr) == "" {
				return fmt.Errorf("no subnet matching %s", address.IpAddress)
			}
			if _, ok := existingIpAddresses[ipAddr.String()]; ok {
				return fmt.Errorf("duplicate IP address: %s", address.IpAddress)
			}
		}
		if _, ok := existingMacAddresses[address.MacAddress]; ok {
			return fmt.Errorf("duplicate MAC address: %s", address.MacAddress)
		}
	}
	m.addressPool = append(m.addressPool, addresses...)
	return json.WriteToFile(path.Join(m.StateDir, "address-pool.json"),
		publicFilePerms, "    ", m.addressPool)
}

func (m *Manager) loadAddressPool() error {
	var addressPool []proto.Address
	err := json.ReadFromFile(path.Join(m.StateDir, "address-pool.json"),
		&addressPool)
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	for index := range addressPool {
		addressPool[index].Shrink()
	}
	m.addressPool = addressPool
	return nil
}

func (m *Manager) getFreeAddress(subnetId string) (proto.Address, error) {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	if len(m.addressPool) < 1 {
		return proto.Address{}, errors.New("no free addresses in pool")
	}
	if subnetId == "" {
		err := json.WriteToFile(path.Join(m.StateDir, "address-pool.json"),
			publicFilePerms, "    ", m.addressPool[1:])
		if err != nil {
			return proto.Address{}, err
		}
		address := m.addressPool[0]
		copy(m.addressPool, m.addressPool[1:])
		m.addressPool = m.addressPool[:len(m.addressPool)-1]
		return address, nil
	}
	subnet, ok := m.subnets[subnetId]
	if !ok {
		return proto.Address{}, fmt.Errorf("no such subnet: %s", subnetId)
	}
	subnetMask := net.IPMask(subnet.IpMask)
	subnetAddr := subnet.IpGateway.Mask(subnetMask)
	foundPos := -1
	for index, address := range m.addressPool {
		if address.IpAddress.Mask(subnetMask).Equal(subnetAddr) {
			foundPos = index
			break
		}
	}
	if foundPos < 0 {
		return proto.Address{},
			fmt.Errorf("no free address in subnet: %s", subnetId)
	}
	addressPool := make([]proto.Address, 0, len(m.addressPool)-1)
	for index, address := range m.addressPool {
		if index == foundPos {
			break
		}
		addressPool = append(addressPool, address)
	}
	err := json.WriteToFile(path.Join(m.StateDir, "address-pool.json"),
		publicFilePerms, "    ", addressPool)
	if err != nil {
		return proto.Address{}, err
	}
	address := m.addressPool[foundPos]
	m.addressPool = addressPool
	return address, nil
}

func (m *Manager) listAvailableAddresses() []proto.Address {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	addresses := make([]proto.Address, 0, len(m.addressPool))
	for _, address := range m.addressPool {
		addresses = append(addresses, address)
	}
	return addresses
}
<|endoftext|>


<commit_before>package util

const (
	VERSION = "0.69 20150413"
)
<commit_msg>0.70 beta start<commit_after>package util

const (
	VERSION = "0.70 beta 20150414"
)
<|endoftext|>


<commit_before>package exporter

import (
	"encoding/json"
	"io"
	"strconv"

	"github.com/cayleygraph/cayley/graph"
)

type Exporter struct {
	wr     io.Writer
	qstore graph.QuadStore
	qi     graph.Iterator
	err    error
	count  int
}

func NewExporter(writer io.Writer, qstore graph.QuadStore) *Exporter {
	return NewExporterForIterator(writer, qstore, qstore.QuadsAllIterator())
}

func NewExporterForIterator(writer io.Writer, qstore graph.QuadStore, qi graph.Iterator) *Exporter {
	return &Exporter{wr: writer, qstore: qstore, qi: qi}
}

// number of records
func (exp *Exporter) Count() int {
	return exp.count
}

func (exp *Exporter) ExportQuad() {
	exp.qi.Reset()
	for it := exp.qi; graph.Next(it); {
		exp.count++
		quad := exp.qstore.Quad(it.Result())

		exp.WriteEscString(quad.Subject)
		exp.Write(" ")
		exp.WriteEscString(quad.Predicate)
		exp.Write(" ")
		exp.WriteEscString(quad.Object)
		if quad.Label != "" {
			exp.Write(" ")
			exp.WriteEscString(quad.Label)
		}
		exp.Write(" .\n")
	}
}

func (exp *Exporter) ExportJson() {
	var jstr []byte
	exp.Write("[")
	exp.qi.Reset()
	for it := exp.qi; graph.Next(it); {
		exp.count++
		if exp.count > 1 {
			exp.Write(",")
		}

		jstr, exp.err = json.Marshal(exp.qstore.Quad(it.Result()))
		if exp.err != nil {
			return
		}
		exp.Write(string(jstr[:]))
	}
	exp.Write("]\n")
}

//experimental
func (exp *Exporter) ExportGml() {
	var seen map[string]int32 // todo eliminate this for large dbs
	var id int32

	exp.Write("Creator Cayley\ngraph\n[\n")

	seen = make(map[string]int32)
	exp.qi.Reset()
	for it := exp.qi; graph.Next(it); {
		cur := exp.qstore.Quad(it.Result())
		if _, ok := seen[cur.Subject]; !ok {
			exp.Write("  node\n  [\n    id ")
			seen[cur.Subject] = id
			exp.Write(strconv.FormatInt(int64(id), 10))
			exp.Write("\n    label ")
			exp.WriteEscString(cur.Subject)
			exp.Write("\n  ]\n")
			id++
		}
		if _, ok := seen[cur.Object]; !ok {
			exp.Write("  node\n  [\n    id ")
			seen[cur.Object] = id
			exp.Write(strconv.FormatInt(int64(id), 10))
			exp.Write("\n    label ")
			exp.WriteEscString(cur.Object)
			exp.Write("\n  ]\n")
			id++
		}
		exp.count++
	}

	exp.qi.Reset()
	for it := exp.qi; graph.Next(it); {
		cur := exp.qstore.Quad(it.Result())
		exp.Write("  edge\n  [\n    source ")
		exp.Write(strconv.FormatInt(int64(seen[cur.Subject]), 10))
		exp.Write("\n    target ")
		exp.Write(strconv.FormatInt(int64(seen[cur.Object]), 10))
		exp.Write("\n    label ")
		exp.WriteEscString(cur.Predicate)
		exp.Write("\n  ]\n")
		exp.count++
	}
	exp.Write("]\n")
}

//experimental
func (exp *Exporter) ExportGraphml() {
	var seen map[string]bool // eliminate this for large databases

	exp.Write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
	exp.Write("<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\"\n")
	exp.Write("   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n")
	exp.Write("   xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">\n")
	exp.Write("  <graph id=\"Caylay\" edgedefault=\"directed\">\n")

	seen = make(map[string]bool)
	exp.qi.Reset()
	for it := exp.qi; graph.Next(it); {
		cur := exp.qstore.Quad(it.Result())
		if found := seen[cur.Subject]; !found {
			seen[cur.Subject] = true
			exp.Write("    <node id=")
			exp.WriteEscString(cur.Subject)
			exp.Write(" />\n")
		}
		if found := seen[cur.Object]; !found {
			seen[cur.Object] = true
			exp.Write("    <node id=")
			exp.WriteEscString(cur.Object)
			exp.Write(" />\n")
		}
		exp.count++
	}

	exp.qi.Reset()
	for it := exp.qi; graph.Next(it); {
		cur := exp.qstore.Quad(it.Result())
		exp.Write("    <edge source=")
		exp.WriteEscString(cur.Subject)
		exp.Write(" target=")
		exp.WriteEscString(cur.Object)
		exp.Write(">\n")
		exp.Write("      <data key=\"predicate\">")
		exp.Write(cur.Predicate)
		exp.Write("</data>\n    </edge>\n")
		exp.count++
	}
	exp.Write("  </graph>\n</graphml>\n")
}

//print out the string quoted, escaped
func (exp *Exporter) WriteEscString(str string) {
	var esc []byte

	if exp.err != nil {
		return
	}
	esc, exp.err = json.Marshal(str)
	if exp.err != nil {
		return
	}
	_, exp.err = exp.wr.Write(esc)
}

func (exp *Exporter) Write(str string) {
	if exp.err != nil {
		return
	}
	_, exp.err = exp.wr.Write([]byte(str))
}

func (exp *Exporter) Err() error {
	return exp.err
}
<commit_msg>update exporter<commit_after>package exporter

import (
	"encoding/json"
	"io"
	"strconv"

	"github.com/cayleygraph/cayley/graph"
	"github.com/cayleygraph/cayley/quad"
)

type Exporter struct {
	wr     io.Writer
	qstore graph.QuadStore
	qi     graph.Iterator
	err    error
	count  int
}

func NewExporter(writer io.Writer, qstore graph.QuadStore) *Exporter {
	return NewExporterForIterator(writer, qstore, qstore.QuadsAllIterator())
}

func NewExporterForIterator(writer io.Writer, qstore graph.QuadStore, qi graph.Iterator) *Exporter {
	return &Exporter{wr: writer, qstore: qstore, qi: qi}
}

// number of records
func (exp *Exporter) Count() int {
	return exp.count
}

func (exp *Exporter) ExportQuad() {
	exp.qi.Reset()
	for it := exp.qi; graph.Next(it); {
		exp.count++
		quad := exp.qstore.Quad(it.Result())

		exp.WriteEscString(quad.Subject.String())
		exp.Write(" ")
		exp.WriteEscString(quad.Predicate.String())
		exp.Write(" ")
		exp.WriteEscString(quad.Object.String())
		if quad.Label != nil {
			exp.Write(" ")
			exp.WriteEscString(quad.Label.String())
		}
		exp.Write(" .\n")
	}
}

func (exp *Exporter) ExportJson() {
	var jstr []byte
	exp.Write("[")
	exp.qi.Reset()
	for it := exp.qi; graph.Next(it); {
		exp.count++
		if exp.count > 1 {
			exp.Write(",")
		}

		jstr, exp.err = json.Marshal(exp.qstore.Quad(it.Result()))
		if exp.err != nil {
			return
		}
		exp.Write(string(jstr[:]))
	}
	exp.Write("]\n")
}

//experimental
func (exp *Exporter) ExportGml() {
	var seen map[quad.Value]int32 // todo eliminate this for large dbs
	var id int32

	exp.Write("Creator Cayley\ngraph\n[\n")

	seen = make(map[quad.Value]int32)
	exp.qi.Reset()
	for it := exp.qi; graph.Next(it); {
		cur := exp.qstore.Quad(it.Result())
		if _, ok := seen[cur.Subject]; !ok {
			exp.Write("  node\n  [\n    id ")
			seen[cur.Subject] = id
			exp.Write(strconv.FormatInt(int64(id), 10))
			exp.Write("\n    label ")
			exp.WriteEscString(cur.Subject.String())
			exp.Write("\n  ]\n")
			id++
		}
		if _, ok := seen[cur.Object]; !ok {
			exp.Write("  node\n  [\n    id ")
			seen[cur.Object] = id
			exp.Write(strconv.FormatInt(int64(id), 10))
			exp.Write("\n    label ")
			exp.WriteEscString(cur.Object.String())
			exp.Write("\n  ]\n")
			id++
		}
		exp.count++
	}

	exp.qi.Reset()
	for it := exp.qi; graph.Next(it); {
		cur := exp.qstore.Quad(it.Result())
		exp.Write("  edge\n  [\n    source ")
		exp.Write(strconv.FormatInt(int64(seen[cur.Subject]), 10))
		exp.Write("\n    target ")
		exp.Write(strconv.FormatInt(int64(seen[cur.Object]), 10))
		exp.Write("\n    label ")
		exp.WriteEscString(cur.Predicate.String())
		exp.Write("\n  ]\n")
		exp.count++
	}
	exp.Write("]\n")
}

//experimental
func (exp *Exporter) ExportGraphml() {
	var seen map[quad.Value]bool // eliminate this for large databases

	exp.Write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
	exp.Write("<graphml xmlns=\"http://graphml.graphdrawing.org/xmlns\"\n")
	exp.Write("   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n")
	exp.Write("   xsi:schemaLocation=\"http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd\">\n")
	exp.Write("  <graph id=\"Caylay\" edgedefault=\"directed\">\n")

	seen = make(map[quad.Value]bool)
	exp.qi.Reset()
	for it := exp.qi; graph.Next(it); {
		cur := exp.qstore.Quad(it.Result())
		if found := seen[cur.Subject]; !found {
			seen[cur.Subject] = true
			exp.Write("    <node id=")
			exp.WriteEscString(cur.Subject.String())
			exp.Write(" />\n")
		}
		if found := seen[cur.Object]; !found {
			seen[cur.Object] = true
			exp.Write("    <node id=")
			exp.WriteEscString(cur.Object.String())
			exp.Write(" />\n")
		}
		exp.count++
	}

	exp.qi.Reset()
	for it := exp.qi; graph.Next(it); {
		cur := exp.qstore.Quad(it.Result())
		exp.Write("    <edge source=")
		exp.WriteEscString(cur.Subject.String())
		exp.Write(" target=")
		exp.WriteEscString(cur.Object.String())
		exp.Write(">\n")
		exp.Write("      <data key=\"predicate\">")
		exp.Write(cur.Predicate.String())
		exp.Write("</data>\n    </edge>\n")
		exp.count++
	}
	exp.Write("  </graph>\n</graphml>\n")
}

//print out the string quoted, escaped
func (exp *Exporter) WriteEscString(str string) {
	var esc []byte

	if exp.err != nil {
		return
	}
	esc, exp.err = json.Marshal(str)
	if exp.err != nil {
		return
	}
	_, exp.err = exp.wr.Write(esc)
}

func (exp *Exporter) Write(str string) {
	if exp.err != nil {
		return
	}
	_, exp.err = exp.wr.Write([]byte(str))
}

func (exp *Exporter) Err() error {
	return exp.err
}
<|endoftext|>


<commit_before>package tchannel_test

// Copyright (c) 2015 Uber Technologies, Inc.

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

import (
	"os"
	"testing"
	"time"

	. "github.com/uber/tchannel/golang"

	"github.com/stretchr/testify/require"
	"github.com/uber/tchannel/golang/raw"
	"github.com/uber/tchannel/golang/testutils"
)

func tagsForOutboundCall(serverCh *Channel, clientCh *Channel, operation string) map[string]string {
	host, _ := os.Hostname()
	return map[string]string{
		"app":             clientCh.PeerInfo().ProcessName,
		"host":            host,
		"service":         clientCh.PeerInfo().ServiceName,
		"target-service":  serverCh.PeerInfo().ServiceName,
		"target-endpoint": operation,
	}
}

func tagsForInboundCall(serverCh *Channel, clientCh *Channel, operation string) map[string]string {
	host, _ := os.Hostname()
	return map[string]string{
		"app":             serverCh.PeerInfo().ProcessName,
		"host":            host,
		"service":         serverCh.PeerInfo().ServiceName,
		"calling-service": clientCh.PeerInfo().ServiceName,
		"endpoint":        operation,
	}
}

func TestStatsCalls(t *testing.T) {
	testutils.SetTimeout(t, time.Second)

	initialTime := time.Date(2015, 2, 1, 10, 10, 0, 0, time.UTC)
	nowFn := testutils.NowStub(GetTimeNow(), initialTime)
	defer testutils.ResetNowStub(GetTimeNow())

	// time.Now will be called in this order for each call:
	// sender records time they started sending
	// receiver records time the request is sent to application
	// receiver calculates application handler latency
	// sender records call latency
	// So expected times are going to be:
	// Inbound latency: 50
	// Outbound latency: 150
	nowFn(50 * time.Millisecond)

	serverStats := newRecordingStatsReporter()
	serverOpts := &testutils.ChannelOpts{
		StatsReporter: serverStats,
	}
	require.NoError(t, testutils.WithServer(serverOpts, func(serverCh *Channel, hostPort string) {
		handler := raw.Wrap(newTestHandler(t))
		serverCh.Register(handler, "echo")
		serverCh.Register(handler, "app-error")

		clientStats := newRecordingStatsReporter()
		ch, err := testutils.NewClient(&testutils.ChannelOpts{StatsReporter: clientStats})
		require.NoError(t, err)

		ctx, cancel := NewContext(time.Second * 5)
		defer cancel()

		_, _, _, err = raw.Call(ctx, ch, hostPort, testServiceName, "echo", []byte("Headers"), []byte("Body"))
		require.NoError(t, err)

		_, _, resp, err := raw.Call(ctx, ch, hostPort, testServiceName, "app-error", nil, nil)
		require.NoError(t, err)
		require.True(t, resp.ApplicationError(), "expected application error")

		outboundTags := tagsForOutboundCall(serverCh, ch, "echo")
		clientStats.Expected.IncCounter("outbound.calls.send", outboundTags, 1)
		clientStats.Expected.IncCounter("outbound.calls.success", outboundTags, 1)
		clientStats.Expected.RecordTimer("outbound.calls.latency", outboundTags, 150*time.Millisecond)
		outboundTags["target-endpoint"] = "app-error"
		clientStats.Expected.IncCounter("outbound.calls.send", outboundTags, 1)
		clientStats.Expected.IncCounter("outbound.calls.app-errors", outboundTags, 1)
		clientStats.Expected.RecordTimer("outbound.calls.latency", outboundTags, 150*time.Millisecond)

		inboundTags := tagsForInboundCall(serverCh, ch, "echo")
		serverStats.Expected.IncCounter("inbound.calls.recvd", inboundTags, 1)
		serverStats.Expected.IncCounter("inbound.calls.success", inboundTags, 1)
		serverStats.Expected.RecordTimer("inbound.calls.latency", inboundTags, 50*time.Millisecond)
		inboundTags["endpoint"] = "app-error"
		serverStats.Expected.IncCounter("inbound.calls.recvd", inboundTags, 1)
		serverStats.Expected.IncCounter("inbound.calls.app-errors", inboundTags, 1)
		serverStats.Expected.RecordTimer("inbound.calls.latency", inboundTags, 50*time.Millisecond)

		clientStats.Validate(t)
		serverStats.Validate(t)
	}))
}
<commit_msg>Use different latencies for "app-error" call.<commit_after>package tchannel_test

// Copyright (c) 2015 Uber Technologies, Inc.

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

import (
	"os"
	"testing"
	"time"

	. "github.com/uber/tchannel/golang"

	"github.com/stretchr/testify/require"
	"github.com/uber/tchannel/golang/raw"
	"github.com/uber/tchannel/golang/testutils"
)

func tagsForOutboundCall(serverCh *Channel, clientCh *Channel, operation string) map[string]string {
	host, _ := os.Hostname()
	return map[string]string{
		"app":             clientCh.PeerInfo().ProcessName,
		"host":            host,
		"service":         clientCh.PeerInfo().ServiceName,
		"target-service":  serverCh.PeerInfo().ServiceName,
		"target-endpoint": operation,
	}
}

func tagsForInboundCall(serverCh *Channel, clientCh *Channel, operation string) map[string]string {
	host, _ := os.Hostname()
	return map[string]string{
		"app":             serverCh.PeerInfo().ProcessName,
		"host":            host,
		"service":         serverCh.PeerInfo().ServiceName,
		"calling-service": clientCh.PeerInfo().ServiceName,
		"endpoint":        operation,
	}
}

func TestStatsCalls(t *testing.T) {
	defer testutils.SetTimeout(t, time.Second)()

	initialTime := time.Date(2015, 2, 1, 10, 10, 0, 0, time.UTC)
	nowFn := testutils.NowStub(GetTimeNow(), initialTime)
	defer testutils.ResetNowStub(GetTimeNow())
	// time.Now will be called in this order for each call:
	// sender records time they started sending
	// receiver records time the request is sent to application
	// receiver calculates application handler latency
	// sender records call latency
	// so expected inbound latency = incrementor, outbound = 3 * incrementor

	serverStats := newRecordingStatsReporter()
	serverOpts := &testutils.ChannelOpts{
		StatsReporter: serverStats,
	}
	require.NoError(t, testutils.WithServer(serverOpts, func(serverCh *Channel, hostPort string) {
		handler := raw.Wrap(newTestHandler(t))
		serverCh.Register(handler, "echo")
		serverCh.Register(handler, "app-error")

		clientStats := newRecordingStatsReporter()
		ch, err := testutils.NewClient(&testutils.ChannelOpts{StatsReporter: clientStats})
		require.NoError(t, err)

		ctx, cancel := NewContext(time.Second * 5)
		defer cancel()

		// Set now incrementor to 50ms, so expected Inbound latency is 50ms, outbound is 150ms.
		nowFn(50 * time.Millisecond)
		_, _, _, err = raw.Call(ctx, ch, hostPort, testServiceName, "echo", []byte("Headers"), []byte("Body"))
		require.NoError(t, err)

		outboundTags := tagsForOutboundCall(serverCh, ch, "echo")
		clientStats.Expected.IncCounter("outbound.calls.send", outboundTags, 1)
		clientStats.Expected.IncCounter("outbound.calls.success", outboundTags, 1)
		clientStats.Expected.RecordTimer("outbound.calls.latency", outboundTags, 150*time.Millisecond)
		inboundTags := tagsForInboundCall(serverCh, ch, "echo")
		serverStats.Expected.IncCounter("inbound.calls.recvd", inboundTags, 1)
		serverStats.Expected.IncCounter("inbound.calls.success", inboundTags, 1)
		serverStats.Expected.RecordTimer("inbound.calls.latency", inboundTags, 50*time.Millisecond)

		// Expected inbound latency = 70ms, outbound = 210ms.
		nowFn(70 * time.Millisecond)
		_, _, resp, err := raw.Call(ctx, ch, hostPort, testServiceName, "app-error", nil, nil)
		require.NoError(t, err)
		require.True(t, resp.ApplicationError(), "expected application error")

		outboundTags = tagsForOutboundCall(serverCh, ch, "app-error")
		clientStats.Expected.IncCounter("outbound.calls.send", outboundTags, 1)
		clientStats.Expected.IncCounter("outbound.calls.app-errors", outboundTags, 1)
		clientStats.Expected.RecordTimer("outbound.calls.latency", outboundTags, 210*time.Millisecond)
		inboundTags = tagsForInboundCall(serverCh, ch, "app-error")
		serverStats.Expected.IncCounter("inbound.calls.recvd", inboundTags, 1)
		serverStats.Expected.IncCounter("inbound.calls.app-errors", inboundTags, 1)
		serverStats.Expected.RecordTimer("inbound.calls.latency", inboundTags, 70*time.Millisecond)

		clientStats.Validate(t)
		serverStats.Validate(t)
	}))
}
<|endoftext|>


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

// Package gomock is a mock framework for Go.
//
// Standard usage:
//   (1) Define an interface that you wish to mock.
//         type MyInterface interface {
//           SomeMethod(x int64, y string)
//         }
//   (2) Use mockgen to generate a mock from the interface.
//   (3) Use the mock in a test:
//         func TestMyThing(t *testing.T) {
//           mockCtrl := gomock.NewController(t)
//           defer mockCtrl.Finish()
//
//           mockObj := something.NewMockMyInterface(mockCtrl)
//           mockObj.EXPECT().SomeMethod(4, "blah")
//           // pass mockObj to a real object and play with it.
//         }
//
// By default, expected calls are not enforced to run in any particular order.
// Call order dependency can be enforced by use of InOrder and/or Call.After.
// Call.After can create more varied call order dependencies, but InOrder is
// often more convenient.
//
// The following examples create equivalent call order dependencies.
//
// Example of using Call.After to chain expected call order:
//
//     firstCall := mockObj.EXPECT().SomeMethod(1, "first")
//     secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall)
//     mockObj.EXPECT().SomeMethod(3, "third").After(secondCall)
//
// Example of using InOrder to declare expected call order:
//
//     gomock.InOrder(
//         mockObj.EXPECT().SomeMethod(1, "first"),
//         mockObj.EXPECT().SomeMethod(2, "second"),
//         mockObj.EXPECT().SomeMethod(3, "third"),
//     )
//
// TODO:
//	- Handle different argument/return types (e.g. ..., chan, map, interface).
package gomock

import (
	"context"
	"fmt"
	"reflect"
	"runtime"
	"sync"
)

// A TestReporter is something that can be used to report test failures.  It
// is satisfied by the standard library's *testing.T.
type TestReporter interface {
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
}

// TestHelper is a TestReporter that has the Helper method.  It is satisfied
// by the standard library's *testing.T.
type TestHelper interface {
	TestReporter
	Helper()
}

// A Controller represents the top-level control of a mock ecosystem.  It
// defines the scope and lifetime of mock objects, as well as their
// expectations.  It is safe to call Controller's methods from multiple
// goroutines. Each test should create a new Controller and invoke Finish via
// defer.
//
//   func TestFoo(t *testing.T) {
//     ctrl := gomock.NewController(st)
//     defer ctrl.Finish()
//     // ..
//   }
//
//   func TestBar(t *testing.T) {
//     t.Run("Sub-Test-1", st) {
//       ctrl := gomock.NewController(st)
//       defer ctrl.Finish()
//       // ..
//     })
//     t.Run("Sub-Test-2", st) {
//       ctrl := gomock.NewController(st)
//       defer ctrl.Finish()
//       // ..
//     })
//   })
type Controller struct {
	// T should only be called within a generated mock. It is not intended to
	// be used in user code and may be changed in future versions. T is the
	// TestReporter passed in when creating the Controller via NewController.
	// If the TestReporter does not implment a TestHelper it will be wrapped
	// with a nopTestHelper.
	T             TestHelper
	mu            sync.Mutex
	expectedCalls *callSet
	finished      bool
}

// NewController returns a new Controller. It is the preferred way to create a
// Controller.
func NewController(t TestReporter) *Controller {
	h, ok := t.(TestHelper)
	if !ok {
		h = nopTestHelper{t}
	}

	return &Controller{
		T:             h,
		expectedCalls: newCallSet(),
	}
}

type cancelReporter struct {
	TestHelper
	cancel func()
}

func (r *cancelReporter) Errorf(format string, args ...interface{}) {
	r.TestHelper.Errorf(format, args...)
}
func (r *cancelReporter) Fatalf(format string, args ...interface{}) {
	defer r.cancel()
	r.TestHelper.Fatalf(format, args...)
}

// WithContext returns a new Controller and a Context, which is cancelled on any
// fatal failure.
func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) {
	h, ok := t.(TestHelper)
	if !ok {
		h = nopTestHelper{t}
	}

	ctx, cancel := context.WithCancel(ctx)
	return NewController(&cancelReporter{h, cancel}), ctx
}

type nopTestHelper struct {
	TestReporter
}

func (h nopTestHelper) Helper() {}

// RecordCall is called by a mock. It should not be called by user code.
func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call {
	ctrl.T.Helper()

	recv := reflect.ValueOf(receiver)
	for i := 0; i < recv.Type().NumMethod(); i++ {
		if recv.Type().Method(i).Name == method {
			return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...)
		}
	}
	ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver)
	panic("unreachable")
}

// RecordCallWithMethodType is called by a mock. It should not be called by user code.
func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call {
	ctrl.T.Helper()

	call := newCall(ctrl.T, receiver, method, methodType, args...)

	ctrl.mu.Lock()
	defer ctrl.mu.Unlock()
	ctrl.expectedCalls.Add(call)

	return call
}

// Call is called by a mock. It should not be called by user code.
func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} {
	ctrl.T.Helper()

	// Nest this code so we can use defer to make sure the lock is released.
	actions := func() []func([]interface{}) []interface{} {
		ctrl.T.Helper()
		ctrl.mu.Lock()
		defer ctrl.mu.Unlock()

		expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args)
		if err != nil {
			origin := callerInfo(2)
			ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err)
		}

		// Two things happen here:
		// * the matching call no longer needs to check prerequite calls,
		// * and the prerequite calls are no longer expected, so remove them.
		preReqCalls := expected.dropPrereqs()
		for _, preReqCall := range preReqCalls {
			ctrl.expectedCalls.Remove(preReqCall)
		}

		actions := expected.call(args)
		if expected.exhausted() {
			ctrl.expectedCalls.Remove(expected)
		}
		return actions
	}()

	var rets []interface{}
	for _, action := range actions {
		if r := action(args); r != nil {
			rets = r
		}
	}

	return rets
}

// Finish checks to see if all the methods that were expected to be called
// were called. It should be invoked for each Controller. It is not idempotent
// and therefore can only be invoked once.
func (ctrl *Controller) Finish() {
	ctrl.T.Helper()

	ctrl.mu.Lock()
	defer ctrl.mu.Unlock()

	if ctrl.finished {
		ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.")
	}
	ctrl.finished = true

	// If we're currently panicking, probably because this is a deferred call,
	// pass through the panic.
	if err := recover(); err != nil {
		panic(err)
	}

	// Check that all remaining expected calls are satisfied.
	failures := ctrl.expectedCalls.Failures()
	for _, call := range failures {
		ctrl.T.Errorf("missing call(s) to %v", call)
	}
	if len(failures) != 0 {
		ctrl.T.Fatalf("aborting test due to missing call(s)")
	}
}

func callerInfo(skip int) string {
	if _, file, line, ok := runtime.Caller(skip + 1); ok {
		return fmt.Sprintf("%s:%d", file, line)
	}
	return "unknown file"
}
<commit_msg>Fix small typo (#280)<commit_after>// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package gomock is a mock framework for Go.
//
// Standard usage:
//   (1) Define an interface that you wish to mock.
//         type MyInterface interface {
//           SomeMethod(x int64, y string)
//         }
//   (2) Use mockgen to generate a mock from the interface.
//   (3) Use the mock in a test:
//         func TestMyThing(t *testing.T) {
//           mockCtrl := gomock.NewController(t)
//           defer mockCtrl.Finish()
//
//           mockObj := something.NewMockMyInterface(mockCtrl)
//           mockObj.EXPECT().SomeMethod(4, "blah")
//           // pass mockObj to a real object and play with it.
//         }
//
// By default, expected calls are not enforced to run in any particular order.
// Call order dependency can be enforced by use of InOrder and/or Call.After.
// Call.After can create more varied call order dependencies, but InOrder is
// often more convenient.
//
// The following examples create equivalent call order dependencies.
//
// Example of using Call.After to chain expected call order:
//
//     firstCall := mockObj.EXPECT().SomeMethod(1, "first")
//     secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall)
//     mockObj.EXPECT().SomeMethod(3, "third").After(secondCall)
//
// Example of using InOrder to declare expected call order:
//
//     gomock.InOrder(
//         mockObj.EXPECT().SomeMethod(1, "first"),
//         mockObj.EXPECT().SomeMethod(2, "second"),
//         mockObj.EXPECT().SomeMethod(3, "third"),
//     )
//
// TODO:
//	- Handle different argument/return types (e.g. ..., chan, map, interface).
package gomock

import (
	"context"
	"fmt"
	"reflect"
	"runtime"
	"sync"
)

// A TestReporter is something that can be used to report test failures.  It
// is satisfied by the standard library's *testing.T.
type TestReporter interface {
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
}

// TestHelper is a TestReporter that has the Helper method.  It is satisfied
// by the standard library's *testing.T.
type TestHelper interface {
	TestReporter
	Helper()
}

// A Controller represents the top-level control of a mock ecosystem.  It
// defines the scope and lifetime of mock objects, as well as their
// expectations.  It is safe to call Controller's methods from multiple
// goroutines. Each test should create a new Controller and invoke Finish via
// defer.
//
//   func TestFoo(t *testing.T) {
//     ctrl := gomock.NewController(st)
//     defer ctrl.Finish()
//     // ..
//   }
//
//   func TestBar(t *testing.T) {
//     t.Run("Sub-Test-1", st) {
//       ctrl := gomock.NewController(st)
//       defer ctrl.Finish()
//       // ..
//     })
//     t.Run("Sub-Test-2", st) {
//       ctrl := gomock.NewController(st)
//       defer ctrl.Finish()
//       // ..
//     })
//   })
type Controller struct {
	// T should only be called within a generated mock. It is not intended to
	// be used in user code and may be changed in future versions. T is the
	// TestReporter passed in when creating the Controller via NewController.
	// If the TestReporter does not implement a TestHelper it will be wrapped
	// with a nopTestHelper.
	T             TestHelper
	mu            sync.Mutex
	expectedCalls *callSet
	finished      bool
}

// NewController returns a new Controller. It is the preferred way to create a
// Controller.
func NewController(t TestReporter) *Controller {
	h, ok := t.(TestHelper)
	if !ok {
		h = nopTestHelper{t}
	}

	return &Controller{
		T:             h,
		expectedCalls: newCallSet(),
	}
}

type cancelReporter struct {
	TestHelper
	cancel func()
}

func (r *cancelReporter) Errorf(format string, args ...interface{}) {
	r.TestHelper.Errorf(format, args...)
}
func (r *cancelReporter) Fatalf(format string, args ...interface{}) {
	defer r.cancel()
	r.TestHelper.Fatalf(format, args...)
}

// WithContext returns a new Controller and a Context, which is cancelled on any
// fatal failure.
func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) {
	h, ok := t.(TestHelper)
	if !ok {
		h = nopTestHelper{t}
	}

	ctx, cancel := context.WithCancel(ctx)
	return NewController(&cancelReporter{h, cancel}), ctx
}

type nopTestHelper struct {
	TestReporter
}

func (h nopTestHelper) Helper() {}

// RecordCall is called by a mock. It should not be called by user code.
func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call {
	ctrl.T.Helper()

	recv := reflect.ValueOf(receiver)
	for i := 0; i < recv.Type().NumMethod(); i++ {
		if recv.Type().Method(i).Name == method {
			return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...)
		}
	}
	ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver)
	panic("unreachable")
}

// RecordCallWithMethodType is called by a mock. It should not be called by user code.
func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call {
	ctrl.T.Helper()

	call := newCall(ctrl.T, receiver, method, methodType, args...)

	ctrl.mu.Lock()
	defer ctrl.mu.Unlock()
	ctrl.expectedCalls.Add(call)

	return call
}

// Call is called by a mock. It should not be called by user code.
func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} {
	ctrl.T.Helper()

	// Nest this code so we can use defer to make sure the lock is released.
	actions := func() []func([]interface{}) []interface{} {
		ctrl.T.Helper()
		ctrl.mu.Lock()
		defer ctrl.mu.Unlock()

		expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args)
		if err != nil {
			origin := callerInfo(2)
			ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err)
		}

		// Two things happen here:
		// * the matching call no longer needs to check prerequite calls,
		// * and the prerequite calls are no longer expected, so remove them.
		preReqCalls := expected.dropPrereqs()
		for _, preReqCall := range preReqCalls {
			ctrl.expectedCalls.Remove(preReqCall)
		}

		actions := expected.call(args)
		if expected.exhausted() {
			ctrl.expectedCalls.Remove(expected)
		}
		return actions
	}()

	var rets []interface{}
	for _, action := range actions {
		if r := action(args); r != nil {
			rets = r
		}
	}

	return rets
}

// Finish checks to see if all the methods that were expected to be called
// were called. It should be invoked for each Controller. It is not idempotent
// and therefore can only be invoked once.
func (ctrl *Controller) Finish() {
	ctrl.T.Helper()

	ctrl.mu.Lock()
	defer ctrl.mu.Unlock()

	if ctrl.finished {
		ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.")
	}
	ctrl.finished = true

	// If we're currently panicking, probably because this is a deferred call,
	// pass through the panic.
	if err := recover(); err != nil {
		panic(err)
	}

	// Check that all remaining expected calls are satisfied.
	failures := ctrl.expectedCalls.Failures()
	for _, call := range failures {
		ctrl.T.Errorf("missing call(s) to %v", call)
	}
	if len(failures) != 0 {
		ctrl.T.Fatalf("aborting test due to missing call(s)")
	}
}

func callerInfo(skip int) string {
	if _, file, line, ok := runtime.Caller(skip + 1); ok {
		return fmt.Sprintf("%s:%d", file, line)
	}
	return "unknown file"
}
<|endoftext|>


<commit_before>package blockchain

// BlockHeader contains metadata about a block
import (
	"encoding/binary"
	"encoding/gob"
	"fmt"
	"io"
)

const (
	// MaxBlockSize is the maximum size of a block in bytes when marshaled
	// (about 250K).
	MaxBlockSize = 1 << 18
)

// BlockHeader contains metadata about a block
type BlockHeader struct {
	// BlockNumber is the position of the block within the blockchain
	BlockNumber uint32
	// LastBlock is the hash of the previous block
	LastBlock Hash
	// Target is the current target
	Target Hash
	// Time is represented as the number of seconds elapsed
	// since January 1, 1970 UTC. It increments every second when mining.
	Time uint32
	// Nonce starts at 0 and increments by 1 for every hash when mining
	Nonce uint64
	// ExtraData is an extra field that can be filled with arbitrary data to
	// be stored in the block
	ExtraData []byte
}

// Marshal converts a BlockHeader to a byte slice
func (bh *BlockHeader) Marshal() []byte {
	var buf []byte

	tempBufBlockNumber := make([]byte, 4)
	binary.LittleEndian.PutUint32(tempBufBlockNumber, bh.BlockNumber)

	tempBufTime := make([]byte, 4)
	binary.LittleEndian.PutUint32(tempBufTime, bh.Time)

	tempBufNonce := make([]byte, 8)
	binary.LittleEndian.PutUint64(tempBufNonce, bh.Nonce)

	buf = append(buf, tempBufBlockNumber...)
	buf = append(buf, bh.LastBlock.Marshal()...)
	buf = append(buf, bh.Target.Marshal()...)
	buf = append(buf, tempBufTime...)
	buf = append(buf, tempBufNonce...)
	buf = append(buf, bh.ExtraData...)

	return buf
}

// Len returns the length in bytes of the BlockHeader.
func (bh *BlockHeader) Len() int {
	return len(bh.Marshal())
}

// Block represents a block in the blockchain. Contains transactions and header metadata.
type Block struct {
	BlockHeader
	Transactions []*Transaction
}

// Len returns the length in bytes of the Block.
func (b *Block) Len() int {
	return len(b.Marshal())
}

// Marshal converts a Block to a byte slice.
func (b *Block) Marshal() []byte {
	var buf []byte
	buf = append(buf, b.BlockHeader.Marshal()...)
	for _, t := range b.Transactions {
		buf = append(buf, t.Marshal()...)
	}
	return buf
}

// Encode writes the marshalled block to the given io.Writer
func (b *Block) Encode(w io.Writer) {
	err := gob.NewEncoder(w).Encode(b)
	if err != nil {
		fmt.Println(err.Error())
	}
}

// DecodeBlock reads the marshalled block from the given io.Reader and populates b
func DecodeBlock(r io.Reader) *Block {
	var b Block
	gob.NewDecoder(r).Decode(&b)
	return &b
}

// ContainsTransaction returns true and the transaction itself if the Block
// contains the transaction.
func (b *Block) ContainsTransaction(t *Transaction) (bool, uint32) {
	for i, tr := range b.Transactions {
		if HashSum(t) == HashSum(tr) {
			return true, uint32(i)
		}
	}
	return false, 0
}

// GetCloudBaseTransaction returns the CloudBase transaction within a block
func (b *Block) GetCloudBaseTransaction() *Transaction {
	return b.Transactions[0]
}
<commit_msg>remove max block size constant<commit_after>package blockchain

// BlockHeader contains metadata about a block
import (
	"encoding/binary"
	"encoding/gob"
	"fmt"
	"io"
)

// BlockHeader contains metadata about a block
type BlockHeader struct {
	// BlockNumber is the position of the block within the blockchain
	BlockNumber uint32
	// LastBlock is the hash of the previous block
	LastBlock Hash
	// Target is the current target
	Target Hash
	// Time is represented as the number of seconds elapsed
	// since January 1, 1970 UTC. It increments every second when mining.
	Time uint32
	// Nonce starts at 0 and increments by 1 for every hash when mining
	Nonce uint64
	// ExtraData is an extra field that can be filled with arbitrary data to
	// be stored in the block
	ExtraData []byte
}

// Marshal converts a BlockHeader to a byte slice
func (bh *BlockHeader) Marshal() []byte {
	var buf []byte

	tempBufBlockNumber := make([]byte, 4)
	binary.LittleEndian.PutUint32(tempBufBlockNumber, bh.BlockNumber)

	tempBufTime := make([]byte, 4)
	binary.LittleEndian.PutUint32(tempBufTime, bh.Time)

	tempBufNonce := make([]byte, 8)
	binary.LittleEndian.PutUint64(tempBufNonce, bh.Nonce)

	buf = append(buf, tempBufBlockNumber...)
	buf = append(buf, bh.LastBlock.Marshal()...)
	buf = append(buf, bh.Target.Marshal()...)
	buf = append(buf, tempBufTime...)
	buf = append(buf, tempBufNonce...)
	buf = append(buf, bh.ExtraData...)

	return buf
}

// Len returns the length in bytes of the BlockHeader.
func (bh *BlockHeader) Len() int {
	return len(bh.Marshal())
}

// Block represents a block in the blockchain. Contains transactions and header metadata.
type Block struct {
	BlockHeader
	Transactions []*Transaction
}

// Len returns the length in bytes of the Block.
func (b *Block) Len() int {
	return len(b.Marshal())
}

// Marshal converts a Block to a byte slice.
func (b *Block) Marshal() []byte {
	var buf []byte
	buf = append(buf, b.BlockHeader.Marshal()...)
	for _, t := range b.Transactions {
		buf = append(buf, t.Marshal()...)
	}
	return buf
}

// Encode writes the marshalled block to the given io.Writer
func (b *Block) Encode(w io.Writer) {
	err := gob.NewEncoder(w).Encode(b)
	if err != nil {
		fmt.Println(err.Error())
	}
}

// DecodeBlock reads the marshalled block from the given io.Reader and populates b
func DecodeBlock(r io.Reader) *Block {
	var b Block
	gob.NewDecoder(r).Decode(&b)
	return &b
}

// ContainsTransaction returns true and the transaction itself if the Block
// contains the transaction.
func (b *Block) ContainsTransaction(t *Transaction) (bool, uint32) {
	for i, tr := range b.Transactions {
		if HashSum(t) == HashSum(tr) {
			return true, uint32(i)
		}
	}
	return false, 0
}

// GetCloudBaseTransaction returns the CloudBase transaction within a block
func (b *Block) GetCloudBaseTransaction() *Transaction {
	return b.Transactions[0]
}
<|endoftext|>


<commit_before>package sudoku

//GridModification is a series of CellModifications to apply to a Grid.
type GridModification []*CellModification

//CellModification represents a modification to be made to a given Cell in a
//grid.
type CellModification struct {
	//The cell representing the cell to modify. The cell's analog (at the same
	//row, col address) will be modified in the new grid.
	Cell Cell
	//The number to put in the cell. Negative numbers signify no changes.
	Number int
	//The excludes to proactively set. Invalid numbers will be ignored.
	//Indexes not listed will be left the same.
	ExcludesChanges map[int]bool
	//The marks to proactively set. Invalid numbers will be ignored.
	//Indexes not listed will be left the same.
	MarksChanges map[int]bool
}

//TODO: audit all uses of step/compoundstep.Apply()

//TOOD: make readOnlyCellImpl. Test if neighbors should be derived or not.
//Everything should be actual contiguous memory, no pointers (except for
//grid). Likely should make cellImpl embed a readOnlyCellImpl and only
//override items it needs to.

//TODO: make readOnlyGridImpl. Two possible approaches: a version that is
//incredibly easy to copy and then do minor tweaks. Or a version that stores a
//dictionary of cell configs, and any time you grab a Cell we look it up in
//the dict or in the ancestors' dicts.

//newCellModification returns a CellModification for the given cell that is a
//no-op.
func newCellModification(cell Cell) *CellModification {
	return &CellModification{
		Cell:            cell,
		Number:          -1,
		ExcludesChanges: make(map[int]bool),
		MarksChanges:    make(map[int]bool),
	}
}

//equivalent returns true if the other grid modification is equivalent to this one.
func (m GridModification) equivalent(other GridModification) bool {
	if len(m) != len(other) {
		return false
	}
	for i, modification := range m {
		otherModification := other[i]
		if modification.Cell.ref().String() != otherModification.Cell.ref().String() {
			return false
		}
		if modification.Number != otherModification.Number {
			return false
		}

		if len(modification.ExcludesChanges) != len(otherModification.ExcludesChanges) {
			return false
		}

		for key, val := range modification.ExcludesChanges {
			otherVal, ok := otherModification.ExcludesChanges[key]
			if !ok {
				return false
			}
			if val != otherVal {
				return false
			}
		}

		if len(modification.MarksChanges) != len(otherModification.MarksChanges) {
			return false
		}

		for key, val := range modification.MarksChanges {
			otherVal, ok := otherModification.MarksChanges[key]
			if !ok {
				return false
			}
			if val != otherVal {
				return false
			}
		}
	}
	return true
}

func (self *gridImpl) CopyWithModifications(modifications GridModification) Grid {

	//TODO: test this implementation deeply! Lots of crazy stuff that could go
	//wrong.

	result := new(gridImpl)

	//Copy in everything
	*result = *self

	for i := 0; i < DIM*DIM; i++ {
		cell := &result.cells[i]
		cell.gridRef = result
	}

	cellNumberModified := false

	for _, modification := range modifications {
		cell := result.cellImpl(modification.Cell.Row(), modification.Cell.Col())

		if modification.Number >= 0 && modification.Number <= DIM {
			//cell.setNumber will handle setting all of the impossibles
			if cell.setNumber(modification.Number) {
				cellNumberModified = true
			}
		}

		for key, val := range modification.ExcludesChanges {
			//Key is 1-indexed
			key--
			cell.excluded[key] = val
		}

		for key, val := range modification.MarksChanges {
			//Key is 1-indexed
			key--
			cell.marks[key] = val
		}
	}

	if cellNumberModified {

		//At least one cell's number was modified, which means we need to fix
		//up the queue, numFilledCells, Invalid, Solved.

		filledCellsCount := 0

		for _, cell := range result.cells {
			if cell.number == 0 {
				continue
			}
			filledCellsCount++
		}

		result.filledCellsCount = filledCellsCount

		//Check if we're invalid.

		invalid := false

		for _, cell := range result.cells {
			//Make sure we have at least one possibility per cell
			foundPossibility := false
			for i := 0; i < DIM; i++ {
				if cell.impossibles[i] == 0 {
					foundPossibility = true
					break
				}
			}
			if !foundPossibility {
				invalid = true
				break
			}
		}

		if !invalid {
			//Let's do a deep check
			invalid = gridGroupsInvalid(result)
		}

		result.invalid = invalid

		if filledCellsCount == DIM*DIM && !result.invalid {
			//All cells are filled and it's not invalid, so it's solved!
			result.solved = true
		} else {
			//No way it's solved
			result.solved = false
		}

		result.theQueue.fix()
	}

	return result

}

func (self *mutableGridImpl) CopyWithModifications(modifications GridModification) Grid {
	//TODO: when we have an honest-to-god readonly grid impl, optimize this.
	result := self.MutableCopy()

	for _, modification := range modifications {
		cell := modification.Cell.MutableInGrid(result)

		if modification.Number >= 0 && modification.Number <= DIM {
			cell.SetNumber(modification.Number)
		}

		for key, val := range modification.ExcludesChanges {
			//setExcluded will skip invalid entries
			cell.SetExcluded(key, val)
		}

		for key, val := range modification.MarksChanges {
			//SetMark will skip invalid numbers
			cell.SetMark(key, val)
		}
	}

	return result
}
<commit_msg>Made it so CopyWithModifications with a non-mutable grid will pass TestCopyWithModifications.<commit_after>package sudoku

//GridModification is a series of CellModifications to apply to a Grid.
type GridModification []*CellModification

//CellModification represents a modification to be made to a given Cell in a
//grid.
type CellModification struct {
	//The cell representing the cell to modify. The cell's analog (at the same
	//row, col address) will be modified in the new grid.
	Cell Cell
	//The number to put in the cell. Negative numbers signify no changes.
	Number int
	//The excludes to proactively set. Invalid numbers will be ignored.
	//Indexes not listed will be left the same.
	ExcludesChanges map[int]bool
	//The marks to proactively set. Invalid numbers will be ignored.
	//Indexes not listed will be left the same.
	MarksChanges map[int]bool
}

//TODO: audit all uses of step/compoundstep.Apply()

//TOOD: make readOnlyCellImpl. Test if neighbors should be derived or not.
//Everything should be actual contiguous memory, no pointers (except for
//grid). Likely should make cellImpl embed a readOnlyCellImpl and only
//override items it needs to.

//TODO: make readOnlyGridImpl. Two possible approaches: a version that is
//incredibly easy to copy and then do minor tweaks. Or a version that stores a
//dictionary of cell configs, and any time you grab a Cell we look it up in
//the dict or in the ancestors' dicts.

//newCellModification returns a CellModification for the given cell that is a
//no-op.
func newCellModification(cell Cell) *CellModification {
	return &CellModification{
		Cell:            cell,
		Number:          -1,
		ExcludesChanges: make(map[int]bool),
		MarksChanges:    make(map[int]bool),
	}
}

//normalize makes sure the GridModification is legal.
func (m GridModification) normalize() {
	for _, cellModification := range m {
		for key, _ := range cellModification.ExcludesChanges {
			if key <= 0 || key > DIM {
				delete(cellModification.ExcludesChanges, key)
			}
		}
		for key, _ := range cellModification.MarksChanges {
			if key <= 0 || key > DIM {
				delete(cellModification.MarksChanges, key)
			}
		}

		if cellModification.Number < -1 || cellModification.Number > DIM {
			cellModification.Number = -1
		}
	}

}

//equivalent returns true if the other grid modification is equivalent to this one.
func (m GridModification) equivalent(other GridModification) bool {
	if len(m) != len(other) {
		return false
	}
	for i, modification := range m {
		otherModification := other[i]
		if modification.Cell.ref().String() != otherModification.Cell.ref().String() {
			return false
		}
		if modification.Number != otherModification.Number {
			return false
		}

		if len(modification.ExcludesChanges) != len(otherModification.ExcludesChanges) {
			return false
		}

		for key, val := range modification.ExcludesChanges {
			otherVal, ok := otherModification.ExcludesChanges[key]
			if !ok {
				return false
			}
			if val != otherVal {
				return false
			}
		}

		if len(modification.MarksChanges) != len(otherModification.MarksChanges) {
			return false
		}

		for key, val := range modification.MarksChanges {
			otherVal, ok := otherModification.MarksChanges[key]
			if !ok {
				return false
			}
			if val != otherVal {
				return false
			}
		}
	}
	return true
}

func (self *gridImpl) CopyWithModifications(modifications GridModification) Grid {

	//TODO: test this implementation deeply! Lots of crazy stuff that could go
	//wrong.

	modifications.normalize()

	result := new(gridImpl)

	//Copy in everything
	*result = *self

	for i := 0; i < DIM*DIM; i++ {
		cell := &result.cells[i]
		cell.gridRef = result
	}

	cellNumberModified := false

	for _, modification := range modifications {
		cell := result.cellImpl(modification.Cell.Row(), modification.Cell.Col())

		if modification.Number >= 0 && modification.Number <= DIM {
			//cell.setNumber will handle setting all of the impossibles
			if cell.setNumber(modification.Number) {
				cellNumberModified = true
			}
		}

		for key, val := range modification.ExcludesChanges {
			//Key is 1-indexed
			key--
			cell.excluded[key] = val
		}

		for key, val := range modification.MarksChanges {
			//Key is 1-indexed
			key--
			cell.marks[key] = val
		}
	}

	if cellNumberModified {

		//At least one cell's number was modified, which means we need to fix
		//up the queue, numFilledCells, Invalid, Solved.

		filledCellsCount := 0

		for _, cell := range result.cells {
			if cell.number == 0 {
				continue
			}
			filledCellsCount++
		}

		result.filledCellsCount = filledCellsCount

		//Check if we're invalid.

		invalid := false

		for _, cell := range result.cells {
			//Make sure we have at least one possibility per cell
			foundPossibility := false
			for i := 0; i < DIM; i++ {
				if cell.impossibles[i] == 0 {
					foundPossibility = true
					break
				}
			}
			if !foundPossibility {
				invalid = true
				break
			}
		}

		if !invalid {
			//Let's do a deep check
			invalid = gridGroupsInvalid(result)
		}

		result.invalid = invalid

		if filledCellsCount == DIM*DIM && !result.invalid {
			//All cells are filled and it's not invalid, so it's solved!
			result.solved = true
		} else {
			//No way it's solved
			result.solved = false
		}

		result.theQueue.fix()
	}

	return result

}

func (self *mutableGridImpl) CopyWithModifications(modifications GridModification) Grid {
	//TODO: when we have an honest-to-god readonly grid impl, optimize this.
	result := self.MutableCopy()

	modifications.normalize()

	for _, modification := range modifications {
		cell := modification.Cell.MutableInGrid(result)

		if modification.Number >= 0 && modification.Number <= DIM {
			cell.SetNumber(modification.Number)
		}

		for key, val := range modification.ExcludesChanges {
			//setExcluded will skip invalid entries
			cell.SetExcluded(key, val)
		}

		for key, val := range modification.MarksChanges {
			//SetMark will skip invalid numbers
			cell.SetMark(key, val)
		}
	}

	return result
}
<|endoftext|>


<commit_before>package interceptor

import (
	"encoding/json"
	"github.com/datawire/teleproxy/internal/pkg/nat"
	rt "github.com/datawire/teleproxy/internal/pkg/route"
	"log"
	"net"
	"strings"
	"sync"
)

type Interceptor struct {
	work chan func()
	done chan empty

	translator *nat.Translator
	tables     map[string]rt.Table
	tablesLock sync.RWMutex

	domains     map[string]rt.Route
	domainsLock sync.RWMutex

	search     []string
	searchLock sync.RWMutex
}

type empty struct{}

func NewInterceptor(name string) *Interceptor {
	ret := &Interceptor{
		tables:     make(map[string]rt.Table),
		translator: nat.NewTranslator(name),
		work:       make(chan func()),
		done:       make(chan empty),
		domains:    make(map[string]rt.Route),
		search:     []string{""},
	}
	ret.tablesLock.Lock() // leave it locked until .Start() unlocks it
	return ret
}

func (i *Interceptor) Start() {
	go func() {
		defer close(i.done)
		i.translator.Enable()
		i.tablesLock.Unlock()
		defer func() {
			i.tablesLock.Lock()
			i.translator.Disable()
		}()
		for {
			action, ok := <-i.work
			if ok {
				action()
			} else {
				return
			}
		}
	}()
}

func (i *Interceptor) Stop() {
	close(i.work)
	<-i.done
}

// Resolve looks up the given query in the (FIXME: somewhere), trying
// all the suffixes in the search path, and returns a Route on success
// or nil on failure. This implementation does not count the number of
// dots in the query.
func (i *Interceptor) Resolve(query string) *rt.Route {
	if !strings.HasSuffix(query, ".") {
		query += "."
	}

	i.searchLock.RLock()
	defer i.searchLock.RUnlock()
	i.domainsLock.RLock()
	defer i.domainsLock.RUnlock()

	for _, suffix := range i.search {
		name := query + suffix
		value, ok := i.domains[strings.ToLower(name)]
		if ok {
			return &value
		}
	}
	return nil
}

func (i *Interceptor) Destination(conn *net.TCPConn) (string, error) {
	_, host, err := i.translator.GetOriginalDst(conn)
	return host, err
}

func (i *Interceptor) Render(table string) string {
	var obj interface{}

	if table == "" {
		var tables []rt.Table
		i.tablesLock.RLock()
		for _, t := range i.tables {
			tables = append(tables, t)
		}
		i.tablesLock.RUnlock()
		obj = tables
	} else {
		var ok bool
		i.tablesLock.RLock()
		obj, ok = i.tables[table]
		i.tablesLock.RUnlock()
		if !ok {
			return ""
		}
	}

	bytes, err := json.MarshalIndent(obj, "", "  ")
	if err != nil {
		return err.Error()
	} else {
		return string(bytes)
	}
}

func (i *Interceptor) Delete(table string) bool {
	i.tablesLock.Lock()
	defer i.tablesLock.Unlock()
	i.domainsLock.Lock()
	defer i.domainsLock.Unlock()

	var names []string
	if table == "" {
		for name := range i.tables {
			names = append(names, name)
		}
	} else if _, ok := i.tables[table]; ok {
		names = []string{table}
	} else {
		return false
	}

	for _, name := range names {
		if name != "bootstrap" {
			i.update(rt.Table{Name: name})
		}
	}

	return true
}

func (i *Interceptor) Update(table rt.Table) {
	i.tablesLock.Lock()
	defer i.tablesLock.Unlock()
	i.domainsLock.Lock()
	defer i.domainsLock.Unlock()

	i.update(table)
}

// .update() assumes that both .tablesLock and .domainsLock are held
// for writing.  Ensuring that is the case is the caller's
// responsibility.
func (i *Interceptor) update(table rt.Table) {
	oldTable, ok := i.tables[table.Name]

	oldRoutes := make(map[string]rt.Route)
	if ok {
		for _, route := range oldTable.Routes {
			oldRoutes[route.Name] = route
		}
	}

	for _, newRoute := range table.Routes {
		oldRoute, oldRouteOk := oldRoutes[newRoute.Name]
		// A nil Route (when oldRouteOk != true) will compare
		// inequal to any valid new Route.
		if newRoute != oldRoute {
			// delete the old version
			if oldRouteOk {
				switch newRoute.Proto {
				case "tcp":
					i.translator.ClearTCP(oldRoute.Ip)
				case "udp":
					i.translator.ClearUDP(oldRoute.Ip)
				default:
					log.Printf("INT: unrecognized protocol: %v", newRoute)
				}
			}
			// and add the new version
			if newRoute.Target != "" {
				switch newRoute.Proto {
				case "tcp":
					i.translator.ForwardTCP(newRoute.Ip, newRoute.Target)
				case "udp":
					i.translator.ForwardUDP(newRoute.Ip, newRoute.Target)
				default:
					log.Printf("INT: unrecognized protocol: %v", newRoute)
				}
			}

			if newRoute.Name != "" {
				log.Printf("INT: STORE %v->%v", newRoute.Domain(), newRoute)
				i.domains[newRoute.Domain()] = newRoute
			}
		}

		// remove the route from our map of old routes so we
		// don't end up deleting it below
		delete(oldRoutes, newRoute.Name)
	}

	for _, route := range oldRoutes {
		log.Printf("INT: CLEAR %v->%v", route.Domain(), route)
		delete(i.domains, route.Domain())

		switch route.Proto {
		case "tcp":
			i.translator.ClearTCP(route.Ip)
		case "udp":
			i.translator.ClearUDP(route.Ip)
		default:
			log.Printf("INT: unrecognized protocol: %v", route)
		}

	}

	if table.Routes == nil || len(table.Routes) == 0 {
		delete(i.tables, table.Name)
	} else {
		i.tables[table.Name] = table
	}
}

// SetSearchPath updates the DNS search path used by the resolver
func (i *Interceptor) SetSearchPath(paths []string) {
	i.searchLock.Lock()
	defer i.searchLock.Unlock()

	i.search = paths
}

// GetSearchPath retrieves the current search path
func (i *Interceptor) GetSearchPath() []string {
	i.searchLock.RLock()
	defer i.searchLock.RUnlock()

	return i.search
}
<commit_msg>interceptor: Begone with the now-pointless worker thread<commit_after>package interceptor

import (
	"encoding/json"
	"github.com/datawire/teleproxy/internal/pkg/nat"
	rt "github.com/datawire/teleproxy/internal/pkg/route"
	"log"
	"net"
	"strings"
	"sync"
)

type Interceptor struct {
	translator *nat.Translator
	tables     map[string]rt.Table
	tablesLock sync.RWMutex

	domains     map[string]rt.Route
	domainsLock sync.RWMutex

	search     []string
	searchLock sync.RWMutex
}

func NewInterceptor(name string) *Interceptor {
	ret := &Interceptor{
		tables:     make(map[string]rt.Table),
		translator: nat.NewTranslator(name),
		domains:    make(map[string]rt.Route),
		search:     []string{""},
	}
	ret.tablesLock.Lock() // leave it locked until .Start() unlocks it
	return ret
}

func (i *Interceptor) Start() {
	go func() {
		i.translator.Enable()
		i.tablesLock.Unlock()
	}()
}

func (i *Interceptor) Stop() {
	i.tablesLock.Lock()
	i.translator.Disable()
	// leave it locked
}

// Resolve looks up the given query in the (FIXME: somewhere), trying
// all the suffixes in the search path, and returns a Route on success
// or nil on failure. This implementation does not count the number of
// dots in the query.
func (i *Interceptor) Resolve(query string) *rt.Route {
	if !strings.HasSuffix(query, ".") {
		query += "."
	}

	i.searchLock.RLock()
	defer i.searchLock.RUnlock()
	i.domainsLock.RLock()
	defer i.domainsLock.RUnlock()

	for _, suffix := range i.search {
		name := query + suffix
		value, ok := i.domains[strings.ToLower(name)]
		if ok {
			return &value
		}
	}
	return nil
}

func (i *Interceptor) Destination(conn *net.TCPConn) (string, error) {
	_, host, err := i.translator.GetOriginalDst(conn)
	return host, err
}

func (i *Interceptor) Render(table string) string {
	var obj interface{}

	if table == "" {
		var tables []rt.Table
		i.tablesLock.RLock()
		for _, t := range i.tables {
			tables = append(tables, t)
		}
		i.tablesLock.RUnlock()
		obj = tables
	} else {
		var ok bool
		i.tablesLock.RLock()
		obj, ok = i.tables[table]
		i.tablesLock.RUnlock()
		if !ok {
			return ""
		}
	}

	bytes, err := json.MarshalIndent(obj, "", "  ")
	if err != nil {
		return err.Error()
	} else {
		return string(bytes)
	}
}

func (i *Interceptor) Delete(table string) bool {
	i.tablesLock.Lock()
	defer i.tablesLock.Unlock()
	i.domainsLock.Lock()
	defer i.domainsLock.Unlock()

	var names []string
	if table == "" {
		for name := range i.tables {
			names = append(names, name)
		}
	} else if _, ok := i.tables[table]; ok {
		names = []string{table}
	} else {
		return false
	}

	for _, name := range names {
		if name != "bootstrap" {
			i.update(rt.Table{Name: name})
		}
	}

	return true
}

func (i *Interceptor) Update(table rt.Table) {
	i.tablesLock.Lock()
	defer i.tablesLock.Unlock()
	i.domainsLock.Lock()
	defer i.domainsLock.Unlock()

	i.update(table)
}

// .update() assumes that both .tablesLock and .domainsLock are held
// for writing.  Ensuring that is the case is the caller's
// responsibility.
func (i *Interceptor) update(table rt.Table) {
	oldTable, ok := i.tables[table.Name]

	oldRoutes := make(map[string]rt.Route)
	if ok {
		for _, route := range oldTable.Routes {
			oldRoutes[route.Name] = route
		}
	}

	for _, newRoute := range table.Routes {
		oldRoute, oldRouteOk := oldRoutes[newRoute.Name]
		// A nil Route (when oldRouteOk != true) will compare
		// inequal to any valid new Route.
		if newRoute != oldRoute {
			// delete the old version
			if oldRouteOk {
				switch newRoute.Proto {
				case "tcp":
					i.translator.ClearTCP(oldRoute.Ip)
				case "udp":
					i.translator.ClearUDP(oldRoute.Ip)
				default:
					log.Printf("INT: unrecognized protocol: %v", newRoute)
				}
			}
			// and add the new version
			if newRoute.Target != "" {
				switch newRoute.Proto {
				case "tcp":
					i.translator.ForwardTCP(newRoute.Ip, newRoute.Target)
				case "udp":
					i.translator.ForwardUDP(newRoute.Ip, newRoute.Target)
				default:
					log.Printf("INT: unrecognized protocol: %v", newRoute)
				}
			}

			if newRoute.Name != "" {
				log.Printf("INT: STORE %v->%v", newRoute.Domain(), newRoute)
				i.domains[newRoute.Domain()] = newRoute
			}
		}

		// remove the route from our map of old routes so we
		// don't end up deleting it below
		delete(oldRoutes, newRoute.Name)
	}

	for _, route := range oldRoutes {
		log.Printf("INT: CLEAR %v->%v", route.Domain(), route)
		delete(i.domains, route.Domain())

		switch route.Proto {
		case "tcp":
			i.translator.ClearTCP(route.Ip)
		case "udp":
			i.translator.ClearUDP(route.Ip)
		default:
			log.Printf("INT: unrecognized protocol: %v", route)
		}

	}

	if table.Routes == nil || len(table.Routes) == 0 {
		delete(i.tables, table.Name)
	} else {
		i.tables[table.Name] = table
	}
}

// SetSearchPath updates the DNS search path used by the resolver
func (i *Interceptor) SetSearchPath(paths []string) {
	i.searchLock.Lock()
	defer i.searchLock.Unlock()

	i.search = paths
}

// GetSearchPath retrieves the current search path
func (i *Interceptor) GetSearchPath() []string {
	i.searchLock.RLock()
	defer i.searchLock.RUnlock()

	return i.search
}
<|endoftext|>


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

package restore

import (
	"log"

	"github.com/jacobsa/comeback/internal/blob"
	"github.com/jacobsa/comeback/internal/dag"
)

// Create a dag.DependencyResolver for *node.
//
// For directories, dependencies are resolved by loading a listing from
// n.Info.Scores[0], which must exist and be the only score. No other nodes
// have dependencies.
//
// Child nodes returned are filled into node.Children fields.
func newDependencyResolver(
	blobStore blob.Store,
	logger *log.Logger) (dr dag.DependencyResolver) {
	panic("TODO")
}
<commit_msg>newDependencyResolver<commit_after>// Copyright 2015 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package restore

import (
	"errors"
	"log"

	"golang.org/x/net/context"

	"github.com/jacobsa/comeback/internal/blob"
	"github.com/jacobsa/comeback/internal/dag"
)

// Create a dag.DependencyResolver for *node.
//
// For directories, dependencies are resolved by loading a listing from
// n.Info.Scores[0], which must exist and be the only score. No other nodes
// have dependencies.
//
// Child nodes returned are filled into node.Children fields.
func newDependencyResolver(
	blobStore blob.Store,
	logger *log.Logger) (dr dag.DependencyResolver) {
	dr = &dependencyResolver{
		blobStore: blobStore,
		logger:    logger,
	}

	return
}

type dependencyResolver struct {
	blobStore blob.Store
	logger    *log.Logger
}

func (dr *dependencyResolver) FindDependencies(
	ctx context.Context,
	untyped dag.Node) (deps []dag.Node, err error) {
	err = errors.New("TODO")
	return
}
<|endoftext|>


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

package veto

import (
	"github.com/nmeum/marvin/irc"
	"time"
)

type Module struct {
	timer       *time.Timer
	duration    time.Duration
	DurationStr string `json:"duration"`
}

func (m *Module) Name() string {
	return "veto"
}

func (m *Module) Help() string {
	return "USAGE: !veto"
}

func (m *Module) Defaults() {
	m.DurationStr = "0h90s"
}

func (m *Module) Load(client *irc.Client) (err error) {
	m.duration, err = time.ParseDuration(m.DurationStr)
	if err != nil {
		return
	}

	client.CmdHook("privmsg", m.vetoCmd)
	return
}

func (m *Module) Start() bool {
	ret := false
	m.timer = time.AfterFunc(m.duration, func() {
		ret = true
	})

	return ret
}

func (m *Module) vetoCmd(client *irc.Client, msg irc.Message) error {
	if msg.Data != "!veto" {
		return nil
	}

	if m.timer != nil && m.timer.Stop() {
		return client.Write("NOTICE %s :%s has invoked his right to veto",
			msg.Receiver, msg.Sender.Name)
	}

	return client.Write("NOTICE %s :%s", msg.Receiver, "no vote takes place currently")
}
<commit_msg>Revert "veto: Don't provide init function"<commit_after>// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public
// License along with this program. If not, see <http://www.gnu.org/licenses/>.

package veto

import (
	"github.com/nmeum/marvin/irc"
	"github.com/nmeum/marvin/modules"
	"time"
)

type Module struct {
	timer       *time.Timer
	duration    time.Duration
	DurationStr string `json:"duration"`
}

func Init(moduleSet *modules.ModuleSet) {
	moduleSet.Register(new(Module))
}

func (m *Module) Name() string {
	return "veto"
}

func (m *Module) Help() string {
	return "USAGE: !veto"
}

func (m *Module) Defaults() {
	m.DurationStr = "0h90s"
}

func (m *Module) Load(client *irc.Client) (err error) {
	m.duration, err = time.ParseDuration(m.DurationStr)
	if err != nil {
		return
	}

	client.CmdHook("privmsg", m.vetoCmd)
	return
}

func (m *Module) Start() bool {
	ret := false
	m.timer = time.AfterFunc(m.duration, func() {
		ret = true
	})

	return ret
}

func (m *Module) vetoCmd(client *irc.Client, msg irc.Message) error {
	if msg.Data != "!veto" {
		return nil
	}

	if m.timer != nil && m.timer.Stop() {
		return client.Write("NOTICE %s :%s has invoked his right to veto",
			msg.Receiver, msg.Sender.Name)
	}

	return client.Write("NOTICE %s :%s", msg.Receiver, "no vote takes place currently")
}
<|endoftext|>


<commit_before>package bradesco

const registerBradesco = `
## Content-Type:application/json
## Authorization:Basic {{base64 (concat .Authentication.Username ":" .Authentication.Password)}}
{
    "merchant_id": "{{.Authentication.Username}}",
    "meio_pagamento": "300",
    "pedido": {
        "numero": "{{.Title.DocumentNumber}}",
        "valor": {{.Title.AmountInCents}},
        "descricao": ""
    },
    "comprador": {
        "nome": "{{.Buyer.Name}}",
        "documento": "{{.Buyer.Document.Number}}",
        "endereco": {
            "cep": "{{.Buyer.Address.ZipCode}}",
            "logradouro": "{{.Buyer.Address.Street}}",
            "numero": "{{.Buyer.Address.Number}}",
            "complemento": "{{.Buyer.Address.Complement}}",
            "bairro": "{{.Buyer.Address.District}}",
            "cidade": "{{.Buyer.Address.City}}",
            "uf": "{{.Buyer.Address.StateCode}}"
        },
        "ip": "",
        "user_agent": ""
    },
    "boleto": {
        "beneficiario": "{{.Recipient.Name}}",
        "carteira": "{{.Agreement.Wallet}}",
        "nosso_numero": "{{padLeft (toString .Title.OurNumber) "0" 11}}",
        "data_emissao": "{{enDate today "-"}}",
        "data_vencimento": "{{enDate .Title.ExpireDateTime "-"}}",
        "valor_titulo": {{.Title.AmountInCents}},
        "url_logotipo": "",
        "mensagem_cabecalho": "mensagem de cabecalho",
        "tipo_renderizacao": "2",
        "instrucoes": {
            "instrucao_linha_1": "{{.Title.Instructions}}",
            "instrucao_linha_2": "instrucao 02",
            "instrucao_linha_3": "instrucao 03"
        },
        "registro": {
            "agencia_pagador": "00014",
            "razao_conta_pagador": "07050",
            "conta_pagador": "12345679",
            "controle_participante": "Segurança arquivo remessa",
            "aplicar_multa": true,
            "valor_percentual_multa": 0,
            "valor_desconto_bonificacao": 0,
            "debito_automatico": false,
            "rateio_credito": false,
            "endereco_debito_automatico": "1",
            "tipo_ocorrencia": "02",
            "especie_titulo": "01",
            "primeira_instrucao": "00",
            "segunda_instrucao": "00",
            "valor_juros_mora": 0,
            "data_limite_concessao_desconto": null,
            "valor_desconto": 0,
            "valor_iof": 0,
            "valor_abatimento": 0,
            {{if (eq .Buyer.Document.Type "CPF")}}
            	"tipo_inscricao_pagador": "02",
			{{else}}
            	"tipo_inscricao_pagador": "01",
			{{end}}
            "sequencia_registro": "00001"
        }
    },
    "token_request_confirmacao_pagamento": "21323dsd23434ad12178DDasY"
}
`

const responseBradesco = `
{
    "boleto": {
        "linha_digitavel_formatada": "{{digitableLine}}",
        "url_acesso": "{{url}}"
    },
    "status": {
        "codigo": "{{returnCode}}",
        "mensagem": "{{returnMessage}}"
    }
}
`

func getRequestBradesco() string{
	return registerBradesco
}

func getResponseBradesco() string  {
	return responseBradesco
}<commit_msg>Alter request bradesco<commit_after>package bradesco

const registerBradesco = `
## Content-Type:application/json
## Authorization:Basic {{base64 (concat .Authentication.Username ":" .Authentication.Password)}}
{
    "merchant_id": "{{.Authentication.Username}}",
    "meio_pagamento": "300",
    "pedido": {
        "numero": "{{.Title.DocumentNumber}}",
        "valor": {{.Title.AmountInCents}},
        "descricao": ""
    },
    "comprador": {
        "nome": "{{.Buyer.Name}}",
        "documento": "{{.Buyer.Document.Number}}",
        "endereco": {
            "cep": "{{.Buyer.Address.ZipCode}}",
            "logradouro": "{{.Buyer.Address.Street}}",
            "numero": "{{.Buyer.Address.Number}}",
            "complemento": "{{.Buyer.Address.Complement}}",
            "bairro": "{{.Buyer.Address.District}}",
            "cidade": "{{.Buyer.Address.City}}",
            "uf": "{{.Buyer.Address.StateCode}}"
        },
        "ip": "",
        "user_agent": ""
    },
    "boleto": {
        "beneficiario": "{{.Recipient.Name}}",
        "carteira": "{{.Agreement.Wallet}}",
        "nosso_numero": "{{padLeft (toString .Title.OurNumber) "0" 11}}",
        "data_emissao": "{{enDate today "-"}}",
        "data_vencimento": "{{enDate .Title.ExpireDateTime "-"}}",
        "valor_titulo": {{.Title.AmountInCents}},
        "url_logotipo": "",
        "mensagem_cabecalho": "",
        "tipo_renderizacao": "1",
        "instrucoes": {
            "instrucao_linha_1": "{{.Title.Instructions}}"
        },
        "registro": {
            "agencia_pagador": "",
            "razao_conta_pagador": "",
            "conta_pagador": "",
            "controle_participante": "",
            "aplicar_multa": false,
            "valor_percentual_multa": 0,
            "valor_desconto_bonificacao": 0,
            "debito_automatico": false,
            "rateio_credito": false,
            "endereco_debito_automatico": "2",
            "tipo_ocorrencia": "02",
            "especie_titulo": "01",
            "primeira_instrucao": "00",
            "segunda_instrucao": "00",
            "valor_juros_mora": 0,
            "data_limite_concessao_desconto": null,
            "valor_desconto": 0,
            "valor_iof": 0,
            "valor_abatimento": 0,
            {{if (eq .Buyer.Document.Type "CPF")}}
            	"tipo_inscricao_pagador": "01",
			{{else}}
            	"tipo_inscricao_pagador": "02",
			{{end}}
            "sequencia_registro": ""
        }
    },
    "token_request_confirmacao_pagamento": ""
}
`

const responseBradesco = `
{
    "boleto": {
        "linha_digitavel_formatada": "{{digitableLine}}",
        "url_acesso": "{{url}}"
    },
    "status": {
        "codigo": "{{returnCode}}",
        "mensagem": "{{returnMessage}}"
    }
}
`

func getRequestBradesco() string {
	return registerBradesco
}

func getResponseBradesco() string {
	return responseBradesco
}
<|endoftext|>