<commit_before>package haproxy

import (
	"io"
	"os"
	"os/exec"
	"path"
	"regexp"
	"sort"
	"strconv"
	"text/template"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/newrelic/sidecar/catalog"
	"github.com/newrelic/sidecar/service"
)

type portset map[string]string
type portmap map[string]portset

// Configuration and state for the HAproxy management module
type HAproxy struct {
	ReloadCmd  string
	VerifyCmd  string
	BindIP     string
	Template   string
	ConfigFile string
	PidFile    string
}

// Constructs a properly configure HAProxy and returns a pointer to it
func New(configFile string, pidFile string) *HAproxy {
	reloadCmd := "haproxy -f " + configFile + " -p " + pidFile + "`[[ -f " + pidFile + " ]] && echo \"-sf $(cat " + pidFile + ")\"]]`"
	verifyCmd := "haproxy -c -f " + configFile

	proxy := HAproxy{
		ReloadCmd:  reloadCmd,
		VerifyCmd:  verifyCmd,
		Template:   "views/haproxy.cfg",
		ConfigFile: configFile,
		PidFile:    pidFile,
	}

	return &proxy
}

// Returns a map of ServicePort:Port pairs
func (h *HAproxy) makePortmap(services map[string][]*service.Service) portmap {
	ports := make(portmap)

	for name, svcList := range services {
		if _, ok := ports[name]; !ok {
			ports[name] = make(portset, 5)
		}

		for _, service := range svcList {
			for _, port := range service.Ports {
				// Currently only handle TCP, and we skip ports that aren't exported.
				// That's the effect of not specifying a ServicePort.
				if port.Type == "tcp" && port.ServicePort != 0 {
					svcPort := strconv.FormatInt(port.ServicePort, 10)
					internalPort := strconv.FormatInt(port.Port, 10)
					ports[name][svcPort] = internalPort
				}
			}
		}
	}

	return ports
}

// Clean up image names for writing as HAproxy frontend and backend entries
func sanitizeName(image string) string {
	replace := regexp.MustCompile("[^a-z0-9-]")
	return replace.ReplaceAllString(image, "-")
}

// Create an HAproxy config from the supplied ServicesState. Write it out to the
// supplied io.Writer interface. This gets a list from servicesWithPorts() and
// builds a list of unique ports for all services, then passes these to the
// template. Ports are looked up by the func getPorts().
func (h *HAproxy) WriteConfig(state *catalog.ServicesState, output io.Writer) {
	services := servicesWithPorts(state)
	ports := h.makePortmap(services)

	data := struct {
		Services map[string][]*service.Service
	}{
		Services: services,
	}

	funcMap := template.FuncMap{
		"now": time.Now().UTC,
		"getPorts": func(k string) map[string]string {
			return ports[k]
		},
		"bindIP":       func() string { return h.BindIP },
		"sanitizeName": sanitizeName,
	}

	t, err := template.New("haproxy").Funcs(funcMap).ParseFiles(h.Template)
	if err != nil {
		log.Errorf("Error Parsing template '%s': %s", h.Template, err.Error())
		return
	}
	t.ExecuteTemplate(output, path.Base(h.Template), data)
}

// Execute a command and log the error, but bubble it up as well
func (h *HAproxy) run(command string) error {
	cmd := exec.Command("/bin/bash", "-c", command)
	err := cmd.Run()
	if err != nil {
		log.Errorf("Error running '%s': %s", command, err.Error())
	}

	return err
}

// Run the HAproxy reload command to load the new config and restart.
// Best to use a command with -sf specified to keep the connections up.
func (h *HAproxy) Reload() error {
	return h.run(h.ReloadCmd)
}

// Run HAproxy with the verify command that will check the validity of
// the current config. Used to gate a Reload() so we don't load a bad
// config and tear everything down.
func (h *HAproxy) Verify() error {
	return h.run(h.VerifyCmd)
}

// Watch the state of a ServicesState struct and generate a new proxy
// config file (haproxy.ConfigFile) when the state changes. Also notifies
// the service that it needs to reload once the new file has been written
// and verified.
func (h *HAproxy) Watch(state *catalog.ServicesState) {
	eventChannel := make(chan catalog.ChangeEvent, 2)
	state.AddListener(eventChannel)

	for {
		event := <-eventChannel
		log.Println("State change event from " + event.Hostname)
		outfile, err := os.Create(h.ConfigFile)
		if err != nil {
			log.Errorf("Unable to write to %s! (%s)", h.ConfigFile, err.Error())
			continue
		}

		h.WriteConfig(state, outfile)
		if err := h.Verify(); err != nil {
			log.Errorf("Failed to verify HAproxy config! (%s)", err.Error())
			continue
		}

		h.Reload()
	}
}

// Like state.ByService() but only stores information for services which
// actually have public ports. Only matches services that have the same name
// and the same ports. Otherwise log an error.
func servicesWithPorts(state *catalog.ServicesState) map[string][]*service.Service {
	serviceMap := make(map[string][]*service.Service)

	state.EachServiceSorted(
		func(hostname *string, serviceId *string, svc *service.Service) {
			if len(svc.Ports) < 1 {
				return
			}

			// We only want things that are alive and healthy!
			if !svc.IsAlive() {
				return
			}

			svcName := state.ServiceName(svc)
			if _, ok := serviceMap[svcName]; !ok {
				serviceMap[svcName] = make([]*service.Service, 0, 3)
			}

			// If this is the first one, just add it to the list
			if len(serviceMap[svcName]) < 1 {
				serviceMap[svcName] = append(serviceMap[svcName], svc)
				return
			}

			// Otherwise we need to make sure the ServicePorts match
			match := serviceMap[svcName][0] // Get the first entry for comparison

			// Build up a sorted list of ServicePorts from the existing service
			portsToMatch := getSortedServicePorts(match)

			// Get the list of our ports
			portsWeHave := getSortedServicePorts(svc)

			// Compare the two sorted lists
			for i, port := range portsToMatch {
				if portsWeHave[i] != port {
					// TODO should we just add another service with this port added
					// to the name? We have to find out which port.
					log.Warnf("%s service from %s not added: non-matching ports!",
						state.ServiceName(svc), svc.Hostname)
					return
				}
			}

			// It was a match! Append to the list.
			serviceMap[svcName] = append(serviceMap[svcName], svc)
		},
	)

	return serviceMap
}

func getSortedServicePorts(svc *service.Service) []string {
	var portList []string
	for _, port := range svc.Ports {
		portList = append(portList, strconv.FormatInt(port.ServicePort, 10))
	}

	sort.Strings(portList)
	return portList
}
<commit_msg>This should have a space, otherwise doesn't parse.<commit_after>package haproxy

import (
	"io"
	"os"
	"os/exec"
	"path"
	"regexp"
	"sort"
	"strconv"
	"text/template"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/newrelic/sidecar/catalog"
	"github.com/newrelic/sidecar/service"
)

type portset map[string]string
type portmap map[string]portset

// Configuration and state for the HAproxy management module
type HAproxy struct {
	ReloadCmd  string
	VerifyCmd  string
	BindIP     string
	Template   string
	ConfigFile string
	PidFile    string
}

// Constructs a properly configure HAProxy and returns a pointer to it
func New(configFile string, pidFile string) *HAproxy {
	reloadCmd := "haproxy -f " + configFile + " -p " + pidFile + " `[[ -f " + pidFile + " ]] && echo \"-sf $(cat " + pidFile + ")\"]]`"
	verifyCmd := "haproxy -c -f " + configFile

	proxy := HAproxy{
		ReloadCmd:  reloadCmd,
		VerifyCmd:  verifyCmd,
		Template:   "views/haproxy.cfg",
		ConfigFile: configFile,
		PidFile:    pidFile,
	}

	return &proxy
}

// Returns a map of ServicePort:Port pairs
func (h *HAproxy) makePortmap(services map[string][]*service.Service) portmap {
	ports := make(portmap)

	for name, svcList := range services {
		if _, ok := ports[name]; !ok {
			ports[name] = make(portset, 5)
		}

		for _, service := range svcList {
			for _, port := range service.Ports {
				// Currently only handle TCP, and we skip ports that aren't exported.
				// That's the effect of not specifying a ServicePort.
				if port.Type == "tcp" && port.ServicePort != 0 {
					svcPort := strconv.FormatInt(port.ServicePort, 10)
					internalPort := strconv.FormatInt(port.Port, 10)
					ports[name][svcPort] = internalPort
				}
			}
		}
	}

	return ports
}

// Clean up image names for writing as HAproxy frontend and backend entries
func sanitizeName(image string) string {
	replace := regexp.MustCompile("[^a-z0-9-]")
	return replace.ReplaceAllString(image, "-")
}

// Create an HAproxy config from the supplied ServicesState. Write it out to the
// supplied io.Writer interface. This gets a list from servicesWithPorts() and
// builds a list of unique ports for all services, then passes these to the
// template. Ports are looked up by the func getPorts().
func (h *HAproxy) WriteConfig(state *catalog.ServicesState, output io.Writer) {
	services := servicesWithPorts(state)
	ports := h.makePortmap(services)

	data := struct {
		Services map[string][]*service.Service
	}{
		Services: services,
	}

	funcMap := template.FuncMap{
		"now": time.Now().UTC,
		"getPorts": func(k string) map[string]string {
			return ports[k]
		},
		"bindIP":       func() string { return h.BindIP },
		"sanitizeName": sanitizeName,
	}

	t, err := template.New("haproxy").Funcs(funcMap).ParseFiles(h.Template)
	if err != nil {
		log.Errorf("Error Parsing template '%s': %s", h.Template, err.Error())
		return
	}
	t.ExecuteTemplate(output, path.Base(h.Template), data)
}

// Execute a command and log the error, but bubble it up as well
func (h *HAproxy) run(command string) error {
	cmd := exec.Command("/bin/bash", "-c", command)
	err := cmd.Run()
	if err != nil {
		log.Errorf("Error running '%s': %s", command, err.Error())
	}

	return err
}

// Run the HAproxy reload command to load the new config and restart.
// Best to use a command with -sf specified to keep the connections up.
func (h *HAproxy) Reload() error {
	return h.run(h.ReloadCmd)
}

// Run HAproxy with the verify command that will check the validity of
// the current config. Used to gate a Reload() so we don't load a bad
// config and tear everything down.
func (h *HAproxy) Verify() error {
	return h.run(h.VerifyCmd)
}

// Watch the state of a ServicesState struct and generate a new proxy
// config file (haproxy.ConfigFile) when the state changes. Also notifies
// the service that it needs to reload once the new file has been written
// and verified.
func (h *HAproxy) Watch(state *catalog.ServicesState) {
	eventChannel := make(chan catalog.ChangeEvent, 2)
	state.AddListener(eventChannel)

	for {
		event := <-eventChannel
		log.Println("State change event from " + event.Hostname)
		outfile, err := os.Create(h.ConfigFile)
		if err != nil {
			log.Errorf("Unable to write to %s! (%s)", h.ConfigFile, err.Error())
			continue
		}

		h.WriteConfig(state, outfile)
		if err := h.Verify(); err != nil {
			log.Errorf("Failed to verify HAproxy config! (%s)", err.Error())
			continue
		}

		h.Reload()
	}
}

