<commit_before>package veyron2

import (
	"time"

	"veyron2/ipc/stream"
	"veyron2/naming"
	"veyron2/product"
	"veyron2/security"
)

// Below are the common options required of all veyron implementations.  Let's
// say we have functions MyFuncA and MyFuncB in package demo:
//
//   package demo
//   func MyFuncA(a, b, c int, opts ...MyFuncAOpt)
//   func MyFuncB(opts ...MyFuncBOpt)
//
//   type MyFuncAOpt interface {
//     DemoMyFuncAOpt()
//   }
//   type MyFuncBOpt interface {
//     DemoMyFuncBOpt()
//   }
//
// The MyFuncAOpt interface is used solely to constrain the types of options
// that MyFuncA accepts, and ditto for MyFuncBOpt and MyFuncB.  In order to
// enable an option to be accepted by a particular function, you simply add a
// no-op function definition with the appropriate name.  An example:
//
//   type FooOption int
//   func (FooOption) DemoMyFuncAOpt() {}
//   func (FooOption) DemoMyFuncBOpt() {}
//
//   type BarOption string
//   func (FooOption) DemoMyFuncBOpt() {}
//
// FooOption is accepted by both demo.MyFuncA and demo.MyFuncB, while BarOption
// is only accepted by demo.MyFuncB.  The methods defined for each option
// essentially act as annotations telling us which functions will accept them.
//
// Go stipulates that methods may only be attached to named types, and the type
// may not be an interface.  E.g.
//
//   // BAD: can't attach methods to named interfaces.
//   type BadOption interface{}
//   func (BadOption) DemoMyFuncAOpt() {}
//
//   // GOOD: wrap the interface in a named struct with a helper function.
//   func GoodOption(val interface{}) GoodOptionOpt {
//     return GoodOptionOpt{val}
//   }
//   type GoodOptionOpt struct {
//     val interface{}
//   }
//   func (GoodOption) DemoMyFuncAOpt() {}
//
// The helper function ensures that the caller ends up with the same syntax for
// creating options, e.g. here's some examples of using the options:
//
//   demo.MyFuncA(1, 2, 3, FooOption(5), GoodOption("good"))
//   demo.MyFuncB(FooOption(9), BarOption("bar"))

// LocalIDOpt represents the identity of the local process.
//
// It wraps the security.PrivateID interface so that functions representing
// option annotations can be added.
type LocalIDOpt struct{ security.PrivateID }

func (LocalIDOpt) IPCClientOpt()         {}
func (LocalIDOpt) IPCServerOpt()         {}
func (LocalIDOpt) IPCStreamVCOpt()       {}
func (LocalIDOpt) IPCStreamListenerOpt() {}
func (LocalIDOpt) ROpt()                 {}

// LocalID specifies the identity of the local process.
func LocalID(id security.PrivateID) LocalIDOpt { return LocalIDOpt{id} }

// RemoteID specifies a pattern identifying the set of valid remote identities for
// a call.
type RemoteID security.PrincipalPattern

func (RemoteID) IPCClientCallOpt() {}

// VCSecurityLevel represents the level of confidentiality of data transmitted
// and received over a VC.
type VCSecurityLevel int

func (VCSecurityLevel) IPCClientOpt()         {}
func (VCSecurityLevel) IPCServerOpt()         {}
func (VCSecurityLevel) IPCStreamVCOpt()       {}
func (VCSecurityLevel) IPCStreamListenerOpt() {}

const (
	// All user data transmitted over the VC is encrypted and can be interpreted only
	// by processes at the two ends of the VC.
	// This is the default level.
	VCSecurityConfidential VCSecurityLevel = 0
	// Data is transmitted over the VC in plain text and there is no authentication.
	VCSecurityNone VCSecurityLevel = 1
)

// CallTimeout specifies the timeout for Call.
type CallTimeout time.Duration

func (CallTimeout) IPCClientCallOpt() {}
func (CallTimeout) IPCClientOpt()     {}

// StreamManager specifies an explicit stream.Manager.
func StreamManager(sm stream.Manager) StreamManagerOpt {
	return StreamManagerOpt{sm}
}

// StreamManagerOpt wraps the stream.Manager interface so that we can add
// functions representing the option annotations.
type StreamManagerOpt struct{ stream.Manager }

func (StreamManagerOpt) IPCClientOpt() {}
func (StreamManagerOpt) IPCServerOpt() {}

// MountTable specifies an explicit naming.MountTable.
func MountTable(mt naming.MountTable) MountTableOpt {
	return MountTableOpt{mt}
}

// MountTableOpt wraps the naming.MountTable interface so that we can add
// functions representing the option annotations.
type MountTableOpt struct{ naming.MountTable }

func (MountTableOpt) IPCClientOpt() {}
func (MountTableOpt) IPCServerOpt() {}

// MountTableRoots wraps an array of strings so that we specify the root
// of the mounttable when initializing the runtime.
type MountTableRoots []string

func (MountTableRoots) ROpt() {}

// RuntimeOpt wraps the Runtime interface so that we can add
// functions representing the option annotations.
type RuntimeOpt struct{ Runtime }

func (RuntimeOpt) IPCBindOpt() {}

// ProductOpt wraps the product.T interface so that we can add
// functions representing the option annotations
type ProductOpt struct{ product.T }

func (ProductOpt) ROpt() {}

// HTTPDebugOpt specifies the address on which an HTTP server will be run for
// debugging the process.
type HTTPDebugOpt string

func (HTTPDebugOpt) ROpt() {}
<commit_msg>veyron/runtimes/google/ipc: add options to ipc server constructor to control which endpoints to mount when publishing, and to allow for endpoint rewrite.<commit_after>package veyron2

import (
	"time"

	"veyron2/ipc/stream"
	"veyron2/naming"
	"veyron2/product"
	"veyron2/security"
)

// Below are the common options required of all veyron implementations.  Let's
// say we have functions MyFuncA and MyFuncB in package demo:
//
//   package demo
//   func MyFuncA(a, b, c int, opts ...MyFuncAOpt)
//   func MyFuncB(opts ...MyFuncBOpt)
//
//   type MyFuncAOpt interface {
//     DemoMyFuncAOpt()
//   }
//   type MyFuncBOpt interface {
//     DemoMyFuncBOpt()
//   }
//
// The MyFuncAOpt interface is used solely to constrain the types of options
// that MyFuncA accepts, and ditto for MyFuncBOpt and MyFuncB.  In order to
// enable an option to be accepted by a particular function, you simply add a
// no-op function definition with the appropriate name.  An example:
//
//   type FooOption int
//   func (FooOption) DemoMyFuncAOpt() {}
//   func (FooOption) DemoMyFuncBOpt() {}
//
//   type BarOption string
//   func (FooOption) DemoMyFuncBOpt() {}
//
// FooOption is accepted by both demo.MyFuncA and demo.MyFuncB, while BarOption
// is only accepted by demo.MyFuncB.  The methods defined for each option
// essentially act as annotations telling us which functions will accept them.
//
// Go stipulates that methods may only be attached to named types, and the type
// may not be an interface.  E.g.
//
//   // BAD: can't attach methods to named interfaces.
//   type BadOption interface{}
//   func (BadOption) DemoMyFuncAOpt() {}
//
//   // GOOD: wrap the interface in a named struct with a helper function.
//   func GoodOption(val interface{}) GoodOptionOpt {
//     return GoodOptionOpt{val}
//   }
//   type GoodOptionOpt struct {
//     val interface{}
//   }
//   func (GoodOption) DemoMyFuncAOpt() {}
//
// The helper function ensures that the caller ends up with the same syntax for
// creating options, e.g. here's some examples of using the options:
//
//   demo.MyFuncA(1, 2, 3, FooOption(5), GoodOption("good"))
//   demo.MyFuncB(FooOption(9), BarOption("bar"))

// LocalIDOpt represents the identity of the local process.
//
// It wraps the security.PrivateID interface so that functions representing
// option annotations can be added.
type LocalIDOpt struct{ security.PrivateID }

func (LocalIDOpt) IPCClientOpt()         {}
func (LocalIDOpt) IPCServerOpt()         {}
func (LocalIDOpt) IPCStreamVCOpt()       {}
func (LocalIDOpt) IPCStreamListenerOpt() {}
func (LocalIDOpt) ROpt()                 {}

// LocalID specifies the identity of the local process.
func LocalID(id security.PrivateID) LocalIDOpt { return LocalIDOpt{id} }

// RemoteID specifies a pattern identifying the set of valid remote identities for
// a call.
type RemoteID security.PrincipalPattern

func (RemoteID) IPCClientCallOpt() {}

// VCSecurityLevel represents the level of confidentiality of data transmitted
// and received over a VC.
type VCSecurityLevel int

func (VCSecurityLevel) IPCClientOpt()         {}
func (VCSecurityLevel) IPCServerOpt()         {}
func (VCSecurityLevel) IPCStreamVCOpt()       {}
func (VCSecurityLevel) IPCStreamListenerOpt() {}

const (
	// All user data transmitted over the VC is encrypted and can be interpreted only
	// by processes at the two ends of the VC.
	// This is the default level.
	VCSecurityConfidential VCSecurityLevel = 0
	// Data is transmitted over the VC in plain text and there is no authentication.
	VCSecurityNone VCSecurityLevel = 1
)

// CallTimeout specifies the timeout for Call.
type CallTimeout time.Duration

func (CallTimeout) IPCClientCallOpt() {}
func (CallTimeout) IPCClientOpt()     {}

// StreamManager specifies an explicit stream.Manager.
func StreamManager(sm stream.Manager) StreamManagerOpt {
	return StreamManagerOpt{sm}
}

// StreamManagerOpt wraps the stream.Manager interface so that we can add
// functions representing the option annotations.
type StreamManagerOpt struct{ stream.Manager }

func (StreamManagerOpt) IPCClientOpt() {}
func (StreamManagerOpt) IPCServerOpt() {}

// MountTable specifies an explicit naming.MountTable.
func MountTable(mt naming.MountTable) MountTableOpt {
	return MountTableOpt{mt}
}

// MountTableOpt wraps the naming.MountTable interface so that we can add
// functions representing the option annotations.
type MountTableOpt struct{ naming.MountTable }

func (MountTableOpt) IPCClientOpt() {}
func (MountTableOpt) IPCServerOpt() {}

// MountTableRoots wraps an array of strings so that we specify the root
// of the mounttable when initializing the runtime.
type MountTableRoots []string

func (MountTableRoots) ROpt() {}

// RuntimeOpt wraps the Runtime interface so that we can add
// functions representing the option annotations.
type RuntimeOpt struct{ Runtime }

func (RuntimeOpt) IPCBindOpt() {}

// ProductOpt wraps the product.T interface so that we can add
// functions representing the option annotations
type ProductOpt struct{ product.T }

func (ProductOpt) ROpt() {}

// HTTPDebugOpt specifies the address on which an HTTP server will be run for
// debugging the process.
type HTTPDebugOpt string

func (HTTPDebugOpt) ROpt() {}

// ServerPublishOpt tells the ipc server which of the endpoints it listens on
// should be published by Publish.
type ServerPublishOpt int

const (
	PublishAll   ServerPublishOpt = 0
	PublishFirst ServerPublishOpt = 1
)

func (ServerPublishOpt) IPCServerOpt() {}

// EndpointRewriteOpt specifies how to rewrite the address of the endpoints
// being listened on.  The rewrite only applies to tcp endpoints.  The value of
// the option is the rewritten host/ip portion of the address of the endpoint.
type EndpointRewriteOpt string

func (EndpointRewriteOpt) IPCServerOpt()         {}
func (EndpointRewriteOpt) IPCStreamListenerOpt() {}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"os"
	"sort"
	"strings"
)

