<commit_before>// Copyright 2015 Google Inc. 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

import "time"

// Storage for all flags in the flag set returned by newFlagSet.
type flags struct {
	Help                               bool
	MountOptions                       map[string]string
	Uid                                int64
	Gid                                int64
	FileMode                           uint
	DirMode                            uint
	TempDir                            string
	TempDirLimit                       int64
	GCSChunkSize                       uint64
	ImplicitDirs                       bool
	StatCacheTTL                       time.Duration
	TypeCacheTTL                       time.Duration
	OpRateLimitHz                      float64
	EgressBandwidthLimitBytesPerSecond float64
}
<commit_msg>populateFlagSet<commit_after>// Copyright 2015 Google Inc. 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

import (
	"flag"
	"time"

	"github.com/googlecloudplatform/gcsfuse/mount"
)

////////////////////////////////////////////////////////////////////////
// Flags
////////////////////////////////////////////////////////////////////////

type flagStorage struct {
	Help                               bool
	MountOptions                       map[string]string
	Uid                                int64
	Gid                                int64
	FileMode                           uint
	DirMode                            uint
	TempDir                            string
	TempDirLimit                       int64
	GCSChunkSize                       uint64
	ImplicitDirs                       bool
	StatCacheTTL                       time.Duration
	TypeCacheTTL                       time.Duration
	OpRateLimitHz                      float64
	EgressBandwidthLimitBytesPerSecond float64
}

// Add the flags accepted by run to the supplied flag set, returning the
// variables into which the flags will parse.
func populateFlagSet(fs *flag.FlagSet) (flags *flagStorage) {
	flags = new(flagStorage)

	flag.BoolVar(
		&flags.Help,
		"help",
		false,
		"If set, print usage and exit successfully.")

	flag.Var(
		mount.OptionValue(flags.MountOptions),
		"o",
		"Additional system-specific mount options. Be careful!")

	flag.Int64Var(
		&flags.Uid,
		"uid",
		-1,
		"If non-negative, the UID that owns all inodes. The default is the UID of "+
			"the gcsfuse process.")

	flag.Int64Var(
		&flags.Gid,
		"gid",
		-1,
		"If non-negative, the GID that owns all inodes. The default is the GID of "+
			"the gcsfuse process.")

	flag.UintVar(
		&flags.FileMode,
		"file_mode",
		0644,
		"Permissions bits for files. Default is 0644.")

	flag.UintVar(
		&flags.DirMode,
		"dir_mode",
		0755,
		"Permissions bits for directories. Default is 0755.")

	flag.StringVar(
		&flags.TempDir,
		"temp_dir", "",
		"The temporary directory in which to store local copies of GCS objects. "+
			"If empty, the system default (probably /tmp) will be used.")

	flag.Int64Var(
		&flags.TempDirLimit,
		"temp_dir_bytes", 1<<31,
		"A desired limit on the number of bytes used in --temp_dir. May be exceeded "+
			"for dirty files that have not been flushed or closed.")

	flag.Uint64Var(
		&flags.GCSChunkSize,
		"gcs_chunk_size", 1<<24,
		"If set to a non-zero value N, split up GCS objects into multiple chunks of "+
			"size at most N when reading, and do not read or cache unnecessary chunks.")

	flag.BoolVar(
		&flags.ImplicitDirs,
		"implicit_dirs",
		false,
		"Implicitly define directories based on their content. See "+
			"docs/semantics.md.")

	flag.DurationVar(
		&flags.StatCacheTTL,
		"stat_cache_ttl",
		time.Minute,
		"How long to cache StatObject results from GCS.")

	flag.DurationVar(
		&flags.TypeCacheTTL,
		"type_cache_ttl",
		time.Minute,
		"How long to cache name -> file/dir type mappings in directory inodes.")

	flag.Float64Var(
		&flags.OpRateLimitHz,
		"op_rate_limit_hz",
		-1,
		"If positive, a limit on the rate at which we send requests to GCS, "+
			"measured over a 30-second window.")

	flag.Float64Var(
		&flags.EgressBandwidthLimitBytesPerSecond,
		"egress_bandwidth_limit_bytes_per_second",
		-1,
		"If positive, a limit on the GCS -> gcsfuse bandwidth for reading objects, "+
			"measured over a 30-second window.")

	return
}
<|endoftext|>


<commit_before>package libkb

import (
	"fmt"
)

const (
	PROOF_NONE  = 0
	PROOF_OK    = 1
	PROOF_LOCAL = 2
	PROOF_FOUND = 3 // It's been found in the hunt, but not proven yet

	// Retryable =soft errors
	PROOF_BASE_ERROR        = 100
	PROOF_HOST_UNREACHABLE  = 101
	PROOF_PERMISSION_DENIED = 103 // # Since the user might fix it
	PROOF_FAILED_PARSE      = 106
	PROOF_DNS_ERROR         = 107
	PROOF_AUTH_FAILED       = 108
	PROOF_HTTP_500          = 150
	PROOF_TIMEOUT           = 160
	PROOF_INTERNAL_ERROR    = 170

	// Likely will result in a hard error, if repeated enough
	PROOF_BASE_HARD_ERROR  = 200
	PROOF_NOT_FOUND        = 201
	PROOF_CONTENT_FAILURE  = 202
	PROOF_BAD_USERNAME     = 203
	PROOF_BAD_REMOTE_ID    = 204
	PROOF_TEXT_NOT_FOUND   = 205
	PROOF_BAD_ARGS         = 206
	PROOF_CONTENT_MISSING  = 207
	PROOF_TITLE_NOT_FOUND  = 208
	PROOF_SERVICE_ERROR    = 209
	PROOF_TOR_SKIPPED      = 210
	PROOF_TOR_INCOMPATIBLE = 211
	PROOF_HTTP_300         = 230
	PROOF_HTTP_400         = 240
	PROOF_HTTP_OTHER       = 260
	PROOF_EMPTY_JSON       = 270

	// Hard final errors
	PROOF_DELETED       = 301
	PROOF_SERVICE_DEAD  = 302
	PROOF_BAD_SIGNATURE = 303
	PROOF_BAD_API_URL   = 304
	PROOF_UNKNOWN_TYPE  = 305
	PROOF_NO_HINT       = 306
	PROOF_BAD_HINT_TEXT = 307
)

//=============================================================================
//
type ProofStatus int

type ProofError interface {
	error
	GetStatus() ProofStatus
}

type ProofErrorImpl struct {
	Status ProofStatus
	Desc   string
}

func NewProofError(s ProofStatus, d string, a ...interface{}) *ProofErrorImpl {
	return &ProofErrorImpl{s, fmt.Sprintf(d, a...)}
}

func (e *ProofErrorImpl) Error() string {
	return fmt.Sprintf("%s (code=%d)", e.Desc, int(e.Status))
}

func (e *ProofErrorImpl) GetStatus() ProofStatus { return e.Status }

type ProofApiError struct {
	ProofErrorImpl
	url string
}

// Might be overkill, let's revisit...
//func (e *ProofApiError) Error() string {
//	return fmt.Sprintf("%s (url=%s; code=%d)", e.Desc, e.url, int(e.Status))
//}

func NewProofApiError(s ProofStatus, u string, d string, a ...interface{}) *ProofApiError {
	base := NewProofError(s, d, a...)
	return &ProofApiError{*base, u}
}

//
//=============================================================================

type ProofChecker interface {
	CheckHint(h SigHint) ProofError
	CheckStatus(h SigHint) ProofError
}

//
//=============================================================================

func XapiError(err error, u string) *ProofApiError {
	if ae, ok := err.(*ApiError); ok {
		var code ProofStatus = PROOF_NONE
		switch ae.Code / 100 {
		case 3:
			code = PROOF_HTTP_300
		case 4:
			code = PROOF_HTTP_400
		case 5:
			code = PROOF_HTTP_500
		default:
			code = PROOF_HTTP_OTHER
		}
		return NewProofApiError(code, u, ae.Msg)
	} else {
		return NewProofApiError(PROOF_INTERNAL_ERROR, u, err.Error())
	}
}

//=============================================================================
//

type ProofCheckHook (func(l RemoteProofChainLink) (ProofChecker, ProofError))

type ProofCheckDispatch map[string]ProofCheckHook

var _dispatch = make(ProofCheckDispatch)

func RegisterProofCheckHook(s string, h ProofCheckHook) {
	_dispatch[s] = h
}

func getProofCheckDispatch() ProofCheckDispatch {
	return _dispatch
}

func NewProofChecker(l RemoteProofChainLink) (ProofChecker, ProofError) {
	k := l.TableKey()
	hook, found := getProofCheckDispatch()[l.TableKey()]
	if !found {
		return nil, NewProofError(PROOF_UNKNOWN_TYPE,
			"No proof checker for type: %s", k)
	}
	return hook(l)
}

//
//=============================================================================
<commit_msg>cleaner hyet<commit_after>package libkb

import (
	"fmt"
)

const (
	PROOF_NONE  = 0
	PROOF_OK    = 1
	PROOF_LOCAL = 2
	PROOF_FOUND = 3 // It's been found in the hunt, but not proven yet

	// Retryable =soft errors
	PROOF_BASE_ERROR        = 100
	PROOF_HOST_UNREACHABLE  = 101
	PROOF_PERMISSION_DENIED = 103 // # Since the user might fix it
	PROOF_FAILED_PARSE      = 106
	PROOF_DNS_ERROR         = 107
	PROOF_AUTH_FAILED       = 108
	PROOF_HTTP_500          = 150
	PROOF_TIMEOUT           = 160
	PROOF_INTERNAL_ERROR    = 170

	// Likely will result in a hard error, if repeated enough
	PROOF_BASE_HARD_ERROR  = 200
	PROOF_NOT_FOUND        = 201
	PROOF_CONTENT_FAILURE  = 202
	PROOF_BAD_USERNAME     = 203
	PROOF_BAD_REMOTE_ID    = 204
	PROOF_TEXT_NOT_FOUND   = 205
	PROOF_BAD_ARGS         = 206
	PROOF_CONTENT_MISSING  = 207
	PROOF_TITLE_NOT_FOUND  = 208
	PROOF_SERVICE_ERROR    = 209
	PROOF_TOR_SKIPPED      = 210
	PROOF_TOR_INCOMPATIBLE = 211
	PROOF_HTTP_300         = 230
	PROOF_HTTP_400         = 240
	PROOF_HTTP_OTHER       = 260
	PROOF_EMPTY_JSON       = 270

	// Hard final errors
	PROOF_DELETED       = 301
	PROOF_SERVICE_DEAD  = 302
	PROOF_BAD_SIGNATURE = 303
	PROOF_BAD_API_URL   = 304
	PROOF_UNKNOWN_TYPE  = 305
	PROOF_NO_HINT       = 306
	PROOF_BAD_HINT_TEXT = 307
)

//=============================================================================
//
type ProofStatus int

type ProofError interface {
	error
	GetStatus() ProofStatus
}

type ProofErrorImpl struct {
	Status ProofStatus
	Desc   string
}

func NewProofError(s ProofStatus, d string, a ...interface{}) *ProofErrorImpl {
	return &ProofErrorImpl{s, fmt.Sprintf(d, a...)}
}

func (e *ProofErrorImpl) Error() string {
	return fmt.Sprintf("%s (code=%d)", e.Desc, int(e.Status))
}

func (e *ProofErrorImpl) GetStatus() ProofStatus { return e.Status }

type ProofApiError struct {
	ProofErrorImpl
	url string
}

// Might be overkill, let's revisit...
//func (e *ProofApiError) Error() string {
//	return fmt.Sprintf("%s (url=%s; code=%d)", e.Desc, e.url, int(e.Status))
//}

func NewProofApiError(s ProofStatus, u string, d string, a ...interface{}) *ProofApiError {
	base := NewProofError(s, d, a...)
	return &ProofApiError{*base, u}
}

//
//=============================================================================

type ProofChecker interface {
	CheckHint(h SigHint) ProofError
	CheckStatus(h SigHint) ProofError
}

//
//=============================================================================

func XapiError(err error, u string) *ProofApiError {
	if ae, ok := err.(*ApiError); ok {
		var code ProofStatus = PROOF_NONE
		switch ae.Code / 100 {
		case 3:
			code = PROOF_HTTP_300
		case 4:
			code = PROOF_HTTP_400
		case 5:
			code = PROOF_HTTP_500
		default:
			code = PROOF_HTTP_OTHER
		}
		return NewProofApiError(code, u, ae.Msg)
	} else {
		return NewProofApiError(PROOF_INTERNAL_ERROR, u, err.Error())
	}
}

//=============================================================================
//

type ProofCheckHook func(l RemoteProofChainLink) (ProofChecker, ProofError)

var _dispatch = make(map[string]ProofCheckHook)

func RegisterProofCheckHook(s string, h ProofCheckHook) {
	_dispatch[s] = h
}

func NewProofChecker(l RemoteProofChainLink) (ProofChecker, ProofError) {
	k := l.TableKey()
	hook, found := _dispatch[l.TableKey()]
	if !found {
		return nil, NewProofError(PROOF_UNKNOWN_TYPE,
			"No proof checker for type: %s", k)
	}
	return hook(l)
}

//
//=============================================================================
<|endoftext|>


<commit_before>//
// Written by Michael Mattioli
//

package main

import (
    "fmt"
    "strconv"
    "os"
)

// Position is a simple X,Y coordinate pair corresponding to a location on a 2D grid.
type Position struct {
    x, y int
}

// NewGrid returns a square, 2D slice; the size is determined by the span and each value is
// initialized to 0.
func NewGrid(span int) [][]int {
    grid := make([][]int, span)
    for i := range grid {
        grid[i] = make([]int, span)
    }
    return grid
}