// Like state.ByService() but only stores information for services which
// actually have public ports. Only matches services that have the same name
// and the same ports. Otherwise log an error.
func servicesWithPorts(state *catalog.ServicesState) map[string][]*service.Service {
	serviceMap := make(map[string][]*service.Service)

	state.EachServiceSorted(
		func(hostname *string, serviceId *string, svc *service.Service) {
			if len(svc.Ports) < 1 {
				return
			}

			// We only want things that are alive and healthy!
			if !svc.IsAlive() {
				return
			}

			svcName := state.ServiceName(svc)
			if _, ok := serviceMap[svcName]; !ok {
				serviceMap[svcName] = make([]*service.Service, 0, 3)
			}

			// If this is the first one, just add it to the list
			if len(serviceMap[svcName]) < 1 {
				serviceMap[svcName] = append(serviceMap[svcName], svc)
				return
			}

			// Otherwise we need to make sure the ServicePorts match
			match := serviceMap[svcName][0] // Get the first entry for comparison

			// Build up a sorted list of ServicePorts from the existing service
			portsToMatch := getSortedServicePorts(match)

			// Get the list of our ports
			portsWeHave := getSortedServicePorts(svc)

			// Compare the two sorted lists
			for i, port := range portsToMatch {
				if portsWeHave[i] != port {
					// TODO should we just add another service with this port added
					// to the name? We have to find out which port.
					log.Warnf("%s service from %s not added: non-matching ports!",
						state.ServiceName(svc), svc.Hostname)
					return
				}
			}

			// It was a match! Append to the list.
			serviceMap[svcName] = append(serviceMap[svcName], svc)
		},
	)

	return serviceMap
}

func getSortedServicePorts(svc *service.Service) []string {
	var portList []string
	for _, port := range svc.Ports {
		portList = append(portList, strconv.FormatInt(port.ServicePort, 10))
	}

	sort.Strings(portList)
	return portList
}
<|endoftext|>


<commit_before>// The Harness for a Revel program.
//
// It has a couple responsibilities:
// 1. Parse the user program, generating a main.go file that registers
//    controller classes and starts the user's server.
// 2. Build and run the user program.  Show compile errors.
// 3. Monitor the user source and re-build / restart the program when necessary.
//
// Source files are generated in the app/tmp directory.

package harness

import (
	"fmt"
	"github.com/robfig/revel"
	"io"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
	"strings"
	"sync/atomic"
)

var (
	watcher    *rev.Watcher
	doNotWatch = []string{"tmp", "views"}

	lastRequestHadError int32
)

// Harness reverse proxies requests to the application server.
// It builds / runs / rebuilds / restarts the server when code is changed.
type Harness struct {
	serverHost string
	port       int
	proxy      *httputil.ReverseProxy
}

func renderError(w http.ResponseWriter, r *http.Request, err error) {
	rev.RenderError(rev.NewRequest(r), rev.NewResponse(w), err)
}

// ServeHTTP handles all requests.
// It checks for changes to app, rebuilds if necessary, and forwards the request.
func (hp *Harness) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Don't rebuild the app for favicon requests.
	if lastRequestHadError > 0 && r.URL.Path == "/favicon.ico" {
		return
	}

	// Flush any change events and rebuild app if necessary.
	// Render an error page if the rebuild / restart failed.
	err := watcher.Notify()
	if err != nil {
		atomic.CompareAndSwapInt32(&lastRequestHadError, 0, 1)
		renderError(w, r, err)
		return
	}
	atomic.CompareAndSwapInt32(&lastRequestHadError, 1, 0)

	// Reverse proxy the request.
	// (Need special code for websockets, courtesy of bradfitz)
	if r.Header.Get("Upgrade") == "websocket" {
		proxyWebsocket(w, r, hp.serverHost)
	} else {
		hp.proxy.ServeHTTP(w, r)
	}
}

// Return a reverse proxy that forwards requests to the given port.
func NewHarness() *Harness {
	// Get a template loader to render errors.
	// Prefer the app's views/errors directory, and fall back to the stock error pages.
	rev.MainTemplateLoader = rev.NewTemplateLoader(rev.TemplatePaths)
	rev.MainTemplateLoader.Refresh()

	port := getFreePort()
	serverUrl, _ := url.ParseRequestURI(fmt.Sprintf("http://localhost:%d", port))
	harness := &Harness{
		port:       port,
		serverHost: serverUrl.String()[len("http://"):],
		proxy:      httputil.NewSingleHostReverseProxy(serverUrl),
	}
	return harness
}

// Rebuild the Revel application and run it on the given port.
func (h *Harness) Refresh() *rev.Error {
	rev.TRACE.Println("Rebuild")
	binName, err := Build()
	if err != nil {
		return err
	}
	start(binName, "", h.port)
	return nil
}

func (h *Harness) WatchDir(info os.FileInfo) bool {
	return !rev.ContainsString(doNotWatch, info.Name())
}

func (h *Harness) WatchFile(filename string) bool {
	return strings.HasSuffix(filename, ".go")
}

func (h *Harness) Run() {
	// If the harness exits, be sure to kill the app server.
	defer func() {
		if cmd != nil {
			cmd.Process.Kill()
			cmd = nil
		}
	}()

	watcher = rev.NewWatcher()
	for _, codePath := range rev.CodePaths {
		watcher.Listen(h, codePath)
	}

	appAddr := getAppAddress()
	appPort := getAppPort()
	rev.INFO.Printf("Listening on %s:%d", appAddr, appPort)
	err := http.ListenAndServe(fmt.Sprintf("%s:%d", appAddr, appPort), h)
	if err != nil {
		rev.ERROR.Fatalln("Failed to start reverse proxy:", err)
	}
}

// proxyWebsocket copies data between websocket client and server until one side
// closes the connection.  (ReverseProxy doesn't work with websocket requests.)
func proxyWebsocket(w http.ResponseWriter, r *http.Request, host string) {
	d, err := net.Dial("tcp", host)
	if err != nil {
		http.Error(w, "Error contacting backend server.", 500)
		rev.ERROR.Printf("Error dialing websocket backend %s: %v", host, err)
		return
	}
	hj, ok := w.(http.Hijacker)
	if !ok {
		http.Error(w, "Not a hijacker?", 500)
		return
	}
	nc, _, err := hj.Hijack()
	if err != nil {
		rev.ERROR.Printf("Hijack error: %v", err)
		return
	}
	defer nc.Close()
	defer d.Close()

	err = r.Write(d)
	if err != nil {
		rev.ERROR.Printf("Error copying request to target: %v", err)
		return
	}

	errc := make(chan error, 2)
	cp := func(dst io.Writer, src io.Reader) {
		_, err := io.Copy(dst, src)
		errc <- err
	}
	go cp(d, nc)
	go cp(nc, d)
	<-errc
}
<commit_msg>BugFix: Listen only once to the code paths.<commit_after>// The Harness for a Revel program.
//
// It has a couple responsibilities:
// 1. Parse the user program, generating a main.go file that registers
//    controller classes and starts the user's server.
// 2. Build and run the user program.  Show compile errors.
// 3. Monitor the user source and re-build / restart the program when necessary.
//
// Source files are generated in the app/tmp directory.

package harness

import (
	"fmt"
	"github.com/robfig/revel"
	"io"
	"net"
	"net/http"
	"net/http/httputil"
	"net/url"
	"os"
	"strings"
	"sync/atomic"
)

var (
	watcher    *rev.Watcher
	doNotWatch = []string{"tmp", "views"}

	lastRequestHadError int32
)

// Harness reverse proxies requests to the application server.
// It builds / runs / rebuilds / restarts the server when code is changed.
type Harness struct {
	serverHost string
	port       int
	proxy      *httputil.ReverseProxy
}

func renderError(w http.ResponseWriter, r *http.Request, err error) {
	rev.RenderError(rev.NewRequest(r), rev.NewResponse(w), err)
}

// ServeHTTP handles all requests.
// It checks for changes to app, rebuilds if necessary, and forwards the request.
func (hp *Harness) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Don't rebuild the app for favicon requests.
	if lastRequestHadError > 0 && r.URL.Path == "/favicon.ico" {
		return
	}

	// Flush any change events and rebuild app if necessary.
	// Render an error page if the rebuild / restart failed.
	err := watcher.Notify()
	if err != nil {
		atomic.CompareAndSwapInt32(&lastRequestHadError, 0, 1)
		renderError(w, r, err)
		return
	}
	atomic.CompareAndSwapInt32(&lastRequestHadError, 1, 0)

	// Reverse proxy the request.
	// (Need special code for websockets, courtesy of bradfitz)
	if r.Header.Get("Upgrade") == "websocket" {
		proxyWebsocket(w, r, hp.serverHost)
	} else {
		hp.proxy.ServeHTTP(w, r)
	}
}

// Return a reverse proxy that forwards requests to the given port.
func NewHarness() *Harness {
	// Get a template loader to render errors.
	// Prefer the app's views/errors directory, and fall back to the stock error pages.
	rev.MainTemplateLoader = rev.NewTemplateLoader(rev.TemplatePaths)
	rev.MainTemplateLoader.Refresh()

	port := getFreePort()
	serverUrl, _ := url.ParseRequestURI(fmt.Sprintf("http://localhost:%d", port))
	harness := &Harness{
		port:       port,
		serverHost: serverUrl.String()[len("http://"):],
		proxy:      httputil.NewSingleHostReverseProxy(serverUrl),
	}
	return harness
}

// Rebuild the Revel application and run it on the given port.
func (h *Harness) Refresh() *rev.Error {
	rev.TRACE.Println("Rebuild")
	binName, err := Build()
	if err != nil {
		return err
	}
	start(binName, "", h.port)
	return nil
}

func (h *Harness) WatchDir(info os.FileInfo) bool {
	return !rev.ContainsString(doNotWatch, info.Name())
}

func (h *Harness) WatchFile(filename string) bool {
	return strings.HasSuffix(filename, ".go")
}

func (h *Harness) Run() {
	// If the harness exits, be sure to kill the app server.
	defer func() {
		if cmd != nil {
			cmd.Process.Kill()
			cmd = nil
		}
	}()

	watcher = rev.NewWatcher()
	watcher.Listen(h, rev.CodePaths...)

	appAddr := getAppAddress()
	appPort := getAppPort()
	rev.INFO.Printf("Listening on %s:%d", appAddr, appPort)
	err := http.ListenAndServe(fmt.Sprintf("%s:%d", appAddr, appPort), h)
	if err != nil {
		rev.ERROR.Fatalln("Failed to start reverse proxy:", err)
	}
}

// proxyWebsocket copies data between websocket client and server until one side
// closes the connection.  (ReverseProxy doesn't work with websocket requests.)
func proxyWebsocket(w http.ResponseWriter, r *http.Request, host string) {
	d, err := net.Dial("tcp", host)
	if err != nil {
		http.Error(w, "Error contacting backend server.", 500)
		rev.ERROR.Printf("Error dialing websocket backend %s: %v", host, err)
		return
	}
	hj, ok := w.(http.Hijacker)
	if !ok {
		http.Error(w, "Not a hijacker?", 500)
		return
	}
	nc, _, err := hj.Hijack()
	if err != nil {
		rev.ERROR.Printf("Hijack error: %v", err)
		return
	}
	defer nc.Close()
	defer d.Close()

	err = r.Write(d)
	if err != nil {
		rev.ERROR.Printf("Error copying request to target: %v", err)
		return
	}

	errc := make(chan error, 2)
	cp := func(dst io.Writer, src io.Reader) {
		_, err := io.Copy(dst, src)
		errc <- err
	}
	go cp(d, nc)
	go cp(nc, d)
	<-errc
}
<|endoftext|>


<commit_before>package quadedge_test

import (
	"fmt"
	"math/rand"
	"testing"

	"github.com/drakmaniso/glam"
	"github.com/drakmaniso/glam/colour"
	"github.com/drakmaniso/glam/mouse"
	"github.com/drakmaniso/glam/palette"
	"github.com/drakmaniso/glam/pixel"
	"github.com/drakmaniso/glam/plane"
	"github.com/drakmaniso/glam/plane/quadedge"
)

//------------------------------------------------------------------------------

var screen = pixel.NewCanvas(pixel.Zoom(1))

var cursor = pixel.NewCursor()

func init() {
	cursor.Canvas(screen)
}

var (
	points        []plane.Coord
	triangulation quadedge.Edge
)

//------------------------------------------------------------------------------

var c0 = []plane.Coord{
	{1, 2},
	{1, 2},
	{0, 8},
	{1, 2},
	{0, 8},
	{1, 2},
	{1, 2},
	{0, 8},
}

