<commit_before>package api

import "testing"

type People struct {
	Hello string `json:"hello"`
	Name  string `json:"name"`
	Age   string `json:"age"`
}

func TestPing(t *testing.T) {
	client, err := NewDClient("http://42.96.195.83:4213", "1.13", 20)

	if err != nil {
		t.Fatal(err.Error())
	}

	str, err := client.Ping()

	if err != nil {
		t.Fatal(err.Error())
	}

	t.Log(str)
}

func TestListImages(t *testing.T) {
	client, err := NewDClient("http://42.96.195.83:4213", "1.12", 20)

	if err != nil {
		t.Fatal(err.Error())
	}

	var images []ListImagesAPI_Resp
	err = client.ListImages(ListImagesAPI_Query {
		All : false,
	}, &images)

	if err != nil {
		t.Error(err)
		return
	}

	t.Log(images)
}

func TestInspectImages(t *testing.T) {
	var image InspectImageAPI_Resp
	client, err := NewDClient("http://222.26.224.50:4213", "1.13", 20)

	if err != nil {
		t.Fatal(err.Error())
	}
	err = client.InspectImage("ubuntu", &image)
	if err != nil {
		t.Error(err)
		return
	}

	t.Log(image)
}
<commit_msg>change ip<commit_after>package api

import "testing"

type People struct {
	Hello string `json:"hello"`
	Name  string `json:"name"`
	Age   string `json:"age"`
}

func TestPing(t *testing.T) {
	client, err := NewDClient("http://42.96.195.83:4213", "1.13", 20)

	if err != nil {
		t.Fatal(err.Error())
	}

	str, err := client.Ping()

	if err != nil {
		t.Fatal(err.Error())
	}

	t.Log(str)
}

func TestListImages(t *testing.T) {
	client, err := NewDClient("http://42.96.195.83:4213", "1.12", 20)

	if err != nil {
		t.Fatal(err.Error())
	}

	var images []ListImagesAPI_Resp
	err = client.ListImages(ListImagesAPI_Query {
		All : false,
	}, &images)

	if err != nil {
		t.Error(err)
		return
	}

	t.Log(images)
}

func TestInspectImages(t *testing.T) {
	var image InspectImageAPI_Resp
	client, err := NewDClient("http://42.96.195.83:4213", "1.13", 20)

	if err != nil {
		t.Fatal(err.Error())
	}
	err = client.InspectImage("ubuntu", &image)
	if err != nil {
		t.Error(err)
		return
	}

	t.Log(image)
}
<|endoftext|>


<commit_before>package characteristic

import (
	"encoding/base64"
	"net"
)

type Bytes struct {
	*String
}

func NewBytes(typ string) *Bytes {
	s := NewString(typ)
	s.Format = FormatTLV8

	return &Bytes{s}
}

func (bs *Bytes) SetValue(b []byte) {
	bs.String.SetValue(base64FromBytes(b))
}

func (bs *Bytes) GetValue() []byte {
	str := bs.String.GetValue()
	if b, err := base64.StdEncoding.DecodeString(str); err != nil {
		return []byte{}
	} else {
		return b
	}
}

// OnValueRemoteUpdate calls fn when the value was updated by a client.
func (bs *Bytes) OnValueRemoteUpdate(fn func([]byte)) {
	bs.OnValueUpdateFromConn(func(conn net.Conn, c *Characteristic, new, old interface{}) {
		fn(new.([]byte))
	})
}

func base64FromBytes(b []byte) string {
	return base64.StdEncoding.EncodeToString(b)
}
<commit_msg>Add callback when bytes characteristic changed<commit_after>package characteristic

import (
	"encoding/base64"
	"net"
)

type Bytes struct {
	*String
}

func NewBytes(typ string) *Bytes {
	s := NewString(typ)
	s.Format = FormatTLV8

	return &Bytes{s}
}

func (bs *Bytes) SetValue(b []byte) {
	bs.String.SetValue(base64FromBytes(b))
}

func (bs *Bytes) GetValue() []byte {
	str := bs.String.GetValue()
	if b, err := base64.StdEncoding.DecodeString(str); err != nil {
		return []byte{}
	} else {
		return b
	}
}

func (bs *Bytes) OnValueRemoteUpdate(fn func([]byte)) {
	bs.OnValueUpdateFromConn(func(conn net.Conn, c *Characteristic, new, old interface{}) {
		fn(bs.GetValue())
	})
}

func base64FromBytes(b []byte) string {
	return base64.StdEncoding.EncodeToString(b)
}
<|endoftext|>


<commit_before>package mocks

import (
	"github.com/evandigby/rtb"
)

type MockPacer struct {
	canBidResults map[int64]bool
}

func (p *MockPacer) CanBid(account int64) bool {
	return p.canBidResults[account]
}

func NewMockPacer(canBidResults map[int64]bool) rtb.Pacer {
	p := new(MockPacer)

	p.canBidResults = canBidResults

	return p
}
<commit_msg>fixed test<commit_after>package mocks

import (
	"github.com/evandigby/rtb"
)

type MockPacer struct {
	canBidResults map[int64]bool
}

func (p *MockPacer) CanBid(campaign rtb.Campaign) bool {
	return p.canBidResults[campaign.Id()]
}

func NewMockPacer(canBidResults map[int64]bool) rtb.Pacer {
	p := new(MockPacer)

	p.canBidResults = canBidResults

	return p
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestStubEndpoint(t *testing.T) {
	body := new(bytes.Buffer)
	encoder := json.NewEncoder(body)
	handler := NewStubHandler()
	ts := httptest.NewServer(handler)
	stub := Stub{Method: "GET", Path: "/foo", Body: `{"foo":"bar"}`}
	encoder.Encode(stub)
	resp, err := http.Post(ts.URL+"/stub", "text/json", body)
	if err != nil {
		t.Error(err)
	}

	if resp.StatusCode != 200 {
		t.Errorf("Status was incorrect, expected 200, got: %v", resp.Status)
	}

	resp.Body.Close()

	body.Reset()
	resp, err = http.Get(ts.URL + "/foo")
	if err != nil {
		t.Error(err)
	}

	if resp.StatusCode != 200 {
		t.Errorf("Status was incorrect, expected 200, got: %v", resp.Status)
	}

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Error(err)
	}

	if string(respBody) != `{"foo":"bar"}` {
		t.Errorf("Unexpected response body: %s", string(respBody))
	}
}
<commit_msg>Refactor tests to extract HTTP assertions<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"
)

func mustEncodeStub(t *testing.T, stub Stub) (buf *bytes.Buffer) {
	buf = new(bytes.Buffer)
	encoder := json.NewEncoder(buf)
	if err := encoder.Encode(stub); err != nil {
		t.Fatalf("Unable to JSON encode: %#v", stub)
	}
	return
}

func mustPost(t *testing.T, url string, body io.Reader) {
	resp, err := http.Post(url, "application/json", body)
	if err != nil {
		t.Fatalf("Unable to POST: %v", err)
	}

	if resp.StatusCode != 200 {
		t.Fatalf("Post failure - Status was incorrect, expected 200, got: %v", resp.Status)
	}

	err = resp.Body.Close()
	if err != nil {
		t.Fatalf("Closing response body failed: %v", err)
	}
}

func mustGet(t *testing.T, url string) (resp *http.Response) {
	var err error
	resp, err = http.Get(url)
	if err != nil {
		t.Fatal(err)
	}

	if resp.StatusCode != 200 {
		t.Fatalf("Status was incorrect, expected 200, got: %v", resp.Status)
	}

	return
}

func TestStubEndpoint(t *testing.T) {
	handler := NewStubHandler()
	ts := httptest.NewServer(handler)

	stub := Stub{Method: "GET", Path: "/foo", Body: `{"foo":"bar"}`}
	postBody := mustEncodeStub(t, stub)
	mustPost(t, ts.URL+"/stub", postBody)

	resp := mustGet(t, ts.URL+"/foo")

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Error(err)
	}

	if string(respBody) != `{"foo":"bar"}` {
		t.Errorf("Unexpected response body: %s", string(respBody))
	}
}
<|endoftext|>


<commit_before>// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package info

import (
	"fmt"
	"net/http"

	"github.com/gorilla/rpc/v2"

	"github.com/ava-labs/avalanchego/chains"
	"github.com/ava-labs/avalanchego/genesis"
	"github.com/ava-labs/avalanchego/ids"
	"github.com/ava-labs/avalanchego/network"
	"github.com/ava-labs/avalanchego/snow/engine/common"
	"github.com/ava-labs/avalanchego/utils/constants"
	"github.com/ava-labs/avalanchego/utils/json"
	"github.com/ava-labs/avalanchego/utils/logging"
	"github.com/ava-labs/avalanchego/version"
)

// Info is the API service for unprivileged info on a node
type Info struct {
	version      version.Version
	nodeID       ids.ShortID
	networkID    uint32
	log          logging.Logger
	networking   network.Network
	chainManager chains.Manager
	txFee        uint64
}

// NewService returns a new admin API service
func NewService(log logging.Logger, version version.Version, nodeID ids.ShortID, networkID uint32, chainManager chains.Manager, peers network.Network, txFee uint64) (*common.HTTPHandler, error) {
	newServer := rpc.NewServer()
	codec := json.NewCodec()
	newServer.RegisterCodec(codec, "application/json")
	newServer.RegisterCodec(codec, "application/json;charset=UTF-8")
	if err := newServer.RegisterService(&Info{
		version:      version,
		nodeID:       nodeID,
		networkID:    networkID,
		log:          log,
		chainManager: chainManager,
		networking:   peers,
		txFee:        txFee,
	}, "info"); err != nil {
		return nil, err
	}
	return &common.HTTPHandler{Handler: newServer}, nil
}

// GetNodeVersionReply are the results from calling GetNodeVersion
type GetNodeVersionReply struct {
	Version string `json:"version"`
}

// GetNodeVersion returns the version this node is running
func (service *Info) GetNodeVersion(_ *http.Request, _ *struct{}, reply *GetNodeVersionReply) error {
	service.log.Info("Info: GetNodeVersion called")

	reply.Version = service.version.String()
	return nil
}

// GetNodeIDReply are the results from calling GetNodeID
type GetNodeIDReply struct {
	NodeID string `json:"nodeID"`
}

// GetNodeID returns the node ID of this node
func (service *Info) GetNodeID(_ *http.Request, _ *struct{}, reply *GetNodeIDReply) error {
	service.log.Info("Info: GetNodeID called")

	reply.NodeID = service.nodeID.PrefixedString(constants.NodeIDPrefix)
	return nil
}

// GetNetworkIDReply are the results from calling GetNetworkID
type GetNetworkIDReply struct {
	NetworkID json.Uint32 `json:"networkID"`
}

// GetNetworkID returns the network ID this node is running on
func (service *Info) GetNetworkID(_ *http.Request, _ *struct{}, reply *GetNetworkIDReply) error {
	service.log.Info("Info: GetNetworkID called")

	reply.NetworkID = json.Uint32(service.networkID)
	return nil
}

// GetNetworkNameReply is the result from calling GetNetworkName
type GetNetworkNameReply struct {
	NetworkName string `json:"networkName"`
}

// GetNetworkName returns the network name this node is running on
func (service *Info) GetNetworkName(_ *http.Request, _ *struct{}, reply *GetNetworkNameReply) error {
	service.log.Info("Info: GetNetworkName called")

	reply.NetworkName = genesis.NetworkName(service.networkID)
	return nil
}

// GetBlockchainIDArgs are the arguments for calling GetBlockchainID
type GetBlockchainIDArgs struct {
	Alias string `json:"alias"`
}

// GetBlockchainIDReply are the results from calling GetBlockchainID
type GetBlockchainIDReply struct {
	BlockchainID string `json:"blockchainID"`
}

// GetBlockchainID returns the blockchain ID that resolves the alias that was supplied
func (service *Info) GetBlockchainID(_ *http.Request, args *GetBlockchainIDArgs, reply *GetBlockchainIDReply) error {
	service.log.Info("Info: GetBlockchainID called")

	bID, err := service.chainManager.Lookup(args.Alias)
	reply.BlockchainID = bID.String()
	return err
}

// PeersReply are the results from calling Peers
type PeersReply struct {
	Peers []network.PeerID `json:"peers"`
}

// Peers returns the list of current validators
func (service *Info) Peers(_ *http.Request, _ *struct{}, reply *PeersReply) error {
	service.log.Info("Info: Peers called")

	reply.Peers = service.networking.Peers()
	return nil
}

// IsBootstrappedArgs are the arguments for calling IsBootstrapped
type IsBootstrappedArgs struct {
	// Alias of the chain
	// Can also be the string representation of the chain's ID
	Chain string `json:"chain"`
}

// IsBootstrappedResponse are the results from calling IsBootstrapped
type IsBootstrappedResponse struct {
	// True iff the chain exists and is done bootstrapping
	IsBootstrapped bool `json:"isBootstrapped"`
}

