<commit_before>//
// Copyright (C) 2013 The Docker Cloud authors
//
// 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 dockercloud

import (
	"code.google.com/p/goauth2/oauth"
	compute "code.google.com/p/google-api-go-client/compute/v1beta16"
	"errors"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"time"
)

var(
  instanceType = flag.String("instance-type",
                             "/zones/us-central1-a/machineTypes/n1-standard-1",
                             "The reference to the instance type to create.")
  image = flag.String("image",
                      "https://www.googleapis.com/compute/v1beta16/projects/debian-cloud/global/images/debian-7-wheezy-v20131120",
                      "The GCE image to boot from.")

)
const startup = `#!/bin/bash
sysctl -w net.ipv4.ip_forward=1
wget -qO- https://get.docker.io/ | sh
/etc/init.d/docker stop
docker -d -H=tcp://127.0.0.1:8080 &
`

// A Google Compute Engine implementation of the Cloud interface
type GCECloud struct {
	service   *compute.Service
	projectId string
}

// Create a GCE Cloud instance.  'clientId', 'clientSecret' and 'scope' are used to ask for a client
// credential.  'code' is optional and is only used if a cached credential can not be found.
// 'projectId' is the Google Cloud project name.
func NewCloudGce(clientId string, clientSecret string, scope string, code string, projectId string) *GCECloud {
	// Set up a configuration.
	config := &oauth.Config{
		ClientId:     clientId,
		ClientSecret: clientSecret,
		RedirectURL:  "oob",
		Scope:        scope,
		AuthURL:      "https://accounts.google.com/o/oauth2/auth",
		TokenURL:     "https://accounts.google.com/o/oauth2/token",
		// TODO(bburns) : This prob. won't work on Windows
		TokenCache: oauth.CacheFile(os.Getenv("HOME") + "/cache.json"),
	}

	// Set up a Transport using the config.
	// transport := &oauth.Transport{Config: config,
	//         Transport: &LogTransport{http.DefaultTransport},}
	transport := &oauth.Transport{Config: config, Transport: http.DefaultTransport}

	// Try to pull the token from the cache; if this fails, we need to get one.
	token, err := config.TokenCache.Token()
	if err != nil {
		if clientId == "" || clientSecret == "" {
			flag.Usage()
			fmt.Fprint(os.Stderr, "Client id and secret are required.")
			os.Exit(2)
		}
		if code == "" {
			// Get an authorization code from the data provider.
			// ("Please ask the user if I can access this resource.")
			url := config.AuthCodeURL("")
			fmt.Println("Visit this URL to get a code, then run again with -code=YOUR_CODE\n")
			fmt.Println(url)
			// The below doesn't work for some reason.  Not sure why.  I get 404's
			// fmt.Print("Enter code: ")
			// bio := bufio.NewReader(os.Stdin)
			// code, err = bio.ReadString('\n')
			// if err != nil {
			//        log.Fatal("input: ", err)
			// }
			return nil
		}
		// Exchange the authorization code for an access token.
		// ("Here's the code you gave the user, now give me a token!")
		// TODO(bburns) : Put up a separate web end point to do the oauth dance, so a user can just go to a web page.
		token, err = transport.Exchange(code)
		if err != nil {
			log.Fatal("Exchange:", err)
		}
		// (The Exchange method will automatically cache the token.)
		fmt.Printf("Token is cached in %v\n", config.TokenCache)
	}

	// Make the actual request using the cached token to authenticate.
	// ("Here's the token, let me in!")
	transport.Token = token

	svc, err := compute.New(transport.Client())
	if err != nil {
		log.Printf("Error creating service: %v", err)
	}
	return &GCECloud{
		service:   svc,
		projectId: projectId,
	}
}

// Implementation of the Cloud interface
func (cloud GCECloud) GetPublicIPAddress(name string, zone string) (string, error) {
	instance, err := cloud.service.Instances.Get(cloud.projectId, zone, name).Do()
	if err != nil {
		return "", err
	}
	// Found the instance, we're good.
	return instance.NetworkInterfaces[0].AccessConfigs[0].NatIP, nil
}

// Implementation of the Cloud interface
func (cloud GCECloud) CreateInstance(name string, zone string) (string, error) {
	prefix := "https://www.googleapis.com/compute/v1beta16/projects/" + cloud.projectId
	instance := &compute.Instance{
		Name:        name,
		Description: "Docker on GCE",
		MachineType: prefix + *instanceType,
		Image:       *image,
		NetworkInterfaces: []*compute.NetworkInterface{
			&compute.NetworkInterface{
				AccessConfigs: []*compute.AccessConfig{
					&compute.AccessConfig{Type: "ONE_TO_ONE_NAT"},
				},
				Network: prefix + "/global/networks/default",
			},
		},
		Metadata: &compute.Metadata{
			Items: []*compute.MetadataItems{
				&compute.MetadataItems{
					Key:   "startup-script",
					Value: startup,
				},
			},
		},
	}
	op, err := cloud.service.Instances.Insert(cloud.projectId, zone, instance).Do()
	if err != nil {
		fmt.Printf("Error: %s\n", err)
		return instance.NetworkInterfaces[0].AccessConfigs[0].NatIP, err
	}
	err = cloud.waitForOp(op, zone)
	// Wait for docker to come up
	// TODO(bburns) : Use metadata instead to signal that docker is up and read.
	time.Sleep(60 * time.Second)

	return instance.NetworkInterfaces[0].AccessConfigs[0].NatIP, err
}

// Implementation of the Cloud interface
func (cloud GCECloud) DeleteInstance(name string, zone string) error {
	op, err := cloud.service.Instances.Delete(cloud.projectId, zone, name).Do()
	if err != nil {
		log.Printf("Got compute.Operation, err: %#v, %v", op, err)
		return err
	}
	return cloud.waitForOp(op, zone)
}

