<commit_before>package main

import (
	"fmt"
)

const formatOptionHelp = `
This command supports advanced formatting via --format flag with full
support of Golang templates (https://golang.org/pkg/text/template).

Special formatting functions are available:

  > {{name <variable>}} — return file URI without extension for specified
    <variable>;
  > {{ext <variable}} — return extension from file URI for specified <variable>;
`

const authenticationOptionsHelp = `
  --user <user>
    Specify user ID for authentication.

  --secret <secret>
    Specify secret token for authentication.

  -a --account <account>
    Specify account ID.
`

const globPatternHelp = `argument support globbing with following patterns:

  > ** — matches any number of any chars;
  > *  — matches any number of chars except '/';
  > ?  — matches any single char except '/';
  > [xyz]   — matches 'x', 'y' or 'z' charachers;
  > [!xyz]  — matches not 'x', 'y' or 'z' charachers;
  > {a,b,c} — matches alternatives a, b or c;`

const initHelp = `smartling init — create config file interactively.

Walk down common config file parameters and fill them through dialog.

Init process will inspect if config file already exists and if it is, it will
be loaded as default values, so init can be used sequentially without config
is lost.

Options like --user, --secret, --account and --project can be used to specify
config values prior dialog:

  smartling init --user=your_user_id

Also, --dry-run option can be used to just look at resulting config without
overwritting anything:

  smartling init --dry-run

By default, smartling.yml file in the local directory will be used as target
config file, but it can be overriden by using --config option:

  smartling init --config=/path/to/project/smartling.yml

Available options:
  -c --config <file>
    Specify config file to operate on. Default: smartling.yml

  --dry-run
    Do not overwrite config file, only output to stdout.

Default config values can be passed via following options:` +
	authenticationOptionsHelp + `
  -p --project <project>
    Specify default project.
`

const projectsListHelp = `smartling projects list — list projects from account.

Command will list projects from specified account in tabular format with
following information:

  > Project ID
  > Project Description
  > Project Source Locale ID

Only project IDs will be listed if --short option is specified.

Note, that you should specify account ID either in config file or via --account
option to be able to see projects list.

Available options:
  -s --short
    List only project IDs.
` + authenticationOptionsHelp

const projectsInfoHelp = `smartling projects info — show detailed project info.

Displays detailed information for specific project.

Project should be specified either in config or via --project option.

Available options:` + authenticationOptionsHelp

const projectsLocalesHelp = `smartling projects locales — list target locales.

Lists target locales from specified project.

To list only locale IDs --short option can be used.
` + formatOptionHelp + `
Following variables are available:

  > .LocaleID — target locale ID to translate into;
  > .Description — human-readable locale description;
  > .Enabled — true/false specifying is locale active or not;

Available options:
  -p --project <project>
    Specify project to use.

  -s --short
    List only locale IDs.

  --format
    Use specific output format instead of default.
` + authenticationOptionsHelp

const filesListHelp = `smartling files list — list files from project.

Lists all files from project or only files which matches specified uri.

Note, that by default listing is limited to 500 items in Smartling API,
so several requests may be needed to obtain full file list, which will
take some time.

List command will output following fields in tabular format by default:

  > File URI;
  > Last uploaded date;
  > File Type;
` + formatOptionHelp + `
Following variables are available:

  > .FileURI — full file URI in Smartling system;
  > .FileType — internal Smartling file type;
  > .LastUploaded — timestamp when file was last uploaded;
  > .HasInstructions — true/false if file has translation instructions;

<uri> ` + globPatternHelp + `

Available options:
  -p --project <project>
    Specify project to use.

  -s --short
    List only file URIs.

  --format <format>
    Override default listing format.
` + authenticationOptionsHelp

const filesPullHelp = `smartling files pull — downloads translated files from project.

Downloads files from specified project into local directory.

It's possible to download only specific files by file mask, to download source
files with translations, to download file to specific directory or to download
specific locales only.

If special value of "-" is specified as <uri>, then program will expect
to read files list from stdin:

  cat files.txt | smartling files pull -

<uri> ` + globPatternHelp + `

If --locale flag is not specified, all available locales are downloaded. To
see available locales, use "status" command.

To download files into subdirectory, use --directory option and specify
directory name you want to download into.

To download source file as well as translated files specify --source option.

Files will be downloaded and stored under names used while upload (e.g. File
URI). While downloading translated file suffix "_<locale>" will be appended to
file name before extension. To override file format name, use --format option.
` + formatOptionHelp + `
Following variables are available:

  > .FileURI — full file URI in Smartling system;
  > .Locale — locale ID for translated file and empty for source file;

Available options:
  -p --project <project>
    Specify project to use.

  --source
    Download source files along with translated files.

  —d ——directory <dir>
    Download files into specified directory.

  --format <format>
    Specify format for download file nmae.
` + authenticationOptionsHelp

const filesPushHelp = `smartling files push — upload files to project.

Uploads files designated for translation.

One or several files can be pushed.

When pushing single file, <uri> can be specified to override local path.
When pushing multiple files, they will be uploaded using local path as URI.
If no file specified in command line, config file will be used to lookup
for file masks to push.

To authorize all locales, use --authorize option.

To authorize only specific locales, use one or more --locale.

To prepend prefix to all target URIs, use --branch option. Special
value "@auto" can be used to tell that tool should try to took current git
branch name as value for --branch option.

File type will be deduced from file extension. If file extension is unknown,
type should be specified manually by using --type option. That option also
can be used to override detected file type.

<file> ` + globPatternHelp + `

Available options:
  -p --project <project>
    Specify project to use.

  --authorize
    Authorize all available locales. Incompatible with --locale option.

  --locale <locale>
    Authorize speicified locale only. Can be specified several times.
    Incompatible with --authorize option.

  --branch <branch>
    Prepend specified prefix to target file URI.

  --type <type>
    Override automatically detected file type.
` + authenticationOptionsHelp

const filesStatusHelp = `smartling files status — show files status from project.

Lists all files from project along with their translation progress into
different locales.

Status command will check, if files are missing locally or not.

Command will list projects from specified account in tabular format with
following information:

  > File URI
  > File Locale
  > File Status on Local System
  > Translation Progress
  > Strings Count
  > Words Count

If no <uri> is specified, all files will be listed.

To list files status from specific directory, --directory option can be used.

To override default file name format --format can be used.
` + formatOptionHelp + `
Following variables are available:

  > .FileURI — full file URI in Smartling system;
  > .Locale — locale ID for translated file and empty for source file;

<uri> ` + globPatternHelp + `

Available options:
  -p --project <project>
    Specify project to use.

  --directory <directory>
    Check files in specific directory instead of local directory.

  --format <format>
    Specify format for listing file names.
` + authenticationOptionsHelp

const filesDeleteHelp = `smartling files delete — removes files from project.

Removes files from project according to specified pattern.

<uri> ` + globPatternHelp + `

If special value of "-" is specified as <uri>, then program will expect
to read files list from stdin:

  cat files.txt | smartling files delete -

Available options:
  -p --project <project>
    Specify project to use.
` + authenticationOptionsHelp

func showHelp(args map[string]interface{}) {
	switch {
	case args["init"].(bool):
		fmt.Print(initHelp)

	case args["projects"].(bool):
		switch {
		case args["list"].(bool):
			fmt.Print(projectsListHelp)

		case args["info"].(bool):
			fmt.Print(projectsInfoHelp)

		case args["locales"].(bool):
			fmt.Print(projectsLocalesHelp)
		}

	case args["files"].(bool):
		switch {
		case args["list"].(bool):
			fmt.Print(filesListHelp)
		case args["pull"].(bool):
			fmt.Print(filesPullHelp)
		case args["push"].(bool):
			fmt.Print(filesPushHelp)
		case args["status"].(bool):
			fmt.Print(filesStatusHelp)
		case args["delete"].(bool):
			fmt.Print(filesDeleteHelp)
		}

	default:
		fmt.Print(usage)
	}
}
<commit_msg>add help about --progress<commit_after>package main

import (
	"fmt"
)

const formatOptionHelp = `
This command supports advanced formatting via --format flag with full
support of Golang templates (https://golang.org/pkg/text/template).

Special formatting functions are available:

  > {{name <variable>}} — return file URI without extension for specified
    <variable>;
  > {{ext <variable}} — return extension from file URI for specified <variable>;
`

const authenticationOptionsHelp = `
  --user <user>
    Specify user ID for authentication.

  --secret <secret>
    Specify secret token for authentication.

  -a --account <account>
    Specify account ID.
`

const globPatternHelp = `argument support globbing with following patterns:

  > ** — matches any number of any chars;
  > *  — matches any number of chars except '/';
  > ?  — matches any single char except '/';
  > [xyz]   — matches 'x', 'y' or 'z' charachers;
  > [!xyz]  — matches not 'x', 'y' or 'z' charachers;
  > {a,b,c} — matches alternatives a, b or c;`

const initHelp = `smartling init — create config file interactively.

Walk down common config file parameters and fill them through dialog.

Init process will inspect if config file already exists and if it is, it will
be loaded as default values, so init can be used sequentially without config
is lost.

Options like --user, --secret, --account and --project can be used to specify
config values prior dialog:

  smartling init --user=your_user_id

Also, --dry-run option can be used to just look at resulting config without
overwritting anything:

  smartling init --dry-run

By default, smartling.yml file in the local directory will be used as target
config file, but it can be overriden by using --config option:

  smartling init --config=/path/to/project/smartling.yml

Available options:
  -c --config <file>
    Specify config file to operate on. Default: smartling.yml

  --dry-run
    Do not overwrite config file, only output to stdout.

Default config values can be passed via following options:` +
	authenticationOptionsHelp + `
  -p --project <project>
    Specify default project.
`

const projectsListHelp = `smartling projects list — list projects from account.

Command will list projects from specified account in tabular format with
following information:

  > Project ID
  > Project Description
  > Project Source Locale ID

Only project IDs will be listed if --short option is specified.

Note, that you should specify account ID either in config file or via --account
option to be able to see projects list.

Available options:
  -s --short
    List only project IDs.
` + authenticationOptionsHelp

const projectsInfoHelp = `smartling projects info — show detailed project info.

Displays detailed information for specific project.

Project should be specified either in config or via --project option.

Available options:` + authenticationOptionsHelp