var four = []plane.Coord{
	{-10, -4},
	{10, -4},
	{0, 10},
	{0, 7.5},
}

func TestDelaunay(t *testing.T) {
	e := quadedge.Delaunay(c0)
	e.Walk(func(f quadedge.Edge) {
		fmt.Println(f.Orig(), "->", f.Dest())
	})
}

//------------------------------------------------------------------------------

func TestDelaunay_graphic(t *testing.T) {
	do(func() {
		glam.Configure(glam.TimeStep(0.0005))
		err := glam.Run(delLoop{})
		if err != nil {
			t.Error(err)
		}
	})
}

//------------------------------------------------------------------------------

type delLoop struct {
	glam.Handlers
}

//------------------------------------------------------------------------------

func (delLoop) Enter() error {
	points = make([]plane.Coord, 999)
	newPoints()

	palette.Clear()
	palette.Index(1).SetColour(colour.LRGB{0.1, 0.3, 0.6})
	palette.Index(2).SetColour(colour.LRGB{0.8, 0.1, 0.0})
	return nil
}

//------------------------------------------------------------------------------

var (
	ratio  float32
	offset plane.Coord
)

func (delLoop) Update() error {
	newPoints()
	return nil
}

func (delLoop) Draw() error {
	screen.Clear(0)
	ratio = float32(screen.Size().Y)
	offset = plane.Coord{
		X: (float32(screen.Size().X) - ratio) / 2,
		Y: float32(screen.Size().Y),
	}

	m := screen.Mouse()
	p := fromScreen(m)
	cursor.Locate(2, 8, 0x7FFF)
	cursor.ColorShift(0)
	if p.X >= 0 {
		cursor.Printf("   %.3f, %.3f\n", p.X, p.Y)
	} else {
		cursor.Println(" ")
	}

	pt := make([]pixel.Coord, len(points))
	l2 := pixel.Coord{2, 2}
	l1 := pixel.Coord{1, 1}
	for i, sd := range points {
		pt[i] = toScreen(sd)
		screen.Lines(2, 0, pt[i].Minus(l2), pt[i].Plus(l2.Perp()),
			pt[i].Plus(l2), pt[i].Minus(l2.Perp()), pt[i].Minus(l2))
		screen.Lines(2, 0, pt[i].Minus(l1), pt[i].Plus(l1.Perp()),
			pt[i].Plus(l1), pt[i].Minus(l1.Perp()), pt[i].Minus(l1))
	}

	triangulation.Walk(func(e quadedge.Edge) {
		screen.Lines(1, 1, toScreen(points[e.Orig()]), toScreen(points[e.Dest()]))
	})

	screen.Display()
	return nil
}

//------------------------------------------------------------------------------

func toScreen(p plane.Coord) pixel.Coord {
	return pixel.Coord{
		X: int16(offset.X + p.X*ratio),
		Y: int16(offset.Y - p.Y*ratio),
	}
}

func fromScreen(p pixel.Coord) plane.Coord {
	return plane.Coord{
		X: (float32(p.X) - offset.X) / ratio,
		Y: (offset.Y - float32(p.Y)) / ratio,
	}
}

//------------------------------------------------------------------------------

func (delLoop) MouseButtonDown(b mouse.Button, _ int) {
	switch b {
	case mouse.Left:
		newPoints()
	case mouse.Right:
		p := fromScreen(screen.Mouse())
		points = append(points, p)
		triangulation = quadedge.Delaunay(points)
	}
}

//------------------------------------------------------------------------------

func newPoints() {
	for i := range points {
		points[i] = plane.Coord{X: rand.Float32(), Y: rand.Float32()}
	}
	triangulation = quadedge.Delaunay(points)
}

//------------------------------------------------------------------------------
<commit_msg>Cleanup delaunay test<commit_after>package quadedge_test

import (
	"fmt"
	"math/rand"
	"testing"

	"github.com/drakmaniso/glam"
	"github.com/drakmaniso/glam/colour"
	"github.com/drakmaniso/glam/mouse"
	"github.com/drakmaniso/glam/palette"
	"github.com/drakmaniso/glam/pixel"
	"github.com/drakmaniso/glam/plane"
	"github.com/drakmaniso/glam/plane/quadedge"
)

//------------------------------------------------------------------------------

var screen = pixel.NewCanvas(pixel.Zoom(1))

var cursor = pixel.NewCursor()

func init() {
	cursor.Canvas(screen)
}

var (
	points        []plane.Coord
	triangulation quadedge.Edge
)

//------------------------------------------------------------------------------

var c0 = []plane.Coord{
	{1, 2},
	{1, 2},
	{0, 8},
	{1, 2},
	{0, 8},
	{1, 2},
	{1, 2},
	{0, 8},
}

var four = []plane.Coord{
	{-10, -4},
	{10, -4},
	{0, 10},
	{0, 7.5},
}

func TestDelaunay(t *testing.T) {
	e := quadedge.Delaunay(c0)
	e.Walk(func(f quadedge.Edge) {
		fmt.Println(f.Orig(), "->", f.Dest())
	})
}

//------------------------------------------------------------------------------

func TestDelaunay_graphic(t *testing.T) {
	do(func() {
		err := glam.Run(delLoop{})
		if err != nil {
			t.Error(err)
		}
	})
}

//------------------------------------------------------------------------------

type delLoop struct {
	glam.Handlers
}

//------------------------------------------------------------------------------

func (delLoop) Enter() error {
	points = make([]plane.Coord, 111)
	newPoints()

	palette.Clear()
	palette.Index(1).SetColour(colour.LRGB{0.1, 0.3, 0.6})
	palette.Index(2).SetColour(colour.LRGB{0.8, 0.1, 0.0})
	return nil
}

//------------------------------------------------------------------------------

var (
	ratio  float32
	offset plane.Coord
)

func (delLoop) Draw() error {
	screen.Clear(0)
	ratio = float32(screen.Size().Y)
	offset = plane.Coord{
		X: (float32(screen.Size().X) - ratio) / 2,
		Y: float32(screen.Size().Y),
	}

	m := screen.Mouse()
	p := fromScreen(m)
	cursor.Locate(2, 8, 0x7FFF)
	cursor.ColorShift(0)
	if p.X >= 0 && p.X <= 1.0 {
		cursor.Printf("   %.3f, %.3f\n", p.X, p.Y)
	} else {
		cursor.Println(" ")
	}

	pt := make([]pixel.Coord, len(points))
	l2 := pixel.Coord{2, 2}
	l1 := pixel.Coord{1, 1}
	for i, sd := range points {
		pt[i] = toScreen(sd)
		screen.Lines(2, 0, pt[i].Minus(l2), pt[i].Plus(l2.Perp()),
			pt[i].Plus(l2), pt[i].Minus(l2.Perp()), pt[i].Minus(l2))
		screen.Lines(2, 0, pt[i].Minus(l1), pt[i].Plus(l1.Perp()),
			pt[i].Plus(l1), pt[i].Minus(l1.Perp()), pt[i].Minus(l1))
	}

	triangulation.Walk(func(e quadedge.Edge) {
		screen.Lines(1, 1, toScreen(points[e.Orig()]), toScreen(points[e.Dest()]))
	})

	screen.Display()
	return nil
}

//------------------------------------------------------------------------------

func toScreen(p plane.Coord) pixel.Coord {
	return pixel.Coord{
		X: int16(offset.X + p.X*ratio),
		Y: int16(offset.Y - p.Y*ratio),
	}
}

func fromScreen(p pixel.Coord) plane.Coord {
	return plane.Coord{
		X: (float32(p.X) - offset.X) / ratio,
		Y: (offset.Y - float32(p.Y)) / ratio,
	}
}

//------------------------------------------------------------------------------

func (delLoop) MouseButtonDown(b mouse.Button, _ int) {
	switch b {
	case mouse.Left:
		newPoints()
	case mouse.Right:
		p := fromScreen(screen.Mouse())
		points = append(points, p)
		triangulation = quadedge.Delaunay(points)
	}
}

//------------------------------------------------------------------------------

func newPoints() {
	for i := range points {
		points[i] = plane.Coord{X: rand.Float32(), Y: rand.Float32()}
	}
	triangulation = quadedge.Delaunay(points)
}

//------------------------------------------------------------------------------
<|endoftext|>


<commit_before>package kutil

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
)

type UtilError string

func (err UtilError) Error() string { return "Utils Error: " + string(err) }

func ProcessName() string {
	file := os.Args[0]
	i := strings.LastIndex(file, "\\")
	j := strings.LastIndex(file, "/")
	if j < i {
		file = file[i+1:]
	} else if j > i {
		file = file[j+1:]
	}
	i = strings.LastIndex(file, ".")
	if i > 0 {
		file = file[0:i]
	}
	return file
}

func DefaultPidFileName() string {
	file := ProcessName()
	pidFile := "/var/run/"
	if runtime.GOOS == "windows" {
		pidFile = "c:\\" + file + ".pid"
	} else {
		pidFile += file + ".pid"
	}
	return pidFile
}

func ProcessFile() string {
	file, _ := exec.LookPath(os.Args[0])
	path, _ := filepath.Abs(file)
	return path
}

func ProcessPath() string {
	path := filepath.Dir(ProcessFile())
	return path
}

func WritePidFile(myFile string, pid int) (err error) {
	return ioutil.WriteFile(myFile, []byte(fmt.Sprintf("%d", pid)), 0644)
}

func CheckWritePidPermission(pidFile string) error {
	if len(pidFile) <= 0 {
		pidFile = DefaultPidFileName()
	}
	file := pidFile + ".tmp"
	if err := ioutil.WriteFile(file, []byte(fmt.Sprintf("%d", 0)), 0644); err != nil {
		return UtilError("had no permission to write pid file")
	}
	os.Remove(file)
	return nil
}

func ExecProcess(background bool, file string, args ...string) (int, error) {
	fmt.Println("args:", args, "-Len:", len(args))
	filePath, _ := filepath.Abs(file)
	cmd := exec.Command(filePath, args...)
	if background {
		cmd.Stdin = nil //给新进程设置文件描述符，可以重定向到文件中
		cmd.Stdout = nil
		cmd.Stderr = nil
	} else {
		cmd.Stdin = os.Stdin //给新进程设置文件描述符，可以重定向到文件中
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}
	err := cmd.Start()
	if err == nil {
		return cmd.Process.Pid, nil
	}
	return -1, err
}

func StartProcess(background bool, file string, args []string) (*os.Process, error) {
	filePath, _ := filepath.Abs(file)
	if background {
		return os.StartProcess(filePath, args, &os.ProcAttr{Files: []*os.File{nil, nil, nil}})
	}
	return os.StartProcess(filePath, args, &os.ProcAttr{Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}})
}

func WaitProcess(background bool, file string, args []string) ([]byte, error) {
	filePath, _ := filepath.Abs(file)
	cmd := exec.Command(filePath, args...)
	if background {
		cmd.Stdin = nil //给新进程设置文件描述符，可以重定向到文件中
		cmd.Stdout = nil
		cmd.Stderr = nil
	} else {
		cmd.Stdin = os.Stdin //给新进程设置文件描述符，可以重定向到文件中
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}
	//cmd.Run()不能返回内容，而Output可以返回内容。
	return cmd.Output()
}
<commit_msg>try to make daemon<commit_after>package kutil

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"
)

type UtilError string

func (err UtilError) Error() string { return "Utils Error: " + string(err) }

func ProcessName() string {
	file := os.Args[0]
	i := strings.LastIndex(file, "\\")
	j := strings.LastIndex(file, "/")
	if j < i {
		file = file[i+1:]
	} else if j > i {
		file = file[j+1:]
	}
	i = strings.LastIndex(file, ".")
	if i > 0 {
		file = file[0:i]
	}
	return file
}

func DefaultPidFileName() string {
	file := ProcessName()
	pidFile := "/var/run/"
	if runtime.GOOS == "windows" {
		pidFile = "c:\\" + file + ".pid"
	} else {
		pidFile += file + ".pid"
	}
	return pidFile
}