func (cloud GCECloud) OpenSecureTunnel(name string, zone string, localPort int, remotePort int) (*os.Process, error) {
	ip, err := cloud.GetPublicIPAddress(name, zone)
	if err != nil {
		return nil, err
	}
	username := os.Getenv("USER")
	homedir := os.Getenv("HOME")

	sshCommand := fmt.Sprintf("-o LogLevel=quiet -o UserKnownHostsFile=/dev/null -o CheckHostIP=no -o StrictHostKeyChecking=no -i %s/.ssh/google_compute_engine -A -p 22 %s@%s -f -N -L %d:localhost:%d", homedir, username, ip, localPort, remotePort)
	fmt.Printf("Running %s\n", sshCommand)
	cmd := exec.Command("ssh", strings.Split(sshCommand, " ")...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	cmd.Run()
	return cmd.Process, nil
}

// Implementation of the Cloud interface
func (cloud GCECloud) RunRemoteCommand(name string, zone string, outstream io.Writer, errstream io.Writer, instream io.Reader, args ...string) error {
	ip, err := cloud.GetPublicIPAddress(name, zone)
	if err != nil {
		return err
	}
	username := os.Getenv("USER")
	homedir := os.Getenv("HOME")

	sshCommand := fmt.Sprintf("-o LogLevel=quiet -o UserKnownHostsFile=/dev/null -o CheckHostIP=no -o StrictHostKeyChecking=no -i %s/.ssh/google_compute_engine -A -p 22 %s@%s %s", homedir, username, ip, strings.Join(args, " "))
	fmt.Printf("Running %s\n", sshCommand)
	cmd := exec.Command("ssh", strings.Split(sshCommand, " ")...)
	cmd.Stdout = outstream
	cmd.Stderr = errstream
	if instream != nil {
		cmd.Stdin = os.Stdin
	}
	cmd.Run()
	fmt.Printf("Run...")
	return nil
}

// Wait for a compute operation to finish.
//   op The operation
//   zone The zone for the operation
// Returns an error if one occurs, or nil
func (cloud GCECloud) waitForOp(op *compute.Operation, zone string) error {
	op, err := cloud.service.ZoneOperations.Get(cloud.projectId, zone, op.Name).Do()
	for op.Status != "DONE" {
		time.Sleep(5 * time.Second)
		op, err = cloud.service.ZoneOperations.Get(cloud.projectId, zone, op.Name).Do()
		if err != nil {
			log.Printf("Got compute.Operation, err: %#v, %v", op, err)
		}
		if op.Status != "PENDING" && op.Status != "RUNNING" && op.Status != "DONE" {
			log.Printf("Error waiting for operation: %s\n", op);
			return errors.New(fmt.Sprintf("Bad operation: %s", op))
		}
	}
	return err
}
<commit_msg>gce: upgrade to compute v1<commit_after>//
// Copyright (C) 2013 The Docker Cloud authors
//
// 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 dockercloud

import (
	"code.google.com/p/goauth2/oauth"
	compute "code.google.com/p/google-api-go-client/compute/v1"
	"errors"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"
	"strings"
	"time"
)

var (
	instanceType = flag.String("instancetype",
		"/zones/us-central1-a/machineTypes/n1-standard-1",
		"The reference to the instance type to create.")
	image = flag.String("image",
		"https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/backports-debian-7-wheezy-v20131127",
		"The GCE image to boot from.")
	diskName   = flag.String("diskname", "docker-root", "Name of the instance root disk")
	diskSizeGb = flag.Int64("disksize", 100, "Size of the root disk in GB")
)

const startup = `#!/bin/bash
sysctl -w net.ipv4.ip_forward=1
wget -qO- https://get.docker.io/ | sh
/etc/init.d/docker stop
docker -d -H=tcp://127.0.0.1:8080 &
`

// A Google Compute Engine implementation of the Cloud interface
type GCECloud struct {
	service   *compute.Service
	projectId string
}

// Create a GCE Cloud instance.  'clientId', 'clientSecret' and 'scope' are used to ask for a client
// credential.  'code' is optional and is only used if a cached credential can not be found.
// 'projectId' is the Google Cloud project name.
func NewCloudGce(clientId string, clientSecret string, scope string, code string, projectId string) *GCECloud {
	// Set up a configuration.
	config := &oauth.Config{
		ClientId:     clientId,
		ClientSecret: clientSecret,
		RedirectURL:  "oob",
		Scope:        scope,
		AuthURL:      "https://accounts.google.com/o/oauth2/auth",
		TokenURL:     "https://accounts.google.com/o/oauth2/token",
		// TODO(bburns) : This prob. won't work on Windows
		TokenCache: oauth.CacheFile(os.Getenv("HOME") + "/cache.json"),
	}

	// Set up a Transport using the config.
	// transport := &oauth.Transport{Config: config,
	//         Transport: &LogTransport{http.DefaultTransport},}
	transport := &oauth.Transport{Config: config, Transport: http.DefaultTransport}

	// Try to pull the token from the cache; if this fails, we need to get one.
	token, err := config.TokenCache.Token()
	if err != nil {
		if clientId == "" || clientSecret == "" {
			flag.Usage()
			fmt.Fprint(os.Stderr, "Client id and secret are required.")
			os.Exit(2)
		}
		if code == "" {
			// Get an authorization code from the data provider.
			// ("Please ask the user if I can access this resource.")
			url := config.AuthCodeURL("")
			fmt.Println("Visit this URL to get a code, then run again with -code=YOUR_CODE\n")
			fmt.Println(url)
			// The below doesn't work for some reason.  Not sure why.  I get 404's
			// fmt.Print("Enter code: ")
			// bio := bufio.NewReader(os.Stdin)
			// code, err = bio.ReadString('\n')
			// if err != nil {
			//        log.Fatal("input: ", err)
			// }
			return nil
		}
		// Exchange the authorization code for an access token.
		// ("Here's the code you gave the user, now give me a token!")
		// TODO(bburns) : Put up a separate web end point to do the oauth dance, so a user can just go to a web page.
		token, err = transport.Exchange(code)
		if err != nil {
			log.Fatal("Exchange:", err)
		}
		// (The Exchange method will automatically cache the token.)
		fmt.Printf("Token is cached in %v\n", config.TokenCache)
	}

	// Make the actual request using the cached token to authenticate.
	// ("Here's the token, let me in!")
	transport.Token = token

	svc, err := compute.New(transport.Client())
	if err != nil {
		log.Printf("Error creating service: %v", err)
	}
	return &GCECloud{
		service:   svc,
		projectId: projectId,
	}
}

// Implementation of the Cloud interface
func (cloud GCECloud) GetPublicIPAddress(name string, zone string) (string, error) {
	instance, err := cloud.service.Instances.Get(cloud.projectId, zone, name).Do()
	if err != nil {
		return "", err
	}
	// Found the instance, we're good.
	return instance.NetworkInterfaces[0].AccessConfigs[0].NatIP, nil
}

// Get or create a new root disk.
func (cloud GCECloud) getOrCreateRootDisk(name, zone string) (string, error) {
	disk, err := cloud.service.Disks.Get(cloud.projectId, zone, *diskName).Do()
	if err == nil {
		return disk.SelfLink, nil
	}
	op, err := cloud.service.Disks.Insert(cloud.projectId, zone, &compute.Disk{
		Name:        *diskName,
		SourceImage: *image,
		SizeGb:      *diskSizeGb,
	}).Do()
	if err != nil {
		log.Printf("disk insert api call failed: %v", err)
		return "", err
	}
	err = cloud.waitForOp(op, zone)
	if err != nil {
		log.Printf("disk insert operation failed: %v", err)
		return "", err
	}
	return op.TargetLink, nil
}

// Implementation of the Cloud interface
func (cloud GCECloud) CreateInstance(name string, zone string) (string, error) {
	rootDisk, err := cloud.getOrCreateRootDisk(*diskName, zone)
	if err != nil {
		log.Printf("failed to create root disk: %v", err)
		return "", err
	}
	prefix := "https://www.googleapis.com/compute/v1/projects/" + cloud.projectId
	instance := &compute.Instance{
		Name:        name,
		Description: "Docker on GCE",
		MachineType: prefix + *instanceType,
		Disks: []*compute.AttachedDisk{
			{
				Boot:   true,
				Type:   "PERSISTENT",
				Mode:   "READ_WRITE",
				Source: rootDisk,
			},
		},
		NetworkInterfaces: []*compute.NetworkInterface{
			{
				AccessConfigs: []*compute.AccessConfig{
					&compute.AccessConfig{Type: "ONE_TO_ONE_NAT"},
				},
				Network: prefix + "/global/networks/default",
			},
		},
		Metadata: &compute.Metadata{
			Items: []*compute.MetadataItems{
				{
					Key:   "startup-script",
					Value: startup,
				},
			},
		},
	}
	op, err := cloud.service.Instances.Insert(cloud.projectId, zone, instance).Do()
	if err != nil {
		log.Printf("instance insert api call failed: %v", err)
		return "", err
	}
	err = cloud.waitForOp(op, zone)
	if err != nil {
		log.Printf("instance insert operation failed: %v", err)
		return "", err
	}
	// Wait for docker to come up
	// TODO(bburns) : Use metadata instead to signal that docker is up and read.
	time.Sleep(60 * time.Second)

	return instance.NetworkInterfaces[0].AccessConfigs[0].NatIP, err
}

// Implementation of the Cloud interface
func (cloud GCECloud) DeleteInstance(name string, zone string) error {
	op, err := cloud.service.Instances.Delete(cloud.projectId, zone, name).Do()
	if err != nil {
		log.Printf("Got compute.Operation, err: %#v, %v", op, err)
		return err
	}
	return cloud.waitForOp(op, zone)
}

func (cloud GCECloud) OpenSecureTunnel(name string, zone string, localPort int, remotePort int) (*os.Process, error) {
	ip, err := cloud.GetPublicIPAddress(name, zone)
	if err != nil {
		return nil, err
	}
	username := os.Getenv("USER")
	homedir := os.Getenv("HOME")

	sshCommand := fmt.Sprintf("-o LogLevel=quiet -o UserKnownHostsFile=/dev/null -o CheckHostIP=no -o StrictHostKeyChecking=no -i %s/.ssh/google_compute_engine -A -p 22 %s@%s -f -N -L %d:localhost:%d", homedir, username, ip, localPort, remotePort)
	fmt.Printf("Running %s\n", sshCommand)
	cmd := exec.Command("ssh", strings.Split(sshCommand, " ")...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	cmd.Run()
	return cmd.Process, nil
}

// Implementation of the Cloud interface
func (cloud GCECloud) RunRemoteCommand(name string, zone string, outstream io.Writer, errstream io.Writer, instream io.Reader, args ...string) error {
	ip, err := cloud.GetPublicIPAddress(name, zone)
	if err != nil {
		return err
	}
	username := os.Getenv("USER")
	homedir := os.Getenv("HOME")

	sshCommand := fmt.Sprintf("-o LogLevel=quiet -o UserKnownHostsFile=/dev/null -o CheckHostIP=no -o StrictHostKeyChecking=no -i %s/.ssh/google_compute_engine -A -p 22 %s@%s %s", homedir, username, ip, strings.Join(args, " "))
	fmt.Printf("Running %s\n", sshCommand)
	cmd := exec.Command("ssh", strings.Split(sshCommand, " ")...)
	cmd.Stdout = outstream
	cmd.Stderr = errstream
	if instream != nil {
		cmd.Stdin = os.Stdin
	}
	cmd.Run()
	fmt.Printf("Run...")
	return nil
}

// Wait for a compute operation to finish.
//   op The operation
//   zone The zone for the operation
// Returns an error if one occurs, or nil
func (cloud GCECloud) waitForOp(op *compute.Operation, zone string) error {
	op, err := cloud.service.ZoneOperations.Get(cloud.projectId, zone, op.Name).Do()
	for op.Status != "DONE" {
		time.Sleep(5 * time.Second)
		op, err = cloud.service.ZoneOperations.Get(cloud.projectId, zone, op.Name).Do()
		if err != nil {
			log.Printf("Got compute.Operation, err: %#v, %v", op, err)
		}
		if op.Status != "PENDING" && op.Status != "RUNNING" && op.Status != "DONE" {
			log.Printf("Error waiting for operation: %s\n", op)
			return errors.New(fmt.Sprintf("Bad operation: %s", op))
		}
	}
	return err
}
<|endoftext|>


<commit_before>package buildinfo

import (
	"encoding/base64"
	"fmt"
	"github.com/hlandau/buildinfo"
	"gopkg.in/hlandau/easyconfig.v1/cflag"
	"os"
	"runtime"
	"strings"
)

// Full build info.
var BuildInfo string

// Set via go build.
var RawBuildInfo string

// Program-settable extra version information to print.
var Extra string

func init() {
	if RawBuildInfo != "" {
		buildinfo.RawBuildInfo = RawBuildInfo
	}
	if BuildInfo != "" {
		buildinfo.BuildInfo = BuildInfo
	}
	if Extra != "" {
		buildinfo.Extra = Extra
	}
	buildinfo.Update()
	RawBuildInfo = buildinfo.RawBuildInfo
	BuildInfo = buildinfo.BuildInfo
	Extra = buildinfo.Extra
}

func Full() string {
	return buildinfo.Full()
}
<commit_msg>Fixes<commit_after>package buildinfo

import "github.com/hlandau/buildinfo"

// Full build info.
var BuildInfo string

// Set via go build.
var RawBuildInfo string

// Program-settable extra version information to print.
var Extra string

func init() {
	if RawBuildInfo != "" {
		buildinfo.RawBuildInfo = RawBuildInfo
	}
	if BuildInfo != "" {
		buildinfo.BuildInfo = BuildInfo
	}
	if Extra != "" {
		buildinfo.Extra = Extra
	}
	buildinfo.Update()
	RawBuildInfo = buildinfo.RawBuildInfo
	BuildInfo = buildinfo.BuildInfo
	Extra = buildinfo.Extra
}

func Full() string {
	return buildinfo.Full()
}
<|endoftext|>


<commit_before>package cache

// SessionCache allows storing a map between a session ID and a session signature
type SessionCache struct {
	ID        string `bson:"_id" json:"key"`
	Signature string `bson:"signature" json:"signature"`
}

// GetKey returns the key of the cached session map
func (s SessionCache) GetKey() string {
	return s.ID
}

// GetValue returns session data as a string
func (s SessionCache) GetValue() string {
	return s.Signature
}
<commit_msg>:arrow_up: cache: update marshalling to conform to camelcase as per idiomatic JS<commit_after>package cache

// SessionCache allows storing a map between a session ID and a session signature
type SessionCache struct {
	ID        string `bson:"_id" json:"id" xml:"id"`
	Signature string `bson:"signature" json:"signature" xml:"signature"`
}

// GetKey returns the key of the cached session map
func (s SessionCache) GetKey() string {
	return s.ID
}

// GetValue returns session data as a string
func (s SessionCache) GetValue() string {
	return s.Signature
}
<|endoftext|>


<commit_before>/*
Copyright IBM Corp. 2016 All Rights Reserved.

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 main

//WARNING - this chaincode's ID is hard-coded in chaincode_example04 to illustrate one way of
//calling chaincode from a chaincode. If this example is modified, chaincode_example04.go has
//to be modified as well with the new ID of chaincode_example02.
//chaincode_example05 show's how chaincode ID can be passed in as a parameter instead of
//hard-coding.

import (
	"errors"
	"fmt"
	"strconv"
	"bytes"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var err error

	if len(args) != 4 {
		return nil, errors.New("Incorrect number of arguments. Expecting 4")
	}

	// Initialize the chaincode
	A = args[0]
	Aval, err = strconv.Atoi(args[1])
	if err != nil {
		return nil, errors.New("Expecting integer value for asset holding")
	}
	B = args[2]
	Bval, err = strconv.Atoi(args[3])
	if err != nil {
		return nil, errors.New("Expecting integer value for asset holding")
	}
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

func (t *SimpleChaincode) write(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
    var key, value string
    var err error
    fmt.Println("Storing the parameters in hyperledger fabric...")

    /*if len(args) != 2 {
        return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the key and value to set")
    }*/

	if(len(args)%2 != 0) {
		  fmt.Printf("Incorrect number of arguments. One of the keys or values is missing.")
		  fmt.Println("")

    }else{
	     for i := 0; i < len(args); i++ {
	     if(i%2 == 0){
		     if args[i] != "" {
                  fmt.Printf("Key: %s", args[i])
				  fmt.Println("")
				  key = args[i]
				  i++
             }
		     if(i!=len(args)) {
			      fmt.Printf("Value: %s", args[i])
			      fmt.Println("")
				  value = args[i]
			 }
		     err = stub.PutState(key, []byte(value))  //write the variable into the chaincode state
			 if err != nil {
				return nil, err
			 }
		 }
    }
	}

	/*
    key = args[0]                            //rename for fun
    value = args[1]
    err = stub.PutState(key, []byte(value))  //write the variable into the chaincode state
    if err != nil {
        return nil, err
    }
	*/

    return nil, nil
}

// Transaction makes payment of X units from A to B
func (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	if function == "delete" {
		// Deletes an entity from its state
		return t.delete(stub, args)
	}
	if function == "write" {
		fmt.Println("Calling write()")
        return t.write(stub, args)
    }

	var A, B string    // Entities
	var Aval, Bval int // Asset holdings
	var X int          // Transaction value
	var err error

	if len(args) != 3 {
		return nil, errors.New("Incorrect number of arguments. Expecting 3")
	}

	A = args[0]
	B = args[1]

	// Get the state from the ledger
	// TODO: will be nice to have a GetAllState call to ledger
	Avalbytes, err := stub.GetState(A)
	if err != nil {
		return nil, errors.New("Failed to get state")
	}
	if Avalbytes == nil {
		return nil, errors.New("Entity not found")
	}
	Aval, _ = strconv.Atoi(string(Avalbytes))

	Bvalbytes, err := stub.GetState(B)
	if err != nil {
		return nil, errors.New("Failed to get state")
	}
	if Bvalbytes == nil {
		return nil, errors.New("Entity not found")
	}
	Bval, _ = strconv.Atoi(string(Bvalbytes))

	// Perform the execution
	X, err = strconv.Atoi(args[2])
	Aval = Aval - X
	Bval = Bval + X
	fmt.Printf("Aval = %d, Bval = %d\n", Aval, Bval)

	// Write the state back to the ledger
	err = stub.PutState(A, []byte(strconv.Itoa(Aval)))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(B, []byte(strconv.Itoa(Bval)))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Deletes an entity from state
func (t *SimpleChaincode) delete(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting 1")
	}

	A := args[0]

	// Delete the key from the state in ledger
	err := stub.DelState(A)
	if err != nil {
		return nil, errors.New("Failed to delete state")
	}

	return nil, nil
}

// Query callback representing the query of a chaincode
func (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	/*if function != "query" {
		return nil, errors.New("Invalid query function name. Expecting \"query\"")
	}*/

	if function == "queryAll" {
		fmt.Println("Calling QueryAll()")
        return t.queryAll(stub, args)
    }

	var A string // Entities
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the person to query")
	}

	A = args[0]

	// Get the state from the ledger
	Avalbytes, err := stub.GetState(A)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}"
		return nil, errors.New(jsonResp)
	}

	if Avalbytes == nil {
		jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}"
		return nil, errors.New(jsonResp)
	}

	jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return Avalbytes, nil
}

// Query callback representing the query of a chaincode
func (t *SimpleChaincode) queryAll(stub *shim.ChaincodeStub, args []string) ([]byte, error) {

	//var A string // Entities
	//var err error

	/*if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the person to query")
	}*/
    var RetValue []byte
	var buffer bytes.Buffer
		for i := 0; i < len(args); i++ {
		    Avalbytes, err := stub.GetState(args[i])
			if err != nil {
				jsonResp := "{\"Error\":\"Failed to get state for " + args[i] + "\"}"
				return nil, errors.New(jsonResp)
			}

			if Avalbytes == nil {
				jsonResp := "{\"Error\":\"Nil amount for " + args[i] + "\"}"
				return nil, errors.New(jsonResp)
			}

			jsonRespString :=  "\"Name\":\"" + args[i] + "\",\"Value\":\"" + string(Avalbytes) + "\""
			RetValue = []byte(jsonRespString)
			buffer.WriteString(jsonRespString)

		}
		jsonResp := "{"+buffer.String()+"}"
		fmt.Printf("Query Response:%s\n", jsonResp)
		return RetValue, nil

	/*
	A = args[0]

	// Get the state from the ledger
	Avalbytes, err := stub.GetState(A)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + A + "\"}"
		return nil, errors.New(jsonResp)
	}

	if Avalbytes == nil {
		jsonResp := "{\"Error\":\"Nil amount for " + A + "\"}"
		return nil, errors.New(jsonResp)
	}

	jsonResp := "{\"Name\":\"" + A + "\",\"Amount\":\"" + string(Avalbytes) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return Avalbytes, nil
	*/
}

