<commit_before>package fuse

const (

/** Version number of this interface */
FUSE_KERNEL_VERSION = 7

/** Minor version number of this interface */
FUSE_KERNEL_MINOR_VERSION = 13

/** The node ID of the root inode */
FUSE_ROOT_ID = 1

/**
 * Bitmasks for fuse_setattr_in.valid
 */
FATTR_MODE = (1 << 0)
FATTR_UID = (1 << 1)
FATTR_GID = (1 << 2)
FATTR_SIZE = (1 << 3)
FATTR_ATIME = (1 << 4)
FATTR_MTIME = (1 << 5)
FATTR_FH = (1 << 6)
FATTR_ATIME_NOW = (1 << 7)
FATTR_MTIME_NOW = (1 << 8)
FATTR_LOCKOWNER = (1 << 9)

/**
 * Flags returned by the OPEN request
 *
 * FOPEN_DIRECT_IO: bypass page cache for this open file
 * FOPEN_KEEP_CACHE: don't invalidate the data cache on open
 * FOPEN_NONSEEKABLE: the file is not seekable
 */
FOPEN_DIRECT_IO = 	(1 << 0)
FOPEN_KEEP_CACHE = (1 << 1)
FOPEN_NONSEEKABLE = (1 << 2)

/**
 * INIT request/reply flags
 *
 * FUSE_EXPORT_SUPPORT: filesystem handles lookups of "." and ".."
 * FUSE_DONT_MASK: don't apply umask to file mode on create operations
 */
FUSE_ASYNC_READ = 	(1 << 0)
FUSE_POSIX_LOCKS = (1 << 1)
FUSE_FILE_OPS = 	(1 << 2)
FUSE_ATOMIC_O_TRUNC = (1 << 3)
FUSE_EXPORT_SUPPORT = (1 << 4)
FUSE_BIG_WRITES = 	(1 << 5)
FUSE_DONT_MASK = 	(1 << 6)

/**
 * CUSE INIT request/reply flags
 *
 * CUSE_UNRESTRICTED_IOCTL:  use unrestricted ioctl
 */
CUSE_UNRESTRICTED_IOCTL = (1 << 0)

/**
 * Release flags
 */
FUSE_RELEASE_FLUSH = (1 << 0)

/**
 * Getattr flags
 */
FUSE_GETATTR_FH = 	(1 << 0)

/**
 * Lock flags
 */
FUSE_LK_FLOCK = 	(1 << 0)

/**
 * WRITE flags
 *
 * FUSE_WRITE_CACHE: delayed write from page cache, file handle is guessed
 * FUSE_WRITE_LOCKOWNER: lock_owner field is valid
 */
FUSE_WRITE_CACHE = (1 << 0)
FUSE_WRITE_LOCKOWNER = (1 << 1)

/**
 * Read flags
 */
FUSE_READ_LOCKOWNER = (1 << 1)

/**
 * Ioctl flags
 *
 * FUSE_IOCTL_COMPAT: 32bit compat ioctl on 64bit machine
 * FUSE_IOCTL_UNRESTRICTED: not restricted to well-formed ioctls, retry allowed
 * FUSE_IOCTL_RETRY: retry with new iovecs
 *
 * FUSE_IOCTL_MAX_IOV: maximum of in_iovecs + out_iovecs
 */
FUSE_IOCTL_COMPAT = (1 << 0)
FUSE_IOCTL_UNRESTRICTED = (1 << 1)
FUSE_IOCTL_RETRY = (1 << 2)

FUSE_IOCTL_MAX_IOV = 256

/**
 * Poll flags
 *
 * FUSE_POLL_SCHEDULE_NOTIFY: request poll notify
 */
FUSE_POLL_SCHEDULE_NOTIFY = (1 << 0)

FUSE_COMPAT_WRITE_IN_SIZE = 24

/* The read buffer is required to be at least 8k, but may be much larger */
FUSE_MIN_READ_BUFFER = 8192

FUSE_COMPAT_ENTRY_OUT_SIZE = 120

FUSE_COMPAT_ATTR_OUT_SIZE = 96

FUSE_COMPAT_MKNOD_IN_SIZE = 8

FUSE_COMPAT_STATFS_SIZE = 48

CUSE_INIT_INFO_MAX = 4096

)

type fuse_opcode int

const (
	FUSE_LOOKUP	   = 1
	FUSE_FORGET	   = 2  /* no reply */
	FUSE_GETATTR	   = 3
	FUSE_SETATTR	   = 4
	FUSE_READLINK	   = 5
	FUSE_SYMLINK	   = 6
	FUSE_MKNOD	   = 8
	FUSE_MKDIR	   = 9
	FUSE_UNLINK	   = 10
	FUSE_RMDIR	   = 11
	FUSE_RENAME	   = 12
	FUSE_LINK	   = 13
	FUSE_OPEN	   = 14
	FUSE_READ	   = 15
	FUSE_WRITE	   = 16
	FUSE_STATFS	   = 17
	FUSE_RELEASE       = 18
	FUSE_FSYNC         = 20
	FUSE_SETXATTR      = 21
	FUSE_GETXATTR      = 22
	FUSE_LISTXATTR     = 23
	FUSE_REMOVEXATTR   = 24
	FUSE_FLUSH         = 25
	FUSE_INIT          = 26
	FUSE_OPENDIR       = 27
	FUSE_READDIR       = 28
	FUSE_RELEASEDIR    = 29
	FUSE_FSYNCDIR      = 30
	FUSE_GETLK         = 31
	FUSE_SETLK         = 32
	FUSE_SETLKW        = 33
	FUSE_ACCESS        = 34
	FUSE_CREATE        = 35
	FUSE_INTERRUPT     = 36
	FUSE_BMAP          = 37
	FUSE_DESTROY       = 38
	FUSE_IOCTL         = 39
	FUSE_POLL          = 40

	/* CUSE specific operations */
	CUSE_INIT          = 4096
)

type fuse_notyfy_code int

const (
	FUSE_NOTIFY_POLL   = 1
	FUSE_NOTIFY_INVAL_INODE = 2
	FUSE_NOTIFY_INVAL_ENTRY = 3
	FUSE_NOTIFY_CODE_MAX = 4
)

/* Make sure all structures are padded to 64bit boundary, so 32bit
   userspace works under 64bit kernels */

type fuse_attr struct {
	ino uint64
	size uint64
	blocks uint64
	atime uint64
	mtime uint64
	ctime uint64
	atimensec uint32
	mtimensec uint32
	ctimensec uint32
	mode uint32
	nlink uint32
	uid uint32
	gid uint32
	rdev uint32
	blksize uint32
	padding uint32
}

type fuse_kstatfs struct {
	blocks uint64
	bfree uint64
	bavail uint64
	files uint64
	ffree uint64
	bsize uint32
	namelen uint32
	frsize uint32
	padding uint32
	spare [6]uint32
}

type fuse_file_lock struct {
	start uint64
	end uint64
	typ uint32
	pid uint32 /* tgid */
}

type fuse_entry_out struct {
	nodeid uint64		/* Inode ID */
	generation uint64	/* Inode generation: nodeid:gen must
				   be unique for the fs's lifetime */
	entry_valid uint64	/* Cache timeout for the name */
	attr_valid uint64	/* Cache timeout for the attributes */
	entry_valid_nsec uint32
	attr_valid_nsec uint32
	attr fuse_attr
}

type fuse_forget_in struct {
	nlookup uint64
}

type fuse_getattr_in struct {
	getattr_flags uint32
	dummy uint32
	fh uint64
}

type fuse_attr_out struct {
	attr_valid uint64	/* Cache timeout for the attributes */
	attr_valid_nsec uint32
	dummy uint32
	attr fuse_attr
}

type fuse_mknod_in struct {
	mode uint32
	rdev uint32
	umask uint32
	padding uint32
}

type fuse_mkdir_in struct {
	mode uint32
	umask uint32
}

type fuse_rename_in struct {
	newdir uint64
}

type fuse_link_in struct {
	oldnodeid uint64
}

type fuse_setattr_in struct {
	valid uint32
	padding uint32
	fh uint64
	size uint64
	lock_owner uint64
	atime uint64
	mtime uint64
	unused2 uint64
	atimensec uint32
	mtimensec uint32
	unused3 uint32
	mode uint32
	unused4 uint32
	uid uint32
	gid uint32
	unused5 uint32
}

type fuse_open_in struct {
	flags uint32
	unused uint32
}

type fuse_create_in struct {
	flags uint32
	mode uint32
	umask uint32
	padding uint32
}

type fuse_open_out struct {
	fh uint64
	open_flags uint32
	padding uint32
}

type fuse_release_in struct {
	fh uint64
	flags uint32
	release_flags uint32
	lock_owner uint64
}

type fuse_flush_in struct {
	fh uint64
	unused uint32
	padding uint32
	lock_owner uint64
}

type fuse_read_in struct {
	fh uint64
	offset uint64
	size uint32
	read_flags uint32
	lock_owner uint64
	flags uint32
	padding uint32
}

type fuse_write_in struct {
	fh uint64
	offset uint64
	size uint32
	write_flags uint32
	lock_owner uint64
	flags uint32
	padding uint32
}

type fuse_write_out struct {
	size uint32
	padding uint32
}

type fuse_statfs_out struct {
	st fuse_kstatfs
}

type fuse_fsync_in struct {
	fh uint64
	fsync_flags uint32
	padding uint32
}

type fuse_setxattr_in struct {
	size uint32
	flags uint32
}

type fuse_getxattr_in struct {
	size uint32
	padding uint32
}

type fuse_getxattr_out struct {
	size uint32
	padding uint32
}

type fuse_lk_in struct {
	fh uint64
	owner uint64
	lk fuse_file_lock
	lk_flags uint32
	padding uint32
}

type fuse_lk_out struct {
	lk fuse_file_lock
}

type fuse_access_in struct {
	mask uint32
	padding uint32
}

type fuse_init_in struct {
	major uint32
	minor uint32
	max_readahead uint32
	flags uint32
}

type fuse_init_out struct {
	major uint32
	minor uint32
	max_readahead uint32
	flags uint32
	max_background uint16
	congestion_threshold uint16
	max_write uint32
}

type cuse_init_in struct {
	major uint32
	minor uint32
	unused uint32
	flags uint32
}

type cuse_init_out struct {
	major uint32
	minor uint32
	unused uint32
	flags uint32
	max_read uint32
	max_write uint32
	dev_major uint32		/* chardev major */
	dev_minor uint32		/* chardev minor */
	spare [10]uint32
}

type fuse_interrupt_in struct {
	unique uint64
}

type fuse_bmap_in struct {
	block uint64
	blocksize uint32
	padding uint32
}

type fuse_bmap_out struct {
	block uint64
}

type fuse_ioctl_in struct {
	fh uint64
	flags uint32
	cmd uint32
	arg uint64
	in_size uint32
	out_size uint32
}

type fuse_ioctl_out struct {
	result int32
	flags uint32
	in_iovs uint32
	out_iovs uint32
}

type fuse_poll_in struct {
	fh uint64
	kh uint64
	flags uint32
	padding uint32
}

type fuse_poll_out struct {
	revents uint32
	padding uint32
}

type fuse_notify_poll_wakeup_out struct {
	kh uint64
}

type fuse_in_header struct {
 length uint32
	opcode uint32
	unique uint64
	nodeid uint64
	uid uint32
	gid uint32
	pid uint32
	padding uint32
}

type fuse_out_header struct {
 length uint32
	error int32
	unique uint64
}

type fuse_dirent struct {
	ino uint64
	off uint64
	namelen uint32
	typ uint32
//	name []byte // char name[0] -- looks like the name is right after this struct.
}

type fuse_notify_inval_inode_out struct {
	ino uint64
	off int64
 length int64
}

type fuse_notify_inval_entry_out struct {
	parent uint64
	namelen uint32
	padding uint32
}

<commit_msg>gomake succeeds, gofmt make the code looks nice<commit_after>package fuse

const (

	/** Version number of this interface */
	FUSE_KERNEL_VERSION = 7

	/** Minor version number of this interface */
	FUSE_KERNEL_MINOR_VERSION = 13

	/** The node ID of the root inode */
	FUSE_ROOT_ID = 1

	/**
	 * Bitmasks for fuse_setattr_in.valid
	 */
	FATTR_MODE      = (1 << 0)
	FATTR_UID       = (1 << 1)
	FATTR_GID       = (1 << 2)
	FATTR_SIZE      = (1 << 3)
	FATTR_ATIME     = (1 << 4)
	FATTR_MTIME     = (1 << 5)
	FATTR_FH        = (1 << 6)
	FATTR_ATIME_NOW = (1 << 7)
	FATTR_MTIME_NOW = (1 << 8)
	FATTR_LOCKOWNER = (1 << 9)

	/**
	 * Flags returned by the OPEN request
	 *
	 * FOPEN_DIRECT_IO: bypass page cache for this open file
	 * FOPEN_KEEP_CACHE: don't invalidate the data cache on open
	 * FOPEN_NONSEEKABLE: the file is not seekable
	 */
	FOPEN_DIRECT_IO   = (1 << 0)
	FOPEN_KEEP_CACHE  = (1 << 1)
	FOPEN_NONSEEKABLE = (1 << 2)

	/**
	 * INIT request/reply flags
	 *
	 * FUSE_EXPORT_SUPPORT: filesystem handles lookups of "." and ".."
	 * FUSE_DONT_MASK: don't apply umask to file mode on create operations
	 */
	FUSE_ASYNC_READ     = (1 << 0)
	FUSE_POSIX_LOCKS    = (1 << 1)
	FUSE_FILE_OPS       = (1 << 2)
	FUSE_ATOMIC_O_TRUNC = (1 << 3)
	FUSE_EXPORT_SUPPORT = (1 << 4)
	FUSE_BIG_WRITES     = (1 << 5)
	FUSE_DONT_MASK      = (1 << 6)

	/**
	 * CUSE INIT request/reply flags
	 *
	 * CUSE_UNRESTRICTED_IOCTL:  use unrestricted ioctl
	 */
	CUSE_UNRESTRICTED_IOCTL = (1 << 0)

	/**
	 * Release flags
	 */
	FUSE_RELEASE_FLUSH = (1 << 0)

	/**
	 * Getattr flags
	 */
	FUSE_GETATTR_FH = (1 << 0)

	/**
	 * Lock flags
	 */
	FUSE_LK_FLOCK = (1 << 0)

	/**
	 * WRITE flags
	 *
	 * FUSE_WRITE_CACHE: delayed write from page cache, file handle is guessed
	 * FUSE_WRITE_LOCKOWNER: lock_owner field is valid
	 */
	FUSE_WRITE_CACHE     = (1 << 0)
	FUSE_WRITE_LOCKOWNER = (1 << 1)

	/**
	 * Read flags
	 */
	FUSE_READ_LOCKOWNER = (1 << 1)

	/**
	 * Ioctl flags
	 *
	 * FUSE_IOCTL_COMPAT: 32bit compat ioctl on 64bit machine
	 * FUSE_IOCTL_UNRESTRICTED: not restricted to well-formed ioctls, retry allowed
	 * FUSE_IOCTL_RETRY: retry with new iovecs
	 *
	 * FUSE_IOCTL_MAX_IOV: maximum of in_iovecs + out_iovecs
	 */
	FUSE_IOCTL_COMPAT       = (1 << 0)
	FUSE_IOCTL_UNRESTRICTED = (1 << 1)
	FUSE_IOCTL_RETRY        = (1 << 2)

	FUSE_IOCTL_MAX_IOV = 256

	/**
	 * Poll flags
	 *
	 * FUSE_POLL_SCHEDULE_NOTIFY: request poll notify
	 */
	FUSE_POLL_SCHEDULE_NOTIFY = (1 << 0)

	FUSE_COMPAT_WRITE_IN_SIZE = 24

	/* The read buffer is required to be at least 8k, but may be much larger */
	FUSE_MIN_READ_BUFFER = 8192

	FUSE_COMPAT_ENTRY_OUT_SIZE = 120

	FUSE_COMPAT_ATTR_OUT_SIZE = 96

	FUSE_COMPAT_MKNOD_IN_SIZE = 8

	FUSE_COMPAT_STATFS_SIZE = 48

	CUSE_INIT_INFO_MAX = 4096
)