func ProcessFile() string {
	file, _ := exec.LookPath(os.Args[0])
	path, _ := filepath.Abs(file)
	return path
}

func ProcessPath() string {
	path := filepath.Dir(ProcessFile())
	return path
}

func WritePidFile(myFile string, pid int) (err error) {
	return ioutil.WriteFile(myFile, []byte(fmt.Sprintf("%d", pid)), 0644)
}

func CheckWritePidPermission(pidFile string) error {
	if len(pidFile) <= 0 {
		pidFile = DefaultPidFileName()
	}
	file := pidFile + ".tmp"
	if err := ioutil.WriteFile(file, []byte(fmt.Sprintf("%d", 0)), 0644); err != nil {
		return UtilError("had no permission to write pid file")
	}
	os.Remove(file)
	return nil
}

func ExecProcess(background bool, file string, args ...string) (int, error) {
	fmt.Println("args:", args, "-Len:", len(args))
	filePath, _ := filepath.Abs(file)
	cmd := exec.Command(filePath, args...)
	if background {
		cmd.Stdin = nil //给新进程设置文件描述符，可以重定向到文件中
		cmd.Stdout = nil
		cmd.Stderr = nil
	} else {
		cmd.Stdin = os.Stdin //给新进程设置文件描述符，可以重定向到文件中
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}
	err := cmd.Start()
	if err == nil {
		return cmd.Process.Pid, nil
	}
	return -1, err
}

func TryToRunAsDaemon(key string) {
	for _,arg := range(os.Args){
		arg.
	}
}

func StartProcess(background bool, file string, args []string) (*os.Process, error) {
	filePath, _ := filepath.Abs(file)
	if background {
		return os.StartProcess(filePath, args, &os.ProcAttr{Files: []*os.File{nil, nil, nil}})
	}
	return os.StartProcess(filePath, args, &os.ProcAttr{Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}})
}

func WaitProcess(background bool, file string, args []string) ([]byte, error) {
	filePath, _ := filepath.Abs(file)
	cmd := exec.Command(filePath, args...)
	if background {
		cmd.Stdin = nil //给新进程设置文件描述符，可以重定向到文件中
		cmd.Stdout = nil
		cmd.Stderr = nil
	} else {
		cmd.Stdin = os.Stdin //给新进程设置文件描述符，可以重定向到文件中
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}
	//cmd.Run()不能返回内容，而Output可以返回内容。
	return cmd.Output()
}
<|endoftext|>


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

package kwikdesk

import (
    "bytes"
    "fmt"
    "strings"
    "strconv"
    "net/http"
    "encoding/json"
    "io/ioutil"
    "os"
)

// A set of variables we use to represent endpoints and the
// header content-type we need to use thourough the library.
const (
    kdHTTPContentType = "application/json"

    _KD_TOKEN      = "/token"
    _KD_SEARCH     = "/search"
    _KD_CHANNEL    = "/channel"
    _KD_MESSAGES   = "/messages"
    _KD_SERVERTIME = "/server-time"
)

// The HTTP Client structure that contains the
// request handler.
type Client struct {
    Host       string
    FullHost   string
    XToken   string
    HttpClient *http.Client
    ContentType string
}

// The Message structure that contains the json
// translation. This is used to store a message before
// passing it to the Requester.
type Message struct {
    Content string `json:"content"`
    Delete  int `json:"delete"`
    Private bool `json:"private"`
}

// Not used.
type Error struct {
    Message interface{}
    error int
}

// NewClient creates a new Client object.
// The token can be empty if you plan on creating
// the token using the `CreateToken` func. If you want
// to use your existing token, you need to pass it as the paramter.
// It returns a Client object that is pre-configured for usage.
func NewClient(token string) *Client {

    // Perhaps we should allow people to configure this through some
    // variable. It would make the package almost 100% backwards compatible
    // with the public api (https://developer.kwikdesk.com)
    var (
        host = "platform.kwikdesk.com"
        base = "https://" + host
        req, _ = http.NewRequest("GET", base, nil)
        proxy, _ = http.ProxyFromEnvironment(req)
        transport *http.Transport
    )

    transport = &http.Transport{}
    if proxy != nil {
        transport = &http.Transport{
            Proxy: http.ProxyURL(proxy),
        }
    }

    return &Client{
        Host: host,
        FullHost: base,
        HttpClient: &http.Client{
            Transport: transport,
        },
        ContentType: kdHTTPContentType,
        XToken: token,
    }
}

// This handles parsing the body from the API whenever there's an ERROR
// that happens and is returned by the API. It returns the parsed error and the
// error code that's been retrieve.
func ResponseErrorHandler(res *http.Response, res_err error) (ret interface{}, err error) {
    var (
        message = map[string]interface{}{}
        responseBody []byte
    )

    responseBody, _ = ioutil.ReadAll(res.Body)
    json.Unmarshal(responseBody, &message)

    return message, res_err
}

// This is the most used func of the package. It is used to execute every request on the platform endpoints.
// You pass an endpoint (i.e. /channel), a request type (i.e. "GET"), the body content to post (JSON-formatted string),
// and the extra headers you want to add (i.e. X-API-Token, X-Appname, etc.) and it'll add them.
// It will then return an interface containing the results, and the error code if there's an error.
func (c *Client) Requester(endpoint string, reqType string, bodyContent string, headers map[string]interface{}) (ret interface{}, err error) {
    var (
        request *http.Request
        response *http.Response
        responseBody []byte
        responseJson = map[string]interface{}{}
        url = fmt.Sprintf("%s/%s", c.FullHost, endpoint)
    )

    // I'm too dumb to find out how to transform a string "" into nil so fuck it.
    if len(bodyContent) > 0 {
        request, err = http.NewRequest(strings.ToUpper(reqType), url, bytes.NewBufferString(bodyContent))
    } else {
        request, err = http.NewRequest(strings.ToUpper(reqType), url, nil)
    }

    request.Header.Set("Content-Type", c.ContentType)
    for key, value := range headers {
        request.Header.Set(fmt.Sprintf("%v", key), fmt.Sprintf("%v", value))
    }

    if response, err = c.HttpClient.Do(request); err != nil {
        return ResponseErrorHandler(response, err)
    }

    // Transpose to string because I don't know how to use "HasPrefix" with an int.
    code := strconv.Itoa(response.StatusCode)

    // Here we check if the prefix starts with "20". That's a 200, 201, etc.
    if !strings.HasPrefix(code, "20") {
        err = fmt.Errorf("HTTP Response Code: %v", response.StatusCode)
        return ResponseErrorHandler(response, err)
    }

    // We then identify whether or not there's an error whilst reading the
    // response body from the response object.
    if responseBody, err = ioutil.ReadAll(response.Body); err != nil {
        return ResponseErrorHandler(response, err)
    }

    // Furthermore, we look for errors when unmarshalling the json.
    if err = json.Unmarshal(responseBody, &responseJson); err != nil {
        return ResponseErrorHandler(response, err)
    }

    // Everything went well so we just send the JSON-interface object back to the user with no error.
    return responseJson, nil
}

// This function is used to create Messages as described in:
// https://partners.kwikdesk.com/#create
// You pass the content string, the delete time integer value and whether or not it's private (true false)
// This will return the response from the API and the error if something happened.
func (c *Client) Messages(messageContent string, deleteTime int, privateFlag bool) (ret interface{}, err error) {
    var (
        endpoint = _KD_MESSAGES
        requestType = "POST"
        bodyContent = &Message{Content: messageContent, Delete: deleteTime, Private: privateFlag}
        headers = make(map[string]interface{})
    )

    headers["X-API-Token"] = c.XToken

    body, err := json.Marshal(bodyContent)
    response, err := c.Requester(endpoint, requestType, string(body), headers)

    results := response.(map[string]interface{})
    return results, err
}

// This function is used to retrieve channel-messages as described in:
// https://partners.kwikdesk.com/#channel
// All you require to pass is the token which is stored in the Client object
// that was either saved at instance creation, or after you've invoked the CreateToken func.
// This will return the response from the API and the error if something happened.
func (c *Client) Channel() (ret interface{}, err error) {
    var (
        endpoint = _KD_CHANNEL
        requestType = "GET"
        bodyContent = ""
        headers = make(map[string]interface{})
    )

    headers["X-API-Token"] = c.XToken

    response, err := c.Requester(endpoint, requestType, bodyContent, headers)
    results := response.(map[string]interface{})["results"]

    return results, err
}

// This function is used to place searches on hashtags associated to your token
// and marked as private being false, as described in:
// https://partners.kwikdesk.com/#search
// You only need to pass the search term you are interested in searching for
// and the function will return the response from the API and the error
// if something happened.
func (c* Client) Search(term string) (ret interface{}, err error) {
    var (
        endpoint = fmt.Sprintf("%s?q=%s", _KD_SEARCH, term)
        requestType = "GET"
        bodyContent = ""
        headers = make(map[string]interface{})
    )

    headers["X-API-Token"] = c.XToken

    response, err := c.Requester(endpoint, requestType, bodyContent, headers)
    results := response.(map[string]interface{})["results"]

    stopOnError(err)
    return results, err
}

// Set the Xtoken Client object variable.
func (c *Client) SetToken(token string) {
    c.XToken = token
}

// Retrieve the token value from the Client object variable XToken
func (c *Client) GetToken() string {
    return c.XToken
}

// This function is used to create Tokens as described in:
// https://partners.kwikdesk.com/#token
// You are required to pass the application name (or an email address). Upon success,
// the value of the token will be set in the Client object which you can then reuse
// easily with the other funcs like Message, Search, etc.
// This will return the response from the API and the error if something happened.
func (c *Client) CreateToken(appName string) (ret interface{}, err error) {
    var (
        endpoint = _KD_TOKEN
        requestType = "POST"
        bodyContent = ""
        headers = make(map[string]interface{})
    )

    headers["X-Appname"] = appName

    response, err := c.Requester(endpoint, requestType, bodyContent, headers)
    token := response.(map[string]interface{})["token"].(string)

    c.SetToken(token)
    results := response.(map[string]interface{})

    return results, err
}

// This queries the KwikDesk Platform to retrieve the current
// server time. Even though HTTP has a native mechanism for accomplishing
// precisely that, we want to insure consistency between and this also gives
// you different formats to work with.
// This will return the response from the API and the error if something happened.
func (c* Client) ServerTime() (ret interface{}, err error) {
    var (
        endpoint = _KD_SERVERTIME
        requestType = "GET"
        bodyContent = ""
        headers = make(map[string]interface{})
    )

    headers["X-API-Token"] = c.XToken

    response, err := c.Requester(endpoint, requestType, bodyContent, headers)
    stopOnError(err)

    results := response.(map[string]interface{})
    return results, err
}

// Stop on error and print the message if something happened. This is just
// like a fake "catch".
func stopOnError(err error) {
    if err != nil {
        fmt.Fprintln(os.Stderr, "Error caught during request: ", err)
        os.Exit(1)
    }
}
<commit_msg>Moved the file to the kwikdesk subfolder<commit_after><|endoftext|>


<commit_before>// Copyright 2015 The go-hep 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 hbook

import (
	"errors"
	"sort"
)

// Indices for the under- and over-flow 1-dim bins.
const (
	UnderflowBin = -1
	OverflowBin  = -2
)

var (
	errInvalidXAxis   = errors.New("hbook: invalid X-axis limits")
	errEmptyXAxis     = errors.New("hbook: X-axis with zero bins")
	errShortXAxis     = errors.New("hbook: too few 1-dim X-bins")
	errOverlapXAxis   = errors.New("hbook: invalid X-binning (overlap)")
	errNotSortedXAxis = errors.New("hbook: X-edges slice not sorted")
	errDupEdgesXAxis  = errors.New("hbook: duplicates in X-edge values")

	errInvalidYAxis   = errors.New("hbook: invalid Y-axis limits")
	errEmptyYAxis     = errors.New("hbook: Y-axis with zero bins")
	errShortYAxis     = errors.New("hbook: too few 1-dim Y-bins")
	errOverlapYAxis   = errors.New("hbook: invalid Y-binning (overlap)")
	errNotSortedYAxis = errors.New("hbook: Y-edges slice not sorted")
	errDupEdgesYAxis  = errors.New("hbook: duplicates in Y-edge values")
)