func main() {
	err := shim.Start(new(SimpleChaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}
<commit_msg>Delete chaincode_example02.go<commit_after><|endoftext|>


<commit_before>package progressbar

import (
	"io"
	"time"

	pb "gopkg.in/cheggaaa/pb.v1"
)

type ProgressBar struct {
	ready chan bool
	bar   *pb.ProgressBar
}

func NewProgressBar() *ProgressBar {
	return &ProgressBar{
		ready: make(chan bool),
	}
}

func (p *ProgressBar) NewProgressBarWrapper(reader io.Reader, sizeOfFile int64) io.Reader {
	ready, ok := <-p.ready
	if !ready || !ok {
		return nil
	}

	p.bar = pb.New(int(sizeOfFile)).SetUnits(pb.U_BYTES)
	p.bar.ShowTimeLeft = false
	p.bar.Start()
	return p.bar.NewProxyReader(reader)
}

func (p *ProgressBar) Ready() {
	p.ready <- true
}

func (p *ProgressBar) Complete() {
	// Adding sleep to ensure UI has finished drawing
	time.Sleep(time.Second)
}
<commit_msg>calling Finish on progress bar is required<commit_after>package progressbar

import (
	"io"
	"time"

	pb "gopkg.in/cheggaaa/pb.v1"
)

type ProgressBar struct {
	ready chan bool
	bar   *pb.ProgressBar
}

func NewProgressBar() *ProgressBar {
	return &ProgressBar{
		ready: make(chan bool),
	}
}

func (p *ProgressBar) NewProgressBarWrapper(reader io.Reader, sizeOfFile int64) io.Reader {
	ready, ok := <-p.ready
	if !ready || !ok {
		return nil
	}

	p.bar = pb.New(int(sizeOfFile)).SetUnits(pb.U_BYTES)
	p.bar.ShowTimeLeft = false
	p.bar.Start()
	return p.bar.NewProxyReader(reader)
}

func (p *ProgressBar) Ready() {
	p.ready <- true
}

func (p *ProgressBar) Complete() {
	// Adding sleep to ensure UI has finished drawing
	time.Sleep(time.Second)
	p.bar.Finish()
}
<|endoftext|>


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

package gc

//	case OADD:
//		if(n->right->op == OLITERAL) {
//			v = n->right->vconst;
//			naddr(n->left, a, canemitcode);
//		} else
//		if(n->left->op == OLITERAL) {
//			v = n->left->vconst;
//			naddr(n->right, a, canemitcode);
//		} else
//			goto bad;
//		a->offset += v;
//		break;

// a function named init is a special case.
// it is called by the initialization before
// main is run. to make it unique within a
// package and also uncallable, the name,
// normally "pkg.init", is altered to "pkg.init.1".

var renameinit_initgen int

func renameinit() *Sym {
	renameinit_initgen++
	return Lookupf("init.%d", renameinit_initgen)
}

// hand-craft the following initialization code
//	var initdone· uint8 				(1)
//	func init()					(2)
//		if initdone· != 0 {			(3)
//			if initdone· == 2		(4)
//				return
//			throw();			(5)
//		}
//		initdone· = 1;				(6)
//		// over all matching imported symbols
//			<pkg>.init()			(7)
//		{ <init stmts> }			(8)
//		init.<n>() // if any			(9)
//		initdone· = 2;				(10)
//		return					(11)
//	}
func anyinit(n *NodeList) bool {
	// are there any interesting init statements
	for l := n; l != nil; l = l.Next {
		switch l.N.Op {
		case ODCLFUNC, ODCLCONST, ODCLTYPE, OEMPTY:
			break

		case OAS, OASWB:
			if isblank(l.N.Left) && candiscard(l.N.Right) {
				break
			}
			fallthrough

			// fall through
		default:
			return true
		}
	}

	// is this main
	if localpkg.Name == "main" {
		return true
	}

	// is there an explicit init function
	s := Lookup("init.1")

	if s.Def != nil {
		return true
	}

	// are there any imported init functions
	for _, s := range initSyms {
		if s.Def != nil {
			return true
		}
	}

	// then none
	return false
}

func fninit(n *NodeList) {
	if Debug['A'] != 0 {
		// sys.go or unsafe.go during compiler build
		return
	}

	n = initfix(n)
	if !anyinit(n) {
		return
	}

	var r *NodeList

	// (1)
	gatevar := newname(Lookup("initdone·"))
	addvar(gatevar, Types[TUINT8], PEXTERN)

	// (2)
	Maxarg = 0

	fn := Nod(ODCLFUNC, nil, nil)
	initsym := Lookup("init")
	fn.Func.Nname = newname(initsym)
	fn.Func.Nname.Name.Defn = fn
	fn.Func.Nname.Name.Param.Ntype = Nod(OTFUNC, nil, nil)
	declare(fn.Func.Nname, PFUNC)
	funchdr(fn)

	// (3)
	a := Nod(OIF, nil, nil)

	a.Left = Nod(ONE, gatevar, Nodintconst(0))
	r = list(r, a)

	// (4)
	b := Nod(OIF, nil, nil)

	b.Left = Nod(OEQ, gatevar, Nodintconst(2))
	b.Nbody = list1(Nod(ORETURN, nil, nil))
	a.Nbody = list1(b)

	// (5)
	b = syslook("throwinit", 0)

	b = Nod(OCALL, b, nil)
	a.Nbody = list(a.Nbody, b)

	// (6)
	a = Nod(OAS, gatevar, Nodintconst(1))

	r = list(r, a)

	// (7)
	for _, s := range initSyms {
		if s.Def != nil && s != initsym {
			// could check that it is fn of no args/returns
			a = Nod(OCALL, s.Def, nil)
			r = list(r, a)
		}
	}

	// (8)
	r = concat(r, n)

	// (9)
	// could check that it is fn of no args/returns
	for i := 1; ; i++ {
		s := Lookupf("init.%d", i)
		if s.Def == nil {
			break
		}
		a = Nod(OCALL, s.Def, nil)
		r = list(r, a)
	}

	// (10)
	a = Nod(OAS, gatevar, Nodintconst(2))

	r = list(r, a)

	// (11)
	a = Nod(ORETURN, nil, nil)

	r = list(r, a)
	exportsym(fn.Func.Nname)

	fn.Nbody = r
	funcbody(fn)

	Curfn = fn
	typecheck(&fn, Etop)
	typechecklist(r, Etop)
	Curfn = nil
	funccompile(fn)
}
<commit_msg>[dev.ssa] cmd/compile: tweak init function prologue<commit_after>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package gc

//	case OADD:
//		if(n->right->op == OLITERAL) {
//			v = n->right->vconst;
//			naddr(n->left, a, canemitcode);
//		} else
//		if(n->left->op == OLITERAL) {
//			v = n->left->vconst;
//			naddr(n->right, a, canemitcode);
//		} else
//			goto bad;
//		a->offset += v;
//		break;

// a function named init is a special case.
// it is called by the initialization before
// main is run. to make it unique within a
// package and also uncallable, the name,
// normally "pkg.init", is altered to "pkg.init.1".

var renameinit_initgen int

func renameinit() *Sym {
	renameinit_initgen++
	return Lookupf("init.%d", renameinit_initgen)
}

// hand-craft the following initialization code
//	var initdone· uint8 				(1)
//	func init()					(2)
//              if initdone· > 1 {                      (3)
//                      return                          (3a)
//		if initdone· == 1 {			(4)
//			throw();			(4a)
//		}
//		initdone· = 1;				(6)
//		// over all matching imported symbols
//			<pkg>.init()			(7)
//		{ <init stmts> }			(8)
//		init.<n>() // if any			(9)
//		initdone· = 2;				(10)
//		return					(11)
//	}
func anyinit(n *NodeList) bool {
	// are there any interesting init statements
	for l := n; l != nil; l = l.Next {
		switch l.N.Op {
		case ODCLFUNC, ODCLCONST, ODCLTYPE, OEMPTY:
			break

		case OAS, OASWB:
			if isblank(l.N.Left) && candiscard(l.N.Right) {
				break
			}
			fallthrough

			// fall through
		default:
			return true
		}
	}

	// is this main
	if localpkg.Name == "main" {
		return true
	}

	// is there an explicit init function
	s := Lookup("init.1")

	if s.Def != nil {
		return true
	}

	// are there any imported init functions
	for _, s := range initSyms {
		if s.Def != nil {
			return true
		}
	}

	// then none
	return false
}

func fninit(n *NodeList) {
	if Debug['A'] != 0 {
		// sys.go or unsafe.go during compiler build
		return
	}

	n = initfix(n)
	if !anyinit(n) {
		return
	}

	var r *NodeList

	// (1)
	gatevar := newname(Lookup("initdone·"))
	addvar(gatevar, Types[TUINT8], PEXTERN)

	// (2)
	Maxarg = 0

	fn := Nod(ODCLFUNC, nil, nil)
	initsym := Lookup("init")
	fn.Func.Nname = newname(initsym)
	fn.Func.Nname.Name.Defn = fn
	fn.Func.Nname.Name.Param.Ntype = Nod(OTFUNC, nil, nil)
	declare(fn.Func.Nname, PFUNC)
	funchdr(fn)

	// (3)
	a := Nod(OIF, nil, nil)
	a.Left = Nod(OGT, gatevar, Nodintconst(1))
	a.Likely = 1
	r = list(r, a)
	// (3a)
	a.Nbody = list1(Nod(ORETURN, nil, nil))

	// (4)
	b := Nod(OIF, nil, nil)
	b.Left = Nod(OEQ, gatevar, Nodintconst(1))
	// this actually isn't likely, but code layout is better
	// like this: no JMP needed after the call.
	b.Likely = 1
	r = list(r, b)
	// (4a)
	b.Nbody = list1(Nod(OCALL, syslook("throwinit", 0), nil))

	// (6)
	a = Nod(OAS, gatevar, Nodintconst(1))

	r = list(r, a)

	// (7)
	for _, s := range initSyms {
		if s.Def != nil && s != initsym {
			// could check that it is fn of no args/returns
			a = Nod(OCALL, s.Def, nil)
			r = list(r, a)
		}
	}

	// (8)
	r = concat(r, n)

	// (9)
	// could check that it is fn of no args/returns
	for i := 1; ; i++ {
		s := Lookupf("init.%d", i)
		if s.Def == nil {
			break
		}
		a = Nod(OCALL, s.Def, nil)
		r = list(r, a)
	}

	// (10)
	a = Nod(OAS, gatevar, Nodintconst(2))

	r = list(r, a)

	// (11)
	a = Nod(ORETURN, nil, nil)

	r = list(r, a)
	exportsym(fn.Func.Nname)

	fn.Nbody = r
	funcbody(fn)

	Curfn = fn
	typecheck(&fn, Etop)
	typechecklist(r, Etop)
	Curfn = nil
	funccompile(fn)
}
<|endoftext|>


<commit_before>package spoukfw

import (
	"sync"
	"net/http"
	"log"
	"fmt"
	"runtime"
	"reflect"
)

const (
	prefixSpoukMix = "[spoukmix][logger]"
	defaultErrorMsgSpoukMux = "[spoukmux][error] `%v`"
	//errors spoukmux
	errorSessionObject = "не найден объект сессии, надо подключить"
)

type (
	Spoukmux struct {
		config      *Spoukconfig
		router      *spoukrouter
		pool        sync.Pool
		middlewares spoukstockmiddlewares
		render      SpoukMuxRendering
		logger      *SpoukLogger
		RouteMapper map[string]spoukMapRoute
		session     *SpoukSession
		handlers    SpoukHandlerStock
	}
//интерфейс для рендера
	SpoukMuxRendering  interface {
		SpoukRenderIO(name string, data interface{}, resp http.ResponseWriter, reloadTemplate bool) (err error)
		AddUserFilter(name string, f interface{})
		AddFilters(stack map[string]interface{})
		ReloadTemplate()
	}
//интерфейс для стека обработчиков
	SpoukHandlerStock interface {
		StockInit(s *SpoukCarry, args ...interface{})
	}

)

func (m *Spoukmux) SetStockHandlerStock(stock SpoukHandlerStock) {
	m.handlers = stock
}
func (m *Spoukmux) ShowRoutingMap() {
	for _, x := range m.RouteMapper {
		fmt.Printf("[spoukmux] [%7s] `%20s`  `%+v`   `%v`\n", x.Method, x.Path, x.Handler, x.HandlerX)
	}
}
func (m *Spoukmux) SetRender(r SpoukMuxRendering) {
	m.render = r
}
func (m *Spoukmux) Session() *SpoukSession {
	return m.session
}

func (m Spoukmux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	m.router.ServeHTTP(w, r)
}
func (m *Spoukmux) getPool(w http.ResponseWriter, r *http.Request) (res *SpoukCarry) {
	newcarry := m.pool.Get().(*SpoukCarry)
	newcarry.response = &w
	newcarry.request = r.WithContext(r.Context())
	return newcarry
}
func (m *Spoukmux) putPool(res *SpoukCarry) {
	m.pool.Put(res)
}
func (m *Spoukmux) StaticFiles(realpath, wwwpath string) {
	m.router.StaticFiles(realpath, wwwpath)
}
func (s *Spoukmux) catchErrors() {
	log.Printf("[spoukmux][catcher-errros]\n")
}
func (s *Spoukmux) Run() {
	//reload template для парсинга шаблонов
	s.render.ReloadTemplate()
	defer s.catchErrors()
	srv := http.Server{
		Addr:         s.config.Address,
		Handler:      s,
		ReadTimeout:  s.config.HTTPReadTimeout,
		WriteTimeout: s.config.HTTPWriteTimeout,
	}
	log.Printf(fmt.Sprintf("[middlewares]%v\n[session] `%v`\n[sessionobject] `%v`\n", s.middlewares, s.session))
	log.Printf(fmt.Sprintf(runInfo, s.config.Address))
	log.Fatal(srv.ListenAndServe())
}

func (s *Spoukmux) AddMiddleware(mid Midfunc) {
	s.middlewares.setStockMiddlePrefix("", mid)
}
func (s *Spoukmux) ShowConfig() {
	fmt.Printf("[spoukmux]ConfigProxy: %v\nSpoukconfig: %v\n ", s.config.ConfigProxy, s.config)
}

// user filter map[commandintemplate]func closure
func (s *Spoukmux) AddUserFlitersRender(userfilters  map[string]interface{}) {
	s.render.AddFilters(userfilters)
}
func (s *Spoukmux) AddUserFilterRender(name string, f interface{}) {
	s.render.AddUserFilter(name, f)
}
func NewSpoukmux(spcfg *Spoukconfig) *Spoukmux {
	m := Spoukmux{
		pool:   sync.Pool{},
		config:spcfg,
		router:newSpoukRouter(),
	}
	m.router.spoukmux = &m
	m.middlewares = make(spoukstockmiddlewares)
	m.middlewares.setStockMiddlePrefix("", loggerMiddleware)
	m.router.middlewares = &m.middlewares
	m.RouteMapper = make(map[string]spoukMapRoute)
	if m.config.UseSession {
		m.session = newSpoukSession(&m)
		m.middlewares.setStockMiddlePrefix("", sessionMiddleware)
	}
	//m.middlewares.setStockMiddlePrefix("", initFuncMidleware)
	m.logger = NewSpoukLogger(prefixSpoukMix, nil)
	m.router.router.HandleMethodNotAllowed = false
	m.router.router.NotFound = m.router.wrapperforSpoukHandler(error404spoukhandler)
	//m.SetMehodNotAllowedHandler(error405methodNotAllowed)
	m.router.router.MethodNotAllowed = http.HandlerFunc(allow405)

	m.router.spoukmux = &m
	m.router.router.RedirectTrailingSlash = true
	m.pool.New = func() interface{} {
		return &SpoukCarry{
			Spoukmux: &m,
			request: &http.Request{},
		}
	}

	//rendering default
	m.render = NewSpoukRender(m.config.TemplatePath, m.config.TemplateDebug)

	//fmt.Printf("[spoukmux] middlewaresstock: %v\n", m.middlewares)
	//m.ShowMiddlewares()
	return &m
}

func (s *Spoukmux) ShowMiddlewares() {
	for prefix, stock := range s.middlewares {
		fmt.Printf("[spoukmux][`%s`] \n", prefix)
		for _, x := range stock {
			nameHandler := runtime.FuncForPC(reflect.ValueOf(x).Pointer()).Name()
			fmt.Printf("[spoukmux][`%s`]  `%v`\n", prefix, nameHandler)
		}
	}
}
func (s *Spoukmux) Multi(methods []string, path string, h SpoukHandler) {
	s.router.Multi(methods, path, h)
}
func (s *Spoukmux) Get(path string, h SpoukHandler) {
	s.router.Get(path, h)
}
func (s *Spoukmux) Post(path string, h SpoukHandler) {
	s.router.Post(path, h)
}
func (s *Spoukmux) Config() *Spoukconfig {
	return s.config
}
func (s *Spoukmux) SetSessionObject(so SpoukSessionObject) {
	if s.session != nil {
		s.session.SessionObject = so
	} else {
		s.logger.Printf(makeErrorMessage(defaultErrorMsgSpoukMux, errorSessionObject).Error())
	}
}
func (s *Spoukmux ) SetMehodNotAllowedHandler(h  SpoukHandler) {
	s.router.router.MethodNotAllowed = s.router.wrapperforSpoukHandler(h)
}
//---------------------------------------------------------------------------
//  testing subroute
//---------------------------------------------------------------------------
func (s *Spoukmux) Subroute(prefix string) *spoukSubdomain {
	newss := &spoukSubdomain{spoukmux:*s, prefix:prefix}
	newss.prefix = prefix
	return newss
}

type spoukSubdomain struct {
	spoukmux Spoukmux
	prefix   string
}
func (ss *spoukSubdomain) Multi(methods []string, path string, s SpoukHandler) {
	for _, m := range methods {
		if ss.spoukmux.router.checkMethod(m) {
			ss.spoukmux.router.addRoute(m, path, ss.prefix, s)
		} else {
			err := makeErrorMessage(defRouterError, fmt.Sprintf("метод  `%s` не подходящий", m))
			log.Fatal(err.Error())
		}
	}
}
func (ss *spoukSubdomain) AddMiddleware(mid Midfunc) {
	ss.spoukmux.middlewares.setStockMiddlePrefix(ss.prefix, mid)
	fmt.Printf("[spoukSubdomain][AddMiddleware] %v\n", ss.spoukmux.middlewares)
}
func (ss *spoukSubdomain) Get(path string, h SpoukHandler) {
	ss.spoukmux.router.addRoute("GET", path, ss.prefix, h)
}
func (ss *spoukSubdomain) Post(path string, h SpoukHandler) {
	ss.spoukmux.router.addRoute("POST", path, ss.prefix, h)
}
func (ss *spoukSubdomain) Delete(path string, h SpoukHandler) {
	ss.spoukmux.router.addRoute("DELETE", path, ss.prefix, h)
}
func (ss *spoukSubdomain) Update(path string, h SpoukHandler) {
	ss.spoukmux.router.addRoute("UPDATE", path, ss.prefix, h)
}<commit_msg>correct code<commit_after>package spoukfw

import (
	"sync"
	"net/http"
	"log"
	"fmt"
	"runtime"
	"reflect"
)

const (
	prefixSpoukMix = "[spoukmix][logger]"
	defaultErrorMsgSpoukMux = "[spoukmux][error] `%v`"
	//errors spoukmux
	errorSessionObject = "не найден объект сессии, надо подключить"
)

type (
	Spoukmux struct {
		config      *Spoukconfig
		router      *spoukrouter
		pool        sync.Pool
		middlewares spoukstockmiddlewares
		render      SpoukMuxRendering
		logger      *SpoukLogger
		RouteMapper map[string]spoukMapRoute
		session     *SpoukSession
		handlers    SpoukHandlerStock
	}
//интерфейс для рендера
	SpoukMuxRendering  interface {
		SpoukRenderIO(name string, data interface{}, resp http.ResponseWriter, reloadTemplate bool) (err error)
		AddUserFilter(name string, f interface{})
		AddFilters(stack map[string]interface{})
		ReloadTemplate()
	}
//интерфейс для стека обработчиков
	SpoukHandlerStock interface {
		StockInit(s *SpoukCarry, args ...interface{})
	}

)

func (m *Spoukmux) SetStockHandlerStock(stock SpoukHandlerStock) {
	m.handlers = stock
}
func (m *Spoukmux) ShowRoutingMap() {
	for _, x := range m.RouteMapper {
		fmt.Printf("[spoukmux] [%7s] `%20s`  `%+v`   `%v`\n", x.Method, x.Path, x.Handler, x.HandlerX)
	}
}
func (m *Spoukmux) SetRender(r SpoukMuxRendering) {
	m.render = r
}
func (m *Spoukmux) Session() *SpoukSession {
	return m.session
}

func (m Spoukmux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	m.router.ServeHTTP(w, r)
}
func (m *Spoukmux) getPool(w http.ResponseWriter, r *http.Request) (res *SpoukCarry) {
	newcarry := m.pool.Get().(*SpoukCarry)
	newcarry.response = &w
	newcarry.request = r.WithContext(r.Context())
	return newcarry
}
func (m *Spoukmux) putPool(res *SpoukCarry) {
	m.pool.Put(res)
}
func (m *Spoukmux) StaticFiles(realpath, wwwpath string) {
	m.router.StaticFiles(realpath, wwwpath)
}
func (s *Spoukmux) catchErrors() {
	log.Printf("[spoukmux][catcher-errros]\n")
}
func (s *Spoukmux) Run() {
	//reload template для парсинга шаблонов
	s.render.ReloadTemplate()
	defer s.catchErrors()
	srv := http.Server{
		Addr:         s.config.Address,
		Handler:      s,
		ReadTimeout:  s.config.HTTPReadTimeout,
		WriteTimeout: s.config.HTTPWriteTimeout,
	}
	log.Printf(fmt.Sprintf("[middlewares]%v\n[session] `%v`\n[sessionobject] `%v`\n", s.middlewares, s.session))
	log.Printf(fmt.Sprintf(runInfo, s.config.Address))
	log.Fatal(srv.ListenAndServe())
}
func (s *Spoukmux) RunTLS(certFile, keyFile string) {
	//reload template для парсинга шаблонов
	s.render.ReloadTemplate()
	defer s.catchErrors()
	srv := http.Server{
		Addr:         s.config.Address,
		Handler:      s,
		ReadTimeout:  s.config.HTTPReadTimeout,
		WriteTimeout: s.config.HTTPWriteTimeout,
	}
	log.Printf(fmt.Sprintf("[middlewares]%v\n[session] `%v`\n[sessionobject] `%v`\n", s.middlewares, s.session))
	log.Printf(fmt.Sprintf(runInfo, s.config.Address))
	log.Fatal(srv.ListenAndServeTLS(certFile, keyFile))
}

func (s *Spoukmux) AddMiddleware(mid Midfunc) {
	s.middlewares.setStockMiddlePrefix("", mid)
}
func (s *Spoukmux) ShowConfig() {
	fmt.Printf("[spoukmux]ConfigProxy: %v\nSpoukconfig: %v\n ", s.config.ConfigProxy, s.config)
}

// user filter map[commandintemplate]func closure
func (s *Spoukmux) AddUserFlitersRender(userfilters  map[string]interface{}) {
	s.render.AddFilters(userfilters)
}
func (s *Spoukmux) AddUserFilterRender(name string, f interface{}) {
	s.render.AddUserFilter(name, f)
}
func NewSpoukmux(spcfg *Spoukconfig) *Spoukmux {
	m := Spoukmux{
		pool:   sync.Pool{},
		config:spcfg,
		router:newSpoukRouter(),
	}
	m.router.spoukmux = &m
	m.middlewares = make(spoukstockmiddlewares)
	m.middlewares.setStockMiddlePrefix("", loggerMiddleware)
	m.router.middlewares = &m.middlewares
	m.RouteMapper = make(map[string]spoukMapRoute)
	if m.config.UseSession {
		m.session = newSpoukSession(&m)
		m.middlewares.setStockMiddlePrefix("", sessionMiddleware)
	}
	//m.middlewares.setStockMiddlePrefix("", initFuncMidleware)
	m.logger = NewSpoukLogger(prefixSpoukMix, nil)
	m.router.router.HandleMethodNotAllowed = false
	m.router.router.NotFound = m.router.wrapperforSpoukHandler(error404spoukhandler)
	//m.SetMehodNotAllowedHandler(error405methodNotAllowed)
	m.router.router.MethodNotAllowed = http.HandlerFunc(allow405)

	m.router.spoukmux = &m
	m.router.router.RedirectTrailingSlash = true
	m.pool.New = func() interface{} {
		return &SpoukCarry{
			Spoukmux: &m,
			request: &http.Request{},
		}
	}

	//rendering default
	m.render = NewSpoukRender(m.config.TemplatePath, m.config.TemplateDebug)

	//fmt.Printf("[spoukmux] middlewaresstock: %v\n", m.middlewares)
	//m.ShowMiddlewares()
	return &m
}

func (s *Spoukmux) ShowMiddlewares() {
	for prefix, stock := range s.middlewares {
		fmt.Printf("[spoukmux][`%s`] \n", prefix)
		for _, x := range stock {
			nameHandler := runtime.FuncForPC(reflect.ValueOf(x).Pointer()).Name()
			fmt.Printf("[spoukmux][`%s`]  `%v`\n", prefix, nameHandler)
		}
	}
}
func (s *Spoukmux) Multi(methods []string, path string, h SpoukHandler) {
	s.router.Multi(methods, path, h)
}
func (s *Spoukmux) Get(path string, h SpoukHandler) {
	s.router.Get(path, h)
}
func (s *Spoukmux) Post(path string, h SpoukHandler) {
	s.router.Post(path, h)
}
func (s *Spoukmux) Config() *Spoukconfig {
	return s.config
}
func (s *Spoukmux) SetSessionObject(so SpoukSessionObject) {
	if s.session != nil {
		s.session.SessionObject = so
	} else {
		s.logger.Printf(makeErrorMessage(defaultErrorMsgSpoukMux, errorSessionObject).Error())
	}
}
func (s *Spoukmux ) SetMehodNotAllowedHandler(h  SpoukHandler) {
	s.router.router.MethodNotAllowed = s.router.wrapperforSpoukHandler(h)
}
//---------------------------------------------------------------------------
//  testing subroute
//---------------------------------------------------------------------------
func (s *Spoukmux) Subroute(prefix string) *spoukSubdomain {
	newss := &spoukSubdomain{spoukmux:*s, prefix:prefix}
	newss.prefix = prefix
	return newss
}

type spoukSubdomain struct {
	spoukmux Spoukmux
	prefix   string
}
func (ss *spoukSubdomain) Multi(methods []string, path string, s SpoukHandler) {
	for _, m := range methods {
		if ss.spoukmux.router.checkMethod(m) {
			ss.spoukmux.router.addRoute(m, path, ss.prefix, s)
		} else {
			err := makeErrorMessage(defRouterError, fmt.Sprintf("метод  `%s` не подходящий", m))
			log.Fatal(err.Error())
		}
	}
}
func (ss *spoukSubdomain) AddMiddleware(mid Midfunc) {
	ss.spoukmux.middlewares.setStockMiddlePrefix(ss.prefix, mid)
	fmt.Printf("[spoukSubdomain][AddMiddleware] %v\n", ss.spoukmux.middlewares)
}
func (ss *spoukSubdomain) Get(path string, h SpoukHandler) {
	ss.spoukmux.router.addRoute("GET", path, ss.prefix, h)
}
func (ss *spoukSubdomain) Post(path string, h SpoukHandler) {
	ss.spoukmux.router.addRoute("POST", path, ss.prefix, h)
}
func (ss *spoukSubdomain) Delete(path string, h SpoukHandler) {
	ss.spoukmux.router.addRoute("DELETE", path, ss.prefix, h)
}
func (ss *spoukSubdomain) Update(path string, h SpoukHandler) {
	ss.spoukmux.router.addRoute("UPDATE", path, ss.prefix, h)
}<|endoftext|>


<commit_before>package main

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"time"
)

const baseURL = "http://gateway.marvel.com/v1/public"

type Client struct {
	public, private string
}

func NewClient(public, private string) Client {
	return Client{public, private}
}

// See http://developer.marvel.com/documentation/authorization
func (c Client) hash() (int64, string) {
	ts := time.Now().Unix()
	hash := md5.New()
	io.WriteString(hash, fmt.Sprintf("%d%s%s", ts, c.private, c.public))
	return ts, fmt.Sprintf("%x", hash.Sum(nil))
}

func (c Client) baseURL() url.URL {
	u := url.URL{
		Scheme: "https",
		Host:   "gateway.marvel.com",
		Path:   "/v1/public/",
	}
	ts, hash := c.hash()
	u.RawQuery = url.Values(map[string][]string{
		"ts":     []string{fmt.Sprintf("%d", ts)},
		"apikey": []string{c.public},
		"hash":   []string{hash},
	}).Encode()
	return u
}

type commonResponse struct {
	Code            int    `json:"code"`
	ETag            string `json:"etag"`
	Status          string `json:"status"`
	Copyright       string `json:"copyright"`
	AttributionText string `json:"attributionText"`
	AttributionHTML string `json:"attributionHTML"`
}

type commonList struct {
	Offset int `json:"offset"`
	Limit  int `json:"limit"`
	Total  int `json:"total"`
	Count  int `json:"count"`
}

func (c Client) Series(id int64) (r struct {
	commonResponse
	Data struct {
		commonList
		Results []struct {
			ID        int `json:"id"`
			DigitalID int `json:"digitalId"`
		} `json:"results"`
	} `json:"data"`
}, err error) {
	u := c.baseURL()
	u.Path += fmt.Sprintf("series/%d/comics", id)

	resp, herr := http.Get(u.String())
	if herr != nil {
		err = herr
		return
	}
	defer resp.Body.Close()

	err = json.NewDecoder(resp.Body).Decode(&r)
	return
}
<commit_msg>Handle HTTP errors moar better<commit_after>package main

import (
	"crypto/md5"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"
)

const baseURL = "http://gateway.marvel.com/v1/public"

type Client struct {
	public, private string
}

func NewClient(public, private string) Client {
	return Client{public, private}
}

// See http://developer.marvel.com/documentation/authorization
func (c Client) hash() (int64, string) {
	ts := time.Now().Unix()
	hash := md5.New()
	io.WriteString(hash, fmt.Sprintf("%d%s%s", ts, c.private, c.public))
	return ts, fmt.Sprintf("%x", hash.Sum(nil))
}

func (c Client) baseURL() url.URL {
	u := url.URL{
		Scheme: "https",
		Host:   "gateway.marvel.com",
		Path:   "/v1/public/",
	}
	ts, hash := c.hash()
	u.RawQuery = url.Values(map[string][]string{
		"ts":     []string{fmt.Sprintf("%d", ts)},
		"apikey": []string{c.public},
		"hash":   []string{hash},
	}).Encode()
	return u
}

// Fields common to all response entities
type commonResponse struct {
	Code            int    `json:"code"`
	ETag            string `json:"etag"`
	Status          string `json:"status"`
	Copyright       string `json:"copyright"`
	AttributionText string `json:"attributionText"`
	AttributionHTML string `json:"attributionHTML"`
}

// Fields common to data that lists entities, with pagination
type commonList struct {
	Offset int `json:"offset"`
	Limit  int `json:"limit"`
	Total  int `json:"total"`
	Count  int `json:"count"`
}

func (c Client) Series(id int64) (r struct {
	commonResponse
	Data struct {
		commonList
		Results []struct {
			ID        int `json:"id"`
			DigitalID int `json:"digitalId"`
		} `json:"results"`
	} `json:"data"`
}, err error) {
	u := c.baseURL()
	u.Path += fmt.Sprintf("series/%d/comics", id)

	resp, herr := http.Get(u.String())
	if herr != nil {
		err = herr
		return
	}
	defer resp.Body.Close()
	if resp.StatusCode >= http.StatusBadRequest {
		slurp, rerr := ioutil.ReadAll(resp.Body)
		if rerr != nil {
			err = rerr
			return
		}
		err = fmt.Errorf("error response from API: %d\n%s", resp.StatusCode, slurp)
		return
	}

	err = json.NewDecoder(resp.Body).Decode(&r)
	return
}
<|endoftext|>


<commit_before>// Package matrix provides functions for simple linear algebra
package matrix

import (
	"bytes"
	"fmt"
	"math"
	"math/rand"
	"strconv"
	"strings"
)

var (
	ErrIncompatibleSizes    = &MatrixError{"Incompatible sizes of matricies"}
	ErrInsertionOutOfBounds = &MatrixError{"The matrix you are trying to insert to hasn't got that row or column."}
	ErrOutOfBounds          = &MatrixError{"The element you are trying to access is out of bounds."}
)

// Describes error during calculations
type MatrixError struct {
	ErrorString string
}

// Return the Error's string
func (err *MatrixError) Error() string { return err.ErrorString }

// Matrix construct that holds all the information about a matrix
type Matrix struct {
	rows, cols int
	values     []float64
}

// A function that will apply an abitary transformation to an element in the matrix
type ApplyFunc func(index int, value float64) float64

// Creates a new Matrix and initializes all values to 0
func Zeros(rows, cols int) *Matrix {
	A := new(Matrix)

	A.rows = rows
	A.cols = cols
	A.values = make([]float64, rows*cols)

	return A
}

// Creates a new Matrix and initializes all values to 1
func Ones(rows, cols int) *Matrix {
	A := Zeros(rows, cols)
	A.AddNum(1)

	return A
}

// Creates a new identity matrix
func Eye(size int) *Matrix {
	A := Zeros(size, size)

	for i := 1; i <= size; i++ {
		A.Set(i, i, 1)
	}

	return A
}

// Constructs a new matrix with random values in range [0;1)
func Rand(rows, cols int) *Matrix {
	A := Zeros(rows, cols)

	for i := range A.values {
		A.values[i] = rand.Float64()
	}

	return A
}

// Constructs a new Matrix from a Matlab style representation
//
//	A := matrix.FromMatlab("[1 2 3; 4 5 6]")
func FromMatlab(str string) *Matrix {
	rows := strings.Split(str, ";")

	for i, row := range rows {
		rows[i] = strings.Replace(row, ",", " ", -1)
	}

	nRows := len(rows)
	nColumns := len(strings.Fields(rows[0]))

	A := Zeros(nRows, nColumns)

	for i, row := range rows {
		row = strings.Trim(row, "[] ")
		strNums := strings.Fields(row)

		for j, num := range strNums {
			n, _ := strconv.ParseFloat(num, 64)
			A.Set(i+1, j+1, n)
		}
	}

	return A
}

// Return a Matlab representation of the matrix
func (A *Matrix) ToMatlab() string {
	buffer := new(bytes.Buffer)
	buffer.WriteString("[")

	for i, v := range A.values {
		buffer.WriteString(fmt.Sprintf("%f ", v))

		if (i+1)%A.cols == 0 {
			buffer.WriteString("; ")
		}
	}

	buffer.WriteString("]")

	return buffer.String()
}

// Gives the dimensions of the matrix
func (A *Matrix) Dim() (int, int) {
	return A.rows, A.cols
}

// Return the number of rows in the matrix
func (A *Matrix) Rows() int {
	return A.rows
}

// Return the number of columns in the matrix
func (A *Matrix) Columns() int {
	return A.cols
}

// Returns an array of all the values
func (A *Matrix) Values() []float64 {
	tmp := make([]float64, len(A.values))
	copy(tmp, A.values)
	return tmp
}

// Returns a string representation of the matrix
func (A *Matrix) String() string {
	buffer := new(bytes.Buffer)

	for i, elem := range A.values {
		buffer.WriteString(fmt.Sprintf("%.3f ", elem))

		if (i+1)%A.cols == 0 {
			buffer.WriteString("\n")
		}
	}

	return buffer.String()
}

// Returns an exact copy of the matrix
func (A *Matrix) Copy() *Matrix {
	B := Zeros(A.rows, A.cols)
	copy(B.values, A.values)

	return B
}

// Insert the given rows into the matrix, returning a new matrix.
// Passing 0 as the second argument is like making the
// passed rows the first few, whereas passing Rows() is like appending
// the additional rows to the matrix.
//
// Warning: This is an unsafe method to use, it does no boundary
// checking what so ever. If you'd like a safe version
// use: SafeInsertRows
func (A *Matrix) InsertRows(rows *Matrix, afterRow int) *Matrix {
	B := Zeros(A.rows+rows.rows, A.cols)

	// copy rows before inserted rows
	copy(B.values[0:afterRow*B.cols], A.values[0:afterRow*B.cols])
	// insert new rows
	copy(B.values[afterRow*B.cols:afterRow*B.cols+rows.rows*B.cols], rows.values)
	// copy rows after inserted rows
	copy(B.values[afterRow*B.cols+rows.rows*B.cols:], A.values[afterRow*B.cols:])

	return B
}

// Insert the given columns into the matrix, returning a new matrix.
// Passing 0 as the second argument is like making the
// passed columns the first few (on the left), whereas passing Columns() is like appending
// the additional columns to the matrix (on the right).
//
// Warning: This is an unsafe method to use, it does no boundary
// checking what so ever. If you'd like a safe version
// use: SafeInsertColumns
func (A *Matrix) InsertColumns(cols *Matrix, afterCol int) *Matrix {
	B := Zeros(A.rows, A.cols+cols.cols)

	return B
}

// Give a function, apply its transformation to every element in the matrix.
//
//	A := matrix.Rand(4, 8)
//	A.Apply(func(index int, value float64) float64 {
//		return sigmoid(value)
//	})
func (A *Matrix) Apply(f ApplyFunc) *Matrix {
	for i, v := range A.values {
		A.values[i] = f(i, v)
	}

	return A
}

// Get the element at [row, col].
//
// Warning: This is an unsafe method to use, it does no boundary
// checking what so ever. If you'd like a safe version
// use: SafeGet
func (A *Matrix) Get(row, col int) float64 {
	return A.values[(row-1)*A.cols+col-1]
}

// Set the element at [row, col] to val.
//
// Warning: This is an unsafe method to use, it does no boundary
// checking what so ever. If you'd like a safe version
// use: SafeSet
func (A *Matrix) Set(row, col int, val float64) {

	A.values[(row-1)*A.cols+col-1] = val

}

// Transpose the matrix
func (A *Matrix) Transpose() *Matrix {
	B := Zeros(A.cols, A.rows)

	for i := 1; i <= A.rows; i++ {
		for j := 1; j <= A.cols; j++ {
			B.values[(j-1)*B.cols+i-1] = A.values[(i-1)*A.cols+j-1]
		}
	}

	return B
}

// Add B to the matrix A, produces new matrix
func (A *Matrix) Add(B *Matrix) (*Matrix, error) {
	if !sameSize(A, B) {
		return nil, ErrIncompatibleSizes
	}

	C := Zeros(A.rows, A.cols)

	for i, val := range A.values {
		C.values[i] = val + B.values[i]
	}

	return C, nil
}

// Subtract B from the matrix A, produces a new matrix
func (A *Matrix) Sub(B *Matrix) (*Matrix, error) {
	if !sameSize(A, B) {
		return nil, ErrIncompatibleSizes
	}

	C := Zeros(A.rows, A.cols)

	for i, val := range A.values {
		C.values[i] = val - B.values[i]
	}

	return C, nil
}

// Multiplies 2 matricies with each other.
// Returns a new matrix.
//
// Warning: This is an unsafe method to use, it does no boundary
// checking what so ever. If you'd like a safe version
// use: SafeMul
func (A *Matrix) Mul(B *Matrix) *Matrix {

	C := Zeros(A.rows, B.cols)

	for i := 0; i < C.rows; i++ {
		for j := 0; j < C.cols; j++ {
			sum := float64(0)

			for k := 0; k < A.cols; k++ {
				sum += A.values[i*A.cols+k] * B.values[k*B.cols+j]
			}

			C.values[i*C.rows+j] = sum
		}
	}

	return C
}

// Standard scalar product of 2 matricies.
// Returns a new matrix.
//
// Warning: This is an unsafe method to use, it does no boundary
// checking what so ever. If you'd like a safe version
// use: SafeDot
func (A *Matrix) Dot(B *Matrix) *Matrix {
	C := Zeros(A.rows, A.cols)

	for i, val := range A.values {
		C.values[i] = val * B.values[i]
	}

	return C
}

// Scale the matrix by the factor f
func (A *Matrix) Scale(f float64) *Matrix {
	B := Zeros(A.rows, A.cols)

	for i, val := range A.values {
		B.values[i] = val * f
	}

	return B
}

// Take every element of the matrix to the power of n
func (A *Matrix) Power(n float64) *Matrix {
	B := Zeros(A.rows, A.cols)

	for i, val := range A.values {
		B.values[i] = math.Pow(val, n)
	}

	return B
}

// Add n to all elements in the matrix (in-place)
func (A *Matrix) AddNum(n float64) *Matrix {
	for i := range A.values {
		A.values[i] += n
	}

	return A
}
<commit_msg>implemented InsertColumns; next up is the safe version<commit_after>// Package matrix provides functions for simple linear algebra
package matrix

import (
	"bytes"
	"fmt"
	"math"
	"math/rand"
	"strconv"
	"strings"
)

var (
	ErrIncompatibleSizes    = &MatrixError{"Incompatible sizes of matricies"}
	ErrInsertionOutOfBounds = &MatrixError{"The matrix you are trying to insert to hasn't got that row or column."}
	ErrOutOfBounds          = &MatrixError{"The element you are trying to access is out of bounds."}
)

// Describes error during calculations
type MatrixError struct {
	ErrorString string
}

// Return the Error's string
func (err *MatrixError) Error() string { return err.ErrorString }

// Matrix construct that holds all the information about a matrix
type Matrix struct {
	rows, cols int
	values     []float64
}

// A function that will apply an abitary transformation to an element in the matrix
type ApplyFunc func(index int, value float64) float64

// Creates a new Matrix and initializes all values to 0
func Zeros(rows, cols int) *Matrix {
	A := new(Matrix)

	A.rows = rows
	A.cols = cols
	A.values = make([]float64, rows*cols)

	return A
}

// Creates a new Matrix and initializes all values to 1
func Ones(rows, cols int) *Matrix {
	A := Zeros(rows, cols)
	A.AddNum(1)

	return A
}

// Creates a new identity matrix
func Eye(size int) *Matrix {
	A := Zeros(size, size)

	for i := 1; i <= size; i++ {
		A.Set(i, i, 1)
	}

	return A
}

// Constructs a new matrix with random values in range [0;1)
func Rand(rows, cols int) *Matrix {
	A := Zeros(rows, cols)

	for i := range A.values {
		A.values[i] = rand.Float64()
	}

	return A
}

// Constructs a new Matrix from a Matlab style representation
//
//	A := matrix.FromMatlab("[1 2 3; 4 5 6]")
func FromMatlab(str string) *Matrix {
	rows := strings.Split(str, ";")

	for i, row := range rows {
		rows[i] = strings.Replace(row, ",", " ", -1)
	}

	nRows := len(rows)
	nColumns := len(strings.Fields(rows[0]))

	A := Zeros(nRows, nColumns)

	for i, row := range rows {
		row = strings.Trim(row, "[] ")
		strNums := strings.Fields(row)

		for j, num := range strNums {
			n, _ := strconv.ParseFloat(num, 64)
			A.Set(i+1, j+1, n)
		}
	}

	return A
}

// Return a Matlab representation of the matrix
func (A *Matrix) ToMatlab() string {
	buffer := new(bytes.Buffer)
	buffer.WriteString("[")

	for i, v := range A.values {
		buffer.WriteString(fmt.Sprintf("%f ", v))

		if (i+1)%A.cols == 0 {
			buffer.WriteString("; ")
		}
	}

	buffer.WriteString("]")

	return buffer.String()
}

// Gives the dimensions of the matrix
func (A *Matrix) Dim() (int, int) {
	return A.rows, A.cols
}

// Return the number of rows in the matrix
func (A *Matrix) Rows() int {
	return A.rows
}

// Return the number of columns in the matrix
func (A *Matrix) Columns() int {
	return A.cols
}

// Returns an array of all the values
func (A *Matrix) Values() []float64 {
	tmp := make([]float64, len(A.values))
	copy(tmp, A.values)
	return tmp
}

// Returns a string representation of the matrix
func (A *Matrix) String() string {
	buffer := new(bytes.Buffer)

	for i, elem := range A.values {
		buffer.WriteString(fmt.Sprintf("%.3f ", elem))

		if (i+1)%A.cols == 0 {
			buffer.WriteString("\n")
		}
	}

	return buffer.String()
}

// Returns an exact copy of the matrix
func (A *Matrix) Copy() *Matrix {
	B := Zeros(A.rows, A.cols)
	copy(B.values, A.values)

	return B
}

// Insert the given rows into the matrix, returning a new matrix.
// Passing 0 as the second argument is like making the
// passed rows the first few, whereas passing Rows() is like appending
// the additional rows to the matrix.
//
// Warning: This is an unsafe method to use, it does no boundary
// checking what so ever. If you'd like a safe version
// use: SafeInsertRows
func (A *Matrix) InsertRows(rows *Matrix, afterRow int) *Matrix {
	B := Zeros(A.rows+rows.rows, A.cols)

	// copy rows before inserted rows
	copy(B.values[0:afterRow*B.cols], A.values[0:afterRow*B.cols])
	// insert new rows
	copy(B.values[afterRow*B.cols:afterRow*B.cols+rows.rows*B.cols], rows.values)
	// copy rows after inserted rows
	copy(B.values[afterRow*B.cols+rows.rows*B.cols:], A.values[afterRow*B.cols:])

	return B
}

// Insert the given columns into the matrix, returning a new matrix.
// Passing 0 as the second argument is like making the
// passed columns the first few (on the left), whereas passing Columns() is like appending
// the additional columns to the matrix (on the right).
//
// Warning: This is an unsafe method to use, it does no boundary
// checking what so ever. If you'd like a safe version
// use: SafeInsertColumns
func (A *Matrix) InsertColumns(cols *Matrix, afterCol int) *Matrix {
	B := Zeros(A.rows, A.cols+cols.cols)

	for i := 0; i < A.rows; i++ {
		copy(B.values[i*B.cols:i*B.cols+afterCol], A.values[i*A.cols:i*A.cols+afterCol])
		copy(B.values[i*B.cols+afterCol:i*B.cols+afterCol+cols.cols], cols.values[i*cols.cols:(i+1)*cols.cols])
		copy(B.values[i*B.cols+afterCol+cols.cols:(i+1)*B.cols], A.values[i*A.cols+afterCol:(i+1)*A.cols])
	}

	return B
}

// Give a function, apply its transformation to every element in the matrix.
//
//	A := matrix.Rand(4, 8)
//	A.Apply(func(index int, value float64) float64 {
//		return sigmoid(value)
//	})
func (A *Matrix) Apply(f ApplyFunc) *Matrix {
	for i, v := range A.values {
		A.values[i] = f(i, v)
	}

	return A
}

// Get the element at [row, col].
//
// Warning: This is an unsafe method to use, it does no boundary
// checking what so ever. If you'd like a safe version
// use: SafeGet
func (A *Matrix) Get(row, col int) float64 {
	return A.values[(row-1)*A.cols+col-1]
}

// Set the element at [row, col] to val.
//
// Warning: This is an unsafe method to use, it does no boundary
// checking what so ever. If you'd like a safe version
// use: SafeSet
func (A *Matrix) Set(row, col int, val float64) {

	A.values[(row-1)*A.cols+col-1] = val

}

// Transpose the matrix
func (A *Matrix) Transpose() *Matrix {
	B := Zeros(A.cols, A.rows)

	for i := 1; i <= A.rows; i++ {
		for j := 1; j <= A.cols; j++ {
			B.values[(j-1)*B.cols+i-1] = A.values[(i-1)*A.cols+j-1]
		}
	}

	return B
}

// Add B to the matrix A, produces new matrix
func (A *Matrix) Add(B *Matrix) (*Matrix, error) {
	if !sameSize(A, B) {
		return nil, ErrIncompatibleSizes
	}

	C := Zeros(A.rows, A.cols)

	for i, val := range A.values {
		C.values[i] = val + B.values[i]
	}

	return C, nil
}

// Subtract B from the matrix A, produces a new matrix
func (A *Matrix) Sub(B *Matrix) (*Matrix, error) {
	if !sameSize(A, B) {
		return nil, ErrIncompatibleSizes
	}

	C := Zeros(A.rows, A.cols)

	for i, val := range A.values {
		C.values[i] = val - B.values[i]
	}

	return C, nil
}

// Multiplies 2 matricies with each other.
// Returns a new matrix.
//
// Warning: This is an unsafe method to use, it does no boundary
// checking what so ever. If you'd like a safe version
// use: SafeMul
func (A *Matrix) Mul(B *Matrix) *Matrix {

	C := Zeros(A.rows, B.cols)

	for i := 0; i < C.rows; i++ {
		for j := 0; j < C.cols; j++ {
			sum := float64(0)

			for k := 0; k < A.cols; k++ {
				sum += A.values[i*A.cols+k] * B.values[k*B.cols+j]
			}

			C.values[i*C.rows+j] = sum
		}
	}

	return C
}

// Standard scalar product of 2 matricies.
// Returns a new matrix.
//
// Warning: This is an unsafe method to use, it does no boundary
// checking what so ever. If you'd like a safe version
// use: SafeDot
func (A *Matrix) Dot(B *Matrix) *Matrix {
	C := Zeros(A.rows, A.cols)

	for i, val := range A.values {
		C.values[i] = val * B.values[i]
	}

	return C
}

// Scale the matrix by the factor f
func (A *Matrix) Scale(f float64) *Matrix {
	B := Zeros(A.rows, A.cols)

	for i, val := range A.values {
		B.values[i] = val * f
	}

	return B
}

// Take every element of the matrix to the power of n
func (A *Matrix) Power(n float64) *Matrix {
	B := Zeros(A.rows, A.cols)

	for i, val := range A.values {
		B.values[i] = math.Pow(val, n)
	}

	return B
}

// Add n to all elements in the matrix (in-place)
func (A *Matrix) AddNum(n float64) *Matrix {
	for i := range A.values {
		A.values[i] += n
	}

	return A
}
<|endoftext|>


<commit_before>package mc

import (
	"errors"
	"fmt"
	multiaddr "github.com/multiformats/go-multiaddr"
	"io/ioutil"
	"log"
	"net/http"
	"regexp"
	"strings"
)

var (
	BadAddressSpec = errors.New("Bad NAT address specification")
)

type NATConfig struct {
	Opt  int
	spec string              // address spec when option = NATConfigManual
	addr multiaddr.Multiaddr // public address when option = NATConfigManual
}

const (
	NATConfigNone = iota
	NATConfigAuto
	NATConfigManual
)

var natConfigString = []string{"none", "auto", "manual"}

func (cfg *NATConfig) String() string {
	switch cfg.Opt {
	case NATConfigManual:
		return cfg.spec
	default:
		return natConfigString[cfg.Opt]
	}
}

func (cfg *NATConfig) PublicAddr(base multiaddr.Multiaddr) (multiaddr.Multiaddr, error) {
	if cfg.Opt != NATConfigManual {
		return nil, BadAddressSpec
	}

	if cfg.addr != nil {
		return cfg.addr, nil
	}

	ix := strings.LastIndex(cfg.spec, ":")
	switch {
	case ix < 0:
		addr, err := GetPublicIP()
		if err != nil {
			return nil, err
		}

		port, err := base.ValueForProtocol(multiaddr.P_TCP)
		if err != nil {
			return nil, err
		}

		return cfg.makePublicAddr(addr, port)

	case cfg.spec[:ix] == "*":
		addr, err := GetPublicIP()
		if err != nil {
			return nil, err
		}
		port := cfg.spec[ix+1:]
		return cfg.makePublicAddr(addr, port)

	default:
		addr, port := cfg.spec[:ix], cfg.spec[ix+1:]
		return cfg.makePublicAddr(addr, port)
	}
}

func (cfg *NATConfig) makePublicAddr(addr, port string) (multiaddr.Multiaddr, error) {
	maddr, err := ParseAddress(fmt.Sprintf("/ip4/%s/tcp/%s", addr, port))
	if err != nil {
		return nil, err
	}

	cfg.addr = maddr
	return maddr, nil
}

func (cfg *NATConfig) Clear() {
	cfg.addr = nil
}

var natcfgrx *regexp.Regexp

func init() {
	rx, err := regexp.Compile("([*])|([*]:[0-9]+)|([0-9]{1,3}([.][0-9]{1,3}){3}:[0-9]+)")
	if err != nil {
		log.Fatal(err)
	}
	natcfgrx = rx
}

func NATConfigFromString(str string) (cfg NATConfig, err error) {
	switch str {
	case "none":
		cfg.Opt = NATConfigNone
		return cfg, nil
	case "auto":
		cfg.Opt = NATConfigAuto
		return cfg, nil
	default:
		if !natcfgrx.Match([]byte(str)) {
			return cfg, BadAddressSpec
		}
		cfg.Opt = NATConfigManual
		cfg.spec = str
		return cfg, nil
	}
}

func GetPublicIP() (string, error) {
	res, err := http.Get("http://ifconfig.co/ip")
	if err != nil {
		return "", err
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "", err
	}

	return strings.TrimSpace(string(body)), nil
}
<commit_msg>mc/nat: GetPublicIP: use ifconfig.mediachain.io with fallback to ifconfig.co<commit_after>package mc

import (
	"errors"
	"fmt"
	multiaddr "github.com/multiformats/go-multiaddr"
	"io/ioutil"
	"log"
	"net/http"
	"regexp"
	"strings"
)

var (
	BadAddressSpec = errors.New("Bad NAT address specification")
)

type NATConfig struct {
	Opt  int
	spec string              // address spec when option = NATConfigManual
	addr multiaddr.Multiaddr // public address when option = NATConfigManual
}

const (
	NATConfigNone = iota
	NATConfigAuto
	NATConfigManual
)

var natConfigString = []string{"none", "auto", "manual"}

func (cfg *NATConfig) String() string {
	switch cfg.Opt {
	case NATConfigManual:
		return cfg.spec
	default:
		return natConfigString[cfg.Opt]
	}
}

func (cfg *NATConfig) PublicAddr(base multiaddr.Multiaddr) (multiaddr.Multiaddr, error) {
	if cfg.Opt != NATConfigManual {
		return nil, BadAddressSpec
	}

	if cfg.addr != nil {
		return cfg.addr, nil
	}

	ix := strings.LastIndex(cfg.spec, ":")
	switch {
	case ix < 0:
		addr, err := GetPublicIP()
		if err != nil {
			return nil, err
		}

		port, err := base.ValueForProtocol(multiaddr.P_TCP)
		if err != nil {
			return nil, err
		}

		return cfg.makePublicAddr(addr, port)

	case cfg.spec[:ix] == "*":
		addr, err := GetPublicIP()
		if err != nil {
			return nil, err
		}
		port := cfg.spec[ix+1:]
		return cfg.makePublicAddr(addr, port)

	default:
		addr, port := cfg.spec[:ix], cfg.spec[ix+1:]
		return cfg.makePublicAddr(addr, port)
	}
}

func (cfg *NATConfig) makePublicAddr(addr, port string) (multiaddr.Multiaddr, error) {
	maddr, err := ParseAddress(fmt.Sprintf("/ip4/%s/tcp/%s", addr, port))
	if err != nil {
		return nil, err
	}

	cfg.addr = maddr
	return maddr, nil
}

func (cfg *NATConfig) Clear() {
	cfg.addr = nil
}

var natcfgrx *regexp.Regexp

func init() {
	rx, err := regexp.Compile("([*])|([*]:[0-9]+)|([0-9]{1,3}([.][0-9]{1,3}){3}:[0-9]+)")
	if err != nil {
		log.Fatal(err)
	}
	natcfgrx = rx
}

func NATConfigFromString(str string) (cfg NATConfig, err error) {
	switch str {
	case "none":
		cfg.Opt = NATConfigNone
		return cfg, nil
	case "auto":
		cfg.Opt = NATConfigAuto
		return cfg, nil
	default:
		if !natcfgrx.Match([]byte(str)) {
			return cfg, BadAddressSpec
		}
		cfg.Opt = NATConfigManual
		cfg.spec = str
		return cfg, nil
	}
}

var ifconfigSvc = []string{
	"http://ifconfig.mediachain.io/ip",
	"http://ifconfig.co/ip"}

var IfconfigError = errors.New("ifconfig service error")

func GetPublicIP() (string, error) {
	for _, url := range ifconfigSvc {
		ip, err := doGetPublicIP(url)
		if err != nil {
			log.Printf("Error getting IP from %s: %s", url, err.Error())
			continue
		}
		return ip, nil
	}

	return "", IfconfigError
}

func doGetPublicIP(url string) (string, error) {
	res, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return "", err
	}

	return strings.TrimSpace(string(body)), nil
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"os/signal"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"text/template"
	"time"

	"github.com/citadel/citadel"
	"github.com/citadel/citadel/cluster"
	"github.com/citadel/citadel/scheduler"
	"github.com/ehazlett/interlock"
)