// NewSpiral returns a square, 2D slice containing the numbers within the range of a particular
// number, n, squared organized in a spiral fashion.
func NewSpiral(n int) [][]int {

    // Make a new grid.
    grid := NewGrid(n)

    // Define the initial amount of steps to take when walking the grid in a spiral fashion.
    rightSteps := n - 1
    downSteps := n - 2
    leftSteps := n - 2
    upSteps := n - 3

    // Starting point will be the top-left corner (0,0).
    currentPosition := &Position{0, 0}

    // Always start to fill the grid with 1.
    currentNumber := 1

    // Start by moving toward the right then down, then left, then up, etc.
    nextStep := "Right"

    // Keep track o the number of steps we've taken in each direction.
    stepsTaken := 0

    for currentNumber <= (n * n) { // While we haven't reached the final number...
        grid[currentPosition.x][currentPosition.y] = currentNumber
        switch nextStep {
        case "Right":
            if stepsTaken < rightSteps {
                currentPosition.x++
                stepsTaken++
            } else {
                currentPosition.y++
                rightSteps -= 2
                stepsTaken = 0
                nextStep = "Down"
            }
        case "Down":
            if stepsTaken < downSteps {
                currentPosition.y++
                stepsTaken++
            } else {
                currentPosition.x--
                downSteps -= 2
                stepsTaken = 0
                nextStep = "Left"
            }
        case "Left":
            if stepsTaken < leftSteps {
                currentPosition.x--
                stepsTaken++
            } else {
                currentPosition.y--
                leftSteps -= 2
                stepsTaken = 0
                nextStep = "Up"
            }
        case "Up":
            if stepsTaken < upSteps {
                currentPosition.y--
                stepsTaken++
            } else {
                currentPosition.x++
                upSteps -= 2
                stepsTaken = 0
                nextStep = "Right"
            }
        }
        currentNumber++
    }

    return grid

}

// SpiralPrinter prints the elements of a square, 2D slice on the screen in which each element is
// equally spaced; it is assumed the specified slice's elements are arranged in a spiral fashion.
func SpiralPrinter(spiral [][]int) {

    elementWidth := len(strconv.Itoa(len(spiral) * len(spiral)))

    for i := range spiral {
        line := ""
        for j := range spiral[i] {
            element := strconv.Itoa(spiral[j][i])
            for padding := len(element); padding <= elementWidth; padding++ {
                element += " "
            }
            line += element
        }
        fmt.Println(line)
    }
}

func main() {

    specimen, err := strconv.Atoi(os.Args[1])
    if err != nil {
        fmt.Println("Incorrect usage")
        os.Exit(1)
    }

    spiral := NewSpiral(specimen)
    SpiralPrinter(spiral)

}
<commit_msg>Idiomatic improvements to challenge 320<commit_after>//
// Written by Michael Mattioli
//

package main

import (
    "fmt"
    "strconv"
    "os"
)

// NewSpiral returns a square, 2D slice containing the numbers within the range of a particular
// number, n, squared organized in a spiral fashion.
func NewSpiral(n int) [][]int {

    // Make a new square, 2D grid.
    grid := make([][]int, n)
    for i := range grid {
        grid[i] = make([]int, n)
    }

    // Define the initial amount of steps to take when walking the grid in a spiral fashion.
    steps := map[string]int {
        "Right" : n - 1,
        "Down" : n - 2,
        "Left": n - 2,
        "Up" : n - 3,
    }

    // Starting point will be the top-left corner (0,0).
    currentPosition := struct {
        x, y int
    }{
        0,
        0,
    }

    // Always start to fill the grid with 1.
    currentNumber := 1

    // Start by moving toward the right then down, then left, then up, etc.
    nextStep := "Right"

    // Keep track of the number of steps we've taken in each direction.
    stepsTaken := 0

    for currentNumber <= (n * n) { // While we haven't reached the final number...

        grid[currentPosition.x][currentPosition.y] = currentNumber

        turn := func(d string) {
            steps[nextStep] -= 2
            stepsTaken = 0
            nextStep = d
        }

        switch nextStep {
        case "Right":
            if stepsTaken < steps[nextStep] {
                currentPosition.x++
                stepsTaken++
                break
            }
            currentPosition.y++
            turn("Down")
        case "Down":
            if stepsTaken < steps[nextStep] {
                currentPosition.y++
                stepsTaken++
                break
            }
            currentPosition.x--
            turn("Left")
        case "Left":
            if stepsTaken < steps[nextStep] {
                currentPosition.x--
                stepsTaken++
                break
            }
            currentPosition.y--
            turn("Up")
        case "Up":
            if stepsTaken < steps[nextStep] {
                currentPosition.y--
                stepsTaken++
                break
            }
            currentPosition.x++
            turn("Right")
        }

        currentNumber++

    }

    return grid

}

// SpiralPrinter prints the elements of a square, 2D slice on the screen in which each element is
// equally spaced; it is assumed the specified slice's elements are arranged in a spiral fashion.
func SpiralPrinter(spiral [][]int) {

    elementWidth := len(strconv.Itoa(len(spiral) * len(spiral)))

    for i := range spiral {
        for j := range spiral[i] {
            element := strconv.Itoa(spiral[j][i])
            for padding := len(element); padding <= elementWidth; padding++ {
                element += " "
            }
            fmt.Printf("%s", element)
        }
        fmt.Printf("\n")
    }
}

func main() {

    specimen, err := strconv.Atoi(os.Args[1])
    if err != nil {
        fmt.Println("Incorrect usage")
        os.Exit(1)
    }

    spiral := NewSpiral(specimen)
    SpiralPrinter(spiral)

}
<|endoftext|>


<commit_before>/*

Package gogame is a set of functions and modules designed for writing games. Gogame uses SDL2 internally.

This software is free. It's released under the LGPL license. You can create open source and commercial games with it. See the license for full details.

OPENGL is required. Developer libraries of SDL2, SDL2-image and SDL2-TTF are required also.

*/
package gogame

/*
#cgo pkg-config: sdl2
#include "SDL.h"

int initSDL() {
	if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO) != 0) {
		SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
		return 1;
	}
	return 0;
}

SDL_Window * newScreen(char *title, int h, int v) {
    return SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, h, v, SDL_WINDOW_RESIZABLE);
}

SDL_Renderer * newRenderer( SDL_Window * screen ) {
    return SDL_CreateRenderer(screen, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); // SDL_RENDERER_SOFTWARE ); // SDL_RENDERER_ACCELERATED  );
}

*/
import "C"
import "errors"

var screen *C.SDL_Window
var renderer *C.SDL_Renderer

type Color struct {
	R, G, B, A uint8
}

var COLOR_WHITE = &Color{255, 255, 255, 255}
var COLOR_BLACK = &Color{0, 0, 0, 255}
var COLOR_RED = &Color{255, 0, 0, 255}
var COLOR_BLUE = &Color{0, 0, 255, 255}

// Use this function to create a window and a renderer (not visible to user)
func Init(title string, h, v int) error {
	if i := C.initSDL(); i != 0 {
		return errors.New("Error initializing SDL")
	}
	screen = C.newScreen(C.CString(title), C.int(h), C.int(v))
	renderer = C.newRenderer(screen)
	if screen == nil || renderer == nil {
		return errors.New("Error on initializing SDL2")
	}
	return nil
}

// Full Screen mode
func SetFullScreen(fs bool) {
	if fs {
		C.SDL_SetWindowFullscreen(screen, C.SDL_WINDOW_FULLSCREEN_DESKTOP)
	} else {
		C.SDL_SetWindowFullscreen(screen, 0)
	}
}

// Get window size
func GetWindowSize() (int, int) {
	var w, h C.int
	C.SDL_GetWindowSize(screen, &w, &h)
	return int(w), int(h)
}

// Set window size
func SetWindowSize(h, v int) {
	C.SDL_SetWindowSize(screen, C.int(h), C.int(v))
}

// Set a device independent resolution for rendering
func SetLogicalSize(h, v int) {
	C.SDL_RenderSetLogicalSize(renderer, C.int(h), C.int(v))
}

// Destroys renderer and window
func Quit() {
	C.SDL_DestroyRenderer(renderer)
	C.SDL_DestroyWindow(screen)
	C.SDL_Quit()
}

// Clear the current rendering target with black color
func RenderClear() {
	C.SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0)
	C.SDL_RenderClear(renderer)
}

// Update the screen with rendering performed
func RenderPresent() {
	C.SDL_RenderPresent(renderer)
}

// Wait specified number of milliseconds before returning
func Delay(s int) {
	C.SDL_Delay(C.Uint32(s))
}

// Draw pixel at position x,y
func DrawPixel(x, y int, color *Color) {
	C.SDL_SetRenderDrawColor(renderer, C.Uint8(color.R), C.Uint8(color.G), C.Uint8(color.B), C.Uint8(color.A))
	C.SDL_RenderDrawPoint(renderer, C.int(x), C.int(y))
}

// Draw line
func DrawLine(x1, y1, x2, y2 int, color *Color) {
	C.SDL_SetRenderDrawColor(renderer, C.Uint8(color.R), C.Uint8(color.G), C.Uint8(color.B), C.Uint8(color.A))
	C.SDL_RenderDrawLine(renderer, C.int(x1), C.int(y1), C.int(x2), C.int(y2))
}
<commit_msg>Added SetScaleQuality()<commit_after>/*

Package gogame is a set of functions and modules designed for writing games. Gogame uses SDL2 internally.

This software is free. It's released under the LGPL license. You can create open source and commercial games with it. See the license for full details.

OPENGL is required. Developer libraries of SDL2, SDL2-image and SDL2-TTF are required also.

*/
package gogame

/*
#cgo pkg-config: sdl2
#include "SDL.h"

int initSDL() {
	if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO) != 0) {
		SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
		return 1;
	}
	return 0;
}

SDL_Window * newScreen(char *title, int h, int v) {
    return SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, h, v, SDL_WINDOW_RESIZABLE);
}

SDL_Renderer * newRenderer( SDL_Window * screen ) {
    SDL_Renderer * r = SDL_CreateRenderer(screen, -1, SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_ACCELERATED); // SDL_RENDERER_SOFTWARE ); // SDL_RENDERER_ACCELERATED  );
	return r;
}

void setScaleQuality(int n) {
	switch(n) {
	case 1:
		SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1");
		break;
	case 2:
		SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "2");
	}
}

*/
import "C"
import "errors"

var screen *C.SDL_Window
var renderer *C.SDL_Renderer

type Color struct {
	R, G, B, A uint8
}

var COLOR_WHITE = &Color{255, 255, 255, 255}
var COLOR_BLACK = &Color{0, 0, 0, 255}
var COLOR_RED = &Color{255, 0, 0, 255}
var COLOR_BLUE = &Color{0, 0, 255, 255}

// Use this function to create a window and a renderer (not visible to user)
func Init(title string, h, v int) error {
	if i := C.initSDL(); i != 0 {
		return errors.New("Error initializing SDL")
	}
	screen = C.newScreen(C.CString(title), C.int(h), C.int(v))
	renderer = C.newRenderer(screen)
	if screen == nil || renderer == nil {
		return errors.New("Error on initializing SDL2")
	}
	return nil
}

func SetScaleQuality(n int) {
	C.setScaleQuality(C.int(n))
}

// Full Screen mode
func SetFullScreen(fs bool) {
	if fs {
		C.SDL_SetWindowFullscreen(screen, C.SDL_WINDOW_FULLSCREEN_DESKTOP)
	} else {
		C.SDL_SetWindowFullscreen(screen, 0)
	}
}

// Get window size
func GetWindowSize() (int, int) {
	var w, h C.int
	C.SDL_GetWindowSize(screen, &w, &h)
	return int(w), int(h)
}

// Set window size
func SetWindowSize(h, v int) {
	C.SDL_SetWindowSize(screen, C.int(h), C.int(v))
}

// Set a device independent resolution for rendering
func SetLogicalSize(h, v int) {
	C.SDL_RenderSetLogicalSize(renderer, C.int(h), C.int(v))
}

// Destroys renderer and window
func Quit() {
	C.SDL_DestroyRenderer(renderer)
	C.SDL_DestroyWindow(screen)
	C.SDL_Quit()
}

// Clear the current rendering target with black color
func RenderClear() {
	C.SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0)
	C.SDL_RenderClear(renderer)
}

// Update the screen with rendering performed
func RenderPresent() {
	C.SDL_RenderPresent(renderer)
}

// Wait specified number of milliseconds before returning
func Delay(s int) {
	C.SDL_Delay(C.Uint32(s))
}

// Draw pixel at position x,y
func DrawPixel(x, y int, color *Color) {
	C.SDL_SetRenderDrawColor(renderer, C.Uint8(color.R), C.Uint8(color.G), C.Uint8(color.B), C.Uint8(color.A))
	C.SDL_RenderDrawPoint(renderer, C.int(x), C.int(y))
}

// Draw line
func DrawLine(x1, y1, x2, y2 int, color *Color) {
	C.SDL_SetRenderDrawColor(renderer, C.Uint8(color.R), C.Uint8(color.G), C.Uint8(color.B), C.Uint8(color.A))
	C.SDL_RenderDrawLine(renderer, C.int(x1), C.int(y1), C.int(x2), C.int(y2))
}
<|endoftext|>


<commit_before>// run

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

// Test the behavior of closures.

package main

import "runtime"

var c = make(chan int)

func check(a []int) {
	for i := 0; i < len(a); i++ {
		n := <-c
		if n != a[i] {
			println("want", a[i], "got", n, "at", i)
			panic("fail")
		}
	}
}

func f() {
	var i, j int

	i = 1
	j = 2
	f := func() {
		c <- i
		i = 4
		g := func() {
			c <- i
			c <- j
		}
		g()
		c <- i
	}
	j = 5
	f()
}

// Accumulator generator
func accum(n int) func(int) int {
	return func(i int) int {
		n += i
		return n
	}
}

func g(a, b func(int) int) {
	c <- a(2)
	c <- b(3)
	c <- a(4)
	c <- b(5)
}

func h() {
	var x8 byte = 100
	var x64 int64 = 200

	c <- int(x8)
	c <- int(x64)
	f := func(z int) {
		g := func() {
			c <- int(x8)
			c <- int(x64)
			c <- z
		}
		g()
		c <- int(x8)
		c <- int(x64)
		c <- int(z)
	}
	x8 = 101
	x64 = 201
	f(500)
}

func newfunc() func(int) int { return func(x int) int { return x } }

func main() {
	var fail bool

	go f()
	check([]int{1, 4, 5, 4})

	a := accum(0)
	b := accum(1)
	go g(a, b)
	check([]int{2, 4, 6, 9})

	go h()
	check([]int{100, 200, 101, 201, 500, 101, 201, 500})

	memstats := new(runtime.MemStats)
	runtime.ReadMemStats(memstats)
	n0 := memstats.Mallocs

	x, y := newfunc(), newfunc()
	if x(1) != 1 || y(2) != 2 {
		println("newfunc returned broken funcs")
		fail = true
	}

	runtime.ReadMemStats(memstats)
	if n0 != memstats.Mallocs {
		println("newfunc allocated unexpectedly")
		fail = true
	}

	ff(1)

	if fail {
		panic("fail")
	}
}