const packageTemplateString = `<!DOCTYPE html>

		<meta charset="utf-8">
		<title>{{.Repo.PackageName}}.{{.Repo.MajorVersion}}{{.Repo.SubPath}} - {{.Repo.GopkgPath}}</title>
		<link href='//fonts.googleapis.com/css?family=Ubuntu+Mono|Ubuntu' rel='stylesheet' >
		<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet" >
		<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" >

{{.Repo.GopkgPath}}

						 Source Code
						 API Documentation

Getting started

To get the package, execute:

go get {{.Repo.GopkgPath}}

To import this package, add the following line to your code:

import "{{.Repo.GopkgPath}}"

								{{if .CleanPackageName}}
Refer to it as {{.CleanPackageName}}.{{end}}

For more details, see the API documentation.

Versions

						{{ if .LatestVersions }}
							{{ range .LatestVersions }}

									v{{.Major}}
									→
									{{.}}

							{{ end }}
						{{ else }}

								v0
								→
								master

						{{ end }}

gopkg.in

`

var packageTemplate *template.Template

func gopkgVersionRoot(repo *Repo, version Version) string {
	return repo.GopkgVersionRoot(version)
}

var packageFuncs = template.FuncMap{
	"gopkgVersionRoot": gopkgVersionRoot,
}

func init() {
	var err error
	packageTemplate, err = template.New("page").Funcs(packageFuncs).Parse(packageTemplateString)
	if err != nil {
		fmt.Fprintf(os.Stderr, "fatal: parsing package template failed: %s\n", err)
		os.Exit(1)
	}
}

type packageData struct {
	Repo             *Repo
	LatestVersions   VersionList // Contains only the latest version for each major
	FullVersion      Version     // Version that the major requested resolves to
	CleanPackageName string
}

func renderPackagePage(resp http.ResponseWriter, req *http.Request, repo *Repo) {
	data := &packageData{
		Repo: repo,
	}
	latestVersionsMap := make(map[int]Version)
	for _, v := range repo.AllVersions {
		v2, exists := latestVersionsMap[v.Major]
		if !exists || v2.Less(v) {
			latestVersionsMap[v.Major] = v
		}
	}
	data.FullVersion = latestVersionsMap[repo.MajorVersion.Major]
	data.LatestVersions = make(VersionList, 0, len(latestVersionsMap))
	for _, v := range latestVersionsMap {
		data.LatestVersions = append(data.LatestVersions, v)
	}
	sort.Sort(sort.Reverse(data.LatestVersions))

	data.CleanPackageName = repo.PackageName
	if strings.HasPrefix(data.CleanPackageName, "go-") {
		data.CleanPackageName = data.CleanPackageName[3:]
	}
	if strings.HasSuffix(data.CleanPackageName, "-go") {
		data.CleanPackageName = data.CleanPackageName[:len(data.CleanPackageName)-3]
	}
	for i, c := range data.CleanPackageName {
		if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' {
			continue
		}
		if i > 0 && (c == '_' || c >= '0' && c <= '9') {
			continue
		}
		data.CleanPackageName = ""
		break
	}

	err := packageTemplate.Execute(resp, data)
	if err != nil {
		log.Printf("error executing tmplPackage: %s\n", err)
	}
}
<commit_msg>Add package synopsis.<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net/http"
	"net/url"
	"os"
	"sort"
	"strings"
)

const packageTemplateString = `<!DOCTYPE html>

		<meta charset="utf-8">
		<title>{{.Repo.PackageName}}.{{.Repo.MajorVersion}}{{.Repo.SubPath}} - {{.Repo.GopkgPath}}</title>
		<link href='//fonts.googleapis.com/css?family=Ubuntu+Mono|Ubuntu' rel='stylesheet' >
		<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet" >
		<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" >

{{.Repo.GopkgPath}}

						 Source Code
						 API Documentation

Getting started

To get the package, execute:

go get {{.Repo.GopkgPath}}

To import this package, add the following line to your code:

import "{{.Repo.GopkgPath}}"

								{{if .CleanPackageName}}
Refer to it as {{.CleanPackageName}}.{{end}}

								{{if .Synopsis}}
{{.Synopsis}}
{{end}}

For more details, see the API documentation.

Versions

						{{ if .LatestVersions }}
							{{ range .LatestVersions }}

									v{{.Major}}
									→
									{{.}}

							{{ end }}
						{{ else }}

								v0
								→
								master

						{{ end }}

gopkg.in

`

var packageTemplate *template.Template

func gopkgVersionRoot(repo *Repo, version Version) string {
	return repo.GopkgVersionRoot(version)
}

var packageFuncs = template.FuncMap{
	"gopkgVersionRoot": gopkgVersionRoot,
}

func init() {
	var err error
	packageTemplate, err = template.New("page").Funcs(packageFuncs).Parse(packageTemplateString)
	if err != nil {
		fmt.Fprintf(os.Stderr, "fatal: parsing package template failed: %s\n", err)
		os.Exit(1)
	}
}

type packageData struct {
	Repo             *Repo
	LatestVersions   VersionList // Contains only the latest version for each major
	FullVersion      Version     // Version that the major requested resolves to
	CleanPackageName string
	Synopsis         string
}

type gddoApiSynopsisResult struct {
	Results []struct {
		Path     string `json:"path"`
		Synopsis string `json:"synopsis"`
	} `json:"results"`
}

func renderPackagePage(resp http.ResponseWriter, req *http.Request, repo *Repo) {
	data := &packageData{
		Repo: repo,
	}

	// calculate version mapping
	latestVersionsMap := make(map[int]Version)
	for _, v := range repo.AllVersions {
		v2, exists := latestVersionsMap[v.Major]
		if !exists || v2.Less(v) {
			latestVersionsMap[v.Major] = v
		}
	}
	data.FullVersion = latestVersionsMap[repo.MajorVersion.Major]
	data.LatestVersions = make(VersionList, 0, len(latestVersionsMap))
	for _, v := range latestVersionsMap {
		data.LatestVersions = append(data.LatestVersions, v)
	}
	sort.Sort(sort.Reverse(data.LatestVersions))

	// find clean package name
	data.CleanPackageName = repo.PackageName
	if strings.HasPrefix(data.CleanPackageName, "go-") {
		data.CleanPackageName = data.CleanPackageName[3:]
	}
	if strings.HasSuffix(data.CleanPackageName, "-go") {
		data.CleanPackageName = data.CleanPackageName[:len(data.CleanPackageName)-3]
	}
	for i, c := range data.CleanPackageName {
		if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' {
			continue
		}
		if i > 0 && (c == '_' || c >= '0' && c <= '9') {
			continue
		}
		data.CleanPackageName = ""
		break
	}

	// retrieve synopsis
	gddoResp, err := http.Get(`http://api.godoc.org/search?q=` + url.QueryEscape(repo.GopkgPath()))
	if err == nil {
		synopsisResult := &gddoApiSynopsisResult{}
		err = json.NewDecoder(gddoResp.Body).Decode(&synopsisResult)
		gddoResp.Body.Close()
		if err == nil {
			for _, apiPkg := range synopsisResult.Results {
				if apiPkg.Path == repo.GopkgPath() {
					data.Synopsis = apiPkg.Synopsis
					break
				}
			}
		}
	}

	err = packageTemplate.Execute(resp, data)
	if err != nil {
		log.Printf("error executing tmplPackage: %s\n", err)
	}
}
<|endoftext|>


<commit_before>// +build ignore

/*
Copyright 2013 Brandon Philips

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// This program builds a project and is a copy of build.go. See
// github.com/philips/build.go
//
// $ go run build.go
//
// See the README file for more details.
package main

import (
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
)

const (
	DefaultThirdParty = "third_party"
)

type Package struct {
}

func thirdPartyDir() string {
	root, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get the current working directory: %v", err)
	}
	return path.Join(root, DefaultThirdParty)
}

func binDir() string {
	root, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get the current working directory: %v", err)
	}
	return path.Join(root, "bin")
}

func run(name string, arg ...string) {
	cmd := exec.Command(name, arg...)

	cmd.Env = append(os.Environ(),
		"GOPATH="+thirdPartyDir(),
		"GOBIN="+binDir(),
	)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	err = cmd.Start()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)
	cmd.Wait()
}

// setupProject does the initial setup of the third_party src directory
// including setting up the symlink to the cwd from the src directory.
func setupProject(pkg string) {
	root, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get the current working directory: %v", err)
	}

	src := path.Join(thirdPartyDir(), "src", pkg)
	srcdir := path.Dir(src)

	os.MkdirAll(srcdir, 0777)

	rel, err := filepath.Rel(srcdir, root)
	if err != nil {
		log.Fatalf("creating relative third party path: %v", err)
	}

	err = os.Symlink(rel, src)
	if err != nil && os.IsExist(err) == false {
		log.Fatalf("creating project third party symlink: %v", err)
	}
}

func build(pkg string, args ...string) {
	buildArgs := []string{"build", pkg}
	buildArgs = append(buildArgs, args...)
	run("go", buildArgs...)
}

func main() {
	log.SetFlags(0)

	if len(os.Args) <= 1 {
		log.Fatalf("No commnad")
	}

	cmd := os.Args[1]

	if cmd == "setup" && len(os.Args) > 2 {
		setupProject(os.Args[2])
		return
	}

	run("go", os.Args[1:]...)
}
<commit_msg>fix(path): remove build.go references<commit_after>// +build ignore

/*
Copyright 2013 Brandon Philips

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// This program builds a project and is a copy of path.go. See
// github.com/philips/path.go
//
// $ go run path.go
//
// See the README file for more details.
package main

import (
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
)

const (
	DefaultThirdParty = "third_party"
)

type Package struct {
}

func thirdPartyDir() string {
	root, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get the current working directory: %v", err)
	}
	return path.Join(root, DefaultThirdParty)
}

func binDir() string {
	root, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get the current working directory: %v", err)
	}
	return path.Join(root, "bin")
}

func run(name string, arg ...string) {
	cmd := exec.Command(name, arg...)

	cmd.Env = append(os.Environ(),
		"GOPATH="+thirdPartyDir(),
		"GOBIN="+binDir(),
	)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	stderr, err := cmd.StderrPipe()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	err = cmd.Start()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		os.Exit(1)
	}
	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)
	cmd.Wait()
}

// setupProject does the initial setup of the third_party src directory
// including setting up the symlink to the cwd from the src directory.
func setupProject(pkg string) {
	root, err := os.Getwd()
	if err != nil {
		log.Fatalf("Failed to get the current working directory: %v", err)
	}

	src := path.Join(thirdPartyDir(), "src", pkg)
	srcdir := path.Dir(src)

	os.MkdirAll(srcdir, 0777)

	rel, err := filepath.Rel(srcdir, root)
	if err != nil {
		log.Fatalf("creating relative third party path: %v", err)
	}

	err = os.Symlink(rel, src)
	if err != nil && os.IsExist(err) == false {
		log.Fatalf("creating project third party symlink: %v", err)
	}
}

func build(pkg string, args ...string) {
	buildArgs := []string{"build", pkg}
	buildArgs = append(buildArgs, args...)
	run("go", buildArgs...)
}

func main() {
	log.SetFlags(0)

	if len(os.Args) <= 1 {
		log.Fatalf("No commnad")
	}

	cmd := os.Args[1]

	if cmd == "setup" && len(os.Args) > 2 {
		setupProject(os.Args[2])
		return
	}

	run("go", os.Args[1:]...)
}
<|endoftext|>


<commit_before>package villa

import (
	"os"
	"os/exec"
	"path/filepath"
	"io/ioutil"
)

// Path is a wrapper for a path in the OS
type Path string

/*
	filepath package
*/

func (p Path) Abs() (pth Path, err error) {
	pt, err := filepath.Abs(string(p))
	return Path(pt), err
}

func (p Path) Join(elem ...interface{}) Path {
	els := make(StringSlice, 0, len(elem) + 1)
	els.Add(p).Add(elem...)
	return Path(filepath.Join(els...))
}

func (p Path) Ext() string {
	return filepath.Ext(string(p))
}

/*
	os
*/

// Create is a wrapper to os.Create
func (p Path) Create() (file *os.File, err error) {
	return os.Create(string(p))
}

// Open is a wrapper to os.Open
func (p Path) Open() (file *os.File, err error) {
	return os.Open(string(p))

}
// Open is a wrapper to os.OpenFile
func (p Path) OpenFile(flag int, perm os.FileMode) (file *os.File, err error) {
	return os.OpenFile(string(p), flag, perm)
}

// Mkdir is a wrappter to os.Mkdir
func (p Path) Mkdir(perm os.FileMode) error {
	return os.Mkdir(string(p), perm)
}