const (
	haproxyTmpl = `# managed by interlock
global
    {{ if .Config.SyslogAddr }}log {{ .Config.SyslogAddr }} local0
    log-send-hostname{{ end }}
    maxconn {{ .Config.MaxConn }}
    pidfile {{ .Config.PidPath }}

defaults
    mode http
    retries 3
    option redispatch
    option httplog
    option dontlognull
    timeout connect {{ .Config.ConnectTimeout }}
    timeout client {{ .Config.ClientTimeout }}
    timeout server {{ .Config.ServerTimeout }}

frontend http-default
    bind *:{{ .Config.Port }}
    monitor-uri /haproxy?monitor
    {{ if .Config.StatsUser }}stats realm Stats
    stats auth {{ .Config.StatsUser }}:{{ .Config.StatsPassword }}{{ end }}
    stats enable
    stats uri /haproxy?stats
    {{ range $host := .Hosts }}acl is_{{ $host.Name }} hdr_end(host) -i {{ $host.Domain }}
    use_backend {{ $host.Name }} if is_{{ $host.Name }}
    {{ end }}
{{ range $host := .Hosts }}backend {{ $host.Name }}
    balance roundrobin
    option httpclose
    option forwardfor
    {{ range $i,$up := $host.Upstreams }}server {{$host.Name}}_{{$i}} {{$up.Addr}} check
    {{ end }}
{{ end }}`
)