func ff(x int) {
	call(func() {
		_ = x
	})
}

func call(func()) {
}
<commit_msg>test: enforce 1 proc in the test otherwise it fails spuriously with "newfunc allocated unexpectedly" message when run with GOMAXPROCS>1 (other goroutine allocates).<commit_after>// run

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

// Test the behavior of closures.

package main

import "runtime"

var c = make(chan int)

func check(a []int) {
	for i := 0; i < len(a); i++ {
		n := <-c
		if n != a[i] {
			println("want", a[i], "got", n, "at", i)
			panic("fail")
		}
	}
}

func f() {
	var i, j int

	i = 1
	j = 2
	f := func() {
		c <- i
		i = 4
		g := func() {
			c <- i
			c <- j
		}
		g()
		c <- i
	}
	j = 5
	f()
}

// Accumulator generator
func accum(n int) func(int) int {
	return func(i int) int {
		n += i
		return n
	}
}

func g(a, b func(int) int) {
	c <- a(2)
	c <- b(3)
	c <- a(4)
	c <- b(5)
}

func h() {
	var x8 byte = 100
	var x64 int64 = 200

	c <- int(x8)
	c <- int(x64)
	f := func(z int) {
		g := func() {
			c <- int(x8)
			c <- int(x64)
			c <- z
		}
		g()
		c <- int(x8)
		c <- int(x64)
		c <- int(z)
	}
	x8 = 101
	x64 = 201
	f(500)
}

func newfunc() func(int) int { return func(x int) int { return x } }

func main() {
	runtime.GOMAXPROCS(1)
	var fail bool

	go f()
	check([]int{1, 4, 5, 4})

	a := accum(0)
	b := accum(1)
	go g(a, b)
	check([]int{2, 4, 6, 9})

	go h()
	check([]int{100, 200, 101, 201, 500, 101, 201, 500})

	memstats := new(runtime.MemStats)
	runtime.ReadMemStats(memstats)
	n0 := memstats.Mallocs

	x, y := newfunc(), newfunc()
	if x(1) != 1 || y(2) != 2 {
		println("newfunc returned broken funcs")
		fail = true
	}

	runtime.ReadMemStats(memstats)
	if n0 != memstats.Mallocs {
		println("newfunc allocated unexpectedly")
		fail = true
	}

	ff(1)

	if fail {
		panic("fail")
	}
}

func ff(x int) {
	call(func() {
		_ = x
	})
}

func call(func()) {
}
<|endoftext|>


<commit_before>// +build freebsd

package memory

import (
	"bufio"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"os/exec"
	"strconv"
	"strings"
	"syscall"
)

// Get memory statistics
func Get() (*Stats, error) {
	cmd := exec.Command("top", "-b", "-n", "1")
	out, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}
	if err := cmd.Start(); err != nil {
		return nil, err
	}
	memory, err := collectMemoryStats(out)
	if err != nil {
		return nil, err
	}
	if err := cmd.Wait(); err != nil {
		return nil, err
	}

	ret, err := syscall.Sysctl("hw.physmem")
	if err != nil {
		return nil, fmt.Errorf("failed in sysctl hw.physmem: %s", err)
	}
	memory.Total = binary.LittleEndian.Uint64([]byte(ret + "\x00"))
	memory.Used = memory.Total - memory.Free - memory.Buffers - memory.Cached - memory.Inactive

	return memory, nil
}

// Stats represents memory statistics for freebsd
type Stats struct {
	Total, Used, Buffers, Cached, Free, Active, Inactive, Wired,
	SwapTotal, SwapFree uint64
}

func collectMemoryStats(out io.Reader) (*Stats, error) {
	scanner := bufio.NewScanner(out)

	var memory Stats
	memStats := map[string]*uint64{
		"MemBuf":    &memory.Buffers,
		"MemFree":   &memory.Free,
		"MemActive": &memory.Active,
		"MemInact":  &memory.Inactive,
		"MemWired":  &memory.Wired,
		"SwapTotal": &memory.SwapTotal,
		"SwapFree":  &memory.SwapFree,
	}

	var cnt int
	for scanner.Scan() {
		line := scanner.Text()
		if !strings.HasPrefix(line, "Mem:") && !strings.HasPrefix(line, "Swap:") {
			continue
		}
		cnt += 1
		i := strings.IndexRune(line, ':')
		prefix := line[:i]
		stats := strings.Split(line[i+1:], ",")
		for _, stat := range stats {
			cs := strings.Fields(stat)
			if len(cs) != 2 {
				continue
			}
			if ptr := memStats[prefix+cs[1]]; ptr != nil {
				if val, err := parseValue(cs[0]); err == nil {
					*ptr = val
				}
			}
		}
		if cnt == 2 {
			break
		}
	}

	if err := scanner.Err(); err != nil {
		return nil, fmt.Errorf("scan error for top -b -n 1: %s", err)
	}

	return &memory, nil
}

func parseValue(valStr string) (uint64, error) {
	if len(valStr) < 1 {
		return 0, errors.New("empty value")
	}
	var unit uint64
	switch valStr[len(valStr)-1] {
	case 'T':
		unit = 1024 * 1024 * 1024 * 1024
	case 'G':
		unit = 1024 * 1024 * 1024
	case 'M':
		unit = 1024 * 1024
	case 'K':
		unit = 1024
	default:
		unit = 1
	}
	val, err := strconv.ParseUint(valStr[:len(valStr)-1], 10, 64)
	return val * unit, err
}
<commit_msg>add swap_used memory for freebsd<commit_after>// +build freebsd

package memory

import (
	"bufio"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"os/exec"
	"strconv"
	"strings"
	"syscall"
)

// Get memory statistics
func Get() (*Stats, error) {
	cmd := exec.Command("top", "-b", "-n", "1")
	out, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}
	if err := cmd.Start(); err != nil {
		return nil, err
	}
	memory, err := collectMemoryStats(out)
	if err != nil {
		return nil, err
	}
	if err := cmd.Wait(); err != nil {
		return nil, err
	}

	ret, err := syscall.Sysctl("hw.physmem")
	if err != nil {
		return nil, fmt.Errorf("failed in sysctl hw.physmem: %s", err)
	}
	memory.Total = binary.LittleEndian.Uint64([]byte(ret + "\x00"))
	memory.Used = memory.Total - memory.Free - memory.Buffers - memory.Cached - memory.Inactive
	memory.SwapUsed = memory.SwapTotal - memory.SwapFree

	return memory, nil
}

// Stats represents memory statistics for freebsd
type Stats struct {
	Total, Used, Buffers, Cached, Free, Active, Inactive, Wired,
	SwapTotal, SwapUsed, SwapFree uint64
}

func collectMemoryStats(out io.Reader) (*Stats, error) {
	scanner := bufio.NewScanner(out)

	var memory Stats
	memStats := map[string]*uint64{
		"MemBuf":    &memory.Buffers,
		"MemFree":   &memory.Free,
		"MemActive": &memory.Active,
		"MemInact":  &memory.Inactive,
		"MemWired":  &memory.Wired,
		"SwapTotal": &memory.SwapTotal,
		"SwapFree":  &memory.SwapFree,
	}

	var cnt int
	for scanner.Scan() {
		line := scanner.Text()
		if !strings.HasPrefix(line, "Mem:") && !strings.HasPrefix(line, "Swap:") {
			continue
		}
		cnt += 1
		i := strings.IndexRune(line, ':')
		prefix := line[:i]
		stats := strings.Split(line[i+1:], ",")
		for _, stat := range stats {
			cs := strings.Fields(stat)
			if len(cs) != 2 {
				continue
			}
			if ptr := memStats[prefix+cs[1]]; ptr != nil {
				if val, err := parseValue(cs[0]); err == nil {
					*ptr = val
				}
			}
		}
		if cnt == 2 {
			break
		}
	}

	if err := scanner.Err(); err != nil {
		return nil, fmt.Errorf("scan error for top -b -n 1: %s", err)
	}

	return &memory, nil
}

func parseValue(valStr string) (uint64, error) {
	if len(valStr) < 1 {
		return 0, errors.New("empty value")
	}
	var unit uint64
	switch valStr[len(valStr)-1] {
	case 'T':
		unit = 1024 * 1024 * 1024 * 1024
	case 'G':
		unit = 1024 * 1024 * 1024
	case 'M':
		unit = 1024 * 1024
	case 'K':
		unit = 1024
	default:
		unit = 1
	}
	val, err := strconv.ParseUint(valStr[:len(valStr)-1], 10, 64)
	return val * unit, err
}
<|endoftext|>


<commit_before>package calcom
import (
	"golang.org/x/net/context"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
	"google.golang.org/api/calendar/v3"
	"io/ioutil"
	. "github.com/rugo/sacapi/modules/apilog"
	"github.com/rugo/sacapi/modules/auth"
	"github.com/rugo/sacapi/modules/data"
	"time"
	"errors"
)

var (
	oauthConfig *oauth2.Config
)

func GetNextGoogleCalendarEntry(ctx context.Context, deviceId string) (data.ClockInfo, error) {
	/* ToDo: remove test code */
	// Not to be done in every request, JUST FOR TESTING!!
	b, err := ioutil.ReadFile("/tmp/google_api_secret.json")
	if err != nil {
		Log.Fatalf("Unable to read client secret file: %v", err)
	}

	oauthConfig, err = google.ConfigFromJSON(b, calendar.CalendarReadonlyScope)
	if err != nil {
		Log.Fatalf("Unable to parse client secret file to config: %v", err)
	}

	token, err := auth.LoadToken(deviceId)
	if err != nil {
		Log.Error("Could not load token for device %s", deviceId)
		return data.ClockInfo{}, err
	}

	client := oauthConfig.Client(ctx, token)
	srv, err := calendar.New(client)

	if err != nil {
		Log.Error("Unable to retrieve calendar Client %v", err)
	}

	t := time.Now().Format(time.RFC3339)
	events, err := srv.Events.List("primary").ShowDeleted(false).
	SingleEvents(true).TimeMin(t).MaxResults(1).OrderBy("startTime").Do()
	if err != nil {
		Log.Error("Unable to retrieve next ten of the user's events. %v", err)
	}

	if len(events.Items) > 0 {
		entry := events.Items[0]
		nextEntry := data.ClockInfo{
			Appointment: data.Appointment{
				Time: 12345,
				Name: entry.Summary,
				Description: entry.Description,
			},
			Timezone: events.TimeZone,
			Apivers: 0,
		}
		return nextEntry, nil
	} else {
		errMsg := "Device %s user has no appointments."
		Log.Error(errMsg, deviceId)
		return data.ClockInfo{}, errors.New(errMsg)
	}

}
<commit_msg>did quick and dirty stuff<commit_after>package calcom
import (
	"golang.org/x/net/context"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/google"
	"google.golang.org/api/calendar/v3"
	"io/ioutil"
	. "github.com/rugo/sacapi/modules/apilog"
	"github.com/rugo/sacapi/modules/auth"
	"github.com/rugo/sacapi/modules/data"
	"time"
	"errors"
)

var (
	oauthConfig *oauth2.Config
)

func GetNextGoogleCalendarEntry(ctx context.Context, deviceId string) (data.ClockInfo, error) {
	/* ToDo: remove test code */
	// Not to be done in every request, JUST FOR TESTING!!
	b, err := ioutil.ReadFile("/tmp/google_api_secret.json")
	if err != nil {
		Log.Fatalf("Unable to read client secret file: %v", err)
	}

	oauthConfig, err = google.ConfigFromJSON(b, calendar.CalendarReadonlyScope)
	if err != nil {
		Log.Fatalf("Unable to parse client secret file to config: %v", err)
	}

	token, err := auth.LoadToken(deviceId)
	if err != nil {
		Log.Error("Could not load token for device %s", deviceId)
		return data.ClockInfo{}, err
	}

	client := oauthConfig.Client(ctx, token)
	srv, err := calendar.New(client)

	if err != nil {
		Log.Error("Unable to retrieve calendar Client %v", err)
	}

	t := time.Now().Format(time.RFC3339)
	events, err := srv.Events.List("primary").ShowDeleted(false).
	SingleEvents(true).TimeMin(t).MaxResults(1).OrderBy("startTime").Do()
	if err != nil {
		Log.Error("Unable to retrieve next ten of the user's events. %v", err)
	}

	if len(events.Items) > 0 {
		entry := events.Items[0]
		startTime, err := time.Parse(time.RFC3339, entry.Start.DateTime)

		if err != nil {
			Log.Error("Could not parse time %s", entry.Start.DateTime)
			return data.ClockInfo{}, errors.New("Communication error with API")
		}

		nextEntry := data.ClockInfo{
			Appointment: data.Appointment{
				Time: startTime.Unix(),
				Name: entry.Summary,
				Description: entry.Description,
			},
			Timezone: events.TimeZone,
			Apivers: 0,
		}
		return nextEntry, nil
	} else {
		errMsg := "Device %s user has no appointments."
		Log.Error(errMsg, deviceId)
		return data.ClockInfo{}, errors.New(errMsg)
	}

}
<|endoftext|>


<commit_before><commit_msg>delete unnecessary directory<commit_after><|endoftext|>


<commit_before>// Package core provides http handlers for all Chain operations.
package core

import (
	"strconv"
	"time"

	"chain/core/appdb"
	"chain/core/blocksigner"
	"chain/core/generator"
	"chain/core/mockhsm"
	"chain/core/query"
	"chain/core/txdb"
	chainhttp "chain/net/http"
	"chain/net/http/httpjson"
	"chain/net/http/pat"
)

const (
	sessionTokenLifetime = 2 * 7 * 24 * time.Hour
	defAccountPageSize   = 100
	defAssetPageSize     = 100
	defGenericPageSize   = 100
)