// binning1D is a 1-dim binning of the x-axis.
type binning1D struct {
	bins     []Bin1D
	dist     dist1D
	outflows [2]dist1D
	xrange   Range
}

func newBinning1D(n int, xmin, xmax float64) binning1D {
	if xmin >= xmax {
		panic(errInvalidXAxis)
	}
	if n <= 0 {
		panic(errEmptyXAxis)
	}
	bng := binning1D{
		bins:   make([]Bin1D, n),
		xrange: Range{Min: xmin, Max: xmax},
	}
	width := bng.xrange.Width() / float64(n)
	for i := range bng.bins {
		bin := &bng.bins[i]
		bin.xrange.Min = xmin + float64(i)*width
		bin.xrange.Max = xmin + float64(i+1)*width
	}
	return bng
}

func newBinning1DFromBins(xbins []Range) binning1D {
	if len(xbins) < 1 {
		panic(errShortXAxis)
	}
	n := len(xbins)
	bng := binning1D{
		bins: make([]Bin1D, n),
	}
	for i, xbin := range xbins {
		bin := &bng.bins[i]
		bin.xrange = xbin
	}
	sort.Sort(Bin1Ds(bng.bins))
	for i := 0; i < len(bng.bins)-1; i++ {
		b0 := bng.bins[i]
		b1 := bng.bins[i+1]
		if b0.xrange.Max > b1.xrange.Min {
			panic(errOverlapXAxis)
		}
	}
	bng.xrange = Range{Min: bng.bins[0].XMin(), Max: bng.bins[n-1].XMax()}
	return bng
}

func newBinning1DFromEdges(edges []float64) binning1D {
	if len(edges) <= 1 {
		panic(errShortXAxis)
	}
	if !sort.IsSorted(sort.Float64Slice(edges)) {
		panic(errNotSortedXAxis)
	}
	n := len(edges) - 1
	bng := binning1D{
		bins:   make([]Bin1D, n),
		xrange: Range{Min: edges[0], Max: edges[n]},
	}
	for i := range bng.bins {
		bin := &bng.bins[i]
		xmin := edges[i]
		xmax := edges[i+1]
		if xmin == xmax {
			panic(errDupEdgesXAxis)
		}
		bin.xrange.Min = xmin
		bin.xrange.Max = xmax
	}
	return bng
}

func (bng *binning1D) entries() int64 {
	return bng.dist.Entries()
}

func (bng *binning1D) effEntries() float64 {
	return bng.dist.EffEntries()
}

// xMin returns the low edge of the X-axis
func (bng *binning1D) xMin() float64 {
	return bng.xrange.Min
}

// xMax returns the high edge of the X-axis
func (bng *binning1D) xMax() float64 {
	return bng.xrange.Max
}

func (bng *binning1D) fill(x, w float64) {
	idx := bng.coordToIndex(x)
	bng.dist.fill(x, w)
	if idx < 0 {
		bng.outflows[-idx-1].fill(x, w)
		return
	}
	if idx == len(bng.bins) {
		// gap bin.
		return
	}
	bng.bins[idx].fill(x, w)
}

// coordToIndex returns the bin index corresponding to the coordinate x.
func (bng *binning1D) coordToIndex(x float64) int {
	switch {
	default:
		return Bin1Ds(bng.bins).IndexOf(x)
	case x < bng.xrange.Min:
		return UnderflowBin
	case x >= bng.xrange.Max:
		return OverflowBin
	}
}

func (bng *binning1D) scaleW(f float64) {
	bng.dist.scaleW(f)
	bng.outflows[0].scaleW(f)
	bng.outflows[1].scaleW(f)
	for i := range bng.bins {
		bin := &bng.bins[i]
		bin.scaleW(f)
	}
}

// Bins returns the slice of bins for this binning.
func (bng *binning1D) Bins() []Bin1D {
	return bng.bins
}
<commit_msg>hbook: make binning1D.coordToIndex flow better<commit_after>// Copyright 2015 The go-hep 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 hbook

import (
	"errors"
	"sort"
)

// Indices for the under- and over-flow 1-dim bins.
const (
	UnderflowBin = -1
	OverflowBin  = -2
)

var (
	errInvalidXAxis   = errors.New("hbook: invalid X-axis limits")
	errEmptyXAxis     = errors.New("hbook: X-axis with zero bins")
	errShortXAxis     = errors.New("hbook: too few 1-dim X-bins")
	errOverlapXAxis   = errors.New("hbook: invalid X-binning (overlap)")
	errNotSortedXAxis = errors.New("hbook: X-edges slice not sorted")
	errDupEdgesXAxis  = errors.New("hbook: duplicates in X-edge values")

	errInvalidYAxis   = errors.New("hbook: invalid Y-axis limits")
	errEmptyYAxis     = errors.New("hbook: Y-axis with zero bins")
	errShortYAxis     = errors.New("hbook: too few 1-dim Y-bins")
	errOverlapYAxis   = errors.New("hbook: invalid Y-binning (overlap)")
	errNotSortedYAxis = errors.New("hbook: Y-edges slice not sorted")
	errDupEdgesYAxis  = errors.New("hbook: duplicates in Y-edge values")
)

// binning1D is a 1-dim binning of the x-axis.
type binning1D struct {
	bins     []Bin1D
	dist     dist1D
	outflows [2]dist1D
	xrange   Range
}

func newBinning1D(n int, xmin, xmax float64) binning1D {
	if xmin >= xmax {
		panic(errInvalidXAxis)
	}
	if n <= 0 {
		panic(errEmptyXAxis)
	}
	bng := binning1D{
		bins:   make([]Bin1D, n),
		xrange: Range{Min: xmin, Max: xmax},
	}
	width := bng.xrange.Width() / float64(n)
	for i := range bng.bins {
		bin := &bng.bins[i]
		bin.xrange.Min = xmin + float64(i)*width
		bin.xrange.Max = xmin + float64(i+1)*width
	}
	return bng
}

func newBinning1DFromBins(xbins []Range) binning1D {
	if len(xbins) < 1 {
		panic(errShortXAxis)
	}
	n := len(xbins)
	bng := binning1D{
		bins: make([]Bin1D, n),
	}
	for i, xbin := range xbins {
		bin := &bng.bins[i]
		bin.xrange = xbin
	}
	sort.Sort(Bin1Ds(bng.bins))
	for i := 0; i < len(bng.bins)-1; i++ {
		b0 := bng.bins[i]
		b1 := bng.bins[i+1]
		if b0.xrange.Max > b1.xrange.Min {
			panic(errOverlapXAxis)
		}
	}
	bng.xrange = Range{Min: bng.bins[0].XMin(), Max: bng.bins[n-1].XMax()}
	return bng
}

func newBinning1DFromEdges(edges []float64) binning1D {
	if len(edges) <= 1 {
		panic(errShortXAxis)
	}
	if !sort.IsSorted(sort.Float64Slice(edges)) {
		panic(errNotSortedXAxis)
	}
	n := len(edges) - 1
	bng := binning1D{
		bins:   make([]Bin1D, n),
		xrange: Range{Min: edges[0], Max: edges[n]},
	}
	for i := range bng.bins {
		bin := &bng.bins[i]
		xmin := edges[i]
		xmax := edges[i+1]
		if xmin == xmax {
			panic(errDupEdgesXAxis)
		}
		bin.xrange.Min = xmin
		bin.xrange.Max = xmax
	}
	return bng
}

func (bng *binning1D) entries() int64 {
	return bng.dist.Entries()
}

func (bng *binning1D) effEntries() float64 {
	return bng.dist.EffEntries()
}

// xMin returns the low edge of the X-axis
func (bng *binning1D) xMin() float64 {
	return bng.xrange.Min
}

// xMax returns the high edge of the X-axis
func (bng *binning1D) xMax() float64 {
	return bng.xrange.Max
}

func (bng *binning1D) fill(x, w float64) {
	idx := bng.coordToIndex(x)
	bng.dist.fill(x, w)
	if idx < 0 {
		bng.outflows[-idx-1].fill(x, w)
		return
	}
	if idx == len(bng.bins) {
		// gap bin.
		return
	}
	bng.bins[idx].fill(x, w)
}

// coordToIndex returns the bin index corresponding to the coordinate x.
func (bng *binning1D) coordToIndex(x float64) int {
	switch {
	case x < bng.xrange.Min:
		return UnderflowBin
	case x >= bng.xrange.Max:
		return OverflowBin
	}
	return Bin1Ds(bng.bins).IndexOf(x)
}

func (bng *binning1D) scaleW(f float64) {
	bng.dist.scaleW(f)
	bng.outflows[0].scaleW(f)
	bng.outflows[1].scaleW(f)
	for i := range bng.bins {
		bin := &bng.bins[i]
		bin.scaleW(f)
	}
}

// Bins returns the slice of bins for this binning.
func (bng *binning1D) Bins() []Bin1D {
	return bng.bins
}
<|endoftext|>


<commit_before>package siad

import (
	"fmt"
	"time"

	"github.com/NebulousLabs/Andromeda/network"
	"github.com/NebulousLabs/Andromeda/siacore"
)

type Environment struct {
	state *siacore.State

	server   *network.TCPServer
	caughtUp bool // False while downloading blocks.

	// host   *Host
	miner *Miner
	// renter *Renter
	wallet *Wallet

	friends map[string]siacore.CoinAddress

	// Channels for incoming blocks/transactions to be processed
	blockChan       chan siacore.Block
	transactionChan chan siacore.Transaction
}

// createEnvironment() creates a server, host, miner, renter and wallet and
// puts it all in a single environment struct that's used as the state for the
// main package.
func CreateEnvironment() (e *Environment, err error) {
	e = &Environment{
		state:           siacore.CreateGenesisState(),
		friends:         make(map[string]siacore.CoinAddress),
		blockChan:       make(chan siacore.Block, 100),
		transactionChan: make(chan siacore.Transaction, 100),
	}

	err = e.initializeNetwork()
	if err != nil {
		return
	}
	e.wallet = CreateWallet(e.state)
	ROblockChan := (chan<- siacore.Block)(e.blockChan)
	e.miner = CreateMiner(e.state, ROblockChan, e.wallet.SpendConditions.CoinAddress())
	// e.host = CreateHost(e.state)
	// e.renter = CreateRenter(e.state)

	return
}

func (e *Environment) Close() {
	e.server.Close()
}

func (e *Environment) initializeNetwork() (err error) {
	e.server, err = network.NewTCPServer(9988)
	if err != nil {
		return
	}

	// establish an initial peer list
	if err = e.server.Bootstrap(); err != nil {
		fmt.Println(err)
		return
	}

	e.server.Register("AcceptBlock", e.AcceptBlock)
	e.server.Register("AcceptTransaction", e.AcceptTransaction)
	e.server.Register("SendBlocks", e.state.SendBlocks)

	// Get a peer to download the blockchain from.
	randomPeer := e.server.RandomPeer()
	fmt.Println(randomPeer)

	// Download the blockchain, getting blocks one batch at a time until an
	// empty batch is sent.
	go func() {
		// Catch up the first time.
		e.state.Lock()
		if err := e.state.CatchUp(randomPeer); err != nil {
			fmt.Println("Error during CatchUp:", err)
		}
		e.state.Unlock()
		e.caughtUp = true

		// Every 2 minutes call CatchUp() on a random peer. This will help to
		// resolve synchronization issues and keep everybody on the same page
		// with regards to the longest chain. It's a bit of a hack but will
		// make the network substantially more robust.
		for {
			time.Sleep(time.Minute * 2)
			e.state.Lock()
			e.state.CatchUp(e.server.RandomPeer())
			e.state.Unlock()
		}
	}()

	go e.listen()

	return nil
}