type (
	Manager struct {
		mux      sync.Mutex
		config   *interlock.Config
		engines  []*citadel.Engine
		cluster  *cluster.Cluster
		proxyCmd *exec.Cmd
	}
)

func NewManager(cfg *interlock.Config) (*Manager, error) {
	engines := []*citadel.Engine{}
	for _, e := range cfg.InterlockEngines {
		if err := e.Engine.Connect(nil); err != nil {
			return nil, err
		}
		engines = append(engines, e.Engine)
	}
	m := &Manager{
		config:  cfg,
		engines: engines,
	}
	if err := m.init(); err != nil {
		return nil, err
	}
	return m, nil
}

func (m *Manager) init() error {
	c, err := cluster.New(scheduler.NewResourceManager(), m.engines...)
	if err != nil {
		return err
	}
	m.cluster = c
	return nil
}

func (m *Manager) writeConfig(config *interlock.ProxyConfig) error {
	m.mux.Lock()
	defer m.mux.Unlock()
	f, err := os.OpenFile(m.config.ProxyConfigPath, os.O_WRONLY|os.O_TRUNC, 0664)
	if err != nil {
		if !os.IsNotExist(err) {
			return err
		}
		ff, fErr := os.Create(m.config.ProxyConfigPath)
		defer ff.Close()
		if fErr != nil {
			return fErr
		}
		f = ff
	}
	defer f.Close()
	t := template.New("haproxy")
	tmpl, err := t.Parse(haproxyTmpl)
	if err != nil {
		return err
	}
	var c bytes.Buffer
	if err := tmpl.Execute(&c, config); err != nil {
		return err
	}
	_, fErr := f.Write(c.Bytes())
	if fErr != nil {
		return fErr
	}
	f.Sync()
	return nil
}