const projectsLocalesHelp = `smartling projects locales — list target locales.

Lists target locales from specified project.

To list only locale IDs --short option can be used.
` + formatOptionHelp + `
Following variables are available:

  > .LocaleID — target locale ID to translate into;
  > .Description — human-readable locale description;
  > .Enabled — true/false specifying is locale active or not;

Available options:
  -p --project <project>
    Specify project to use.

  -s --short
    List only locale IDs.

  --format
    Use specific output format instead of default.
` + authenticationOptionsHelp

const filesListHelp = `smartling files list — list files from project.

Lists all files from project or only files which matches specified uri.

Note, that by default listing is limited to 500 items in Smartling API,
so several requests may be needed to obtain full file list, which will
take some time.

List command will output following fields in tabular format by default:

  > File URI;
  > Last uploaded date;
  > File Type;
` + formatOptionHelp + `
Following variables are available:

  > .FileURI — full file URI in Smartling system;
  > .FileType — internal Smartling file type;
  > .LastUploaded — timestamp when file was last uploaded;
  > .HasInstructions — true/false if file has translation instructions;

<uri> ` + globPatternHelp + `

Available options:
  -p --project <project>
    Specify project to use.

  -s --short
    List only file URIs.

  --format <format>
    Override default listing format.
` + authenticationOptionsHelp

const filesPullHelp = `smartling files pull — downloads translated files from project.

Downloads files from specified project into local directory.

It's possible to download only specific files by file mask, to download source
files with translations, to download file to specific directory or to download
specific locales only.

If special value of "-" is specified as <uri>, then program will expect
to read files list from stdin:

  cat files.txt | smartling files pull -

<uri> ` + globPatternHelp + `

If --locale flag is not specified, all available locales are downloaded. To
see available locales, use "status" command.

To download files into subdirectory, use --directory option and specify
directory name you want to download into.

To download source file as well as translated files specify --source option.

Files will be downloaded and stored under names used while upload (e.g. File
URI). While downloading translated file suffix "_<locale>" will be appended to
file name before extension. To override file format name, use --format option.
` + formatOptionHelp + `
Following variables are available:

  > .FileURI — full file URI in Smartling system;
  > .Locale — locale ID for translated file and empty for source file;

Available options:
  -p --project <project>
    Specify project to use.

  --source
    Download source files along with translated files.

  —d ——directory <dir>
    Download files into specified directory.

  --format <format>
    Specify format for download file nmae.

  --progress <percents>
    Specify minimum of translation progress in percents.
	By default that filter does not apply.
` + authenticationOptionsHelp

const filesPushHelp = `smartling files push — upload files to project.

Uploads files designated for translation.

One or several files can be pushed.

When pushing single file, <uri> can be specified to override local path.
When pushing multiple files, they will be uploaded using local path as URI.
If no file specified in command line, config file will be used to lookup
for file masks to push.

To authorize all locales, use --authorize option.

To authorize only specific locales, use one or more --locale.

To prepend prefix to all target URIs, use --branch option. Special
value "@auto" can be used to tell that tool should try to took current git
branch name as value for --branch option.

File type will be deduced from file extension. If file extension is unknown,
type should be specified manually by using --type option. That option also
can be used to override detected file type.

<file> ` + globPatternHelp + `

Available options:
  -p --project <project>
    Specify project to use.

  --authorize
    Authorize all available locales. Incompatible with --locale option.

  --locale <locale>
    Authorize speicified locale only. Can be specified several times.
    Incompatible with --authorize option.

  --branch <branch>
    Prepend specified prefix to target file URI.

  --type <type>
    Override automatically detected file type.
` + authenticationOptionsHelp

const filesStatusHelp = `smartling files status — show files status from project.

Lists all files from project along with their translation progress into
different locales.

Status command will check, if files are missing locally or not.

Command will list projects from specified account in tabular format with
following information:

  > File URI
  > File Locale
  > File Status on Local System
  > Translation Progress
  > Strings Count
  > Words Count

If no <uri> is specified, all files will be listed.

To list files status from specific directory, --directory option can be used.

To override default file name format --format can be used.
` + formatOptionHelp + `
Following variables are available:

  > .FileURI — full file URI in Smartling system;
  > .Locale — locale ID for translated file and empty for source file;

<uri> ` + globPatternHelp + `

Available options:
  -p --project <project>
    Specify project to use.

  --directory <directory>
    Check files in specific directory instead of local directory.

  --format <format>
    Specify format for listing file names.
` + authenticationOptionsHelp

const filesDeleteHelp = `smartling files delete — removes files from project.

Removes files from project according to specified pattern.

<uri> ` + globPatternHelp + `

If special value of "-" is specified as <uri>, then program will expect
to read files list from stdin:

  cat files.txt | smartling files delete -

Available options:
  -p --project <project>
    Specify project to use.
` + authenticationOptionsHelp

func showHelp(args map[string]interface{}) {
	switch {
	case args["init"].(bool):
		fmt.Print(initHelp)

	case args["projects"].(bool):
		switch {
		case args["list"].(bool):
			fmt.Print(projectsListHelp)

		case args["info"].(bool):
			fmt.Print(projectsInfoHelp)

		case args["locales"].(bool):
			fmt.Print(projectsLocalesHelp)
		}

	case args["files"].(bool):
		switch {
		case args["list"].(bool):
			fmt.Print(filesListHelp)
		case args["pull"].(bool):
			fmt.Print(filesPullHelp)
		case args["push"].(bool):
			fmt.Print(filesPushHelp)
		case args["status"].(bool):
			fmt.Print(filesStatusHelp)
		case args["delete"].(bool):
			fmt.Print(filesDeleteHelp)
		}

	default:
		fmt.Print(usage)
	}
}
<|endoftext|>


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

/*
Hist shows the history of a given file, using Arq backups.

    usage: hist [-d] [-h host] [-m mtpt] [-s yyyy/mmdd] file ...

The -d flag causes it to show diffs between successive versions.

By default, hist assumes backups are mounted at mtpt/host, where
mtpt defaults to /mnt/arq and host is the first element of the local host name.
Hist starts the file list with the present copy of the file.

The -h and -s flags override these assumptions.

*/
package main

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

var usageString = `usage: hist [-d] [-h host] [-m mtpt] [-s yyyy/mmdd] file ...

Hist lists the known versions of the given file.
The -d flag causes it to show diffs between successive versions.

By default, hist assumes backups are mounted at mtpt/host, where
mtpt defaults to /mnt/arq and host is the first element of the local host name.
Hist starts the file list with the present copy of the file.

The -h and -s flags override these assumptions.
`

var (
	diff = flag.Bool("d", false, "diff")
	host = flag.String("h", defaultHost(), "host name")
	mtpt = flag.String("m", "/mnt/arq", "mount point")
	vers = flag.String("s", "", "version")
)

func defaultHost() string {
	name, _ := os.Hostname()
	if name == "" {
		name = "gnot"
	}
	if i := strings.Index(name, "."); i >= 0 {
		name = name[:i]
	}
	return name
}

func main() {
	flag.Usage = func() {
		fmt.Fprint(os.Stderr, usageString)
		os.Exit(2)
	}

	flag.Parse()
	args := flag.Args()
	if len(args) == 0 {
		flag.Usage()
	}

	dates := loadDates()
	for _, file := range args {
		list(dates, file)
	}
}

var (
	yyyy = regexp.MustCompile(`^\d{4}$`)
	mmdd = regexp.MustCompile(`^\d{4}(\.\d+)?$`)
)

func loadDates() []string {
	var all []string
	ydir, err := ioutil.ReadDir(filepath.Join(*mtpt, *host))
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(3)
	}
	for _, y := range ydir {
		if !y.IsDir() || !yyyy.MatchString(y.Name()) {
			continue
		}
		ddir, err := ioutil.ReadDir(filepath.Join(*mtpt, *host, y.Name()))
		if err != nil {
			continue
		}
		for _, d := range ddir {
			if !d.IsDir() || !mmdd.MatchString(d.Name()) {
				continue
			}
			date := y.Name() + "/" + d.Name()
			if *vers > date {
				continue
			}
			all = append(all, filepath.Join(*mtpt, *host, date))
		}
	}
	return all
}

const timeFormat = "Jan 02 15:04:05 MST 2006"

func list(dates []string, file string) {
	var (
		last os.FileInfo
		lastPath string
	)

	fi, err := os.Stat(file)
	if err != nil {
		fmt.Fprintf(os.Stderr, "hist: warning: %s: %v\n", file, err)
	} else {
		fmt.Printf("%s %s %d\n", fi.ModTime().Format(timeFormat), file, fi.Size())
		last = fi
		lastPath = file
	}

	file, err = filepath.Abs(file)
	if err != nil {
		fmt.Fprintf(os.Stderr, "hist: abs: %v\n", err)
		return
	}

	for i := len(dates)-1; i >= 0; i-- {
		p := filepath.Join(dates[i], file)
		fi, err := os.Stat(p)
		if err != nil {
			continue
		}
		if last != nil && fi.ModTime() == last.ModTime() && fi.Size() == last.Size() {
			continue
		}
		if *diff {
			cmd := exec.Command("diff", lastPath, p)
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			if err := cmd.Start(); err != nil {
				fmt.Fprintf(os.Stderr, "%s\n", err)
			}
			cmd.Wait()
		}
		fmt.Printf("%s %s %d\n", fi.ModTime().Format(timeFormat), file, fi.Size())
		last = fi
		lastPath = p
	}
}

<commit_msg>arq/hist: fix print<commit_after>// Copyright 2012 The Go Authors.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
Hist shows the history of a given file, using Arq backups.

    usage: hist [-d] [-h host] [-m mtpt] [-s yyyy/mmdd] file ...

The -d flag causes it to show diffs between successive versions.

By default, hist assumes backups are mounted at mtpt/host, where
mtpt defaults to /mnt/arq and host is the first element of the local host name.
Hist starts the file list with the present copy of the file.

The -h and -s flags override these assumptions.

*/
package main

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

var usageString = `usage: hist [-d] [-h host] [-m mtpt] [-s yyyy/mmdd] file ...

Hist lists the known versions of the given file.
The -d flag causes it to show diffs between successive versions.

By default, hist assumes backups are mounted at mtpt/host, where
mtpt defaults to /mnt/arq and host is the first element of the local host name.
Hist starts the file list with the present copy of the file.

The -h and -s flags override these assumptions.
`