// IsBootstrapped returns nil and sets [reply.IsBootstrapped] == true iff [args.Chain] exists and is done bootstrapping
// Returns an error if the chain doesn't exist
func (service *Info) IsBootstrapped(_ *http.Request, args *IsBootstrappedArgs, reply *IsBootstrappedResponse) error {
	service.log.Info("Info: IsBootstrapped called")
	if args.Chain == "" {
		return fmt.Errorf("argument 'chain' not given")
	}
	chainID, err := service.chainManager.Lookup(args.Chain)
	if err != nil {
		return fmt.Errorf("there is no chain with alias/ID '%s'", args.Chain)
	}
	reply.IsBootstrapped = service.chainManager.IsBootstrapped(chainID)
	return nil
}

// GetTxFee returns the transaction fee in nAVAX.
func (service *Info) GetTxFee(_ *http.Request, args *struct{}, reply *struct {
	Fee json.Uint64 `json:"txFee"`
}) error {
	reply.Fee = json.Uint64(service.txFee)
	return nil
}
<commit_msg>Pass Chain in to the log.<commit_after>// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package info

import (
	"fmt"
	"net/http"

	"github.com/gorilla/rpc/v2"

	"github.com/ava-labs/avalanchego/chains"
	"github.com/ava-labs/avalanchego/genesis"
	"github.com/ava-labs/avalanchego/ids"
	"github.com/ava-labs/avalanchego/network"
	"github.com/ava-labs/avalanchego/snow/engine/common"
	"github.com/ava-labs/avalanchego/utils/constants"
	"github.com/ava-labs/avalanchego/utils/json"
	"github.com/ava-labs/avalanchego/utils/logging"
	"github.com/ava-labs/avalanchego/version"
)

// Info is the API service for unprivileged info on a node
type Info struct {
	version      version.Version
	nodeID       ids.ShortID
	networkID    uint32
	log          logging.Logger
	networking   network.Network
	chainManager chains.Manager
	txFee        uint64
}

// NewService returns a new admin API service
func NewService(log logging.Logger, version version.Version, nodeID ids.ShortID, networkID uint32, chainManager chains.Manager, peers network.Network, txFee uint64) (*common.HTTPHandler, error) {
	newServer := rpc.NewServer()
	codec := json.NewCodec()
	newServer.RegisterCodec(codec, "application/json")
	newServer.RegisterCodec(codec, "application/json;charset=UTF-8")
	if err := newServer.RegisterService(&Info{
		version:      version,
		nodeID:       nodeID,
		networkID:    networkID,
		log:          log,
		chainManager: chainManager,
		networking:   peers,
		txFee:        txFee,
	}, "info"); err != nil {
		return nil, err
	}
	return &common.HTTPHandler{Handler: newServer}, nil
}

// GetNodeVersionReply are the results from calling GetNodeVersion
type GetNodeVersionReply struct {
	Version string `json:"version"`
}

// GetNodeVersion returns the version this node is running
func (service *Info) GetNodeVersion(_ *http.Request, _ *struct{}, reply *GetNodeVersionReply) error {
	service.log.Info("Info: GetNodeVersion called")

	reply.Version = service.version.String()
	return nil
}

// GetNodeIDReply are the results from calling GetNodeID
type GetNodeIDReply struct {
	NodeID string `json:"nodeID"`
}

// GetNodeID returns the node ID of this node
func (service *Info) GetNodeID(_ *http.Request, _ *struct{}, reply *GetNodeIDReply) error {
	service.log.Info("Info: GetNodeID called")

	reply.NodeID = service.nodeID.PrefixedString(constants.NodeIDPrefix)
	return nil
}

// GetNetworkIDReply are the results from calling GetNetworkID
type GetNetworkIDReply struct {
	NetworkID json.Uint32 `json:"networkID"`
}

// GetNetworkID returns the network ID this node is running on
func (service *Info) GetNetworkID(_ *http.Request, _ *struct{}, reply *GetNetworkIDReply) error {
	service.log.Info("Info: GetNetworkID called")

	reply.NetworkID = json.Uint32(service.networkID)
	return nil
}

// GetNetworkNameReply is the result from calling GetNetworkName
type GetNetworkNameReply struct {
	NetworkName string `json:"networkName"`
}

// GetNetworkName returns the network name this node is running on
func (service *Info) GetNetworkName(_ *http.Request, _ *struct{}, reply *GetNetworkNameReply) error {
	service.log.Info("Info: GetNetworkName called")

	reply.NetworkName = genesis.NetworkName(service.networkID)
	return nil
}

// GetBlockchainIDArgs are the arguments for calling GetBlockchainID
type GetBlockchainIDArgs struct {
	Alias string `json:"alias"`
}

// GetBlockchainIDReply are the results from calling GetBlockchainID
type GetBlockchainIDReply struct {
	BlockchainID string `json:"blockchainID"`
}

// GetBlockchainID returns the blockchain ID that resolves the alias that was supplied
func (service *Info) GetBlockchainID(_ *http.Request, args *GetBlockchainIDArgs, reply *GetBlockchainIDReply) error {
	service.log.Info("Info: GetBlockchainID called")

	bID, err := service.chainManager.Lookup(args.Alias)
	reply.BlockchainID = bID.String()
	return err
}

// PeersReply are the results from calling Peers
type PeersReply struct {
	Peers []network.PeerID `json:"peers"`
}

// Peers returns the list of current validators
func (service *Info) Peers(_ *http.Request, _ *struct{}, reply *PeersReply) error {
	service.log.Info("Info: Peers called")

	reply.Peers = service.networking.Peers()
	return nil
}

// IsBootstrappedArgs are the arguments for calling IsBootstrapped
type IsBootstrappedArgs struct {
	// Alias of the chain
	// Can also be the string representation of the chain's ID
	Chain string `json:"chain"`
}

// IsBootstrappedResponse are the results from calling IsBootstrapped
type IsBootstrappedResponse struct {
	// True iff the chain exists and is done bootstrapping
	IsBootstrapped bool `json:"isBootstrapped"`
}

// IsBootstrapped returns nil and sets [reply.IsBootstrapped] == true iff [args.Chain] exists and is done bootstrapping
// Returns an error if the chain doesn't exist
func (service *Info) IsBootstrapped(_ *http.Request, args *IsBootstrappedArgs, reply *IsBootstrappedResponse) error {
	service.log.Info("Info: IsBootstrapped called with chain: %s", args.Chain)
	if args.Chain == "" {
		return fmt.Errorf("argument 'chain' not given")
	}
	chainID, err := service.chainManager.Lookup(args.Chain)
	if err != nil {
		return fmt.Errorf("there is no chain with alias/ID '%s'", args.Chain)
	}
	reply.IsBootstrapped = service.chainManager.IsBootstrapped(chainID)
	return nil
}

// GetTxFee returns the transaction fee in nAVAX.
func (service *Info) GetTxFee(_ *http.Request, args *struct{}, reply *struct {
	Fee json.Uint64 `json:"txFee"`
}) error {
	reply.Fee = json.Uint64(service.txFee)
	return nil
}
<|endoftext|>


<commit_before>package model

type UserRepo interface {
    FindUser(id string) (user User, found bool)
    FindUserByName(name string) (user User, found bool)
    All() UserList
}

type userRepo struct {
    users map[string]User
}

func NewUserRepo(users []User) UserRepo {
    return &userRepo{users: listToMap(users)}
}

func (r *userRepo) FindUser(id string) (User, bool) {
    for id, user := range r.users {
        if user.ID == id {
            return user, true
        }
    }
    return User{}, false
}

func (r *userRepo) FindUserByName(name string) (User, bool) {
    for _, user := range r.users {
        if user.Name == name {
            return user, true
        }
    }
    return User{}, false
}

func (r *userRepo) All() UserList {
    return UserList{Users: mapToList(r.users)}
}

func mapToList(userMap map[string]User) []User {
    userList := make([]User, 0, len(userMap))
    for _, user := range userMap {
        userList = append(userList, user)
    }
    return userList
}

func listToMap(userList []User) map[string]User {
    userMap := make(map[string]User, len(userList))
    for _, user := range userList {
        userMap[user.ID] = user
    }
    return userMap
}<commit_msg>Bug in FindUser(id string) fixed<commit_after>package model

type UserRepo interface {
    FindUser(id string) (user User, found bool)
    FindUserByName(name string) (user User, found bool)
    All() UserList
}

type userRepo struct {
    users map[string]User
}

func NewUserRepo(users []User) UserRepo {
    return &userRepo{users: listToMap(users)}
}

func (r *userRepo) FindUser(id string) (User, bool) {
    for _, user := range r.users {
        if user.ID == id {
            return user, true
        }
    }
    return User{}, false
}

func (r *userRepo) FindUserByName(name string) (User, bool) {
    for _, user := range r.users {
        if user.Name == name {
            return user, true
        }
    }
    return User{}, false
}

func (r *userRepo) All() UserList {
    return UserList{Users: mapToList(r.users)}
}

func mapToList(userMap map[string]User) []User {
    userList := make([]User, 0, len(userMap))
    for _, user := range userMap {
        userList = append(userList, user)
    }
    return userList
}

func listToMap(userList []User) map[string]User {
    userMap := make(map[string]User, len(userList))
    for _, user := range userList {
        userMap[user.ID] = user
    }
    return userMap
}
<|endoftext|>


<commit_before>package schema

func NewExample() Schema {
	location := locationSchema{
		Lat:  35.712758,
		Long: 51.392114,
	}

	score := scoreSchema{
		Type:  "GPA",
		Value: "3.4",
	}

	resource := resourceSchema{
		URL:   "http://www.example.com/my-example-slides/",
		Label: "Slides",
	}

	core := coreSchema{
		Name:              "John Doe",
		Title:             "Software Engineer",
		Image:             "example.com/Abcxyz",
		Email:             "lucas@example.com",
		Phone:             "http://www.example.com/my-slides/",
		URL:               "http://www.example.com/",
		Summary:           "The man who sold the world!",
		CurrentLocation:   location,
		PermanentLocation: location,
	}

	work := workSchema{
		Name:        "XYZ Inc",
		Description: "A social media company",
		Position:    "Software Engineer",
		Location:    location,
		URL:         "http:/xyz.example.com",
		StartDate:   "2017-12-29",
		EndDate:     "2018-12-29",
		Summary:     "Developing and maintaining the company website using syna",
		Highlights:  []string{"Worked with mobile team at Twitter to develop remote debugging tools for mobile browsers"},
	}

	education := educationSchema{
		Institution: "e.g. XYZ Institute of Technology",
		Location:    location,
		Area:        "Engineering",
		StudyType:   "Bachelor",
		StartDate:   "2017-06-28",
		EndDate:     "2013-06-28",
		Score:       score,
		Courses:     []string{"CS302 - Introduction to Algorithms "},
		Honors:      []string{"Magna Cum Laude"},
	}

	volunteer := volunteerSchema{
		Organization: "Xyz",
		Position:     "Open Source Contributor",
		Location:     location,
		URL:          "http://xyz.example.com",
		StartDate:    "2014-06-29",
		EndDate:      "2017-06-29",
		Summary:      "Frontend developer",
		Highlights:   []string{"Invited as a speaker in Xyzcon'17"},
	}

	publication := publicationSchema{
		Name:        "Deep learning and Artificial Intelligence",
		Publisher:   "XYZ, Computer Magazine",
		ReleaseDate: "2015-08-01",
		Resources:   []resourceSchema{resource},
		URL:         "http://www.computer.org.example.com/csdl/mags/co/2015/10/rx069-abs.html;format:uri",
		Summary:     "Discussion of the advent of deep learning and artificial intelligence",
	}

	legal := legalSchema{
		Name:            "XYZ's patent on LZW compression, a fundamental part of the widely used GIF graphics format",
		LegalType:       "Patent, Trademark, Copyright",
		Description:     "Some legal document!",
		ApplicationDate: "2015-08-01",
		GrantDate:       "2016-09-01",
		EndDate:         "2020-09-3",
		Resources:       []resourceSchema{resource},
		IDNumber:        "JP2004369746A",
	}

	skill := skillSchema{
		Name: "Web Development",
		Keyword: []struct {
			Name  string      `jsonschema:"name;description:e.g. HTML - [Add the skill name]"`
			Score scoreSchema `jsonschema:"score;additionalProperties;description:Score for the skill name"`
		}{
			{
				Name:  "HTML",
				Score: score,
			},
		},
	}

	award := awardSchema{
		Title:   "Awarded Software Process Achievement Award",
		Date:    "2016-06-12",
		Awarder: "IEEE",
		Summary: "Received for my work in Deep learning and AI",
	}

	project := projectSchema{
		Name:        "File Transfer application",
		Location:    location,
		Description: "Developed a client and server based application",
		Highlights:  []string{"used Java AWT and Swing for client side userinterface"},
		Keywords:    []string{"Java"},
		StartDate:   "2016-06-29",
		EndDate:     "2017-03-02",
		Resources:   []resourceSchema{resource},
		URL:         "http://www.example.org/csdl/mags/co/1996/10/rx069-abs.html",
		Roles:       []string{"Team Lead", "Speaker", "Writer"},
		Entity:      "greenpeace",
		Type:        "volunteering",
	}

	certificate := certificateSchema{
		Code:          "1Z0-062",
		Name:          "XYZ Certified Application Specialist (MCAS)",
		Website:       "http://www.example.org",
		Verification:  "http://www.example.org",
		GrantDate:     "2017-06-29",
		Score:         score,
		EndDate:       "2017-06-29",
		DoesNotExpire: true,
	}

	reference := referenceSchema{
		Name:      "Stephan Mark",
		Company:   "Xyz",
		Position:  "Senior Software Engineer",
		Reference: "Joe blogs was a great employee, who turned up to work at least once a week. He exceeded my expectations when it came to doing nothing.",
	}

	language := languageSchema{
		Language: "English",
		Score:    score,
	}

	interest := interestSchema{
		Name:     "Machine Learning",
		Keywords: []string{"Neural Networks"},
	}

	meta := metaSchema{
		Canonical:    "",
		Version:      "v1.0.0",
		LastModified: "2017-06-29T15:53:01",
	}

	schema := Schema{
		Core:         core,
		Work:         []workSchema{work},
		Education:    []educationSchema{education},
		Volunteer:    []volunteerSchema{volunteer},
		Publications: []publicationSchema{publication},
		Legal:        []legalSchema{legal},
		Skills:       []skillSchema{skill},
		Awards:       []awardSchema{award},
		Projects:     []projectSchema{project},
		Certificates: []certificateSchema{certificate},
		References:   []referenceSchema{reference},
		Languages:    []languageSchema{language},
		Interests:    []interestSchema{interest},
		Meta:         meta,
	}

	return schema
}
<commit_msg>Fix the issue in the example<commit_after>package schema