func (e *Environment) AcceptBlock(b siacore.Block) error {
	e.blockChan <- b
	return nil
}

func (e *Environment) AcceptTransaction(t siacore.Transaction) error {
	e.transactionChan <- t
	return nil
}

// listen waits until a new block or transaction arrives, then attempts to
// process and rebroadcast it.
func (e *Environment) listen() {
	var err error
	for {
		select {
		case b := <-e.blockChan:
			e.state.Lock()
			err = e.state.AcceptBlock(b)
			e.state.Unlock()
			if err == siacore.BlockKnownErr {
				continue
			} else if err != nil {
				if err == siacore.UnknownOrphanErr {
					e.state.Lock()
					err = e.state.CatchUp(e.server.RandomPeer())
					e.state.Unlock()
					if err != nil {
						// Logging
						// fmt.Println(err2)
					}
				} else if err != siacore.KnownOrphanErr {
					fmt.Println("AcceptBlock Error: ", err)
				}
				continue
			}
			go e.server.Broadcast("AcceptBlock", b, nil)

		case t := <-e.transactionChan:
			e.state.Lock()
			err = e.state.AcceptTransaction(t)
			e.state.Unlock()
			if err != nil {
				fmt.Println("AcceptTransaction Error:", err)
				continue
			}
			go e.server.Broadcast("AcceptTransaction", t, nil)
		}
	}
}
<commit_msg>try port 9989 if port 9988 fails<commit_after>package siad

import (
	"fmt"
	"time"

	"github.com/NebulousLabs/Andromeda/network"
	"github.com/NebulousLabs/Andromeda/siacore"
)

type Environment struct {
	state *siacore.State

	server   *network.TCPServer
	caughtUp bool // False while downloading blocks.

	// host   *Host
	miner *Miner
	// renter *Renter
	wallet *Wallet

	friends map[string]siacore.CoinAddress

	// Channels for incoming blocks/transactions to be processed
	blockChan       chan siacore.Block
	transactionChan chan siacore.Transaction
}

// createEnvironment() creates a server, host, miner, renter and wallet and
// puts it all in a single environment struct that's used as the state for the
// main package.
func CreateEnvironment() (e *Environment, err error) {
	e = &Environment{
		state:           siacore.CreateGenesisState(),
		friends:         make(map[string]siacore.CoinAddress),
		blockChan:       make(chan siacore.Block, 100),
		transactionChan: make(chan siacore.Transaction, 100),
	}

	err = e.initializeNetwork()
	if err != nil {
		return
	}
	e.wallet = CreateWallet(e.state)
	ROblockChan := (chan<- siacore.Block)(e.blockChan)
	e.miner = CreateMiner(e.state, ROblockChan, e.wallet.SpendConditions.CoinAddress())
	// e.host = CreateHost(e.state)
	// e.renter = CreateRenter(e.state)

	return
}

func (e *Environment) Close() {
	e.server.Close()
}

func (e *Environment) initializeNetwork() (err error) {
	e.server, err = network.NewTCPServer(9988)
	if err != nil {
		// TODO: Retry a single time with a different port number. This allows 2
		// instances to be running on the same machine, which is useful for
		// testing. It's hacky.
		e.server, err = network.NewTCPServer(9989)
		if err != nil {
			return
		}
	}

	// establish an initial peer list
	if err = e.server.Bootstrap(); err != nil {
		fmt.Println(err)
		return
	}

	e.server.Register("AcceptBlock", e.AcceptBlock)
	e.server.Register("AcceptTransaction", e.AcceptTransaction)
	e.server.Register("SendBlocks", e.state.SendBlocks)

	// Get a peer to download the blockchain from.
	randomPeer := e.server.RandomPeer()
	fmt.Println(randomPeer)

	// Download the blockchain, getting blocks one batch at a time until an
	// empty batch is sent.
	go func() {
		// Catch up the first time.
		e.state.Lock()
		if err := e.state.CatchUp(randomPeer); err != nil {
			fmt.Println("Error during CatchUp:", err)
		}
		e.state.Unlock()
		e.caughtUp = true

		// Every 2 minutes call CatchUp() on a random peer. This will help to
		// resolve synchronization issues and keep everybody on the same page
		// with regards to the longest chain. It's a bit of a hack but will
		// make the network substantially more robust.
		for {
			time.Sleep(time.Minute * 2)
			e.state.Lock()
			e.state.CatchUp(e.server.RandomPeer())
			e.state.Unlock()
		}
	}()

	go e.listen()

	return nil
}

func (e *Environment) AcceptBlock(b siacore.Block) error {
	e.blockChan <- b
	return nil
}

func (e *Environment) AcceptTransaction(t siacore.Transaction) error {
	e.transactionChan <- t
	return nil
}

// listen waits until a new block or transaction arrives, then attempts to
// process and rebroadcast it.
func (e *Environment) listen() {
	var err error
	for {
		select {
		case b := <-e.blockChan:
			e.state.Lock()
			err = e.state.AcceptBlock(b)
			e.state.Unlock()
			if err == siacore.BlockKnownErr {
				continue
			} else if err != nil {
				if err == siacore.UnknownOrphanErr {
					e.state.Lock()
					err = e.state.CatchUp(e.server.RandomPeer())
					e.state.Unlock()
					if err != nil {
						// Logging
						// fmt.Println(err2)
					}
				} else if err != siacore.KnownOrphanErr {
					fmt.Println("AcceptBlock Error: ", err)
				}
				continue
			}
			go e.server.Broadcast("AcceptBlock", b, nil)

		case t := <-e.transactionChan:
			e.state.Lock()
			err = e.state.AcceptTransaction(t)
			e.state.Unlock()
			if err != nil {
				fmt.Println("AcceptTransaction Error:", err)
				continue
			}
			go e.server.Broadcast("AcceptTransaction", t, nil)
		}
	}
}
<|endoftext|>


<commit_before>package api

import "strings"

// NetworkACLRule represents a single rule in an ACL ruleset.
// Refer to doc/network-acls.md for details.
//
// swagger:model
//
// API extension: network_acl
type NetworkACLRule struct {
	// Action to perform on rule match
	// Example: allow
	Action string `json:"action" yaml:"action"`

	// Source address
	// Example: #internal
	Source string `json:"source" yaml:"source"`

	// Destination address
	// Example: 8.8.8.8/32,8.8.4.4/32
	Destination string `json:"destination" yaml:"destination"`

	// Protocol
	// Example: udp
	Protocol string `json:"protocol" yaml:"protocol"`

	// Source port
	// Example: 1234
	SourcePort string `json:"source_port" yaml:"source_port"`

	// Destination port
	// Example: 53
	DestinationPort string `json:"destination_port" yaml:"destination_port"`

	// Type of ICMP message (for ICMP protocol)
	// Example: 8
	ICMPType string `json:"icmp_type" yaml:"icmp_type"`

	// ICMP message code (for ICMP protocol)
	// Example: 0
	ICMPCode string `json:"icmp_code" yaml:"icmp_code"`

	// Description of the rule
	// Example: Allow DNS queries to Google DNS
	Description string `json:"description" yaml:"description"`

	// State of the rule
	// Example: enabled
	State string `json:"state" yaml:"state"`
}

// Normalise normalises the fields in the rule so that they are comparable with ones stored.
func (r *NetworkACLRule) Normalise() {
	r.Action = strings.TrimSpace(r.Action)
	r.Protocol = strings.TrimSpace(r.Protocol)
	r.ICMPType = strings.TrimSpace(r.ICMPType)
	r.ICMPCode = strings.TrimSpace(r.ICMPCode)
	r.Description = strings.TrimSpace(r.Description)
	r.State = strings.TrimSpace(r.State)

	// Remove whitespace from Source subject list.
	subjects := strings.Split(r.Source, ",")
	for i, s := range subjects {
		subjects[i] = strings.TrimSpace(s)
	}
	r.Source = strings.Join(subjects, ",")

	// Remove whitespace from Destination subject list.
	subjects = strings.Split(r.Destination, ",")
	for i, s := range subjects {
		subjects[i] = strings.TrimSpace(s)
	}
	r.Destination = strings.Join(subjects, ",")

	// Remove whitespace from SourcePort port list.
	ports := strings.Split(r.SourcePort, ",")
	for i, s := range ports {
		ports[i] = strings.TrimSpace(s)
	}
	r.SourcePort = strings.Join(ports, ",")

	// Remove whitespace from DestinationPort port list.
	ports = strings.Split(r.DestinationPort, ",")
	for i, s := range ports {
		ports[i] = strings.TrimSpace(s)
	}
	r.DestinationPort = strings.Join(ports, ",")
}

// NetworkACLPost used for renaming an ACL.
//
// swagger:model
//
// API extension: network_acl
type NetworkACLPost struct {
	// The new name for the ACL
	// Example: bar
	Name string `json:"name" yaml:"name"` // Name of ACL.
}

// NetworkACLPut used for updating an ACL.
//
// swagger:model
//
// API extension: network_acl
type NetworkACLPut struct {
	// Description of the ACL
	// Example: Web servers
	Description string `json:"description" yaml:"description"`

	// List of egress rules (order independent)
	Egress []NetworkACLRule `json:"egress" yaml:"egress"`

	// List of ingress rules (order independent)
	Ingress []NetworkACLRule `json:"ingress" yaml:"ingress"`

	// ACL configuration map (refer to doc/network-acls.md)
	// Example: {"default.action": "drop"}
	Config map[string]string `json:"config" yaml:"config"`
}

// NetworkACL used for displaying an ACL.
//
// swagger:model
//
// API extension: network_acl
type NetworkACL struct {
	NetworkACLPost `yaml:",inline"`
	NetworkACLPut  `yaml:",inline"`

	// List of URLs of objects using this profile
	// Read only: true
	// Example: ["/1.0/instances/c1", "/1.0/instances/v1", "/1.0/networks/lxdbr0"]
	UsedBy []string `json:"used_by" yaml:"used_by"` // Resources that use the ACL.
}

// Writable converts a full NetworkACL struct into a NetworkACLPut struct (filters read-only fields).
func (acl *NetworkACL) Writable() NetworkACLPut {
	return acl.NetworkACLPut
}

// NetworkACLsPost used for creating an ACL.
//
// swagger:model
//
// API extension: network_acl
type NetworkACLsPost struct {
	NetworkACLPost `yaml:",inline"`
	NetworkACLPut  `yaml:",inline"`
}
<commit_msg>shared/api: Mark most ACL rule fields omitempty<commit_after>package api

import "strings"

// NetworkACLRule represents a single rule in an ACL ruleset.
// Refer to doc/network-acls.md for details.
//
// swagger:model
//
// API extension: network_acl
type NetworkACLRule struct {
	// Action to perform on rule match
	// Example: allow
	Action string `json:"action" yaml:"action"`

	// Source address
	// Example: #internal
	Source string `json:"source,omitempty" yaml:"source,omitempty"`

	// Destination address
	// Example: 8.8.8.8/32,8.8.4.4/32
	Destination string `json:"destination,omitempty" yaml:"destination,omitempty"`

	// Protocol
	// Example: udp
	Protocol string `json:"protocol,omitempty" yaml:"protocol,omitempty"`

	// Source port
	// Example: 1234
	SourcePort string `json:"source_port,omitempty" yaml:"source_port,omitempty"`

	// Destination port
	// Example: 53
	DestinationPort string `json:"destination_port,omitempty" yaml:"destination_port,omitempty"`

	// Type of ICMP message (for ICMP protocol)
	// Example: 8
	ICMPType string `json:"icmp_type,omitempty" yaml:"icmp_type,omitempty"`

	// ICMP message code (for ICMP protocol)
	// Example: 0
	ICMPCode string `json:"icmp_code,omitempty" yaml:"icmp_code,omitempty"`

	// Description of the rule
	// Example: Allow DNS queries to Google DNS
	Description string `json:"description,omitempty" yaml:"description,omitempty"`

	// State of the rule
	// Example: enabled
	State string `json:"state" yaml:"state"`
}