var (
	diff = flag.Bool("d", false, "diff")
	host = flag.String("h", defaultHost(), "host name")
	mtpt = flag.String("m", "/mnt/arq", "mount point")
	vers = flag.String("s", "", "version")
)

func defaultHost() string {
	name, _ := os.Hostname()
	if name == "" {
		name = "gnot"
	}
	if i := strings.Index(name, "."); i >= 0 {
		name = name[:i]
	}
	return name
}

func main() {
	flag.Usage = func() {
		fmt.Fprint(os.Stderr, usageString)
		os.Exit(2)
	}

	flag.Parse()
	args := flag.Args()
	if len(args) == 0 {
		flag.Usage()
	}

	dates := loadDates()
	for _, file := range args {
		list(dates, file)
	}
}

var (
	yyyy = regexp.MustCompile(`^\d{4}$`)
	mmdd = regexp.MustCompile(`^\d{4}(\.\d+)?$`)
)

func loadDates() []string {
	var all []string
	ydir, err := ioutil.ReadDir(filepath.Join(*mtpt, *host))
	if err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(3)
	}
	for _, y := range ydir {
		if !y.IsDir() || !yyyy.MatchString(y.Name()) {
			continue
		}
		ddir, err := ioutil.ReadDir(filepath.Join(*mtpt, *host, y.Name()))
		if err != nil {
			continue
		}
		for _, d := range ddir {
			if !d.IsDir() || !mmdd.MatchString(d.Name()) {
				continue
			}
			date := y.Name() + "/" + d.Name()
			if *vers > date {
				continue
			}
			all = append(all, filepath.Join(*mtpt, *host, date))
		}
	}
	return all
}

const timeFormat = "Jan 02 15:04:05 MST 2006"

func list(dates []string, file string) {
	var (
		last os.FileInfo
		lastPath string
	)

	fi, err := os.Stat(file)
	if err != nil {
		fmt.Fprintf(os.Stderr, "hist: warning: %s: %v\n", file, err)
	} else {
		fmt.Printf("%s %s %d\n", fi.ModTime().Format(timeFormat), file, fi.Size())
		last = fi
		lastPath = file
	}

	file, err = filepath.Abs(file)
	if err != nil {
		fmt.Fprintf(os.Stderr, "hist: abs: %v\n", err)
		return
	}

	for i := len(dates)-1; i >= 0; i-- {
		p := filepath.Join(dates[i], file)
		fi, err := os.Stat(p)
		if err != nil {
			continue
		}
		if last != nil && fi.ModTime() == last.ModTime() && fi.Size() == last.Size() {
			continue
		}
		if *diff {
			cmd := exec.Command("diff", lastPath, p)
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			if err := cmd.Start(); err != nil {
				fmt.Fprintf(os.Stderr, "%s\n", err)
			}
			cmd.Wait()
		}
		fmt.Printf("%s %s %d\n", fi.ModTime().Format(timeFormat), p, fi.Size())
		last = fi
		lastPath = p
	}
}

<|endoftext|>


<commit_before>// Copyright 2013 Arne Roomann-Kurrik
//
// 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

import (
	"./system"
	"log"
	"math"
)

type Cast struct {
	Texture *system.Texture
	Actors  []*Actor
	Width   int
	Height  int
	OffsetX int
	OffsetY int
}

func LoadCast(path string, width int, height int, th int, tw int) (c *Cast, err error) {
	var t *system.Texture
	if t, err = system.LoadTexture(path, system.IntNearest, width, height); err != nil {
		return
	}
	c = &Cast{
		Texture: t,
		Width:   width,
		Height:  height,
		OffsetX: width - tw,
		OffsetY: height - th,
	}
	return
}

func (c *Cast) AddActor(x float64, y float64, state int, offset int) (a *Actor) {
	a = &Actor{
		X:       x,
		Y:       y,
		State:   state,
		Offset:  offset,
		Rate:    2.0,
		Padding: 12,
	}
	c.Actors = append(c.Actors, a)
	return
}

func (c *Cast) Update(level *Level) {
	for _, a := range c.Actors {
		if !a.TestState(WALKING) {
			continue
		}
		switch {
		case a.TestState(DOWN):
			a.moveDown(level)
		case a.TestState(UP):
			a.moveUp(level)
		case a.TestState(RIGHT):
			a.moveRight(level)
		case a.TestState(LEFT):
			a.moveLeft(level)
		}
	}
	for _, a := range ACTOR_ANIMATIONS {
		a.Next()
	}
}

type Actor struct {
	X       float64
	Y       float64
	State   int
	Offset  int
	FlipX   bool
	Rate    float64
	Padding int
}

// Attempts to round X or Y values to tile boundaries if they're within Padding
func (a *Actor) getClamped(v float64, size int) int {
	var (
		clamped = math.Floor(v/float64(size)+0.5) * float64(size)
		diff    = math.Abs(clamped - v)
	)
	if int(diff) <= a.Padding {
		return int(clamped)
	}
	return int(v)
}

func (a *Actor) moveDown(l *Level) {
	var (
		x int
		y int
	)
	x = a.getClamped(a.X, l.TileWidth)
	if (x == int(a.X)) {
		// Only move once we've clamped.
		y = int(a.Y + a.Rate)
	} else {
		y = int(a.Y)
	}
	if l.TestPixelPassable(x+a.Padding, y+l.TileHeight) &&
		l.TestPixelPassable(x+l.TileWidth-a.Padding, y+l.TileHeight) {
		a.X = float64(x)
		a.Y = float64(y)
	}
}

func (a *Actor) moveUp(l *Level) {
	var (
		x int
		y int
	)
	x = a.getClamped(a.X, l.TileWidth)
	if (x == int(a.X)) {
		// Only move once we've clamped.
		y = int(a.Y - a.Rate)
	} else {
		y = int(a.Y)
	}
	if l.TestPixelPassable(x+a.Padding, y) &&
		l.TestPixelPassable(x+l.TileWidth-a.Padding, y) {
		a.X = float64(x)
		a.Y = float64(y)
	}
}

func (a *Actor) moveRight(l *Level) {
	var (
		x int
		y int
	)
	y = a.getClamped(a.Y, l.TileHeight)
	if (y == int(a.Y)) {
		// Only move once we've clamped.
		x = int(a.X + a.Rate)
	} else {
		x = int(a.X)
	}
	if l.TestPixelPassable(x+l.TileWidth, y+a.Padding) &&
		l.TestPixelPassable(x+l.TileWidth, y+l.TileHeight-a.Padding) {
		a.X = float64(x)
		a.Y = float64(y)
	}
}

func (a *Actor) moveLeft(l *Level) {
	var (
		x int
		y int
	)
	y = a.getClamped(a.Y, l.TileHeight)
	if (y == int(a.Y)) {
		// Only move once we've clamped.
		x = int(a.X - a.Rate)
	} else {
		x = int(a.X)
	}
	if l.TestPixelPassable(x, y+a.Padding) &&
		l.TestPixelPassable(x, y+l.TileHeight-a.Padding) {
		a.X = float64(x)
		a.Y = float64(y)
	}
}

const UNSET_MASK = 1<<10 - 1

func (a *Actor) unsetState(mask int) {
	a.State &= UNSET_MASK ^ mask
}

func (a *Actor) setState(mask int) {
	a.State |= mask
}

func (a *Actor) SetDirection(dir int) {
	a.unsetState(LEFT | RIGHT | UP | DOWN)
	if dir == RIGHT {
		a.FlipX = true
	} else {
		a.FlipX = false
	}
	a.setState(dir)
}

func (a *Actor) SetMovement(mov int) {
	a.unsetState(WALKING | STOPPED)
	a.setState(mov)
}

func (a *Actor) TestState(state int) bool {
	return a.State&state == state
}

func (a *Actor) GetFrame() int {
	var (
		anim *system.Animation
		ok   bool
	)
	if anim, ok = ACTOR_ANIMATIONS[a.State]; !ok {
		log.Printf("No animation for state %v", a.State)
		anim = ACTOR_ANIMATIONS[LEFT|STOPPED]
	}
	return anim.Curr() + a.Offset
}

const (
	LEFT    = 1 << iota
	RIGHT   = 1 << iota
	UP      = 1 << iota
	DOWN    = 1 << iota
	WALKING = 1 << iota
	STOPPED = 1 << iota
)

var ACTOR_ANIMATIONS = map[int]*system.Animation{
	LEFT | STOPPED:  system.Anim([]int{6}, 4),
	RIGHT | STOPPED: system.Anim([]int{6}, 4),
	UP | STOPPED:    system.Anim([]int{3}, 4),
	DOWN | STOPPED:  system.Anim([]int{0}, 4),
	LEFT | WALKING:  system.Anim([]int{6, 7, 6, 8}, 4),
	RIGHT | WALKING: system.Anim([]int{6, 7, 6, 8}, 4),
	UP | WALKING:    system.Anim([]int{3, 4, 3, 5}, 4),
	DOWN | WALKING:  system.Anim([]int{0, 1, 0, 2}, 4),
}
<commit_msg>Don't round to the nearest tile so often.<commit_after>// Copyright 2013 Arne Roomann-Kurrik
//
// 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

import (
	"./system"
	"log"
	"math"
)

type Cast struct {
	Texture *system.Texture
	Actors  []*Actor
	Width   int
	Height  int
	OffsetX int
	OffsetY int
}

func LoadCast(path string, width int, height int, th int, tw int) (c *Cast, err error) {
	var t *system.Texture
	if t, err = system.LoadTexture(path, system.IntNearest, width, height); err != nil {
		return
	}
	c = &Cast{
		Texture: t,
		Width:   width,
		Height:  height,
		OffsetX: width - tw,
		OffsetY: height - th,
	}
	return
}

func (c *Cast) AddActor(x float64, y float64, state int, offset int) (a *Actor) {
	a = &Actor{
		X:       x,
		Y:       y,
		State:   state,
		Offset:  offset,
		Rate:    2.0,
		Padding: 12,
	}
	c.Actors = append(c.Actors, a)
	return
}