// Handler returns a handler that serves the Chain HTTP API. Param nouserSecret
// will be used as the password for routes starting with /nouser/.
func Handler(
	nouserSecret string,
	generatorConfig *generator.Config,
	signer *blocksigner.Signer,
	store *txdb.Store,
	pool *txdb.Pool,
	hsm *mockhsm.HSM,
	indexer *query.Indexer,
) chainhttp.Handler {
	h := pat.New()
	a := &api{
		store:     store,
		pool:      pool,
		generator: generatorConfig,
		hsm:       hsm,
		indexer:   indexer,
	}

	pwHandler := httpjson.NewServeMux(writeHTTPError)
	pwHandler.HandleFunc("POST", "/v3/login", login)
	h.AddFunc("POST", "/v3/login", userCredsAuthn(pwHandler.ServeHTTPContext))

	nouserHandler := chainhttp.HandlerFunc(nouserAuthn(nouserSecret, nouserHandler()))
	h.Add("GET", "/nouser/", nouserHandler)
	h.Add("PUT", "/nouser/", nouserHandler)
	h.Add("POST", "/nouser/", nouserHandler)
	h.Add("DELETE", "/nouser/", nouserHandler)

	tokenHandler := chainhttp.HandlerFunc(tokenAuthn(a.tokenAuthedHandler()))
	h.Add("GET", "/", tokenHandler)
	h.Add("PUT", "/", tokenHandler)
	h.Add("POST", "/", tokenHandler)
	h.Add("DELETE", "/", tokenHandler)

	rpcHandler := chainhttp.HandlerFunc(rpcAuthn(rpcAuthedHandler(generatorConfig, signer)))
	h.Add("GET", "/rpc/", rpcHandler)
	h.Add("PUT", "/rpc/", rpcHandler)
	h.Add("POST", "/rpc/", rpcHandler)
	h.Add("DELETE", "/rpc/", rpcHandler)

	return h
}

func nouserHandler() chainhttp.HandlerFunc {
	h := httpjson.NewServeMux(writeHTTPError)

	// These routes must trust the client to enforce access control.
	// Think twice before adding something here.
	h.HandleFunc("GET", "/nouser/invitations/:invID", appdb.GetInvitation)
	h.HandleFunc("POST", "/nouser/invitations/:invID/create-user", createUserFromInvitation)
	h.HandleFunc("POST", "/nouser/password-reset/start", startPasswordReset)
	h.HandleFunc("POST", "/nouser/password-reset/check", checkPasswordReset)
	h.HandleFunc("POST", "/nouser/password-reset/finish", finishPasswordReset)

	return h.ServeHTTPContext
}

type api struct {
	store     *txdb.Store
	pool      *txdb.Pool
	generator *generator.Config
	hsm       *mockhsm.HSM
	indexer   *query.Indexer
}

// Used as a request object for api queries
type requestQuery struct {
	Cursor    string   `json:"cursor"`
	Index     string   `json:"index,omitempty"`
	StartTime uint64   `json:"start_time,omitempty"`
	EndTime   uint64   `json:"end_time,omitempty"`
	Params    []string `json:"params,omitempty"`
}

// Used as a response object for api queries
type page struct {
	Items    []interface{} `json:"items"`
	LastPage bool          `json:"last_page"`
	Query    requestQuery  `json:"query"`
}

func (a *api) tokenAuthedHandler() chainhttp.HandlerFunc {
	h := httpjson.NewServeMux(writeHTTPError)
	h.HandleFunc("POST", "/v3/invitations", createInvitation)
	h.HandleFunc("POST", "/list-accounts", listAccounts)
	h.HandleFunc("POST", "/create-account", createAccount)
	h.HandleFunc("POST", "/get-account", getAccount)
	h.HandleFunc("POST", "/set-account-tags", setAccountTags)
	h.HandleFunc("POST", "/list-assets", a.listAssets)
	h.HandleFunc("POST", "/create-asset", a.createAsset)
	h.HandleFunc("POST", "/update-asset", setAssetTags)
	h.HandleFunc("POST", "/v3/accounts/:accountID/control-programs", createAccountControlProgram)
	h.HandleFunc("DELETE", "/v3/accounts/:accountID", archiveAccount)
	h.HandleFunc("DELETE", "/v3/assets/:assetID", archiveAsset)
	h.HandleFunc("POST", "/build-transaction-template", build)
	h.HandleFunc("POST", "/v3/transact/submit", submit)
	h.HandleFunc("POST", "/v3/transact/finalize", submitSingle) // DEPRECATED
	h.HandleFunc("POST", "/v3/transact/finalize-batch", submit) // DEPRECATED
	h.HandleFunc("POST", "/v3/transact/cancel-reservation", cancelReservation)
	h.HandleFunc("GET", "/v3/user", getAuthdUser)
	h.HandleFunc("POST", "/v3/user/email", updateUserEmail)
	h.HandleFunc("POST", "/v3/user/password", updateUserPassword)
	h.HandleFunc("PUT", "/v3/user/:userID/role", updateUserRole)
	h.HandleFunc("GET", "/v3/users", listUsers)
	h.HandleFunc("GET", "/v3/authcheck", func() {})
	h.HandleFunc("GET", "/v3/api-tokens", listAPITokens)
	h.HandleFunc("POST", "/v3/api-tokens", createAPIToken)
	h.HandleFunc("DELETE", "/v3/api-tokens/:tokenID", appdb.DeleteAuthToken)

	// MockHSM endpoints
	h.HandleFunc("POST", "/mockhsm/create-key", a.mockhsmCreateKey)
	h.HandleFunc("POST", "/mockhsm/list-keys", a.mockhsmListKeys)
	h.HandleFunc("POST", "/mockhsm/delkey", a.mockhsmDelKey)
	h.HandleFunc("POST", "/mockhsm/signtemplates", a.mockhsmSignTemplates)

	// Transaction indexes & querying
	h.HandleFunc("POST", "/create-index", a.createIndex)
	h.HandleFunc("POST", "/list-indexes", a.listIndexes)
	h.HandleFunc("POST", "/get-index", a.getIndex)

	return h.ServeHTTPContext
}

func rpcAuthedHandler(generator *generator.Config, signer *blocksigner.Signer) chainhttp.HandlerFunc {
	h := httpjson.NewServeMux(writeHTTPError)

	if generator != nil {
		h.HandleFunc("POST", "/rpc/generator/submit", generator.Submit)
		h.HandleFunc("POST", "/rpc/generator/get-blocks", generator.GetBlocks)
	}
	if signer != nil {
		h.HandleFunc("POST", "/rpc/signer/sign-block", signer.SignBlock)
	}

	return h.ServeHTTPContext
}

// For time query-params that can be in either RFC3339 or
// Unix-timestamp form.
func parseTime(s string) (t time.Time, err error) {
	t, err = time.Parse(time.RFC3339, s)
	if err != nil {
		i, err := strconv.ParseInt(s, 10, 64)
		if err != nil {
			return t, err
		}
		t = time.Unix(i, 0)
	}
	return t, nil
}
<commit_msg>core: use spec-defined submit tx template path<commit_after>// Package core provides http handlers for all Chain operations.
package core

import (
	"strconv"
	"time"

	"chain/core/appdb"
	"chain/core/blocksigner"
	"chain/core/generator"
	"chain/core/mockhsm"
	"chain/core/query"
	"chain/core/txdb"
	chainhttp "chain/net/http"
	"chain/net/http/httpjson"
	"chain/net/http/pat"
)

const (
	sessionTokenLifetime = 2 * 7 * 24 * time.Hour
	defAccountPageSize   = 100
	defAssetPageSize     = 100
	defGenericPageSize   = 100
)

// Handler returns a handler that serves the Chain HTTP API. Param nouserSecret
// will be used as the password for routes starting with /nouser/.
func Handler(
	nouserSecret string,
	generatorConfig *generator.Config,
	signer *blocksigner.Signer,
	store *txdb.Store,
	pool *txdb.Pool,
	hsm *mockhsm.HSM,
	indexer *query.Indexer,
) chainhttp.Handler {
	h := pat.New()
	a := &api{
		store:     store,
		pool:      pool,
		generator: generatorConfig,
		hsm:       hsm,
		indexer:   indexer,
	}

	pwHandler := httpjson.NewServeMux(writeHTTPError)
	pwHandler.HandleFunc("POST", "/v3/login", login)
	h.AddFunc("POST", "/v3/login", userCredsAuthn(pwHandler.ServeHTTPContext))

	nouserHandler := chainhttp.HandlerFunc(nouserAuthn(nouserSecret, nouserHandler()))
	h.Add("GET", "/nouser/", nouserHandler)
	h.Add("PUT", "/nouser/", nouserHandler)
	h.Add("POST", "/nouser/", nouserHandler)
	h.Add("DELETE", "/nouser/", nouserHandler)

	tokenHandler := chainhttp.HandlerFunc(tokenAuthn(a.tokenAuthedHandler()))
	h.Add("GET", "/", tokenHandler)
	h.Add("PUT", "/", tokenHandler)
	h.Add("POST", "/", tokenHandler)
	h.Add("DELETE", "/", tokenHandler)

	rpcHandler := chainhttp.HandlerFunc(rpcAuthn(rpcAuthedHandler(generatorConfig, signer)))
	h.Add("GET", "/rpc/", rpcHandler)
	h.Add("PUT", "/rpc/", rpcHandler)
	h.Add("POST", "/rpc/", rpcHandler)
	h.Add("DELETE", "/rpc/", rpcHandler)

	return h
}

func nouserHandler() chainhttp.HandlerFunc {
	h := httpjson.NewServeMux(writeHTTPError)

	// These routes must trust the client to enforce access control.
	// Think twice before adding something here.
	h.HandleFunc("GET", "/nouser/invitations/:invID", appdb.GetInvitation)
	h.HandleFunc("POST", "/nouser/invitations/:invID/create-user", createUserFromInvitation)
	h.HandleFunc("POST", "/nouser/password-reset/start", startPasswordReset)
	h.HandleFunc("POST", "/nouser/password-reset/check", checkPasswordReset)
	h.HandleFunc("POST", "/nouser/password-reset/finish", finishPasswordReset)

	return h.ServeHTTPContext
}

type api struct {
	store     *txdb.Store
	pool      *txdb.Pool
	generator *generator.Config
	hsm       *mockhsm.HSM
	indexer   *query.Indexer
}

// Used as a request object for api queries
type requestQuery struct {
	Cursor    string   `json:"cursor"`
	Index     string   `json:"index,omitempty"`
	StartTime uint64   `json:"start_time,omitempty"`
	EndTime   uint64   `json:"end_time,omitempty"`
	Params    []string `json:"params,omitempty"`
}

// Used as a response object for api queries
type page struct {
	Items    []interface{} `json:"items"`
	LastPage bool          `json:"last_page"`
	Query    requestQuery  `json:"query"`
}

func (a *api) tokenAuthedHandler() chainhttp.HandlerFunc {
	h := httpjson.NewServeMux(writeHTTPError)
	h.HandleFunc("POST", "/v3/invitations", createInvitation)
	h.HandleFunc("POST", "/list-accounts", listAccounts)
	h.HandleFunc("POST", "/create-account", createAccount)
	h.HandleFunc("POST", "/get-account", getAccount)
	h.HandleFunc("POST", "/set-account-tags", setAccountTags)
	h.HandleFunc("POST", "/list-assets", a.listAssets)
	h.HandleFunc("POST", "/create-asset", a.createAsset)
	h.HandleFunc("POST", "/update-asset", setAssetTags)
	h.HandleFunc("POST", "/v3/accounts/:accountID/control-programs", createAccountControlProgram)
	h.HandleFunc("DELETE", "/v3/accounts/:accountID", archiveAccount)
	h.HandleFunc("DELETE", "/v3/assets/:assetID", archiveAsset)
	h.HandleFunc("POST", "/build-transaction-template", build)
	h.HandleFunc("POST", "/submit-transaction-template", submit)
	h.HandleFunc("POST", "/v3/transact/cancel-reservation", cancelReservation)
	h.HandleFunc("GET", "/v3/user", getAuthdUser)
	h.HandleFunc("POST", "/v3/user/email", updateUserEmail)
	h.HandleFunc("POST", "/v3/user/password", updateUserPassword)
	h.HandleFunc("PUT", "/v3/user/:userID/role", updateUserRole)
	h.HandleFunc("GET", "/v3/users", listUsers)
	h.HandleFunc("GET", "/v3/authcheck", func() {})
	h.HandleFunc("GET", "/v3/api-tokens", listAPITokens)
	h.HandleFunc("POST", "/v3/api-tokens", createAPIToken)
	h.HandleFunc("DELETE", "/v3/api-tokens/:tokenID", appdb.DeleteAuthToken)

	// MockHSM endpoints
	h.HandleFunc("POST", "/mockhsm/create-key", a.mockhsmCreateKey)
	h.HandleFunc("POST", "/mockhsm/list-keys", a.mockhsmListKeys)
	h.HandleFunc("POST", "/mockhsm/delkey", a.mockhsmDelKey)
	h.HandleFunc("POST", "/mockhsm/signtemplates", a.mockhsmSignTemplates)

	// Transaction indexes & querying
	h.HandleFunc("POST", "/create-index", a.createIndex)
	h.HandleFunc("POST", "/list-indexes", a.listIndexes)
	h.HandleFunc("POST", "/get-index", a.getIndex)

	return h.ServeHTTPContext
}

func rpcAuthedHandler(generator *generator.Config, signer *blocksigner.Signer) chainhttp.HandlerFunc {
	h := httpjson.NewServeMux(writeHTTPError)

	if generator != nil {
		h.HandleFunc("POST", "/rpc/generator/submit", generator.Submit)
		h.HandleFunc("POST", "/rpc/generator/get-blocks", generator.GetBlocks)
	}
	if signer != nil {
		h.HandleFunc("POST", "/rpc/signer/sign-block", signer.SignBlock)
	}

	return h.ServeHTTPContext
}

// For time query-params that can be in either RFC3339 or
// Unix-timestamp form.
func parseTime(s string) (t time.Time, err error) {
	t, err = time.Parse(time.RFC3339, s)
	if err != nil {
		i, err := strconv.ParseInt(s, 10, 64)
		if err != nil {
			return t, err
		}
		t = time.Unix(i, 0)
	}
	return t, nil
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"fmt"
	"io"
	"os/exec"

	"github.com/pkg/errors"
)

func printLine(r io.Reader) {
	sc := bufio.NewScanner(r)

	for sc.Scan() {
		fmt.Println(sc.Text())
	}
}