func NewExample() Schema {
	location := locationSchema{
		Lat:  35.712758,
		Long: 51.392114,
	}

	score := scoreSchema{
		Type:  "GPA",
		Value: "3.4",
	}

	resource := resourceSchema{
		URL:   "http://www.example.com/my-example-slides/",
		Label: "Slides",
	}

	core := coreSchema{
		Name:              "John Doe",
		Title:             "Software Engineer",
		Image:             "example.com/Abcxyz",
		Email:             "lucas@example.com",
		Phone:             "http://www.example.com/my-slides/",
		URL:               "http://www.example.com/",
		Summary:           "The man who sold the world!",
		CurrentLocation:   location,
		PermanentLocation: location,
	}

	work := workSchema{
		Name:        "XYZ Inc",
		Description: "A social media company",
		Position:    "Software Engineer",
		Location:    location,
		URL:         "http:/xyz.example.com",
		StartDate:   "2017-12-29",
		EndDate:     "2018-12-29",
		Summary:     "Developing and maintaining the company website using syna",
		Highlights:  []string{"Worked with mobile team at Twitter to develop remote debugging tools for mobile browsers"},
	}

	education := educationSchema{
		Institution: "e.g. XYZ Institute of Technology",
		Location:    location,
		Area:        "Engineering",
		StudyType:   "Bachelor",
		StartDate:   "2017-06-28",
		EndDate:     "2013-06-28",
		Score:       score,
		Courses:     []string{"CS302 - Introduction to Algorithms "},
		Honors:      []string{"Magna Cum Laude"},
	}

	volunteer := volunteerSchema{
		Organization: "Xyz",
		Position:     "Open Source Contributor",
		Location:     location,
		URL:          "http://xyz.example.com",
		StartDate:    "2014-06-29",
		EndDate:      "2017-06-29",
		Summary:      "Frontend developer",
		Highlights:   []string{"Invited as a speaker in Xyzcon'17"},
	}

	publication := publicationSchema{
		Name:        "Deep learning and Artificial Intelligence",
		Publisher:   "XYZ, Computer Magazine",
		ReleaseDate: "2015-08-01",
		Resources:   []resourceSchema{resource},
		URL:         "http://www.computer.org.example.com/csdl/mags/co/2015/10/rx069-abs.html;format:uri",
		Summary:     "Discussion of the advent of deep learning and artificial intelligence",
	}

	legal := legalSchema{
		Name:            "XYZ's patent on LZW compression, a fundamental part of the widely used GIF graphics format",
		LegalType:       "Patent, Trademark, Copyright",
		Description:     "Some legal document!",
		ApplicationDate: "2015-08-01",
		GrantDate:       "2016-09-01",
		EndDate:         "2020-09-3",
		Resources:       []resourceSchema{resource},
		IDNumber:        "JP2004369746A",
	}

	skill := skillSchema{
		Name: "Web Development",
		Keyword: []struct {
			Name  string      `jsonschema:"name;description:Add the skill name"`
			Score scoreSchema `jsonschema:"score;additionalProperties;description:Score for the skill name"`
		}{
			{
				Name:  "HTML",
				Score: score,
			},
		},
	}

	award := awardSchema{
		Title:   "Awarded Software Process Achievement Award",
		Date:    "2016-06-12",
		Awarder: "IEEE",
		Summary: "Received for my work in Deep learning and AI",
	}

	project := projectSchema{
		Name:        "File Transfer application",
		Location:    location,
		Description: "Developed a client and server based application",
		Highlights:  []string{"used Java AWT and Swing for client side userinterface"},
		Keywords:    []string{"Java"},
		StartDate:   "2016-06-29",
		EndDate:     "2017-03-02",
		Resources:   []resourceSchema{resource},
		URL:         "http://www.example.org/csdl/mags/co/1996/10/rx069-abs.html",
		Roles:       []string{"Team Lead", "Speaker", "Writer"},
		Entity:      "greenpeace",
		Type:        "volunteering",
	}

	certificate := certificateSchema{
		Code:          "1Z0-062",
		Name:          "XYZ Certified Application Specialist (MCAS)",
		Website:       "http://www.example.org",
		Verification:  "http://www.example.org",
		GrantDate:     "2017-06-29",
		Score:         score,
		EndDate:       "2017-06-29",
		DoesNotExpire: true,
	}

	reference := referenceSchema{
		Name:      "Stephan Mark",
		Company:   "Xyz",
		Position:  "Senior Software Engineer",
		Reference: "Joe blogs was a great employee, who turned up to work at least once a week. He exceeded my expectations when it came to doing nothing.",
	}

	language := languageSchema{
		Language: "English",
		Score:    score,
	}

	interest := interestSchema{
		Name:     "Machine Learning",
		Keywords: []string{"Neural Networks"},
	}

	meta := metaSchema{
		Canonical:    "",
		Version:      "v1.0.0",
		LastModified: "2017-06-29T15:53:01",
	}

	schema := Schema{
		Core:         core,
		Work:         []workSchema{work},
		Education:    []educationSchema{education},
		Volunteer:    []volunteerSchema{volunteer},
		Publications: []publicationSchema{publication},
		Legal:        []legalSchema{legal},
		Skills:       []skillSchema{skill},
		Awards:       []awardSchema{award},
		Projects:     []projectSchema{project},
		Certificates: []certificateSchema{certificate},
		References:   []referenceSchema{reference},
		Languages:    []languageSchema{language},
		Interests:    []interestSchema{interest},
		Meta:         meta,
	}

	return schema
}
<|endoftext|>


<commit_before>// This file defines built-in procedures for TopLevel environment.

package scheme

import (
	"fmt"
	"strings"
)

var builtinProcedures = Binding{
	"+":             NewProcedure(plus),
	"-":             NewProcedure(minus),
	"*":             NewProcedure(multiply),
	"/":             NewProcedure(divide),
	"=":             NewProcedure(equal),
	"number?":       NewProcedure(isNumber),
	"null?":         NewProcedure(isNull),
	"procedure?":    NewProcedure(isProcedure),
	"boolean?":      NewProcedure(isBoolean),
	"pair?":         NewProcedure(isPair),
	"list?":         NewProcedure(isList),
	"symbol?":       NewProcedure(isSymbol),
	"string?":       NewProcedure(isString),
	"not":           NewProcedure(not),
	"car":           NewProcedure(car),
	"cdr":           NewProcedure(cdr),
	"list":          NewProcedure(list),
	"string-append": NewProcedure(stringAppend),
}

func assertListMinimum(arguments Object, minimum int) {
	if !arguments.IsList() {
		panic("Compile Error: proper list required for function application or macro use")
	} else if arguments.(*Pair).ListLength() < minimum {
		panic(fmt.Sprintf("Compile Error: procedure requires at least %d argument", minimum))
	}
}

func assertListEqual(arguments Object, length int) {
	if !arguments.IsList() {
		panic("Compile Error: proper list required for function application or macro use")
	} else if arguments.(*Pair).ListLength() != length {
		panic(fmt.Sprintf("Compile Error: wrong number of arguments: number? requires %d, but got %d",
			length, arguments.(*Pair).ListLength()))
	}
}

func assertObjectsType(objects []Object, typeName string) {
	for _, object := range objects {
		if typeName == "Number" && !object.IsNumber() {
			panic("Compile Error: number required")
		} else if typeName == "String" && !object.IsString() {
			panic("Compile Error: string required")
		}
	}
}

func assertPair(object Object) {
	switch object.(type) {
	case *Pair:
		if object.IsPair() {
			return
		}
	}
	panic("Compile Error: pair required")
}

func evaledObjects(objects []Object) []Object {
	evaledObjects := []Object{}

	for _, object := range objects {
		evaledObjects = append(evaledObjects, object.Eval())
	}
	return evaledObjects
}

func typeCheckResult(arguments Object, typeCheckFunc func(Object) bool) Object {
	assertListEqual(arguments, 1)

	object := arguments.(*Pair).ElementAt(0).Eval()
	return NewBoolean(typeCheckFunc(object))
}

func plus(arguments Object) Object {
	assertListMinimum(arguments, 0)

	numbers := evaledObjects(arguments.(*Pair).Elements())
	assertObjectsType(numbers, "Number")

	sum := 0
	for _, number := range numbers {
		sum += number.(*Number).value
	}
	return NewNumber(sum)
}

func minus(arguments Object) Object {
	assertListMinimum(arguments, 1)

	numbers := evaledObjects(arguments.(*Pair).Elements())
	assertObjectsType(numbers, "Number")

	difference := numbers[0].(*Number).value
	for _, number := range numbers[1:] {
		difference -= number.(*Number).value
	}
	return NewNumber(difference)
}

func multiply(arguments Object) Object {
	assertListMinimum(arguments, 0)

	numbers := evaledObjects(arguments.(*Pair).Elements())
	assertObjectsType(numbers, "Number")

	product := 1
	for _, number := range numbers {
		product *= number.(*Number).value
	}
	return NewNumber(product)
}

func divide(arguments Object) Object {
	assertListMinimum(arguments, 1)

	numbers := evaledObjects(arguments.(*Pair).Elements())
	assertObjectsType(numbers, "Number")

	quotient := numbers[0].(*Number).value
	for _, number := range numbers[1:] {
		quotient /= number.(*Number).value
	}
	return NewNumber(quotient)
}

func equal(arguments Object) Object {
	assertListMinimum(arguments, 2)

	numbers := evaledObjects(arguments.(*Pair).Elements())
	assertObjectsType(numbers, "Number")

	firstValue := numbers[0].(*Number).value
	for _, number := range numbers[1:] {
		if firstValue != number.(*Number).value {
			return NewBoolean(false)
		}
	}
	return NewBoolean(true)
}

func isNumber(arguments Object) Object {
	return typeCheckResult(arguments, func(object Object) bool { return object.IsNumber() })
}

func isNull(arguments Object) Object {
	return typeCheckResult(arguments, func(object Object) bool { return object.IsNull() })
}

func isProcedure(arguments Object) Object {
	return typeCheckResult(arguments, func(object Object) bool { return object.IsProcedure() })
}

func isBoolean(arguments Object) Object {
	return typeCheckResult(arguments, func(object Object) bool { return object.IsBoolean() })
}

func isPair(arguments Object) Object {
	return typeCheckResult(arguments, func(object Object) bool { return object.IsPair() })
}

func isList(arguments Object) Object {
	return typeCheckResult(arguments, func(object Object) bool { return object.IsList() })
}

func isSymbol(arguments Object) Object {
	return typeCheckResult(arguments, func(object Object) bool { return object.IsSymbol() })
}

func isString(arguments Object) Object {
	return typeCheckResult(arguments, func(object Object) bool { return object.IsString() })
}

func not(arguments Object) Object {
	assertListEqual(arguments, 1)

	object := arguments.(*Pair).ElementAt(0).Eval()
	return NewBoolean(object.IsBoolean() && !object.(*Boolean).value)
}

func car(arguments Object) Object {
	assertListEqual(arguments, 1)

	object := arguments.(*Pair).ElementAt(0).Eval()
	assertPair(object)
	return object.(*Pair).Car
}

func cdr(arguments Object) Object {
	assertListEqual(arguments, 1)

	object := arguments.(*Pair).ElementAt(0).Eval()
	assertPair(object)
	return object.(*Pair).Cdr
}

func list(arguments Object) Object {
	return arguments
}