func (c *Cast) Update(level *Level) {
	for _, a := range c.Actors {
		if !a.TestState(WALKING) {
			continue
		}
		switch {
		case a.TestState(DOWN):
			a.moveDown(level)
		case a.TestState(UP):
			a.moveUp(level)
		case a.TestState(RIGHT):
			a.moveRight(level)
		case a.TestState(LEFT):
			a.moveLeft(level)
		}
	}
	for _, a := range ACTOR_ANIMATIONS {
		a.Next()
	}
}

type Actor struct {
	X       float64
	Y       float64
	State   int
	Offset  int
	FlipX   bool
	Rate    float64
	Padding int
}

// Attempts to round X or Y values to tile boundaries if they're within Padding
func (a *Actor) getClamped(v float64, size int) int {
	var (
		clamped = math.Floor(v/float64(size)+0.5) * float64(size)
		diff    = math.Abs(clamped - v)
	)
	if int(diff) <= a.Padding {
		return int(clamped)
	}
	return int(v)
}

func (a *Actor) moveDown(l *Level) {
	var (
		x int
		y int
	)
	x = a.getClamped(a.X, l.TileWidth)
	y = int(a.Y + a.Rate)
	if l.TestPixelPassable(x+a.Padding, y+l.TileHeight) &&
		l.TestPixelPassable(x+l.TileWidth-a.Padding, y+l.TileHeight) {
		if x == int(a.X) {
			// Only move once we've clamped.
			a.Y = float64(y)
		}
		a.X = float64(x)
	}
}

func (a *Actor) moveUp(l *Level) {
	var (
		x int
		y int
	)
	x = a.getClamped(a.X, l.TileWidth)
	y = int(a.Y - a.Rate)
	if l.TestPixelPassable(x+a.Padding, y) &&
		l.TestPixelPassable(x+l.TileWidth-a.Padding, y) {
		if x == int(a.X) {
			// Only move once we've clamped.
			a.Y = float64(y)
		}
		a.X = float64(x)
	}
}

func (a *Actor) moveRight(l *Level) {
	var (
		x int
		y int
	)
	y = a.getClamped(a.Y, l.TileHeight)
	x = int(a.X + a.Rate)
	if l.TestPixelPassable(x+l.TileWidth, y+a.Padding) &&
		l.TestPixelPassable(x+l.TileWidth, y+l.TileHeight-a.Padding) {
		if y == int(a.Y) {
			// Only move once we've clamped.
			a.X = float64(x)
		}
		a.Y = float64(y)
	}
}

func (a *Actor) moveLeft(l *Level) {
	var (
		x int
		y int
	)
	y = a.getClamped(a.Y, l.TileHeight)
	x = int(a.X - a.Rate)
	if l.TestPixelPassable(x, y+a.Padding) &&
		l.TestPixelPassable(x, y+l.TileHeight-a.Padding) {
		if y == int(a.Y) {
			// Only move once we've clamped.
			a.X = float64(x)
		}
		a.Y = float64(y)
	}
}

const UNSET_MASK = 1<<10 - 1

func (a *Actor) unsetState(mask int) {
	a.State &= UNSET_MASK ^ mask
}

func (a *Actor) setState(mask int) {
	a.State |= mask
}

func (a *Actor) SetDirection(dir int) {
	a.unsetState(LEFT | RIGHT | UP | DOWN)
	if dir == RIGHT {
		a.FlipX = true
	} else {
		a.FlipX = false
	}
	a.setState(dir)
}

func (a *Actor) SetMovement(mov int) {
	a.unsetState(WALKING | STOPPED)
	a.setState(mov)
}

func (a *Actor) TestState(state int) bool {
	return a.State&state == state
}

func (a *Actor) GetFrame() int {
	var (
		anim *system.Animation
		ok   bool
	)
	if anim, ok = ACTOR_ANIMATIONS[a.State]; !ok {
		log.Printf("No animation for state %v", a.State)
		anim = ACTOR_ANIMATIONS[LEFT|STOPPED]
	}
	return anim.Curr() + a.Offset
}

const (
	LEFT    = 1 << iota
	RIGHT   = 1 << iota
	UP      = 1 << iota
	DOWN    = 1 << iota
	WALKING = 1 << iota
	STOPPED = 1 << iota
)

var ACTOR_ANIMATIONS = map[int]*system.Animation{
	LEFT | STOPPED:  system.Anim([]int{6}, 4),
	RIGHT | STOPPED: system.Anim([]int{6}, 4),
	UP | STOPPED:    system.Anim([]int{3}, 4),
	DOWN | STOPPED:  system.Anim([]int{0}, 4),
	LEFT | WALKING:  system.Anim([]int{6, 7, 6, 8}, 4),
	RIGHT | WALKING: system.Anim([]int{6, 7, 6, 8}, 4),
	UP | WALKING:    system.Anim([]int{3, 4, 3, 5}, 4),
	DOWN | WALKING:  system.Anim([]int{0, 1, 0, 2}, 4),
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/julienschmidt/httprouter"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	fmt.Fprint(w, "Welcome!\n")
	fmt.Printf("%v", r)
}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
	fmt.Printf("%v", ps)
	fmt.Printf("%v", r)
}

func main() {
	router := httprouter.New()
	router.GET("/", Index)
	router.GET("/hello/:name", Hello)

	log.Fatal(http.ListenAndServe(":8080", router))
}
<commit_msg>add httprouter params<commit_after>package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/julienschmidt/httprouter"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	fmt.Fprint(w, "Welcome!\n")
}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
	fmt.Fprintf(w, "%v\n", r)
}

func handler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	fmt.Fprintf(w, "%s; %s; %s\n", r.Method, r.URL, r.Proto)
	fmt.Fprintf(w, "Host = %q\n", r.Host)
	fmt.Fprintf(w, "RemoteAddr = %q\n", r.RemoteAddr)

	for k, v := range r.Header {
		fmt.Fprintf(w, "Header[%q] = %q\n", k, v)
	}

	if err := r.ParseForm(); err != nil {
		log.Print(err)
	}
	for k, v := range r.Form {
		fmt.Fprintf(w, "Form[%q] = %q\n", k, v)
	}
}

func main() {
	router := httprouter.New()
	router.GET("/", Index)
	router.GET("/hello/:name", Hello)
	router.GET("/handler", handler)

	log.Fatal(http.ListenAndServe(":8080", router))
}
<|endoftext|>


<commit_before>package kiwi_test

// It was adapted from logxi package.

import (
	"encoding/json"
	L "log"
	"os"
	"testing"
	"time"

	"bytes"
	"github.com/Sirupsen/logrus"
	"github.com/grafov/kiwi"
	"github.com/mgutz/logxi/v1"
	"gopkg.in/inconshreveable/log15.v2"
)

type M map[string]interface{}

var testObject = M{
	"foo": "bar",
	"bah": M{
		"int":      1,
		"float":    -100.23,
		"date":     "06-01-01T15:04:05-0700",
		"bool":     true,
		"nullable": nil,
	},
}

// Right way for kiwi is realize Record interface for the custom type
// that logger can't accept directly. But you can simply pass fmt.Stringer
// interface as well.
// You need Record interface if you want specify quotation rules with IsQuoted().
// Elsewere String() is enough.
func (m *M) String() string {
	b, _ := json.Marshal(m)
	return string(b)
}

var pid = os.Getpid()

func toJSON(m map[string]interface{}) string {
	b, _ := json.Marshal(m)
	return string(b)
}

// These tests write out all log levels with concurrency turned on and
// (mostly) equivalent fields.

func BenchmarkKiwi(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := kiwi.NewLogger()
	l.With("_n", "bench", "_p", pid)
	l.WithTimestamp(time.RFC3339)
	kiwi.LevelName = "l"
	out := kiwi.UseOutput(buf, kiwi.JSON)
	defer out.Close()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.Debug("key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Info("key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Warn("key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Error("key", 1, "key2", 3.141592, "key3", "string", "key4", false)
	}
	b.StopTimer()
}

func BenchmarkKiwiComplex(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := kiwi.NewLogger()
	l.With("_n", "bench", "_p", pid)
	l.WithTimestamp(time.RFC3339)
	kiwi.LevelName = "l"
	out := kiwi.UseOutput(buf, kiwi.JSON)
	defer out.Close()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.Debug("key", 1, "obj", testObject)
		l.Info("key", 1, "obj", testObject)
		l.Warn("key", 1, "obj", testObject)
		l.Error("key", 1, "obj", testObject)
	}
	b.StopTimer()
}

func BenchmarkStdLog(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := L.New(buf, "bench ", L.LstdFlags)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		debug := map[string]interface{}{"l": "debug", "key1": 1, "key2": 3.141592, "key3": "string", "key4": false}
		l.Printf(toJSON(debug))

		info := map[string]interface{}{"l": "info", "key1": 1, "key2": 3.141592, "key3": "string", "key4": false}
		l.Printf(toJSON(info))

		warn := map[string]interface{}{"l": "warn", "key1": 1, "key2": 3.141592, "key3": "string", "key4": false}
		l.Printf(toJSON(warn))

		err := map[string]interface{}{"l": "error", "key1": 1, "key2": 3.141592, "key3": "string", "key4": false}
		l.Printf(toJSON(err))
	}
	b.StopTimer()
}

func BenchmarkStdLogComplex(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := L.New(buf, "bench ", L.LstdFlags)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		debug := map[string]interface{}{"l": "debug", "key1": 1, "obj": testObject}
		l.Printf(toJSON(debug))

		info := map[string]interface{}{"l": "info", "key1": 1, "obj": testObject}
		l.Printf(toJSON(info))

		warn := map[string]interface{}{"l": "warn", "key1": 1, "obj": testObject}
		l.Printf(toJSON(warn))

		err := map[string]interface{}{"l": "error", "key1": 1, "obj": testObject}
		l.Printf(toJSON(err))
	}
	b.StopTimer()
}