// MkdirAll is a wrappter to os.MkdirAll
func (p Path) MkdirAll(perm os.FileMode) error {
	return os.MkdirAll(string(p), perm)
}

// Remove is a wrappter to os.Remove
func (p Path) Remove() error {
	return os.Remove(string(p))
}

// RemoveAll is a wrappter to os.RemoveAll
func (p Path) RemoveAll() error {
	return os.RemoveAll(string(p))
}

// Rename is a wrappter to os.Rename
func (p Path) Rename(newname Path) error {
	return os.Rename(string(p), string(newname))
}

// Stat is a wrappter to os.Stat
func (p Path) Stat() (fi os.FileInfo, err error) {
	return os.Stat(string(p))
}

// Symlink is a wrappter to os.Symlink
func (p Path) Symlink(dst Path) error {
	return os.Symlink(string(p), string(dst))
}

/*
	ioutil package
*/

func (p Path) ReadDir() (fi []os.FileInfo, err error) {
	return ioutil.ReadDir(string(p))
}

func (p Path) ReadFile() ([]byte, error) {
	return ioutil.ReadFile(string(p))
}

func (p Path) WriteFile(data []byte, perm os.FileMode) error {
	return ioutil.WriteFile(string(p), data, perm)
}

func (p Path) TempDir(prefix string) (name Path, err error) {
	nm, err := ioutil.TempDir(string(p), prefix)
	return Path(nm), err
}

/*
	exec package
*/

// Command is a wrappter to exec.Command
func (p Path) Command(arg ...string) *exec.Cmd {
	return exec.Command(string(p), arg...)
}

/*
	Composite
*/

// Exists checks whether the file exists
func (p Path) Exists() bool {
	_, err := p.Stat()
	return err == nil
}

// S converts Path back to string
func (p Path) S() string {
	return string(p)
}
<commit_msg>TRIVIAL<commit_after>package villa

import (
	"os"
	"os/exec"
	"path/filepath"
	"io/ioutil"
)

// Path is a wrapper for a path in the OS
type Path string

// Join connect elems to the tail of path
func (p Path) Join(elem ...interface{}) Path {
	els := make(StringSlice, 0, len(elem) + 1)
	els.Add(p).Add(elem...)
	return Path(filepath.Join(els...))
}

// Exists checks whether the file exists
func (p Path) Exists() bool {
	_, err := p.Stat()
	return err == nil
}

// S converts Path back to string
func (p Path) S() string {
	return string(p)
}

/*
	wrappers of filepath package
*/

// Abs is a wrapper to Abs.Ext
func (p Path) Abs() (pth Path, err error) {
	pt, err := filepath.Abs(string(p))
	return Path(pt), err
}

// Ext is a wrapper to filepath.Ext
func (p Path) Ext() string {
	return filepath.Ext(string(p))
}

/*
	wrappers of os package
*/

// Create is a wrapper to os.Create
func (p Path) Create() (file *os.File, err error) {
	return os.Create(string(p))
}

// Open is a wrapper to os.Open
func (p Path) Open() (file *os.File, err error) {
	return os.Open(string(p))

}
// Open is a wrapper to os.OpenFile
func (p Path) OpenFile(flag int, perm os.FileMode) (file *os.File, err error) {
	return os.OpenFile(string(p), flag, perm)
}

// Mkdir is a wrappter to os.Mkdir
func (p Path) Mkdir(perm os.FileMode) error {
	return os.Mkdir(string(p), perm)
}

// MkdirAll is a wrappter to os.MkdirAll
func (p Path) MkdirAll(perm os.FileMode) error {
	return os.MkdirAll(string(p), perm)
}

// Remove is a wrappter to os.Remove
func (p Path) Remove() error {
	return os.Remove(string(p))
}

// RemoveAll is a wrappter to os.RemoveAll
func (p Path) RemoveAll() error {
	return os.RemoveAll(string(p))
}

// Rename is a wrappter to os.Rename
func (p Path) Rename(newname Path) error {
	return os.Rename(string(p), string(newname))
}

// Stat is a wrappter to os.Stat
func (p Path) Stat() (fi os.FileInfo, err error) {
	return os.Stat(string(p))
}

// Symlink is a wrappter to os.Symlink
func (p Path) Symlink(dst Path) error {
	return os.Symlink(string(p), string(dst))
}

/*
	wrappers of ioutil package
*/

func (p Path) ReadDir() (fi []os.FileInfo, err error) {
	return ioutil.ReadDir(string(p))
}

func (p Path) ReadFile() ([]byte, error) {
	return ioutil.ReadFile(string(p))
}

func (p Path) WriteFile(data []byte, perm os.FileMode) error {
	return ioutil.WriteFile(string(p), data, perm)
}

func (p Path) TempDir(prefix string) (name Path, err error) {
	nm, err := ioutil.TempDir(string(p), prefix)
	return Path(nm), err
}

/*
	wrapppers of exec package
*/

// Command is a wrappter to exec.Command
func (p Path) Command(arg ...string) *exec.Cmd {
	return exec.Command(string(p), arg...)
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"

	"github.com/doozr/guac"
	"github.com/doozr/jot"
	"github.com/doozr/qbot/command"
	"github.com/doozr/qbot/notification"
	"github.com/doozr/qbot/queue"
	"github.com/doozr/qbot/usercache"
)

// Version is the current release version
var Version string

// DoneChan is a channel used for informing go routines to shut down
type DoneChan chan struct{}

func main() {
	if len(os.Args) < 3 {
		fmt.Println("Usage: qbot <token> <data file>")
		os.Exit(1)
	}

	if Version != "" {
		log.Printf("Qbot version %s", Version)
	} else {
		log.Printf("Qbot <unversioned build>")
	}

	// Get command line parameters
	token := os.Args[1]
	filename := os.Args[2]

	// Turn on jot if required
	if os.Getenv("QBOT_DEBUG") == "true" {
		jot.Enable()
	}

	// Synchronisation primitives
	waitGroup := sync.WaitGroup{}
	done := make(DoneChan)

	// Connect to Slack
	client := connectToSlack(token)
	log.Print("Connected to slack as ", client.Name())

	// Instantiate state
	userCache := getUserList(client)
	name := client.Name()
	jot.Print("qbot: name is ", name)
	q := loadQueue(filename)

	// Set up command and response processors
	notifications := notification.New(userCache)
	commands := command.New(notifications, userCache)

	// Create dispatchers
	notify := createNotifier(client)
	persist := createPersister(filename)
	messageHandler := createMessageHandler(client.ID(), client.Name(), q, commands, notify, persist)
	userChangeHandler := createUserChangeHandler(userCache)

	// start keepalive
	startKeepAlive(client, done, &waitGroup)

	// Receive incoming events
	receiver := createReceiver(client)
	events := receive(receiver, done, &waitGroup)

	// Dispatch incoming events
	jot.Println("qbot: ready to receive events")
	dispatcher := createDispatcher(client, 1*time.Minute, messageHandler, userChangeHandler)
	abort := dispatch(dispatcher, events, done, &waitGroup)

	// Wait for signals to stop
	sig := addSignalHandler()

	// Wait for a signal or an error to kill the process
	wait(sig, abort)

	// Shut it down
	close(done)
	client.Close()
	waitGroup.Wait()

	jot.Print("qbot: shutdown complete")
}

func connectToSlack(token string) guac.RealTimeClient {
	client, err := guac.New(token).RealTime()
	if err != nil {
		log.Fatal(err)
	}
	return client
}

func getUserList(client guac.WebClient) (userCache *usercache.UserCache) {
	log.Println("Getting user list")
	users, err := client.UsersList()
	if err != nil {
		log.Fatal(err)
	}
	userCache = usercache.New(users)
	jot.Print("loaded user list: ", userCache)
	return
}

func loadQueue(filename string) (q queue.Queue) {
	q = queue.Queue{}
	if _, err := os.Stat(filename); err == nil {
		dat, err := ioutil.ReadFile(filename)
		if err != nil {
			log.Fatalf("Error loading queue: %s", err)
		}
		json.Unmarshal(dat, &q)
		jot.Printf("loadQueue: read queue from %s: %v", filename, q)
		log.Printf("Loaded queue from %s", filename)
	}
	return q
}

func addSignalHandler() chan os.Signal {
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT)
	signal.Notify(sig, syscall.SIGTERM)
	signal.Notify(sig, syscall.SIGKILL)
	return sig
}

func wait(sig chan os.Signal, abort chan error) {
	select {
	case err := <-abort:
		if err != nil {
			log.Print("Error: ", err)
		}
		log.Print("Execution terminated - shutting down")
	case s := <-sig:
		log.Printf("Received %s signal - shutting down", s)
	}
}
<commit_msg>Flatten main some more<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"

	"github.com/doozr/guac"
	"github.com/doozr/jot"
	"github.com/doozr/qbot/command"
	"github.com/doozr/qbot/notification"
	"github.com/doozr/qbot/queue"
	"github.com/doozr/qbot/usercache"
)

// Version is the current release version
var Version = "<unversioned build>"

// DoneChan is a channel used for informing go routines to shut down
type DoneChan chan struct{}

func main() {
	log.Printf("Qbot version %s", Version)

	// Turn on jot if required
	if os.Getenv("QBOT_DEBUG") == "true" {
		jot.Enable()
	}

	token, filename := parseArgs()

	// Synchronisation primitives
	waitGroup := sync.WaitGroup{}
	done := make(DoneChan)

	// Connect to Slack
	client := connectToSlack(token)
	log.Print("Connected to slack as ", client.Name())

	// Instantiate state
	userCache := getUserList(client)
	q := loadQueue(filename)

	// Set up command and response processors
	notifications := notification.New(userCache)
	commands := command.New(notifications, userCache)

	// Create dispatchers
	notify := createNotifier(client)
	persist := createPersister(filename)
	messageHandler := createMessageHandler(client.ID(), client.Name(), q, commands, notify, persist)
	userChangeHandler := createUserChangeHandler(userCache)

	// start keepalive
	startKeepAlive(client, done, &waitGroup)

	// Receive incoming events
	receiver := createReceiver(client)
	events := receive(receiver, done, &waitGroup)

	// Dispatch incoming events
	jot.Println("qbot: ready to receive events")
	dispatcher := createDispatcher(client, 1*time.Minute, messageHandler, userChangeHandler)
	abort := dispatch(dispatcher, events, done, &waitGroup)

	// Wait for signals to stop
	sig := addSignalHandler()

	// Wait for a signal or an error to kill the process
	wait(sig, abort)

	// Shut it down
	close(done)
	client.Close()
	waitGroup.Wait()

	jot.Print("qbot: shutdown complete")
}

func parseArgs() (token, filename string) {
	if len(os.Args) < 3 {
		fmt.Println("Usage: qbot <token> <data file>")
		os.Exit(1)
	}
	// Get command line parameters
	token = os.Args[1]
	filename = os.Args[2]
	return
}

func connectToSlack(token string) guac.RealTimeClient {
	client, err := guac.New(token).RealTime()
	if err != nil {
		log.Fatal(err)
	}
	return client
}

func getUserList(client guac.WebClient) (userCache *usercache.UserCache) {
	log.Println("Getting user list")
	users, err := client.UsersList()
	if err != nil {
		log.Fatal(err)
	}
	userCache = usercache.New(users)
	jot.Print("loaded user list: ", userCache)
	return
}

func loadQueue(filename string) (q queue.Queue) {
	q = queue.Queue{}
	if _, err := os.Stat(filename); err == nil {
		dat, err := ioutil.ReadFile(filename)
		if err != nil {
			log.Fatalf("Error loading queue: %s", err)
		}
		json.Unmarshal(dat, &q)
		jot.Printf("loadQueue: read queue from %s: %v", filename, q)
		log.Printf("Loaded queue from %s", filename)
	}
	return q
}

func addSignalHandler() chan os.Signal {
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGINT)
	signal.Notify(sig, syscall.SIGTERM)
	signal.Notify(sig, syscall.SIGKILL)
	return sig
}