type fuse_opcode int

const (
	FUSE_LOOKUP      = 1
	FUSE_FORGET      = 2 /* no reply */
	FUSE_GETATTR     = 3
	FUSE_SETATTR     = 4
	FUSE_READLINK    = 5
	FUSE_SYMLINK     = 6
	FUSE_MKNOD       = 8
	FUSE_MKDIR       = 9
	FUSE_UNLINK      = 10
	FUSE_RMDIR       = 11
	FUSE_RENAME      = 12
	FUSE_LINK        = 13
	FUSE_OPEN        = 14
	FUSE_READ        = 15
	FUSE_WRITE       = 16
	FUSE_STATFS      = 17
	FUSE_RELEASE     = 18
	FUSE_FSYNC       = 20
	FUSE_SETXATTR    = 21
	FUSE_GETXATTR    = 22
	FUSE_LISTXATTR   = 23
	FUSE_REMOVEXATTR = 24
	FUSE_FLUSH       = 25
	FUSE_INIT        = 26
	FUSE_OPENDIR     = 27
	FUSE_READDIR     = 28
	FUSE_RELEASEDIR  = 29
	FUSE_FSYNCDIR    = 30
	FUSE_GETLK       = 31
	FUSE_SETLK       = 32
	FUSE_SETLKW      = 33
	FUSE_ACCESS      = 34
	FUSE_CREATE      = 35
	FUSE_INTERRUPT   = 36
	FUSE_BMAP        = 37
	FUSE_DESTROY     = 38
	FUSE_IOCTL       = 39
	FUSE_POLL        = 40

	/* CUSE specific operations */
	CUSE_INIT = 4096
)

type fuse_notyfy_code int

const (
	FUSE_NOTIFY_POLL        = 1
	FUSE_NOTIFY_INVAL_INODE = 2
	FUSE_NOTIFY_INVAL_ENTRY = 3
	FUSE_NOTIFY_CODE_MAX    = 4
)

/* Make sure all structures are padded to 64bit boundary, so 32bit
   userspace works under 64bit kernels */

type fuse_attr struct {
	ino       uint64
	size      uint64
	blocks    uint64
	atime     uint64
	mtime     uint64
	ctime     uint64
	atimensec uint32
	mtimensec uint32
	ctimensec uint32
	mode      uint32
	nlink     uint32
	uid       uint32
	gid       uint32
	rdev      uint32
	blksize   uint32
	padding   uint32
}

type fuse_kstatfs struct {
	blocks  uint64
	bfree   uint64
	bavail  uint64
	files   uint64
	ffree   uint64
	bsize   uint32
	namelen uint32
	frsize  uint32
	padding uint32
	spare   [6]uint32
}

type fuse_file_lock struct {
	start uint64
	end   uint64
	typ   uint32
	pid   uint32 /* tgid */
}

type fuse_entry_out struct {
	nodeid     uint64 /* Inode ID */
	generation uint64 /* Inode generation: nodeid:gen must
	   be unique for the fs's lifetime */
	entry_valid      uint64 /* Cache timeout for the name */
	attr_valid       uint64 /* Cache timeout for the attributes */
	entry_valid_nsec uint32
	attr_valid_nsec  uint32
	attr             fuse_attr
}

type fuse_forget_in struct {
	nlookup uint64
}

type fuse_getattr_in struct {
	getattr_flags uint32
	dummy         uint32
	fh            uint64
}

type fuse_attr_out struct {
	attr_valid      uint64 /* Cache timeout for the attributes */
	attr_valid_nsec uint32
	dummy           uint32
	attr            fuse_attr
}

type fuse_mknod_in struct {
	mode    uint32
	rdev    uint32
	umask   uint32
	padding uint32
}

type fuse_mkdir_in struct {
	mode  uint32
	umask uint32
}

type fuse_rename_in struct {
	newdir uint64
}

type fuse_link_in struct {
	oldnodeid uint64
}

type fuse_setattr_in struct {
	valid      uint32
	padding    uint32
	fh         uint64
	size       uint64
	lock_owner uint64
	atime      uint64
	mtime      uint64
	unused2    uint64
	atimensec  uint32
	mtimensec  uint32
	unused3    uint32
	mode       uint32
	unused4    uint32
	uid        uint32
	gid        uint32
	unused5    uint32
}

type fuse_open_in struct {
	flags  uint32
	unused uint32
}

type fuse_create_in struct {
	flags   uint32
	mode    uint32
	umask   uint32
	padding uint32
}

type fuse_open_out struct {
	fh         uint64
	open_flags uint32
	padding    uint32
}

type fuse_release_in struct {
	fh            uint64
	flags         uint32
	release_flags uint32
	lock_owner    uint64
}

type fuse_flush_in struct {
	fh         uint64
	unused     uint32
	padding    uint32
	lock_owner uint64
}

type fuse_read_in struct {
	fh         uint64
	offset     uint64
	size       uint32
	read_flags uint32
	lock_owner uint64
	flags      uint32
	padding    uint32
}

type fuse_write_in struct {
	fh          uint64
	offset      uint64
	size        uint32
	write_flags uint32
	lock_owner  uint64
	flags       uint32
	padding     uint32
}

type fuse_write_out struct {
	size    uint32
	padding uint32
}

type fuse_statfs_out struct {
	st fuse_kstatfs
}

type fuse_fsync_in struct {
	fh          uint64
	fsync_flags uint32
	padding     uint32
}

type fuse_setxattr_in struct {
	size  uint32
	flags uint32
}

type fuse_getxattr_in struct {
	size    uint32
	padding uint32
}

type fuse_getxattr_out struct {
	size    uint32
	padding uint32
}

type fuse_lk_in struct {
	fh       uint64
	owner    uint64
	lk       fuse_file_lock
	lk_flags uint32
	padding  uint32
}

type fuse_lk_out struct {
	lk fuse_file_lock
}

type fuse_access_in struct {
	mask    uint32
	padding uint32
}

type fuse_init_in struct {
	major         uint32
	minor         uint32
	max_readahead uint32
	flags         uint32
}

type fuse_init_out struct {
	major                uint32
	minor                uint32
	max_readahead        uint32
	flags                uint32
	max_background       uint16
	congestion_threshold uint16
	max_write            uint32
}

type cuse_init_in struct {
	major  uint32
	minor  uint32
	unused uint32
	flags  uint32
}

type cuse_init_out struct {
	major     uint32
	minor     uint32
	unused    uint32
	flags     uint32
	max_read  uint32
	max_write uint32
	dev_major uint32 /* chardev major */
	dev_minor uint32 /* chardev minor */
	spare     [10]uint32
}

type fuse_interrupt_in struct {
	unique uint64
}

type fuse_bmap_in struct {
	block     uint64
	blocksize uint32
	padding   uint32
}

type fuse_bmap_out struct {
	block uint64
}

type fuse_ioctl_in struct {
	fh       uint64
	flags    uint32
	cmd      uint32
	arg      uint64
	in_size  uint32
	out_size uint32
}

type fuse_ioctl_out struct {
	result   int32
	flags    uint32
	in_iovs  uint32
	out_iovs uint32
}

type fuse_poll_in struct {
	fh      uint64
	kh      uint64
	flags   uint32
	padding uint32
}

type fuse_poll_out struct {
	revents uint32
	padding uint32
}

type fuse_notify_poll_wakeup_out struct {
	kh uint64
}

type fuse_in_header struct {
	length  uint32
	opcode  uint32
	unique  uint64
	nodeid  uint64
	uid     uint32
	gid     uint32
	pid     uint32
	padding uint32
}

type fuse_out_header struct {
	length uint32
	error  int32
	unique uint64
}

type fuse_dirent struct {
	ino     uint64
	off     uint64
	namelen uint32
	typ     uint32
	//	name []byte // char name[0] -- looks like the name is right after this struct.
}

type fuse_notify_inval_inode_out struct {
	ino    uint64
	off    int64
	length int64
}

type fuse_notify_inval_entry_out struct {
	parent  uint64
	namelen uint32
	padding uint32
}
<|endoftext|>


<commit_before>package game

import (
  "fmt"
)

type Game struct {
  Id uint `json:"id"`
  Name string `json:"name"`
  SetupRules []*SetupRule
  MinPlayers int
  MaxPlayers int
}

func NewGame(name string, rules []*SetupRule, minPlayers int, maxPlayers int) *Game {
  return &Game{
    Name: name,
    SetupRules: rules,
    MinPlayers: minPlayers,
    MaxPlayers: maxPlayers,
  }
}

func (game *Game) PrintSetupRules() {
  for _,r := range game.SetupRules {
    fmt.Printf("%s\t%s\n", r.Description, r.Arity)
  }
}
<commit_msg>Snake case for Game JSON<commit_after>package game

import (
  "fmt"
)

type Game struct {
  Id uint `json:"id"`
  Name string `json:"name"`
  SetupRules []*SetupRule
  MinPlayers int `json:"min_players"`
  MaxPlayers int `json:"max_players"`
}

func NewGame(name string, rules []*SetupRule, minPlayers int, maxPlayers int) *Game {
  return &Game{
    Name: name,
    SetupRules: rules,
    MinPlayers: minPlayers,
    MaxPlayers: maxPlayers,
  }
}

func (game *Game) PrintSetupRules() {
  for _,r := range game.SetupRules {
    fmt.Printf("%s\t%s\n", r.Description, r.Arity)
  }
}
<|endoftext|>


<commit_before>package game

import (
	"fmt"

	"github.com/sirupsen/logrus"

	"github.com/ivan1993spb/snake-server/observers"
	"github.com/ivan1993spb/snake-server/world"
)

type Game struct {
	world  *world.World
	logger logrus.FieldLogger
}

type ErrCreateGame struct {
	Err error
}

func (e *ErrCreateGame) Error() string {
	return "cannot create game: " + e.Err.Error()
}

func NewGame(logger logrus.FieldLogger, width, height uint8) (*Game, error) {
	w, err := world.NewWorld(width, height)
	if err != nil {
		return nil, fmt.Errorf("cannot create game: %s", err)
	}

	return &Game{
		world:  w,
		logger: logger,
	}, nil
}

func (g *Game) Start(stop <-chan struct{}) {
	g.world.Start(stop)

	observers.AppleObserver{}.Observe(stop, g.world)

	go func() {
		// TODO: Create buffer const.
		for event := range g.world.Events(stop, 32) {
			g.logger.Debugln("game event", event)
		}
	}()

}

func (g *Game) World() *world.World {
	return g.world
}

func (g *Game) ListenEvents(stop <-chan struct{}, buffer uint) <-chan Event {
	chout := make(chan Event, buffer)
	go func() {
		defer close(chout)
		for worldEvent := range g.world.Events(stop, buffer) {
			chout <- Event{
				Type:    worldEventTypeToGameEventType(worldEvent.Type),
				Payload: worldEvent.Payload,
			}
		}
	}()
	return chout
}
<commit_msg>Disable apple observer in Game<commit_after>package game

import (
	"fmt"

	"github.com/sirupsen/logrus"

	//"github.com/ivan1993spb/snake-server/observers"
	"github.com/ivan1993spb/snake-server/world"
)

type Game struct {
	world  *world.World
	logger logrus.FieldLogger
}

type ErrCreateGame struct {
	Err error
}

func (e *ErrCreateGame) Error() string {
	return "cannot create game: " + e.Err.Error()
}

func NewGame(logger logrus.FieldLogger, width, height uint8) (*Game, error) {
	w, err := world.NewWorld(width, height)
	if err != nil {
		return nil, fmt.Errorf("cannot create game: %s", err)
	}

	return &Game{
		world:  w,
		logger: logger,
	}, nil
}

func (g *Game) Start(stop <-chan struct{}) {
	g.world.Start(stop)

	// TODO: Run observers.
	//observers.AppleObserver{}.Observe(stop, g.world)

	go func() {
		// TODO: Create buffer const.
		for event := range g.world.Events(stop, 32) {
			g.logger.Debugln("game event", event)
		}
	}()

}

func (g *Game) World() *world.World {
	return g.world
}

func (g *Game) ListenEvents(stop <-chan struct{}, buffer uint) <-chan Event {
	chout := make(chan Event, buffer)
	go func() {
		defer close(chout)
		for worldEvent := range g.world.Events(stop, buffer) {
			chout <- Event{
				Type:    worldEventTypeToGameEventType(worldEvent.Type),
				Payload: worldEvent.Payload,
			}
		}
	}()
	return chout
}
<|endoftext|>


<commit_before>package acquire

import (
	"math/rand"
	"reflect"
	"testing"
)

func genGameParams() (r *rand.Rand, players []Player) {
	r = rand.New(rand.NewSource(0))
	players = []Player{NewPlayerRandom(r)}
	return
}