func BenchmarkLogxi(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	stdout := log.NewConcurrentWriter(buf)
	l := log.NewLogger3(stdout, "bench", log.NewJSONFormatter("bench"))
	l.SetLevel(log.LevelDebug)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.Debug("debug", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Info("info", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Warn("warn", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Error("error", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
	}
	b.StopTimer()
}

func BenchmarkLogxiComplex(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	stdout := log.NewConcurrentWriter(buf)
	l := log.NewLogger3(stdout, "bench", log.NewJSONFormatter("bench"))
	l.SetLevel(log.LevelDebug)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.Debug("debug", "key", 1, "obj", testObject)
		l.Info("info", "key", 1, "obj", testObject)
		l.Warn("warn", "key", 1, "obj", testObject)
		l.Error("error", "key", 1, "obj", testObject)
	}
	b.StopTimer()

}

func BenchmarkLogrus(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := logrus.New()
	l.Out = buf
	l.Formatter = &logrus.JSONFormatter{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "key2": 3.141592, "key3": "string", "key4": false}).Debug("debug")
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "key2": 3.141592, "key3": "string", "key4": false}).Info("info")
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "key2": 3.141592, "key3": "string", "key4": false}).Warn("warn")
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "key2": 3.141592, "key3": "string", "key4": false}).Error("error")
	}
	b.StopTimer()
}

func BenchmarkLogrusComplex(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := logrus.New()
	l.Out = buf
	l.Formatter = &logrus.JSONFormatter{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "obj": testObject}).Debug("debug")
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "obj": testObject}).Info("info")
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "obj": testObject}).Warn("warn")
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "obj": testObject}).Error("error")
	}
	b.StopTimer()
}

func BenchmarkLog15(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := log15.New(log15.Ctx{"_n": "bench", "_p": pid})
	l.SetHandler(log15.SyncHandler(log15.StreamHandler(buf, log15.JsonFormat())))
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.Debug("debug", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Info("info", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Warn("warn", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Error("error", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
	}
	b.StopTimer()

}

func BenchmarkLog15Complex(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := log15.New(log15.Ctx{"_n": "bench", "_p": pid})
	l.SetHandler(log15.SyncHandler(log15.StreamHandler(buf, log15.JsonFormat())))
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.Debug("debug", "key", 1, "obj", testObject)
		l.Info("info", "key", 1, "obj", testObject)
		l.Warn("warn", "key", 1, "obj", testObject)
		l.Error("error", "key", 1, "obj", testObject)
	}
	b.StopTimer()
}
<commit_msg>Rename benchmarks.<commit_after>package kiwi_test

// It was adapted from logxi package.

import (
	"bytes"
	"encoding/json"
	L "log"
	"os"
	"testing"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/grafov/kiwi"
	"github.com/mgutz/logxi/v1"
	"gopkg.in/inconshreveable/log15.v2"
)

type M map[string]interface{}

var testObject = M{
	"foo": "bar",
	"bah": M{
		"int":      1,
		"float":    -100.23,
		"date":     "06-01-01T15:04:05-0700",
		"bool":     true,
		"nullable": nil,
	},
}

// Right way for kiwi is realize Record interface for the custom type
// that logger can't accept directly. But you can simply pass fmt.Stringer
// interface as well.
// You need Record interface if you want specify quotation rules with IsQuoted().
// Elsewere String() is enough.
func (m *M) String() string {
	b, _ := json.Marshal(m)
	return string(b)
}

var pid = os.Getpid()

func toJSON(m map[string]interface{}) string {
	b, _ := json.Marshal(m)
	return string(b)
}

// These tests write out all log levels with concurrency turned on and
// (mostly) equivalent fields.

func BenchmarkLevelsKiwi(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := kiwi.NewLogger()
	l.With("_n", "bench", "_p", pid)
	l.WithTimestamp(time.RFC3339)
	kiwi.LevelName = "l"
	out := kiwi.UseOutput(buf, kiwi.JSON)
	defer out.Close()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.Debug("key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Info("key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Warn("key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Error("key", 1, "key2", 3.141592, "key3", "string", "key4", false)
	}
	b.StopTimer()
}

func BenchmarkLevelsKiwiComplex(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := kiwi.NewLogger()
	l.With("_n", "bench", "_p", pid)
	l.WithTimestamp(time.RFC3339)
	kiwi.LevelName = "l"
	out := kiwi.UseOutput(buf, kiwi.JSON)
	defer out.Close()
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.Debug("key", 1, "obj", testObject)
		l.Info("key", 1, "obj", testObject)
		l.Warn("key", 1, "obj", testObject)
		l.Error("key", 1, "obj", testObject)
	}
	b.StopTimer()
}

func BenchmarkLevelsStdLog(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := L.New(buf, "bench ", L.LstdFlags)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		debug := map[string]interface{}{"l": "debug", "key1": 1, "key2": 3.141592, "key3": "string", "key4": false}
		l.Printf(toJSON(debug))

		info := map[string]interface{}{"l": "info", "key1": 1, "key2": 3.141592, "key3": "string", "key4": false}
		l.Printf(toJSON(info))

		warn := map[string]interface{}{"l": "warn", "key1": 1, "key2": 3.141592, "key3": "string", "key4": false}
		l.Printf(toJSON(warn))

		err := map[string]interface{}{"l": "error", "key1": 1, "key2": 3.141592, "key3": "string", "key4": false}
		l.Printf(toJSON(err))
	}
	b.StopTimer()
}

func BenchmarkLevelsStdLogComplex(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := L.New(buf, "bench ", L.LstdFlags)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		debug := map[string]interface{}{"l": "debug", "key1": 1, "obj": testObject}
		l.Printf(toJSON(debug))

		info := map[string]interface{}{"l": "info", "key1": 1, "obj": testObject}
		l.Printf(toJSON(info))

		warn := map[string]interface{}{"l": "warn", "key1": 1, "obj": testObject}
		l.Printf(toJSON(warn))

		err := map[string]interface{}{"l": "error", "key1": 1, "obj": testObject}
		l.Printf(toJSON(err))
	}
	b.StopTimer()
}

func BenchmarkLevelsLogxi(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	stdout := log.NewConcurrentWriter(buf)
	l := log.NewLogger3(stdout, "bench", log.NewJSONFormatter("bench"))
	l.SetLevel(log.LevelDebug)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.Debug("debug", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Info("info", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Warn("warn", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Error("error", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
	}
	b.StopTimer()
}

func BenchmarkLevelsLogxiComplex(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	stdout := log.NewConcurrentWriter(buf)
	l := log.NewLogger3(stdout, "bench", log.NewJSONFormatter("bench"))
	l.SetLevel(log.LevelDebug)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.Debug("debug", "key", 1, "obj", testObject)
		l.Info("info", "key", 1, "obj", testObject)
		l.Warn("warn", "key", 1, "obj", testObject)
		l.Error("error", "key", 1, "obj", testObject)
	}
	b.StopTimer()

}

func BenchmarkLevelsLogrus(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := logrus.New()
	l.Out = buf
	l.Formatter = &logrus.JSONFormatter{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "key2": 3.141592, "key3": "string", "key4": false}).Debug("debug")
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "key2": 3.141592, "key3": "string", "key4": false}).Info("info")
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "key2": 3.141592, "key3": "string", "key4": false}).Warn("warn")
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "key2": 3.141592, "key3": "string", "key4": false}).Error("error")
	}
	b.StopTimer()
}

func BenchmarkLevelsLogrusComplex(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := logrus.New()
	l.Out = buf
	l.Formatter = &logrus.JSONFormatter{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "obj": testObject}).Debug("debug")
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "obj": testObject}).Info("info")
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "obj": testObject}).Warn("warn")
		l.WithFields(logrus.Fields{"_n": "bench", "_p": pid, "key": 1, "obj": testObject}).Error("error")
	}
	b.StopTimer()
}

func BenchmarkLevelsLog15(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := log15.New(log15.Ctx{"_n": "bench", "_p": pid})
	l.SetHandler(log15.SyncHandler(log15.StreamHandler(buf, log15.JsonFormat())))
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.Debug("debug", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Info("info", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Warn("warn", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
		l.Error("error", "key", 1, "key2", 3.141592, "key3", "string", "key4", false)
	}
	b.StopTimer()

}

func BenchmarkLevelsLog15Complex(b *testing.B) {
	buf := &bytes.Buffer{}
	b.SetBytes(2)
	l := log15.New(log15.Ctx{"_n": "bench", "_p": pid})
	l.SetHandler(log15.SyncHandler(log15.StreamHandler(buf, log15.JsonFormat())))
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		l.Debug("debug", "key", 1, "obj", testObject)
		l.Info("info", "key", 1, "obj", testObject)
		l.Warn("warn", "key", 1, "obj", testObject)
		l.Error("error", "key", 1, "obj", testObject)
	}
	b.StopTimer()
}
<|endoftext|>


<commit_before>package backup

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"time"

	"github.com/pivotal-cf/cf-redis-broker/backup/s3bucket"
	"github.com/pivotal-cf/cf-redis-broker/backupconfig"
	"github.com/pivotal-cf/cf-redis-broker/redis/client"
	"github.com/pivotal-cf/cf-redis-broker/redisconf"
	"github.com/pivotal-golang/lager"
)

type Backup struct {
	Config *backupconfig.Config
	Logger lager.Logger
}

// http://golang.org/pkg/time/#pkg-constants if you need to understand these crazy layouts
const timeFormat = "200601021504"

func (backup Backup) Create(configPath, instanceDataPath, instanceID, planName string) error {
	if err := backup.createSnapshot(configPath); err != nil {
		return err
	}

	timestamp := time.Now().Format(timeFormat)

	pathToRdbFile := path.Join(instanceDataPath, "dump.rdb")
	if !fileExists(pathToRdbFile) {
		backup.Logger.Info("dump.rdb not found, skipping instance backup", lager.Data{
			"Local file": pathToRdbFile,
		})
		return nil
	}

	bucket, err := backup.getOrCreateBucket()
	if err != nil {
		return err
	}
	return backup.uploadToS3(instanceID, planName, pathToRdbFile, timestamp, bucket)
}

func (backup Backup) getOrCreateBucket() (s3bucket.Bucket, error) {
	s3Client := s3bucket.NewClient(
		backup.Config.S3Configuration.EndpointUrl,
		backup.Config.S3Configuration.AccessKeyId,
		backup.Config.S3Configuration.SecretAccessKey,
	)

	return s3Client.GetOrCreate(backup.Config.S3Configuration.BucketName)
}