func stringAppend(arguments Object) Object {
	assertListMinimum(arguments, 0)

	stringObjects := evaledObjects(arguments.(*Pair).Elements())
	assertObjectsType(stringObjects, "String")

	texts := []string{}
	for _, stringObject := range stringObjects {
		texts = append(texts, stringObject.(*String).text)
	}
	return NewString(strings.Join(texts, ""))
}
<commit_msg>Refactor not procedure too<commit_after>// This file defines built-in procedures for TopLevel environment.

package scheme

import (
	"fmt"
	"strings"
)

var builtinProcedures = Binding{
	"+":             NewProcedure(plus),
	"-":             NewProcedure(minus),
	"*":             NewProcedure(multiply),
	"/":             NewProcedure(divide),
	"=":             NewProcedure(equal),
	"number?":       NewProcedure(isNumber),
	"null?":         NewProcedure(isNull),
	"procedure?":    NewProcedure(isProcedure),
	"boolean?":      NewProcedure(isBoolean),
	"pair?":         NewProcedure(isPair),
	"list?":         NewProcedure(isList),
	"symbol?":       NewProcedure(isSymbol),
	"string?":       NewProcedure(isString),
	"not":           NewProcedure(not),
	"car":           NewProcedure(car),
	"cdr":           NewProcedure(cdr),
	"list":          NewProcedure(list),
	"string-append": NewProcedure(stringAppend),
}

func assertListMinimum(arguments Object, minimum int) {
	if !arguments.IsList() {
		panic("Compile Error: proper list required for function application or macro use")
	} else if arguments.(*Pair).ListLength() < minimum {
		panic(fmt.Sprintf("Compile Error: procedure requires at least %d argument", minimum))
	}
}

func assertListEqual(arguments Object, length int) {
	if !arguments.IsList() {
		panic("Compile Error: proper list required for function application or macro use")
	} else if arguments.(*Pair).ListLength() != length {
		panic(fmt.Sprintf("Compile Error: wrong number of arguments: number? requires %d, but got %d",
			length, arguments.(*Pair).ListLength()))
	}
}

func assertObjectsType(objects []Object, typeName string) {
	for _, object := range objects {
		if typeName == "Number" && !object.IsNumber() {
			panic("Compile Error: number required")
		} else if typeName == "String" && !object.IsString() {
			panic("Compile Error: string required")
		}
	}
}

func assertPair(object Object) {
	switch object.(type) {
	case *Pair:
		if object.IsPair() {
			return
		}
	}
	panic("Compile Error: pair required")
}

func evaledObjects(objects []Object) []Object {
	evaledObjects := []Object{}

	for _, object := range objects {
		evaledObjects = append(evaledObjects, object.Eval())
	}
	return evaledObjects
}

func booleanByFunc(arguments Object, typeCheckFunc func(Object) bool) Object {
	assertListEqual(arguments, 1)

	object := arguments.(*Pair).ElementAt(0).Eval()
	return NewBoolean(typeCheckFunc(object))
}

func plus(arguments Object) Object {
	assertListMinimum(arguments, 0)

	numbers := evaledObjects(arguments.(*Pair).Elements())
	assertObjectsType(numbers, "Number")

	sum := 0
	for _, number := range numbers {
		sum += number.(*Number).value
	}
	return NewNumber(sum)
}

func minus(arguments Object) Object {
	assertListMinimum(arguments, 1)

	numbers := evaledObjects(arguments.(*Pair).Elements())
	assertObjectsType(numbers, "Number")

	difference := numbers[0].(*Number).value
	for _, number := range numbers[1:] {
		difference -= number.(*Number).value
	}
	return NewNumber(difference)
}

func multiply(arguments Object) Object {
	assertListMinimum(arguments, 0)

	numbers := evaledObjects(arguments.(*Pair).Elements())
	assertObjectsType(numbers, "Number")

	product := 1
	for _, number := range numbers {
		product *= number.(*Number).value
	}
	return NewNumber(product)
}

func divide(arguments Object) Object {
	assertListMinimum(arguments, 1)

	numbers := evaledObjects(arguments.(*Pair).Elements())
	assertObjectsType(numbers, "Number")

	quotient := numbers[0].(*Number).value
	for _, number := range numbers[1:] {
		quotient /= number.(*Number).value
	}
	return NewNumber(quotient)
}

func equal(arguments Object) Object {
	assertListMinimum(arguments, 2)

	numbers := evaledObjects(arguments.(*Pair).Elements())
	assertObjectsType(numbers, "Number")

	firstValue := numbers[0].(*Number).value
	for _, number := range numbers[1:] {
		if firstValue != number.(*Number).value {
			return NewBoolean(false)
		}
	}
	return NewBoolean(true)
}

func isNumber(arguments Object) Object {
	return booleanByFunc(arguments, func(object Object) bool { return object.IsNumber() })
}

func isNull(arguments Object) Object {
	return booleanByFunc(arguments, func(object Object) bool { return object.IsNull() })
}

func isProcedure(arguments Object) Object {
	return booleanByFunc(arguments, func(object Object) bool { return object.IsProcedure() })
}

func isBoolean(arguments Object) Object {
	return booleanByFunc(arguments, func(object Object) bool { return object.IsBoolean() })
}

func isPair(arguments Object) Object {
	return booleanByFunc(arguments, func(object Object) bool { return object.IsPair() })
}

func isList(arguments Object) Object {
	return booleanByFunc(arguments, func(object Object) bool { return object.IsList() })
}

func isSymbol(arguments Object) Object {
	return booleanByFunc(arguments, func(object Object) bool { return object.IsSymbol() })
}

func isString(arguments Object) Object {
	return booleanByFunc(arguments, func(object Object) bool { return object.IsString() })
}

func not(arguments Object) Object {
	return booleanByFunc(arguments,
		func(object Object) bool { return object.IsBoolean() && !object.(*Boolean).value })
}

func car(arguments Object) Object {
	assertListEqual(arguments, 1)

	object := arguments.(*Pair).ElementAt(0).Eval()
	assertPair(object)
	return object.(*Pair).Car
}

func cdr(arguments Object) Object {
	assertListEqual(arguments, 1)

	object := arguments.(*Pair).ElementAt(0).Eval()
	assertPair(object)
	return object.(*Pair).Cdr
}

func list(arguments Object) Object {
	return arguments
}