func TestNewGame(t *testing.T) {
	r, players := genGameParams()
	g := NewGame(r, players)

	for i := HotelFirst; i < HotelLast; i++ {
		if g.AvailableStocks[i] != StartingStocks {
			t.Errorf("Should have %d stocks for %d, but instead have %d", StartingStocks, i, g.AvailableStocks[i])
		}
	}

	if len(g.AvailableChains) != HotelCount {
		t.Errorf("Did not have expected number of available hotel chains at start: %v", g.AvailableChains)
	}

	numPlayers := len(g.Players)

	if g.Players == nil {
		t.Error("Missing players")
	} else if numPlayers != len(players) {
		t.Error("Players not assigned")
	}

	targetPieces := BoardWidth*BoardHeight - 6*numPlayers

	if g.PieceBag == nil {
		t.Errorf("Pice bag missing")
	} else if len(g.PieceBag.Pieces) == BoardWidth*BoardHeight {
		t.Errorf("Piece bag started full, should have %d pieces but instead has %d", targetPieces, len(g.PieceBag.Pieces))
	} else if len(g.PieceBag.Pieces) != targetPieces {
		t.Errorf("Piece bag did not get drawn from correctly, has %d pieces but should have %d", len(g.PieceBag.Pieces), targetPieces)
	}

	if startingStateType := reflect.TypeOf(g.State); startingStateType == nil {
		t.Error("Starting state not set")
	} else {
		stateName := reflect.TypeOf(g.State).Name()
		if stateName != "StatePlayTile" {
			t.Errorf("Unexpected starting state: %v (should be StatePlayTile)", reflect.TypeOf(g.State))
		}
	}

	for h, s := range g.CurrentChainSizes {
		if s != 0 {
			t.Errorf("Unexpected chain size of %d for hotel %d, should be 0", s, h)
		}
	}
}
<commit_msg>Typo fix<commit_after>package acquire

import (
	"math/rand"
	"reflect"
	"testing"
)

func genGameParams() (r *rand.Rand, players []Player) {
	r = rand.New(rand.NewSource(0))
	players = []Player{NewPlayerRandom(r)}
	return
}

func TestNewGame(t *testing.T) {
	r, players := genGameParams()
	g := NewGame(r, players)

	for i := HotelFirst; i < HotelLast; i++ {
		if g.AvailableStocks[i] != StartingStocks {
			t.Errorf("Should have %d stocks for %d, but instead have %d", StartingStocks, i, g.AvailableStocks[i])
		}
	}

	if len(g.AvailableChains) != HotelCount {
		t.Errorf("Did not have expected number of available hotel chains at start: %v", g.AvailableChains)
	}

	numPlayers := len(g.Players)

	if g.Players == nil {
		t.Error("Missing players")
	} else if numPlayers != len(players) {
		t.Error("Players not assigned")
	}

	targetPieces := BoardWidth*BoardHeight - 6*numPlayers

	if g.PieceBag == nil {
		t.Errorf("Piece bag missing")
	} else if len(g.PieceBag.Pieces) == BoardWidth*BoardHeight {
		t.Errorf("Piece bag started full, should have %d pieces but instead has %d", targetPieces, len(g.PieceBag.Pieces))
	} else if len(g.PieceBag.Pieces) != targetPieces {
		t.Errorf("Piece bag did not get drawn from correctly, has %d pieces but should have %d", len(g.PieceBag.Pieces), targetPieces)
	}

	if startingStateType := reflect.TypeOf(g.State); startingStateType == nil {
		t.Error("Starting state not set")
	} else {
		stateName := reflect.TypeOf(g.State).Name()
		if stateName != "StatePlayTile" {
			t.Errorf("Unexpected starting state: %v (should be StatePlayTile)", reflect.TypeOf(g.State))
		}
	}

	for h, s := range g.CurrentChainSizes {
		if s != 0 {
			t.Errorf("Unexpected chain size of %d for hotel %d, should be 0", s, h)
		}
	}
}
<|endoftext|>


<commit_before>package gehirndns

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"path"
	"strconv"
	"time"

	"github.com/kr/pretty"
)

const (
	APIENDPOINT = "https://cp.gehirn.jp/api/dns/"
)

type (
	ZoneId      uint
	IPv4        string
	IPv6        string
	HostName    string
	MailAddress string
	RecordId    string
	RecordType  string
	Seconds     int64
	Priority    uint64
)

func (s Seconds) Duration() time.Duration {
	return time.Duration(s) * time.Second
}

type IRecord interface {
	GetId() RecordId
	GetHostName() HostName
	GetType() RecordType
	GetTTL() Seconds
}

type Record struct {
	Id       RecordId `json:"ID,omitempty"`
	Name     HostName `json:",omitempty"`
	HostName HostName
	Type     RecordType `json:"Type"`
	TTL      Seconds    `json:"TTL"`
}

func (r *Record) GetId() RecordId {
	return r.Id
}

func (r *Record) GetHostName() HostName {
	if len(r.Name) > 0 {
		return r.Name
	}

	return r.HostName
}

func (r *Record) GetType() RecordType {
	return r.Type
}

func (r *Record) GetTTL() Seconds {
	return r.TTL
}

type SOARecord struct {
	Mname            HostName    `json:"MNAME"`
	Rname            MailAddress `json:"RNAME"`
	Serial           uint
	Refresh          Seconds
	Retry            Seconds
	Expire           Seconds
	NegativeCacheTTL Seconds
	Record
}

type NSRecord struct {
	NameServer HostName
	Record
}

type ARecord struct {
	IPAddress IPv4 `json:"IPAddress"`
	Record
}

type AAAARecord struct {
	IPAddress IPv6 `json:"IPAddress"`
	Record
}

type CNAMERecord struct {
	AliasTo HostName `json:"AliasTo"`
	Record
}

type MXRecord struct {
	MailServer HostName
	Priority   Priority
	Record
}

type TXTRecord struct {
	Value string
	Record
}

type SRVRecord struct {
	Priority Priority
	Weight   uint
	Port     uint
	Target   HostName
	Record
}

type Client struct {
	endpoint  *url.URL
	apiToken  string
	apiSecret string
}

func NewClient(zoneId ZoneId, apiToken, apiSecret string) *Client {
	endpoint, err := url.Parse(APIENDPOINT)
	if err != nil {
		panic(err)
	}

	endpoint.Path = path.Join(
		endpoint.Path,
		"resource",
		strconv.Itoa(int(zoneId)))

	return &Client{
		endpoint:  endpoint,
		apiToken:  apiToken,
		apiSecret: apiSecret,
	}
}

func (c *Client) buildURL(relativePath string) (endpoint *url.URL) {
	endpoint = new(url.URL)
	*endpoint = *c.endpoint
	endpoint.Path = path.Join(endpoint.Path, relativePath)
	return
}

func (c *Client) makeRequest(method, path string, body io.Reader) (req *http.Request, err error) {
	endpoint := c.buildURL(path)
	req, err = http.NewRequest(method, endpoint.String(), body)
	if err != nil {
		return
	}

	req.SetBasicAuth(c.apiToken, c.apiSecret)
	return
}

func (c *Client) request(req *http.Request, body interface{}) (err error) {
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return
	}

	if resp.StatusCode != 200 {
		return fmt.Errorf(resp.Status)
	}

	decoder := json.NewDecoder(resp.Body)
	if err = decoder.Decode(&body); err != nil {
		return
	}

	return
}

func (c *Client) GetResources() (err error) {
	req, err := c.makeRequest("GET", "", nil)
	if err != nil {
		return
	}

	body := struct {
		Resource struct {
			SOA   SOARecord
			NS    []NSRecord
			A     []ARecord
			AAAA  []AAAARecord
			CNAME []CNAMERecord
			MX    []MXRecord
			TXT   []TXTRecord
			SRV   []SRVRecord
		}
		Successful bool `json:"is_success"`
	}{}

	if err = c.request(req, &body); err != nil {
		return
	} else if !body.Successful {
		return fmt.Errorf("unsuccessful")
	}

	pretty.Println(body.Resource)
	return
}