func (backup Backup) createSnapshot(instancePath string) error {
	client, err := backup.buildRedisClient(instancePath)
	if err != nil {
		return err
	}

	return client.CreateSnapshot(backup.Config.BGSaveTimeoutSeconds)
}

func (backup Backup) buildRedisClient(instancePath string) (*client.Client, error) {
	instanceConf, err := redisconf.Load(path.Join(instancePath, "redis.conf"))
	if err != nil {
		return nil, err
	}

	return client.Connect("localhost", instanceConf)
}

func (backup Backup) uploadToS3(instanceID, planName, pathToRdbFile string, timestamp string, bucket s3bucket.Bucket) error {
	rdbBytes, err := ioutil.ReadFile(pathToRdbFile)
	if err != nil {
		return err
	}

	remotePath := fmt.Sprintf("%s/%s_%s_%s_redis_backup.tgz", backup.Config.S3Configuration.Path, timestamp, instanceID, planName)

	backup.Logger.Info("Backing up instance", lager.Data{
		"Local file":  pathToRdbFile,
		"Remote file": remotePath,
	})

	return bucket.Upload(rdbBytes, remotePath)
}

func fileExists(path string) bool {
	_, err := os.Stat(path)
	return err == nil || os.IsExist(err)
}
<commit_msg>small simplification in backup.go<commit_after>package backup

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"
	"time"

	"github.com/pivotal-cf/cf-redis-broker/backup/s3bucket"
	"github.com/pivotal-cf/cf-redis-broker/backupconfig"
	"github.com/pivotal-cf/cf-redis-broker/redis/client"
	"github.com/pivotal-cf/cf-redis-broker/redisconf"
	"github.com/pivotal-golang/lager"
)

type Backup struct {
	Config *backupconfig.Config
	Logger lager.Logger
}

// http://golang.org/pkg/time/#pkg-constants if you need to understand these crazy layouts
const timeFormat = "200601021504"

func (backup Backup) Create(configPath, instanceDataPath, instanceID, planName string) error {
	if err := backup.createSnapshot(configPath); err != nil {
		return err
	}

	timestamp := time.Now().Format(timeFormat)

	pathToRdbFile := path.Join(instanceDataPath, "dump.rdb")
	if !fileExists(pathToRdbFile) {
		backup.Logger.Info("dump.rdb not found, skipping instance backup", lager.Data{
			"Local file": pathToRdbFile,
		})
		return nil
	}

	bucket, err := backup.getOrCreateBucket()
	if err != nil {
		return err
	}
	return backup.uploadToS3(instanceID, planName, pathToRdbFile, timestamp, bucket)
}

func (backup Backup) getOrCreateBucket() (s3bucket.Bucket, error) {
	s3Client := s3bucket.NewClient(
		backup.Config.S3Configuration.EndpointUrl,
		backup.Config.S3Configuration.AccessKeyId,
		backup.Config.S3Configuration.SecretAccessKey,
	)

	return s3Client.GetOrCreate(backup.Config.S3Configuration.BucketName)
}

func (backup Backup) createSnapshot(instancePath string) error {
	instanceConf, err := redisconf.Load(path.Join(instancePath, "redis.conf"))
	if err != nil {
		return err
	}

	client, err := client.Connect("localhost", instanceConf)
	if err != nil {
		return err
	}

	return client.CreateSnapshot(backup.Config.BGSaveTimeoutSeconds)
}

func (backup Backup) uploadToS3(instanceID, planName, pathToRdbFile string, timestamp string, bucket s3bucket.Bucket) error {
	rdbBytes, err := ioutil.ReadFile(pathToRdbFile)
	if err != nil {
		return err
	}

	remotePath := fmt.Sprintf("%s/%s_%s_%s_redis_backup.tgz", backup.Config.S3Configuration.Path, timestamp, instanceID, planName)

	backup.Logger.Info("Backing up instance", lager.Data{
		"Local file":  pathToRdbFile,
		"Remote file": remotePath,
	})

	return bucket.Upload(rdbBytes, remotePath)
}

func fileExists(path string) bool {
	_, err := os.Stat(path)
	return err == nil || os.IsExist(err)
}
<|endoftext|>


<commit_before>package storage

import (
	"io"

	"github.com/lxc/lxd/lxd/instance/instancetype"
	"github.com/lxc/lxd/lxd/migration"
	"github.com/lxc/lxd/lxd/operations"
	"github.com/lxc/lxd/lxd/state"
	"github.com/lxc/lxd/lxd/storage/drivers"
	"github.com/lxc/lxd/shared/api"
)

// Instance represents the storage relevant subset of a LXD instance.
type Instance interface {
	Name() string
	Project() string
	Type() instancetype.Type
	Path() string

	IsRunning() bool
	Snapshots() ([]Instance, error)
	TemplateApply(trigger string) error
}

// Pool represents a LXD storage pool.
type Pool interface {
	// Internal.
	DaemonState() *state.State

	// Pool.
	ID() int64
	Name() string
	Driver() drivers.Driver

	GetResources() (*api.ResourcesStoragePool, error)
	Delete(op *operations.Operation) error

	Mount() (bool, error)
	Unmount() (bool, error)

	// Instances.
	CreateInstance(i Instance, op *operations.Operation) error
	CreateInstanceFromBackup(i Instance, sourcePath string, op *operations.Operation) error
	CreateInstanceFromCopy(i Instance, src Instance, snapshots bool, op *operations.Operation) error
	CreateInstanceFromImage(i Instance, fingerprint string, op *operations.Operation) error
	CreateInstanceFromMigration(i Instance, conn io.ReadWriteCloser, args migration.SinkArgs, op *operations.Operation) error
	RenameInstance(i Instance, newName string, op *operations.Operation) error
	DeleteInstance(i Instance, op *operations.Operation) error

	MigrateInstance(i Instance, snapshots bool, args migration.SourceArgs) (migration.StorageSourceDriver, error)
	RefreshInstance(i Instance, src Instance, snapshots bool, op *operations.Operation) error
	BackupInstance(i Instance, targetPath string, optimized bool, snapshots bool, op *operations.Operation) error

	GetInstanceUsage(i Instance) (uint64, error)
	SetInstanceQuota(i Instance, quota uint64) error

	MountInstance(i Instance) (bool, error)
	UnmountInstance(i Instance) (bool, error)
	GetInstanceDisk(i Instance) (string, string, error)

	// Instance snapshots.
	CreateInstanceSnapshot(i Instance, name string, op *operations.Operation) error
	RenameInstanceSnapshot(i Instance, newName string, op *operations.Operation) error
	DeleteInstanceSnapshot(i Instance, op *operations.Operation) error
	RestoreInstanceSnapshot(i Instance, op *operations.Operation) error
	MountInstanceSnapshot(i Instance) (bool, error)
	UnmountInstanceSnapshot(i Instance) (bool, error)

	// Images.
	CreateImage(img api.Image, op *operations.Operation) error
	DeleteImage(fingerprint string, op *operations.Operation) error

	// Custom volumes.
	CreateCustomVolume(volName, desc string, config map[string]string, op *operations.Operation) error
	CreateCustomVolumeFromCopy(volName, desc string, config map[string]string, srcPoolName, srcVolName string, srcVolOnly bool, op *operations.Operation) error
	UpdateCustomVolume(volName, newDesc string, newConfig map[string]string, op *operations.Operation) error
	RenameCustomVolume(volName string, newVolName string, op *operations.Operation) error
	DeleteCustomVolume(volName string, op *operations.Operation) error
	GetCustomVolumeUsage(vol api.StorageVolume) (uint64, error)
	MountCustomVolume(volName string, op *operations.Operation) (bool, error)
	UnmountCustomVolume(volName string, op *operations.Operation) (bool, error)

	// Custom volume snapshots.
	CreateCustomVolumeSnapshot(volName string, newSnapshotName string, op *operations.Operation) error
	RenameCustomVolumeSnapshot(volName string, newSnapshotName string, op *operations.Operation) error
	DeleteCustomVolumeSnapshot(volName string, op *operations.Operation) error

	// Custom volume migration.
	MigrationTypes(contentType drivers.ContentType) []migration.Type
	CreateCustomVolumeFromMigration(conn io.ReadWriteCloser, args migration.VolumeTargetArgs, op *operations.Operation) error
	MigrateCustomVolume(conn io.ReadWriteCloser, args migration.VolumeSourceArgs, op *operations.Operation) error
}
<commit_msg>lxd/storage/interfaces: Adds RestoreCustomVolume<commit_after>package storage

import (
	"io"

	"github.com/lxc/lxd/lxd/instance/instancetype"
	"github.com/lxc/lxd/lxd/migration"
	"github.com/lxc/lxd/lxd/operations"
	"github.com/lxc/lxd/lxd/state"
	"github.com/lxc/lxd/lxd/storage/drivers"
	"github.com/lxc/lxd/shared/api"
)

// Instance represents the storage relevant subset of a LXD instance.
type Instance interface {
	Name() string
	Project() string
	Type() instancetype.Type
	Path() string

	IsRunning() bool
	Snapshots() ([]Instance, error)
	TemplateApply(trigger string) error
}