func (m *Manager) GenerateProxyConfig(isKillEvent bool) (*interlock.ProxyConfig, error) {
	containers, err := m.cluster.ListContainers()
	if err != nil {
		return nil, err
	}
	var hosts []*interlock.Host
	proxyUpstreams := map[string][]*interlock.Upstream{}
	for _, cnt := range containers {
		if cnt.Image.Domainname == "" {
			continue
		}
		cntId := cnt.ID[:12]
		// load interlock data
		env := cnt.Image.Environment
		interlockData := &interlock.InterlockData{}
		if key, ok := env["INTERLOCK_DATA"]; ok {
			b := bytes.NewBufferString(key)
			if err := json.NewDecoder(b).Decode(&interlockData); err != nil {
				logger.Warnf("%s: unable to parse interlock data: %s", cntId, err)
			}
		}
		hostname := cnt.Image.Hostname
		domain := cnt.Image.Domainname
		if hostname != domain && hostname != "" {
			domain = fmt.Sprintf("%s.%s", hostname, domain)
		}
		hostAddrUrl, err := url.Parse(cnt.Engine.Addr)
		if err != nil {
			logger.Warnf("%s: unable to parse engine addr: %s", cntId, err)
			continue
		}
		host := hostAddrUrl.Host
		hostParts := strings.Split(hostAddrUrl.Host, ":")
		if len(hostParts) != 1 {
			host = hostParts[0]
		}
		if len(cnt.Ports) == 0 {
			logger.Warnf("%s: no ports exposed", cntId)
			continue
		}
		portDef := cnt.Ports[0]
		addr := fmt.Sprintf("%s:%d", host, portDef.Port)
		if interlockData.Port != 0 {
			for _, p := range cnt.Ports {
				if p.ContainerPort == interlockData.Port {
					addr = fmt.Sprintf("%s:%d", host, p.Port)
				}
			}
		}
		up := &interlock.Upstream{
			Addr: addr,
		}
		for _, alias := range interlockData.AliasDomains {
			logger.Infof("adding alias %s for %s", alias, cntId)
			proxyUpstreams[alias] = append(proxyUpstreams[alias], up)
		}
		proxyUpstreams[domain] = append(proxyUpstreams[domain], up)
		if !isKillEvent && interlockData.Warm {
			logger.Infof("warming %s: %s", cntId, addr)
			http.Get(fmt.Sprintf("http://%s", addr))
		}

	}
	for k, v := range proxyUpstreams {
		name := strings.Replace(k, ".", "_", -1)
		host := &interlock.Host{
			Name:      name,
			Domain:    k,
			Upstreams: v,
		}
		logger.Infof("adding host name=%s domain=%s", host.Name, host.Domain)
		hosts = append(hosts, host)
	}
	// generate config
	cfg := &interlock.ProxyConfig{
		Hosts:  hosts,
		Config: m.config,
	}
	return cfg, nil
}