func stringAppend(arguments Object) Object {
	assertListMinimum(arguments, 0)

	stringObjects := evaledObjects(arguments.(*Pair).Elements())
	assertObjectsType(stringObjects, "String")

	texts := []string{}
	for _, stringObject := range stringObjects {
		texts = append(texts, stringObject.(*String).text)
	}
	return NewString(strings.Join(texts, ""))
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	//"github.com/octokit/go-octokit/octokit"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

var githubURL = "https://api.github.com/"

var sourceFolder = filepath.FromSlash(os.Getenv("GOPATH") +
	"/src/github.com/octokit/go-octokit/octokit/")

var URLDeclarationMatcher = regexp.MustCompile(
	`[A-Za-z]+URL\s*=\s*Hyperlink\(\"([\/a-z0-9_{}]+)\"\)`)

func listSourceFiles(dirname string) []string {
	var result []string
	files, err := ioutil.ReadDir(dirname)
	if err != nil {
		panic(err)
	}
	for _, f := range files {
		if strings.HasSuffix(f.Name(), ".go") &&
			!strings.HasSuffix(f.Name(), "_test.go") {
			result = append(result, f.Name())
		}
	}
	return result
}

func extractURLsFromSourceFile(filename string) (results []string) {
	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	varBlockPresent := false
	for scanner.Scan() {
		text := scanner.Text()
		if text == "var (" {
			varBlockPresent = true
		}
		res := URLDeclarationMatcher.FindStringSubmatch(text)
		if len(res) > 1 {

			results = append(results, res[1])
			if !varBlockPresent {
				return
			}
		}
		if varBlockPresent && text == ")" {
			return
		}
	}
	return
}

func main() {

	resp, err := http.Get(githubURL)
	if err != nil {
		fmt.Printf("Error opening %s\n", githubURL)
		panic(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Error fetching data from %s\n", githubURL)
		panic(err)
	}

	var dat map[string]interface{}

	if err := json.Unmarshal(body, &dat); err != nil {
		panic(err)
	}

	existingValues := make(map[string]bool)
	extraValues := make(map[string]bool)

	for _, v := range dat {
		v := v.(string)
		existingValues[v[strings.Index(v, ".com/")+5:]] = false
	}

	var apisFoundCount = 0

	for _, f := range listSourceFiles(sourceFolder) {
		urls := extractURLsFromSourceFile(sourceFolder +
			string(os.PathSeparator) + f)
		for _, url := range urls {
			if len(url) > 1 && url[0] == '/' {
				url = url[1:]
			}
			if url != "" {
				apisFoundCount += 1
				if _, ok := existingValues[url]; ok {
					existingValues[url] = true
				} else {
					extraValues[url] = true
				}
			}
		}
	}

	fmt.Printf("%d APIs found on %s.\n", len(existingValues), githubURL)
	fmt.Printf("%d APIs implementations found.\n", apisFoundCount)

	fmt.Println("\nExisting APIs:")

	for k, v := range existingValues {
		if v {
			fmt.Println(k)
		}
	}

	fmt.Println("\nUnaccounted APIs:")

	for k, _ := range extraValues {
		fmt.Println(k)
	}

	fmt.Println("\nMissing APIs:")

	for k, v := range existingValues {
		if !v {
			fmt.Println(k)
		}
	}
}
<commit_msg>[WIP] Auditor script now use URLs in the comments to do the audit<commit_after>package main

import (
	"bufio"
	//"bytes"
	//"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

var octokitRoot = filepath.FromSlash(os.Getenv("GOPATH") +
	"/src/github.com/octokit/go-octokit/")

var sourceFolder = filepath.FromSlash(octokitRoot + "octokit/")

var todoFile = filepath.FromSlash(octokitRoot + "TODO.md")

var URLDeclarationMatcher = regexp.MustCompile(
	`// See ([\/a-z0-9_{}\.:]+)`)

func listSourceFiles(dirname string) []string {
	var result []string
	files, err := ioutil.ReadDir(dirname)
	if err != nil {
		panic(err)
	}
	for _, f := range files {
		if strings.HasSuffix(f.Name(), ".go") &&
			!strings.HasSuffix(f.Name(), "_test.go") {
			result = append(result, f.Name())
		}
	}
	return result
}

func extractURLsFromSourceFile(filename string) (results []string) {
	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		text := scanner.Text()
		res := URLDeclarationMatcher.FindStringSubmatch(text)
		if len(res) > 1 {
			results = append(results, res[1])
		}
	}
	return
}

func findAllExistingApiUrls() (urls []string) {
	for _, f := range listSourceFiles(sourceFolder) {
		sourceUrls := extractURLsFromSourceFile(sourceFolder +
			string(os.PathSeparator) + f)
		urls = append(urls, sourceUrls...)
	}
	return urls
}

func main() {
	/*file, err := os.Open(todoFile)
	if err != nil {
		fmt.Printf("Error opening TODO file: %s\n", todoFile)
		panic(err)
	}
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		line := scanner.Text()
		url := line[4:]

	}

	var dat map[string]interface{}

	existingValues := make(map[string]bool)
	extraValues := make(map[string]bool)

	for _, v := range dat {
		v := v.(string)
		existingValues[v[strings.Index(v, ".com/")+5:]] = false
	}

	var apisFoundCount = 0

	fmt.Printf("%d APIs implementations found.\n", apisFoundCount)

	fmt.Println("\nExisting APIs:")

	for k, v := range existingValues {
		if v {
			fmt.Println(k)
		}
	}

	fmt.Println("\nUnaccounted APIs:")

	for k, _ := range extraValues {
		fmt.Println(k)
	}

	fmt.Println("\nMissing APIs:")

	for k, v := range existingValues {
		if !v {
			fmt.Println(k)
		}
	}
	*/
}
<|endoftext|>


<commit_before>package models

import (
	"errors"

	"github.com/eirka/eirka-libs/config"
	"github.com/eirka/eirka-libs/db"
	e "github.com/eirka/eirka-libs/errors"
	"github.com/eirka/eirka-libs/validate"
)

// Password contains information for initial account creation
type PasswordModel struct {
	Uid       uint
	Name      string
	OldPw     string
	NewPw     string
	NewHashed []byte
}

// check struct validity
func (p *PasswordModel) IsValid() bool {

	if p.Uid == 0 || p.Uid == 1 {
		return false
	}

	if p.Name == "" {
		return false
	}

	if p.OldPw == "" {
		return false
	}

	if p.NewPw == "" {
		return false
	}

	if p.NewHashed == nil {
		return false
	}

	return true

}

// Validate will check the provided password
func (r *PasswordModel) Validate() (err error) {

	// Validate new password input
	newpassword := validate.Validate{Input: r.NewPw, Max: config.Settings.Limits.PasswordMaxLength, Min: config.Settings.Limits.PasswordMinLength}
	if newpassword.IsEmpty() {
		return e.ErrPasswordEmpty
	} else if newpassword.MinLength() {
		return e.ErrPasswordShort
	} else if newpassword.MaxLength() {
		return e.ErrPasswordLong
	}

	// Validate old password input
	oldpassword := validate.Validate{Input: r.OldPw, Max: config.Settings.Limits.PasswordMaxLength, Min: config.Settings.Limits.PasswordMinLength}
	if oldpassword.IsEmpty() {
		return e.ErrPasswordEmpty
	} else if oldpassword.MinLength() {
		return e.ErrPasswordShort
	} else if oldpassword.MaxLength() {
		return e.ErrPasswordLong
	}

	return

}

// change password
func (r *PasswordModel) Update() (err error) {

	// check model validity
	if !r.IsValid() {
		return errors.New("PasswordModel is not valid")
	}

	// Get Database handle
	dbase, err := db.GetDb()
	if err != nil {
		return
	}

	_, err = dbase.Exec("UPDATE users SET user_password = ? WHERE user_id = ?", r.NewHashed, r.Uid)
	if err != nil {
		return
	}

	return

}
<commit_msg>use user lib password update function<commit_after>package models

import (
	"errors"

	"github.com/eirka/eirka-libs/config"
	"github.com/eirka/eirka-libs/db"
	e "github.com/eirka/eirka-libs/errors"
	"github.com/eirka/eirka-libs/user"
	"github.com/eirka/eirka-libs/validate"
)

// Password contains information for initial account creation
type PasswordModel struct {
	Uid       uint
	Name      string
	OldPw     string
	NewPw     string
	NewHashed []byte
}

// check struct validity
func (p *PasswordModel) IsValid() bool {

	if p.Uid == 0 || p.Uid == 1 {
		return false
	}

	if p.Name == "" {
		return false
	}

	if p.OldPw == "" {
		return false
	}

	if p.NewPw == "" {
		return false
	}

	if p.NewHashed == nil {
		return false
	}

	return true

}

// Validate will check the provided password
func (r *PasswordModel) Validate() (err error) {

	// Validate new password input
	newpassword := validate.Validate{Input: r.NewPw, Max: config.Settings.Limits.PasswordMaxLength, Min: config.Settings.Limits.PasswordMinLength}
	if newpassword.IsEmpty() {
		return e.ErrPasswordEmpty
	} else if newpassword.MinLength() {
		return e.ErrPasswordShort
	} else if newpassword.MaxLength() {
		return e.ErrPasswordLong
	}

	// Validate old password input
	oldpassword := validate.Validate{Input: r.OldPw, Max: config.Settings.Limits.PasswordMaxLength, Min: config.Settings.Limits.PasswordMinLength}
	if oldpassword.IsEmpty() {
		return e.ErrPasswordEmpty
	} else if oldpassword.MinLength() {
		return e.ErrPasswordShort
	} else if oldpassword.MaxLength() {
		return e.ErrPasswordLong
	}

	return

}

// change password
func (r *PasswordModel) Update() (err error) {

	// check model validity
	if !r.IsValid() {
		return errors.New("PasswordModel is not valid")
	}

	// update user password
	user.UpdatePassword(r.NewHashed, r.Uid)
	if err != nil {
		return
	}

	return

}
<|endoftext|>


<commit_before>package models

import (
	"github.com/intervention-engine/fhir/models"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"time"
)

type Pipeline struct {
	MongoPipeline []bson.M
}

type MatchingStage struct {
	AndStatements bson.M
	OrStatements  []bson.M
}

func NewMS() *MatchingStage {
	ms := &MatchingStage{}
	ms.AndStatements = bson.M{}
	ms.OrStatements = []bson.M{}
	return ms
}

func (m *MatchingStage) AddAndStatement(key string, value interface{}) {
	m.AndStatements[key] = value
}

func (m *MatchingStage) AddOrStatement(statement bson.M) {
	m.OrStatements = append(m.OrStatements, statement)
}

func (m *MatchingStage) AddType(typeString string) {
	m.AndStatements["entries.type"] = typeString
}

func (m *MatchingStage) AddCodableConecpt(cc models.CodeableConcept) {
	if len(cc.Coding) == 1 {
		code := cc.Coding[0].Code
		system := cc.Coding[0].System
		m.AddAndStatement("entries.codes.coding.code", code)
		m.AddAndStatement("entries.codes.coding.system", system)
	} else {
		for _, coding := range cc.Coding {
			code := coding.Code
			system := coding.System
			m.AddOrStatement(bson.M{"entries.codes.coding.code": code, "entries.codes.coding.system": system})
		}
	}
}

func (m *MatchingStage) AddAgeRange(ageRange models.Range) {
	rangeQuery := bson.M{}
	if ageRange.Low.Value > 0 {
		lowAgeDate := time.Date(time.Now().Year()-int(ageRange.Low.Value), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.UTC)
		rangeQuery["$lte"] = lowAgeDate
	}

	if ageRange.High.Value > 0 {
		highAgeDate := time.Date(time.Now().Year()-int(ageRange.High.Value), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.UTC)
		rangeQuery["$gte"] = highAgeDate
	}
	m.AddAndStatement("birthdate.time", rangeQuery)
}

func (m *MatchingStage) AddValueCheck(e models.Extension) {
	if e.ValueInteger != 0 {
		m.AddAndStatement("entries.resultquantity.value", float64(e.ValueInteger))
	}
	if e.ValueRange.High.Value != 0 || e.ValueRange.Low.Value != 0 {
		rangeQuery := bson.M{}
		if e.ValueRange.High.Value != 0 {
			rangeQuery["$lte"] = e.ValueRange.High.Value
		}
		if e.ValueRange.Low.Value != 0 {
			rangeQuery["$gte"] = e.ValueRange.Low.Value
		}
		m.AddAndStatement("entries.resultquantity.value", rangeQuery)
	}
}

func (m *MatchingStage) ToBSON() bson.M {
	if len(m.OrStatements) > 1 {
		m.AndStatements["$or"] = m.OrStatements
	}
	return bson.M{"$match": m.AndStatements}
}

type QueryResult struct {
	Total int `json:"total", bson:"total"`
}

type QueryPatientList struct {
	PatientIds []string `json:"patientids", bson:"patientids"`
}

type PipelineProducer func(q *models.Query) (p Pipeline)

func NewPipeline(q *models.Query) Pipeline {
	pipeline := Pipeline{}
	pipeline.MongoPipeline = []bson.M{{"$group": bson.M{"_id": "$patientid", "gender": bson.M{"$max": "$gender"}, "birthdate": bson.M{"$max": "$birthdate"}, "entries": bson.M{"$push": bson.M{"startdate": "$startdate", "enddate": "$enddate", "codes": "$codes", "type": "$type", "resultquantity": "$resultquantity"}}}}}
	for _, extension := range q.Parameter {
		ms := NewMS()
		switch extension.Url {
		case "http://interventionengine.org/patientgender":
			ms.AddAndStatement("gender", extension.ValueString)
		case "http://interventionengine.org/patientage":
			ms.AddAgeRange(*extension.ValueRange)
		case "http://interventionengine.org/conditioncode":
			ms.AddType("Condition")
			ms.AddCodableConecpt(*extension.ValueCodeableConcept)
		case "http://interventionengine.org/encountercode":
			ms.AddType("Encounter")
			ms.AddCodableConecpt(*extension.ValueCodeableConcept)
		case "http://interventionengine.org/observationcode":
			ms.AddType("Observation")
			ms.AddCodableConecpt(*extension.ValueCodeableConcept)
			ms.AddValueCheck(extension)
		}
		pipeline.MongoPipeline = append(pipeline.MongoPipeline, ms.ToBSON())
	}

	return pipeline
}

func IsRangePresent(r models.Range) bool {
	return r.High.Value != 0 && r.Low.Value != 0
}

func NewConditionPipeline(q *models.Query) Pipeline {
	pipeline := NewPipeline(q)

	pipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{"$unwind": "$entries"})
	pipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{"$match": bson.M{"entries.type": "Condition"}})
	pipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{"$group": bson.M{"_id": "entries.codes.coding.code", "total": bson.M{"$sum": 1}}})
	return pipeline
}

func NewEncounterPipeline(q *models.Query) Pipeline {
	pipeline := NewPipeline(q)

	pipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{"$unwind": "$entries"})
	pipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{"$match": bson.M{"entries.type": "Encounter"}})
	return pipeline
}

func (p *Pipeline) MakeCountPipeline() {
	p.MongoPipeline = append(p.MongoPipeline, bson.M{"$group": bson.M{"_id": nil, "total": bson.M{"$sum": 1}}})
}

func (p *Pipeline) MakePatientListPipeline() {
	p.MongoPipeline = append(p.MongoPipeline, bson.M{"$group": bson.M{"_id": nil, "patientids": bson.M{"$push": "$_id"}}})
}

func (p *Pipeline) ExecuteCount(db *mgo.Database) (QueryResult, error) {
	factCollection := db.C("facts")
	qr := QueryResult{}
	p.MakeCountPipeline()
	err := factCollection.Pipe(p.MongoPipeline).One(&qr)
	return qr, err
}

func (p *Pipeline) ExecutePatientList(db *mgo.Database) (QueryPatientList, error) {
	factCollection := db.C("facts")
	qpl := QueryPatientList{}
	p.MakePatientListPipeline()
	err := factCollection.Pipe(p.MongoPipeline).One(&qpl)
	return qpl, err
}
<commit_msg>fix to pipeline code to avoid referencing nil pointers<commit_after>package models

import (
	"github.com/intervention-engine/fhir/models"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"time"
)

type Pipeline struct {
	MongoPipeline []bson.M
}

type MatchingStage struct {
	AndStatements bson.M
	OrStatements  []bson.M
}

func NewMS() *MatchingStage {
	ms := &MatchingStage{}
	ms.AndStatements = bson.M{}
	ms.OrStatements = []bson.M{}
	return ms
}

func (m *MatchingStage) AddAndStatement(key string, value interface{}) {
	m.AndStatements[key] = value
}

func (m *MatchingStage) AddOrStatement(statement bson.M) {
	m.OrStatements = append(m.OrStatements, statement)
}

func (m *MatchingStage) AddType(typeString string) {
	m.AndStatements["entries.type"] = typeString
}

func (m *MatchingStage) AddCodableConecpt(cc models.CodeableConcept) {
	if len(cc.Coding) == 1 {
		code := cc.Coding[0].Code
		system := cc.Coding[0].System
		m.AddAndStatement("entries.codes.coding.code", code)
		m.AddAndStatement("entries.codes.coding.system", system)
	} else {
		for _, coding := range cc.Coding {
			code := coding.Code
			system := coding.System
			m.AddOrStatement(bson.M{"entries.codes.coding.code": code, "entries.codes.coding.system": system})
		}
	}
}

func (m *MatchingStage) AddAgeRange(ageRange models.Range) {
	rangeQuery := bson.M{}
	if (ageRange.Low != nil && ageRange.Low.Value > 0) {
		lowAgeDate := time.Date(time.Now().Year()-int(ageRange.Low.Value), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.UTC)
		rangeQuery["$lte"] = lowAgeDate
	}

	if (ageRange.High != nil && ageRange.High.Value > 0) {
		highAgeDate := time.Date(time.Now().Year()-int(ageRange.High.Value), time.Now().Month(), time.Now().Day(), 0, 0, 0, 0, time.UTC)
		rangeQuery["$gte"] = highAgeDate
	}
	m.AddAndStatement("birthdate.time", rangeQuery)
}

func (m *MatchingStage) AddValueCheck(e models.Extension) {
	if e.ValueInteger != 0 {
		m.AddAndStatement("entries.resultquantity.value", float64(e.ValueInteger))
	}
	if e.ValueRange != nil {
		if e.ValueRange.High.Value != 0 || e.ValueRange.Low.Value != 0 {
			rangeQuery := bson.M{}
			if e.ValueRange.High.Value != 0 {
				rangeQuery["$lte"] = e.ValueRange.High.Value
			}
			if e.ValueRange.Low.Value != 0 {
				rangeQuery["$gte"] = e.ValueRange.Low.Value
			}
			m.AddAndStatement("entries.resultquantity.value", rangeQuery)
		}
	}
}

func (m *MatchingStage) ToBSON() bson.M {
	if len(m.OrStatements) > 1 {
		m.AndStatements["$or"] = m.OrStatements
	}
	return bson.M{"$match": m.AndStatements}
}

type QueryResult struct {
	Total int `json:"total", bson:"total"`
}

type QueryPatientList struct {
	PatientIds []string `json:"patientids", bson:"patientids"`
}

type PipelineProducer func(q *models.Query) (p Pipeline)