// Pool represents a LXD storage pool.
type Pool interface {
	// Internal.
	DaemonState() *state.State

	// Pool.
	ID() int64
	Name() string
	Driver() drivers.Driver

	GetResources() (*api.ResourcesStoragePool, error)
	Delete(op *operations.Operation) error

	Mount() (bool, error)
	Unmount() (bool, error)

	// Instances.
	CreateInstance(i Instance, op *operations.Operation) error
	CreateInstanceFromBackup(i Instance, sourcePath string, op *operations.Operation) error
	CreateInstanceFromCopy(i Instance, src Instance, snapshots bool, op *operations.Operation) error
	CreateInstanceFromImage(i Instance, fingerprint string, op *operations.Operation) error
	CreateInstanceFromMigration(i Instance, conn io.ReadWriteCloser, args migration.SinkArgs, op *operations.Operation) error
	RenameInstance(i Instance, newName string, op *operations.Operation) error
	DeleteInstance(i Instance, op *operations.Operation) error

	MigrateInstance(i Instance, snapshots bool, args migration.SourceArgs) (migration.StorageSourceDriver, error)
	RefreshInstance(i Instance, src Instance, snapshots bool, op *operations.Operation) error
	BackupInstance(i Instance, targetPath string, optimized bool, snapshots bool, op *operations.Operation) error

	GetInstanceUsage(i Instance) (uint64, error)
	SetInstanceQuota(i Instance, quota uint64) error

	MountInstance(i Instance) (bool, error)
	UnmountInstance(i Instance) (bool, error)
	GetInstanceDisk(i Instance) (string, string, error)

	// Instance snapshots.
	CreateInstanceSnapshot(i Instance, name string, op *operations.Operation) error
	RenameInstanceSnapshot(i Instance, newName string, op *operations.Operation) error
	DeleteInstanceSnapshot(i Instance, op *operations.Operation) error
	RestoreInstanceSnapshot(i Instance, op *operations.Operation) error
	MountInstanceSnapshot(i Instance) (bool, error)
	UnmountInstanceSnapshot(i Instance) (bool, error)

	// Images.
	CreateImage(img api.Image, op *operations.Operation) error
	DeleteImage(fingerprint string, op *operations.Operation) error

	// Custom volumes.
	CreateCustomVolume(volName, desc string, config map[string]string, op *operations.Operation) error
	CreateCustomVolumeFromCopy(volName, desc string, config map[string]string, srcPoolName, srcVolName string, srcVolOnly bool, op *operations.Operation) error
	UpdateCustomVolume(volName, newDesc string, newConfig map[string]string, op *operations.Operation) error
	RenameCustomVolume(volName string, newVolName string, op *operations.Operation) error
	DeleteCustomVolume(volName string, op *operations.Operation) error
	GetCustomVolumeUsage(vol api.StorageVolume) (uint64, error)
	MountCustomVolume(volName string, op *operations.Operation) (bool, error)
	UnmountCustomVolume(volName string, op *operations.Operation) (bool, error)

	// Custom volume snapshots.
	CreateCustomVolumeSnapshot(volName string, newSnapshotName string, op *operations.Operation) error
	RenameCustomVolumeSnapshot(volName string, newSnapshotName string, op *operations.Operation) error
	DeleteCustomVolumeSnapshot(volName string, op *operations.Operation) error
	RestoreCustomVolume(volName string, snapshotName string, op *operations.Operation) error

	// Custom volume migration.
	MigrationTypes(contentType drivers.ContentType) []migration.Type
	CreateCustomVolumeFromMigration(conn io.ReadWriteCloser, args migration.VolumeTargetArgs, op *operations.Operation) error
	MigrateCustomVolume(conn io.ReadWriteCloser, args migration.VolumeSourceArgs, op *operations.Operation) error
}
<|endoftext|>


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

package mat_test

import (
	"fmt"

	"gonum.org/v1/gonum/mat"
)