func (m *Manager) UpdateConfig(e *citadel.Event) error {
	isKillEvent := false
	if e != nil && e.Type == "kill" {
		isKillEvent = true
	}
	cfg, err := m.GenerateProxyConfig(isKillEvent)
	if err != nil {
		return err
	}
	if err := m.writeConfig(cfg); err != nil {
		return err
	}
	return nil
}

func (m *Manager) getProxyPid() (int, error) {
	f, err := ioutil.ReadFile(m.config.PidPath)
	if err != nil {
		return -1, err
	}
	buf := bytes.NewBuffer(f)
	p := buf.String()
	p = strings.TrimSpace(p)
	pid, err := strconv.Atoi(p)
	if err != nil {
		return -1, err
	}
	return pid, nil
}

func (m *Manager) Reload() error {
	args := []string{"-D", "-f", m.config.ProxyConfigPath, "-p", m.config.PidPath, "-sf"}
	if m.proxyCmd != nil {
		p, err := m.getProxyPid()
		if err != nil {
			logger.Error(err)
		}
		pid := strconv.Itoa(p)
		args = append(args, pid)
	}
	//cmd := exec.Command("haproxy", "-f", m.config.ProxyConfigPath, "-p", "/var/run/haproxy.pid", pidKill)
	cmd := exec.Command("haproxy", args...)
	if err := cmd.Run(); err != nil {
		return err
	}
	// kill old process
	//if m.proxyCmd != nil {
	//	syscall.Kill(m.proxyCmd.Process.Pid, syscall.SIGKILL)
	//}
	m.proxyCmd = cmd
	logger.Info("reloaded proxy")
	return nil
}

func (m *Manager) Run() error {
	if err := m.UpdateConfig(nil); err != nil {
		return err
	}
	if err := m.cluster.Events(&EventHandler{Manager: m}); err != nil {
		return err
	}
	m.Reload()
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt)
	signal.Notify(ch, syscall.SIGTERM)
	go func() {
		<-ch
		if m.proxyCmd != nil {
			pid, err := m.getProxyPid()
			if err != nil {
				logger.Fatal(err)
			}
			syscall.Kill(pid, syscall.SIGTERM)
		}
		os.Exit(1)
	}()

	for {
		time.Sleep(1 * time.Second)
	}
}
<commit_msg>added auto refresh for stats<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"os/signal"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"text/template"
	"time"

	"github.com/citadel/citadel"
	"github.com/citadel/citadel/cluster"
	"github.com/citadel/citadel/scheduler"
	"github.com/ehazlett/interlock"
)

const (
	haproxyTmpl = `# managed by interlock
global
    {{ if .Config.SyslogAddr }}log {{ .Config.SyslogAddr }} local0
    log-send-hostname{{ end }}
    maxconn {{ .Config.MaxConn }}
    pidfile {{ .Config.PidPath }}

defaults
    mode http
    retries 3
    option redispatch
    option httplog
    option dontlognull
    timeout connect {{ .Config.ConnectTimeout }}
    timeout client {{ .Config.ClientTimeout }}
    timeout server {{ .Config.ServerTimeout }}

frontend http-default
    bind *:{{ .Config.Port }}
    monitor-uri /haproxy?monitor
    {{ if .Config.StatsUser }}stats realm Stats
    stats auth {{ .Config.StatsUser }}:{{ .Config.StatsPassword }}{{ end }}
    stats enable
    stats uri /haproxy?stats
    stats refresh 5s
    {{ range $host := .Hosts }}acl is_{{ $host.Name }} hdr_end(host) -i {{ $host.Domain }}
    use_backend {{ $host.Name }} if is_{{ $host.Name }}
    {{ end }}
{{ range $host := .Hosts }}backend {{ $host.Name }}
    balance roundrobin
    option httpclose
    option forwardfor
    {{ range $i,$up := $host.Upstreams }}server {{$host.Name}}_{{$i}} {{$up.Addr}} check
    {{ end }}
{{ end }}`
)

type (
	Manager struct {
		mux      sync.Mutex
		config   *interlock.Config
		engines  []*citadel.Engine
		cluster  *cluster.Cluster
		proxyCmd *exec.Cmd
	}
)

func NewManager(cfg *interlock.Config) (*Manager, error) {
	engines := []*citadel.Engine{}
	for _, e := range cfg.InterlockEngines {
		if err := e.Engine.Connect(nil); err != nil {
			return nil, err
		}
		engines = append(engines, e.Engine)
	}
	m := &Manager{
		config:  cfg,
		engines: engines,
	}
	if err := m.init(); err != nil {
		return nil, err
	}
	return m, nil
}

func (m *Manager) init() error {
	c, err := cluster.New(scheduler.NewResourceManager(), m.engines...)
	if err != nil {
		return err
	}
	m.cluster = c
	return nil
}

func (m *Manager) writeConfig(config *interlock.ProxyConfig) error {
	m.mux.Lock()
	defer m.mux.Unlock()
	f, err := os.OpenFile(m.config.ProxyConfigPath, os.O_WRONLY|os.O_TRUNC, 0664)
	if err != nil {
		if !os.IsNotExist(err) {
			return err
		}
		ff, fErr := os.Create(m.config.ProxyConfigPath)
		defer ff.Close()
		if fErr != nil {
			return fErr
		}
		f = ff
	}
	defer f.Close()
	t := template.New("haproxy")
	tmpl, err := t.Parse(haproxyTmpl)
	if err != nil {
		return err
	}
	var c bytes.Buffer
	if err := tmpl.Execute(&c, config); err != nil {
		return err
	}
	_, fErr := f.Write(c.Bytes())
	if fErr != nil {
		return fErr
	}
	f.Sync()
	return nil
}

func (m *Manager) GenerateProxyConfig(isKillEvent bool) (*interlock.ProxyConfig, error) {
	containers, err := m.cluster.ListContainers()
	if err != nil {
		return nil, err
	}
	var hosts []*interlock.Host
	proxyUpstreams := map[string][]*interlock.Upstream{}
	for _, cnt := range containers {
		if cnt.Image.Domainname == "" {
			continue
		}
		cntId := cnt.ID[:12]
		// load interlock data
		env := cnt.Image.Environment
		interlockData := &interlock.InterlockData{}
		if key, ok := env["INTERLOCK_DATA"]; ok {
			b := bytes.NewBufferString(key)
			if err := json.NewDecoder(b).Decode(&interlockData); err != nil {
				logger.Warnf("%s: unable to parse interlock data: %s", cntId, err)
			}
		}
		hostname := cnt.Image.Hostname
		domain := cnt.Image.Domainname
		if hostname != domain && hostname != "" {
			domain = fmt.Sprintf("%s.%s", hostname, domain)
		}
		hostAddrUrl, err := url.Parse(cnt.Engine.Addr)
		if err != nil {
			logger.Warnf("%s: unable to parse engine addr: %s", cntId, err)
			continue
		}
		host := hostAddrUrl.Host
		hostParts := strings.Split(hostAddrUrl.Host, ":")
		if len(hostParts) != 1 {
			host = hostParts[0]
		}
		if len(cnt.Ports) == 0 {
			logger.Warnf("%s: no ports exposed", cntId)
			continue
		}
		portDef := cnt.Ports[0]
		addr := fmt.Sprintf("%s:%d", host, portDef.Port)
		if interlockData.Port != 0 {
			for _, p := range cnt.Ports {
				if p.ContainerPort == interlockData.Port {
					addr = fmt.Sprintf("%s:%d", host, p.Port)
				}
			}
		}
		up := &interlock.Upstream{
			Addr: addr,
		}
		for _, alias := range interlockData.AliasDomains {
			logger.Infof("adding alias %s for %s", alias, cntId)
			proxyUpstreams[alias] = append(proxyUpstreams[alias], up)
		}
		proxyUpstreams[domain] = append(proxyUpstreams[domain], up)
		if !isKillEvent && interlockData.Warm {
			logger.Infof("warming %s: %s", cntId, addr)
			http.Get(fmt.Sprintf("http://%s", addr))
		}

	}
	for k, v := range proxyUpstreams {
		name := strings.Replace(k, ".", "_", -1)
		host := &interlock.Host{
			Name:      name,
			Domain:    k,
			Upstreams: v,
		}
		logger.Infof("adding host name=%s domain=%s", host.Name, host.Domain)
		hosts = append(hosts, host)
	}
	// generate config
	cfg := &interlock.ProxyConfig{
		Hosts:  hosts,
		Config: m.config,
	}
	return cfg, nil
}

func (m *Manager) UpdateConfig(e *citadel.Event) error {
	isKillEvent := false
	if e != nil && e.Type == "kill" {
		isKillEvent = true
	}
	cfg, err := m.GenerateProxyConfig(isKillEvent)
	if err != nil {
		return err
	}
	if err := m.writeConfig(cfg); err != nil {
		return err
	}
	return nil
}

func (m *Manager) getProxyPid() (int, error) {
	f, err := ioutil.ReadFile(m.config.PidPath)
	if err != nil {
		return -1, err
	}
	buf := bytes.NewBuffer(f)
	p := buf.String()
	p = strings.TrimSpace(p)
	pid, err := strconv.Atoi(p)
	if err != nil {
		return -1, err
	}
	return pid, nil
}