func RunCommand(cmd *exec.Cmd) error {
	stdout, err := cmd.StdoutPipe()

	if err != nil {
		return errors.Wrap(err, fmt.Sprintf("creating stdout failed. command: %v", cmd.Args))
	}

	stderr, err := cmd.StderrPipe()

	if err != nil {
		return errors.Wrap(err, fmt.Sprintf("creating stderr failed. command: %v", cmd.Args))
	}

	cmd.Start()

	go printLine(stdout)
	go printLine(stderr)

	if err = cmd.Wait(); err != nil {
		return errors.Wrap(err, fmt.Sprintf("command execution failed. command: %v", cmd.Args))
	}

	return nil
}
<commit_msg>Show stdout/stderr with indentation<commit_after>package main

import (
	"bufio"
	"fmt"
	"io"
	"os/exec"

	"github.com/pkg/errors"
)

func printLine(r io.Reader) {
	sc := bufio.NewScanner(r)

	for sc.Scan() {
		fmt.Println("       " + sc.Text())
	}
}

func RunCommand(cmd *exec.Cmd) error {
	stdout, err := cmd.StdoutPipe()

	if err != nil {
		return errors.Wrap(err, fmt.Sprintf("creating stdout failed. command: %v", cmd.Args))
	}

	stderr, err := cmd.StderrPipe()

	if err != nil {
		return errors.Wrap(err, fmt.Sprintf("creating stderr failed. command: %v", cmd.Args))
	}

	cmd.Start()

	go printLine(stdout)
	go printLine(stderr)

	if err = cmd.Wait(); err != nil {
		return errors.Wrap(err, fmt.Sprintf("command execution failed. command: %v", cmd.Args))
	}

	return nil
}
<|endoftext|>


<commit_before>// Copyright 2013 Hui Chen
// Copyright 2016 ego 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 riot

// NumTokenIndexAdded added token index number
func (engine *Engine) NumTokenIndexAdded() uint64 {
	return engine.numTokenIndexAdded
}

// NumDocsIndexed documents indexed number
func (engine *Engine) NumDocsIndexed() uint64 {
	return engine.numDocsIndexed
}

// NumDocsRemoved documents removed number
func (engine *Engine) NumDocsRemoved() uint64 {
	return engine.numDocsRemoved
}
<commit_msg>optimize counters func [ci skip]<commit_after>// Copyright 2013 Hui Chen
// Copyright 2016 ego 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 riot

// NumTokenAdded added token index number
func (engine *Engine) NumTokenAdded() uint64 {
	return engine.numTokenIndexAdded
}

// NumIndexed documents indexed number
func (engine *Engine) NumIndexed() uint64 {
	return engine.numDocsIndexed
}

// NumRemoved documents removed number
func (engine *Engine) NumRemoved() uint64 {
	return engine.numDocsRemoved
}

// NumTokenIndexAdded added token index number, deprecated
func (engine *Engine) NumTokenIndexAdded() uint64 {
	return engine.numTokenIndexAdded
}

// NumDocsIndexed documents indexed number, deprecated
func (engine *Engine) NumDocsIndexed() uint64 {
	return engine.numDocsIndexed
}

// NumDocsRemoved documents removed number, deprecated
func (engine *Engine) NumDocsRemoved() uint64 {
	return engine.numDocsRemoved
}
<|endoftext|>


<commit_before>// Copyright 2015 Claudemiro Alves Feitosa Neto. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package gochip8

import (
	"testing"

	"github.com/bmizerany/assert"
)

// dumbSound - Only for testing purpuses
type dumbSound struct {
	BeepCalled bool
}

func (s *dumbSound) Beep() {
	(*s).BeepCalled = true
}

// newCpuAt creates a new cpu and write the ins to the pc memory location
// Only for testing purpuse
func newCpuAt(ins uint16) cpu {
	s := &dumbSound{}
	c := newCpu(s)
	c.memory.WriteWord(uint16(c.pc), ins)

	return c
}

func TestTimers(t *testing.T) {
	s := &dumbSound{}
	c := newCpu(s)

	// With Beep
	c.memory.WriteWord(uint16(c.pc), 0x0E0)

	c.dt = 1
	c.st = 1

	assert.Equal(t, s.BeepCalled, false)

	c.Step()

	assert.Equal(t, c.dt, byte(0))
	assert.Equal(t, c.st, byte(0))
	assert.Equal(t, s.BeepCalled, true)

	// No Beep
	c.memory.WriteWord(uint16(c.pc), 0x0E0)
	s.BeepCalled = false

	c.st = 2
	c.Step()

	assert.Equal(t, s.BeepCalled, false)
	assert.Equal(t, c.st, byte(1))
}

// 00E0 - CLS
func Test00E0(t *testing.T) {

	c := newCpuAt(0x00E0)
	c.gfx.SetPixel(0, 0)
	c.Step()

	for i := 0; i < 64; i++ {
		for j := 0; j < 32; j++ {
			assert.Equal(t, byte(COLOR_BLACK), byte(c.gfx.GetPixel(i, j)))
		}
	}
}

// 00EE - RET
func Test00EE(t *testing.T) {
	c := newCpuAt(0x00EE)

	c.stack.Push(pc(1))
	c.Step()

	assert.Equal(t, pc(1), c.pc)
}

// 1nnn - JP addr
func Test1000(t *testing.T) {
	c := newCpuAt(0x1FFF)
	c.Step()

	assert.Equal(t, pc(0x0FFF), c.pc)
}

// 2nnn - CALL addr
func Test2000(t *testing.T) {
	c := newCpuAt(0x2FFF)
	oldPC := c.pc + 2 // The increment happen before the Step

	c.Step()

	assert.Equal(t, oldPC, c.stack.Pop())
	assert.Equal(t, pc(0x0FFF), c.pc)
}

// 3xkk - SE Vx, byte
func Test3000Equal(t *testing.T) {
	c := newCpuAt(0x31FF)
	c.regs[1] = 0xFF

	oldPC := c.pc + 4
	c.Step()

	assert.Equal(t, oldPC, c.pc)
}

// 3xkk - SE Vx, byte
func Test3000NotEqual(t *testing.T) {
	c := newCpuAt(0x31FF)
	c.regs[1] = 0xAA

	oldPC := c.pc + 2
	c.Step()

	assert.Equal(t, oldPC, c.pc)
}

// 4xkk - SNE Vx, byte
func Test4000Equal(t *testing.T) {
	c := newCpuAt(0x41FF)
	c.regs[1] = 0xFF

	oldPC := c.pc + 2
	c.Step()

	assert.Equal(t, oldPC, c.pc)
}

// 4xkk - SNE Vx, byte
func Test4000NotEqual(t *testing.T) {
	c := newCpuAt(0x41FF)
	c.regs[1] = 0xAA

	oldPC := c.pc + 4
	c.Step()

	assert.Equal(t, oldPC, c.pc)
}

// 5xy0 - SE Vx, Vy
func Test5000Equal(t *testing.T) {
	c := newCpuAt(0x512F)
	c.regs[1] = 0xFF
	c.regs[2] = 0xFF

	oldPC := c.pc + 4
	c.Step()

	assert.Equal(t, oldPC, c.pc)
}

// 5xy0 - SE Vx, Vy
func Test5000NotEqual(t *testing.T) {
	c := newCpuAt(0x512F)
	c.regs[1] = 0xFF
	c.regs[2] = 0xAA

	oldPC := c.pc + 2
	c.Step()

	assert.Equal(t, oldPC, c.pc)
}

// 6xkk - LD Vx, byte
func Test6000(t *testing.T) {
	c := newCpuAt(0x61FF)
	c.Step()
	assert.Equal(t, c.regs[1], byte(0xFF))
}

// 7xkk - ADD Vx, byte
func Test7000(t *testing.T) {
	c := newCpuAt(0x7101)
	c.regs[1] = 1
	c.Step()
	assert.Equal(t, c.regs[1], byte(2))
}

// 8xy0 - LD Vx, Vy
func Test8xy0(t *testing.T) {
	c := newCpuAt(0x8120)
	c.regs[1] = 1
	c.regs[2] = 0
	assert.Equal(t, c.regs[1], byte(1))
	assert.Equal(t, c.regs[2], byte(0))
	c.Step()
	assert.Equal(t, c.regs[1], byte(0))
	assert.Equal(t, c.regs[2], byte(0))
}

// 8xy1 - OR Vx, Vy
func Test8xy1(t *testing.T) {
	c := newCpuAt(0x8121)
	c.regs[1] = 1
	c.regs[2] = 2
	assert.Equal(t, c.regs[1], byte(1))
	assert.Equal(t, c.regs[2], byte(2))
	c.Step()
	assert.Equal(t, c.regs[1], byte(1|2))
	assert.Equal(t, c.regs[2], byte(2))
}

// 8xy2 - OR Vx, Vy
func Test8xy2(t *testing.T) {
	c := newCpuAt(0x8122)
	c.regs[1] = 1
	c.regs[2] = 2
	assert.Equal(t, c.regs[1], byte(1))
	assert.Equal(t, c.regs[2], byte(2))
	c.Step()
	assert.Equal(t, c.regs[1], byte(1&2))
	assert.Equal(t, c.regs[2], byte(2))
}

// 8xy3 - OR Vx, Vy
func Test8xy3(t *testing.T) {
	c := newCpuAt(0x8123)
	c.regs[1] = 1
	c.regs[2] = 2
	assert.Equal(t, c.regs[1], byte(1))
	assert.Equal(t, c.regs[2], byte(2))
	c.Step()
	assert.Equal(t, c.regs[1], byte(1^2))
	assert.Equal(t, c.regs[2], byte(2))
}

// 8xy4 - ADD Vx, Vy
func Test8xy4Overflow(t *testing.T) {
	c := newCpuAt(0x8124)
	c.regs[1] = 0xFF
	c.regs[2] = 1

	assert.Equal(t, c.regs[0xF], byte(0))

	c.Step()

	assert.Equal(t, c.regs[1], byte(0))
	assert.Equal(t, c.regs[0xF], byte(1))
}

// 8xy4 - ADD Vx, Vy
func Test8xy4ONotverflow(t *testing.T) {
	c := newCpuAt(0x8124)
	c.regs[1] = 0xF0
	c.regs[2] = 1

	assert.Equal(t, c.regs[0xF], byte(0))

	c.Step()

	assert.Equal(t, c.regs[1], byte(0xF0+1))
	assert.Equal(t, c.regs[0xF], byte(0))
}

// 8xy5 - SUB Vx, Vy
func Test8xy5Greater(t *testing.T) {
	c := newCpuAt(0x8125)
	c.regs[1] = 2
	c.regs[2] = 1

	assert.Equal(t, c.regs[0xF], byte(0))

	c.Step()

	assert.Equal(t, c.regs[1], byte(1))
	assert.Equal(t, c.regs[0xF], byte(1))
}

// 8xy5 - SUB Vx, Vy
func Test8xy5NotGreater(t *testing.T) {
	c := newCpuAt(0x8125)
	c.regs[1] = 1
	c.regs[2] = 2

	assert.Equal(t, c.regs[0xF], byte(0))

	c.Step()

	assert.Equal(t, c.regs[1], byte(0xFF))
	assert.Equal(t, c.regs[0xF], byte(0))
}

// 8xy6 - SHR Vx {, Vy}
func Test8xy6(t *testing.T) {
	c := newCpuAt(0x8126)
	c.regs[1] = 1

	c.Step()

	assert.Equal(t, c.regs[0xF], byte(1&0x0001))
	assert.Equal(t, c.regs[1], byte(1/2))
}

// 8xy7 - SUBN Vx, Vy
func Test8xy7Greater(t *testing.T) {
	c := newCpuAt(0x8127)
	c.regs[1] = 1
	c.regs[2] = 2

	assert.Equal(t, c.regs[0xF], byte(0))

	c.Step()

	assert.Equal(t, c.regs[1], byte(1))
	assert.Equal(t, c.regs[0xF], byte(1))
}

// 8xy7 - SUBN Vx, Vy
func Test8xy7NotGreater(t *testing.T) {
	c := newCpuAt(0x8127)
	c.regs[1] = 2
	c.regs[2] = 1

	assert.Equal(t, c.regs[0xF], byte(0))

	c.Step()

	assert.Equal(t, c.regs[1], byte(0xFF))
	assert.Equal(t, c.regs[0xF], byte(0))
}

// 8xyE - SHL Vx {, Vy}
func Test8xyE(t *testing.T) {
	c := newCpuAt(0x812E)
	c.regs[1] = 1

	c.Step()

	assert.Equal(t, c.regs[0xF], byte(1&0x0001))
	assert.Equal(t, c.regs[1], byte(1*2))
}
<commit_msg>Added Test 9xy0<commit_after>// Copyright 2015 Claudemiro Alves Feitosa Neto. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package gochip8

import (
	"testing"

	"github.com/bmizerany/assert"
)

// dumbSound - Only for testing purpuses
type dumbSound struct {
	BeepCalled bool
}

func (s *dumbSound) Beep() {
	(*s).BeepCalled = true
}

// newCpuAt creates a new cpu and write the ins to the pc memory location
// Only for testing purpuse
func newCpuAt(ins uint16) cpu {
	s := &dumbSound{}
	c := newCpu(s)
	c.memory.WriteWord(uint16(c.pc), ins)

	return c
}

func TestTimers(t *testing.T) {
	s := &dumbSound{}
	c := newCpu(s)

	// With Beep
	c.memory.WriteWord(uint16(c.pc), 0x0E0)

	c.dt = 1
	c.st = 1

	assert.Equal(t, s.BeepCalled, false)

	c.Step()

	assert.Equal(t, c.dt, byte(0))
	assert.Equal(t, c.st, byte(0))
	assert.Equal(t, s.BeepCalled, true)

	// No Beep
	c.memory.WriteWord(uint16(c.pc), 0x0E0)
	s.BeepCalled = false

	c.st = 2
	c.Step()

	assert.Equal(t, s.BeepCalled, false)
	assert.Equal(t, c.st, byte(1))
}

// 00E0 - CLS
func Test00E0(t *testing.T) {

	c := newCpuAt(0x00E0)
	c.gfx.SetPixel(0, 0)
	c.Step()

	for i := 0; i < 64; i++ {
		for j := 0; j < 32; j++ {
			assert.Equal(t, byte(COLOR_BLACK), byte(c.gfx.GetPixel(i, j)))
		}
	}
}

// 00EE - RET
func Test00EE(t *testing.T) {
	c := newCpuAt(0x00EE)

	c.stack.Push(pc(1))
	c.Step()

	assert.Equal(t, pc(1), c.pc)
}