func wait(sig chan os.Signal, abort chan error) {
	select {
	case err := <-abort:
		if err != nil {
			log.Print("Error: ", err)
		}
		log.Print("Execution terminated - shutting down")
	case s := <-sig:
		log.Printf("Received %s signal - shutting down", s)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"net/http"

	"os/exec"
	"syscall"

	"github.com/go-martini/martini"
	"github.com/martini-contrib/cors"
	"github.com/ninjasphere/go-ninja/api"
	"github.com/ninjasphere/redigo/redis"
	"github.com/ninjasphere/sphere-go-homecloud/homecloud"
	"github.com/ninjasphere/sphere-go-homecloud/routes"
	"github.com/ninjasphere/sphere-go-homecloud/state"
)

// RestServer Holds stuff shared by all the rest services
type RestServer struct {
	redisPool *redis.Pool
	conn      *ninja.Connection

	roomModel    *homecloud.RoomModel
	thingModel   *homecloud.ThingModel
	deviceModel  *homecloud.DeviceModel
	siteModel    *homecloud.SiteModel
	stateManager state.StateManager
}

func NewRestServer(conn *ninja.Connection) *RestServer {

	conn, err := ninja.Connect("sphere-go-homecloud-rest")

	if err != nil {
		log.FatalError(err, "Failed to connect to mqtt")
	}

	return &RestServer{
		redisPool:    homecloud.RedisPool,
		conn:         conn,
		roomModel:    homecloud.NewRoomModel(homecloud.RedisPool, conn),
		thingModel:   homecloud.NewThingModel(homecloud.RedisPool, conn),
		deviceModel:  homecloud.NewDeviceModel(homecloud.RedisPool, conn),
		siteModel:    homecloud.NewSiteModel(homecloud.RedisPool, conn),
		stateManager: state.NewStateManager(conn),
	}
}

func (r *RestServer) Listen() {

	m := martini.Classic()

	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins: true,
	}))

	m.Map(r.roomModel)
	m.Map(r.thingModel)
	m.Map(r.deviceModel)
	m.Map(r.siteModel)
	m.Map(r.conn)
	m.Map(r.stateManager)

	location := routes.NewLocationRouter()
	thing := routes.NewThingRouter()
	room := routes.NewRoomRouter()
	site := routes.NewSiteRouter()

	m.Group("/rest/v1/locations", location.Register)
	m.Group("/rest/v1/things", thing.Register)
	m.Group("/rest/v1/rooms", room.Register)
	m.Group("/rest/v1/sites", site.Register)

	// the following methods are temporary, and will go away at some stage once a real update process is in place
	m.Post("/rest/tmp/apt/update", func() string {
		cmd := exec.Command("/usr/bin/nohup", "/bin/sh", "-c", "apt-get update; apt-get -y dist-upgrade")
		cmd.SysProcAttr = &syscall.SysProcAttr{}
		cmd.SysProcAttr.Setpgid = true
		cmd.Start()
		return "OK"
	})

	http.ListenAndServe(":8000", m)
}
<commit_msg>Remove temporary rest update task<commit_after>package main

import (
	"net/http"

	"github.com/go-martini/martini"
	"github.com/martini-contrib/cors"
	"github.com/ninjasphere/go-ninja/api"
	"github.com/ninjasphere/redigo/redis"
	"github.com/ninjasphere/sphere-go-homecloud/homecloud"
	"github.com/ninjasphere/sphere-go-homecloud/routes"
	"github.com/ninjasphere/sphere-go-homecloud/state"
)

// RestServer Holds stuff shared by all the rest services
type RestServer struct {
	redisPool *redis.Pool
	conn      *ninja.Connection

	roomModel    *homecloud.RoomModel
	thingModel   *homecloud.ThingModel
	deviceModel  *homecloud.DeviceModel
	siteModel    *homecloud.SiteModel
	stateManager state.StateManager
}

func NewRestServer(conn *ninja.Connection) *RestServer {

	conn, err := ninja.Connect("sphere-go-homecloud-rest")

	if err != nil {
		log.FatalError(err, "Failed to connect to mqtt")
	}

	return &RestServer{
		redisPool:    homecloud.RedisPool,
		conn:         conn,
		roomModel:    homecloud.NewRoomModel(homecloud.RedisPool, conn),
		thingModel:   homecloud.NewThingModel(homecloud.RedisPool, conn),
		deviceModel:  homecloud.NewDeviceModel(homecloud.RedisPool, conn),
		siteModel:    homecloud.NewSiteModel(homecloud.RedisPool, conn),
		stateManager: state.NewStateManager(conn),
	}
}

func (r *RestServer) Listen() {

	m := martini.Classic()

	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins: true,
	}))

	m.Map(r.roomModel)
	m.Map(r.thingModel)
	m.Map(r.deviceModel)
	m.Map(r.siteModel)
	m.Map(r.conn)
	m.Map(r.stateManager)

	location := routes.NewLocationRouter()
	thing := routes.NewThingRouter()
	room := routes.NewRoomRouter()
	site := routes.NewSiteRouter()

	m.Group("/rest/v1/locations", location.Register)
	m.Group("/rest/v1/things", thing.Register)
	m.Group("/rest/v1/rooms", room.Register)
	m.Group("/rest/v1/sites", site.Register)

	http.ListenAndServe(":8000", m)
}
<|endoftext|>


<commit_before>package dnsr

var root = `
;       This file holds the information on root name servers needed to
;       initialize cache of Internet domain name servers
;       (e.g. reference this file in the "cache  .  <file>"
;       configuration file of BIND domain name servers).
;
;       This file is made available by InterNIC
;       under anonymous FTP as
;           file                /domain/named.cache
;           on server           FTP.INTERNIC.NET
;       -OR-                    RS.INTERNIC.NET
;
;       last update:     December 05, 2019
;       related version of root zone:     2019120501
;
; FORMERLY NS.INTERNIC.NET
;
.                        3600000      NS    A.ROOT-SERVERS.NET.
A.ROOT-SERVERS.NET.      3600000      A     198.41.0.4
A.ROOT-SERVERS.NET.      3600000      AAAA  2001:503:ba3e::2:30
;
; FORMERLY NS1.ISI.EDU
;
.                        3600000      NS    B.ROOT-SERVERS.NET.
B.ROOT-SERVERS.NET.      3600000      A     199.9.14.201
B.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:200::b
;
; FORMERLY C.PSI.NET
;
.                        3600000      NS    C.ROOT-SERVERS.NET.
C.ROOT-SERVERS.NET.      3600000      A     192.33.4.12
C.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:2::c
;
; FORMERLY TERP.UMD.EDU
;
.                        3600000      NS    D.ROOT-SERVERS.NET.
D.ROOT-SERVERS.NET.      3600000      A     199.7.91.13
D.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:2d::d
;
; FORMERLY NS.NASA.GOV
;
.                        3600000      NS    E.ROOT-SERVERS.NET.
E.ROOT-SERVERS.NET.      3600000      A     192.203.230.10
E.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:a8::e
;
; FORMERLY NS.ISC.ORG
;
.                        3600000      NS    F.ROOT-SERVERS.NET.
F.ROOT-SERVERS.NET.      3600000      A     192.5.5.241
F.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:2f::f
;
; FORMERLY NS.NIC.DDN.MIL
;
.                        3600000      NS    G.ROOT-SERVERS.NET.
G.ROOT-SERVERS.NET.      3600000      A     192.112.36.4
G.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:12::d0d
;
; FORMERLY AOS.ARL.ARMY.MIL
;
.                        3600000      NS    H.ROOT-SERVERS.NET.
H.ROOT-SERVERS.NET.      3600000      A     198.97.190.53
H.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:1::53
;
; FORMERLY NIC.NORDU.NET
;
.                        3600000      NS    I.ROOT-SERVERS.NET.
I.ROOT-SERVERS.NET.      3600000      A     192.36.148.17
I.ROOT-SERVERS.NET.      3600000      AAAA  2001:7fe::53
;
; OPERATED BY VERISIGN, INC.
;
.                        3600000      NS    J.ROOT-SERVERS.NET.
J.ROOT-SERVERS.NET.      3600000      A     192.58.128.30
J.ROOT-SERVERS.NET.      3600000      AAAA  2001:503:c27::2:30
;
; OPERATED BY RIPE NCC
;
.                        3600000      NS    K.ROOT-SERVERS.NET.
K.ROOT-SERVERS.NET.      3600000      A     193.0.14.129
K.ROOT-SERVERS.NET.      3600000      AAAA  2001:7fd::1
;
; OPERATED BY ICANN
;
.                        3600000      NS    L.ROOT-SERVERS.NET.
L.ROOT-SERVERS.NET.      3600000      A     199.7.83.42
L.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:9f::42
;
; OPERATED BY WIDE
;
.                        3600000      NS    M.ROOT-SERVERS.NET.
M.ROOT-SERVERS.NET.      3600000      A     202.12.27.33
M.ROOT-SERVERS.NET.      3600000      AAAA  2001:dc3::35
; End of file`
<commit_msg>auto-update<commit_after>package dnsr

var root = `
;       This file holds the information on root name servers needed to
;       initialize cache of Internet domain name servers
;       (e.g. reference this file in the "cache  .  <file>"
;       configuration file of BIND domain name servers).
;
;       This file is made available by InterNIC
;       under anonymous FTP as
;           file                /domain/named.cache
;           on server           FTP.INTERNIC.NET
;       -OR-                    RS.INTERNIC.NET
;
;       last update:     January 30, 2020
;       related version of root zone:     2020013002
;
; FORMERLY NS.INTERNIC.NET
;
.                        3600000      NS    A.ROOT-SERVERS.NET.
A.ROOT-SERVERS.NET.      3600000      A     198.41.0.4
A.ROOT-SERVERS.NET.      3600000      AAAA  2001:503:ba3e::2:30
;
; FORMERLY NS1.ISI.EDU
;
.                        3600000      NS    B.ROOT-SERVERS.NET.
B.ROOT-SERVERS.NET.      3600000      A     199.9.14.201
B.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:200::b
;
; FORMERLY C.PSI.NET
;
.                        3600000      NS    C.ROOT-SERVERS.NET.
C.ROOT-SERVERS.NET.      3600000      A     192.33.4.12
C.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:2::c
;
; FORMERLY TERP.UMD.EDU
;
.                        3600000      NS    D.ROOT-SERVERS.NET.
D.ROOT-SERVERS.NET.      3600000      A     199.7.91.13
D.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:2d::d
;
; FORMERLY NS.NASA.GOV
;
.                        3600000      NS    E.ROOT-SERVERS.NET.
E.ROOT-SERVERS.NET.      3600000      A     192.203.230.10
E.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:a8::e
;
; FORMERLY NS.ISC.ORG
;
.                        3600000      NS    F.ROOT-SERVERS.NET.
F.ROOT-SERVERS.NET.      3600000      A     192.5.5.241
F.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:2f::f
;
; FORMERLY NS.NIC.DDN.MIL
;
.                        3600000      NS    G.ROOT-SERVERS.NET.
G.ROOT-SERVERS.NET.      3600000      A     192.112.36.4
G.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:12::d0d
;
; FORMERLY AOS.ARL.ARMY.MIL
;
.                        3600000      NS    H.ROOT-SERVERS.NET.
H.ROOT-SERVERS.NET.      3600000      A     198.97.190.53
H.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:1::53
;
; FORMERLY NIC.NORDU.NET
;
.                        3600000      NS    I.ROOT-SERVERS.NET.
I.ROOT-SERVERS.NET.      3600000      A     192.36.148.17
I.ROOT-SERVERS.NET.      3600000      AAAA  2001:7fe::53
;
; OPERATED BY VERISIGN, INC.
;
.                        3600000      NS    J.ROOT-SERVERS.NET.
J.ROOT-SERVERS.NET.      3600000      A     192.58.128.30
J.ROOT-SERVERS.NET.      3600000      AAAA  2001:503:c27::2:30
;
; OPERATED BY RIPE NCC
;
.                        3600000      NS    K.ROOT-SERVERS.NET.
K.ROOT-SERVERS.NET.      3600000      A     193.0.14.129
K.ROOT-SERVERS.NET.      3600000      AAAA  2001:7fd::1
;
; OPERATED BY ICANN
;
.                        3600000      NS    L.ROOT-SERVERS.NET.
L.ROOT-SERVERS.NET.      3600000      A     199.7.83.42
L.ROOT-SERVERS.NET.      3600000      AAAA  2001:500:9f::42
;
; OPERATED BY WIDE
;
.                        3600000      NS    M.ROOT-SERVERS.NET.
M.ROOT-SERVERS.NET.      3600000      A     202.12.27.33
M.ROOT-SERVERS.NET.      3600000      AAAA  2001:dc3::35
; End of file`
<|endoftext|>