// Normalise normalises the fields in the rule so that they are comparable with ones stored.
func (r *NetworkACLRule) Normalise() {
	r.Action = strings.TrimSpace(r.Action)
	r.Protocol = strings.TrimSpace(r.Protocol)
	r.ICMPType = strings.TrimSpace(r.ICMPType)
	r.ICMPCode = strings.TrimSpace(r.ICMPCode)
	r.Description = strings.TrimSpace(r.Description)
	r.State = strings.TrimSpace(r.State)

	// Remove whitespace from Source subject list.
	subjects := strings.Split(r.Source, ",")
	for i, s := range subjects {
		subjects[i] = strings.TrimSpace(s)
	}
	r.Source = strings.Join(subjects, ",")

	// Remove whitespace from Destination subject list.
	subjects = strings.Split(r.Destination, ",")
	for i, s := range subjects {
		subjects[i] = strings.TrimSpace(s)
	}
	r.Destination = strings.Join(subjects, ",")

	// Remove whitespace from SourcePort port list.
	ports := strings.Split(r.SourcePort, ",")
	for i, s := range ports {
		ports[i] = strings.TrimSpace(s)
	}
	r.SourcePort = strings.Join(ports, ",")

	// Remove whitespace from DestinationPort port list.
	ports = strings.Split(r.DestinationPort, ",")
	for i, s := range ports {
		ports[i] = strings.TrimSpace(s)
	}
	r.DestinationPort = strings.Join(ports, ",")
}

// NetworkACLPost used for renaming an ACL.
//
// swagger:model
//
// API extension: network_acl
type NetworkACLPost struct {
	// The new name for the ACL
	// Example: bar
	Name string `json:"name" yaml:"name"` // Name of ACL.
}

// NetworkACLPut used for updating an ACL.
//
// swagger:model
//
// API extension: network_acl
type NetworkACLPut struct {
	// Description of the ACL
	// Example: Web servers
	Description string `json:"description" yaml:"description"`

	// List of egress rules (order independent)
	Egress []NetworkACLRule `json:"egress" yaml:"egress"`

	// List of ingress rules (order independent)
	Ingress []NetworkACLRule `json:"ingress" yaml:"ingress"`

	// ACL configuration map (refer to doc/network-acls.md)
	// Example: {"default.action": "drop"}
	Config map[string]string `json:"config" yaml:"config"`
}

// NetworkACL used for displaying an ACL.
//
// swagger:model
//
// API extension: network_acl
type NetworkACL struct {
	NetworkACLPost `yaml:",inline"`
	NetworkACLPut  `yaml:",inline"`

	// List of URLs of objects using this profile
	// Read only: true
	// Example: ["/1.0/instances/c1", "/1.0/instances/v1", "/1.0/networks/lxdbr0"]
	UsedBy []string `json:"used_by" yaml:"used_by"` // Resources that use the ACL.
}

// Writable converts a full NetworkACL struct into a NetworkACLPut struct (filters read-only fields).
func (acl *NetworkACL) Writable() NetworkACLPut {
	return acl.NetworkACLPut
}

// NetworkACLsPost used for creating an ACL.
//
// swagger:model
//
// API extension: network_acl
type NetworkACLsPost struct {
	NetworkACLPost `yaml:",inline"`
	NetworkACLPut  `yaml:",inline"`
}
<|endoftext|>


<commit_before>package polymer

import (
	"github.com/gopherjs/gopherjs/js"
	"reflect"
)

var typeOfPtrBindProto = reflect.TypeOf(&BindProto{})

type BindInterface interface {
	Notify(path string)
	data() *BindProto
}

type BindProto struct {
	this *js.Object
}

func (p *BindProto) data() *BindProto { return p }
func (p *BindProto) Notify(path string) {
	lookupProto(p.data().this).data().Notify("model." + path)
}

type AutoBindGoTemplate struct {
	*WrappedElement
}

func (el *AutoBindGoTemplate) Bind(model BindInterface) {
	refType := reflect.TypeOf(model)
	if refType.Kind() != reflect.Ptr || refType.Elem().Kind() != reflect.Struct {
		panic("BindInterface should be a pointer to a struct")
	}

	refVal := reflect.ValueOf(model).Elem()

	bindProtoField, found := refType.Elem().FieldByName("BindProto")
	if !found || !bindProtoField.Anonymous || bindProtoField.Type != typeOfPtrBindProto {
		panic("BindInterface should have an anonymous field polymer.BindProto")
	}

	// Set the BindProto
	refVal.FieldByIndex(bindProtoField.Index).Set(reflect.New(typeOfPtrBindProto.Elem()))

	jsObj := unwrap(el.Underlying())
	proto := lookupProto(jsObj).(*autoBindTemplate)

	if proto.Model != nil {
		panic("Model may only be bound once")
	}

	if model.data().this != nil {
		panic("model is already bound to another template")
	}

	// Setup handlers
	for _, handler := range parseHandlers(refType) {
		jsObj.Set(getJsName(handler.Name), eventHandlerCallback(handler.Func))
	}

	// Setup compute functions
	for _, handler := range parseComputes(refType) {
		jsObj.Set(getJsName(handler.Name), computeCallback(handler.Func))
	}

	// Setup channel based event handlers
	for _, handler := range parseChanHandlers(refType) {
		// Create channel
		chanVal := refVal.FieldByIndex(handler.Index)
		chanVal.Set(reflect.MakeChan(chanVal.Type(), 0))

		// Set handler function
		jsObj.Set(getJsName(handler.Name), eventChanCallback(chanVal))
	}

	// Set the needed data on Go side
	proto.Model = model
	model.data().this = jsObj
	proto.bound = true
	proto.render()

	// Notify the JS side
	proto.Notify("model")
}

// autoBind is a port of the polymer auto-bind template to go, so we can bind our own observers to it
// Original source: https://github.com/Polymer/polymer/blob/master/src/lib/template/dom-bind.html
type autoBindTemplate struct {
	*Proto

	importsReady bool
	bound        bool
	readied      bool
	children     *js.Object // js Array of child nodes

	Model interface{} `polymer:"bind"`
}

func (t *autoBindTemplate) Created() {
	js.Global.Get("Polymer").Get("RenderStatus").Call("whenReady", t.markImportsReady)
}

func (t *autoBindTemplate) Attached() {
	if t.importsReady {
		t.render()
	}
}

func (t *autoBindTemplate) Detached() {
	t.removeChildren()
}

func (t *autoBindTemplate) markImportsReady() {
	t.importsReady = true
	t.ensureReady()
}

func (t *autoBindTemplate) ensureReady() {
	if t.bound && !t.readied {
		t.This().Call("_readySelf")
	}
}

func (t *autoBindTemplate) insertChildren() {
	t.ParentElement().InsertBefore(t.Root(), t)
}

func (t *autoBindTemplate) removeChildren() {
	if t.children.Bool() {
		root := t.Root()
		for i := 0; i < t.children.Length(); i++ {
			root.AppendChild(WrapJSElement(t.children.Index(i)))
		}
	}
}

func (t *autoBindTemplate) prepConfigure() {
	config := js.M{}
	propertyEffects := t.This().Get("_propertyEffects")
	if propertyEffects != js.Undefined {
		for i := 0; i < propertyEffects.Length(); i++ {
			propStr := propertyEffects.Index(i).String()
			config[propStr] = propStr
		}
	}

	setupConfigFunc := t.This().Get("_setupConfigure")
	t.This().Set("_setupConfigure", func() { setupConfigFunc.Call("call", t.This(), config) })
}

func (t *autoBindTemplate) render() {
	if t.bound {
		t.ensureReady()
		if t.children == nil {
			this := t.This()
			this.Set("_template", this)
			this.Call("_prepAnnotations")
			this.Call("_prepEffects")
			this.Call("_prepBehaviors")
			t.prepConfigure()
			this.Call("_prepBindings")
			this.Call("_prepPropertyInfo")
			js.Global.Get("Polymer").Get("Base").Get("_initFeatures").Call("call", this)
			t.children = js.Global.Get("Polymer").Get("TreeApi").Call("arrayCopyChildNodes", this.Get("root"))
		}

		t.insertChildren()
		t.Fire("dom-change", nil)
	}
}

func init() {
	Register("dom-bind-go", &autoBindTemplate{},
		WithExtends("template"),
		CustomRegistrationAttr{"_template", nil},
		CustomRegistrationAttr{"_registerFeatures", js.MakeFunc(func(this *js.Object, args []*js.Object) interface{} {
			this.Call("_prepConstructor")
			return nil
		})},
		CustomRegistrationAttr{"_initFeatures", js.MakeFunc(func(this *js.Object, args []*js.Object) interface{} { return nil })},
		CustomRegistrationAttr{"_scopeElementClass", js.MakeFunc(func(this *js.Object, args []*js.Object) interface{} {
			element := args[0]
			selector := args[1]

			datahost := this.Get("dataHost")
			if datahost.Bool() {
				return datahost.Call("_scopeElementClass", element, selector)
			} else {
				return selector
			}
		})},
	)
}
<commit_msg>Add Element as embedded field to BindProto<commit_after>package polymer

import (
	"github.com/gopherjs/gopherjs/js"
	"reflect"
)

var typeOfPtrBindProto = reflect.TypeOf(&BindProto{})

type BindInterface interface {
	Notify(path string)
	data() *BindProto
}

type BindProto struct {
	this *js.Object
	Element
}

func (p *BindProto) data() *BindProto { return p }
func (p *BindProto) Notify(path string) {
	lookupProto(p.data().this).data().Notify("model." + path)
}

type AutoBindGoTemplate struct {
	*WrappedElement
}

func (el *AutoBindGoTemplate) Bind(model BindInterface) {
	model.data().Element = el.WrappedElement

	refType := reflect.TypeOf(model)
	if refType.Kind() != reflect.Ptr || refType.Elem().Kind() != reflect.Struct {
		panic("BindInterface should be a pointer to a struct")
	}

	refVal := reflect.ValueOf(model).Elem()

	bindProtoField, found := refType.Elem().FieldByName("BindProto")
	if !found || !bindProtoField.Anonymous || bindProtoField.Type != typeOfPtrBindProto {
		panic("BindInterface should have an anonymous field polymer.BindProto")
	}

	// Set the BindProto
	refVal.FieldByIndex(bindProtoField.Index).Set(reflect.New(typeOfPtrBindProto.Elem()))

	jsObj := unwrap(el.Underlying())
	proto := lookupProto(jsObj).(*autoBindTemplate)

	if proto.Model != nil {
		panic("Model may only be bound once")
	}

	if model.data().this != nil {
		panic("model is already bound to another template")
	}

	// Setup handlers
	for _, handler := range parseHandlers(refType) {
		jsObj.Set(getJsName(handler.Name), eventHandlerCallback(handler.Func))
	}

	// Setup compute functions
	for _, handler := range parseComputes(refType) {
		jsObj.Set(getJsName(handler.Name), computeCallback(handler.Func))
	}

	// Setup channel based event handlers
	for _, handler := range parseChanHandlers(refType) {
		// Create channel
		chanVal := refVal.FieldByIndex(handler.Index)
		chanVal.Set(reflect.MakeChan(chanVal.Type(), 0))

		// Set handler function
		jsObj.Set(getJsName(handler.Name), eventChanCallback(chanVal))
	}

	// Set the needed data on Go side
	proto.Model = model
	model.data().this = jsObj
	proto.bound = true
	proto.render()

	// Notify the JS side
	proto.Notify("model")
}