// 1nnn - JP addr
func Test1000(t *testing.T) {
	c := newCpuAt(0x1FFF)
	c.Step()

	assert.Equal(t, pc(0x0FFF), c.pc)
}

// 2nnn - CALL addr
func Test2000(t *testing.T) {
	c := newCpuAt(0x2FFF)
	oldPC := c.pc + 2 // The increment happen before the Step

	c.Step()

	assert.Equal(t, oldPC, c.stack.Pop())
	assert.Equal(t, pc(0x0FFF), c.pc)
}

// 3xkk - SE Vx, byte
func Test3000Equal(t *testing.T) {
	c := newCpuAt(0x31FF)
	c.regs[1] = 0xFF

	oldPC := c.pc + 4
	c.Step()

	assert.Equal(t, oldPC, c.pc)
}

// 3xkk - SE Vx, byte
func Test3000NotEqual(t *testing.T) {
	c := newCpuAt(0x31FF)
	c.regs[1] = 0xAA

	oldPC := c.pc + 2
	c.Step()

	assert.Equal(t, oldPC, c.pc)
}

// 4xkk - SNE Vx, byte
func Test4000Equal(t *testing.T) {
	c := newCpuAt(0x41FF)
	c.regs[1] = 0xFF

	oldPC := c.pc + 2
	c.Step()

	assert.Equal(t, oldPC, c.pc)
}

// 4xkk - SNE Vx, byte
func Test4000NotEqual(t *testing.T) {
	c := newCpuAt(0x41FF)
	c.regs[1] = 0xAA

	oldPC := c.pc + 4
	c.Step()

	assert.Equal(t, oldPC, c.pc)
}

// 5xy0 - SE Vx, Vy
func Test5000Equal(t *testing.T) {
	c := newCpuAt(0x512F)
	c.regs[1] = 0xFF
	c.regs[2] = 0xFF

	oldPC := c.pc + 4
	c.Step()

	assert.Equal(t, oldPC, c.pc)
}

// 5xy0 - SE Vx, Vy
func Test5000NotEqual(t *testing.T) {
	c := newCpuAt(0x512F)
	c.regs[1] = 0xFF
	c.regs[2] = 0xAA

	oldPC := c.pc + 2
	c.Step()

	assert.Equal(t, oldPC, c.pc)
}

// 6xkk - LD Vx, byte
func Test6000(t *testing.T) {
	c := newCpuAt(0x61FF)
	c.Step()
	assert.Equal(t, c.regs[1], byte(0xFF))
}

// 7xkk - ADD Vx, byte
func Test7000(t *testing.T) {
	c := newCpuAt(0x7101)
	c.regs[1] = 1
	c.Step()
	assert.Equal(t, c.regs[1], byte(2))
}

// 8xy0 - LD Vx, Vy
func Test8xy0(t *testing.T) {
	c := newCpuAt(0x8120)
	c.regs[1] = 1
	c.regs[2] = 0
	assert.Equal(t, c.regs[1], byte(1))
	assert.Equal(t, c.regs[2], byte(0))
	c.Step()
	assert.Equal(t, c.regs[1], byte(0))
	assert.Equal(t, c.regs[2], byte(0))
}

// 8xy1 - OR Vx, Vy
func Test8xy1(t *testing.T) {
	c := newCpuAt(0x8121)
	c.regs[1] = 1
	c.regs[2] = 2
	assert.Equal(t, c.regs[1], byte(1))
	assert.Equal(t, c.regs[2], byte(2))
	c.Step()
	assert.Equal(t, c.regs[1], byte(1|2))
	assert.Equal(t, c.regs[2], byte(2))
}

// 8xy2 - OR Vx, Vy
func Test8xy2(t *testing.T) {
	c := newCpuAt(0x8122)
	c.regs[1] = 1
	c.regs[2] = 2
	assert.Equal(t, c.regs[1], byte(1))
	assert.Equal(t, c.regs[2], byte(2))
	c.Step()
	assert.Equal(t, c.regs[1], byte(1&2))
	assert.Equal(t, c.regs[2], byte(2))
}

// 8xy3 - OR Vx, Vy
func Test8xy3(t *testing.T) {
	c := newCpuAt(0x8123)
	c.regs[1] = 1
	c.regs[2] = 2
	assert.Equal(t, c.regs[1], byte(1))
	assert.Equal(t, c.regs[2], byte(2))
	c.Step()
	assert.Equal(t, c.regs[1], byte(1^2))
	assert.Equal(t, c.regs[2], byte(2))
}

// 8xy4 - ADD Vx, Vy
func Test8xy4Overflow(t *testing.T) {
	c := newCpuAt(0x8124)
	c.regs[1] = 0xFF
	c.regs[2] = 1

	assert.Equal(t, c.regs[0xF], byte(0))

	c.Step()

	assert.Equal(t, c.regs[1], byte(0))
	assert.Equal(t, c.regs[0xF], byte(1))
}

// 8xy4 - ADD Vx, Vy
func Test8xy4ONotverflow(t *testing.T) {
	c := newCpuAt(0x8124)
	c.regs[1] = 0xF0
	c.regs[2] = 1

	assert.Equal(t, c.regs[0xF], byte(0))

	c.Step()

	assert.Equal(t, c.regs[1], byte(0xF0+1))
	assert.Equal(t, c.regs[0xF], byte(0))
}

// 8xy5 - SUB Vx, Vy
func Test8xy5Greater(t *testing.T) {
	c := newCpuAt(0x8125)
	c.regs[1] = 2
	c.regs[2] = 1

	assert.Equal(t, c.regs[0xF], byte(0))

	c.Step()

	assert.Equal(t, c.regs[1], byte(1))
	assert.Equal(t, c.regs[0xF], byte(1))
}

// 8xy5 - SUB Vx, Vy
func Test8xy5NotGreater(t *testing.T) {
	c := newCpuAt(0x8125)
	c.regs[1] = 1
	c.regs[2] = 2

	assert.Equal(t, c.regs[0xF], byte(0))

	c.Step()

	assert.Equal(t, c.regs[1], byte(0xFF))
	assert.Equal(t, c.regs[0xF], byte(0))
}

// 8xy6 - SHR Vx {, Vy}
func Test8xy6(t *testing.T) {
	c := newCpuAt(0x8126)
	c.regs[1] = 1

	c.Step()

	assert.Equal(t, c.regs[0xF], byte(1&0x0001))
	assert.Equal(t, c.regs[1], byte(1/2))
}

// 8xy7 - SUBN Vx, Vy
func Test8xy7Greater(t *testing.T) {
	c := newCpuAt(0x8127)
	c.regs[1] = 1
	c.regs[2] = 2

	assert.Equal(t, c.regs[0xF], byte(0))

	c.Step()

	assert.Equal(t, c.regs[1], byte(1))
	assert.Equal(t, c.regs[0xF], byte(1))
}

// 8xy7 - SUBN Vx, Vy
func Test8xy7NotGreater(t *testing.T) {
	c := newCpuAt(0x8127)
	c.regs[1] = 2
	c.regs[2] = 1

	assert.Equal(t, c.regs[0xF], byte(0))

	c.Step()

	assert.Equal(t, c.regs[1], byte(0xFF))
	assert.Equal(t, c.regs[0xF], byte(0))
}

// 8xyE - SHL Vx {, Vy}
func Test8xyE(t *testing.T) {
	c := newCpuAt(0x812E)
	c.regs[1] = 1

	c.Step()

	assert.Equal(t, c.regs[0xF], byte(1&0x0001))
	assert.Equal(t, c.regs[1], byte(1*2))
}

// 9xy0 - SNE Vx, Vy
func Test9xy0NotEqual(t *testing.T) {
	c := newCpuAt(0x9120)
	c.regs[1] = 1
	c.regs[2] = 2

	oldPC := c.pc

	c.Step()

	assert.Equal(t, c.pc, oldPC+4)
}

// 9xy0 - SNE Vx, Vy
func Test9xy0Equal(t *testing.T) {
	c := newCpuAt(0x9120)
	c.regs[1] = 1
	c.regs[2] = 1

	oldPC := c.pc

	c.Step()

	assert.Equal(t, c.pc, oldPC+2)
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/go-sql-driver/mysql"
	"database/sql/driver"
	"fmt"
	"time"
	"sync"
	"runtime"
	"flag"
	"math/big"
	"math"
	"io"
)

const (
	STAGE_CONN  byte = 0
	STAGE_QUERY byte = 1
	STAGE_READ  byte = 2
	STAGE_TOTAL byte = 3
	//
	STAGE_MAX   byte = 4
)

type TestResult struct {
	stage                  byte
	ok                     bool
	err                    error
	time                   time.Duration
}

type SummeryResult struct {
	count             int64
	failCount         int64
	totalTime         time.Duration
	totalSquareTime   big.Int
	maxTime           time.Duration
	minTime           time.Duration
	avgTime           time.Duration
	stddevTime        time.Duration
	lastError         error
}

func getColumnCount(dsn, query string) (int, error) {
	db, err := (mysql.MySQLDriver{}).Open(dsn)
	if err != nil {
		return 0, err
	}
	defer db.Close()

	rows, err := db.(driver.Queryer).Query(query, []driver.Value{})
	if err != nil {
		return 0, err
	}
	defer rows.Close()
	return len(rows.Columns()), nil
}

func testOnce(dsn string, queries []string, result *[STAGE_MAX]TestResult) {
	for i := byte(0); i < STAGE_MAX; i++ {
		(*result)[i].ok = false
	}
	beforeConn := time.Now()
	db, err := (mysql.MySQLDriver{}).Open(dsn)
	if err != nil {
		(*result)[STAGE_CONN].err = err
		return
	}
	(*result)[STAGE_CONN].ok = true
	afterConn := time.Now()
	(*result)[STAGE_CONN].time = afterConn.Sub(beforeConn)
	defer db.Close()
	afterRead := afterConn
	(*result)[STAGE_QUERY].time = 0
	(*result)[STAGE_READ].time = 0
	for _, query := range queries {
		beforeQuery := time.Now()
		rows, err := db.(driver.Queryer).Query(query, []driver.Value{})
		if err != nil {
			(*result)[STAGE_QUERY].err = err
			(*result)[STAGE_QUERY].ok = false
			return
		}

		afterQuery := time.Now()
		(*result)[STAGE_QUERY].ok = true
		(*result)[STAGE_QUERY].time += afterQuery.Sub(beforeQuery)

		err = rows.Close() // Close() will read all rows
		if err != nil && err != io.EOF {
			(*result)[STAGE_READ].err = err
			(*result)[STAGE_READ].ok = false
			return
		}
		afterRead = time.Now()
		(*result)[STAGE_READ].ok = true
		(*result)[STAGE_READ].time += afterRead.Sub(afterQuery)
	}
	(*result)[STAGE_TOTAL].ok = true
	(*result)[STAGE_TOTAL].time = afterRead.Sub(beforeConn)
}

func testRoutine(dsn string, queries []string, n int, outChan chan<- [STAGE_MAX]TestResult) {
	var result [STAGE_MAX]TestResult
	result[STAGE_CONN].stage = STAGE_CONN
	result[STAGE_QUERY].stage = STAGE_QUERY
	result[STAGE_READ].stage = STAGE_READ
	result[STAGE_TOTAL].stage = STAGE_TOTAL

	for i := 0; i < n; i++ {
		testOnce(dsn, queries, &result)
		outChan <-result
	}
}

func collectInto(result *[STAGE_MAX]TestResult, ret *[STAGE_MAX]SummeryResult) {
	var bigA  big.Int
	for i := byte(0); i < STAGE_MAX; i++ {
		ret[i].count++
		if result[i].ok {
			if result[i].time > ret[i].maxTime {
				ret[i].maxTime = result[i].time
			}
			if result[i].time < ret[i].minTime {
				ret[i].minTime = result[i].time
			}
			ret[i].totalTime+= result[i].time
			bigA.SetInt64((int64)(result[i].time)).Mul(&bigA, &bigA)
			ret[i].totalSquareTime.Add(&ret[i].totalSquareTime, &bigA)
		} else {
			ret[i].failCount++
			if result[i].err != nil {
				ret[i].lastError = result[i].err
			}
		}
	}
}

func summeryRoutine(inChan <-chan [STAGE_MAX]TestResult, outChan chan<- [STAGE_MAX]SummeryResult, summeryIntervalSecond int) {
	var ret   [STAGE_MAX]SummeryResult
	var ticker *time.Ticker
	for i := byte(0); i < STAGE_MAX; i++ {
		ret[i].minTime = math.MaxInt64
	}

	if summeryIntervalSecond > 0 {
		summeryInterval := time.Second * time.Duration(summeryIntervalSecond)
		ticker = time.NewTicker(summeryInterval)
		for {
			select {
			case result, ok := <-inChan:
				if !ok {
					break;
				}
				collectInto(&result, &ret)
			case <-ticker.C:
				for i := byte(0); i < STAGE_MAX; i++ {
					ret[i].Summery()
				}
				outChan<-ret
				ret = [STAGE_MAX]SummeryResult{}
				for i := byte(0); i < STAGE_MAX; i++ {
					ret[i].minTime = math.MaxInt64
				}
			}
		}
	} else {
		for result := range inChan {
			collectInto(&result, &ret)
		}
	}
	for i := byte(0); i < STAGE_MAX; i++ {
		ret[i].Summery()
	}
	outChan<-ret
	close(outChan)
	return
}

func (self *SummeryResult) Summery() {
	var bigA, big2 big.Int
	var bigR1, bigR2, big1N, big1N1 big.Rat
	big2.SetInt64(2)
	//  ∑(i-miu)2 = ∑(i2)-(∑i)2/n
	n := self.count - self.failCount
	if n > 1 {
		self.avgTime = (time.Duration)((int64)(self.totalTime) / n)

		big1N.SetInt64(n).Inv(&big1N) // 1/n
		big1N1.SetInt64(n-1).Inv(&big1N1) // 1/(n-1)
		bigA.SetInt64((int64)(self.totalTime)).Mul(&bigA, &bigA) // (∑i)2
		bigR1.SetInt(&bigA).Mul(&bigR1, &big1N) // (∑i)2/n
		bigR2.SetInt(&self.totalSquareTime).Sub(&bigR2, &bigR1)
		s2, _ := bigR2.Mul(&bigR2, &big1N1).Float64()
		self.stddevTime = (time.Duration)((int64)(math.Sqrt(s2)))
	}
	if self.minTime == math.MaxInt64 {
		self.minTime = 0
	}
}