func NewPipeline(q *models.Query) Pipeline {
	pipeline := Pipeline{}
	pipeline.MongoPipeline = []bson.M{{"$group": bson.M{"_id": "$patientid", "gender": bson.M{"$max": "$gender"}, "birthdate": bson.M{"$max": "$birthdate"}, "entries": bson.M{"$push": bson.M{"startdate": "$startdate", "enddate": "$enddate", "codes": "$codes", "type": "$type", "resultquantity": "$resultquantity"}}}}}
	for _, extension := range q.Parameter {
		ms := NewMS()
		switch extension.Url {
		case "http://interventionengine.org/patientgender":
			ms.AddAndStatement("gender", extension.ValueString)
		case "http://interventionengine.org/patientage":
			ms.AddAgeRange(*extension.ValueRange)
		case "http://interventionengine.org/conditioncode":
			ms.AddType("Condition")
			ms.AddCodableConecpt(*extension.ValueCodeableConcept)
		case "http://interventionengine.org/encountercode":
			ms.AddType("Encounter")
			ms.AddCodableConecpt(*extension.ValueCodeableConcept)
		case "http://interventionengine.org/observationcode":
			ms.AddType("Observation")
			ms.AddCodableConecpt(*extension.ValueCodeableConcept)
			ms.AddValueCheck(extension)
		}
		pipeline.MongoPipeline = append(pipeline.MongoPipeline, ms.ToBSON())
	}

	return pipeline
}

func IsRangePresent(r models.Range) bool {
	return r.High.Value != 0 && r.Low.Value != 0
}

func NewConditionPipeline(q *models.Query) Pipeline {
	pipeline := NewPipeline(q)

	pipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{"$unwind": "$entries"})
	pipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{"$match": bson.M{"entries.type": "Condition"}})
	pipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{"$group": bson.M{"_id": "entries.codes.coding.code", "total": bson.M{"$sum": 1}}})
	return pipeline
}

func NewEncounterPipeline(q *models.Query) Pipeline {
	pipeline := NewPipeline(q)

	pipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{"$unwind": "$entries"})
	pipeline.MongoPipeline = append(pipeline.MongoPipeline, bson.M{"$match": bson.M{"entries.type": "Encounter"}})
	return pipeline
}

func (p *Pipeline) MakeCountPipeline() {
	p.MongoPipeline = append(p.MongoPipeline, bson.M{"$group": bson.M{"_id": nil, "total": bson.M{"$sum": 1}}})
}

func (p *Pipeline) MakePatientListPipeline() {
	p.MongoPipeline = append(p.MongoPipeline, bson.M{"$group": bson.M{"_id": nil, "patientids": bson.M{"$push": "$_id"}}})
}

func (p *Pipeline) ExecuteCount(db *mgo.Database) (QueryResult, error) {
	factCollection := db.C("facts")
	qr := QueryResult{}
	p.MakeCountPipeline()
	err := factCollection.Pipe(p.MongoPipeline).One(&qr)
	return qr, err
}

func (p *Pipeline) ExecutePatientList(db *mgo.Database) (QueryPatientList, error) {
	factCollection := db.C("facts")
	qpl := QueryPatientList{}
	p.MakePatientListPipeline()
	err := factCollection.Pipe(p.MongoPipeline).One(&qpl)
	return qpl, err
}
<|endoftext|>


<commit_before>package kcp

import (
	"errors"
	"io"
	"net"
	"sync"
	"sync/atomic"
	"time"

	"github.com/v2ray/v2ray-core/common/alloc"
	"github.com/v2ray/v2ray-core/common/log"
)

var (
	errTimeout          = errors.New("i/o timeout")
	errBrokenPipe       = errors.New("broken pipe")
	errClosedListener   = errors.New("Listener closed.")
	errClosedConnection = errors.New("Connection closed.")
)

type State int32

const (
	StateActive          State = 0
	StateReadyToClose    State = 1
	StatePeerClosed      State = 2
	StateTerminating     State = 3
	StatePeerTerminating State = 4
	StateTerminated      State = 5
)

const (
	headerSize uint32 = 2
)

func nowMillisec() int64 {
	now := time.Now()
	return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
}

type RountTripInfo struct {
	sync.RWMutex
	variation uint32
	srtt      uint32
	rto       uint32
	minRtt    uint32
}

func (this *RountTripInfo) Update(rtt uint32) {
	if rtt > 0x7FFFFFFF {
		return
	}
	this.Lock()
	defer this.Unlock()

	// https://tools.ietf.org/html/rfc6298
	if this.srtt == 0 {
		this.srtt = rtt
		this.variation = rtt / 2
	} else {
		delta := rtt - this.srtt
		if this.srtt > rtt {
			delta = this.srtt - rtt
		}
		this.variation = (3*this.variation + delta) / 4
		this.srtt = (7*this.srtt + rtt) / 8
		if this.srtt < this.minRtt {
			this.srtt = this.minRtt
		}
	}
	var rto uint32
	if this.minRtt < 4*this.variation {
		rto = this.srtt + 4*this.variation
	} else {
		rto = this.srtt + this.variation
	}

	if rto > 10000 {
		rto = 10000
	}
	this.rto = rto * 3 / 2
}

func (this *RountTripInfo) Timeout() uint32 {
	this.RLock()
	defer this.RUnlock()

	return this.rto
}

func (this *RountTripInfo) SmoothedTime() uint32 {
	this.RLock()
	defer this.RUnlock()

	return this.srtt
}

// Connection is a KCP connection over UDP.
type Connection struct {
	block          Authenticator
	local, remote  net.Addr
	rd             time.Time
	wd             time.Time // write deadline
	writer         io.WriteCloser
	since          int64
	dataInputCond  *sync.Cond
	dataOutputCond *sync.Cond

	conv             uint16
	state            State
	stateBeginTime   uint32
	lastIncomingTime uint32
	lastPingTime     uint32

	mss       uint32
	roundTrip *RountTripInfo
	interval  uint32

	receivingWorker *ReceivingWorker
	sendingWorker   *SendingWorker

	fastresend        uint32
	congestionControl bool
	output            *BufferedSegmentWriter
}