func (m *Manager) Reload() error {
	args := []string{"-D", "-f", m.config.ProxyConfigPath, "-p", m.config.PidPath, "-sf"}
	if m.proxyCmd != nil {
		p, err := m.getProxyPid()
		if err != nil {
			logger.Error(err)
		}
		pid := strconv.Itoa(p)
		args = append(args, pid)
	}
	//cmd := exec.Command("haproxy", "-f", m.config.ProxyConfigPath, "-p", "/var/run/haproxy.pid", pidKill)
	cmd := exec.Command("haproxy", args...)
	if err := cmd.Run(); err != nil {
		return err
	}
	// kill old process
	//if m.proxyCmd != nil {
	//	syscall.Kill(m.proxyCmd.Process.Pid, syscall.SIGKILL)
	//}
	m.proxyCmd = cmd
	logger.Info("reloaded proxy")
	return nil
}

func (m *Manager) Run() error {
	if err := m.UpdateConfig(nil); err != nil {
		return err
	}
	if err := m.cluster.Events(&EventHandler{Manager: m}); err != nil {
		return err
	}
	m.Reload()
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt)
	signal.Notify(ch, syscall.SIGTERM)
	go func() {
		<-ch
		if m.proxyCmd != nil {
			pid, err := m.getProxyPid()
			if err != nil {
				logger.Fatal(err)
			}
			syscall.Kill(pid, syscall.SIGTERM)
		}
		os.Exit(1)
	}()

	for {
		time.Sleep(1 * time.Second)
	}
}
<|endoftext|>


<commit_before>package main

import "fmt"

const (
	a = iota // 0
	b = iota // 1
	c = iota //3
)

func main()  {
	fmt.Println(a)
	fmt.Println(b)
	fmt.Println(c)
}<commit_msg>golangTraining iota doc<commit_after>package main

import "fmt"

const (
	a = iota // 0
	b = iota // 1
	c = iota //3
)

/**
* https://golang.org/ref/spec#Iota
* Within a constant declaration, the predeclared identifier iota represents successive untyped integer constants.
* It is reset to 0 whenever the reserved word const appears in the source and increments after each ConstSpec.
* It can be used to construct a set of related constants:
*/

func main()  {
	fmt.Println(a)
	fmt.Println(b)
	fmt.Println(c)
}<|endoftext|>


<commit_before>package checkerlution

import (
	"fmt"
	"github.com/couchbaselabs/logg"
	cbot "github.com/tleyden/checkers-bot"
	ng "github.com/tleyden/neurgo"
)

type CheckerlutionScape struct {
	team                  cbot.TeamType
	syncGatewayUrl        string
	feedType              cbot.FeedType
	randomDelayBeforeMove int
	fitnessHistory        map[string]float64
}

func (scape *CheckerlutionScape) FitnessAgainst(cortex *ng.Cortex, opponentCortex *ng.Cortex) (fitness float64) {

	if cortex == opponentCortex {
		logg.LogPanic("Cannot calculate fitnesss between cortex %p and itself %p", cortex, opponentCortex)
	}

	savedFitness, isPresent := scape.lookupFitnessHistory(cortex, opponentCortex)
	if isPresent {
		fitness = savedFitness
		logg.LogTo("CHECKERLUTION_SCAPE", "Fitness from history (us %v): %v", cortex.NodeId.UUID, fitness)
		return
	}

	cortex.Init()
	opponentCortex.Init()

	// setup checkers game for cortex
	thinker := &Checkerlution{}
	thinker.SetMode(TRAINING_MODE)
	thinker.StartWithCortex(cortex, scape.team)
	game := cbot.NewGame(scape.team, thinker)
	game.SetServerUrl(scape.syncGatewayUrl)
	game.SetFeedType(scape.feedType)
	game.SetDelayBeforeMove(scape.randomDelayBeforeMove)

	// setup checkers game for opponent
	thinkerOpponent := &Checkerlution{}
	thinkerOpponent.SetMode(TRAINING_MODE)
	var opponentTeam cbot.TeamType // TODO: why can't just use := syntax here?
	opponentTeam = cbot.RED_TEAM
	if scape.team == cbot.RED_TEAM {
		opponentTeam = cbot.BLUE_TEAM
	}
	thinkerOpponent.StartWithCortex(opponentCortex, opponentTeam)
	gameOpponent := cbot.NewGame(opponentTeam, thinkerOpponent)
	gameOpponent.SetServerUrl(scape.syncGatewayUrl)
	gameOpponent.SetFeedType(scape.feedType)
	gameOpponent.SetDelayBeforeMove(scape.randomDelayBeforeMove)

	// run both game loops and wait for both to finish
	logg.LogTo("CHECKERLUTION_SCAPE", "Started game: %v vs %v", cortex.NodeId.UUID, opponentCortex.NodeId.UUID)
	games := []*cbot.Game{game, gameOpponent}
	scape.runGameLoops(games)
	logg.LogTo("CHECKERLUTION_SCAPE", "Game finished after %v turns", game.Turn())

	fitness = thinker.latestFitnessScore
	fitnessOpponent := thinkerOpponent.latestFitnessScore

	logg.LogTo("CHECKERLUTION_SCAPE", "Fitness (us %v): %v", cortex.NodeId.UUID, fitness)
	logg.LogTo("CHECKERLUTION_SCAPE", "Fitness (opponent %v): %v", opponentCortex.NodeId.UUID, fitnessOpponent)

	scape.recordFitness(cortex, fitness, opponentCortex, fitnessOpponent)

	// wait until the game number increments, otherwise on the
	// next callback to this method, we'll jump into a game which
	// is already over.
	logg.LogTo("CHECKERLUTION_SCAPE", "Wait For Next Game ..")
	game.WaitForNextGame()
	gameOpponent.WaitForNextGame()
	logg.LogTo("CHECKERLUTION_SCAPE", "Done waiting For Next Game ..")

	cortex.Shutdown()
	opponentCortex.Shutdown()

	return
}

func (scape *CheckerlutionScape) Fitness(cortex *ng.Cortex) (fitness float64) {

	logg.LogTo("CHECKERLUTION_SCAPE", "CheckerlutionScape Fitness() called, create random opponent")

	// create an opponent
	thinker := &Checkerlution{}
	thinker.CreateNeurgoCortex()
	thinker.Cortex()

	return scape.FitnessAgainst(cortex, thinker.Cortex())

}

func (scape *CheckerlutionScape) runGameLoops(games []*cbot.Game) {

	resultChannel := make(chan bool)
	runGameLoop := func(game *cbot.Game, result chan bool) {
		game.GameLoop()
		result <- true
	}
	for _, game := range games {
		go runGameLoop(game, resultChannel)
	}
	for _, _ = range games {
		<-resultChannel
	}

}

func (scape *CheckerlutionScape) recordFitness(cortex *ng.Cortex, fitness float64, opponentCortex *ng.Cortex, fitnessOpponent float64) {

	if scape.fitnessHistory == nil {
		scape.fitnessHistory = make(map[string]float64)
	}

	// record the fitness score of us vs them
	key := fmt.Sprintf("%v-%v", cortex.NodeId.UUID, opponentCortex.NodeId.UUID)
	scape.fitnessHistory[key] = fitness

	// also record the reverse direction - them vs us fitness
	key = fmt.Sprintf("%v-%v", opponentCortex.NodeId.UUID, cortex.NodeId.UUID)
	scape.fitnessHistory[key] = fitnessOpponent

}

func (scape *CheckerlutionScape) lookupFitnessHistory(cortex *ng.Cortex, opponentCortex *ng.Cortex) (fitness float64, isPresent bool) {

	key := fmt.Sprintf("%v-%v", cortex.NodeId.UUID, opponentCortex.NodeId.UUID)
	fitness, isPresent = scape.fitnessHistory[key]
	return

}

func (scape *CheckerlutionScape) SetSyncGatewayUrl(syncGatewayUrl string) {
	scape.syncGatewayUrl = syncGatewayUrl
}

func (scape *CheckerlutionScape) SetTeam(team cbot.TeamType) {
	scape.team = team
}

func (scape *CheckerlutionScape) SetFeedType(feedType cbot.FeedType) {
	scape.feedType = feedType
}

func (scape *CheckerlutionScape) SetRandomDelayBeforeMove(delay int) {
	scape.randomDelayBeforeMove = delay
}
<commit_msg>realized that recording the reverse direction score is not fair and gives unfair advantage to "trivial wins"<commit_after>package checkerlution

import (
	"fmt"
	"github.com/couchbaselabs/logg"
	cbot "github.com/tleyden/checkers-bot"
	ng "github.com/tleyden/neurgo"
)

type CheckerlutionScape struct {
	team                  cbot.TeamType
	syncGatewayUrl        string
	feedType              cbot.FeedType
	randomDelayBeforeMove int
	fitnessHistory        map[string]float64
}

func (scape *CheckerlutionScape) FitnessAgainst(cortex *ng.Cortex, opponentCortex *ng.Cortex) (fitness float64) {

	if cortex == opponentCortex {
		logg.LogPanic("Cannot calculate fitnesss between cortex %p and itself %p", cortex, opponentCortex)
	}

	savedFitness, isPresent := scape.lookupFitnessHistory(cortex, opponentCortex)
	if isPresent {
		fitness = savedFitness
		logg.LogTo("CHECKERLUTION_SCAPE", "Fitness from history (us %v): %v", cortex.NodeId.UUID, fitness)
		return
	}

	cortex.Init()
	opponentCortex.Init()

	// setup checkers game for cortex
	thinker := &Checkerlution{}
	thinker.SetMode(TRAINING_MODE)
	thinker.StartWithCortex(cortex, scape.team)
	game := cbot.NewGame(scape.team, thinker)
	game.SetServerUrl(scape.syncGatewayUrl)
	game.SetFeedType(scape.feedType)
	game.SetDelayBeforeMove(scape.randomDelayBeforeMove)

	// setup checkers game for opponent
	thinkerOpponent := &Checkerlution{}
	thinkerOpponent.SetMode(TRAINING_MODE)
	var opponentTeam cbot.TeamType // TODO: why can't just use := syntax here?
	opponentTeam = cbot.RED_TEAM
	if scape.team == cbot.RED_TEAM {
		opponentTeam = cbot.BLUE_TEAM
	}
	thinkerOpponent.StartWithCortex(opponentCortex, opponentTeam)
	gameOpponent := cbot.NewGame(opponentTeam, thinkerOpponent)
	gameOpponent.SetServerUrl(scape.syncGatewayUrl)
	gameOpponent.SetFeedType(scape.feedType)
	gameOpponent.SetDelayBeforeMove(scape.randomDelayBeforeMove)

	// run both game loops and wait for both to finish
	logg.LogTo("CHECKERLUTION_SCAPE", "Started game: %v vs %v", cortex.NodeId.UUID, opponentCortex.NodeId.UUID)
	games := []*cbot.Game{game, gameOpponent}
	scape.runGameLoops(games)
	logg.LogTo("CHECKERLUTION_SCAPE", "Game finished after %v turns", game.Turn())

	fitness = thinker.latestFitnessScore
	fitnessOpponent := thinkerOpponent.latestFitnessScore

	logg.LogTo("CHECKERLUTION_SCAPE", "Fitness (us %v): %v", cortex.NodeId.UUID, fitness)
	logg.LogTo("CHECKERLUTION_SCAPE", "Fitness (opponent %v): %v", opponentCortex.NodeId.UUID, fitnessOpponent)

	scape.recordFitness(cortex, fitness, opponentCortex, fitnessOpponent)

	// wait until the game number increments, otherwise on the
	// next callback to this method, we'll jump into a game which
	// is already over.
	logg.LogTo("CHECKERLUTION_SCAPE", "Wait For Next Game ..")
	game.WaitForNextGame()
	gameOpponent.WaitForNextGame()
	logg.LogTo("CHECKERLUTION_SCAPE", "Done waiting For Next Game ..")

	cortex.Shutdown()
	opponentCortex.Shutdown()

	return
}

func (scape *CheckerlutionScape) Fitness(cortex *ng.Cortex) (fitness float64) {

	logg.LogTo("CHECKERLUTION_SCAPE", "CheckerlutionScape Fitness() called, create random opponent")

	// create an opponent
	thinker := &Checkerlution{}
	thinker.CreateNeurgoCortex()
	thinker.Cortex()

	return scape.FitnessAgainst(cortex, thinker.Cortex())

}

func (scape *CheckerlutionScape) runGameLoops(games []*cbot.Game) {

	resultChannel := make(chan bool)
	runGameLoop := func(game *cbot.Game, result chan bool) {
		game.GameLoop()
		result <- true
	}
	for _, game := range games {
		go runGameLoop(game, resultChannel)
	}
	for _, _ = range games {
		<-resultChannel
	}

}

func (scape *CheckerlutionScape) recordFitness(cortex *ng.Cortex, fitness float64, opponentCortex *ng.Cortex, fitnessOpponent float64) {

	if scape.fitnessHistory == nil {
		scape.fitnessHistory = make(map[string]float64)
	}

	// record the fitness score of us vs them
	key := fmt.Sprintf("%v-%v", cortex.NodeId.UUID, opponentCortex.NodeId.UUID)
	scape.fitnessHistory[key] = fitness

}

func (scape *CheckerlutionScape) lookupFitnessHistory(cortex *ng.Cortex, opponentCortex *ng.Cortex) (fitness float64, isPresent bool) {

	key := fmt.Sprintf("%v-%v", cortex.NodeId.UUID, opponentCortex.NodeId.UUID)
	fitness, isPresent = scape.fitnessHistory[key]
	return

}

func (scape *CheckerlutionScape) SetSyncGatewayUrl(syncGatewayUrl string) {
	scape.syncGatewayUrl = syncGatewayUrl
}

func (scape *CheckerlutionScape) SetTeam(team cbot.TeamType) {
	scape.team = team
}

func (scape *CheckerlutionScape) SetFeedType(feedType cbot.FeedType) {
	scape.feedType = feedType
}

func (scape *CheckerlutionScape) SetRandomDelayBeforeMove(delay int) {
	scape.randomDelayBeforeMove = delay
}
<|endoftext|>