func ExampleDense_Add() {
	// Initialize two matrices, a and b.
	a := mat.NewDense(2, 2, []float64{1, 0, 1, 0})
	b := mat.NewDense(2, 2, []float64{0, 1, 0, 1})

	// Add a and b, placing the result into c.
	// ...Notice that the size is automatically adjusted when the receiver has zero size.
	var c mat.Dense
	c.Add(a, b)

	// Print the result using the formatter.
	fc := mat.Formatted(&c, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\nc = %v\n\n", fc)
	// Output:
	// Result:
	// c = ⎡1  1⎤
	//     ⎣1  1⎦
	//
}

func ExampleDense_Sub() {
	// Initialize two matrices, a and b.
	a := mat.NewDense(2, 2, []float64{1, 1, 1, 1})
	b := mat.NewDense(2, 2, []float64{1, 0, 0, 1})

	// Subtract b from a, placing the result into a.
	a.Sub(a, b)

	// Print the result using the formatter.
	fa := mat.Formatted(a, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\na = %v\n\n", fa)
	// Output:
	// Result:
	// a = ⎡0  1⎤
	//     ⎣1  0⎦
	//
}

func ExampleDense_MulElem() {
	// Initialize two matrices, a and b.
	a := mat.NewDense(2, 2, []float64{1, 2, 3, 4})
	b := mat.NewDense(2, 2, []float64{1, 2, 3, 4})

	// Multiply the elements of a and b, placing the result into a.
	a.MulElem(a, b)

	// Print the result using the formatter.
	fa := mat.Formatted(a, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\na = %v\n\n", fa)
	// Output:
	// Result:
	// a = ⎡1   4⎤
	//     ⎣9  16⎦
	//
}

func ExampleDense_DivElem() {
	// Initialize two matrices, a and b.
	a := mat.NewDense(2, 2, []float64{5, 10, 15, 20})
	b := mat.NewDense(2, 2, []float64{5, 5, 5, 5})

	// Divide the elements of a by b, placing the result into a.
	a.DivElem(a, b)

	// Print the result using the formatter.
	fa := mat.Formatted(a, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\na = %v\n\n", fa)
	// Output:
	// Result:
	// a = ⎡1  2⎤
	//     ⎣3  4⎦
	//
}

func ExampleDense_Inverse() {
	// Initialize two matrices, a and ia.
	a := mat.NewDense(2, 2, []float64{4, 0, 0, 4})
	var ia mat.Dense

	// Take the inverse of a and place the result in ia.
	ia.Inverse(a)

	// Print the result using the formatter.
	fa := mat.Formatted(&ia, mat.Prefix("     "), mat.Squeeze())
	fmt.Printf("Result:\nia = %.2g\n\n", fa)

	// Confirm that A * A^-1 = I
	var r mat.Dense
	r.Mul(a, &ia)
	fr := mat.Formatted(&r, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\nr = %v\n\n", fr)

	// The Inverse operation, however, is numerically unstable, and should typically be avoided.
	// For example, a common need is to find x = A^-1 * b. In this case, the SolveVec method of VecDense
	// (if b is a Vector) or Solve method of Dense (if b is a matrix) should used instead of computing
	// the Inverse of A.
	b := mat.NewDense(2, 2, []float64{2, 0, 0, 2})
	var x mat.Dense
	x.Solve(a, b)

	// Print the result using the formatter.
	fx := mat.Formatted(&x, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\nx = %v\n\n", fx)

	// Output:
	// Result:
	// ia = ⎡0.25    -0⎤
	//      ⎣   0  0.25⎦
	//
	// Result:
	// r = ⎡1  0⎤
	//     ⎣0  1⎦
	//
	// Result:
	// x = ⎡0.5    0⎤
	//     ⎣  0  0.5⎦
	//
}
<commit_msg>added examples for mul/exp/pow/scale<commit_after>// Copyright ©2017 The gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package mat_test

import (
	"fmt"

	"gonum.org/v1/gonum/mat"
)

func ExampleDense_Add() {
	// Initialize two matrices, a and b.
	a := mat.NewDense(2, 2, []float64{1, 0, 1, 0})
	b := mat.NewDense(2, 2, []float64{0, 1, 0, 1})

	// Add a and b, placing the result into c.
	// ...Notice that the size is automatically adjusted when the receiver has zero size.
	var c mat.Dense
	c.Add(a, b)

	// Print the result using the formatter.
	fc := mat.Formatted(&c, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\nc = %v\n\n", fc)
	// Output:
	// Result:
	// c = ⎡1  1⎤
	//     ⎣1  1⎦
	//
}

func ExampleDense_Sub() {
	// Initialize two matrices, a and b.
	a := mat.NewDense(2, 2, []float64{1, 1, 1, 1})
	b := mat.NewDense(2, 2, []float64{1, 0, 0, 1})

	// Subtract b from a, placing the result into a.
	a.Sub(a, b)

	// Print the result using the formatter.
	fa := mat.Formatted(a, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\na = %v\n\n", fa)
	// Output:
	// Result:
	// a = ⎡0  1⎤
	//     ⎣1  0⎦
	//
}

func ExampleDense_MulElem() {
	// Initialize two matrices, a and b.
	a := mat.NewDense(2, 2, []float64{1, 2, 3, 4})
	b := mat.NewDense(2, 2, []float64{1, 2, 3, 4})

	// Multiply the elements of a and b, placing the result into a.
	a.MulElem(a, b)

	// Print the result using the formatter.
	fa := mat.Formatted(a, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\na = %v\n\n", fa)
	// Output:
	// Result:
	// a = ⎡1   4⎤
	//     ⎣9  16⎦
	//
}

func ExampleDense_DivElem() {
	// Initialize two matrices, a and b.
	a := mat.NewDense(2, 2, []float64{5, 10, 15, 20})
	b := mat.NewDense(2, 2, []float64{5, 5, 5, 5})

	// Divide the elements of a by b, placing the result into a.
	a.DivElem(a, b)

	// Print the result using the formatter.
	fa := mat.Formatted(a, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\na = %v\n\n", fa)
	// Output:
	// Result:
	// a = ⎡1  2⎤
	//     ⎣3  4⎦
	//
}

func ExampleDense_Inverse() {
	// Initialize two matrices, a and ia.
	a := mat.NewDense(2, 2, []float64{4, 0, 0, 4})
	var ia mat.Dense

	// Take the inverse of a and place the result in ia.
	ia.Inverse(a)

	// Print the result using the formatter.
	fa := mat.Formatted(&ia, mat.Prefix("     "), mat.Squeeze())
	fmt.Printf("Result:\nia = %.2g\n\n", fa)

	// Confirm that A * A^-1 = I
	var r mat.Dense
	r.Mul(a, &ia)
	fr := mat.Formatted(&r, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\nr = %v\n\n", fr)

	// The Inverse operation, however, is numerically unstable, and should typically be avoided.
	// For example, a common need is to find x = A^-1 * b. In this case, the SolveVec method of VecDense
	// (if b is a Vector) or Solve method of Dense (if b is a matrix) should used instead of computing
	// the Inverse of A.
	b := mat.NewDense(2, 2, []float64{2, 0, 0, 2})
	var x mat.Dense
	x.Solve(a, b)

	// Print the result using the formatter.
	fx := mat.Formatted(&x, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\nx = %v\n\n", fx)

	// Output:
	// Result:
	// ia = ⎡0.25    -0⎤
	//      ⎣   0  0.25⎦
	//
	// Result:
	// r = ⎡1  0⎤
	//     ⎣0  1⎦
	//
	// Result:
	// x = ⎡0.5    0⎤
	//     ⎣  0  0.5⎦
	//
}

func ExampleDense_Mul() {
	// Initialize two matrices, a and b.
	a := mat.NewDense(2, 2, []float64{4, 0, 0, 4})
	b := mat.NewDense(2, 3, []float64{4, 0, 0, 0, 0, 4})

	// Take the matrix product of a and b and place the result in c.
	var c mat.Dense
	c.Mul(a, b)

	// Print the result using the formatter.
	fc := mat.Formatted(&c, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\nc = %v\n\n", fc)
	// Output:
	// Result:
	// c = ⎡16  0   0⎤
	//     ⎣ 0  0  16⎦
	//
}

func ExampleDense_Exp() {
	// Initialize a matrix a with some data.
	a := mat.NewDense(2, 2, []float64{1, 0, 0, 1})

	// Take the exponential of the matrix and place the result in m.
	var m mat.Dense
	m.Exp(a)

	// Print the result using the formatter.
	fm := mat.Formatted(&m, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\nm = %4.2f\n\n", fm)
	// Output:
	// Result:
	// m = ⎡2.72  0.00⎤
	//     ⎣0.00  2.72⎦
	//
}

func ExampleDense_Pow() {
	// Initialize a matrix with some data.
	a := mat.NewDense(2, 2, []float64{4, 4, 4, 4})

	// Take the second power of matrix a and place the result in m.
	var m mat.Dense
	m.Pow(a, 2)

	// Print the result using the formatter.
	fm := mat.Formatted(&m, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\nm = %v\n\n", fm)

	// Take the zeroth power of matrix a and place the result in n.
	// We expect an identity matrix of the same size as matrix a.
	var n mat.Dense
	n.Pow(a, 0)

	// Print the result using the formatter.
	fn := mat.Formatted(&n, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\nn = %v\n\n", fn)
	// Output:
	// Result:
	// m = ⎡32  32⎤
	//     ⎣32  32⎦
	//
	// Result:
	// n = ⎡1  0⎤
	//     ⎣0  1⎦
	//
}

func ExampleDense_Scale() {
	// Initialize a matrix with some data.
	a := mat.NewDense(2, 2, []float64{4, 4, 4, 4})

	// Scale the matrix by a factor of 0.25 and place the result in m.
	var m mat.Dense
	m.Scale(0.25, a)

	// Print the result using the formatter.
	fm := mat.Formatted(&m, mat.Prefix("    "), mat.Squeeze())
	fmt.Printf("Result:\nm = %4.3f\n\n", fm)
	// Output:
	// Result:
	// m = ⎡1.000  1.000⎤
	//     ⎣1.000  1.000⎦
	//
}
<|endoftext|>


<commit_before>/*
Copyright 2014 The Kubernetes 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 cloudprovider

import (
	"fmt"
	"io"
	"os"
	"sync"

	"k8s.io/klog/v2"
)

// Factory is a function that returns a cloudprovider.Interface.
// The config parameter provides an io.Reader handler to the factory in
// order to load specific configurations. If no configuration is provided
// the parameter is nil.
type Factory func(config io.Reader) (Interface, error)

// All registered cloud providers.
var (
	providersMutex           sync.Mutex
	providers                = make(map[string]Factory)
	deprecatedCloudProviders = []struct {
		name     string
		external bool
		detail   string
	}{
		{"aws", false, "The AWS provider is deprecated and will be removed in a future release"},
		{"azure", false, "The Azure provider is deprecated and will be removed in a future release"},
		{"gce", false, "The GCE provider is deprecated and will be removed in a future release"},
		{"openstack", true, "https://github.com/kubernetes/cloud-provider-openstack"},
		{"vsphere", false, "The vSphere provider is deprecated and will be removed in a future release"},
	}
)

const externalCloudProvider = "external"

// RegisterCloudProvider registers a cloudprovider.Factory by name.  This
// is expected to happen during app startup.
func RegisterCloudProvider(name string, cloud Factory) {
	providersMutex.Lock()
	defer providersMutex.Unlock()
	if _, found := providers[name]; found {
		klog.Fatalf("Cloud provider %q was registered twice", name)
	}
	klog.V(1).Infof("Registered cloud provider %q", name)
	providers[name] = cloud
}

// IsCloudProvider returns true if name corresponds to an already registered
// cloud provider.
func IsCloudProvider(name string) bool {
	providersMutex.Lock()
	defer providersMutex.Unlock()
	_, found := providers[name]
	return found
}

// GetCloudProvider creates an instance of the named cloud provider, or nil if
// the name is unknown.  The error return is only used if the named provider
// was known but failed to initialize. The config parameter specifies the
// io.Reader handler of the configuration file for the cloud provider, or nil
// for no configuration.
func GetCloudProvider(name string, config io.Reader) (Interface, error) {
	providersMutex.Lock()
	defer providersMutex.Unlock()
	f, found := providers[name]
	if !found {
		return nil, nil
	}
	return f(config)
}

// Detects if the string is an external cloud provider
func IsExternal(name string) bool {
	return name == externalCloudProvider
}

// InitCloudProvider creates an instance of the named cloud provider.
func InitCloudProvider(name string, configFilePath string) (Interface, error) {
	var cloud Interface
	var err error

	if name == "" {
		return nil, nil
	}

	if IsExternal(name) {
		klog.Info("External cloud provider specified")
		return nil, nil
	}

	for _, provider := range deprecatedCloudProviders {
		if provider.name == name {
			detail := provider.detail
			if provider.external {
				detail = fmt.Sprintf("Please use 'external' cloud provider for %s: %s", name, provider.detail)
			}
			klog.Warningf("WARNING: %s built-in cloud provider is now deprecated. %s", name, detail)

			break
		}
	}

	if configFilePath != "" {
		var config *os.File
		config, err = os.Open(configFilePath)
		if err != nil {
			klog.Fatalf("Couldn't open cloud provider configuration %s: %#v",
				configFilePath, err)
		}

		defer config.Close()
		cloud, err = GetCloudProvider(name, config)
	} else {
		// Pass explicit nil so plugins can actually check for nil. See
		// "Why is my nil error value not equal to nil?" in golang.org/doc/faq.
		cloud, err = GetCloudProvider(name, nil)
	}

	if err != nil {
		return nil, fmt.Errorf("could not init cloud provider %q: %v", name, err)
	}
	if cloud == nil {
		return nil, fmt.Errorf("unknown cloud provider %q", name)
	}

	return cloud, nil
}
<commit_msg>only log cloud provider deprecation warning for in-tree components<commit_after>/*
Copyright 2014 The Kubernetes 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 cloudprovider

import (
	"fmt"
	"io"
	"os"
	"sync"

	"k8s.io/klog/v2"
)

// Factory is a function that returns a cloudprovider.Interface.
// The config parameter provides an io.Reader handler to the factory in
// order to load specific configurations. If no configuration is provided
// the parameter is nil.
type Factory func(config io.Reader) (Interface, error)

// All registered cloud providers.
var (
	providersMutex           sync.Mutex
	providers                = make(map[string]Factory)
	deprecatedCloudProviders = []struct {
		name     string
		external bool
		detail   string
	}{
		{"aws", false, "The AWS provider is deprecated and will be removed in a future release"},
		{"azure", false, "The Azure provider is deprecated and will be removed in a future release"},
		{"gce", false, "The GCE provider is deprecated and will be removed in a future release"},
		{"openstack", true, "https://github.com/kubernetes/cloud-provider-openstack"},
		{"vsphere", false, "The vSphere provider is deprecated and will be removed in a future release"},
	}
)

const externalCloudProvider = "external"

// RegisterCloudProvider registers a cloudprovider.Factory by name.  This
// is expected to happen during app startup.
func RegisterCloudProvider(name string, cloud Factory) {
	providersMutex.Lock()
	defer providersMutex.Unlock()
	if _, found := providers[name]; found {
		klog.Fatalf("Cloud provider %q was registered twice", name)
	}
	klog.V(1).Infof("Registered cloud provider %q", name)
	providers[name] = cloud
}

// IsCloudProvider returns true if name corresponds to an already registered
// cloud provider.
func IsCloudProvider(name string) bool {
	providersMutex.Lock()
	defer providersMutex.Unlock()
	_, found := providers[name]
	return found
}

// GetCloudProvider creates an instance of the named cloud provider, or nil if
// the name is unknown.  The error return is only used if the named provider
// was known but failed to initialize. The config parameter specifies the
// io.Reader handler of the configuration file for the cloud provider, or nil
// for no configuration.
func GetCloudProvider(name string, config io.Reader) (Interface, error) {
	providersMutex.Lock()
	defer providersMutex.Unlock()
	f, found := providers[name]
	if !found {
		return nil, nil
	}
	return f(config)
}

// Detects if the string is an external cloud provider
func IsExternal(name string) bool {
	return name == externalCloudProvider
}

func DeprecationWarningForProvider(providerName string) {
	for _, provider := range deprecatedCloudProviders {
		if provider.name != providerName {
			continue
		}

		detail := provider.detail
		if provider.external {
			detail = fmt.Sprintf("Please use 'external' cloud provider for %s: %s", providerName, provider.detail)
		}

		klog.Warningf("WARNING: %s built-in cloud provider is now deprecated. %s", providerName, detail)
		break
	}
}

// InitCloudProvider creates an instance of the named cloud provider.
func InitCloudProvider(name string, configFilePath string) (Interface, error) {
	var cloud Interface
	var err error

	if name == "" {
		return nil, nil
	}

	if IsExternal(name) {
		klog.Info("External cloud provider specified")
		return nil, nil
	}

	if configFilePath != "" {
		var config *os.File
		config, err = os.Open(configFilePath)
		if err != nil {
			klog.Fatalf("Couldn't open cloud provider configuration %s: %#v",
				configFilePath, err)
		}

		defer config.Close()
		cloud, err = GetCloudProvider(name, config)
	} else {
		// Pass explicit nil so plugins can actually check for nil. See
		// "Why is my nil error value not equal to nil?" in golang.org/doc/faq.
		cloud, err = GetCloudProvider(name, nil)
	}

	if err != nil {
		return nil, fmt.Errorf("could not init cloud provider %q: %v", name, err)
	}
	if cloud == nil {
		return nil, fmt.Errorf("unknown cloud provider %q", name)
	}

	return cloud, nil
}
<|endoftext|>