// NewConnection create a new KCP connection between local and remote.
func NewConnection(conv uint16, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *Connection {
	log.Info("KCP|Connection: creating connection ", conv)

	conn := new(Connection)
	conn.local = local
	conn.remote = remote
	conn.block = block
	conn.writer = writerCloser
	conn.since = nowMillisec()
	conn.dataInputCond = sync.NewCond(new(sync.Mutex))
	conn.dataOutputCond = sync.NewCond(new(sync.Mutex))

	authWriter := &AuthenticationWriter{
		Authenticator: block,
		Writer:        writerCloser,
	}
	conn.conv = conv
	conn.output = NewSegmentWriter(authWriter)

	conn.mss = authWriter.Mtu() - DataSegmentOverhead
	conn.roundTrip = &RountTripInfo{
		rto:    100,
		minRtt: effectiveConfig.Tti,
	}
	conn.interval = effectiveConfig.Tti
	conn.receivingWorker = NewReceivingWorker(conn)
	conn.fastresend = 2
	conn.congestionControl = effectiveConfig.Congestion
	conn.sendingWorker = NewSendingWorker(conn)

	go conn.updateTask()

	return conn
}

func (this *Connection) Elapsed() uint32 {
	return uint32(nowMillisec() - this.since)
}

// Read implements the Conn Read method.
func (this *Connection) Read(b []byte) (int, error) {
	if this == nil {
		return 0, io.EOF
	}

	for {
		if this.State() == StateReadyToClose || this.State() == StateTerminating || this.State() == StateTerminated {
			return 0, io.EOF
		}
		nBytes := this.receivingWorker.Read(b)
		if nBytes > 0 {
			return nBytes, nil
		}

		if this.State() == StatePeerTerminating {
			return 0, io.EOF
		}

		var timer *time.Timer
		if !this.rd.IsZero() {
			duration := this.rd.Sub(time.Now())
			if duration <= 0 {
				return 0, errTimeout
			}
			timer = time.AfterFunc(duration, this.dataInputCond.Signal)
		}
		this.dataInputCond.L.Lock()
		this.dataInputCond.Wait()
		this.dataInputCond.L.Unlock()
		if timer != nil {
			timer.Stop()
		}
		if !this.rd.IsZero() && this.rd.Before(time.Now()) {
			return 0, errTimeout
		}
	}
}

// Write implements the Conn Write method.
func (this *Connection) Write(b []byte) (int, error) {
	if this == nil || this.State() != StateActive {
		return 0, io.ErrClosedPipe
	}
	totalWritten := 0

	for {
		if this == nil || this.State() != StateActive {
			return totalWritten, io.ErrClosedPipe
		}

		nBytes := this.sendingWorker.Push(b[totalWritten:])
		if nBytes > 0 {
			totalWritten += nBytes
			if totalWritten == len(b) {
				return totalWritten, nil
			}
		}

		var timer *time.Timer
		if !this.wd.IsZero() {
			duration := this.wd.Sub(time.Now())
			if duration <= 0 {
				return totalWritten, errTimeout
			}
			timer = time.AfterFunc(duration, this.dataOutputCond.Signal)
		}
		this.dataOutputCond.L.Lock()
		this.dataOutputCond.Wait()
		this.dataOutputCond.L.Unlock()

		if timer != nil {
			timer.Stop()
		}

		if !this.wd.IsZero() && this.wd.Before(time.Now()) {
			return totalWritten, errTimeout
		}
	}
}

func (this *Connection) SetState(state State) {
	current := this.Elapsed()
	atomic.StoreInt32((*int32)(&this.state), int32(state))
	atomic.StoreUint32(&this.stateBeginTime, current)
	log.Debug("KCP|Connection: #", this.conv, " entering state ", state, " at ", current)

	switch state {
	case StateReadyToClose:
		this.receivingWorker.CloseRead()
	case StatePeerClosed:
		this.sendingWorker.CloseWrite()
	case StateTerminating:
		this.receivingWorker.CloseRead()
		this.sendingWorker.CloseWrite()
	case StatePeerTerminating:
		this.sendingWorker.CloseWrite()
	case StateTerminated:
		this.receivingWorker.CloseRead()
		this.sendingWorker.CloseWrite()
	}
}

// Close closes the connection.
func (this *Connection) Close() error {
	if this == nil {
		return errClosedConnection
	}

	this.dataInputCond.Broadcast()
	this.dataOutputCond.Broadcast()

	state := this.State()
	if state == StateReadyToClose ||
		state == StateTerminating ||
		state == StateTerminated {
		return errClosedConnection
	}
	log.Info("KCP|Connection: Closing connection to ", this.remote)

	if state == StateActive {
		this.SetState(StateReadyToClose)
	}
	if state == StatePeerClosed {
		this.SetState(StateTerminating)
	}
	if state == StatePeerTerminating {
		this.SetState(StateTerminated)
	}

	return nil
}

// LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
func (this *Connection) LocalAddr() net.Addr {
	if this == nil {
		return nil
	}
	return this.local
}

// RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
func (this *Connection) RemoteAddr() net.Addr {
	if this == nil {
		return nil
	}
	return this.remote
}

// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
func (this *Connection) SetDeadline(t time.Time) error {
	if err := this.SetReadDeadline(t); err != nil {
		return err
	}
	if err := this.SetWriteDeadline(t); err != nil {
		return err
	}
	return nil
}

// SetReadDeadline implements the Conn SetReadDeadline method.
func (this *Connection) SetReadDeadline(t time.Time) error {
	if this == nil || this.State() != StateActive {
		return errClosedConnection
	}
	this.rd = t
	return nil
}

// SetWriteDeadline implements the Conn SetWriteDeadline method.
func (this *Connection) SetWriteDeadline(t time.Time) error {
	if this == nil || this.State() != StateActive {
		return errClosedConnection
	}
	this.wd = t
	return nil
}

// kcp update, input loop
func (this *Connection) updateTask() {
	for this.State() != StateTerminated {
		this.flush()

		interval := time.Duration(effectiveConfig.Tti) * time.Millisecond
		if this.State() == StateTerminating {
			interval = time.Second
		}
		time.Sleep(interval)
	}
	this.Terminate()
}

func (this *Connection) FetchInputFrom(conn io.Reader) {
	go func() {
		payload := alloc.NewLocalBuffer(2048)
		defer payload.Release()
		for {
			payload.Reset()
			nBytes, err := conn.Read(payload.Value)
			if err != nil {
				return
			}
			payload.Slice(0, nBytes)
			if this.block.Open(payload) {
				this.Input(payload.Value)
			}
		}
	}()
}

func (this *Connection) Reusable() bool {
	return false
}

func (this *Connection) SetReusable(b bool) {}

func (this *Connection) Terminate() {
	if this == nil || this.writer == nil {
		return
	}
	log.Info("KCP|Connection: Terminating connection to ", this.RemoteAddr())

	this.writer.Close()
}

func (this *Connection) HandleOption(opt SegmentOption) {
	if (opt & SegmentOptionClose) == SegmentOptionClose {
		this.OnPeerClosed()
	}
}

func (this *Connection) OnPeerClosed() {
	state := this.State()
	if state == StateReadyToClose {
		this.SetState(StateTerminating)
	}
	if state == StateActive {
		this.SetState(StatePeerClosed)
	}
}

// Input when you received a low level packet (eg. UDP packet), call it
func (this *Connection) Input(data []byte) int {
	current := this.Elapsed()
	atomic.StoreUint32(&this.lastIncomingTime, current)

	var seg Segment
	for {
		seg, data = ReadSegment(data)
		if seg == nil {
			break
		}

		switch seg := seg.(type) {
		case *DataSegment:
			this.HandleOption(seg.Option)
			this.receivingWorker.ProcessSegment(seg)
			this.dataInputCond.Signal()
		case *AckSegment:
			this.HandleOption(seg.Option)
			this.sendingWorker.ProcessSegment(current, seg)
			this.dataOutputCond.Signal()
		case *CmdOnlySegment:
			this.HandleOption(seg.Option)
			if seg.Command == CommandTerminate {
				state := this.State()
				if state == StateActive ||
					state == StatePeerClosed {
					this.SetState(StatePeerTerminating)
				} else if state == StateReadyToClose {
					this.SetState(StateTerminating)
				} else if state == StateTerminating {
					this.SetState(StateTerminated)
				}
			}
			this.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
			this.receivingWorker.ProcessSendingNext(seg.SendingNext)
			seg.Release()
		default:
		}
	}

	return 0
}

func (this *Connection) flush() {
	current := this.Elapsed()

	if this.State() == StateTerminated {
		return
	}
	if this.State() == StateActive && current-atomic.LoadUint32(&this.lastIncomingTime) >= 30000 {
		this.Close()
	}
	if this.State() == StateReadyToClose && this.sendingWorker.IsEmpty() {
		this.SetState(StateTerminating)
	}

	if this.State() == StateTerminating {
		log.Debug("KCP|Connection: #", this.conv, " sending terminating cmd.")
		seg := NewCmdOnlySegment()
		defer seg.Release()

		seg.Conv = this.conv
		seg.Command = CommandTerminate
		this.output.Write(seg)
		this.output.Flush()

		if current-atomic.LoadUint32(&this.stateBeginTime) > 8000 {
			this.SetState(StateTerminated)
		}
		return
	}
	if this.State() == StatePeerTerminating && current-atomic.LoadUint32(&this.stateBeginTime) > 4000 {
		this.SetState(StateTerminating)
	}

	if this.State() == StateReadyToClose && current-atomic.LoadUint32(&this.stateBeginTime) > 15000 {
		this.SetState(StateTerminating)
	}

	// flush acknowledges
	this.receivingWorker.Flush(current)
	this.sendingWorker.Flush(current)

	if this.sendingWorker.PingNecessary() || this.receivingWorker.PingNecessary() || current-atomic.LoadUint32(&this.lastPingTime) >= 5000 {
		seg := NewCmdOnlySegment()
		seg.Conv = this.conv
		seg.Command = CommandPing
		seg.ReceivinNext = this.receivingWorker.nextNumber
		seg.SendingNext = this.sendingWorker.firstUnacknowledged
		if this.State() == StateReadyToClose {
			seg.Option = SegmentOptionClose
		}
		this.output.Write(seg)
		this.lastPingTime = current
		this.sendingWorker.MarkPingNecessary(false)
		this.receivingWorker.MarkPingNecessary(false)
		seg.Release()
	}

	// flash remain segments
	this.output.Flush()
}

func (this *Connection) State() State {
	return State(atomic.LoadInt32((*int32)(&this.state)))
}
<commit_msg>simplify state checking<commit_after>package kcp

import (
	"errors"
	"io"
	"net"
	"sync"
	"sync/atomic"
	"time"

	"github.com/v2ray/v2ray-core/common/alloc"
	"github.com/v2ray/v2ray-core/common/log"
)

var (
	errTimeout          = errors.New("i/o timeout")
	errBrokenPipe       = errors.New("broken pipe")
	errClosedListener   = errors.New("Listener closed.")
	errClosedConnection = errors.New("Connection closed.")
)

type State int32

func (this State) Is(states ...State) bool {
	for _, state := range states {
		if this == state {
			return true
		}
	}
	return false
}

const (
	StateActive          State = 0
	StateReadyToClose    State = 1
	StatePeerClosed      State = 2
	StateTerminating     State = 3
	StatePeerTerminating State = 4
	StateTerminated      State = 5
)

const (
	headerSize uint32 = 2
)

func nowMillisec() int64 {
	now := time.Now()
	return now.Unix()*1000 + int64(now.Nanosecond()/1000000)
}

type RountTripInfo struct {
	sync.RWMutex
	variation uint32
	srtt      uint32
	rto       uint32
	minRtt    uint32
}

func (this *RountTripInfo) Update(rtt uint32) {
	if rtt > 0x7FFFFFFF {
		return
	}
	this.Lock()
	defer this.Unlock()

	// https://tools.ietf.org/html/rfc6298
	if this.srtt == 0 {
		this.srtt = rtt
		this.variation = rtt / 2
	} else {
		delta := rtt - this.srtt
		if this.srtt > rtt {
			delta = this.srtt - rtt
		}
		this.variation = (3*this.variation + delta) / 4
		this.srtt = (7*this.srtt + rtt) / 8
		if this.srtt < this.minRtt {
			this.srtt = this.minRtt
		}
	}
	var rto uint32
	if this.minRtt < 4*this.variation {
		rto = this.srtt + 4*this.variation
	} else {
		rto = this.srtt + this.variation
	}

	if rto > 10000 {
		rto = 10000
	}
	this.rto = rto * 3 / 2
}

func (this *RountTripInfo) Timeout() uint32 {
	this.RLock()
	defer this.RUnlock()

	return this.rto
}

func (this *RountTripInfo) SmoothedTime() uint32 {
	this.RLock()
	defer this.RUnlock()

	return this.srtt
}

// Connection is a KCP connection over UDP.
type Connection struct {
	block          Authenticator
	local, remote  net.Addr
	rd             time.Time
	wd             time.Time // write deadline
	writer         io.WriteCloser
	since          int64
	dataInputCond  *sync.Cond
	dataOutputCond *sync.Cond

	conv             uint16
	state            State
	stateBeginTime   uint32
	lastIncomingTime uint32
	lastPingTime     uint32

	mss       uint32
	roundTrip *RountTripInfo
	interval  uint32

	receivingWorker *ReceivingWorker
	sendingWorker   *SendingWorker

	fastresend        uint32
	congestionControl bool
	output            *BufferedSegmentWriter
}

// NewConnection create a new KCP connection between local and remote.
func NewConnection(conv uint16, writerCloser io.WriteCloser, local *net.UDPAddr, remote *net.UDPAddr, block Authenticator) *Connection {
	log.Info("KCP|Connection: creating connection ", conv)

	conn := new(Connection)
	conn.local = local
	conn.remote = remote
	conn.block = block
	conn.writer = writerCloser
	conn.since = nowMillisec()
	conn.dataInputCond = sync.NewCond(new(sync.Mutex))
	conn.dataOutputCond = sync.NewCond(new(sync.Mutex))

	authWriter := &AuthenticationWriter{
		Authenticator: block,
		Writer:        writerCloser,
	}
	conn.conv = conv
	conn.output = NewSegmentWriter(authWriter)

	conn.mss = authWriter.Mtu() - DataSegmentOverhead
	conn.roundTrip = &RountTripInfo{
		rto:    100,
		minRtt: effectiveConfig.Tti,
	}
	conn.interval = effectiveConfig.Tti
	conn.receivingWorker = NewReceivingWorker(conn)
	conn.fastresend = 2
	conn.congestionControl = effectiveConfig.Congestion
	conn.sendingWorker = NewSendingWorker(conn)

	go conn.updateTask()

	return conn
}

func (this *Connection) Elapsed() uint32 {
	return uint32(nowMillisec() - this.since)
}

// Read implements the Conn Read method.
func (this *Connection) Read(b []byte) (int, error) {
	if this == nil {
		return 0, io.EOF
	}

	for {
		if this.State().Is(StateReadyToClose, StateTerminating, StateTerminated) {
			return 0, io.EOF
		}
		nBytes := this.receivingWorker.Read(b)
		if nBytes > 0 {
			return nBytes, nil
		}

		if this.State() == StatePeerTerminating {
			return 0, io.EOF
		}

		var timer *time.Timer
		if !this.rd.IsZero() {
			duration := this.rd.Sub(time.Now())
			if duration <= 0 {
				return 0, errTimeout
			}
			timer = time.AfterFunc(duration, this.dataInputCond.Signal)
		}
		this.dataInputCond.L.Lock()
		this.dataInputCond.Wait()
		this.dataInputCond.L.Unlock()
		if timer != nil {
			timer.Stop()
		}
		if !this.rd.IsZero() && this.rd.Before(time.Now()) {
			return 0, errTimeout
		}
	}
}

// Write implements the Conn Write method.
func (this *Connection) Write(b []byte) (int, error) {
	totalWritten := 0

	for {
		if this == nil || this.State() != StateActive {
			return totalWritten, io.ErrClosedPipe
		}

		nBytes := this.sendingWorker.Push(b[totalWritten:])
		if nBytes > 0 {
			totalWritten += nBytes
			if totalWritten == len(b) {
				return totalWritten, nil
			}
		}

		var timer *time.Timer
		if !this.wd.IsZero() {
			duration := this.wd.Sub(time.Now())
			if duration <= 0 {
				return totalWritten, errTimeout
			}
			timer = time.AfterFunc(duration, this.dataOutputCond.Signal)
		}
		this.dataOutputCond.L.Lock()
		this.dataOutputCond.Wait()
		this.dataOutputCond.L.Unlock()

		if timer != nil {
			timer.Stop()
		}

		if !this.wd.IsZero() && this.wd.Before(time.Now()) {
			return totalWritten, errTimeout
		}
	}
}

func (this *Connection) SetState(state State) {
	current := this.Elapsed()
	atomic.StoreInt32((*int32)(&this.state), int32(state))
	atomic.StoreUint32(&this.stateBeginTime, current)
	log.Debug("KCP|Connection: #", this.conv, " entering state ", state, " at ", current)

	switch state {
	case StateReadyToClose:
		this.receivingWorker.CloseRead()
	case StatePeerClosed:
		this.sendingWorker.CloseWrite()
	case StateTerminating:
		this.receivingWorker.CloseRead()
		this.sendingWorker.CloseWrite()
	case StatePeerTerminating:
		this.sendingWorker.CloseWrite()
	case StateTerminated:
		this.receivingWorker.CloseRead()
		this.sendingWorker.CloseWrite()
	}
}

// Close closes the connection.
func (this *Connection) Close() error {
	if this == nil {
		return errClosedConnection
	}

	this.dataInputCond.Broadcast()
	this.dataOutputCond.Broadcast()

	state := this.State()
	if state.Is(StateReadyToClose, StateTerminating, StateTerminated) {
		return errClosedConnection
	}
	log.Info("KCP|Connection: Closing connection to ", this.remote)

	if state == StateActive {
		this.SetState(StateReadyToClose)
	}
	if state == StatePeerClosed {
		this.SetState(StateTerminating)
	}
	if state == StatePeerTerminating {
		this.SetState(StateTerminated)
	}

	return nil
}

// LocalAddr returns the local network address. The Addr returned is shared by all invocations of LocalAddr, so do not modify it.
func (this *Connection) LocalAddr() net.Addr {
	if this == nil {
		return nil
	}
	return this.local
}

// RemoteAddr returns the remote network address. The Addr returned is shared by all invocations of RemoteAddr, so do not modify it.
func (this *Connection) RemoteAddr() net.Addr {
	if this == nil {
		return nil
	}
	return this.remote
}

// SetDeadline sets the deadline associated with the listener. A zero time value disables the deadline.
func (this *Connection) SetDeadline(t time.Time) error {
	if err := this.SetReadDeadline(t); err != nil {
		return err
	}
	if err := this.SetWriteDeadline(t); err != nil {
		return err
	}
	return nil
}

// SetReadDeadline implements the Conn SetReadDeadline method.
func (this *Connection) SetReadDeadline(t time.Time) error {
	if this == nil || this.State() != StateActive {
		return errClosedConnection
	}
	this.rd = t
	return nil
}

// SetWriteDeadline implements the Conn SetWriteDeadline method.
func (this *Connection) SetWriteDeadline(t time.Time) error {
	if this == nil || this.State() != StateActive {
		return errClosedConnection
	}
	this.wd = t
	return nil
}

// kcp update, input loop
func (this *Connection) updateTask() {
	for this.State() != StateTerminated {
		this.flush()

		interval := time.Duration(effectiveConfig.Tti) * time.Millisecond
		if this.State() == StateTerminating {
			interval = time.Second
		}
		time.Sleep(interval)
	}
	this.Terminate()
}

func (this *Connection) FetchInputFrom(conn io.Reader) {
	go func() {
		payload := alloc.NewLocalBuffer(2048)
		defer payload.Release()
		for {
			payload.Reset()
			nBytes, err := conn.Read(payload.Value)
			if err != nil {
				return
			}
			payload.Slice(0, nBytes)
			if this.block.Open(payload) {
				this.Input(payload.Value)
			}
		}
	}()
}

func (this *Connection) Reusable() bool {
	return false
}

func (this *Connection) SetReusable(b bool) {}

func (this *Connection) Terminate() {
	if this == nil || this.writer == nil {
		return
	}
	log.Info("KCP|Connection: Terminating connection to ", this.RemoteAddr())

	this.writer.Close()
}

func (this *Connection) HandleOption(opt SegmentOption) {
	if (opt & SegmentOptionClose) == SegmentOptionClose {
		this.OnPeerClosed()
	}
}

func (this *Connection) OnPeerClosed() {
	state := this.State()
	if state == StateReadyToClose {
		this.SetState(StateTerminating)
	}
	if state == StateActive {
		this.SetState(StatePeerClosed)
	}
}

// Input when you received a low level packet (eg. UDP packet), call it
func (this *Connection) Input(data []byte) int {
	current := this.Elapsed()
	atomic.StoreUint32(&this.lastIncomingTime, current)

	var seg Segment
	for {
		seg, data = ReadSegment(data)
		if seg == nil {
			break
		}

		switch seg := seg.(type) {
		case *DataSegment:
			this.HandleOption(seg.Option)
			this.receivingWorker.ProcessSegment(seg)
			this.dataInputCond.Signal()
		case *AckSegment:
			this.HandleOption(seg.Option)
			this.sendingWorker.ProcessSegment(current, seg)
			this.dataOutputCond.Signal()
		case *CmdOnlySegment:
			this.HandleOption(seg.Option)
			if seg.Command == CommandTerminate {
				state := this.State()
				if state == StateActive ||
					state == StatePeerClosed {
					this.SetState(StatePeerTerminating)
				} else if state == StateReadyToClose {
					this.SetState(StateTerminating)
				} else if state == StateTerminating {
					this.SetState(StateTerminated)
				}
			}
			this.sendingWorker.ProcessReceivingNext(seg.ReceivinNext)
			this.receivingWorker.ProcessSendingNext(seg.SendingNext)
			seg.Release()
		default:
		}
	}

	return 0
}

func (this *Connection) flush() {
	current := this.Elapsed()

	if this.State() == StateTerminated {
		return
	}
	if this.State() == StateActive && current-atomic.LoadUint32(&this.lastIncomingTime) >= 30000 {
		this.Close()
	}
	if this.State() == StateReadyToClose && this.sendingWorker.IsEmpty() {
		this.SetState(StateTerminating)
	}

	if this.State() == StateTerminating {
		log.Debug("KCP|Connection: #", this.conv, " sending terminating cmd.")
		seg := NewCmdOnlySegment()
		defer seg.Release()

		seg.Conv = this.conv
		seg.Command = CommandTerminate
		this.output.Write(seg)
		this.output.Flush()

		if current-atomic.LoadUint32(&this.stateBeginTime) > 8000 {
			this.SetState(StateTerminated)
		}
		return
	}
	if this.State() == StatePeerTerminating && current-atomic.LoadUint32(&this.stateBeginTime) > 4000 {
		this.SetState(StateTerminating)
	}

	if this.State() == StateReadyToClose && current-atomic.LoadUint32(&this.stateBeginTime) > 15000 {
		this.SetState(StateTerminating)
	}

	// flush acknowledges
	this.receivingWorker.Flush(current)
	this.sendingWorker.Flush(current)

	if this.sendingWorker.PingNecessary() || this.receivingWorker.PingNecessary() || current-atomic.LoadUint32(&this.lastPingTime) >= 5000 {
		seg := NewCmdOnlySegment()
		seg.Conv = this.conv
		seg.Command = CommandPing
		seg.ReceivinNext = this.receivingWorker.nextNumber
		seg.SendingNext = this.sendingWorker.firstUnacknowledged
		if this.State() == StateReadyToClose {
			seg.Option = SegmentOptionClose
		}
		this.output.Write(seg)
		this.lastPingTime = current
		this.sendingWorker.MarkPingNecessary(false)
		this.receivingWorker.MarkPingNecessary(false)
		seg.Release()
	}

	// flash remain segments
	this.output.Flush()
}

func (this *Connection) State() State {
	return State(atomic.LoadInt32((*int32)(&this.state)))
}
<|endoftext|>


<commit_before>// package multistream implements a peerstream transport using
// go-multistream to select the underlying stream muxer
package multistream

import (
	"net"

	pst "github.com/jbenet/go-peerstream/transport"
	spdy "github.com/jbenet/go-peerstream/transport/spdystream"
	yamux "github.com/jbenet/go-peerstream/transport/spdystream"
	mss "github.com/whyrusleeping/go-multistream"
)

type transport struct {
	mux *mss.MultistreamMuxer

	tpts map[string]pst.Transport
}

func NewTransport() pst.Transport {
	mux := mss.NewMultistreamMuxer()
	mux.AddHandler("/spdystream", nil)
	mux.AddHandler("/yamux", nil)

	tpts := map[string]pst.Transport{
		"/spdystream": spdy.Transport,
		"/yamux":      yamux.Transport,
	}

	return &transport{
		mux:  mux,
		tpts: tpts,
	}
}

func (t *transport) NewConn(nc net.Conn, isServer bool) (pst.Conn, error) {
	var proto string
	if isServer {
		selected, _, err := t.mux.Negotiate(nc)
		if err != nil {
			return nil, err
		}
		proto = selected
	} else {
		// prefer yamux
		selected, err := mss.SelectOneOf([]string{"/yamux", "/spdystream"}, nc)
		if err != nil {
			return nil, err
		}
		proto = selected
	}

	tpt := t.tpts[proto]

	return tpt.NewConn(nc, isServer)
}
<commit_msg>actually use yamux<commit_after>// package multistream implements a peerstream transport using
// go-multistream to select the underlying stream muxer
package multistream

import (
	"net"

	pst "github.com/jbenet/go-peerstream/transport"
	spdy "github.com/jbenet/go-peerstream/transport/spdystream"
	yamux "github.com/jbenet/go-peerstream/transport/yamux"
	mss "github.com/whyrusleeping/go-multistream"
)

type transport struct {
	mux *mss.MultistreamMuxer

	tpts map[string]pst.Transport
}

func NewTransport() pst.Transport {
	mux := mss.NewMultistreamMuxer()
	mux.AddHandler("/spdystream", nil)
	mux.AddHandler("/yamux", nil)

	tpts := map[string]pst.Transport{
		"/spdystream": spdy.Transport,
		"/yamux":      yamux.DefaultTransport,
	}

	return &transport{
		mux:  mux,
		tpts: tpts,
	}
}

func (t *transport) NewConn(nc net.Conn, isServer bool) (pst.Conn, error) {
	var proto string
	if isServer {
		selected, _, err := t.mux.Negotiate(nc)
		if err != nil {
			return nil, err
		}
		proto = selected
	} else {
		// prefer yamux
		selected, err := mss.SelectOneOf([]string{"/yamux", "/spdystream"}, nc)
		if err != nil {
			return nil, err
		}
		proto = selected
	}

	tpt := t.tpts[proto]

	return tpt.NewConn(nc, isServer)
}
<|endoftext|>


<commit_before><commit_msg>Update amqp.go<commit_after><|endoftext|>


<commit_before>package types

//import (
//    "testing"
//    "bitgirder/assert"
//    "bitgirder/objpath"
//    mg "mingle"
//)
//
//type ReactorTestCall struct { *mg.ReactorTestCall }
//
//func ( tc *ReactorTestCall ) callCast( ct *CastReactorTest ) {
//    rct := NewCastReactorDefinitionMap( ct.Type, ct.Map )
//    vb := mg.NewValueBuilder()
//    pip := mg.InitReactorPipeline( rct, vb )
//    tc.Logf( "casting %s as %s", mg.QuoteValue( ct.In ), ct.Type )
//    if err := mg.VisitValue( ct.In, pip ); err == nil {
//        tc.CheckNoError( ct.Err )
//        tc.Logf( "expecting %s, got %s", mg.QuoteValue( ct.Expect ),
//            mg.QuoteValue( vb.GetValue() ) )
//        mg.EqualValues( ct.Expect, vb.GetValue(), tc )
//    } else {
//        cae := mg.CastErrorAssert{
//            ErrExpect: ct.Err, ErrAct: err, PathAsserter: tc.PathAsserter }
//        cae.Call()
//    }
//}
//
//func ( tc *ReactorTestCall ) callEventPath( t *EventPathTest ) {
//    chk := mg.NewEventPathCheckReactor( t.Expect, tc.PathAsserter )
//    rct := NewCastReactorDefinitionMap( t.Type, t.Map )
//    pip := mg.InitReactorPipeline( rct, chk )
//    mg.AssertFeedSource( t.Source, pip, tc )
//    chk.Complete()
//}
//
//type checker interface { check() }
//
//func ( tc *ReactorTestCall ) visitAndCheck(
//    in mg.Value, rep mg.ReactorEventProcessor, chk checker, errExpct error ) {
//
//    if err := mg.VisitValue( in, rep ); err == nil {
//        tc.CheckNoError( errExpct )
//        chk.check()
//    } else { tc.EqualErrors( errExpct, err ) }
//}
//
//func initValueBuilder(
//    vbPtr **mg.ValueBuilder ) ( mg.ReactorEventProcessor, error ) {
//
//    *vbPtr = mg.NewValueBuilder()
//    return *vbPtr, nil
//}
//
//type requestCheck struct {
//    *assert.PathAsserter
//    st *ServiceRequestTest
//    auth *mg.ValueBuilder
//    params *mg.ValueBuilder
//}
//
//func ( chk *requestCheck ) GetAuthenticationReactor(
//    path objpath.PathNode ) ( mg.ReactorEventProcessor, error ) {
//
//    return initValueBuilder( &( chk.auth ) )
//}
//
//func ( chk *requestCheck ) GetParametersReactor(
//    path objpath.PathNode ) ( mg.ReactorEventProcessor, error ) {
//
//    return initValueBuilder( &( chk.params ) )
//}
//
//func ( chk *requestCheck ) check() {
//    mg.CheckBuiltValue(
//        chk.st.Authentication, chk.auth, chk.Descend( "authentication" ) )
//    mg.CheckBuiltValue(
//        chk.st.Parameters, chk.params, chk.Descend( "parameters" ) )
//}
//
//func ( tc *ReactorTestCall ) callServiceRequest( st *ServiceRequestTest ) {
//    chk := &requestCheck{ st: st, PathAsserter: tc.PathAsserter }
//    rct := NewRequestReactor( st.Maps.BuildOpMap(), chk )
//    pip := mg.InitReactorPipeline( rct )
//    tc.visitAndCheck( st.In, pip, chk, st.Error )
//}
//
//type responseCheck struct {
//    st *ServiceResponseTest
//    *assert.PathAsserter
//    resultProc, errorProc *mg.ValueBuilder
//}
//
//func ( chk *responseCheck ) GetResultReactor(
//    p objpath.PathNode ) ( mg.ReactorEventProcessor, error ) {
//
//    return initValueBuilder( &( chk.resultProc ) )
//}
//
//func ( chk *responseCheck ) GetErrorReactor(
//    p objpath.PathNode ) ( mg.ReactorEventProcessor, error ) {
//
//    return initValueBuilder( &( chk.errorProc ) )
//}
//
//func ( chk *responseCheck ) check() {
//    mg.CheckBuiltValue(
//        chk.st.ResultValue, chk.resultProc, chk.Descend( "result" ) )
//    mg.CheckBuiltValue(
//        chk.st.ErrorValue, chk.errorProc, chk.Descend( "error" ) )
//}
//
//func ( tc *ReactorTestCall ) callServiceResponse( st *ServiceResponseTest ) {
//    chk := &responseCheck{ st: st, PathAsserter: tc.PathAsserter }
//    svcDef := st.Definitions.MustGet( st.ServiceType ).( *ServiceDefinition )
//    opDef := svcDef.mustFindOperation( st.Operation )
//    rct := NewResponseReactor( st.Definitions, svcDef, opDef, chk )
//    pip := mg.InitReactorPipeline( rct )
//    tc.visitAndCheck( st.In, pip, chk, st.Error )
//}
//
//func ( tc *ReactorTestCall ) call() {
//    tc.Logf( "Calling test of type %T", tc.Test )
//    switch v := tc.Test.( type ) {
//    case *CastReactorTest: tc.callCast( v )
//    case *EventPathTest: tc.callEventPath( v )
//    case *ServiceRequestTest: tc.callServiceRequest( v )
//    case *ServiceResponseTest: tc.callServiceResponse( v )
//    default: panic( libErrorf( "Unhandled test type: %T", tc.Test ) )
//    }
//}
//
//func TestReactors( t *testing.T ) {
//    a := assert.NewListPathAsserter( t )
//    for _, rt := range GetStdReactorTests() {
//        tc := &ReactorTestCall{
//            ReactorTestCall: &mg.ReactorTestCall{
//                PathAsserter: a,
//                Test: rt,
//            },
//        }
//        tc.call()
//        a = a.Next()
//    }
//}
<commit_msg>removing dead reactor test code<commit_after><|endoftext|>