func (c *Client) AddNS(name, ns HostName, ttl Seconds) (record *NSRecord, err error) {
	const (
		recordType RecordType = "NS"
	)

	record = &NSRecord{
		NameServer: ns,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	c.AddResource(record)
	return
}

func (c *Client) AddA(name HostName, addr IPv4, ttl Seconds) (record *ARecord, err error) {
	const (
		recordType RecordType = "A"
	)

	record = &ARecord{
		IPAddress: addr,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	c.AddResource(record)
	return
}

func (c *Client) AddAAAA(name HostName, addr IPv6, ttl Seconds) (record *AAAARecord, err error) {
	const (
		recordType RecordType = "AAAA"
	)

	record = &AAAARecord{
		IPAddress: addr,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	c.AddResource(record)
	return
}

func (c *Client) AddCNAME(name, to HostName, ttl Seconds) (record *CNAMERecord, err error) {
	const (
		recordType RecordType = "CNAME"
	)

	record = &CNAMERecord{
		AliasTo: to,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	c.AddResource(record)
	return
}

func (c *Client) AddMX(name, mailServer HostName, priority Priority, ttl Seconds) (record *MXRecord, err error) {
	const (
		recordType RecordType = "MX"
	)

	record = &MXRecord{
		MailServer: mailServer,
		Priority:   priority,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	c.AddResource(record)
	return
}

func (c *Client) AddTXT(name HostName, value string, ttl Seconds) (record *TXTRecord, err error) {
	const (
		recordType RecordType = "TXT"
	)

	record = &TXTRecord{
		Value: value,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	c.AddResource(record)
	return
}

func (c *Client) AddSRV(name, target HostName, port, weight uint, priority Priority, ttl Seconds) (record *SRVRecord, err error) {
	const (
		recordType RecordType = "SRV"
	)

	record = &SRVRecord{
		Target:   target,
		Port:     port,
		Weight:   weight,
		Priority: priority,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	c.AddResource(record)
	return
}

func (c *Client) AddResource(record IRecord) (err error) {
	request := struct {
		Resource IRecord
	}{
		Resource: record,
	}

	body, err := json.MarshalIndent(request, "", "  ")
	if err != nil {
		return
	}

	fmt.Println(string(body))
	return
}
<commit_msg>impl AddResource<commit_after>package gehirndns

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"path"
	"strconv"
	"time"

	"github.com/kr/pretty"
)

const (
	APIENDPOINT = "https://cp.gehirn.jp/api/dns/"
)

type (
	ZoneId      uint
	IPv4        string
	IPv6        string
	HostName    string
	MailAddress string
	RecordId    string
	RecordType  string
	Seconds     int64
	Priority    uint64
)

func (s Seconds) Duration() time.Duration {
	return time.Duration(s) * time.Second
}

type IRecord interface {
	GetId() RecordId
	GetHostName() HostName
	GetType() RecordType
	GetTTL() Seconds
}

type Record struct {
	Id       RecordId `json:"ID,omitempty"`
	Name     HostName `json:",omitempty"`
	HostName HostName
	Type     RecordType `json:"Type"`
	TTL      Seconds    `json:"TTL"`
}

func (r *Record) GetId() RecordId {
	return r.Id
}

func (r *Record) GetHostName() HostName {
	if len(r.Name) > 0 {
		return r.Name
	}

	return r.HostName
}

func (r *Record) GetType() RecordType {
	return r.Type
}

func (r *Record) GetTTL() Seconds {
	return r.TTL
}

type SOARecord struct {
	Mname            HostName    `json:"MNAME"`
	Rname            MailAddress `json:"RNAME"`
	Serial           uint
	Refresh          Seconds
	Retry            Seconds
	Expire           Seconds
	NegativeCacheTTL Seconds
	Record
}

type NSRecord struct {
	NameServer HostName
	Record
}

type ARecord struct {
	IPAddress IPv4 `json:"IPAddress"`
	Record
}

type AAAARecord struct {
	IPAddress IPv6 `json:"IPAddress"`
	Record
}

type CNAMERecord struct {
	AliasTo HostName `json:"AliasTo"`
	Record
}

type MXRecord struct {
	MailServer HostName
	Priority   Priority
	Record
}

type TXTRecord struct {
	Value string
	Record
}

type SRVRecord struct {
	Priority Priority
	Weight   uint
	Port     uint
	Target   HostName
	Record
}

type Client struct {
	endpoint  *url.URL
	apiToken  string
	apiSecret string
}

func NewClient(zoneId ZoneId, apiToken, apiSecret string) *Client {
	endpoint, err := url.Parse(APIENDPOINT)
	if err != nil {
		panic(err)
	}

	endpoint.Path = path.Join(
		endpoint.Path,
		"resource",
		strconv.Itoa(int(zoneId)))

	return &Client{
		endpoint:  endpoint,
		apiToken:  apiToken,
		apiSecret: apiSecret,
	}
}

func (c *Client) buildURL(relativePath string) (endpoint *url.URL) {
	endpoint = new(url.URL)
	*endpoint = *c.endpoint
	endpoint.Path = path.Join(endpoint.Path, relativePath)
	return
}

func (c *Client) makeRequest(method, path string, body io.Reader) (req *http.Request, err error) {
	endpoint := c.buildURL(path)
	req, err = http.NewRequest(method, endpoint.String(), body)
	if err != nil {
		return
	}

	req.SetBasicAuth(c.apiToken, c.apiSecret)
	req.Header.Add("Content-Type", "text/json;charset=utf8")
	return
}

func (c *Client) request(req *http.Request, body interface{}) (err error) {
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return
	}

	if resp.StatusCode != 200 {
		return fmt.Errorf(resp.Status)
	}

	decoder := json.NewDecoder(resp.Body)
	if err = decoder.Decode(&body); err != nil {
		return
	}

	return
}

func (c *Client) GetResources() (err error) {
	req, err := c.makeRequest("GET", "", nil)
	if err != nil {
		return
	}

	body := struct {
		Resource struct {
			SOA   SOARecord
			NS    []NSRecord
			A     []ARecord
			AAAA  []AAAARecord
			CNAME []CNAMERecord
			MX    []MXRecord
			TXT   []TXTRecord
			SRV   []SRVRecord
		}
		Successful bool `json:"is_success"`
	}{}

	if err = c.request(req, &body); err != nil {
		return
	} else if !body.Successful {
		return fmt.Errorf("unsuccessful")
	}

	pretty.Println(body.Resource)
	return
}

func (c *Client) AddNS(name, ns HostName, ttl Seconds) (record *NSRecord, err error) {
	const (
		recordType RecordType = "NS"
	)

	record = &NSRecord{
		NameServer: ns,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	err = c.AddResource(record)
	return
}

func (c *Client) AddA(name HostName, addr IPv4, ttl Seconds) (record *ARecord, err error) {
	const (
		recordType RecordType = "A"
	)

	record = &ARecord{
		IPAddress: addr,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	err = c.AddResource(record)
	return
}

func (c *Client) AddAAAA(name HostName, addr IPv6, ttl Seconds) (record *AAAARecord, err error) {
	const (
		recordType RecordType = "AAAA"
	)

	record = &AAAARecord{
		IPAddress: addr,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	err = c.AddResource(record)
	return
}

func (c *Client) AddCNAME(name, to HostName, ttl Seconds) (record *CNAMERecord, err error) {
	const (
		recordType RecordType = "CNAME"
	)

	record = &CNAMERecord{
		AliasTo: to,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	err = c.AddResource(record)
	return
}

func (c *Client) AddMX(name, mailServer HostName, priority Priority, ttl Seconds) (record *MXRecord, err error) {
	const (
		recordType RecordType = "MX"
	)

	record = &MXRecord{
		MailServer: mailServer,
		Priority:   priority,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	err = c.AddResource(record)
	return
}

func (c *Client) AddTXT(name HostName, value string, ttl Seconds) (record *TXTRecord, err error) {
	const (
		recordType RecordType = "TXT"
	)

	record = &TXTRecord{
		Value: value,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	err = c.AddResource(record)
	return
}

func (c *Client) AddSRV(name, target HostName, port, weight uint, priority Priority, ttl Seconds) (record *SRVRecord, err error) {
	const (
		recordType RecordType = "SRV"
	)

	record = &SRVRecord{
		Target:   target,
		Port:     port,
		Weight:   weight,
		Priority: priority,
		Record: Record{
			HostName: name,
			Type:     recordType,
			TTL:      ttl,
		},
	}

	err = c.AddResource(record)
	return
}

func (c *Client) encodeJSON(object interface{}) (reader io.Reader, err error) {
	buffer := bytes.NewBuffer(nil)
	encoder := json.NewEncoder(buffer)
	err = encoder.Encode(object)
	if err != nil {
		return
	}

	reader = buffer
	return
}

func (c *Client) AddResource(record IRecord) (err error) {
	bodyObject := struct {
		Resource IRecord
	}{
		Resource: record,
	}
	body, err := c.encodeJSON(bodyObject)
	if err != nil {
		return
	}

	request, err := c.makeRequest("POST", "", body)
	if err != nil {
		return
	}

	err = c.request(request, record)
	return
}
<|endoftext|>


<commit_before>package main // import "sourcegraph.com/sourcegraph/gen-mocks"

import (
	"bytes"
	"flag"
	"fmt"
	"go/ast"
	"go/build"
	"go/parser"
	"go/printer"
	"go/token"
	"io"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"strings"

	"golang.org/x/tools/imports"
)

var (
	ifacePkgDir = flag.String("p", ".", "directory of package containing interface types")
	ifacePat    = flag.String("i", ".+Service", "regexp pattern for selecting interface types by name")
	writeFiles  = flag.Bool("w", false, "write over existing files in output directory (default: writes to stdout)")
	outDir      = flag.String("o", ".", "output directory")
	outPkg      = flag.String("outpkg", "", "output pkg name (default: same as input pkg)")
	namePrefix  = flag.String("name_prefix", "Mock", "output: name prefix of mock impl types (e.g., T -> MockT)")

	fset = token.NewFileSet()
)

func main() {
	flag.Parse()
	log.SetFlags(0)

	bpkg, err := build.Import(*ifacePkgDir, ".", build.FindOnly)
	if err != nil {
		log.Fatal(err)
	}

	pat, err := regexp.Compile(*ifacePat)
	if err != nil {
		log.Fatal(err)
	}

	pkgs, err := parser.ParseDir(fset, *ifacePkgDir, nil, parser.AllErrors)
	if err != nil {
		log.Fatal(err)
	}

	for _, pkg := range pkgs {
		ifaces, err := readIfaces(pkg, pat)
		if err != nil {
			log.Fatal(err)
		}
		if len(ifaces) == 0 {
			log.Printf("warning: package has no interface types matching %q", *ifacePat)
			continue
		}

		var pkgName string
		if *outPkg == "" {
			pkgName = pkg.Name
		} else {
			pkgName = *outPkg
		}

		if err := writeMockImplFiles(*outDir, pkgName, pkg.Name, bpkg.ImportPath, ifaces); err != nil {
			log.Fatal(err)
		}
	}
}

// readIfaces returns a list of interface types in pkg that should be
// mocked.
func readIfaces(pkg *ast.Package, pat *regexp.Regexp) ([]*ast.TypeSpec, error) {
	var ifaces []*ast.TypeSpec
	ast.Walk(visitFn(func(node ast.Node) bool {
		switch node := node.(type) {
		case *ast.GenDecl:
			if node.Tok == token.TYPE {
				for _, spec := range node.Specs {
					tspec := spec.(*ast.TypeSpec)
					if _, ok := tspec.Type.(*ast.InterfaceType); !ok {
						continue
					}
					if name := tspec.Name.Name; pat.MatchString(name) {
						ifaces = append(ifaces, tspec)
					}
				}
			}
			return false
		default:
			return true
		}
	}), pkg)
	return ifaces, nil
}

type visitFn func(node ast.Node) (descend bool)

func (v visitFn) Visit(node ast.Node) ast.Visitor {
	descend := v(node)
	if descend {
		return v
	} else {
		return nil
	}
}

func writeMockImplFiles(outDir, outPkg, ifacePkgName, ifacePkgPath string, svcIfaces []*ast.TypeSpec) error {
	if err := os.MkdirAll(outDir, 0700); err != nil {
		return err
	}
	decls := map[string][]ast.Decl{} // file -> decls
	for _, iface := range svcIfaces {
		filename := fset.Position(iface.Pos()).Filename
		filename = filepath.Join(outDir, strings.TrimSuffix(filepath.Base(filename), ".go")+"_mock.go")

		// mock method fields on struct
		var methFields []*ast.Field
		for _, methField := range iface.Type.(*ast.InterfaceType).Methods.List {
			if meth, ok := methField.Type.(*ast.FuncType); ok {
				methFields = append(methFields, &ast.Field{
					Names: []*ast.Ident{ast.NewIdent(methField.Names[0].Name + "_")},
					Type:  meth,
				})
			}
		}

		// struct implementation type
		mockTypeName := *namePrefix + iface.Name.Name
		implType := &ast.GenDecl{Tok: token.TYPE, Specs: []ast.Spec{&ast.TypeSpec{
			Name: ast.NewIdent(mockTypeName),
			Type: &ast.StructType{Fields: &ast.FieldList{List: methFields}},
		}}}
		decls[filename] = append(decls[filename], implType)

		// struct methods
		for _, methField := range iface.Type.(*ast.InterfaceType).Methods.List {
			if meth, ok := methField.Type.(*ast.FuncType); ok {
				synthesizeFieldNamesIfMissing(meth.Params)
				if ifacePkgName != outPkg {
					// TODO(sqs): check for import paths or dirs unequal, not pkg name
					qualifyPkgRefs(meth, ifacePkgName)
				}
				decls[filename] = append(decls[filename], &ast.FuncDecl{
					Recv: &ast.FieldList{List: []*ast.Field{
						{
							Names: []*ast.Ident{ast.NewIdent("s")},
							Type:  &ast.StarExpr{X: ast.NewIdent(mockTypeName)},
						},
					}},
					Name: ast.NewIdent(methField.Names[0].Name),
					Type: meth,
					Body: &ast.BlockStmt{List: []ast.Stmt{
						&ast.ReturnStmt{Results: []ast.Expr{
							&ast.CallExpr{
								Fun: &ast.SelectorExpr{
									X:   ast.NewIdent("s"),
									Sel: ast.NewIdent(methField.Names[0].Name + "_"),
								},
								Args:     fieldListToIdentList(meth.Params),
								Ellipsis: ellipsisIfNeeded(meth.Params),
							},
						}},
					}},
				})
			}
		}

		// compile-time implements checks
		var ifaceType ast.Expr
		if ifacePkgName == outPkg {
			ifaceType = ast.NewIdent(iface.Name.Name)
		} else {
			ifaceType = &ast.SelectorExpr{X: ast.NewIdent(ifacePkgName), Sel: ast.NewIdent(iface.Name.Name)}
		}
		decls[filename] = append(decls[filename], &ast.GenDecl{
			Tok: token.VAR,
			Specs: []ast.Spec{
				&ast.ValueSpec{
					Names: []*ast.Ident{ast.NewIdent("_")},
					Type:  ifaceType,
					Values: []ast.Expr{
						&ast.CallExpr{
							Fun:  &ast.ParenExpr{X: &ast.StarExpr{X: ast.NewIdent(mockTypeName)}},
							Args: []ast.Expr{ast.NewIdent("nil")},
						},
					},
				},
			},
		})
	}

	for filename, decls := range decls {
		file := &ast.File{
			Name:  ast.NewIdent(outPkg),
			Decls: decls,
		}
		log.Println("#", filename)
		var w io.Writer
		if *writeFiles {
			f, err := os.Create(filename)
			if err != nil {
				return err
			}
			defer f.Close()
			w = f
		} else {
			w = os.Stdout
		}

		var buf bytes.Buffer
		if err := printer.Fprint(&buf, fset, file); err != nil {
			return err
		}

		// Always put blank lines between funcs.
		src := bytes.Replace(buf.Bytes(), []byte("}\nfunc"), []byte("}\n\nfunc"), -1)

		var err error
		src, err = imports.Process(filename, src, nil)
		if err != nil {
			return err
		}

		fmt.Fprintln(w, "// generated by gen-mocks; DO NOT EDIT")
		fmt.Fprintln(w)
		w.Write(src)
	}
	return nil
}

// qualifyPkgRefs qualifies all refs to non-package-qualified non-builtin types in f so that they refer to definitions in pkg. E.g., 'func(x MyType) -> func (x pkg.MyType)'.
func qualifyPkgRefs(f *ast.FuncType, pkg string) {
	var qualify func(x ast.Expr) ast.Expr
	qualify = func(x ast.Expr) ast.Expr {
		switch y := x.(type) {
		case *ast.Ident:
			if ast.IsExported(y.Name) {
				return &ast.SelectorExpr{X: ast.NewIdent(pkg), Sel: y}
			}
		case *ast.StarExpr:
			y.X = qualify(y.X)
		case *ast.ArrayType:
			y.Elt = qualify(y.Elt)
		case *ast.MapType:
			y.Key = qualify(y.Key)
			y.Value = qualify(y.Value)
		}
		return x
	}
	for _, p := range f.Params.List {
		p.Type = qualify(p.Type)
	}
	for _, r := range f.Results.List {
		r.Type = qualify(r.Type)
	}
}

// synthesizeFieldNamesIfMissing adds synthesized variable names to fl
// if it contains fields with no name. E.g., the field list in
// `func(string, int)` would be converted to `func(v0 string, v1
// int)`.
func synthesizeFieldNamesIfMissing(fl *ast.FieldList) {
	for i, f := range fl.List {
		if len(f.Names) == 0 {
			f.Names = []*ast.Ident{ast.NewIdent(fmt.Sprintf("v%d", i))}
		}
	}
}

func fieldListToIdentList(fl *ast.FieldList) []ast.Expr {
	var fs []ast.Expr
	for _, f := range fl.List {
		for _, name := range f.Names {
			x := ast.Expr(ast.NewIdent(name.Name))
			fs = append(fs, x)
		}
	}
	return fs
}

func hasEllipsis(fl *ast.FieldList) bool {
	if fl.List == nil {
		return false
	}
	_, ok := fl.List[len(fl.List)-1].Type.(*ast.Ellipsis)
	return ok
}

func ellipsisIfNeeded(fl *ast.FieldList) token.Pos {
	if hasEllipsis(fl) {
		return 1
	}
	return 0
}

func astString(x ast.Expr) string {
	var buf bytes.Buffer
	if err := printer.Fprint(&buf, fset, x); err != nil {
		panic(err)
	}
	return buf.String()
}
<commit_msg>ignore main and xtest pkgs<commit_after>package main // import "sourcegraph.com/sourcegraph/gen-mocks"

import (
	"bytes"
	"flag"
	"fmt"
	"go/ast"
	"go/build"
	"go/parser"
	"go/printer"
	"go/token"
	"io"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"strings"

	"golang.org/x/tools/imports"
)

var (
	ifacePkgDir = flag.String("p", ".", "directory of package containing interface types")
	ifacePat    = flag.String("i", ".+Service", "regexp pattern for selecting interface types by name")
	writeFiles  = flag.Bool("w", false, "write over existing files in output directory (default: writes to stdout)")
	outDir      = flag.String("o", ".", "output directory")
	outPkg      = flag.String("outpkg", "", "output pkg name (default: same as input pkg)")
	namePrefix  = flag.String("name_prefix", "Mock", "output: name prefix of mock impl types (e.g., T -> MockT)")

	fset = token.NewFileSet()
)

func main() {
	flag.Parse()
	log.SetFlags(0)

	bpkg, err := build.Import(*ifacePkgDir, ".", build.FindOnly)
	if err != nil {
		log.Fatal(err)
	}

	pat, err := regexp.Compile(*ifacePat)
	if err != nil {
		log.Fatal(err)
	}

	pkgs, err := parser.ParseDir(fset, *ifacePkgDir, nil, parser.AllErrors)
	if err != nil {
		log.Fatal(err)
	}

	for _, pkg := range pkgs {
		if pkg.Name == "main" || strings.HasSuffix(pkg.Name, "_test") {
			continue
		}

		ifaces, err := readIfaces(pkg, pat)
		if err != nil {
			log.Fatal(err)
		}
		if len(ifaces) == 0 {
			log.Printf("warning: package %q has no interface types matching %q", pkg.Name, *ifacePat)
			continue
		}

		var pkgName string
		if *outPkg == "" {
			pkgName = pkg.Name
		} else {
			pkgName = *outPkg
		}

		if err := writeMockImplFiles(*outDir, pkgName, pkg.Name, bpkg.ImportPath, ifaces); err != nil {
			log.Fatal(err)
		}
	}
}

// readIfaces returns a list of interface types in pkg that should be
// mocked.
func readIfaces(pkg *ast.Package, pat *regexp.Regexp) ([]*ast.TypeSpec, error) {
	var ifaces []*ast.TypeSpec
	ast.Walk(visitFn(func(node ast.Node) bool {
		switch node := node.(type) {
		case *ast.GenDecl:
			if node.Tok == token.TYPE {
				for _, spec := range node.Specs {
					tspec := spec.(*ast.TypeSpec)
					if _, ok := tspec.Type.(*ast.InterfaceType); !ok {
						continue
					}
					if name := tspec.Name.Name; pat.MatchString(name) {
						ifaces = append(ifaces, tspec)
					}
				}
			}
			return false
		default:
			return true
		}
	}), pkg)
	return ifaces, nil
}

type visitFn func(node ast.Node) (descend bool)

func (v visitFn) Visit(node ast.Node) ast.Visitor {
	descend := v(node)
	if descend {
		return v
	} else {
		return nil
	}
}

func writeMockImplFiles(outDir, outPkg, ifacePkgName, ifacePkgPath string, svcIfaces []*ast.TypeSpec) error {
	if err := os.MkdirAll(outDir, 0700); err != nil {
		return err
	}
	decls := map[string][]ast.Decl{} // file -> decls
	for _, iface := range svcIfaces {
		filename := fset.Position(iface.Pos()).Filename
		filename = filepath.Join(outDir, strings.TrimSuffix(filepath.Base(filename), ".go")+"_mock.go")

		// mock method fields on struct
		var methFields []*ast.Field
		for _, methField := range iface.Type.(*ast.InterfaceType).Methods.List {
			if meth, ok := methField.Type.(*ast.FuncType); ok {
				methFields = append(methFields, &ast.Field{
					Names: []*ast.Ident{ast.NewIdent(methField.Names[0].Name + "_")},
					Type:  meth,
				})
			}
		}

		// struct implementation type
		mockTypeName := *namePrefix + iface.Name.Name
		implType := &ast.GenDecl{Tok: token.TYPE, Specs: []ast.Spec{&ast.TypeSpec{
			Name: ast.NewIdent(mockTypeName),
			Type: &ast.StructType{Fields: &ast.FieldList{List: methFields}},
		}}}
		decls[filename] = append(decls[filename], implType)

		// struct methods
		for _, methField := range iface.Type.(*ast.InterfaceType).Methods.List {
			if meth, ok := methField.Type.(*ast.FuncType); ok {
				synthesizeFieldNamesIfMissing(meth.Params)
				if ifacePkgName != outPkg {
					// TODO(sqs): check for import paths or dirs unequal, not pkg name
					qualifyPkgRefs(meth, ifacePkgName)
				}
				decls[filename] = append(decls[filename], &ast.FuncDecl{
					Recv: &ast.FieldList{List: []*ast.Field{
						{
							Names: []*ast.Ident{ast.NewIdent("s")},
							Type:  &ast.StarExpr{X: ast.NewIdent(mockTypeName)},
						},
					}},
					Name: ast.NewIdent(methField.Names[0].Name),
					Type: meth,
					Body: &ast.BlockStmt{List: []ast.Stmt{
						&ast.ReturnStmt{Results: []ast.Expr{
							&ast.CallExpr{
								Fun: &ast.SelectorExpr{
									X:   ast.NewIdent("s"),
									Sel: ast.NewIdent(methField.Names[0].Name + "_"),
								},
								Args:     fieldListToIdentList(meth.Params),
								Ellipsis: ellipsisIfNeeded(meth.Params),
							},
						}},
					}},
				})
			}
		}

		// compile-time implements checks
		var ifaceType ast.Expr
		if ifacePkgName == outPkg {
			ifaceType = ast.NewIdent(iface.Name.Name)
		} else {
			ifaceType = &ast.SelectorExpr{X: ast.NewIdent(ifacePkgName), Sel: ast.NewIdent(iface.Name.Name)}
		}
		decls[filename] = append(decls[filename], &ast.GenDecl{
			Tok: token.VAR,
			Specs: []ast.Spec{
				&ast.ValueSpec{
					Names: []*ast.Ident{ast.NewIdent("_")},
					Type:  ifaceType,
					Values: []ast.Expr{
						&ast.CallExpr{
							Fun:  &ast.ParenExpr{X: &ast.StarExpr{X: ast.NewIdent(mockTypeName)}},
							Args: []ast.Expr{ast.NewIdent("nil")},
						},
					},
				},
			},
		})
	}

	for filename, decls := range decls {
		file := &ast.File{
			Name:  ast.NewIdent(outPkg),
			Decls: decls,
		}
		log.Println("#", filename)
		var w io.Writer
		if *writeFiles {
			f, err := os.Create(filename)
			if err != nil {
				return err
			}
			defer f.Close()
			w = f
		} else {
			w = os.Stdout
		}

		var buf bytes.Buffer
		if err := printer.Fprint(&buf, fset, file); err != nil {
			return err
		}

		// Always put blank lines between funcs.
		src := bytes.Replace(buf.Bytes(), []byte("}\nfunc"), []byte("}\n\nfunc"), -1)

		var err error
		src, err = imports.Process(filename, src, nil)
		if err != nil {
			return err
		}

		fmt.Fprintln(w, "// generated by gen-mocks; DO NOT EDIT")
		fmt.Fprintln(w)
		w.Write(src)
	}
	return nil
}

// qualifyPkgRefs qualifies all refs to non-package-qualified non-builtin types in f so that they refer to definitions in pkg. E.g., 'func(x MyType) -> func (x pkg.MyType)'.
func qualifyPkgRefs(f *ast.FuncType, pkg string) {
	var qualify func(x ast.Expr) ast.Expr
	qualify = func(x ast.Expr) ast.Expr {
		switch y := x.(type) {
		case *ast.Ident:
			if ast.IsExported(y.Name) {
				return &ast.SelectorExpr{X: ast.NewIdent(pkg), Sel: y}
			}
		case *ast.StarExpr:
			y.X = qualify(y.X)
		case *ast.ArrayType:
			y.Elt = qualify(y.Elt)
		case *ast.MapType:
			y.Key = qualify(y.Key)
			y.Value = qualify(y.Value)
		}
		return x
	}
	for _, p := range f.Params.List {
		p.Type = qualify(p.Type)
	}
	for _, r := range f.Results.List {
		r.Type = qualify(r.Type)
	}
}

// synthesizeFieldNamesIfMissing adds synthesized variable names to fl
// if it contains fields with no name. E.g., the field list in
// `func(string, int)` would be converted to `func(v0 string, v1
// int)`.
func synthesizeFieldNamesIfMissing(fl *ast.FieldList) {
	for i, f := range fl.List {
		if len(f.Names) == 0 {
			f.Names = []*ast.Ident{ast.NewIdent(fmt.Sprintf("v%d", i))}
		}
	}
}

func fieldListToIdentList(fl *ast.FieldList) []ast.Expr {
	var fs []ast.Expr
	for _, f := range fl.List {
		for _, name := range f.Names {
			x := ast.Expr(ast.NewIdent(name.Name))
			fs = append(fs, x)
		}
	}
	return fs
}

func hasEllipsis(fl *ast.FieldList) bool {
	if fl.List == nil {
		return false
	}
	_, ok := fl.List[len(fl.List)-1].Type.(*ast.Ellipsis)
	return ok
}

func ellipsisIfNeeded(fl *ast.FieldList) token.Pos {
	if hasEllipsis(fl) {
		return 1
	}
	return 0
}

func astString(x ast.Expr) string {
	var buf bytes.Buffer
	if err := printer.Fprint(&buf, fset, x); err != nil {
		panic(err)
	}
	return buf.String()
}
<|endoftext|>


<commit_before>package loggen

import (
	"bufio"
	"fmt"
	"math"
	"math/rand"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

var (
	useragentList []string
	categoryList  []string
	endTime       = time.Now()
	currentTime   = endTime
)

func causeErr(errRate float64) bool {
	rand.Seed(time.Now().UnixNano())
	for i := 1.0; ; i *= 10 {
		if errRate*i >= 1.0 {
			n := rand.Intn(100 * int(i))
			if int(errRate*i) > n {
				return true
			} else {
				return false
			}
		}
	}
}

func floatToIntString(input float64) string {
	return strconv.Itoa(int(input))
}

func intToString(input int) string {
	return strconv.Itoa(input)
}

func randInt(min int, max int) int {
	return min + rand.Intn(max-min)
}

// Generate random number based on log-normal distribution
func randLogNormal(mu, sigma float64) float64 {
	s1 := rand.NewSource(time.Now().UnixNano())
	r1 := rand.New(s1).Float64()
	r2 := rand.New(s1).Float64()
	z := mu + sigma*math.Sqrt(-2.0*math.Log(r1))*math.Sin(2.0*math.Pi*r2)
	return math.Exp(z)
}

func returnNewList(path string) []string {
	var newList []string

	absPath, _ := filepath.Abs(path)
	fp, err := os.Open(absPath)
	if err != nil {
		panic(err)
	}
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanLines)

	for scanner.Scan() {
		newList = append(newList, scanner.Text())
	}

	return newList
}

func zitter(i int) int {
	rand.Seed(time.Now().UnixNano())
	min := i - randInt(1, 2)
	max := i + randInt(1, 2)
	if min < 0 {
		min = 1
	}
	return min + rand.Intn(max-min)
}

// TODO: exclude private IP address
func Ipv4Address() string {
	var ipStr string
	ipStr = intToString(randInt(1, 223)) + "."
	ipStr += intToString(randInt(0, 255)) + "."
	ipStr += intToString(randInt(0, 255)) + "."
	ipStr += intToString(randInt(0, 255))
	return ipStr
}

func RequestTime(i int) string {
	returnTime := currentTime.Add(time.Second * time.Duration(i))
	return returnTime.Format("02/Jan/2006:15:04:05 -0700")
}

func RequestType() string {
	s := []string{"GET", "POST", "PUT", "DELETE"}
	return s[rand.Intn(len(s))]
}

func ReturnStatusCode(errRate float64) string {
	rand.NewSource(time.Now().UnixNano())
	if causeErr(errRate) == false {
		return "200"
	} else {
		s := []string{"301", "403", "404", "500"}
		return s[rand.Intn(len(s))]
	}
}

func ReturnUserAgent() string {
	rand.Seed(time.Now().UTC().UnixNano())
	if len(useragentList) == 0 {
		useragentList = returnNewList(os.Getenv("GOPATH") + "/src/github.com/acroquest/apache-loggen-go/resources/useragents.txt")
	}
	useragent := useragentList[rand.Intn(len(useragentList))]
	return useragent
}

func ReturnRequest() string {
	if len(categoryList) == 0 {
		categoryList = returnNewList(os.Getenv("GOPATH") + "/src/github.com/acroquest/apache-loggen-go/resources/categories.txt")
	}
	category := categoryList[rand.Intn(len(categoryList))]

	i := rand.Intn(10)
	if i < 7 {
		return "\"" + RequestType() + " /category/" + category + " HTTP/1.1\" "
	} else {
		return "\"" + RequestType() + " /" + category + "/" + intToString(randInt(1, 999)) + " HTTP/1.1\" "
	}
}

func ReturnReferer() string {
	referer := "-"
	return "\"" + referer + "\""
}

func ReturnRecord(i int, errRate float64) string {
	bytes := floatToIntString(randLogNormal(0.0, 0.5) * 2000)
	referer := ReturnReferer()
	responseTime := floatToIntString(20000 * randLogNormal(0.0, 0.5))
	return Ipv4Address() + " - - [" + RequestTime(i) + "] " + ReturnRequest() + ReturnStatusCode(errRate) + " " + bytes + " " + referer + " \"" + ReturnUserAgent() + "\" " + responseTime
}

// TODO change the amount of log data every day.
func GenerateLog(days int, errRate float64) {
	var weight int
	currentTime = endTime.Add(-24 * time.Hour * time.Duration(days))
	beforeHour := endTime.Hour()

	// generating log data every 1 second
	for i := 0; endTime.Sub(currentTime.Add(time.Second*time.Duration(i))) >= 0; i += 1 {
		hour := currentTime.Add(time.Second * time.Duration(i)).Hour()
		rand.Seed(time.Now().UnixNano())
		j := rand.Intn(10)

		// add weight for adding variation to the amount of data
		if hour != beforeHour {
			weight = zitter(randInt(1, 3))
			beforeHour = hour
		}

		switch {
		case hour >= 1 && hour <= 5:
			if j <= 2+weight {
				fmt.Println(ReturnRecord(i, errRate))
			}
		case hour >= 6 && hour <= 9:
			if j <= 4+weight {
				fmt.Println(ReturnRecord(i, errRate))
			}
		case hour >= 10 && hour <= 17:
			if j <= 6+weight {
				fmt.Println(ReturnRecord(i, errRate))
			}
		case hour >= 18 && hour <= 23:
			if j <= 6+weight {
				fmt.Println(ReturnRecord(i, errRate))
			}
		default:
			if j <= 4+weight {
				fmt.Println(ReturnRecord(i, errRate))
			}
		}
	}
}
<commit_msg>modify function name<commit_after>package loggen

import (
	"bufio"
	"fmt"
	"math"
	"math/rand"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

var (
	useragentList []string
	categoryList  []string
	endTime       = time.Now()
	currentTime   = endTime
)

func causeErr(errRate float64) bool {
	rand.Seed(time.Now().UnixNano())
	for i := 1.0; ; i *= 10 {
		if errRate*i >= 1.0 {
			n := rand.Intn(100 * int(i))
			if int(errRate*i) > n {
				return true
			} else {
				return false
			}
		}
	}
}

func floatToIntString(input float64) string {
	return strconv.Itoa(int(input))
}

func intToString(input int) string {
	return strconv.Itoa(input)
}

func randInt(min int, max int) int {
	return min + rand.Intn(max-min)
}

// Generate random number based on log-normal distribution
func randLogNormal(mu, sigma float64) float64 {
	s1 := rand.NewSource(time.Now().UnixNano())
	r1 := rand.New(s1).Float64()
	r2 := rand.New(s1).Float64()
	z := mu + sigma*math.Sqrt(-2.0*math.Log(r1))*math.Sin(2.0*math.Pi*r2)
	return math.Exp(z)
}

func returnNewList(path string) []string {
	var newList []string

	absPath, _ := filepath.Abs(path)
	fp, err := os.Open(absPath)
	if err != nil {
		panic(err)
	}
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanLines)

	for scanner.Scan() {
		newList = append(newList, scanner.Text())
	}

	return newList
}

func zitter(i int) int {
	rand.Seed(time.Now().UnixNano())
	min := i - randInt(1, 2)
	max := i + randInt(1, 2)
	if min < 0 {
		min = 1
	}
	return min + rand.Intn(max-min)
}

// TODO: exclude private IP address
func Ipv4Address() string {
	var ipStr string
	ipStr = intToString(randInt(1, 223)) + "."
	ipStr += intToString(randInt(0, 255)) + "."
	ipStr += intToString(randInt(0, 255)) + "."
	ipStr += intToString(randInt(0, 255))
	return ipStr
}

func RequestTime(i int) string {
	returnTime := currentTime.Add(time.Second * time.Duration(i))
	return returnTime.Format("02/Jan/2006:15:04:05 -0700")
}

func RequestType() string {
	s := []string{"GET", "POST", "PUT", "DELETE"}
	return s[rand.Intn(len(s))]
}

func HttpStatusCode(errRate float64) string {
	rand.NewSource(time.Now().UnixNano())
	if causeErr(errRate) == false {
		return "200"
	} else {
		s := []string{"301", "403", "404", "500"}
		return s[rand.Intn(len(s))]
	}
}

func UserAgent() string {
	rand.Seed(time.Now().UTC().UnixNano())
	if len(useragentList) == 0 {
		useragentList = returnNewList(os.Getenv("GOPATH") + "/src/github.com/acroquest/apache-loggen-go/resources/useragents.txt")
	}
	useragent := useragentList[rand.Intn(len(useragentList))]
	return useragent
}

func Request() string {
	if len(categoryList) == 0 {
		categoryList = returnNewList(os.Getenv("GOPATH") + "/src/github.com/acroquest/apache-loggen-go/resources/categories.txt")
	}
	category := categoryList[rand.Intn(len(categoryList))]

	i := rand.Intn(10)
	if i < 7 {
		return "\"" + RequestType() + " /category/" + category + " HTTP/1.1\" "
	} else {
		return "\"" + RequestType() + " /" + category + "/" + intToString(randInt(1, 999)) + " HTTP/1.1\" "
	}
}

func Referer() string {
	referer := "-"
	return "\"" + referer + "\""
}

func SizeofBytes(bytes int) string {
	return floatToIntString(randLogNormal(0.0, 0.5) * float64(bytes))
}

func ResponseTime(millisecond int) string {
	return floatToIntString(randLogNormal(0.0, 0.5) * float64(millisecond))
}

func GetRecord(i int, errRate float64) string {
	return Ipv4Address() + " - - [" + RequestTime(i) + "] " + Request() + HttpStatusCode(errRate) + " " + SizeofBytes(2000) + " " + Referer() + " \"" + UserAgent() + "\" " + ResponseTime(20000)
}

// TODO change the amount of log data every day.
func GenerateLog(days int, errRate float64) {
	var weight int
	currentTime = endTime.Add(-24 * time.Hour * time.Duration(days))
	beforeHour := endTime.Hour()

	// generating log data every 1 second
	for i := 0; endTime.Sub(currentTime.Add(time.Second*time.Duration(i))) >= 0; i += 1 {
		hour := currentTime.Add(time.Second * time.Duration(i)).Hour()
		rand.Seed(time.Now().UnixNano())
		j := rand.Intn(10)

		// add weight for adding variation to the amount of data
		if hour != beforeHour {
			weight = zitter(randInt(1, 3))
			beforeHour = hour
		}

		switch {
		case hour >= 1 && hour <= 5:
			if j <= 2+weight {
				fmt.Println(GetRecord(i, errRate))
			}
		case hour >= 6 && hour <= 9:
			if j <= 4+weight {
				fmt.Println(GetRecord(i, errRate))
			}
		case hour >= 10 && hour <= 17:
			if j <= 6+weight {
				fmt.Println(GetRecord(i, errRate))
			}
		case hour >= 18 && hour <= 23:
			if j <= 6+weight {
				fmt.Println(GetRecord(i, errRate))
			}
		default:
			if j <= 4+weight {
				fmt.Println(GetRecord(i, errRate))
			}
		}
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2016 by Richard A. Wilkes. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, version 2.0. If a copy of the MPL was not distributed with
// this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// This Source Code Form is "Incompatible With Secondary Licenses", as
// defined by the Mozilla Public License, version 2.0.

package geom

import (
	"fmt"
	"github.com/richardwilkes/xmath"
)

// Size defines a width and height.
type Size struct {
	Width, Height float32
}

// Add modifies this Size by adding the supplied Size.
func (s *Size) Add(size Size) {
	s.Width += size.Width
	s.Height += size.Height
}

// AddInsets modifies this Size by expanding it to accomodate the specified insets.
func (s *Size) AddInsets(insets Insets) {
	s.Width += insets.Left + insets.Right
	s.Height += insets.Top + insets.Bottom
}

// Subtract modifies this Size by subtracting the supplied Size.
func (s *Size) Subtract(size Size) {
	s.Width -= size.Width
	s.Height -= size.Height
}

// SubtractInsets modifies this Size by reducing it to accomodate the specified insets.
func (s *Size) SubtractInsets(insets Insets) {
	s.Width -= insets.Left + insets.Right
	s.Height -= insets.Top + insets.Bottom
}

// GrowToInteger modifies this Size such that its width and height are both the smallest integers
// greater than or equal to their original values.
func (s *Size) GrowToInteger() {
	s.Width = xmath.CeilFloat32(s.Width)
	s.Height = xmath.CeilFloat32(s.Height)
}

// ConstrainForHint ensures this size is no larger than the hint. Hint values less than zero are
// ignored.
func (s *Size) ConstrainForHint(hint Size) {
	if hint.Width >= 0 && s.Width > hint.Width {
		s.Width = hint.Width
	}
	if hint.Height >= 0 && s.Height > hint.Height {
		s.Height = hint.Height
	}
}

// String implements the fmt.Stringer interface.
func (s Size) String() string {
	return fmt.Sprintf("%v, %v", s.Width, s.Height)
}
<commit_msg>Add Min() and Max()<commit_after>// Copyright (c) 2016 by Richard A. Wilkes. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, version 2.0. If a copy of the MPL was not distributed with
// this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// This Source Code Form is "Incompatible With Secondary Licenses", as
// defined by the Mozilla Public License, version 2.0.

package geom

import (
	"fmt"
	"github.com/richardwilkes/xmath"
)

// Size defines a width and height.
type Size struct {
	Width, Height float32
}

// Add modifies this Size by adding the supplied Size.
func (s *Size) Add(size Size) {
	s.Width += size.Width
	s.Height += size.Height
}

// AddInsets modifies this Size by expanding it to accomodate the specified insets.
func (s *Size) AddInsets(insets Insets) {
	s.Width += insets.Left + insets.Right
	s.Height += insets.Top + insets.Bottom
}

// Subtract modifies this Size by subtracting the supplied Size.
func (s *Size) Subtract(size Size) {
	s.Width -= size.Width
	s.Height -= size.Height
}

// SubtractInsets modifies this Size by reducing it to accomodate the specified insets.
func (s *Size) SubtractInsets(insets Insets) {
	s.Width -= insets.Left + insets.Right
	s.Height -= insets.Top + insets.Bottom
}

// GrowToInteger modifies this Size such that its width and height are both the smallest integers
// greater than or equal to their original values.
func (s *Size) GrowToInteger() {
	s.Width = xmath.CeilFloat32(s.Width)
	s.Height = xmath.CeilFloat32(s.Height)
}

// ConstrainForHint ensures this size is no larger than the hint. Hint values less than zero are
// ignored.
func (s *Size) ConstrainForHint(hint Size) {
	if hint.Width >= 0 && s.Width > hint.Width {
		s.Width = hint.Width
	}
	if hint.Height >= 0 && s.Height > hint.Height {
		s.Height = hint.Height
	}
}

// Min modifies this Size to contain the smallest values between itself and 'other'.
func (s *Size) Min(other Size) {
	if s.Width > other.Width {
		s.Width = other.Width
	}
	if s.Height > other.Height {
		s.Height = other.Height
	}
}

// Max modifies this Size to contain the largest values between itself and 'other'.
func (s *Size) Max(other Size) {
	if s.Width < other.Width {
		s.Width = other.Width
	}
	if s.Height < other.Height {
		s.Height = other.Height
	}
}

// String implements the fmt.Stringer interface.
func (s Size) String() string {
	return fmt.Sprintf("%v, %v", s.Width, s.Height)
}
<|endoftext|>


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

// +build !netgo,!android

package engi

import (
	"image"
	"image/draw"
	_ "image/png"
	"io"
	"io/ioutil"
	"log"
	"os"
	"runtime"

	"azul3d.org/native/glfw.v4"
	"github.com/ajhager/webgl"
)

var window *glfw.Window

func init() {
	runtime.LockOSThread()
}

// fatalErr calls log.Fatal with the given error if it is non-nil.
func fatalErr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func run(title string, width, height int, fullscreen bool) {
	defer runtime.UnlockOSThread()
	runtime.GOMAXPROCS(runtime.NumCPU())
	fatalErr(glfw.Init())

	monitor, err := glfw.GetPrimaryMonitor()
	fatalErr(err)
	mode, err := monitor.GetVideoMode()
	fatalErr(err)

	if fullscreen {
		width = mode.Width
		height = mode.Height
		fatalErr(glfw.WindowHint(glfw.Decorated, 0))
	} else {
		monitor = nil
	}

	fatalErr(glfw.WindowHint(glfw.ContextVersionMajor, 2))
	fatalErr(glfw.WindowHint(glfw.ContextVersionMinor, 1))

	window, err = glfw.CreateWindow(width, height, title, monitor, nil)
	fatalErr(err)
	window.MakeContextCurrent()

	if !fullscreen {
		fatalErr(window.SetPosition((mode.Width-width)/2, (mode.Height-height)/2))
	}

	width, height, err = window.GetFramebufferSize()
	fatalErr(err)

	fatalErr(glfw.SwapInterval(1))

	gl = webgl.NewContext()

	gl.Viewport(0, 0, width, height)
	window.SetFramebufferSizeCallback(func(window *glfw.Window, w, h int) {
		width, height, err = window.GetFramebufferSize()
		fatalErr(err)
		gl.Viewport(0, 0, width, height)
		responder.Resize(w, h)
	})

	window.SetCursorPositionCallback(func(window *glfw.Window, x, y float64) {
		responder.Mouse(float32(x), float32(y), MOVE)
	})

	window.SetMouseButtonCallback(func(window *glfw.Window, b glfw.MouseButton, a glfw.Action, m glfw.ModifierKey) {
		x, y, err := window.GetCursorPosition()
		fatalErr(err)
		if a == glfw.Press {
			responder.Mouse(float32(x), float32(y), PRESS)
		} else {
			responder.Mouse(float32(x), float32(y), RELEASE)
		}
	})

	window.SetScrollCallback(func(window *glfw.Window, xoff, yoff float64) {
		responder.Scroll(float32(yoff))
	})

	window.SetKeyCallback(func(window *glfw.Window, k glfw.Key, s int, a glfw.Action, m glfw.ModifierKey) {
		if a == glfw.Press {
			responder.Key(Key(k), Modifier(m), PRESS)
		} else if a == glfw.Release {
			responder.Key(Key(k), Modifier(m), RELEASE)
		}
	})

	window.SetCharacterCallback(func(window *glfw.Window, char rune) {
		responder.Type(char)
	})

	setupAudio()

	responder.Preload()
	Files.Load(func() {})
	responder.Setup()

	shouldClose, err := window.ShouldClose()
	fatalErr(err)
	for !shouldClose {
		responder.Update(Time.Delta())
		gl.Clear(gl.COLOR_BUFFER_BIT)
		responder.Render()
		fatalErr(window.SwapBuffers())
		fatalErr(glfw.PollEvents())
		Time.Tick()

		shouldClose, err = window.ShouldClose()
		fatalErr(err)
	}
	fatalErr(window.Destroy())
	fatalErr(glfw.Terminate())
	responder.Close()
}

func width() float32 {
	width, _, err := window.GetSize()
	fatalErr(err)
	return float32(width)
}

func height() float32 {
	_, height, err := window.GetSize()
	fatalErr(err)
	return float32(height)
}

func exit() {
	cleanupAudio()
	fatalErr(window.SetShouldClose(true))
}

func init() {
	Dash = Key(glfw.KeyMinus)
	Apostrophe = Key(glfw.KeyApostrophe)
	Semicolon = Key(glfw.KeySemicolon)
	Equals = Key(glfw.KeyEqual)
	Comma = Key(glfw.KeyComma)
	Period = Key(glfw.KeyPeriod)
	Slash = Key(glfw.KeySlash)
	Backslash = Key(glfw.KeyBackslash)
	Backspace = Key(glfw.KeyBackspace)
	Tab = Key(glfw.KeyTab)
	CapsLock = Key(glfw.KeyCapsLock)
	Space = Key(glfw.KeySpace)
	Enter = Key(glfw.KeyEnter)
	Escape = Key(glfw.KeyEscape)
	Insert = Key(glfw.KeyInsert)
	PrintScreen = Key(glfw.KeyPrintScreen)
	Delete = Key(glfw.KeyDelete)
	PageUp = Key(glfw.KeyPageUp)
	PageDown = Key(glfw.KeyPageDown)
	Home = Key(glfw.KeyHome)
	End = Key(glfw.KeyEnd)
	Pause = Key(glfw.KeyPause)
	ScrollLock = Key(glfw.KeyScrollLock)
	ArrowLeft = Key(glfw.KeyLeft)
	ArrowRight = Key(glfw.KeyRight)
	ArrowDown = Key(glfw.KeyDown)
	ArrowUp = Key(glfw.KeyUp)
	LeftBracket = Key(glfw.KeyLeftBracket)
	LeftShift = Key(glfw.KeyLeftShift)
	LeftControl = Key(glfw.KeyLeftControl)
	LeftSuper = Key(glfw.KeyLeftSuper)
	LeftAlt = Key(glfw.KeyLeftAlt)
	RightBracket = Key(glfw.KeyRightBracket)
	RightShift = Key(glfw.KeyRightShift)
	RightControl = Key(glfw.KeyRightControl)
	RightSuper = Key(glfw.KeyRightSuper)
	RightAlt = Key(glfw.KeyRightAlt)
	Zero = Key(glfw.Key0)
	One = Key(glfw.Key1)
	Two = Key(glfw.Key2)
	Three = Key(glfw.Key3)
	Four = Key(glfw.Key4)
	Five = Key(glfw.Key5)
	Six = Key(glfw.Key6)
	Seven = Key(glfw.Key7)
	Eight = Key(glfw.Key8)
	Nine = Key(glfw.Key9)
	F1 = Key(glfw.KeyF1)
	F2 = Key(glfw.KeyF2)
	F3 = Key(glfw.KeyF3)
	F4 = Key(glfw.KeyF4)
	F5 = Key(glfw.KeyF5)
	F6 = Key(glfw.KeyF6)
	F7 = Key(glfw.KeyF7)
	F8 = Key(glfw.KeyF8)
	F9 = Key(glfw.KeyF9)
	F10 = Key(glfw.KeyF10)
	F11 = Key(glfw.KeyF11)
	F12 = Key(glfw.KeyF12)
	A = Key(glfw.KeyA)
	B = Key(glfw.KeyB)
	C = Key(glfw.KeyC)
	D = Key(glfw.KeyD)
	E = Key(glfw.KeyE)
	F = Key(glfw.KeyF)
	G = Key(glfw.KeyG)
	H = Key(glfw.KeyH)
	I = Key(glfw.KeyI)
	J = Key(glfw.KeyJ)
	K = Key(glfw.KeyK)
	L = Key(glfw.KeyL)
	M = Key(glfw.KeyM)
	N = Key(glfw.KeyN)
	O = Key(glfw.KeyO)
	P = Key(glfw.KeyP)
	Q = Key(glfw.KeyQ)
	R = Key(glfw.KeyR)
	S = Key(glfw.KeyS)
	T = Key(glfw.KeyT)
	U = Key(glfw.KeyU)
	V = Key(glfw.KeyV)
	W = Key(glfw.KeyW)
	X = Key(glfw.KeyX)
	Y = Key(glfw.KeyY)
	Z = Key(glfw.KeyZ)
	NumLock = Key(glfw.KeyNumLock)
	NumMultiply = Key(glfw.KeyKpMultiply)
	NumDivide = Key(glfw.KeyKpDivide)
	NumAdd = Key(glfw.KeyKpAdd)
	NumSubtract = Key(glfw.KeyKpSubtract)
	NumZero = Key(glfw.KeyKp0)
	NumOne = Key(glfw.KeyKp1)
	NumTwo = Key(glfw.KeyKp2)
	NumThree = Key(glfw.KeyKp3)
	NumFour = Key(glfw.KeyKp4)
	NumFive = Key(glfw.KeyKp5)
	NumSix = Key(glfw.KeyKp6)
	NumSeven = Key(glfw.KeyKp7)
	NumEight = Key(glfw.KeyKp8)
	NumNine = Key(glfw.KeyKp9)
	NumDecimal = Key(glfw.KeyKpDecimal)
	NumEnter = Key(glfw.KeyKpEnter)
}

func NewImageObject(img *image.NRGBA) *ImageObject {
	return &ImageObject{img}
}

type ImageObject struct {
	data *image.NRGBA
}

func (i *ImageObject) Data() interface{} {
	return i.data
}

func (i *ImageObject) Width() int {
	return i.data.Rect.Max.X
}

func (i *ImageObject) Height() int {
	return i.data.Rect.Max.Y
}

func loadImage(r Resource) (Image, error) {
	file, err := os.Open(r.url)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	img, _, err := image.Decode(file)
	if err != nil {
		return nil, err
	}

	b := img.Bounds()
	newm := image.NewNRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
	draw.Draw(newm, newm.Bounds(), img, b.Min, draw.Src)

	return &ImageObject{newm}, nil
}

func loadJson(r Resource) (string, error) {
	file, err := ioutil.ReadFile(r.url)
	if err != nil {
		return "", err
	}
	return string(file), nil
}

type Assets struct {
	queue  []string
	cache  map[string]Image
	loads  int
	errors int
}

func NewAssets() *Assets {
	return &Assets{make([]string, 0), make(map[string]Image), 0, 0}
}

func (a *Assets) Image(path string) {
	a.queue = append(a.queue, path)
}

func (a *Assets) Get(path string) Image {
	return a.cache[path]
}

func (a *Assets) Load(onFinish func()) {
	if len(a.queue) == 0 {
		onFinish()
	} else {
		for _, path := range a.queue {
			img := LoadImage(path)
			a.cache[path] = img
		}
	}
}

func LoadImage(data interface{}) Image {
	var m image.Image

	switch data := data.(type) {
	default:
		log.Fatal("NewTexture needs a string or io.Reader")
	case string:
		file, err := os.Open(data)
		if err != nil {
			log.Fatal(err)
		}
		defer file.Close()
		img, _, err := image.Decode(file)
		if err != nil {
			log.Fatal(err)
		}
		m = img
	case io.Reader:
		img, _, err := image.Decode(data)
		if err != nil {
			log.Fatal(err)
		}
		m = img
	case image.Image:
		m = data
	}

	b := m.Bounds()
	newm := image.NewNRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
	draw.Draw(newm, newm.Bounds(), m, b.Min, draw.Src)

	return &ImageObject{newm}
}
<commit_msg>AppDir() helper, scale fullscreen<commit_after>// Copyright 2014 Joseph Hager. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build !netgo,!android

package engi

import (
	"image"
	"image/draw"
	_ "image/png"
	"io"
	"io/ioutil"
	"log"
	"os"
	"runtime"

	"azul3d.org/native/glfw.v4"
	"github.com/ajhager/webgl"
	"github.com/kardianos/osext"
)

var window *glfw.Window

func init() {
	runtime.LockOSThread()
}

// fatalErr calls log.Fatal with the given error if it is non-nil.
func fatalErr(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func run(title string, width, height int, fullscreen bool) {
	defer runtime.UnlockOSThread()
	runtime.GOMAXPROCS(runtime.NumCPU())
	fatalErr(glfw.Init())

	monitor, err := glfw.GetPrimaryMonitor()
	fatalErr(err)
	mode, err := monitor.GetVideoMode()
	fatalErr(err)

	if fullscreen {
		fatalErr(glfw.WindowHint(glfw.Decorated, 0))
	} else {
		monitor = nil
	}

	fatalErr(glfw.WindowHint(glfw.ContextVersionMajor, 2))
	fatalErr(glfw.WindowHint(glfw.ContextVersionMinor, 1))

	window, err = glfw.CreateWindow(width, height, title, monitor, nil)
	fatalErr(err)
	window.MakeContextCurrent()

	if !fullscreen {
		fatalErr(window.SetPosition((mode.Width-width)/2, (mode.Height-height)/2))
	}

	width, height, err = window.GetFramebufferSize()
	fatalErr(err)

	fatalErr(glfw.SwapInterval(1))

	gl = webgl.NewContext()

	gl.Viewport(0, 0, width, height)
	window.SetFramebufferSizeCallback(func(window *glfw.Window, w, h int) {
		width, height, err = window.GetFramebufferSize()
		fatalErr(err)
		gl.Viewport(0, 0, width, height)
		responder.Resize(w, h)
	})

	window.SetCursorPositionCallback(func(window *glfw.Window, x, y float64) {
		responder.Mouse(float32(x), float32(y), MOVE)
	})

	window.SetMouseButtonCallback(func(window *glfw.Window, b glfw.MouseButton, a glfw.Action, m glfw.ModifierKey) {
		x, y, err := window.GetCursorPosition()
		fatalErr(err)
		if a == glfw.Press {
			responder.Mouse(float32(x), float32(y), PRESS)
		} else {
			responder.Mouse(float32(x), float32(y), RELEASE)
		}
	})

	window.SetScrollCallback(func(window *glfw.Window, xoff, yoff float64) {
		responder.Scroll(float32(yoff))
	})

	window.SetKeyCallback(func(window *glfw.Window, k glfw.Key, s int, a glfw.Action, m glfw.ModifierKey) {
		if a == glfw.Press {
			responder.Key(Key(k), Modifier(m), PRESS)
		} else if a == glfw.Release {
			responder.Key(Key(k), Modifier(m), RELEASE)
		}
	})

	window.SetCharacterCallback(func(window *glfw.Window, char rune) {
		responder.Type(char)
	})

	setupAudio()

	responder.Preload()
	Files.Load(func() {})
	responder.Setup()

	shouldClose, err := window.ShouldClose()
	fatalErr(err)
	for !shouldClose {
		responder.Update(Time.Delta())
		gl.Clear(gl.COLOR_BUFFER_BIT)
		responder.Render()
		fatalErr(window.SwapBuffers())
		fatalErr(glfw.PollEvents())
		Time.Tick()

		shouldClose, err = window.ShouldClose()
		fatalErr(err)
	}
	fatalErr(window.Destroy())
	fatalErr(glfw.Terminate())
	responder.Close()
}

func width() float32 {
	width, _, err := window.GetSize()
	fatalErr(err)
	return float32(width)
}

func height() float32 {
	_, height, err := window.GetSize()
	fatalErr(err)
	return float32(height)
}

func exit() {
	cleanupAudio()
	fatalErr(window.SetShouldClose(true))
}

func init() {
	Dash = Key(glfw.KeyMinus)
	Apostrophe = Key(glfw.KeyApostrophe)
	Semicolon = Key(glfw.KeySemicolon)
	Equals = Key(glfw.KeyEqual)
	Comma = Key(glfw.KeyComma)
	Period = Key(glfw.KeyPeriod)
	Slash = Key(glfw.KeySlash)
	Backslash = Key(glfw.KeyBackslash)
	Backspace = Key(glfw.KeyBackspace)
	Tab = Key(glfw.KeyTab)
	CapsLock = Key(glfw.KeyCapsLock)
	Space = Key(glfw.KeySpace)
	Enter = Key(glfw.KeyEnter)
	Escape = Key(glfw.KeyEscape)
	Insert = Key(glfw.KeyInsert)
	PrintScreen = Key(glfw.KeyPrintScreen)
	Delete = Key(glfw.KeyDelete)
	PageUp = Key(glfw.KeyPageUp)
	PageDown = Key(glfw.KeyPageDown)
	Home = Key(glfw.KeyHome)
	End = Key(glfw.KeyEnd)
	Pause = Key(glfw.KeyPause)
	ScrollLock = Key(glfw.KeyScrollLock)
	ArrowLeft = Key(glfw.KeyLeft)
	ArrowRight = Key(glfw.KeyRight)
	ArrowDown = Key(glfw.KeyDown)
	ArrowUp = Key(glfw.KeyUp)
	LeftBracket = Key(glfw.KeyLeftBracket)
	LeftShift = Key(glfw.KeyLeftShift)
	LeftControl = Key(glfw.KeyLeftControl)
	LeftSuper = Key(glfw.KeyLeftSuper)
	LeftAlt = Key(glfw.KeyLeftAlt)
	RightBracket = Key(glfw.KeyRightBracket)
	RightShift = Key(glfw.KeyRightShift)
	RightControl = Key(glfw.KeyRightControl)
	RightSuper = Key(glfw.KeyRightSuper)
	RightAlt = Key(glfw.KeyRightAlt)
	Zero = Key(glfw.Key0)
	One = Key(glfw.Key1)
	Two = Key(glfw.Key2)
	Three = Key(glfw.Key3)
	Four = Key(glfw.Key4)
	Five = Key(glfw.Key5)
	Six = Key(glfw.Key6)
	Seven = Key(glfw.Key7)
	Eight = Key(glfw.Key8)
	Nine = Key(glfw.Key9)
	F1 = Key(glfw.KeyF1)
	F2 = Key(glfw.KeyF2)
	F3 = Key(glfw.KeyF3)
	F4 = Key(glfw.KeyF4)
	F5 = Key(glfw.KeyF5)
	F6 = Key(glfw.KeyF6)
	F7 = Key(glfw.KeyF7)
	F8 = Key(glfw.KeyF8)
	F9 = Key(glfw.KeyF9)
	F10 = Key(glfw.KeyF10)
	F11 = Key(glfw.KeyF11)
	F12 = Key(glfw.KeyF12)
	A = Key(glfw.KeyA)
	B = Key(glfw.KeyB)
	C = Key(glfw.KeyC)
	D = Key(glfw.KeyD)
	E = Key(glfw.KeyE)
	F = Key(glfw.KeyF)
	G = Key(glfw.KeyG)
	H = Key(glfw.KeyH)
	I = Key(glfw.KeyI)
	J = Key(glfw.KeyJ)
	K = Key(glfw.KeyK)
	L = Key(glfw.KeyL)
	M = Key(glfw.KeyM)
	N = Key(glfw.KeyN)
	O = Key(glfw.KeyO)
	P = Key(glfw.KeyP)
	Q = Key(glfw.KeyQ)
	R = Key(glfw.KeyR)
	S = Key(glfw.KeyS)
	T = Key(glfw.KeyT)
	U = Key(glfw.KeyU)
	V = Key(glfw.KeyV)
	W = Key(glfw.KeyW)
	X = Key(glfw.KeyX)
	Y = Key(glfw.KeyY)
	Z = Key(glfw.KeyZ)
	NumLock = Key(glfw.KeyNumLock)
	NumMultiply = Key(glfw.KeyKpMultiply)
	NumDivide = Key(glfw.KeyKpDivide)
	NumAdd = Key(glfw.KeyKpAdd)
	NumSubtract = Key(glfw.KeyKpSubtract)
	NumZero = Key(glfw.KeyKp0)
	NumOne = Key(glfw.KeyKp1)
	NumTwo = Key(glfw.KeyKp2)
	NumThree = Key(glfw.KeyKp3)
	NumFour = Key(glfw.KeyKp4)
	NumFive = Key(glfw.KeyKp5)
	NumSix = Key(glfw.KeyKp6)
	NumSeven = Key(glfw.KeyKp7)
	NumEight = Key(glfw.KeyKp8)
	NumNine = Key(glfw.KeyKp9)
	NumDecimal = Key(glfw.KeyKpDecimal)
	NumEnter = Key(glfw.KeyKpEnter)
}

func NewImageObject(img *image.NRGBA) *ImageObject {
	return &ImageObject{img}
}

type ImageObject struct {
	data *image.NRGBA
}

func (i *ImageObject) Data() interface{} {
	return i.data
}

func (i *ImageObject) Width() int {
	return i.data.Rect.Max.X
}

func (i *ImageObject) Height() int {
	return i.data.Rect.Max.Y
}

func loadImage(r Resource) (Image, error) {
	file, err := os.Open(r.url)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	img, _, err := image.Decode(file)
	if err != nil {
		return nil, err
	}

	b := img.Bounds()
	newm := image.NewNRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
	draw.Draw(newm, newm.Bounds(), img, b.Min, draw.Src)

	return &ImageObject{newm}, nil
}

func loadJson(r Resource) (string, error) {
	file, err := ioutil.ReadFile(r.url)
	if err != nil {
		return "", err
	}
	return string(file), nil
}

type Assets struct {
	queue  []string
	cache  map[string]Image
	loads  int
	errors int
}

func NewAssets() *Assets {
	return &Assets{make([]string, 0), make(map[string]Image), 0, 0}
}

func (a *Assets) Image(path string) {
	a.queue = append(a.queue, path)
}

func (a *Assets) Get(path string) Image {
	return a.cache[path]
}

func (a *Assets) Load(onFinish func()) {
	if len(a.queue) == 0 {
		onFinish()
	} else {
		for _, path := range a.queue {
			img := LoadImage(path)
			a.cache[path] = img
		}
	}
}

func LoadImage(data interface{}) Image {
	var m image.Image

	switch data := data.(type) {
	default:
		log.Fatal("NewTexture needs a string or io.Reader")
	case string:
		file, err := os.Open(data)
		if err != nil {
			log.Fatal(err)
		}
		defer file.Close()
		img, _, err := image.Decode(file)
		if err != nil {
			log.Fatal(err)
		}
		m = img
	case io.Reader:
		img, _, err := image.Decode(data)
		if err != nil {
			log.Fatal(err)
		}
		m = img
	case image.Image:
		m = data
	}

	b := m.Bounds()
	newm := image.NewNRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
	draw.Draw(newm, newm.Bounds(), m, b.Min, draw.Src)

	return &ImageObject{newm}
}

func AppDir() string {
	dir, err := osext.ExecutableFolder()
	fatalErr(err)
	return dir
}
<|endoftext|>


<commit_before>package go_flarum

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

const COOKIE_REMEMBER_ME = "flarum_remember"
const COOKIE_SESSION = "flarum_session"
const DAYS_MULTIPLIER = 60 * 60 * 24
const FORUM_API_SUFFIX = "/api"

type FlarumClient struct {
	url    string
	token  string
	maxAge int
}

/*
 * Creates a new client for the Flarum forum.
	Requires:
	- Forum URL: without /api suffix and without trailing slash. eg. http://myforum.example.com
	- Token: The API token that you set in your `_api_keys` table
	- maxAge: Number of days for the cookie to be valid
*/
func NewClient(url string, token string, maxAge int) *FlarumClient {

	client := FlarumClient{
		url:    url,
		token:  token,
		maxAge: maxAge,
	}
	return &client
}

/*
 * Sends HTTP request to forum API instance
 */
func (fc FlarumClient) sendApiRequest(method string, path string, payload map[string]interface{}) (response map[string]interface{}, err error) {
	url := request.PROTOCOL_HTTP + fc.url + FORUM_API_SUFFIX + path

	// Convert map to a JSON string
	payloadString, err := json.Marshal(payload)

	req, err := http.NewRequest(method, url, bytes.NewBuffer(payloadString))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Token "+fc.token+"; userId=1")

	client := &http.Client{}
	resp, err := client.Do(req)

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	var bodyMap map[string]interface{}
	json.Unmarshal(body, &bodyMap)
	return bodyMap, err
}
<commit_msg>Check for response code<commit_after>package go_flarum

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

const COOKIE_REMEMBER_ME = "flarum_remember"
const COOKIE_SESSION = "flarum_session"
const DAYS_MULTIPLIER = 60 * 60 * 24
const FORUM_API_SUFFIX = "/api"

type FlarumClient struct {
	url    string
	token  string
	maxAge int
}

/*
 * Creates a new client for the Flarum forum.
	Requires:
	- Forum URL: without /api suffix and without trailing slash. eg. http://myforum.example.com
	- Token: The API token that you set in your `_api_keys` table
	- maxAge: Number of days for the cookie to be valid
*/
func NewClient(url string, token string, maxAge int) *FlarumClient {

	client := FlarumClient{
		url:    url,
		token:  token,
		maxAge: maxAge,
	}
	return &client
}

/*
 * Sends HTTP request to forum API instance
 */
func (fc FlarumClient) sendApiRequest(method string, path string, payload map[string]interface{}) (response map[string]interface{}, err error) {
	url := request.PROTOCOL_HTTP + fc.url + FORUM_API_SUFFIX + path

	// Convert map to a JSON string
	payloadString, err := json.Marshal(payload)

	req, err := http.NewRequest(method, url, bytes.NewBuffer(payloadString))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Token "+fc.token+"; userId=1")

	client := &http.Client{}
	resp, err := client.Do(req)

	if err == nil {
		if resp.StatusCode != 200 {
			err = errors.New("Forum returned a code other than 200")
		} else {
			defer resp.Body.Close()
			body, _ := ioutil.ReadAll(resp.Body)
			var bodyMap map[string]interface{}
			json.Unmarshal(body, &bodyMap)
			return bodyMap, err
		}
	}

	return map[string]interface{}{}, err
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"flag"
	"fmt"
	"github.com/aurelien-rainone/go-gencon/containers"
	"go/format"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"text/template"
)

var (
	containee = flag.String("type", "", "type name of the containee; must be set")
	container = flag.String("cont", "", "type of the generic container; must be set")
	name      = flag.String("name", "", "override container name; default ContaineeContainer")
	output    = flag.String("output", "", "output file name; default srcdir/<type>_string.go")
	package_  = flag.String("pkg", "", "package name of the generated file; only for cli usage")
)

// Usage is a replacement usage function for the flags package.
func Usage() {
	fmt.Fprintf(os.Stderr, "Usage of %s with go generate:\n", os.Args[0])
	fmt.Fprintf(os.Stderr, "\tgo-gencon [flags] -type containee -cont container\n")
	fmt.Fprintf(os.Stderr, "To use %s on the command line -pkg must be provided\n", os.Args[0])
	fmt.Fprintf(os.Stderr, "Available generic containers:\n")
	fmt.Fprintf(os.Stderr, " - Stack")
	fmt.Fprintf(os.Stderr, " - BoundedStack")
	fmt.Fprintf(os.Stderr, "For more information, see:\n")
	fmt.Fprintf(os.Stderr, "\thttp://github.com/aurelien-rainone/go-gencon\n")
	fmt.Fprintf(os.Stderr, "Flags:\n")
	flag.PrintDefaults()
}

func main() {

	log.SetFlags(0)
	log.SetPrefix("go-gencon: ")
	flag.Usage = Usage
	flag.Parse()

	pkg := os.Getenv("GOPACKAGE")
	if pkg == "" {
		pkg = *package_
	}

	if len(*container) == 0 || len(*container) == 0 || pkg == "" {
		flag.Usage()
		os.Exit(2)
	}

	var (
		g    Generator // generator instance
		cter string    // type name of generate container
	)
	// TODO: string manipulation
	// TODO: string manipulation
	// TODO: string manipulation
	//cter = strings.ToUpper((*containee)[0]) + *containee[1:] + *container
	cter = *containee + *container
	if len(*name) > 0 {
		cter = *name
	}
	g.nfo = FileInfo{*containee, cter, pkg}
	g.contType = *container
	g.Printf(fmt.Sprintln("//", "$GOPACKAGE", os.Getenv("GOPACKAGE")))

	wd, _ := os.Getwd()
	g.Printf(fmt.Sprintln("//", "Getwd()", wd))
	g.Printf(fmt.Sprintln("//", "$GOFILE", os.Getenv("GOFILE")))
	g.Printf(fmt.Sprintln("//", "$GOPACKAGE", os.Getenv("GOPACKAGE")))

	// Print the header and package clause.
	g.Printf("// Code generated by \"go-gencon %s\"; DO NOT EDIT\n", strings.Join(os.Args[1:], " "))
	g.Printf("\n")
	//g.Printf("package %s", g.pkg.name)
	g.Printf("\n")
	//g.Printf("import \"fmt\"\n") // Used by all methods.

	// Format the output.
	src := g.format()

	// Write to file.
	outputName := *output
	if outputName == "" {
		baseName := fmt.Sprintf("%s_%s.go", *containee, *container)
		outputName = filepath.Join(".", strings.ToLower(baseName))
	}
	err := ioutil.WriteFile(outputName, src, 0644)
	if err != nil {
		log.Fatalf("writing output: %s", err)
	}

}

// Generator holds the state of the analysis. Primarily used to buffer
// the output for format.Source.
type Generator struct {
	buf      bytes.Buffer // Accumulated output.
	nfo      FileInfo     // Info needed to the generated file
	contType string       // container to generate
}

type FileInfo struct {
	Containee, Container, Package string
}

func (g *Generator) Printf(format string, args ...interface{}) {
	fmt.Fprintf(&g.buf, format, args...)
}

// format returns the gofmt-ed contents of the Generator's buffer.
func (g *Generator) format() []byte {
	// list supported containers
	containers := map[string]string{
		"boundedstack": containers.BoundedStack,
	}

	// create container template
	var (
		tmpl  *template.Template
		str   string
		err   error
		found bool
	)
	if str, found = containers[strings.ToLower(g.contType)]; !found {
		log.Fatalf("No template for container '%s'", g.contType)
	}
	if tmpl, err = template.New(g.contType).Parse(str); err != nil {
		panic(err)
	}
	err = tmpl.Execute(&g.buf, g.nfo)
	if err != nil {
		panic(err)
	}

	src, err := format.Source(g.buf.Bytes())
	if err != nil {
		// Should never happen, but can arise when developing this code.
		// The user can compile the output to see the error.
		log.Printf("warning: internal error: invalid Go generated: %s", err)
		log.Printf("warning: compile the package to analyze the error")
		return g.buf.Bytes()
	}
	return src
}
<commit_msg>Code cleaning<commit_after>package main

import (
	"bytes"
	"flag"
	"fmt"
	"github.com/aurelien-rainone/go-gencon/containers"
	"go/format"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"text/template"
)

var (
	containee = flag.String("type", "", "type name of the containee; must be set")
	container = flag.String("cont", "", "type of the generic container; must be set")
	name      = flag.String("name", "", "override container name; default ContaineeContainer")
	output    = flag.String("output", "", "output file name; default srcdir/<type>_string.go")
	pkg       = flag.String("pkg", "", "package name of the generated file; only for cli usage")
)

// Usage is a replacement usage function for the flags package.
func Usage() {
	fmt.Fprintf(os.Stderr, "Usage of %s with go generate:\n", os.Args[0])
	fmt.Fprintf(os.Stderr, "\tgo-gencon [flags] -type containee -cont container\n")
	fmt.Fprintf(os.Stderr, "To use %s on the command line -pkg must be provided\n", os.Args[0])
	fmt.Fprintf(os.Stderr, "Available generic containers:\n")
	fmt.Fprintf(os.Stderr, " - Stack")
	fmt.Fprintf(os.Stderr, " - BoundedStack")
	fmt.Fprintf(os.Stderr, "For more information, see:\n")
	fmt.Fprintf(os.Stderr, "\thttp://github.com/aurelien-rainone/go-gencon\n")
	fmt.Fprintf(os.Stderr, "Flags:\n")
	flag.PrintDefaults()
}

func main() {

	log.SetFlags(0)
	log.SetPrefix("go-gencon: ")
	flag.Usage = Usage
	flag.Parse()

	if os.Getenv("GOPACKAGE") != "" {
		*pkg = os.Getenv("GOPACKAGE")
	}

	if *container == "" || *container == "" || *pkg == "" {
		flag.Usage()
		os.Exit(2)
	}

	var (
		g    Generator // generator instance
		cter string    // type name of generate container
	)
	// TODO: string manipulation
	// TODO: string manipulation
	// TODO: string manipulation
	//cter = strings.ToUpper((*containee)[0]) + *containee[1:] + *container
	cter = *containee + *container
	if len(*name) > 0 {
		cter = *name
	}
	g.nfo = FileInfo{*containee, cter, pkg}
	g.contType = *container
	g.Printf(fmt.Sprintln("//", "$GOPACKAGE", os.Getenv("GOPACKAGE")))

	wd, _ := os.Getwd()
	g.Printf(fmt.Sprintln("//", "Getwd()", wd))
	g.Printf(fmt.Sprintln("//", "$GOFILE", os.Getenv("GOFILE")))
	g.Printf(fmt.Sprintln("//", "$GOPACKAGE", os.Getenv("GOPACKAGE")))

	// Print the header and package clause.
	g.Printf("// Code generated by \"go-gencon %s\"; DO NOT EDIT\n", strings.Join(os.Args[1:], " "))
	g.Printf("\n")
	g.Printf("\n")

	// Format the output.
	src := g.format()

	if *output == "" {
		// generate output filename
		baseName := fmt.Sprintf("%s_%s.go", *containee, *container)
		*output = filepath.Join(".", strings.ToLower(baseName))
	}
	err := ioutil.WriteFile(*output, src, 0644)
	if err != nil {
		log.Fatalf("writing output: %s", err)
	}

}

// Generator holds the state of the analysis. Primarily used to buffer
// the output for format.Source.
type Generator struct {
	buf      bytes.Buffer // Accumulated output.
	nfo      FileInfo     // Info needed to the generated file
	contType string       // container to generate
}

type FileInfo struct {
	Containee, Container, Package string
}

func (g *Generator) Printf(format string, args ...interface{}) {
	fmt.Fprintf(&g.buf, format, args...)
}

// format returns the gofmt-ed contents of the Generator's buffer.
func (g *Generator) format() []byte {
	// list supported containers
	containers := map[string]string{
		"boundedstack": containers.BoundedStack,
	}

	// create container template
	var (
		tmpl  *template.Template
		str   string
		err   error
		found bool
	)
	if str, found = containers[strings.ToLower(g.contType)]; !found {
		log.Fatalf("No template for container '%s'", g.contType)
	}
	if tmpl, err = template.New(g.contType).Parse(str); err != nil {
		panic(err)
	}
	err = tmpl.Execute(&g.buf, g.nfo)
	if err != nil {
		panic(err)
	}

	src, err := format.Source(g.buf.Bytes())
	if err != nil {
		// Should never happen, but can arise when developing this code.
		// The user can compile the output to see the error.
		log.Printf("warning: internal error: invalid Go generated: %s", err)
		log.Printf("warning: compile the package to analyze the error")
		return g.buf.Bytes()
	}
	return src
}
<|endoftext|>


<commit_before>/*
Package gode runs a sandboxed node installation to run node code and install npm packages.
*/
package gode

import (
	"os"
	"path/filepath"
	"runtime"
)

var t *target
var registry string
var rootPath string
var lockPath string
var modulesDir string
var nodeBinPath string
var npmBasePath string
var npmBinPath string

func init() {
	registry = os.Getenv("HEROKU_NPM_REGISTRY")
	if registry == "" {
		registry = "https://cli-npm.heroku.com"
	}
}

// SetRootPath sets the root for gode
func SetRootPath(root string) {
	for _, target := range targets {
		if runtime.GOARCH == target.Arch && runtime.GOOS == target.OS {
			t = &target
			break
		}
	}
	rootPath = root
	lockPath = filepath.Join(rootPath, "node.lock")
	modulesDir = filepath.Join(rootPath, "node_modules")
	nodeBinPath = os.Getenv("HEROKU_NODE_PATH")
	if nodeBinPath == "" {
		nodeBinPath = filepath.Join(rootPath, "node-"+NodeVersion+"-"+t.OS+"-"+t.Arch, "node")
		if t.OS == "windows" {
			nodeBinPath += ".exe"
		}
	}
	npmBasePath = filepath.Join(rootPath, npmBase)
	npmBinPath = filepath.Join(npmBasePath, "cli.js")
}
<commit_msg>fix for unsupported node binaries<commit_after>/*
Package gode runs a sandboxed node installation to run node code and install npm packages.
*/
package gode

import (
	"os"
	"path/filepath"
	"runtime"
)

var t *target
var registry string
var rootPath string
var lockPath string
var modulesDir string
var nodeBinPath string
var npmBasePath string
var npmBinPath string

func init() {
	registry = os.Getenv("HEROKU_NPM_REGISTRY")
	if registry == "" {
		registry = "https://cli-npm.heroku.com"
	}
}

// SetRootPath sets the root for gode
func SetRootPath(root string) {
	for _, target := range targets {
		if runtime.GOARCH == target.Arch && runtime.GOOS == target.OS {
			t = &target
			break
		}
	}
	rootPath = root
	lockPath = filepath.Join(rootPath, "node.lock")
	modulesDir = filepath.Join(rootPath, "node_modules")
	nodeBinPath = os.Getenv("HEROKU_NODE_PATH")
	if nodeBinPath == "" {
		nodeBinPath = filepath.Join(rootPath, "node-"+NodeVersion+"-"+runtime.GOOS+"-"+runtime.GOARCH, "node")
		if t.OS == "windows" {
			nodeBinPath += ".exe"
		}
	}
	npmBasePath = filepath.Join(rootPath, npmBase)
	npmBinPath = filepath.Join(npmBasePath, "cli.js")
}
<|endoftext|>