<commit_before><commit_msg>Add set commands<commit_after><|endoftext|>


<commit_before>/*
Copyright 2019 The logr Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package strd implements github.com/go-logr/logr.Logger in terms of
// Go's standard log package.
package stdr

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"runtime"
	"sort"

	"github.com/go-logr/logr"
)

// The global verbosity level.  See SetVerbosity().
var globalVerbosity int = 0

// SetVerbosity sets the global level against which all info logs will be
// compared.  If this is greater than or equal to the "V" of the logger, the
// message will be logged.  A higher value here means more logs will be written.
// The previous verbosity value is returned.  This is not concurrent-safe -
// callers must be sure to call it from only one goroutine.
func SetVerbosity(v int) int {
	old := globalVerbosity
	globalVerbosity = v
	return old
}

// New returns a logr.Logger which is implemented by Go's standard log package,
// or something like it.  If std is nil, this will call functions in the log
// package instead.
//
// Example: stdr.New(log.New(os.Stderr, "", log.LstdFlags)))
func New(std StdLogger) logr.Logger {
	return NewWithOptions(std, Options{})
}

// NewWithOptions returns a logr.Logger which is implemented by Go's standard
// log package, or something like it.  See New for details.
func NewWithOptions(std StdLogger, opts Options) logr.Logger {
	if opts.Depth < 0 {
		opts.Depth = 0
	}

	return logger{
		std:    std,
		level:  0,
		prefix: "",
		values: nil,
		depth:  opts.Depth,
	}
}

type Options struct {
	// DepthOffset biases the assumed number of call frames to the "true"
	// caller.  This is useful when the calling code calls a function which then
	// calls glogr (e.g. a logging shim to another API).  Values less than zero
	// will be treated as zero.
	Depth int
}

// StdLogger is the subset of the Go stdlib log.Logger API that is needed for
// this adapter.
type StdLogger interface {
	// Output is the same as log.Output and log.Logger.Output.
	Output(calldepth int, logline string) error
}

type logger struct {
	std    StdLogger
	level  int
	prefix string
	values []interface{}
	depth  int
}

func (l logger) clone() logger {
	out := l
	l.values = copySlice(l.values)
	return out
}

func copySlice(in []interface{}) []interface{} {
	out := make([]interface{}, len(in))
	copy(out, in)
	return out
}

// Magic string for intermediate frames that we should ignore.
const autogeneratedFrameName = "<autogenerated>"

// Discover how many frames we need to climb to find the caller. This approach
// was suggested by Ian Lance Taylor of the Go team, so it *should* be safe
// enough (famous last words).
func framesToCaller() int {
	// 1 is the immediate caller.  3 should be too many.
	for i := 1; i < 3; i++ {
		_, file, _, _ := runtime.Caller(i + 1) // +1 for this function's frame
		if file != autogeneratedFrameName {
			return i
		}
	}
	return 1 // something went wrong, this is safe
}

type kvPair struct {
	key string
	val interface{}
}

func flatten(kvList ...interface{}) string {
	keys := make([]string, 0, len(kvList))
	vals := make(map[string]interface{}, len(kvList))
	for i := 0; i < len(kvList); i += 2 {
		k, ok := kvList[i].(string)
		if !ok {
			panic(fmt.Sprintf("key is not a string: %s", pretty(kvList[i])))
		}
		var v interface{}
		if i+1 < len(kvList) {
			v = kvList[i+1]
		}
		keys = append(keys, k)
		vals[k] = v
	}
	sort.Strings(keys)
	buf := bytes.Buffer{}
	for i, k := range keys {
		v := vals[k]
		if i > 0 {
			buf.WriteRune(' ')
		}
		buf.WriteString(pretty(k))
		buf.WriteString("=")
		buf.WriteString(pretty(v))
	}
	return buf.String()
}

func pretty(value interface{}) string {
	jb, _ := json.Marshal(value)
	return string(jb)
}

func (l logger) Info(msg string, kvList ...interface{}) {
	if l.Enabled() {
		lvlStr := flatten("level", l.level)
		msgStr := flatten("msg", msg)
		fixedStr := flatten(l.values...)
		userStr := flatten(kvList...)
		l.output(framesToCaller()+l.depth, fmt.Sprintln(l.prefix, lvlStr, msgStr, fixedStr, userStr))
	}
}

func (l logger) Enabled() bool {
	return globalVerbosity >= l.level
}

func (l logger) Error(err error, msg string, kvList ...interface{}) {
	msgStr := flatten("msg", msg)
	var loggableErr interface{}
	if err != nil {
		loggableErr = err.Error()
	}
	errStr := flatten("error", loggableErr)
	fixedStr := flatten(l.values...)
	userStr := flatten(kvList...)
	l.output(framesToCaller()+l.depth, fmt.Sprintln(l.prefix, errStr, msgStr, fixedStr, userStr))
}

func (l logger) output(calldepth int, s string) {
	depth := calldepth + 2 // offset for this adapter

	// ignore errors - what can we really do about them?
	if l.std != nil {
		_ = l.std.Output(depth, s)
	} else {
		_ = log.Output(depth, s)
	}
}

func (l logger) V(level int) logr.Logger {
	new := l.clone()
	new.level += level
	return new
}

// WithName returns a new logr.Logger with the specified name appended.  stdr
// uses '/' characters to separate name elements.  Callers should not pass '/'
// in the provided name string, but this library does not actually enforce that.
func (l logger) WithName(name string) logr.Logger {
	new := l.clone()
	if len(l.prefix) > 0 {
		new.prefix = l.prefix + "/"
	}
	new.prefix += name
	return new
}

func (l logger) WithValues(kvList ...interface{}) logr.Logger {
	new := l.clone()
	new.values = append(new.values, kvList...)
	return new
}

var _ logr.Logger = logger{}
<commit_msg>Add an "Underlier" interface<commit_after>/*
Copyright 2019 The logr Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package strd implements github.com/go-logr/logr.Logger in terms of
// Go's standard log package.
package stdr

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"runtime"
	"sort"

	"github.com/go-logr/logr"
)

// The global verbosity level.  See SetVerbosity().
var globalVerbosity int = 0

// SetVerbosity sets the global level against which all info logs will be
// compared.  If this is greater than or equal to the "V" of the logger, the
// message will be logged.  A higher value here means more logs will be written.
// The previous verbosity value is returned.  This is not concurrent-safe -
// callers must be sure to call it from only one goroutine.
func SetVerbosity(v int) int {
	old := globalVerbosity
	globalVerbosity = v
	return old
}

// New returns a logr.Logger which is implemented by Go's standard log package,
// or something like it.  If std is nil, this will call functions in the log
// package instead.
//
// Example: stdr.New(log.New(os.Stderr, "", log.LstdFlags)))
func New(std StdLogger) logr.Logger {
	return NewWithOptions(std, Options{})
}

// NewWithOptions returns a logr.Logger which is implemented by Go's standard
// log package, or something like it.  See New for details.
func NewWithOptions(std StdLogger, opts Options) logr.Logger {
	if opts.Depth < 0 {
		opts.Depth = 0
	}

	return logger{
		std:    std,
		level:  0,
		prefix: "",
		values: nil,
		depth:  opts.Depth,
	}
}

type Options struct {
	// DepthOffset biases the assumed number of call frames to the "true"
	// caller.  This is useful when the calling code calls a function which then
	// calls glogr (e.g. a logging shim to another API).  Values less than zero
	// will be treated as zero.
	Depth int
}

// StdLogger is the subset of the Go stdlib log.Logger API that is needed for
// this adapter.
type StdLogger interface {
	// Output is the same as log.Output and log.Logger.Output.
	Output(calldepth int, logline string) error
}

type logger struct {
	std    StdLogger
	level  int
	prefix string
	values []interface{}
	depth  int
}

func (l logger) clone() logger {
	out := l
	l.values = copySlice(l.values)
	return out
}

func copySlice(in []interface{}) []interface{} {
	out := make([]interface{}, len(in))
	copy(out, in)
	return out
}

// Magic string for intermediate frames that we should ignore.
const autogeneratedFrameName = "<autogenerated>"

// Discover how many frames we need to climb to find the caller. This approach
// was suggested by Ian Lance Taylor of the Go team, so it *should* be safe
// enough (famous last words).
func framesToCaller() int {
	// 1 is the immediate caller.  3 should be too many.
	for i := 1; i < 3; i++ {
		_, file, _, _ := runtime.Caller(i + 1) // +1 for this function's frame
		if file != autogeneratedFrameName {
			return i
		}
	}
	return 1 // something went wrong, this is safe
}

type kvPair struct {
	key string
	val interface{}
}

func flatten(kvList ...interface{}) string {
	keys := make([]string, 0, len(kvList))
	vals := make(map[string]interface{}, len(kvList))
	for i := 0; i < len(kvList); i += 2 {
		k, ok := kvList[i].(string)
		if !ok {
			panic(fmt.Sprintf("key is not a string: %s", pretty(kvList[i])))
		}
		var v interface{}
		if i+1 < len(kvList) {
			v = kvList[i+1]
		}
		keys = append(keys, k)
		vals[k] = v
	}
	sort.Strings(keys)
	buf := bytes.Buffer{}
	for i, k := range keys {
		v := vals[k]
		if i > 0 {
			buf.WriteRune(' ')
		}
		buf.WriteString(pretty(k))
		buf.WriteString("=")
		buf.WriteString(pretty(v))
	}
	return buf.String()
}

func pretty(value interface{}) string {
	jb, _ := json.Marshal(value)
	return string(jb)
}

func (l logger) Info(msg string, kvList ...interface{}) {
	if l.Enabled() {
		lvlStr := flatten("level", l.level)
		msgStr := flatten("msg", msg)
		fixedStr := flatten(l.values...)
		userStr := flatten(kvList...)
		l.output(framesToCaller()+l.depth, fmt.Sprintln(l.prefix, lvlStr, msgStr, fixedStr, userStr))
	}
}

func (l logger) Enabled() bool {
	return globalVerbosity >= l.level
}

func (l logger) Error(err error, msg string, kvList ...interface{}) {
	msgStr := flatten("msg", msg)
	var loggableErr interface{}
	if err != nil {
		loggableErr = err.Error()
	}
	errStr := flatten("error", loggableErr)
	fixedStr := flatten(l.values...)
	userStr := flatten(kvList...)
	l.output(framesToCaller()+l.depth, fmt.Sprintln(l.prefix, errStr, msgStr, fixedStr, userStr))
}

func (l logger) output(calldepth int, s string) {
	depth := calldepth + 2 // offset for this adapter

	// ignore errors - what can we really do about them?
	if l.std != nil {
		_ = l.std.Output(depth, s)
	} else {
		_ = log.Output(depth, s)
	}
}

func (l logger) V(level int) logr.Logger {
	new := l.clone()
	new.level += level
	return new
}

// WithName returns a new logr.Logger with the specified name appended.  stdr
// uses '/' characters to separate name elements.  Callers should not pass '/'
// in the provided name string, but this library does not actually enforce that.
func (l logger) WithName(name string) logr.Logger {
	new := l.clone()
	if len(l.prefix) > 0 {
		new.prefix = l.prefix + "/"
	}
	new.prefix += name
	return new
}

// WithValues returns a new logr.Logger with the specified key-and-values
// saved.
func (l logger) WithValues(kvList ...interface{}) logr.Logger {
	new := l.clone()
	new.values = append(new.values, kvList...)
	return new
}

var _ logr.Logger = logger{}

// Underlier exposes access to the underlying logging implementation.  Since
// callers only have a logr.Logger, they have to know which implementation is
// in use, so this interface is less of an abstraction and more of way to test
// type conversion.
type Underlier interface {
	GetUnderlying() StdLogger
}

// GetUnderlying returns the StdLogger underneath this logger.  Since StdLogger
// is itself an interface, the result may or may not be a Go log.Logger.
func (l logger) GetUnderlying() StdLogger {
	return l.std
}
<|endoftext|>


<commit_before>// Package surf ensembles other packages into a usable browser.
package surf

import (
	"net/http"

	"github.com/headzoo/surf/agent"
	"github.com/headzoo/surf/browser"
	"github.com/headzoo/surf/jar"
)

var (
	// DefaultUserAgent is the global user agent value.
	DefaultUserAgent = agent.Create()

	// DefaultSendReferer is the global value for the AttributeSendReferer attribute.
	DefaultSendReferer = true

	// DefaultMetaRefreshHandling is the global value for the AttributeHandleRefresh attribute.
	DefaultMetaRefreshHandling = true

	// DefaultFollowRedirects is the global value for the AttributeFollowRedirects attribute.
	DefaultFollowRedirects = true
)

// NewBrowser creates and returns a *browser.Browser type.
func NewBrowser() *browser.Browser {
	bow := &browser.Browser{}
	bow.SetUserAgent(DefaultUserAgent)
	bow.SetState(&jar.State{})
	bow.SetCookieJar(jar.NewMemoryCookies())
	bow.SetBookmarksJar(jar.NewMemoryBookmarks())
	bow.SetHistoryJar(jar.NewMemoryHistory())
	bow.SetHeadersJar(jar.NewMemoryHeaders())
	bow.SetAttributes(browser.AttributeMap{
		browser.SendReferer:         DefaultSendReferer,
		browser.MetaRefreshHandling: DefaultMetaRefreshHandling,
		browser.FollowRedirects:     DefaultFollowRedirects,
	})
	bow.SetTransport(&http.Transport{})

	return bow
}
<commit_msg>Updated paths from "headzoo", to the fork at "gomaps"<commit_after>// Package surf ensembles other packages into a usable browser.
package surf

import (
	"net/http"

	"github.com/gomaps/surf/agent"
	"github.com/gomaps/surf/browser"
	"github.com/gomaps/surf/jar"
)

var (
	// DefaultUserAgent is the global user agent value.
	DefaultUserAgent = agent.Create()

	// DefaultSendReferer is the global value for the AttributeSendReferer attribute.
	DefaultSendReferer = true

	// DefaultMetaRefreshHandling is the global value for the AttributeHandleRefresh attribute.
	DefaultMetaRefreshHandling = true

	// DefaultFollowRedirects is the global value for the AttributeFollowRedirects attribute.
	DefaultFollowRedirects = true
)

// NewBrowser creates and returns a *browser.Browser type.
func NewBrowser() *browser.Browser {
	bow := &browser.Browser{}
	bow.SetUserAgent(DefaultUserAgent)
	bow.SetState(&jar.State{})
	bow.SetCookieJar(jar.NewMemoryCookies())
	bow.SetBookmarksJar(jar.NewMemoryBookmarks())
	bow.SetHistoryJar(jar.NewMemoryHistory())
	bow.SetHeadersJar(jar.NewMemoryHeaders())
	bow.SetAttributes(browser.AttributeMap{
		browser.SendReferer:         DefaultSendReferer,
		browser.MetaRefreshHandling: DefaultMetaRefreshHandling,
		browser.FollowRedirects:     DefaultFollowRedirects,
	})
	bow.SetTransport(&http.Transport{})

	return bow
}
<|endoftext|>


<commit_before>package cpio

import (
	"bytes"
	"io"
	"strconv"
	"time"
)

const (
	svr4MaxNameSize = 4096 // MAX_PATH
	svr4MaxFileSize = 4294967295
)

func readHex(s string) int64 {
	// errors are ignored and 0 returned
	i, _ := strconv.ParseInt(s, 16, 64)
	return i
}

func readSVR4Header(r io.Reader) (*Header, error) {
	var buf [110]byte
	if _, err := io.ReadFull(r, buf[:]); err != nil {
		return nil, err
	}

	// TODO: check endianness

	// check magic
	hasCRC := false
	if !bytes.HasPrefix(buf[:], []byte{0x30, 0x37, 0x30, 0x37, 0x30}) { // 07070
		return nil, ErrHeader
	}
	if buf[5] == 0x32 { // '2'
		hasCRC = true
	} else if buf[5] != 0x31 { // '1'
		return nil, ErrHeader
	}

	asc := string(buf[:])
	hdr := &Header{}

	hdr.Inode = readHex(asc[6:14])
	hdr.Mode = FileMode(readHex(asc[14:22]))
	hdr.UID = int(readHex(asc[22:30]))
	hdr.GID = int(readHex(asc[30:38]))
	hdr.Links = int(readHex(asc[38:46]))
	hdr.ModTime = time.Unix(readHex(asc[46:54]), 0)
	hdr.Size = readHex(asc[54:62])
	if hdr.Size > svr4MaxFileSize {
		return nil, ErrHeader
	}
	nameSize := readHex(asc[94:102])
	if nameSize < 1 || nameSize > svr4MaxNameSize {
		return nil, ErrHeader
	}
	hdr.Checksum = Checksum(readHex(asc[102:110]))
	if !hasCRC && hdr.Checksum != 0 {
		return nil, ErrHeader
	}

	name := make([]byte, nameSize)
	if _, err := io.ReadFull(r, name); err != nil {
		return nil, err
	}
	if bytes.Equal(name, headerEOF) {
		return nil, io.EOF
	}
	hdr.Name = string(name[:nameSize-1])

	// padding between end of file and next header
	hdr.pad = (4 - (hdr.Size % 4)) % 4

	// skip to end of header/start of file
	pad := (4 - (len(buf)+len(name))%4) % 4
	if pad > 0 {
		if _, err := io.ReadFull(r, buf[:pad]); err != nil {
			return nil, err
		}
	}

	// read link name
	if hdr.Mode&^ModePerm == ModeSymlink {
		b := make([]byte, hdr.Size)
		if _, err := io.ReadFull(r, b); err != nil {
			return nil, err
		}
		hdr.Linkname = string(b)
		hdr.Size = 0
	}

	return hdr, nil
}
<commit_msg>Fixed potential out of range error<commit_after>package cpio

import (
	"bytes"
	"io"
	"strconv"
	"time"
)

const (
	svr4MaxNameSize = 4096 // MAX_PATH
	svr4MaxFileSize = 4294967295
)

func readHex(s string) int64 {
	// errors are ignored and 0 returned
	i, _ := strconv.ParseInt(s, 16, 64)
	return i
}

func readSVR4Header(r io.Reader) (*Header, error) {
	var buf [110]byte
	if _, err := io.ReadFull(r, buf[:]); err != nil {
		return nil, err
	}

	// TODO: check endianness

	// check magic
	hasCRC := false
	if !bytes.HasPrefix(buf[:], []byte{0x30, 0x37, 0x30, 0x37, 0x30}) { // 07070
		return nil, ErrHeader
	}
	if buf[5] == 0x32 { // '2'
		hasCRC = true
	} else if buf[5] != 0x31 { // '1'
		return nil, ErrHeader
	}

	asc := string(buf[:])
	hdr := &Header{}

	hdr.Inode = readHex(asc[6:14])
	hdr.Mode = FileMode(readHex(asc[14:22]))
	hdr.UID = int(readHex(asc[22:30]))
	hdr.GID = int(readHex(asc[30:38]))
	hdr.Links = int(readHex(asc[38:46]))
	hdr.ModTime = time.Unix(readHex(asc[46:54]), 0)
	hdr.Size = readHex(asc[54:62])
	if hdr.Size > svr4MaxFileSize {
		return nil, ErrHeader
	}
	nameSize := readHex(asc[94:102])
	if nameSize < 1 || nameSize > svr4MaxNameSize {
		return nil, ErrHeader
	}
	hdr.Checksum = Checksum(readHex(asc[102:110]))
	if !hasCRC && hdr.Checksum != 0 {
		return nil, ErrHeader
	}

	name := make([]byte, nameSize)
	if _, err := io.ReadFull(r, name); err != nil {
		return nil, err
	}
	if bytes.Equal(name, headerEOF) {
		return nil, io.EOF
	}
	hdr.Name = string(name[:nameSize-1])

	// padding between end of file and next header
	hdr.pad = (4 - (hdr.Size % 4)) % 4

	// skip to end of header/start of file
	pad := (4 - (len(buf)+len(name))%4) % 4
	if pad > 0 {
		if _, err := io.ReadFull(r, buf[:pad]); err != nil {
			return nil, err
		}
	}

	// read link name
	if hdr.Mode&^ModePerm == ModeSymlink {
		if hdr.Size < 1 || hdr.Size > svr4MaxNameSize {
			return nil, ErrHeader
		}
		b := make([]byte, hdr.Size)
		if _, err := io.ReadFull(r, b); err != nil {
			return nil, err
		}
		hdr.Linkname = string(b)
		hdr.Size = 0
	}

	return hdr, nil
}
<|endoftext|>


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

package main

import (
	"fmt"
	"log"
)

type task struct {
	Deps    []string
	Links   [][]string
	Cmds    [][]string
	Envs    [][]string
	Accepts [][]string
	Rejects [][]string
}

func (t *task) deps(conf *config) []string {
	deps := t.Deps

	if conf.flags&flagNoCmds == 0 {
		for _, currCmd := range t.Cmds {
			deps = append(deps, findCmdDeps(currCmd, conf)...)
		}
	}

	return deps
}

func (t *task) process(conf *config) error {
	for _, currTask := range t.deps(conf) {
		if err := processTask(currTask, conf); err != nil {
			return err
		}
	}

	for _, currEnv := range t.Envs {
		if err := processEnv(currEnv, conf); err != nil {
			return err
		}
	}

	if conf.flags&flagNoCmds == 0 {
	CmdLoop:
		for {
			for _, currCnd := range t.Accepts {
				if err := processCmd(currCnd, false, conf); err != nil {
					break CmdLoop
				}
			}

			for _, currCnd := range t.Rejects {
				if err := processCmd(currCnd, false, conf); err == nil {
					break CmdLoop
				}
			}

			for _, currCmd := range t.Cmds {
				if err := processCmd(currCmd, true, conf); err != nil {
					return err
				}
			}

			break
		}
	}

	if conf.flags&flagNoLinks == 0 {
		for _, currLink := range t.Links {
			if err := processLink(currLink, conf); err != nil {
				return err
			}
		}
	}

	return nil
}

func processTask(taskName string, conf *config) error {
	for _, tn := range makeVariantNames(taskName, conf.variant) {
		t, ok := conf.Tasks[tn]
		if !ok {
			continue
		}

		if conf.handled[tn] {
			if conf.flags&flagVerbose != 0 {
				log.Printf("skipping processed task: %s", tn)
			}

			return nil
		}

		if conf.flags&flagVerbose != 0 {
			log.Printf("processing task: %s", tn)
		}

		conf.handled[tn] = true
		return t.process(conf)
	}

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

package main

import (
	"fmt"
	"log"
)

type task struct {
	Deps    []string
	Links   [][]string
	Cmds    [][]string
	Envs    [][]string
	Accepts [][]string
	Rejects [][]string
}

func (t *task) deps(conf *config) []string {
	deps := t.Deps

	if conf.flags&flagNoCmds == 0 {
		for _, currCmd := range t.Cmds {
			deps = append(deps, findCmdDeps(currCmd, conf)...)
		}
	}

	return deps
}

func (t *task) process(conf *config) error {
	for _, currTask := range t.deps(conf) {
		if err := processTask(currTask, conf); err != nil {
			return err
		}
	}

	for _, currEnv := range t.Envs {
		if err := processEnv(currEnv, conf); err != nil {
			return err
		}
	}

	if conf.flags&flagNoCmds == 0 {
		for _, currCmd := range t.Cmds {
			if err := processCmd(currCmd, true, conf); err != nil {
				return err
			}
		}
	}

	if conf.flags&flagNoLinks == 0 {
		for _, currLink := range t.Links {
			if err := processLink(currLink, conf); err != nil {
				return err
			}
		}
	}

	return nil
}

func (t *task) skippable(conf *config) bool {
	for _, currCnd := range t.Accepts {
		if err := processCmd(currCnd, false, conf); err != nil {
			return true
		}
	}

	for _, currCnd := range t.Rejects {
		if err := processCmd(currCnd, false, conf); err == nil {
			return true
		}
	}

	return false
}

func processTask(taskName string, conf *config) error {
	for _, tn := range makeVariantNames(taskName, conf.variant) {
		t, ok := conf.Tasks[tn]
		if !ok {
			continue
		}

		if conf.handled[tn] || t.skippable(conf) {
			if conf.flags&flagVerbose != 0 {
				log.Printf("skipping task: %s", tn)
			}

			return nil
		}

		if conf.flags&flagVerbose != 0 {
			log.Printf("processing task: %s", tn)
		}

		conf.handled[tn] = true
		return t.process(conf)
	}

	return fmt.Errorf("task or variant not found: %s", taskName)
}
<|endoftext|>


<commit_before>package golog

import . "fmt"
import . "regexp"
import "strings"
import "bytes"
import "github.com/mndrix/golog/scanner"

var anonCounter <-chan int64
func init() {
    // goroutine providing a counter for anonymous variables
    c := make(chan int64)
    var i int64 = 1
    go func() {
        for {
            c <- i
            i++
        }
    }()
    anonCounter = c
}

// Term represents a single Prolog term which might be an atom, a structure,
// a number, etc.
type Term interface {
    // Functor returns the term's name
    Functor() string

    // Arity returns the number of arguments a term has. An atom has 0 arity.
    Arity() int

    // Arguments returns a slice of this term's arguments, if any
    Arguments() []Term

    // Body returns a term's second argument; otherwise, panics
    Body() Term

    // Head returns a term's first argument; otherwise, panics
    Head() Term

    // Error returns an error value if this is an error term
    Error() error

    // IsClause returns true if the term is like 'Head :- Body'
    IsClause() bool

    // String provides a string representation of a term
    String() string

    // Indicator() provides a "predicate indicator" representation of a term
    Indicator() string
}

// ISO calls this a "compound term" see §6.1.2(e)
// We currently use this type to cover atoms defined in §6.1.2(b)
type Structure struct {
    Func    string
    Args    []Term
}
func (self *Structure) Functor() string {
    return self.Func
}
func (self *Structure) Arity() int {
    return len(self.Args)
}
func (self *Structure) Arguments() []Term {
    return self.Args
}
func (self *Structure) Body() Term {
    return self.Args[1]
}
func (self *Structure) Head() Term {
    return self.Args[0]
}
func (self *Structure) IsClause() bool {
    return self.Arity() == 2 && self.Functor() == ":-"
}
func (self *Structure) String() string {
    // an atom
    quotedFunctor := QuoteFunctor(self.Functor())
    if self.Arity() == 0 {
        return quotedFunctor
    }

    var buf bytes.Buffer
    Fprintf(&buf, "%s(", quotedFunctor)
    arity := self.Arity()
    for i := 0; i<arity; i++ {
        if i>0 {
            Fprintf(&buf, ", ")
        }
        Fprintf(&buf, "%s", self.Arguments()[i])
    }
    Fprintf(&buf, ")")
    return buf.String()
}
func (self *Structure) Indicator() string {
    return Sprintf("%s/%d", self.Functor(), self.Arity())
}
func (self *Structure) Error() error {
    panic("Can't call Error() on a Structure")
}

// See §6.1.2(a)
type Variable struct {
    Name    string
}
func (self *Variable) Functor() string {
    panic("Variables have no Functor()")
}
func (self *Variable) Arity() int {
    panic("Variables have no Arity()")
}
func (self *Variable) Arguments() []Term {
    panic("Variables have no Arguments()")
}
func (self *Variable) Body() Term {
    panic("Variables have no Body()")
}
func (self *Variable) Head() Term {
    panic("Variables have no Head()")
}
func (self *Variable) IsClause() bool {
    return false
}
func (self *Variable) String() string {
    return self.Name
}
func (self *Variable) Indicator() string {
    return Sprintf("%s", self.Name)
}
func (self *Variable) Error() error {
    panic("Can't call Error() on a Variable")
}

type Error string
func (self *Error) Functor() string {
    panic("Errors have no Functor()")
}
func (self *Error) Arity() int {
    panic("Errors have no Arity()")
}
func (self *Error) Arguments() []Term {
    panic("Errors have no Arguments()")
}
func (self *Error) Body() Term {
    panic("Errors have no Body()")
}
func (self *Error) Head() Term {
    panic("Errors have no Head()")
}
func (self *Error) IsClause() bool {
    return false
}
func (self *Error) String() string {
    return string(*self)
}
func (self *Error) Indicator() string {
    panic("Errors have no Indicator()")
}
func (self *Error) Error() error {
    return Errorf("%s", *self)
}

// NewTerm creates a new term with the given functor and optional arguments
func NewTerm(functor string, arguments ...Term) Term {
    return &Structure{
        Func:   functor,
        Args:   arguments,
    }
}

func NewVar(name string) Term {
    // sanity check the variable name's syntax
    isCapitalized, err := MatchString(`^[A-Z_]`, name)
    maybePanic(err)
    if !isCapitalized {
        panic("Variable names must start with a capital letter or underscore")
    }

    // make sure anonymous variables are unique
    if name == "_" {
        i := <-anonCounter
        name = Sprintf("_G%d", i)
    }
    return &Variable{
        Name:   name,
    }
}

func IsVariable(t Term) bool {
    switch t.(type) {
        case *Structure:
            return false
        case *Variable:
            return true
        case *Error:
            return false
    }
    msg := Sprintf("Unexpected term type: %#v", t)
    panic(msg)
}
func IsError(t Term) bool {
    switch t.(type) {
        case *Structure:
            return false
        case *Variable:
            return false
        case *Error:
            return true
    }
    msg := Sprintf("Unexpected term type: %#v", t)
    panic(msg)
}

// QuoteFunctor returns a canonical representation of a term's name
// by quoting characters that require quoting
func QuoteFunctor(name string) string {
    // names composed entirely of graphic characters need no quoting
    allGraphic := true
    for _, c := range name {
        if !scanner.IsGraphic(c) {
            allGraphic = false
            break
        }
    }
    if allGraphic {
        return name
    }

    nonAlpha, err := MatchString(`\W`, name)
    maybePanic(err)
    nonLower, err := MatchString(`^[^a-z]`, name)
    if nonAlpha || nonLower {
        escapedName := strings.Replace(name, `'`, `\'`, -1)
        return Sprintf("'%s'", escapedName)
    }

    return name
}

func maybePanic(err error) {
    if err != nil {
        panic(err)
    }
}
<commit_msg>Rename Structure to Compound<commit_after>package golog

import . "fmt"
import . "regexp"
import "strings"
import "bytes"
import "github.com/mndrix/golog/scanner"

var anonCounter <-chan int64
func init() {
    // goroutine providing a counter for anonymous variables
    c := make(chan int64)
    var i int64 = 1
    go func() {
        for {
            c <- i
            i++
        }
    }()
    anonCounter = c
}

// Term represents a single Prolog term which might be an atom, a structure,
// a number, etc.
type Term interface {
    // Functor returns the term's name
    Functor() string

    // Arity returns the number of arguments a term has. An atom has 0 arity.
    Arity() int

    // Arguments returns a slice of this term's arguments, if any
    Arguments() []Term

    // Body returns a term's second argument; otherwise, panics
    Body() Term

    // Head returns a term's first argument; otherwise, panics
    Head() Term

    // Error returns an error value if this is an error term
    Error() error

    // IsClause returns true if the term is like 'Head :- Body'
    IsClause() bool

    // String provides a string representation of a term
    String() string

    // Indicator() provides a "predicate indicator" representation of a term
    Indicator() string
}

// ISO calls this a "compound term" see §6.1.2(e)
// We currently use this type to cover atoms defined in §6.1.2(b)
type Compound struct {
    Func    string
    Args    []Term
}
func (self *Compound) Functor() string {
    return self.Func
}
func (self *Compound) Arity() int {
    return len(self.Args)
}
func (self *Compound) Arguments() []Term {
    return self.Args
}
func (self *Compound) Body() Term {
    return self.Args[1]
}
func (self *Compound) Head() Term {
    return self.Args[0]
}
func (self *Compound) IsClause() bool {
    return self.Arity() == 2 && self.Functor() == ":-"
}
func (self *Compound) String() string {
    // an atom
    quotedFunctor := QuoteFunctor(self.Functor())
    if self.Arity() == 0 {
        return quotedFunctor
    }

    var buf bytes.Buffer
    Fprintf(&buf, "%s(", quotedFunctor)
    arity := self.Arity()
    for i := 0; i<arity; i++ {
        if i>0 {
            Fprintf(&buf, ", ")
        }
        Fprintf(&buf, "%s", self.Arguments()[i])
    }
    Fprintf(&buf, ")")
    return buf.String()
}
func (self *Compound) Indicator() string {
    return Sprintf("%s/%d", self.Functor(), self.Arity())
}
func (self *Compound) Error() error {
    panic("Can't call Error() on a Structure")
}

// See §6.1.2(a)
type Variable struct {
    Name    string
}
func (self *Variable) Functor() string {
    panic("Variables have no Functor()")
}
func (self *Variable) Arity() int {
    panic("Variables have no Arity()")
}
func (self *Variable) Arguments() []Term {
    panic("Variables have no Arguments()")
}
func (self *Variable) Body() Term {
    panic("Variables have no Body()")
}
func (self *Variable) Head() Term {
    panic("Variables have no Head()")
}
func (self *Variable) IsClause() bool {
    return false
}
func (self *Variable) String() string {
    return self.Name
}
func (self *Variable) Indicator() string {
    return Sprintf("%s", self.Name)
}
func (self *Variable) Error() error {
    panic("Can't call Error() on a Variable")
}

type Error string
func (self *Error) Functor() string {
    panic("Errors have no Functor()")
}
func (self *Error) Arity() int {
    panic("Errors have no Arity()")
}
func (self *Error) Arguments() []Term {
    panic("Errors have no Arguments()")
}
func (self *Error) Body() Term {
    panic("Errors have no Body()")
}
func (self *Error) Head() Term {
    panic("Errors have no Head()")
}
func (self *Error) IsClause() bool {
    return false
}
func (self *Error) String() string {
    return string(*self)
}
func (self *Error) Indicator() string {
    panic("Errors have no Indicator()")
}
func (self *Error) Error() error {
    return Errorf("%s", *self)
}

// NewTerm creates a new term with the given functor and optional arguments
func NewTerm(functor string, arguments ...Term) Term {
    return &Compound{
        Func:   functor,
        Args:   arguments,
    }
}

func NewVar(name string) Term {
    // sanity check the variable name's syntax
    isCapitalized, err := MatchString(`^[A-Z_]`, name)
    maybePanic(err)
    if !isCapitalized {
        panic("Variable names must start with a capital letter or underscore")
    }

    // make sure anonymous variables are unique
    if name == "_" {
        i := <-anonCounter
        name = Sprintf("_G%d", i)
    }
    return &Variable{
        Name:   name,
    }
}

func IsVariable(t Term) bool {
    switch t.(type) {
        case *Compound:
            return false
        case *Variable:
            return true
        case *Error:
            return false
    }
    msg := Sprintf("Unexpected term type: %#v", t)
    panic(msg)
}
func IsError(t Term) bool {
    switch t.(type) {
        case *Compound:
            return false
        case *Variable:
            return false
        case *Error:
            return true
    }
    msg := Sprintf("Unexpected term type: %#v", t)
    panic(msg)
}

// QuoteFunctor returns a canonical representation of a term's name
// by quoting characters that require quoting
func QuoteFunctor(name string) string {
    // names composed entirely of graphic characters need no quoting
    allGraphic := true
    for _, c := range name {
        if !scanner.IsGraphic(c) {
            allGraphic = false
            break
        }
    }
    if allGraphic {
        return name
    }

    nonAlpha, err := MatchString(`\W`, name)
    maybePanic(err)
    nonLower, err := MatchString(`^[^a-z]`, name)
    if nonAlpha || nonLower {
        escapedName := strings.Replace(name, `'`, `\'`, -1)
        return Sprintf("'%s'", escapedName)
    }

    return name
}

func maybePanic(err error) {
    if err != nil {
        panic(err)
    }
}
<|endoftext|>


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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

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

import (
	"errors"
	"fmt"

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

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

func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	var name, sal string    // Entities
	var nameval, salval string // Asset holdings
	var err error

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

	// Initialize the chaincode
	name = args[0]
	nameval = args[1]

	sal = args[2]
	salval = args[3]

	fmt.Printf("nameval = %d, salval = %d\n", nameval, salval)

	// Write the state to the ledger
	err = stub.PutState(name, []byte(nameval))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(sal, []byte(salval))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Transaction makes payment of X units from A to B
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	var name, sal string    // Entities
	var nameval, salval string // Asset holdings
	var err error

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

	// Initialize the chaincode
	name = args[0]
	nameval = args[1]

	sal = args[2]
	salval = args[3]

	fmt.Printf("nameval = %d, salval = %d\n", nameval, salval)

	// Write the state to the ledger
	err = stub.PutState(name, []byte(nameval))
	if err != nil {
		return nil, err
	}

	err = stub.PutState(sal, []byte(salval))
	if err != nil {
		return nil, err
	}

	return nil, nil

}

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

	A := args[0]

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

	return nil, nil
}

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

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

	A = args[0]

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

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

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

func main() {
	err := shim.Start(new(SimpleChaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}
<commit_msg>testjson<commit_after>/*
Copyright IBM Corp. 2016 All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

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

import (
	"errors"
	"fmt"
	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {

}

func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	return nil, nil
}

// Transaction makes payment of X units from A to B
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	var message string // Entities
	var messageval string // Asset holdings
	var err error

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

	// Initialize the chaincode

	message = args[0]
	messageval = args[1]

	fmt.Printf("message = %d", messageval)

	// Write the state to the ledger
	err = stub.PutState(message, []byte(messageval))
	if err != nil {
		return nil, err
	}
	return nil, nil

}

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

	A := args[0]

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

	return nil, nil
}

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

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

	message = args[0]

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

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

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

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


<commit_before>package main

import (
	"fmt"
	"os"
	"strconv"
	"./ssdb"
)

func main() {
	ip := "127.0.0.1"
	port := 8888
	db, err := ssdb.Connect(ip, port)
	if err != nil {
		os.Exit(1)
	}

	defer db.Close()
	var val interface{}

	keys := []string{}
	keys = append(keys, "c");
	keys = append(keys, "d");
	val, err = db.Do("multi_get", "a", "b", keys);
	fmt.Printf("%s\n", val);

	db.Set("a", "xxx")
	val, err = db.Get("a")
	fmt.Printf("%s\n", val)
	db.Del("a")
	val, err = db.Get("a")
	fmt.Printf("%s\n", val)

	fmt.Printf("----\n");

	db.Do("zset", "z", "a", 3)
	db.Do("multi_zset", "z", "b", -2, "c", 5, "d", 3)
	resp, err := db.Do("zrscan", "z", "", "", "", 10)
	if err != nil {
		os.Exit(1)
	}
	if len(resp)%2 != 1 {
		fmt.Printf("bad response")
		os.Exit(1)
	}

	fmt.Printf("Status: %s\n", resp[0])
	for i := 1; i < len(resp); i += 2 {
		fmt.Printf("  %s : %3s\n", resp[i], resp[i+1])
	}

	//_ = db.Send("dump", "", "", "-1");
	_ = db.Send("sync140");
	// receive multi responses on one request
	for{
		resp, _ := db.Recv()
		fmt.Printf("%s\n", strconv.Quote(fmt.Sprintf("%s", resp)));
	}

	return
}
<commit_msg>Fix testing warning.<commit_after>package main

import (
	"fmt"
	"os"
	"strconv"
	"github.com/ssdb/gossdb/ssdb"
)

func main() {
	ip := "127.0.0.1"
	port := 8888
	db, err := ssdb.Connect(ip, port)
	if err != nil {
		os.Exit(1)
	}

	defer db.Close()
	var val interface{}

	keys := []string{}
	keys = append(keys, "c");
	keys = append(keys, "d");
	val, err = db.Do("multi_get", "a", "b", keys);
	fmt.Printf("%s\n", val);

	db.Set("a", "xxx")
	val, err = db.Get("a")
	fmt.Printf("%s\n", val)
	db.Del("a")
	val, err = db.Get("a")
	fmt.Printf("%s\n", val)

	fmt.Printf("----\n");

	db.Do("zset", "z", "a", 3)
	db.Do("multi_zset", "z", "b", -2, "c", 5, "d", 3)
	resp, err := db.Do("zrscan", "z", "", "", "", 10)
	if err != nil {
		os.Exit(1)
	}
	if len(resp)%2 != 1 {
		fmt.Printf("bad response")
		os.Exit(1)
	}

	fmt.Printf("Status: %s\n", resp[0])
	for i := 1; i < len(resp); i += 2 {
		fmt.Printf("  %s : %3s\n", resp[i], resp[i+1])
	}

	//_ = db.Send("dump", "", "", "-1");
	_ = db.Send("sync140");
	// receive multi responses on one request
	for{
		resp, _ := db.Recv()
		fmt.Printf("%s\n", strconv.Quote(fmt.Sprintf("%s", resp)));
	}

	return
}
<|endoftext|>


<commit_before><commit_msg>Added log<commit_after><|endoftext|>


<commit_before>package goboots

import (
	"regexp"
	"strings"
)

const (
	routeMethodExact       = byte(0)
	routeMethodRemainder   = byte(1)
	routeMethodRegExp      = byte(2)
	routeMethodIgnoreTrail = byte(3)
)

type Route struct {
	Path        string
	Controller  string
	Method      string
	RedirectTLS bool
	_t          byte
}

func (route *Route) IsMatch(url string) bool {
	switch route._t {
	case routeMethodRegExp:
		return route.isMatchRegExp(url)
	case routeMethodRemainder:
		return route.isMatchRemainder(url)
	case routeMethodExact:
		return route.isMatchExact(url)
	case routeMethodIgnoreTrail:
		return route.isMatchIgnoreTrail(url)
	}
	return false
}

func (route *Route) isMatchRegExp(url string) bool {
	match, _ := regexp.MatchString(route.Path, url)
	return match
}

func (route *Route) isMatchExact(url string) bool {
	return url == route.Path
}

func (route *Route) isMatchRemainder(url string) bool {
	return strings.HasPrefix(url, route.Path)
}

func (route *Route) isMatchIgnoreTrail(url string) bool {
	return url == strings.TrimRight(route.Path, "/")
}
<commit_msg>fixed ignore trail match<commit_after>package goboots

import (
	"regexp"
	"strings"
)

const (
	routeMethodExact       = byte(0)
	routeMethodRemainder   = byte(1)
	routeMethodRegExp      = byte(2)
	routeMethodIgnoreTrail = byte(3)
)

type Route struct {
	Path        string
	Controller  string
	Method      string
	RedirectTLS bool
	_t          byte
}

func (route *Route) IsMatch(url string) bool {
	switch route._t {
	case routeMethodRegExp:
		return route.isMatchRegExp(url)
	case routeMethodRemainder:
		return route.isMatchRemainder(url)
	case routeMethodExact:
		return route.isMatchExact(url)
	case routeMethodIgnoreTrail:
		return route.isMatchIgnoreTrail(url)
	}
	return false
}

func (route *Route) isMatchRegExp(url string) bool {
	match, _ := regexp.MatchString(route.Path, url)
	return match
}

func (route *Route) isMatchExact(url string) bool {
	return url == route.Path
}

func (route *Route) isMatchRemainder(url string) bool {
	return strings.HasPrefix(url, route.Path)
}

func (route *Route) isMatchIgnoreTrail(url string) bool {
	return strings.TrimRight(url, "/") == route.Path[:len(route.Path)-2]
}
<|endoftext|>


<commit_before>package ai

import (
	"math/rand"
	"time"

	"github.com/loganjspears/chess"
)

type AI interface {
	Move(gs *chess.GameState) *chess.Move
}

type Random struct{}

func (r Random) Move(gs *chess.GameState) *chess.Move {
	moves := gs.ValidMoves()
	rand.Seed(time.Now().UnixNano())
	return moves[rand.Intn(len(moves))]
}

type Athena struct {
	Ply int
}

func (a Athena) Move(gs *chess.GameState) *chess.Move {
	rand.Seed(time.Now().UnixNano())
	return minMax(gs, a.Ply, 0)
}

func minMax(gs *chess.GameState, maxPly, ply int) *chess.Move {
	var topMove *chess.Move
	topScore := -1000.0

	for _, m := range gs.ValidMoves() {
		state := m.PostMoveState()
		if maxPly != ply {
			plyMove := minMax(state, maxPly, ply+1)
			state = plyMove.PostMoveState()
		}
		scr := score(state, gs.Turn()) + (rand.Float64() / 100)
		if scr > topScore {
			topMove = m
			topScore = scr
		}
	}
	return topMove
}

func score(gs *chess.GameState, color chess.Color) float64 {
	outcome, _ := gs.Outcome()
	switch outcome {
	case chess.WhiteWon:
		if color == chess.White {
			return 1000.0
		}
		return -1000.0
	case chess.BlackWon:
		if color == chess.Black {
			return 1000.0
		}
		return -1000.0
	case chess.Draw:
		return 0.0
	}

	total := 0.0
	for _, piece := range gs.Board() {
		score := pieceScore(gs, piece)
		if piece.Color() == color {
			total += score
		} else {
			total -= score
		}
	}
	return total
}

func pieceScore(gs *chess.GameState, piece *chess.Piece) float64 {
	switch piece.Type() {
	case chess.King:
		return 200.0
	case chess.Queen:
		return 9.0
	case chess.Rook:
		return 5.0
	case chess.Bishop:
		return 3.1
	case chess.Knight:
		return 3.0
	case chess.Pawn:
		return 1.0
	}
	return 0.0
}
<commit_msg>bug fix for terminal game state nodes<commit_after>package ai

import (
	"math/rand"
	"time"

	"github.com/loganjspears/chess"
)

type AI interface {
	Move(gs *chess.GameState) *chess.Move
}

type Random struct{}

func (r Random) Move(gs *chess.GameState) *chess.Move {
	moves := gs.ValidMoves()
	rand.Seed(time.Now().UnixNano())
	return moves[rand.Intn(len(moves))]
}

type Athena struct {
	Ply int
}

func (a Athena) Move(gs *chess.GameState) *chess.Move {
	rand.Seed(time.Now().UnixNano())
	return minMax(gs, a.Ply, 0)
}

func minMax(gs *chess.GameState, maxPly, ply int) *chess.Move {
	var topMove *chess.Move
	topScore := -1000.0
	for _, m := range gs.ValidMoves() {
		state := m.PostMoveState()
		if maxPly != ply {
			plyMove := minMax(state, maxPly, ply+1)
			if plyMove != nil {
				state = plyMove.PostMoveState()
			}
		}
		scr := score(state, gs.Turn()) + (rand.Float64() / 100)
		if scr > topScore {
			topMove = m
			topScore = scr
		}
	}
	return topMove
}

func score(gs *chess.GameState, color chess.Color) float64 {
	outcome, _ := gs.Outcome()
	switch outcome {
	case chess.WhiteWon:
		if color == chess.White {
			return 1000.0
		}
		return -1000.0
	case chess.BlackWon:
		if color == chess.Black {
			return 1000.0
		}
		return -1000.0
	case chess.Draw:
		return 0.0
	}

	total := 0.0
	for _, piece := range gs.Board() {
		score := pieceScore(gs, piece)
		if piece.Color() == color {
			total += score
		} else {
			total -= score
		}
	}
	return total
}

func pieceScore(gs *chess.GameState, piece *chess.Piece) float64 {
	switch piece.Type() {
	case chess.King:
		return 200.0
	case chess.Queen:
		return 9.0
	case chess.Rook:
		return 5.0
	case chess.Bishop:
		return 3.1
	case chess.Knight:
		return 3.0
	case chess.Pawn:
		return 1.0
	}
	return 0.0
}
<|endoftext|>