// autoBind is a port of the polymer auto-bind template to go, so we can bind our own observers to it
// Original source: https://github.com/Polymer/polymer/blob/master/src/lib/template/dom-bind.html
type autoBindTemplate struct {
	*Proto

	importsReady bool
	bound        bool
	readied      bool
	children     *js.Object // js Array of child nodes

	Model interface{} `polymer:"bind"`
}

func (t *autoBindTemplate) Created() {
	js.Global.Get("Polymer").Get("RenderStatus").Call("whenReady", t.markImportsReady)
}

func (t *autoBindTemplate) Attached() {
	if t.importsReady {
		t.render()
	}
}

func (t *autoBindTemplate) Detached() {
	t.removeChildren()
}

func (t *autoBindTemplate) markImportsReady() {
	t.importsReady = true
	t.ensureReady()
}

func (t *autoBindTemplate) ensureReady() {
	if t.bound && !t.readied {
		t.This().Call("_readySelf")
	}
}

func (t *autoBindTemplate) insertChildren() {
	t.ParentElement().InsertBefore(t.Root(), t)
}

func (t *autoBindTemplate) removeChildren() {
	if t.children.Bool() {
		root := t.Root()
		for i := 0; i < t.children.Length(); i++ {
			root.AppendChild(WrapJSElement(t.children.Index(i)))
		}
	}
}

func (t *autoBindTemplate) prepConfigure() {
	config := js.M{}
	propertyEffects := t.This().Get("_propertyEffects")
	if propertyEffects != js.Undefined {
		for i := 0; i < propertyEffects.Length(); i++ {
			propStr := propertyEffects.Index(i).String()
			config[propStr] = propStr
		}
	}

	setupConfigFunc := t.This().Get("_setupConfigure")
	t.This().Set("_setupConfigure", func() { setupConfigFunc.Call("call", t.This(), config) })
}

func (t *autoBindTemplate) render() {
	if t.bound {
		t.ensureReady()
		if t.children == nil {
			this := t.This()
			this.Set("_template", this)
			this.Call("_prepAnnotations")
			this.Call("_prepEffects")
			this.Call("_prepBehaviors")
			t.prepConfigure()
			this.Call("_prepBindings")
			this.Call("_prepPropertyInfo")
			js.Global.Get("Polymer").Get("Base").Get("_initFeatures").Call("call", this)
			t.children = js.Global.Get("Polymer").Get("TreeApi").Call("arrayCopyChildNodes", this.Get("root"))
		}

		t.insertChildren()
		t.Fire("dom-change", nil)
	}
}

func init() {
	Register("dom-bind-go", &autoBindTemplate{},
		WithExtends("template"),
		CustomRegistrationAttr{"_template", nil},
		CustomRegistrationAttr{"_registerFeatures", js.MakeFunc(func(this *js.Object, args []*js.Object) interface{} {
			this.Call("_prepConstructor")
			return nil
		})},
		CustomRegistrationAttr{"_initFeatures", js.MakeFunc(func(this *js.Object, args []*js.Object) interface{} { return nil })},
		CustomRegistrationAttr{"_scopeElementClass", js.MakeFunc(func(this *js.Object, args []*js.Object) interface{} {
			element := args[0]
			selector := args[1]

			datahost := this.Get("dataHost")
			if datahost.Bool() {
				return datahost.Call("_scopeElementClass", element, selector)
			} else {
				return selector
			}
		})},
	)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"sort"
	"strconv"
	"strings"

	"github.com/dynport/dgtk/dp-es/Godeps/_workspace/src/github.com/dynport/gocli"
	"github.com/dynport/dgtk/es"
)

type esIndexes struct {
	Host    string `cli:"opt -H default=127.0.0.1"`
	Compact bool   `cli:"opt --compact"`
}

func (r *esIndexes) Run() error {
	idx := &es.Index{Host: r.Host}
	parts := strings.Split(r.Host, ":")
	idx.Host = parts[0]
	var err error
	if len(parts) > 1 {
		idx.Port, err = strconv.Atoi(parts[1])
		if err != nil {
			return err
		}
	}
	stats, e := idx.Stats()
	if e != nil {
		return e
	}
	names := stats.IndexNames()
	if r.Compact {
		for _, n := range names {
			fmt.Println(n)
		}
		return nil
	}
	t := gocli.NewTable()
	if len(names) < 1 {
		logger.Printf("no indexes found")
	}
	t.Add("name", "docs", "size")
	sort.Strings(names)
	for _, name := range names {
		index := stats.Indices[name]
		t.Add(name, index.Total.Docs.Count, sizePretty(index.Total.Store.SizeInBytes))
	}
	fmt.Println(t)
	return nil
}

func sizePretty(size int64) string {
	if size < 1024 {
		return fmt.Sprintf("%d", size)
	} else if size < 1024*1024 {
		return fmt.Sprintf("%.02fk", float64(size)/(1024.0))
	} else {
		return fmt.Sprintf("%.02fm", float64(size)/(1024.0*1024.0))
	}
}
<commit_msg>return early when no indexes are found<commit_after>package main

import (
	"fmt"
	"sort"
	"strconv"
	"strings"

	"github.com/dynport/dgtk/dp-es/Godeps/_workspace/src/github.com/dynport/gocli"
	"github.com/dynport/dgtk/es"
)

type esIndexes struct {
	Host    string `cli:"opt -H default=127.0.0.1"`
	Compact bool   `cli:"opt --compact"`
}

func (r *esIndexes) Run() error {
	idx := &es.Index{Host: r.Host}
	parts := strings.Split(r.Host, ":")
	idx.Host = parts[0]
	var err error
	if len(parts) > 1 {
		idx.Port, err = strconv.Atoi(parts[1])
		if err != nil {
			return err
		}
	}
	stats, e := idx.Stats()
	if e != nil {
		return e
	}
	names := stats.IndexNames()
	if r.Compact {
		for _, n := range names {
			fmt.Println(n)
		}
		return nil
	}
	t := gocli.NewTable()
	if len(names) < 1 {
		logger.Printf("no indexes found")
		return nil
	}
	t.Add("name", "docs", "size")
	sort.Strings(names)
	for _, name := range names {
		index := stats.Indices[name]
		t.Add(name, index.Total.Docs.Count, sizePretty(index.Total.Store.SizeInBytes))
	}
	fmt.Println(t)
	return nil
}

func sizePretty(size int64) string {
	if size < 1024 {
		return fmt.Sprintf("%d", size)
	} else if size < 1024*1024 {
		return fmt.Sprintf("%.02fk", float64(size)/(1024.0))
	} else {
		return fmt.Sprintf("%.02fm", float64(size)/(1024.0*1024.0))
	}
}
<|endoftext|>


<commit_before>// +build linux

package signal // import "github.com/docker/docker/pkg/signal"

import (
	"io/ioutil"
	"os"
	"os/exec"
	"syscall"
	"testing"

	"gotest.tools/assert"
	is "gotest.tools/assert/cmp"
)

func buildTestBinary(t *testing.T, tmpdir string, prefix string) (string, string) {
	tmpDir, err := ioutil.TempDir(tmpdir, prefix)
	assert.NilError(t, err)
	exePath := tmpDir + "/" + prefix
	wd, _ := os.Getwd()
	testHelperCode := wd + "/testfiles/main.go"
	cmd := exec.Command("go", "build", "-o", exePath, testHelperCode)
	err = cmd.Run()
	assert.NilError(t, err)
	return exePath, tmpDir
}

func TestTrap(t *testing.T) {
	var sigmap = []struct {
		name     string
		signal   os.Signal
		multiple bool
	}{
		{"TERM", syscall.SIGTERM, false},
		{"QUIT", syscall.SIGQUIT, true},
		{"INT", os.Interrupt, false},
		{"TERM", syscall.SIGTERM, true},
		{"INT", os.Interrupt, true},
	}
	exePath, tmpDir := buildTestBinary(t, "", "main")
	defer os.RemoveAll(tmpDir)

	for _, v := range sigmap {
		cmd := exec.Command(exePath)
		cmd.Env = append(os.Environ(), "SIGNAL_TYPE="+v.name)
		if v.multiple {
			cmd.Env = append(cmd.Env, "IF_MULTIPLE=1")
		}
		err := cmd.Start()
		assert.NilError(t, err)
		err = cmd.Wait()
		if e, ok := err.(*exec.ExitError); ok {
			code := e.Sys().(syscall.WaitStatus).ExitStatus()
			if v.multiple {
				assert.Check(t, is.DeepEqual(128+int(v.signal.(syscall.Signal)), code))
			} else {
				assert.Check(t, is.Equal(99, code))
			}
			continue
		}
		t.Fatal("process didn't end with any error")
	}

}

func TestDumpStacks(t *testing.T) {
	directory, err := ioutil.TempDir("", "test-dump-tasks")
	assert.Check(t, err)
	defer os.RemoveAll(directory)
	dumpPath, err := DumpStacks(directory)
	assert.Check(t, err)
	readFile, _ := ioutil.ReadFile(dumpPath)
	fileData := string(readFile)
	assert.Check(t, is.Contains(fileData, "goroutine"))
}

func TestDumpStacksWithEmptyInput(t *testing.T) {
	path, err := DumpStacks("")
	assert.Check(t, err)
	assert.Check(t, is.Equal(os.Stderr.Name(), path))
}
<commit_msg>pkg/signal.TestTrap: use a subtest<commit_after>// +build linux

package signal // import "github.com/docker/docker/pkg/signal"

import (
	"io/ioutil"
	"os"
	"os/exec"
	"syscall"
	"testing"

	"gotest.tools/assert"
	is "gotest.tools/assert/cmp"
)

func buildTestBinary(t *testing.T, tmpdir string, prefix string) (string, string) {
	t.Helper()
	tmpDir, err := ioutil.TempDir(tmpdir, prefix)
	assert.NilError(t, err)
	exePath := tmpDir + "/" + prefix
	wd, _ := os.Getwd()
	testHelperCode := wd + "/testfiles/main.go"
	cmd := exec.Command("go", "build", "-o", exePath, testHelperCode)
	err = cmd.Run()
	assert.NilError(t, err)
	return exePath, tmpDir
}

func TestTrap(t *testing.T) {
	var sigmap = []struct {
		name     string
		signal   os.Signal
		multiple bool
	}{
		{"TERM", syscall.SIGTERM, false},
		{"QUIT", syscall.SIGQUIT, true},
		{"INT", os.Interrupt, false},
		{"TERM", syscall.SIGTERM, true},
		{"INT", os.Interrupt, true},
	}
	exePath, tmpDir := buildTestBinary(t, "", "main")
	defer os.RemoveAll(tmpDir)

	for _, v := range sigmap {
		t.Run(v.name, func(t *testing.T) {
			cmd := exec.Command(exePath)
			cmd.Env = append(os.Environ(), "SIGNAL_TYPE="+v.name)
			if v.multiple {
				cmd.Env = append(cmd.Env, "IF_MULTIPLE=1")
			}
			err := cmd.Start()
			assert.NilError(t, err)
			err = cmd.Wait()
			e, ok := err.(*exec.ExitError)
			assert.Assert(t, ok, "expected exec.ExitError, got %T", e)

			code := e.Sys().(syscall.WaitStatus).ExitStatus()
			if v.multiple {
				assert.Check(t, is.DeepEqual(128+int(v.signal.(syscall.Signal)), code))
			} else {
				assert.Check(t, is.Equal(99, code))
			}
		})
	}

}

func TestDumpStacks(t *testing.T) {
	directory, err := ioutil.TempDir("", "test-dump-tasks")
	assert.Check(t, err)
	defer os.RemoveAll(directory)
	dumpPath, err := DumpStacks(directory)
	assert.Check(t, err)
	readFile, _ := ioutil.ReadFile(dumpPath)
	fileData := string(readFile)
	assert.Check(t, is.Contains(fileData, "goroutine"))
}

func TestDumpStacksWithEmptyInput(t *testing.T) {
	path, err := DumpStacks("")
	assert.Check(t, err)
	assert.Check(t, is.Equal(os.Stderr.Name(), path))
}
<|endoftext|>