func msStr(t time.Duration) string {
	return fmt.Sprintf("%0.3f ms", float64(int64(t) / 1000) / 1000.0)
}

type NullLogger struct{}
func (*NullLogger) Print(v ...interface{}) {
}

type arrayFlags []string
func (self *arrayFlags) String() string {
	return fmt.Sprintf("%v", *self)
}
func (self *arrayFlags) Set(value string) error {
	*self = append(*self, value)
	return nil
}

// mysqlburst -c 2000 -r 30 -d 'mha:M616VoUJBnYFi0L02Y24@tcp(10.200.180.54:3342)/x?timeout=5s&readTimeout=3s&writeTimeout=3s'
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	//go func() {
	//      http.ListenAndServe("localhost:6060", nil)
	//}()
	//driver.ErrBadConn = errors.New(driver.ErrBadConn)
	procs := 0
	rounds := 0
	dsn := ""
	var queries arrayFlags
	summeryIntervalSec := 0
	flag.IntVar(&procs, "c", 1000, "concurrency")
	flag.IntVar(&rounds, "r", 100, "rounds")
	flag.StringVar(&dsn, "d", "mysql:@tcp(127.0.0.1:3306)/mysql?timeout=5s&readTimeout=5s&writeTimeout=5s", "dsn")
	flag.Var(&queries, "q", "queries")
	flag.IntVar(&summeryIntervalSec, "i", 0, "summery interval (sec)")
	flag.Parse()

	mysql.SetLogger(&NullLogger{})

	wg := sync.WaitGroup{}
	wg.Add(procs)
	resultChan := make(chan [STAGE_MAX]TestResult, 5000)
	summeryChan := make(chan [STAGE_MAX]SummeryResult, 10)
	go func() {
		for i := 0; i < procs; i++ {
			go func() {
				testRoutine(dsn, queries, rounds, resultChan)
				wg.Done()
			}()
		}
		wg.Wait()
		close(resultChan)
	}()
	go summeryRoutine(resultChan, summeryChan, summeryIntervalSec)

	testBegin := time.Now()
	titles := [STAGE_MAX]string{
		"connect", "query", "read", "total",
	}
	for summery := range summeryChan {
		testEnd := time.Now()
		duration:= testEnd.Sub(testBegin)
		testBegin = testEnd

		fmt.Printf("time: %s\n", duration.String())
		for i, title := range titles {
			errStr := "-"
			lastErr := summery[i].lastError
			if lastErr != nil {
				errStr = lastErr.Error()
			}
			fmt.Printf("%-8s count: %-10d failed: %-8d avg: %-14s min: %-14s max: %-14s stddev: %-14s err: %s\n",
				title, summery[i].count, summery[i].failCount,
				msStr(summery[i].avgTime), msStr(summery[i].minTime), msStr(summery[i].maxTime), msStr(summery[i].stddevTime),
				errStr)
		}
		fmt.Println()
	}
}

<commit_msg>summery duration output<commit_after>package main

import (
	"github.com/go-sql-driver/mysql"
	"database/sql/driver"
	"fmt"
	"time"
	"sync"
	"runtime"
	"flag"
	"math/big"
	"math"
	"io"
)

const (
	STAGE_CONN  byte = 0
	STAGE_QUERY byte = 1
	STAGE_READ  byte = 2
	STAGE_TOTAL byte = 3
	//
	STAGE_MAX   byte = 4
)

type TestResult struct {
	stage                  byte
	ok                     bool
	err                    error
	time                   time.Duration
}

type SummeryResult struct {
	count             int64
	failCount         int64
	totalTime         time.Duration
	totalSquareTime   big.Int
	maxTime           time.Duration
	minTime           time.Duration
	avgTime           time.Duration
	stddevTime        time.Duration
	lastError         error
}

func getColumnCount(dsn, query string) (int, error) {
	db, err := (mysql.MySQLDriver{}).Open(dsn)
	if err != nil {
		return 0, err
	}
	defer db.Close()

	rows, err := db.(driver.Queryer).Query(query, []driver.Value{})
	if err != nil {
		return 0, err
	}
	defer rows.Close()
	return len(rows.Columns()), nil
}

func testOnce(dsn string, queries []string, result *[STAGE_MAX]TestResult) {
	for i := byte(0); i < STAGE_MAX; i++ {
		(*result)[i].ok = false
	}
	beforeConn := time.Now()
	db, err := (mysql.MySQLDriver{}).Open(dsn)
	if err != nil {
		(*result)[STAGE_CONN].err = err
		return
	}
	(*result)[STAGE_CONN].ok = true
	afterConn := time.Now()
	(*result)[STAGE_CONN].time = afterConn.Sub(beforeConn)
	defer db.Close()
	afterRead := afterConn
	(*result)[STAGE_QUERY].time = 0
	(*result)[STAGE_READ].time = 0
	for _, query := range queries {
		beforeQuery := time.Now()
		rows, err := db.(driver.Queryer).Query(query, []driver.Value{})
		if err != nil {
			(*result)[STAGE_QUERY].err = err
			(*result)[STAGE_QUERY].ok = false
			return
		}

		afterQuery := time.Now()
		(*result)[STAGE_QUERY].ok = true
		(*result)[STAGE_QUERY].time += afterQuery.Sub(beforeQuery)

		err = rows.Close() // Close() will read all rows
		if err != nil && err != io.EOF {
			(*result)[STAGE_READ].err = err
			(*result)[STAGE_READ].ok = false
			return
		}
		afterRead = time.Now()
		(*result)[STAGE_READ].ok = true
		(*result)[STAGE_READ].time += afterRead.Sub(afterQuery)
	}
	(*result)[STAGE_TOTAL].ok = true
	(*result)[STAGE_TOTAL].time = afterRead.Sub(beforeConn)
}

func testRoutine(dsn string, queries []string, n int, outChan chan<- [STAGE_MAX]TestResult) {
	var result [STAGE_MAX]TestResult
	result[STAGE_CONN].stage = STAGE_CONN
	result[STAGE_QUERY].stage = STAGE_QUERY
	result[STAGE_READ].stage = STAGE_READ
	result[STAGE_TOTAL].stage = STAGE_TOTAL

	for i := 0; i < n; i++ {
		testOnce(dsn, queries, &result)
		outChan <-result
	}
}

func collectInto(result *[STAGE_MAX]TestResult, ret *[STAGE_MAX]SummeryResult) {
	var bigA  big.Int
	for i := byte(0); i < STAGE_MAX; i++ {
		ret[i].count++
		if result[i].ok {
			if result[i].time > ret[i].maxTime {
				ret[i].maxTime = result[i].time
			}
			if result[i].time < ret[i].minTime {
				ret[i].minTime = result[i].time
			}
			ret[i].totalTime+= result[i].time
			bigA.SetInt64((int64)(result[i].time)).Mul(&bigA, &bigA)
			ret[i].totalSquareTime.Add(&ret[i].totalSquareTime, &bigA)
		} else {
			ret[i].failCount++
			if result[i].err != nil {
				ret[i].lastError = result[i].err
			}
		}
	}
}

func summeryRoutine(inChan <-chan [STAGE_MAX]TestResult, outChan chan<- [STAGE_MAX]SummeryResult, summeryIntervalSecond int) {
	var ret   [STAGE_MAX]SummeryResult
	var ticker *time.Ticker
	for i := byte(0); i < STAGE_MAX; i++ {
		ret[i].minTime = math.MaxInt64
	}

	if summeryIntervalSecond > 0 {
		summeryInterval := time.Second * time.Duration(summeryIntervalSecond)
		ticker = time.NewTicker(summeryInterval)
		for {
			select {
			case result, ok := <-inChan:
				if !ok {
					break;
				}
				collectInto(&result, &ret)
			case <-ticker.C:
				for i := byte(0); i < STAGE_MAX; i++ {
					ret[i].Summery()
				}
				outChan<-ret
				ret = [STAGE_MAX]SummeryResult{}
				for i := byte(0); i < STAGE_MAX; i++ {
					ret[i].minTime = math.MaxInt64
				}
			}
		}
	} else {
		for result := range inChan {
			collectInto(&result, &ret)
		}
	}
	for i := byte(0); i < STAGE_MAX; i++ {
		ret[i].Summery()
	}
	outChan<-ret
	close(outChan)
	return
}

func (self *SummeryResult) Summery() {
	var bigA, big2 big.Int
	var bigR1, bigR2, big1N, big1N1 big.Rat
	big2.SetInt64(2)
	//  ∑(i-miu)2 = ∑(i2)-(∑i)2/n
	n := self.count - self.failCount
	if n > 1 {
		self.avgTime = (time.Duration)((int64)(self.totalTime) / n)

		big1N.SetInt64(n).Inv(&big1N) // 1/n
		big1N1.SetInt64(n-1).Inv(&big1N1) // 1/(n-1)
		bigA.SetInt64((int64)(self.totalTime)).Mul(&bigA, &bigA) // (∑i)2
		bigR1.SetInt(&bigA).Mul(&bigR1, &big1N) // (∑i)2/n
		bigR2.SetInt(&self.totalSquareTime).Sub(&bigR2, &bigR1)
		s2, _ := bigR2.Mul(&bigR2, &big1N1).Float64()
		self.stddevTime = (time.Duration)((int64)(math.Sqrt(s2)))
	}
	if self.minTime == math.MaxInt64 {
		self.minTime = 0
	}
}

func msStr(t time.Duration) string {
	return fmt.Sprintf("%0.3f ms", float64(int64(t) / 1000) / 1000.0)
}

type NullLogger struct{}
func (*NullLogger) Print(v ...interface{}) {
}

type arrayFlags []string
func (self *arrayFlags) String() string {
	return fmt.Sprintf("%v", *self)
}
func (self *arrayFlags) Set(value string) error {
	*self = append(*self, value)
	return nil
}

// mysqlburst -c 2000 -r 30 -d 'mha:M616VoUJBnYFi0L02Y24@tcp(10.200.180.54:3342)/x?timeout=5s&readTimeout=3s&writeTimeout=3s'
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	//go func() {
	//      http.ListenAndServe("localhost:6060", nil)
	//}()
	//driver.ErrBadConn = errors.New(driver.ErrBadConn)
	procs := 0
	rounds := 0
	dsn := ""
	var queries arrayFlags
	summeryIntervalSec := 0
	flag.IntVar(&procs, "c", 1000, "concurrency")
	flag.IntVar(&rounds, "r", 100, "rounds")
	flag.StringVar(&dsn, "d", "mysql:@tcp(127.0.0.1:3306)/mysql?timeout=5s&readTimeout=5s&writeTimeout=5s", "dsn")
	flag.Var(&queries, "q", "queries")
	flag.IntVar(&summeryIntervalSec, "i", 0, "summery interval (sec)")
	flag.Parse()

	mysql.SetLogger(&NullLogger{})

	wg := sync.WaitGroup{}
	wg.Add(procs)
	resultChan := make(chan [STAGE_MAX]TestResult, 5000)
	summeryChan := make(chan [STAGE_MAX]SummeryResult, 10)
	go func() {
		for i := 0; i < procs; i++ {
			go func() {
				testRoutine(dsn, queries, rounds, resultChan)
				wg.Done()
			}()
		}
		wg.Wait()
		close(resultChan)
	}()
	go summeryRoutine(resultChan, summeryChan, summeryIntervalSec)

	testBegin := time.Now()
	titles := [STAGE_MAX]string{
		"connect", "query", "read", "total",
	}
	for summery := range summeryChan {
		testEnd := time.Now()
		duration:= testEnd.Sub(testBegin)
		testBegin = testEnd

		fmt.Printf("time: %s\n", msStr(duration))
		for i, title := range titles {
			errStr := "-"
			lastErr := summery[i].lastError
			if lastErr != nil {
				errStr = lastErr.Error()
			}
			fmt.Printf("%-8s count: %-10d failed: %-8d avg: %-14s min: %-14s max: %-14s stddev: %-14s err: %s\n",
				title, summery[i].count, summery[i].failCount,
				msStr(summery[i].avgTime), msStr(summery[i].minTime), msStr(summery[i].maxTime), msStr(summery[i].stddevTime),
				errStr)
		}
		fmt.Println()
	}
}

<|endoftext|>


<commit_before>package warserver

import (
    "container/list"
    "encoding/json"
    "github.com/gorilla/websocket"
    "strings"
    "warserver/logger"
)

const (
    NUM_PLAYERS = 2
)

type newGame struct {
    NumPlayers int
    cconn *clientConnection
}

type game_hub struct {
    gameRequests chan *newGame
    uncommittedGames *list.List
    committedGames *list.List
    wsRegister chan *websocket.Conn
    localHandlers map[string]func(message string, cconn *clientConnection)
}

func (gh *game_hub) handleWebsocket(message []byte, cconn *clientConnection) {
    cmds := strings.SplitN(string(message), ":", 2)
    if len(cmds) == 2 {
        if fun, ok := gh.localHandlers[cmds[0]]; ok {
            fun(cmds[1], cconn)
        } else {
            logger.Warnf("Unrecognized command: %s", cmds[0])
        }
    } else {
        logger.Errorf("Malformed command: %s", cmds)
    }
}

func (gh *game_hub) handleNewGame(message string, cconn *clientConnection) {
    ng := newGame{}
    err := json.Unmarshal([]byte(message), &ng)
    if err != nil {
        logger.Warnf("Error unmarshalling json: %s", err)
        return
    }
    ng.cconn = cconn
    logger.Infof("Got new game %s", ng)
    gh.gameRequests <- &ng
}

func (gh *game_hub) handleConnections() {
    for conn := range gh.wsRegister {
        cconn := clientConnection{ws: conn, currentHandler: gh, handlers: make(chan websocketHandler)}
        go cconn.wsReadPump()
    }
}

func (gh *game_hub) makeGame(numPlayers int) *game {
    proxy := proxy{proxyConns: make([]*clientConnection, numPlayers)}
    game := game{numPlayers: numPlayers, currentPlayers: 0,
                 proxy: proxy}
    gh.uncommittedGames.PushBack(&game)

    return &game
}

func (gh *game_hub) processNewGameRequests() {
    for ng := range gh.gameRequests {
        // look for an existing game to satisfy the new request
        gm := gh.findGame(ng)
        // create a game if one can't be found
        if gm == nil {
            logger.Info("Couldn't find an available game. Creating a new one")
            gm = gh.makeGame(ng.NumPlayers)
        } else {
            logger.Info("Found existing game. Slotting in")
        }
        gm.proxy.slotClientConnection(gm.currentPlayers, ng.cconn)
        gm.currentPlayers += 1
    }
}

func (gh *game_hub) findGame(ng *newGame) *game {
    for e := gh.uncommittedGames.Front(); e != nil; e = e.Next() {
        currGame := e.Value.(*game)
        if ng.NumPlayers == currGame.numPlayers {
            return currGame
        }
    }
    return nil
}

var gamehub = game_hub {
    gameRequests: make(chan *newGame),
    uncommittedGames: list.New(),
    committedGames: list.New(),
    wsRegister: make(chan *websocket.Conn),
    localHandlers: make(map [string]func(message string, cconn *clientConnection)),
}

func setupGamehub() {
    gamehub.localHandlers["newGame"] = gamehub.handleNewGame

    go gamehub.processNewGameRequests()
}
<commit_msg>Change uncommitedGames to a map for easier everything<commit_after>package warserver

import (
    "container/list"
    "encoding/json"
    "github.com/gorilla/websocket"
    "strings"
    "warserver/logger"
)

const (
    NUM_PLAYERS = 2
)

type newGame struct {
    NumPlayers int
    cconn *clientConnection
}

type game_hub struct {
    gameRequests chan *newGame
    uncommittedGames map[int]*game
    committedGames *list.List
    wsRegister chan *websocket.Conn
    localHandlers map[string]func(message string, cconn *clientConnection)
}

func (gh *game_hub) handleWebsocket(message []byte, cconn *clientConnection) {
    cmds := strings.SplitN(string(message), ":", 2)
    if len(cmds) == 2 {
        if fun, ok := gh.localHandlers[cmds[0]]; ok {
            fun(cmds[1], cconn)
        } else {
            logger.Warnf("Unrecognized command: %s", cmds[0])
        }
    } else {
        logger.Errorf("Malformed command: %s", cmds)
    }
}

func (gh *game_hub) handleNewGame(message string, cconn *clientConnection) {
    ng := newGame{}
    err := json.Unmarshal([]byte(message), &ng)
    if err != nil {
        logger.Warnf("Error unmarshalling json: %s", err)
        return
    }
    ng.cconn = cconn
    logger.Infof("Got new game %s", ng)
    gh.gameRequests <- &ng
}

func (gh *game_hub) handleConnections() {
    for conn := range gh.wsRegister {
        cconn := clientConnection{ws: conn, currentHandler: gh, handlers: make(chan websocketHandler)}
        go cconn.wsReadPump()
    }
}

func (gh *game_hub) makeGame(numPlayers int) *game {
    proxy := proxy{proxyConns: make([]*clientConnection, numPlayers)}
    game := game{numPlayers: numPlayers, currentPlayers: 0,
                 proxy: proxy}
    gh.uncommittedGames.PushBack(&game)

    return &game
}

func (gh *game_hub) processNewGameRequests() {
    for ng := range gh.gameRequests {
        // look for an existing game to satisfy the new request
        gm := gh.findGame(ng)
        // create a game if one can't be found
        if gm == nil {
            logger.Info("Couldn't find an available game. Creating a new one")
            gm = gh.makeGame(ng.NumPlayers)
        } else {
            logger.Info("Found existing game. Slotting in")
        }
        gm.proxy.slotClientConnection(gm.currentPlayers, ng.cconn)
        gm.currentPlayers += 1
        if gm.currentPlayers == gm.numPlayers {
            gh.commitGame(gm)
        }
    }
}

func (gh *game_hub) findGame(ng *newGame) *game {
    game := gh.uncommittedGames[ng.NumPlayers]
    return game
}

var gamehub = game_hub {
    gameRequests: make(chan *newGame),
    uncommittedGames: make(map [int]*game),
    committedGames: list.New(),
    wsRegister: make(chan *websocket.Conn),
    localHandlers: make(map [string]func(message string, cconn *clientConnection)),
}

func setupGamehub() {
    gamehub.localHandlers["newGame"] = gamehub.handleNewGame

    go gamehub.processNewGameRequests()
}
<|endoftext|>


<commit_before>package amazonec2

import (
	"errors"

	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/service/ec2"

	"github.com/stretchr/testify/mock"
)

type fakeEC2 struct {
	*ec2.EC2
}

type errorProvider struct{}

func (p *errorProvider) Retrieve() (credentials.Value, error) {
	return credentials.Value{}, errors.New("bad credentials")
}

func (p *errorProvider) IsExpired() bool {
	return true
}

type okProvider struct {
	accessKeyID     string
	secretAccessKey string
	sessionToken    string
}

func (p *okProvider) Retrieve() (credentials.Value, error) {
	return credentials.Value{
		AccessKeyID:     p.accessKeyID,
		SecretAccessKey: p.secretAccessKey,
		SessionToken:    p.sessionToken,
	}, nil
}

func (p *okProvider) IsExpired() bool {
	return true
}

type fallbackCredentials struct{}

func (c *fallbackCredentials) Credentials() *credentials.Credentials {
	return credentials.NewStaticCredentials("fallback_access", "fallback_secret", "fallback_token")
}

func NewValidAwsCredentials() awsCredentials {
	return &fallbackCredentials{}
}

type errorFallbackCredentials struct{}

func (c *errorFallbackCredentials) Credentials() *credentials.Credentials {
	return credentials.NewCredentials(&errorProvider{})
}

func NewErrorAwsCredentials() awsCredentials {
	return &errorFallbackCredentials{}
}

//type testFileCredentialsProvider struct {
//	fileProvider credentials.Provider
//	staticError  bool
//}
//
//func NewTestFileCredentialsProvider(id, secret, token string) *testFileCredentialsProvider {
//	return &testFileCredentialsProvider{
//		fileProvider: &okProvider{id, secret, token},
//		staticError:  false,
//	}
//}
//
//func NewTestFileCredentialsProviderWithStaticError(id, secret, token string) *testFileCredentialsProvider {
//	return &testFileCredentialsProvider{
//		fileProvider: &okProvider{id, secret, token},
//		staticError:  true,
//	}
//}
//
//func (c *testFileCredentialsProvider) NewStaticProvider(id, secret, token string) credentials.Provider {
//	if c.staticError {
//		return &errorProvider{}
//	} else {
//		return &okProvider{id, secret, token}
//	}
//}
//
//func (c *testFileCredentialsProvider) NewSharedProvider(filename, profile string) credentials.Provider {
//	return c.fileProvider
//}

type errorCredentialsProvider struct{}

func (c *errorCredentialsProvider) NewStaticProvider(id, secret, token string) credentials.Provider {
	return &errorProvider{}
}

type fakeEC2WithDescribe struct {
	*fakeEC2
	output *ec2.DescribeAccountAttributesOutput
	err    error
}

func (f *fakeEC2WithDescribe) DescribeAccountAttributes(input *ec2.DescribeAccountAttributesInput) (*ec2.DescribeAccountAttributesOutput, error) {
	return f.output, f.err
}

type fakeEC2WithLogin struct {
	*fakeEC2
}

func (f *fakeEC2WithLogin) DescribeAccountAttributes(input *ec2.DescribeAccountAttributesInput) (*ec2.DescribeAccountAttributesOutput, error) {
	defaultVpc := "default-vpc"
	vpcName := "vpc-9999"

	return &ec2.DescribeAccountAttributesOutput{
		AccountAttributes: []*ec2.AccountAttribute{
			{
				AttributeName: &defaultVpc,
				AttributeValues: []*ec2.AccountAttributeValue{
					{AttributeValue: &vpcName},
				},
			},
		},
	}, nil
}

type fakeEC2SecurityGroupTestRecorder struct {
	*fakeEC2
	mock.Mock
}

func (f *fakeEC2SecurityGroupTestRecorder) DescribeSecurityGroups(input *ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error) {
	result := f.Called(input)
	err := result.Error(1)
	value, ok := result.Get(0).(*ec2.DescribeSecurityGroupsOutput)
	if !ok && err == nil {
		return nil, errors.New("Type assertion to DescribeSecurityGroupsOutput failed")
	}
	return value, err
}

func (f *fakeEC2SecurityGroupTestRecorder) CreateSecurityGroup(input *ec2.CreateSecurityGroupInput) (*ec2.CreateSecurityGroupOutput, error) {
	result := f.Called(input)
	err := result.Error(1)
	value, ok := result.Get(0).(*ec2.CreateSecurityGroupOutput)
	if !ok && err == nil {
		return nil, errors.New("Type assertion to CreateSecurityGroupOutput failed")
	}
	return value, err
}

func (f *fakeEC2SecurityGroupTestRecorder) AuthorizeSecurityGroupIngress(input *ec2.AuthorizeSecurityGroupIngressInput) (*ec2.AuthorizeSecurityGroupIngressOutput, error) {
	result := f.Called(input)
	err := result.Error(1)
	value, ok := result.Get(0).(*ec2.AuthorizeSecurityGroupIngressOutput)
	if !ok && err == nil {
		return nil, errors.New("Type assertion to AuthorizeSecurityGroupIngressInput failed")
	}
	return value, err
}

func NewTestDriver() *Driver {
	driver := NewDriver("machineFoo", "path")
	driver.clientFactory = func() Ec2Client {
		return &fakeEC2{}
	}
	return driver
}

func NewCustomTestDriver(ec2Client Ec2Client) *Driver {
	driver := NewDriver("machineFoo", "path")
	driver.clientFactory = func() Ec2Client {
		return ec2Client
	}
	return driver
}
<commit_msg>Removed test code that had been commented out.<commit_after>package amazonec2

import (
	"errors"

	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/service/ec2"

	"github.com/stretchr/testify/mock"
)

type fakeEC2 struct {
	*ec2.EC2
}

type errorProvider struct{}

func (p *errorProvider) Retrieve() (credentials.Value, error) {
	return credentials.Value{}, errors.New("bad credentials")
}

func (p *errorProvider) IsExpired() bool {
	return true
}

type okProvider struct {
	accessKeyID     string
	secretAccessKey string
	sessionToken    string
}

func (p *okProvider) Retrieve() (credentials.Value, error) {
	return credentials.Value{
		AccessKeyID:     p.accessKeyID,
		SecretAccessKey: p.secretAccessKey,
		SessionToken:    p.sessionToken,
	}, nil
}

func (p *okProvider) IsExpired() bool {
	return true
}

type fallbackCredentials struct{}

func (c *fallbackCredentials) Credentials() *credentials.Credentials {
	return credentials.NewStaticCredentials("fallback_access", "fallback_secret", "fallback_token")
}

func NewValidAwsCredentials() awsCredentials {
	return &fallbackCredentials{}
}

type errorFallbackCredentials struct{}

func (c *errorFallbackCredentials) Credentials() *credentials.Credentials {
	return credentials.NewCredentials(&errorProvider{})
}

func NewErrorAwsCredentials() awsCredentials {
	return &errorFallbackCredentials{}
}

type errorCredentialsProvider struct{}

func (c *errorCredentialsProvider) NewStaticProvider(id, secret, token string) credentials.Provider {
	return &errorProvider{}
}

type fakeEC2WithDescribe struct {
	*fakeEC2
	output *ec2.DescribeAccountAttributesOutput
	err    error
}

func (f *fakeEC2WithDescribe) DescribeAccountAttributes(input *ec2.DescribeAccountAttributesInput) (*ec2.DescribeAccountAttributesOutput, error) {
	return f.output, f.err
}

type fakeEC2WithLogin struct {
	*fakeEC2
}

func (f *fakeEC2WithLogin) DescribeAccountAttributes(input *ec2.DescribeAccountAttributesInput) (*ec2.DescribeAccountAttributesOutput, error) {
	defaultVpc := "default-vpc"
	vpcName := "vpc-9999"

	return &ec2.DescribeAccountAttributesOutput{
		AccountAttributes: []*ec2.AccountAttribute{
			{
				AttributeName: &defaultVpc,
				AttributeValues: []*ec2.AccountAttributeValue{
					{AttributeValue: &vpcName},
				},
			},
		},
	}, nil
}

type fakeEC2SecurityGroupTestRecorder struct {
	*fakeEC2
	mock.Mock
}

func (f *fakeEC2SecurityGroupTestRecorder) DescribeSecurityGroups(input *ec2.DescribeSecurityGroupsInput) (*ec2.DescribeSecurityGroupsOutput, error) {
	result := f.Called(input)
	err := result.Error(1)
	value, ok := result.Get(0).(*ec2.DescribeSecurityGroupsOutput)
	if !ok && err == nil {
		return nil, errors.New("Type assertion to DescribeSecurityGroupsOutput failed")
	}
	return value, err
}

func (f *fakeEC2SecurityGroupTestRecorder) CreateSecurityGroup(input *ec2.CreateSecurityGroupInput) (*ec2.CreateSecurityGroupOutput, error) {
	result := f.Called(input)
	err := result.Error(1)
	value, ok := result.Get(0).(*ec2.CreateSecurityGroupOutput)
	if !ok && err == nil {
		return nil, errors.New("Type assertion to CreateSecurityGroupOutput failed")
	}
	return value, err
}

func (f *fakeEC2SecurityGroupTestRecorder) AuthorizeSecurityGroupIngress(input *ec2.AuthorizeSecurityGroupIngressInput) (*ec2.AuthorizeSecurityGroupIngressOutput, error) {
	result := f.Called(input)
	err := result.Error(1)
	value, ok := result.Get(0).(*ec2.AuthorizeSecurityGroupIngressOutput)
	if !ok && err == nil {
		return nil, errors.New("Type assertion to AuthorizeSecurityGroupIngressInput failed")
	}
	return value, err
}

func NewTestDriver() *Driver {
	driver := NewDriver("machineFoo", "path")
	driver.clientFactory = func() Ec2Client {
		return &fakeEC2{}
	}
	return driver
}

func NewCustomTestDriver(ec2Client Ec2Client) *Driver {
	driver := NewDriver("machineFoo", "path")
	driver.clientFactory = func() Ec2Client {
		return ec2Client
	}
	return driver
}
<|endoftext|>