<commit_before>package eth

import (
	"bytes"
	"fmt"
	"io"
	"math/big"

	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/ethutil"
	"github.com/ethereum/go-ethereum/p2p"
	"github.com/ethereum/go-ethereum/rlp"
)

const (
	ProtocolVersion    = 51
	NetworkId          = 0
	ProtocolLength     = uint64(8)
	ProtocolMaxMsgSize = 10 * 1024 * 1024
)

// eth protocol message codes
const (
	StatusMsg = iota
	GetTxMsg  // unused
	TxMsg
	GetBlockHashesMsg
	BlockHashesMsg
	GetBlocksMsg
	BlocksMsg
	NewBlockMsg
)

// ethProtocol represents the ethereum wire protocol
// instance is running on each peer
type ethProtocol struct {
	txPool       txPool
	chainManager chainManager
	blockPool    blockPool
	peer         *p2p.Peer
	id           string
	rw           p2p.MsgReadWriter
}

// backend is the interface the ethereum protocol backend should implement
// used as an argument to EthProtocol
type txPool interface {
	AddTransactions([]*types.Transaction)
}

type chainManager interface {
	GetBlockHashesFromHash(hash []byte, amount uint64) (hashes [][]byte)
	GetBlock(hash []byte) (block *types.Block)
	Status() (td *big.Int, currentBlock []byte, genesisBlock []byte)
}

type blockPool interface {
	AddBlockHashes(next func() ([]byte, bool), peerId string)
	AddBlock(block *types.Block, peerId string)
	AddPeer(td *big.Int, currentBlock []byte, peerId string, requestHashes func([]byte) error, requestBlocks func([][]byte) error, peerError func(int, string, ...interface{})) (best bool)
	RemovePeer(peerId string)
}

// message structs used for rlp decoding
type newBlockMsgData struct {
	Block *types.Block
	TD    *big.Int
}

type getBlockHashesMsgData struct {
	Hash   []byte
	Amount uint64
}

// main entrypoint, wrappers starting a server running the eth protocol
// use this constructor to attach the protocol ("class") to server caps
// the Dev p2p layer then runs the protocol instance on each peer
func EthProtocol(txPool txPool, chainManager chainManager, blockPool blockPool) p2p.Protocol {
	return p2p.Protocol{
		Name:    "eth",
		Version: ProtocolVersion,
		Length:  ProtocolLength,
		Run: func(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
			return runEthProtocol(txPool, chainManager, blockPool, peer, rw)
		},
	}
}

// the main loop that handles incoming messages
// note RemovePeer in the post-disconnect hook
func runEthProtocol(txPool txPool, chainManager chainManager, blockPool blockPool, peer *p2p.Peer, rw p2p.MsgReadWriter) (err error) {
	self := &ethProtocol{
		txPool:       txPool,
		chainManager: chainManager,
		blockPool:    blockPool,
		rw:           rw,
		peer:         peer,
		id:           fmt.Sprintf("%x", peer.Identity().Pubkey()[:8]),
	}
	err = self.handleStatus()
	if err == nil {
		for {
			err = self.handle()
			if err != nil {
				self.blockPool.RemovePeer(self.id)
				break
			}
		}
	}
	return
}

func (self *ethProtocol) handle() error {
	msg, err := self.rw.ReadMsg()
	if err != nil {
		return err
	}
	if msg.Size > ProtocolMaxMsgSize {
		return self.protoError(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
	}
	// make sure that the payload has been fully consumed
	defer msg.Discard()

	switch msg.Code {
	case GetTxMsg: // ignore
	case StatusMsg:
		return self.protoError(ErrExtraStatusMsg, "")

	case TxMsg:
		// TODO: rework using lazy RLP stream
		var txs []*types.Transaction
		if err := msg.Decode(&txs); err != nil {
			return self.protoError(ErrDecode, "msg %v: %v", msg, err)
		}
		self.txPool.AddTransactions(txs)

	case GetBlockHashesMsg:
		var request getBlockHashesMsgData
		if err := msg.Decode(&request); err != nil {
			return self.protoError(ErrDecode, "->msg %v: %v", msg, err)
		}
		hashes := self.chainManager.GetBlockHashesFromHash(request.Hash, request.Amount)
		return p2p.EncodeMsg(self.rw, BlockHashesMsg, ethutil.ByteSliceToInterface(hashes)...)

	case BlockHashesMsg:
		// TODO: redo using lazy decode , this way very inefficient on known chains
		msgStream := rlp.NewStream(msg.Payload)
		var err error
		var i int

		iter := func() (hash []byte, ok bool) {
			hash, err = msgStream.Bytes()
			if err == nil {
				i++
				ok = true
			} else {
				if err != io.EOF {
					self.protoError(ErrDecode, "msg %v: after %v hashes : %v", msg, i, err)
				}
			}
			return
		}

		self.blockPool.AddBlockHashes(iter, self.id)

	case GetBlocksMsg:
		msgStream := rlp.NewStream(msg.Payload)
		var blocks []interface{}
		var i int
		for {
			i++
			var hash []byte
			if err := msgStream.Decode(&hash); err != nil {
				if err == io.EOF {
					break
				} else {
					return self.protoError(ErrDecode, "msg %v: %v", msg, err)
				}
			}
			block := self.chainManager.GetBlock(hash)
			if block != nil {
				blocks = append(blocks, block)
			}
			if i == blockHashesBatchSize {
				break
			}
		}
		return p2p.EncodeMsg(self.rw, BlocksMsg, blocks...)

	case BlocksMsg:
		msgStream := rlp.NewStream(msg.Payload)
		for {
			var block types.Block
			if err := msgStream.Decode(&block); err != nil {
				if err == io.EOF {
					break
				} else {
					return self.protoError(ErrDecode, "msg %v: %v", msg, err)
				}
			}
			self.blockPool.AddBlock(&block, self.id)
		}

	case NewBlockMsg:
		var request newBlockMsgData
		if err := msg.Decode(&request); err != nil {
			return self.protoError(ErrDecode, "msg %v: %v", msg, err)
		}
		hash := request.Block.Hash()
		// to simplify backend interface adding a new block
		// uses AddPeer followed by AddHashes, AddBlock only if peer is the best peer
		// (or selected as new best peer)
		if self.blockPool.AddPeer(request.TD, hash, self.id, self.requestBlockHashes, self.requestBlocks, self.protoErrorDisconnect) {
			self.blockPool.AddBlock(request.Block, self.id)
		}

	default:
		return self.protoError(ErrInvalidMsgCode, "%v", msg.Code)
	}
	return nil
}

type statusMsgData struct {
	ProtocolVersion uint32
	NetworkId       uint32
	TD              *big.Int
	CurrentBlock    []byte
	GenesisBlock    []byte
}

func (self *ethProtocol) statusMsg() p2p.Msg {
	td, currentBlock, genesisBlock := self.chainManager.Status()

	return p2p.NewMsg(StatusMsg,
		uint32(ProtocolVersion),
		uint32(NetworkId),
		td,
		currentBlock,
		genesisBlock,
	)
}

func (self *ethProtocol) handleStatus() error {
	// send precanned status message
	if err := self.rw.WriteMsg(self.statusMsg()); err != nil {
		return err
	}

	// read and handle remote status
	msg, err := self.rw.ReadMsg()
	if err != nil {
		return err
	}

	if msg.Code != StatusMsg {
		return self.protoError(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg)
	}

	if msg.Size > ProtocolMaxMsgSize {
		return self.protoError(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
	}

	var status statusMsgData
	if err := msg.Decode(&status); err != nil {
		return self.protoError(ErrDecode, "msg %v: %v", msg, err)
	}

	_, _, genesisBlock := self.chainManager.Status()

	if bytes.Compare(status.GenesisBlock, genesisBlock) != 0 {
		return self.protoError(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock, genesisBlock)
	}

	if status.NetworkId != NetworkId {
		return self.protoError(ErrNetworkIdMismatch, "%d (!= %d)", status.NetworkId, NetworkId)
	}

	if ProtocolVersion != status.ProtocolVersion {
		return self.protoError(ErrProtocolVersionMismatch, "%d (!= %d)", status.ProtocolVersion, ProtocolVersion)
	}

	self.peer.Infof("Peer is [eth] capable (%d/%d). TD=%v H=%x\n", status.ProtocolVersion, status.NetworkId, status.TD, status.CurrentBlock[:4])

	self.blockPool.AddPeer(status.TD, status.CurrentBlock, self.id, self.requestBlockHashes, self.requestBlocks, self.protoErrorDisconnect)

	return nil
}

func (self *ethProtocol) requestBlockHashes(from []byte) error {
	self.peer.Debugf("fetching hashes (%d) %x...\n", blockHashesBatchSize, from[0:4])
	return p2p.EncodeMsg(self.rw, GetBlockHashesMsg, interface{}(from), uint64(blockHashesBatchSize))
}

func (self *ethProtocol) requestBlocks(hashes [][]byte) error {
	self.peer.Debugf("fetching %v blocks", len(hashes))
	return p2p.EncodeMsg(self.rw, GetBlocksMsg, ethutil.ByteSliceToInterface(hashes)...)
}

func (self *ethProtocol) protoError(code int, format string, params ...interface{}) (err *protocolError) {
	err = ProtocolError(code, format, params...)
	if err.Fatal() {
		self.peer.Errorln("err %v", err)
		// disconnect
	} else {
		self.peer.Debugf("fyi %v", err)
	}
	return
}

func (self *ethProtocol) protoErrorDisconnect(code int, format string, params ...interface{}) {
	err := ProtocolError(code, format, params...)
	if err.Fatal() {
		self.peer.Errorln("err %v", err)
		// disconnect
	} else {
		self.peer.Debugf("fyi %v", err)
	}

}
<commit_msg>Limit hashes. Closes #249<commit_after>package eth

import (
	"bytes"
	"fmt"
	"io"
	"math/big"

	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/ethutil"
	"github.com/ethereum/go-ethereum/p2p"
	"github.com/ethereum/go-ethereum/rlp"
)

const (
	ProtocolVersion    = 51
	NetworkId          = 0
	ProtocolLength     = uint64(8)
	ProtocolMaxMsgSize = 10 * 1024 * 1024
)

// eth protocol message codes
const (
	StatusMsg = iota
	GetTxMsg  // unused
	TxMsg
	GetBlockHashesMsg
	BlockHashesMsg
	GetBlocksMsg
	BlocksMsg
	NewBlockMsg
)

// ethProtocol represents the ethereum wire protocol
// instance is running on each peer
type ethProtocol struct {
	txPool       txPool
	chainManager chainManager
	blockPool    blockPool
	peer         *p2p.Peer
	id           string
	rw           p2p.MsgReadWriter
}

// backend is the interface the ethereum protocol backend should implement
// used as an argument to EthProtocol
type txPool interface {
	AddTransactions([]*types.Transaction)
}

type chainManager interface {
	GetBlockHashesFromHash(hash []byte, amount uint64) (hashes [][]byte)
	GetBlock(hash []byte) (block *types.Block)
	Status() (td *big.Int, currentBlock []byte, genesisBlock []byte)
}

type blockPool interface {
	AddBlockHashes(next func() ([]byte, bool), peerId string)
	AddBlock(block *types.Block, peerId string)
	AddPeer(td *big.Int, currentBlock []byte, peerId string, requestHashes func([]byte) error, requestBlocks func([][]byte) error, peerError func(int, string, ...interface{})) (best bool)
	RemovePeer(peerId string)
}

// message structs used for rlp decoding
type newBlockMsgData struct {
	Block *types.Block
	TD    *big.Int
}

const maxHashes = 255

type getBlockHashesMsgData struct {
	Hash   []byte
	Amount uint64
}

// main entrypoint, wrappers starting a server running the eth protocol
// use this constructor to attach the protocol ("class") to server caps
// the Dev p2p layer then runs the protocol instance on each peer
func EthProtocol(txPool txPool, chainManager chainManager, blockPool blockPool) p2p.Protocol {
	return p2p.Protocol{
		Name:    "eth",
		Version: ProtocolVersion,
		Length:  ProtocolLength,
		Run: func(peer *p2p.Peer, rw p2p.MsgReadWriter) error {
			return runEthProtocol(txPool, chainManager, blockPool, peer, rw)
		},
	}
}

// the main loop that handles incoming messages
// note RemovePeer in the post-disconnect hook
func runEthProtocol(txPool txPool, chainManager chainManager, blockPool blockPool, peer *p2p.Peer, rw p2p.MsgReadWriter) (err error) {
	self := &ethProtocol{
		txPool:       txPool,
		chainManager: chainManager,
		blockPool:    blockPool,
		rw:           rw,
		peer:         peer,
		id:           fmt.Sprintf("%x", peer.Identity().Pubkey()[:8]),
	}
	err = self.handleStatus()
	if err == nil {
		for {
			err = self.handle()
			if err != nil {
				self.blockPool.RemovePeer(self.id)
				break
			}
		}
	}
	return
}

func (self *ethProtocol) handle() error {
	msg, err := self.rw.ReadMsg()
	if err != nil {
		return err
	}
	if msg.Size > ProtocolMaxMsgSize {
		return self.protoError(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
	}
	// make sure that the payload has been fully consumed
	defer msg.Discard()

	switch msg.Code {
	case GetTxMsg: // ignore
	case StatusMsg:
		return self.protoError(ErrExtraStatusMsg, "")

	case TxMsg:
		// TODO: rework using lazy RLP stream
		var txs []*types.Transaction
		if err := msg.Decode(&txs); err != nil {
			return self.protoError(ErrDecode, "msg %v: %v", msg, err)
		}
		self.txPool.AddTransactions(txs)

	case GetBlockHashesMsg:
		var request getBlockHashesMsgData
		if err := msg.Decode(&request); err != nil {
			return self.protoError(ErrDecode, "->msg %v: %v", msg, err)
		}

		//request.Amount = uint64(math.Min(float64(maxHashes), float64(request.Amount)))
		if request.Amount > maxHashes {
			request.Amount = maxHashes
		}
		hashes := self.chainManager.GetBlockHashesFromHash(request.Hash, request.Amount)
		return p2p.EncodeMsg(self.rw, BlockHashesMsg, ethutil.ByteSliceToInterface(hashes)...)

	case BlockHashesMsg:
		// TODO: redo using lazy decode , this way very inefficient on known chains
		msgStream := rlp.NewStream(msg.Payload)
		var err error
		var i int

		iter := func() (hash []byte, ok bool) {
			hash, err = msgStream.Bytes()
			if err == nil {
				i++
				ok = true
			} else {
				if err != io.EOF {
					self.protoError(ErrDecode, "msg %v: after %v hashes : %v", msg, i, err)
				}
			}
			return
		}

		self.blockPool.AddBlockHashes(iter, self.id)

	case GetBlocksMsg:
		msgStream := rlp.NewStream(msg.Payload)
		var blocks []interface{}
		var i int
		for {
			i++
			var hash []byte
			if err := msgStream.Decode(&hash); err != nil {
				if err == io.EOF {
					break
				} else {
					return self.protoError(ErrDecode, "msg %v: %v", msg, err)
				}
			}
			block := self.chainManager.GetBlock(hash)
			if block != nil {
				blocks = append(blocks, block)
			}
			if i == blockHashesBatchSize {
				break
			}
		}
		return p2p.EncodeMsg(self.rw, BlocksMsg, blocks...)

	case BlocksMsg:
		msgStream := rlp.NewStream(msg.Payload)
		for {
			var block types.Block
			if err := msgStream.Decode(&block); err != nil {
				if err == io.EOF {
					break
				} else {
					return self.protoError(ErrDecode, "msg %v: %v", msg, err)
				}
			}
			self.blockPool.AddBlock(&block, self.id)
		}

	case NewBlockMsg:
		var request newBlockMsgData
		if err := msg.Decode(&request); err != nil {
			return self.protoError(ErrDecode, "msg %v: %v", msg, err)
		}
		hash := request.Block.Hash()
		// to simplify backend interface adding a new block
		// uses AddPeer followed by AddHashes, AddBlock only if peer is the best peer
		// (or selected as new best peer)
		if self.blockPool.AddPeer(request.TD, hash, self.id, self.requestBlockHashes, self.requestBlocks, self.protoErrorDisconnect) {
			self.blockPool.AddBlock(request.Block, self.id)
		}

	default:
		return self.protoError(ErrInvalidMsgCode, "%v", msg.Code)
	}
	return nil
}

type statusMsgData struct {
	ProtocolVersion uint32
	NetworkId       uint32
	TD              *big.Int
	CurrentBlock    []byte
	GenesisBlock    []byte
}

func (self *ethProtocol) statusMsg() p2p.Msg {
	td, currentBlock, genesisBlock := self.chainManager.Status()

	return p2p.NewMsg(StatusMsg,
		uint32(ProtocolVersion),
		uint32(NetworkId),
		td,
		currentBlock,
		genesisBlock,
	)
}

func (self *ethProtocol) handleStatus() error {
	// send precanned status message
	if err := self.rw.WriteMsg(self.statusMsg()); err != nil {
		return err
	}

	// read and handle remote status
	msg, err := self.rw.ReadMsg()
	if err != nil {
		return err
	}

	if msg.Code != StatusMsg {
		return self.protoError(ErrNoStatusMsg, "first msg has code %x (!= %x)", msg.Code, StatusMsg)
	}

	if msg.Size > ProtocolMaxMsgSize {
		return self.protoError(ErrMsgTooLarge, "%v > %v", msg.Size, ProtocolMaxMsgSize)
	}

	var status statusMsgData
	if err := msg.Decode(&status); err != nil {
		return self.protoError(ErrDecode, "msg %v: %v", msg, err)
	}

	_, _, genesisBlock := self.chainManager.Status()

	if bytes.Compare(status.GenesisBlock, genesisBlock) != 0 {
		return self.protoError(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock, genesisBlock)
	}

	if status.NetworkId != NetworkId {
		return self.protoError(ErrNetworkIdMismatch, "%d (!= %d)", status.NetworkId, NetworkId)
	}

	if ProtocolVersion != status.ProtocolVersion {
		return self.protoError(ErrProtocolVersionMismatch, "%d (!= %d)", status.ProtocolVersion, ProtocolVersion)
	}

	self.peer.Infof("Peer is [eth] capable (%d/%d). TD=%v H=%x\n", status.ProtocolVersion, status.NetworkId, status.TD, status.CurrentBlock[:4])

	self.blockPool.AddPeer(status.TD, status.CurrentBlock, self.id, self.requestBlockHashes, self.requestBlocks, self.protoErrorDisconnect)

	return nil
}

func (self *ethProtocol) requestBlockHashes(from []byte) error {
	self.peer.Debugf("fetching hashes (%d) %x...\n", blockHashesBatchSize, from[0:4])
	return p2p.EncodeMsg(self.rw, GetBlockHashesMsg, interface{}(from), uint64(blockHashesBatchSize))
}

func (self *ethProtocol) requestBlocks(hashes [][]byte) error {
	self.peer.Debugf("fetching %v blocks", len(hashes))
	return p2p.EncodeMsg(self.rw, GetBlocksMsg, ethutil.ByteSliceToInterface(hashes)...)
}

func (self *ethProtocol) protoError(code int, format string, params ...interface{}) (err *protocolError) {
	err = ProtocolError(code, format, params...)
	if err.Fatal() {
		self.peer.Errorln("err %v", err)
		// disconnect
	} else {
		self.peer.Debugf("fyi %v", err)
	}
	return
}

func (self *ethProtocol) protoErrorDisconnect(code int, format string, params ...interface{}) {
	err := ProtocolError(code, format, params...)
	if err.Fatal() {
		self.peer.Errorln("err %v", err)
		// disconnect
	} else {
		self.peer.Debugf("fyi %v", err)
	}

}
<|endoftext|>


<commit_before>package gitmedia

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"strconv"
)

var MediaWarning = []byte("# This is a placeholder for large media, please install GitHub git-media to retrieve content\n# It is also possible you did not have the media locally, run 'git media sync' to retrieve it\n")

type Encoder struct {
	writer      io.Writer
	jsonencoder *json.Encoder
}

func NewEncoder(writer io.Writer) *Encoder {
	return &Encoder{writer, json.NewEncoder(writer)}
}

func (e *Encoder) Encode(obj interface{}) error {
	header := fmt.Sprintf("# %d\n", len(MediaWarning))
	e.writer.Write([]byte(header))
	e.writer.Write(MediaWarning)
	return e.jsonencoder.Encode(obj)
}

type Decoder struct {
	reader      io.Reader
	jsondecoder *json.Decoder
}

func NewDecoder(reader io.Reader) *Decoder {
	return &Decoder{reader, json.NewDecoder(reader)}
}

func (d *Decoder) Decode(obj interface{}) error {
	buf := make([]byte, 10)
	d.reader.Read(buf)
	slices := bytes.SplitN(buf, []byte("\n"), 2)
	headerlen, err := strconv.Atoi(string(slices[0])[2:])
	if err != nil {
		fmt.Printf("Error reading header:\n%s\n", string(buf))
		panic(err)
	}

	buf = make([]byte, headerlen-len(slices[1]))
	d.reader.Read(buf)

	return d.jsondecoder.Decode(obj)
}
<commit_msg>remove that warning header length<commit_after>package gitmedia

import (
	"bytes"
	"encoding/json"
	"io"
)

var MediaWarning = []byte("# This is a placeholder for large media, please install GitHub git-media to retrieve content\n# It is also possible you did not have the media locally, run 'git media sync' to retrieve it\n")

type Encoder struct {
	writer      io.Writer
	jsonencoder *json.Encoder
}

func NewEncoder(writer io.Writer) *Encoder {
	return &Encoder{writer, json.NewEncoder(writer)}
}

func (e *Encoder) Encode(obj interface{}) error {
	e.writer.Write(MediaWarning)
	return e.jsonencoder.Encode(obj)
}

type Decoder struct {
	reader io.Reader
}

func NewDecoder(reader io.Reader) *Decoder {
	return &Decoder{reader}
}

func (d *Decoder) Decode(obj interface{}) error {
	buf := make([]byte, 1024)
	io.ReadFull(d.reader, buf)
	slices := bytes.Split(buf, []byte("\n"))
	dec := json.NewDecoder(bytes.NewBuffer(slices[len(slices)-2]))
	return dec.Decode(obj)
}
<|endoftext|>


<commit_before>/*
  Go program to decode an audio stream of Morse code into a stream of ASCII.

  See the ALGORITHM file for a description of what's going on, and
  'proof.hs' as the original proof-of-concept implementation of this
  algorithm in Haskell.
*/

package main

import (
	// "code.google.com/p/portaudio-go/portaudio"
	"fmt"
	"math"
	"math/rand"
	"os"
	"os/signal"
	"sort"
)

type token int

const (
	dit = iota
	dah = iota
	endLetter = iota
	endWord = iota
	pause = iota
	noOp = iota
	cwError = iota
)

// ------- Stage 1:  Detect tones in the stream. ------------------

// Use Root Mean Square (RMS) method to return 'average' value of an
// array of audio samples.
func rms(audiovals []int) int {
	sum := 0
	squaresum := 0
	for i := 0; i < len(audiovals); i++ {
		v := audiovals[i]
		sum = sum + v
		squaresum = squaresum + (v*v)
	}
	mean := sum / len(audiovals)
	meanOfSquares := squaresum / len(audiovals)
	return int(math.Sqrt(float64(meanOfSquares - (mean * mean))))
}

// Read audiosample chunks from 'chunks' channel, and push simple RMS
// amplitudes into the 'amplitudes' channel.
func amplituder(chunks chan []int, amplitudes chan int) {
	for chunk := range chunks {
		amplitudes <- rms(chunk)
	}
	close(amplitudes)
}

// Read amplitudes from 'amplitudes' channel, and push quantized
// on/off values to 'quants' channel.
func quantizer(amplitudes chan int, quants chan bool) {
	var group [100]int
	seen := 0
	max := 0
	min := 0
	for amp := range amplitudes {
		// Suck 100 amplitudes at a time from input channel,
		// figure out 'middle' amplitude for the group, and
		// use that value to quantize each amplitude.
		group[seen] = amp
		seen += 1
		if amp > max { max = amp }
		if amp < min { min = amp }
		if seen == 100 {
			middle := (max - min) / 2
			for i := 0; i < 100; i++ {
				quants <- (group[i] >= middle)
			}
			max = 0
			min = 0
			seen = 0
		}
	}
	close(quants)
}

// Main stage 1 pipeline: reads audiochunks from input channel;
// returns a boolean channel to which it pushes quantized on/off
// values.
func getQuantizePipe(audiochunks chan []int) chan bool {
	amplitudes := make(chan int)
	quants := make(chan bool)
	go amplituder(audiochunks, amplitudes)
	go quantizer(amplitudes, quants)
	return quants
}

// ------- Stage 2:  Run-length encode the on/off states. ----------
//
// That is, if the input stream is 0001100111100, we want to output
// the list [3, 2, 2, 4, 2], which can be seen as the "rhythm" of the
// coded message.

func getRlePipe(quants chan bool) chan int {
	lengths := make(chan int)
	go func() {
		currentState := false
		tally := 0

		// TODO(sussman): need to "debounce" this stream
		for quant := range quants {
			if quant == currentState {
				tally += 1
			} else {
				lengths <- tally
				currentState = quant
				tally = 1
			}
		}
		close(lengths)
	}()
	return lengths
}

// ------- Stage 3: Figure out length of morse 'unit' & output logic tokens
//

// Take a list of on/off duration events, sort them, return the 25th
// percentile value as the "1 unit" duration within the time window.
//
// This magical 25% number derives from the observation that 1-unit
// silences are the most common symbol in a normal Morse phrase, so
// they should compose the majority of the bottom of the sorted pile
// of durations. In theory we could simply pick the smallest, but by
// going with the 25th percentile, the hope is to avoid picking the
// ridiculously small sample that results from a quantization error.
func calculateUnitDuration(group []int) int {
	sort.Ints(group)
	// fmt.Printf("(%d) ", group)
	return group[(len(group) / 4)]
}

// Take a normalized duration value, 'clamp' it to the magic numbers
// 1, 3, 7 (which are the faundational time durations in Morse code),
// and return a sensible semantic token.
func clamp(x float32, silence bool) token {
	if (silence) {
		switch {
		case x > 8:
			return pause
		case x > 5:
			return endWord
		case x > 2:
			return endLetter
		default:
			return noOp
		}
	} else {
		switch {
		case x > 8:
			return cwError
		case x > 5:
			return cwError
		case x > 2:
			return dah
		default:
			return dit
		}
	}
	return cwError
}

func getTokenPipe(durations chan int) chan token {
	tokens := make(chan token)
	seen := 0
	go func() {
		// As a contextual window, look at sets of 20 on/off
		// duration events when calculating the unitDuration.
		//
		// TODO(sussman): make this windowsize a constant we
		// can fiddle.
		group := make([]int, 20)
		for duration := range durations {
			group[seen] = duration
			seen += 1
			if seen == 20 {
				seen = 0

				// figure out the length of a 'dit' (1 unit)
				unitDuration := calculateUnitDuration(group[:])

				// normalize & clamp each duration by this
				silence := false
				for i := range group {
					norm := float32(group[i] / unitDuration)
					tokens <- clamp(norm, silence)
					silence = !silence
				}
			}
		}
		close(durations)
	}()
	return tokens
}

// ------ Put all the pipes together. --------------

func chk(err error) {
	if err != nil {
		panic(err)
	}
}

func main () {
	// Die on Control-C
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt, os.Kill)

	// main input pipe:
	chunks := make(chan []int)

	// construct main output pipe... whee!
	output := getTokenPipe(getRlePipe(getQuantizePipe(chunks)))

/*	portaudio.Initialize()
	defer portaudio.Terminate()

	in := make([]int32, 64)
	stream, err := portaudio.OpenDefaultStream(1, 0, 44100, len(in), in)
	chk(err)
	defer stream.Close()
	nSamples := 0

	go func() {
		chk(stream.Start())
		for {
			chk(stream.Read())

			// chk(binary.Write(f, binary.BigEndian, in))

			nSamples += len(in)
			select {
			case <-sig:
				return
			default:
			}
		}
		chk(stream.Stop())
	}
*/

	// Start pushing random data into the pipeline in the background
	go func() {
		for i :=0 ; i < 5000; i++ {
			chunk := make([]int, 10)
			for j := 0; j < 10; j++ { chunk[j] = rand.Int() }
			chunks <- chunk
		}
		close(chunks)
	}()

	// Print logical tokens from the pipeline's output
	for val := range output {
		out := ""
		switch val {
		case dit: out = ". "
		case dah: out = "_ "
		case endLetter: out = "  "
		case endWord: out = ": "
		case pause: out = "pause "
		case noOp: out = ""
		default: out = "ERROR "
		}
		fmt.Printf("%s", out)
	}
	close(output)
}

<commit_msg>gofmt reformatting.<commit_after>/*
  Go program to decode an audio stream of Morse code into a stream of ASCII.

  See the ALGORITHM file for a description of what's going on, and
  'proof.hs' as the original proof-of-concept implementation of this
  algorithm in Haskell.
*/

package main

import (
	// "code.google.com/p/portaudio-go/portaudio"
	"fmt"
	"math"
	"math/rand"
	"os"
	"os/signal"
	"sort"
)

type token int

const (
	dit       = iota
	dah       = iota
	endLetter = iota
	endWord   = iota
	pause     = iota
	noOp      = iota
	cwError   = iota
)

// ------- Stage 1:  Detect tones in the stream. ------------------

// Use Root Mean Square (RMS) method to return 'average' value of an
// array of audio samples.
func rms(audiovals []int) int {
	sum := 0
	squaresum := 0
	for i := 0; i < len(audiovals); i++ {
		v := audiovals[i]
		sum = sum + v
		squaresum = squaresum + (v * v)
	}
	mean := sum / len(audiovals)
	meanOfSquares := squaresum / len(audiovals)
	return int(math.Sqrt(float64(meanOfSquares - (mean * mean))))
}

// Read audiosample chunks from 'chunks' channel, and push simple RMS
// amplitudes into the 'amplitudes' channel.
func amplituder(chunks chan []int, amplitudes chan int) {
	for chunk := range chunks {
		amplitudes <- rms(chunk)
	}
	close(amplitudes)
}

// Read amplitudes from 'amplitudes' channel, and push quantized
// on/off values to 'quants' channel.
func quantizer(amplitudes chan int, quants chan bool) {
	var group [100]int
	seen := 0
	max := 0
	min := 0
	for amp := range amplitudes {
		// Suck 100 amplitudes at a time from input channel,
		// figure out 'middle' amplitude for the group, and
		// use that value to quantize each amplitude.
		group[seen] = amp
		seen += 1
		if amp > max {
			max = amp
		}
		if amp < min {
			min = amp
		}
		if seen == 100 {
			middle := (max - min) / 2
			for i := 0; i < 100; i++ {
				quants <- (group[i] >= middle)
			}
			max = 0
			min = 0
			seen = 0
		}
	}
	close(quants)
}

// Main stage 1 pipeline: reads audiochunks from input channel;
// returns a boolean channel to which it pushes quantized on/off
// values.
func getQuantizePipe(audiochunks chan []int) chan bool {
	amplitudes := make(chan int)
	quants := make(chan bool)
	go amplituder(audiochunks, amplitudes)
	go quantizer(amplitudes, quants)
	return quants
}

// ------- Stage 2:  Run-length encode the on/off states. ----------
//
// That is, if the input stream is 0001100111100, we want to output
// the list [3, 2, 2, 4, 2], which can be seen as the "rhythm" of the
// coded message.

func getRlePipe(quants chan bool) chan int {
	lengths := make(chan int)
	go func() {
		currentState := false
		tally := 0

		// TODO(sussman): need to "debounce" this stream
		for quant := range quants {
			if quant == currentState {
				tally += 1
			} else {
				lengths <- tally
				currentState = quant
				tally = 1
			}
		}
		close(lengths)
	}()
	return lengths
}

// ------- Stage 3: Figure out length of morse 'unit' & output logic tokens
//

// Take a list of on/off duration events, sort them, return the 25th
// percentile value as the "1 unit" duration within the time window.
//
// This magical 25% number derives from the observation that 1-unit
// silences are the most common symbol in a normal Morse phrase, so
// they should compose the majority of the bottom of the sorted pile
// of durations. In theory we could simply pick the smallest, but by
// going with the 25th percentile, the hope is to avoid picking the
// ridiculously small sample that results from a quantization error.
func calculateUnitDuration(group []int) int {
	sort.Ints(group)
	// fmt.Printf("(%d) ", group)
	return group[(len(group) / 4)]
}

// Take a normalized duration value, 'clamp' it to the magic numbers
// 1, 3, 7 (which are the faundational time durations in Morse code),
// and return a sensible semantic token.
func clamp(x float32, silence bool) token {
	if silence {
		switch {
		case x > 8:
			return pause
		case x > 5:
			return endWord
		case x > 2:
			return endLetter
		default:
			return noOp
		}
	} else {
		switch {
		case x > 8:
			return cwError
		case x > 5:
			return cwError
		case x > 2:
			return dah
		default:
			return dit
		}
	}
	return cwError
}

func getTokenPipe(durations chan int) chan token {
	tokens := make(chan token)
	seen := 0
	go func() {
		// As a contextual window, look at sets of 20 on/off
		// duration events when calculating the unitDuration.
		//
		// TODO(sussman): make this windowsize a constant we
		// can fiddle.
		group := make([]int, 20)
		for duration := range durations {
			group[seen] = duration
			seen += 1
			if seen == 20 {
				seen = 0

				// figure out the length of a 'dit' (1 unit)
				unitDuration := calculateUnitDuration(group[:])

				// normalize & clamp each duration by this
				silence := false
				for i := range group {
					norm := float32(group[i] / unitDuration)
					tokens <- clamp(norm, silence)
					silence = !silence
				}
			}
		}
		close(durations)
	}()
	return tokens
}

// ------ Put all the pipes together. --------------

func chk(err error) {
	if err != nil {
		panic(err)
	}
}

func main() {
	// Die on Control-C
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt, os.Kill)

	// main input pipe:
	chunks := make(chan []int)

	// construct main output pipe... whee!
	output := getTokenPipe(getRlePipe(getQuantizePipe(chunks)))

	/*	portaudio.Initialize()
		defer portaudio.Terminate()

		in := make([]int32, 64)
		stream, err := portaudio.OpenDefaultStream(1, 0, 44100, len(in), in)
		chk(err)
		defer stream.Close()
		nSamples := 0

		go func() {
			chk(stream.Start())
			for {
				chk(stream.Read())

				// chk(binary.Write(f, binary.BigEndian, in))

				nSamples += len(in)
				select {
				case <-sig:
					return
				default:
				}
			}
			chk(stream.Stop())
		}
	*/

	// Start pushing random data into the pipeline in the background
	go func() {
		for i := 0; i < 5000; i++ {
			chunk := make([]int, 10)
			for j := 0; j < 10; j++ {
				chunk[j] = rand.Int()
			}
			chunks <- chunk
		}
		close(chunks)
	}()

	// Print logical tokens from the pipeline's output
	for val := range output {
		out := ""
		switch val {
		case dit:
			out = ". "
		case dah:
			out = "_ "
		case endLetter:
			out = "  "
		case endWord:
			out = ": "
		case pause:
			out = "pause "
		case noOp:
			out = ""
		default:
			out = "ERROR "
		}
		fmt.Printf("%s", out)
	}
	close(output)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"os/exec"
	"os/signal"
	"syscall"

	"github.com/rfjakob/gocryptfs/internal/exitcodes"
	"github.com/rfjakob/gocryptfs/internal/syscallcompat"
	"github.com/rfjakob/gocryptfs/internal/tlog"
)

// The child sends us USR1 if the mount was successful. Exit with error code
// 0 if we get it.
func exitOnUsr1() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGUSR1)
	go func() {
		<-c
		os.Exit(0)
	}()
}

// forkChild - execute ourselves once again, this time with the "-fg" flag, and
// wait for SIGUSR1 or child exit.
// This is a workaround for the missing true fork function in Go.
func forkChild() int {
	name := os.Args[0]
	newArgs := []string{"-fg", fmt.Sprintf("-notifypid=%d", os.Getpid())}
	newArgs = append(newArgs, os.Args[1:]...)
	c := exec.Command(name, newArgs...)
	c.Stdout = os.Stdout
	c.Stderr = os.Stderr
	c.Stdin = os.Stdin
	exitOnUsr1()
	err := c.Start()
	if err != nil {
		tlog.Fatal.Printf("forkChild: starting %s failed: %v\n", name, err)
		return exitcodes.ForkChild
	}
	err = c.Wait()
	if err != nil {
		if exiterr, ok := err.(*exec.ExitError); ok {
			if waitstat, ok := exiterr.Sys().(syscall.WaitStatus); ok {
				os.Exit(waitstat.ExitStatus())
			}
		}
		tlog.Fatal.Printf("forkChild: wait returned an unknown error: %v\n", err)
		return exitcodes.ForkChild
	}
	// The child exited with 0 - let's do the same.
	return 0
}

// redirectStdFds redirects stderr and stdout to syslog; stdin to /dev/null
func redirectStdFds() {
	// stderr and stdout
	pr, pw, err := os.Pipe()
	if err != nil {
		tlog.Warn.Printf("redirectStdFds: could not create pipe: %v\n", err)
		return
	}
	tag := fmt.Sprintf("gocryptfs-%d-logger", os.Getpid())
	cmd := exec.Command("logger", "-t", tag)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Stdin = pr
	err = cmd.Start()
	if err != nil {
		tlog.Warn.Printf("redirectStdFds: could not start logger: %v\n", err)
	}
	pr.Close()
	err = syscallcompat.Dup3(int(pw.Fd()), 1, 0)
	if err != nil {
		tlog.Warn.Printf("redirectStdFds: stdout dup error: %v\n", err)
	}
	syscallcompat.Dup3(int(pw.Fd()), 2, 0)
	if err != nil {
		tlog.Warn.Printf("redirectStdFds: stderr dup error: %v\n", err)
	}
	pw.Close()

	// stdin
	nullFd, err := os.Open("/dev/null")
	if err != nil {
		tlog.Warn.Printf("redirectStdFds: could not open /dev/null: %v\n", err)
		return
	}
	err = syscallcompat.Dup3(int(nullFd.Fd()), 0, 0)
	if err != nil {
		tlog.Warn.Printf("redirectStdFds: stdin dup error: %v\n", err)
	}
	nullFd.Close()
}
<commit_msg>main: redirectStdFds: keep logger from holding stdout open<commit_after>package main

import (
	"fmt"
	"os"
	"os/exec"
	"os/signal"
	"syscall"

	"github.com/rfjakob/gocryptfs/internal/exitcodes"
	"github.com/rfjakob/gocryptfs/internal/syscallcompat"
	"github.com/rfjakob/gocryptfs/internal/tlog"
)

// The child sends us USR1 if the mount was successful. Exit with error code
// 0 if we get it.
func exitOnUsr1() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGUSR1)
	go func() {
		<-c
		os.Exit(0)
	}()
}

// forkChild - execute ourselves once again, this time with the "-fg" flag, and
// wait for SIGUSR1 or child exit.
// This is a workaround for the missing true fork function in Go.
func forkChild() int {
	name := os.Args[0]
	newArgs := []string{"-fg", fmt.Sprintf("-notifypid=%d", os.Getpid())}
	newArgs = append(newArgs, os.Args[1:]...)
	c := exec.Command(name, newArgs...)
	c.Stdout = os.Stdout
	c.Stderr = os.Stderr
	c.Stdin = os.Stdin
	exitOnUsr1()
	err := c.Start()
	if err != nil {
		tlog.Fatal.Printf("forkChild: starting %s failed: %v\n", name, err)
		return exitcodes.ForkChild
	}
	err = c.Wait()
	if err != nil {
		if exiterr, ok := err.(*exec.ExitError); ok {
			if waitstat, ok := exiterr.Sys().(syscall.WaitStatus); ok {
				os.Exit(waitstat.ExitStatus())
			}
		}
		tlog.Fatal.Printf("forkChild: wait returned an unknown error: %v\n", err)
		return exitcodes.ForkChild
	}
	// The child exited with 0 - let's do the same.
	return 0
}

// redirectStdFds redirects stderr and stdout to syslog; stdin to /dev/null
func redirectStdFds() {
	// Create a pipe pair "pw" -> "pr" and start logger reading from "pr".
	// We do it ourselves instead of using StdinPipe() because we need access
	// to the fd numbers.
	pr, pw, err := os.Pipe()
	if err != nil {
		tlog.Warn.Printf("redirectStdFds: could not create pipe: %v\n", err)
		return
	}
	tag := fmt.Sprintf("gocryptfs-%d-logger", os.Getpid())
	cmd := exec.Command("logger", "-t", tag)
	cmd.Stdin = pr
	err = cmd.Start()
	if err != nil {
		tlog.Warn.Printf("redirectStdFds: could not start logger: %v\n", err)
		return
	}
	// The logger now reads on "pr". We can close it.
	pr.Close()
	// Redirect stout and stderr to "pw".
	err = syscallcompat.Dup3(int(pw.Fd()), 1, 0)
	if err != nil {
		tlog.Warn.Printf("redirectStdFds: stdout dup error: %v\n", err)
	}
	syscallcompat.Dup3(int(pw.Fd()), 2, 0)
	if err != nil {
		tlog.Warn.Printf("redirectStdFds: stderr dup error: %v\n", err)
	}
	// Our stout and stderr point to "pw". We can close the extra copy.
	pw.Close()
	// Redirect stdin to /dev/null
	nullFd, err := os.Open("/dev/null")
	if err != nil {
		tlog.Warn.Printf("redirectStdFds: could not open /dev/null: %v\n", err)
		return
	}
	err = syscallcompat.Dup3(int(nullFd.Fd()), 0, 0)
	if err != nil {
		tlog.Warn.Printf("redirectStdFds: stdin dup error: %v\n", err)
	}
	nullFd.Close()
}
<|endoftext|>


<commit_before>// Package gcp contains a Google Cloud Platform-specific implementation of the generic tracing APIs.
package gcp

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"time"

	"github.com/rakyll/trace"

	api "google.golang.org/api/cloudtrace/v1"
	"google.golang.org/api/option"
	"google.golang.org/api/support/bundler"
	"google.golang.org/api/transport"
)

const (
	httpHeader          = `X-Cloud-Trace-Context`
	userAgent           = `gcloud-golang-trace/20160501`
	cloudPlatformScope  = `https://www.googleapis.com/auth/cloud-platform`
	spanKindClient      = `RPC_CLIENT`
	spanKindServer      = `RPC_SERVER`
	spanKindUnspecified = `SPAN_KIND_UNSPECIFIED`
	maxStackFrames      = 20
	labelSamplingPolicy = `trace.cloud.google.com/sampling_policy`
	labelSamplingWeight = `trace.cloud.google.com/sampling_weight`
)

type client struct {
	service *api.Service
	proj    string
	bundler *bundler.Bundler
}

func NewClient(ctx context.Context, projID string, opts ...option.ClientOption) (trace.Client, error) {
	o := []option.ClientOption{
		option.WithScopes(cloudPlatformScope),
		option.WithUserAgent(userAgent),
	}
	o = append(o, opts...)
	hc, basePath, err := transport.NewHTTPClient(ctx, o...)
	if err != nil {
		return nil, fmt.Errorf("creating HTTP client for Google Stackdriver Trace API: %v", err)
	}
	apiService, err := api.New(hc)
	if err != nil {
		return nil, fmt.Errorf("creating Google Stackdriver Trace API client: %v", err)
	}
	if basePath != "" {
		// An option set a basepath, so override api.New's default.
		apiService.BasePath = basePath
	}
	c := &client{
		service: apiService,
		proj:    projID,
	}
	bundler := bundler.NewBundler((*api.Trace)(nil), func(bundle interface{}) {
		traces := bundle.([]*api.Trace)
		err := c.upload(traces)
		if err != nil {
			log.Printf("failed to upload %d traces to the Cloud Trace server.", len(traces))
		}
	})
	bundler.DelayThreshold = 2 * time.Second
	bundler.BundleCountThreshold = 100
	// We're not measuring bytes here, we're counting traces and spans as one "byte" each.
	bundler.BundleByteThreshold = 1000
	bundler.BundleByteLimit = 1000
	bundler.BufferedByteLimit = 10000
	c.bundler = bundler
	return c, nil
}

func (c *client) upload(traces []*api.Trace) error {
	_, err := c.service.Projects.PatchTraces(c.proj, &api.Traces{Traces: traces}).Do()
	return err
}

func (c *client) NewSpan(parent []byte, causal []byte) []byte { // TODO(jbd): add error.
	var parentID spanID
	var causalID spanID

	if parent != nil {
		json.Unmarshal(parent, &parentID) // ignore errors
	}
	if causal != nil {
		json.Unmarshal(causal, &causalID) // ignore errors
	}

	id := spanID{
		TraceID:  parentID.TraceID,
		ID:       nextSpanID(),
		CausalID: causalID.ID,
		ParentID: parentID.ID,
	}
	by, _ := json.Marshal(id)
	return by
}

func (c *client) Finish(id []byte, name string, labels map[string][]byte, start, end time.Time) error {
	var ident spanID
	json.Unmarshal(id, &ident) // ignore errors
	s := &span{
		name:   name,
		id:     ident,
		labels: labels,
		start:  start,
		end:    end,
	}
	return finish(c, c.proj, []*span{s})
}
<commit_msg>don't ignore Unmarshal errors on finish<commit_after>// Package gcp contains a Google Cloud Platform-specific implementation of the generic tracing APIs.
package gcp

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"time"

	"github.com/rakyll/trace"

	api "google.golang.org/api/cloudtrace/v1"
	"google.golang.org/api/option"
	"google.golang.org/api/support/bundler"
	"google.golang.org/api/transport"
)

const (
	httpHeader          = `X-Cloud-Trace-Context`
	userAgent           = `gcloud-golang-trace/20160501`
	cloudPlatformScope  = `https://www.googleapis.com/auth/cloud-platform`
	spanKindClient      = `RPC_CLIENT`
	spanKindServer      = `RPC_SERVER`
	spanKindUnspecified = `SPAN_KIND_UNSPECIFIED`
	maxStackFrames      = 20
	labelSamplingPolicy = `trace.cloud.google.com/sampling_policy`
	labelSamplingWeight = `trace.cloud.google.com/sampling_weight`
)

type client struct {
	service *api.Service
	proj    string
	bundler *bundler.Bundler
}

func NewClient(ctx context.Context, projID string, opts ...option.ClientOption) (trace.Client, error) {
	o := []option.ClientOption{
		option.WithScopes(cloudPlatformScope),
		option.WithUserAgent(userAgent),
	}
	o = append(o, opts...)
	hc, basePath, err := transport.NewHTTPClient(ctx, o...)
	if err != nil {
		return nil, fmt.Errorf("creating HTTP client for Google Stackdriver Trace API: %v", err)
	}
	apiService, err := api.New(hc)
	if err != nil {
		return nil, fmt.Errorf("creating Google Stackdriver Trace API client: %v", err)
	}
	if basePath != "" {
		// An option set a basepath, so override api.New's default.
		apiService.BasePath = basePath
	}
	c := &client{
		service: apiService,
		proj:    projID,
	}
	bundler := bundler.NewBundler((*api.Trace)(nil), func(bundle interface{}) {
		traces := bundle.([]*api.Trace)
		err := c.upload(traces)
		if err != nil {
			log.Printf("failed to upload %d traces to the Cloud Trace server.", len(traces))
		}
	})
	bundler.DelayThreshold = 2 * time.Second
	bundler.BundleCountThreshold = 100
	// We're not measuring bytes here, we're counting traces and spans as one "byte" each.
	bundler.BundleByteThreshold = 1000
	bundler.BundleByteLimit = 1000
	bundler.BufferedByteLimit = 10000
	c.bundler = bundler
	return c, nil
}

func (c *client) upload(traces []*api.Trace) error {
	_, err := c.service.Projects.PatchTraces(c.proj, &api.Traces{Traces: traces}).Do()
	return err
}

func (c *client) NewSpan(parent []byte, causal []byte) []byte { // TODO(jbd): add error.
	var parentID spanID
	var causalID spanID

	if parent != nil {
		json.Unmarshal(parent, &parentID) // ignore errors
	}
	if causal != nil {
		json.Unmarshal(causal, &causalID) // ignore errors
	}

	id := spanID{
		TraceID:  parentID.TraceID,
		ID:       nextSpanID(),
		CausalID: causalID.ID,
		ParentID: parentID.ID,
	}
	by, _ := json.Marshal(id)
	return by
}

func (c *client) Finish(id []byte, name string, labels map[string][]byte, start, end time.Time) error {
	var ident spanID
	if err := json.Unmarshal(id, &ident); err != nil {
		return err
	}
	s := &span{
		name:   name,
		id:     ident,
		labels: labels,
		start:  start,
		end:    end,
	}
	return finish(c, c.proj, []*span{s})
}
<|endoftext|>


<commit_before>package event

// As in collision and mouse, legacy.go lists functions that
// only operate on DefaultBus, a package global bus.

var (
	// DefaultBus is a bus that has additional operations for CIDs, and can
	// be called via event.Call as opposed to bus.Call
	DefaultBus = NewBus()
)

// Trigger an event, but only for one ID, on the default bus
func (cid CID) Trigger(eventName string, data interface{}) {

	go func(eventName string, data interface{}) {
		DefaultBus.mutex.RLock()
		iid := int(cid)
		if idMap, ok := DefaultBus.bindingMap[eventName]; ok {
			if bs, ok := idMap[iid]; ok {
				for i := bs.highIndex - 1; i >= 0; i-- {
					DefaultBus.triggerDefault((*bs.highPriority[i]).sl, iid, eventName, data)
				}
				DefaultBus.triggerDefault((bs.defaultPriority).sl, iid, eventName, data)

				for i := 0; i < bs.lowIndex; i++ {
					DefaultBus.triggerDefault((*bs.lowPriority[i]).sl, iid, eventName, data)
				}
			}
		}
		DefaultBus.mutex.RUnlock()
	}(eventName, data)
}

// Bind on a CID is shorthand for bus.Bind(fn, name, cid), on the default bus.
func (cid CID) Bind(fn Bindable, name string) {
	DefaultBus.Bind(fn, name, int(cid))
}

// BindPriority on a CID is shorthand for bus.BindPriority(fn, ...), on the default bus.
func (cid CID) BindPriority(fn Bindable, name string, priority int) {
	DefaultBus.BindPriority(fn, BindingOption{
		Event{
			name,
			int(cid),
		},
		priority,
	})
}

// UnbindAll removes all events with the given cid from the event bus
func (cid CID) UnbindAll() {
	DefaultBus.UnbindAll(BindingOption{
		Event{
			"",
			int(cid),
		},
		0,
	})
}

// UnbindAllAndRebind on a CID is equivalent to bus.UnbindAllAndRebind(..., cid)
func (cid CID) UnbindAllAndRebind(binds []Bindable, events []string) {
	DefaultBus.UnbindAllAndRebind(BindingOption{
		Event{
			"",
			int(cid),
		},
		0,
	}, binds, int(cid), events)
}

// Trigger calls Trigger on the DefaultBus
func Trigger(eventName string, data interface{}) {
	DefaultBus.Trigger(eventName, data)
}

// TriggerBack calls TriggerBack on the DefaultBus
func TriggerBack(eventName string, data interface{}) chan bool {
	return DefaultBus.TriggerBack(eventName, data)
}

// GlobalBind calls GlobalBind on the DefaultBus
func GlobalBind(fn Bindable, name string) {
	DefaultBus.GlobalBind(fn, name)
}

// UnbindAll calls UnbindAll on the DefaultBus
func UnbindAll(opt BindingOption) {
	DefaultBus.UnbindAll(opt)
}

// UnbindAllAndRebind calls UnbindAllAndRebind on the DefaultBus
func UnbindAllAndRebind(bo BindingOption, binds []Bindable, cid int, events []string) {
	DefaultBus.UnbindAllAndRebind(bo, binds, cid, events)
}

// UnbindBindable calls UnbindBindable on the DefaultBus
func UnbindBindable(opt UnbindOption) {
	DefaultBus.UnbindBindable(opt)
}

// Bind calls Bind on the DefaultBus
func Bind(fn Bindable, name string, callerID int) {
	DefaultBus.Bind(fn, name, callerID)
}

// BindPriority calls BindPriority on the DefaultBus
func BindPriority(fn Bindable, opt BindingOption) {
	DefaultBus.BindPriority(fn, opt)
}

// Flush calls Flush on the DefaultBus
func Flush() error {
	return DefaultBus.Flush()
}

// FramesElapsed calls FramesElapsed on the DefaultBus
func FramesElapsed() int {
	return DefaultBus.FramesElapsed()
}

// Reset calls Reset on the DefaultBus
func Reset() {
	DefaultBus.Reset()
}

// ResolvePending calls ResolvePending on the DefaultBus
func ResolvePending() {
	DefaultBus.ResolvePending()
}

// SetTick calls SetTick on the DefaultBus
func SetTick(framerate int) error {
	return DefaultBus.SetTick(framerate)
}

// Stop calls Stop on the DefaultBus
func Stop() error {
	return DefaultBus.Stop()
}

// Update calls Update on the DefaultBus
func Update() error {
	return DefaultBus.Update()
}

// UpdateLoop calls UpdateLoop on the DefaultBus
func UpdateLoop(framerate int, updateCh chan<- bool) error {
	return DefaultBus.UpdateLoop(framerate, updateCh)
}
<commit_msg>Moving priority fix over to legacy<commit_after>package event

// As in collision and mouse, legacy.go lists functions that
// only operate on DefaultBus, a package global bus.

var (
	// DefaultBus is a bus that has additional operations for CIDs, and can
	// be called via event.Call as opposed to bus.Call
	DefaultBus = NewBus()
)

// Trigger an event, but only for one ID, on the default bus
func (cid CID) Trigger(eventName string, data interface{}) {

	go func(eventName string, data interface{}) {
		DefaultBus.mutex.RLock()
		iid := int(cid)
		if idMap, ok := DefaultBus.bindingMap[eventName]; ok {
			if bs, ok := idMap[iid]; ok {
				for i := bs.highIndex - 1; i >= 0; i-- {
					lst := bs.highPriority[i]
					if lst != nil {
						DefaultBus.triggerDefault((*lst).sl, iid, eventName, data)
					}
				}
				DefaultBus.triggerDefault((bs.defaultPriority).sl, iid, eventName, data)

				for i := 0; i < bs.lowIndex; i++ {
					lst := bs.lowPriority[i]
					if lst != nil {
						DefaultBus.triggerDefault((*lst).sl, iid, eventName, data)
					}
				}
			}
		}
		DefaultBus.mutex.RUnlock()
	}(eventName, data)
}

// Bind on a CID is shorthand for bus.Bind(fn, name, cid), on the default bus.
func (cid CID) Bind(fn Bindable, name string) {
	DefaultBus.Bind(fn, name, int(cid))
}

// BindPriority on a CID is shorthand for bus.BindPriority(fn, ...), on the default bus.
func (cid CID) BindPriority(fn Bindable, name string, priority int) {
	DefaultBus.BindPriority(fn, BindingOption{
		Event{
			name,
			int(cid),
		},
		priority,
	})
}

// UnbindAll removes all events with the given cid from the event bus
func (cid CID) UnbindAll() {
	DefaultBus.UnbindAll(BindingOption{
		Event{
			"",
			int(cid),
		},
		0,
	})
}

// UnbindAllAndRebind on a CID is equivalent to bus.UnbindAllAndRebind(..., cid)
func (cid CID) UnbindAllAndRebind(binds []Bindable, events []string) {
	DefaultBus.UnbindAllAndRebind(BindingOption{
		Event{
			"",
			int(cid),
		},
		0,
	}, binds, int(cid), events)
}

// Trigger calls Trigger on the DefaultBus
func Trigger(eventName string, data interface{}) {
	DefaultBus.Trigger(eventName, data)
}

// TriggerBack calls TriggerBack on the DefaultBus
func TriggerBack(eventName string, data interface{}) chan bool {
	return DefaultBus.TriggerBack(eventName, data)
}

// GlobalBind calls GlobalBind on the DefaultBus
func GlobalBind(fn Bindable, name string) {
	DefaultBus.GlobalBind(fn, name)
}

// UnbindAll calls UnbindAll on the DefaultBus
func UnbindAll(opt BindingOption) {
	DefaultBus.UnbindAll(opt)
}

// UnbindAllAndRebind calls UnbindAllAndRebind on the DefaultBus
func UnbindAllAndRebind(bo BindingOption, binds []Bindable, cid int, events []string) {
	DefaultBus.UnbindAllAndRebind(bo, binds, cid, events)
}

// UnbindBindable calls UnbindBindable on the DefaultBus
func UnbindBindable(opt UnbindOption) {
	DefaultBus.UnbindBindable(opt)
}

// Bind calls Bind on the DefaultBus
func Bind(fn Bindable, name string, callerID int) {
	DefaultBus.Bind(fn, name, callerID)
}

// BindPriority calls BindPriority on the DefaultBus
func BindPriority(fn Bindable, opt BindingOption) {
	DefaultBus.BindPriority(fn, opt)
}

// Flush calls Flush on the DefaultBus
func Flush() error {
	return DefaultBus.Flush()
}

// FramesElapsed calls FramesElapsed on the DefaultBus
func FramesElapsed() int {
	return DefaultBus.FramesElapsed()
}

// Reset calls Reset on the DefaultBus
func Reset() {
	DefaultBus.Reset()
}

// ResolvePending calls ResolvePending on the DefaultBus
func ResolvePending() {
	DefaultBus.ResolvePending()
}

// SetTick calls SetTick on the DefaultBus
func SetTick(framerate int) error {
	return DefaultBus.SetTick(framerate)
}

// Stop calls Stop on the DefaultBus
func Stop() error {
	return DefaultBus.Stop()
}

// Update calls Update on the DefaultBus
func Update() error {
	return DefaultBus.Update()
}

// UpdateLoop calls UpdateLoop on the DefaultBus
func UpdateLoop(framerate int, updateCh chan<- bool) error {
	return DefaultBus.UpdateLoop(framerate, updateCh)
}
<|endoftext|>


<commit_before>package sourcegraph

import (
	"encoding/json"
	"fmt"
)

// A Plan is a query plan that fetches the data necessary to satisfy
// (and provide autocomplete suggestions for) a query.
type Plan struct {
	Repos *RepoListOptions
	Defs  *DefListOptions
	Users *UsersListOptions
}

func (p *Plan) String() string {
	b, _ := json.MarshalIndent(p, "", "  ")
	return string(b)
}

// A TokenError is an error about a specific token.
type TokenError struct {
	// Index is the 1-indexed index of the token that caused the error
	// (0 means not associated with any particular token).
	//
	// NOTE: Index is 1-indexed (not 0-indexed) because some
	// TokenErrors don't pertain to a token, and it's misleading if
	// the Index in the JSON is 0 (which could mean that it pertains
	// to the 1st token if index was 0-indexed).
	Index int `json:",omitempty"`

	Token   Token  `json:",omitempty"` // the token that caused the error
	Message string // the public, user-readable error message to display
}

func (e TokenError) Error() string { return fmt.Sprintf("%s (%v)", e.Message, e.Token) }

type jsonTokenError struct {
	Index   int       `json:",omitempty"`
	Token   jsonToken `json:",omitempty"`
	Message string
}

func (e TokenError) MarshalJSON() ([]byte, error) {
	return json.Marshal(jsonTokenError{e.Index, jsonToken{e.Token}, e.Message})
}

func (e *TokenError) UnmarshalJSON(b []byte) error {
	var jv jsonTokenError
	if err := json.Unmarshal(b, &jv); err != nil {
		return err
	}
	*e = TokenError{jv.Index, jv.Token.Token, jv.Message}
	return nil
}
<commit_msg>add Suggestion type<commit_after>package sourcegraph

import (
	"encoding/json"
	"fmt"
)

// A Plan is a query plan that fetches the data necessary to satisfy
// (and provide autocomplete suggestions for) a query.
type Plan struct {
	Repos *RepoListOptions
	Defs  *DefListOptions
	Users *UsersListOptions
}

// A Suggestion is a possible completion of a query (returned by
// Suggest method). It does not attempt to "complete" a query but
// rather indicate to the user what types of queries are possible.
type Suggestion struct {
	// Query is a suggested query related to the original query.
	Query Tokens

	// Description is the human-readable description of Query (usually
	// generated by calling the Describe func).
	Description string `json:",omitempty"`
}

func (p *Plan) String() string {
	b, _ := json.MarshalIndent(p, "", "  ")
	return string(b)
}

// A TokenError is an error about a specific token.
type TokenError struct {
	// Index is the 1-indexed index of the token that caused the error
	// (0 means not associated with any particular token).
	//
	// NOTE: Index is 1-indexed (not 0-indexed) because some
	// TokenErrors don't pertain to a token, and it's misleading if
	// the Index in the JSON is 0 (which could mean that it pertains
	// to the 1st token if index was 0-indexed).
	Index int `json:",omitempty"`

	Token   Token  `json:",omitempty"` // the token that caused the error
	Message string // the public, user-readable error message to display
}

func (e TokenError) Error() string { return fmt.Sprintf("%s (%v)", e.Message, e.Token) }

type jsonTokenError struct {
	Index   int       `json:",omitempty"`
	Token   jsonToken `json:",omitempty"`
	Message string
}

func (e TokenError) MarshalJSON() ([]byte, error) {
	return json.Marshal(jsonTokenError{e.Index, jsonToken{e.Token}, e.Message})
}

func (e *TokenError) UnmarshalJSON(b []byte) error {
	var jv jsonTokenError
	if err := json.Unmarshal(b, &jv); err != nil {
		return err
	}
	*e = TokenError{jv.Index, jv.Token.Token, jv.Message}
	return nil
}
<|endoftext|>


<commit_before>// Copyright 2015 Hajime Hoshi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build ignore

// Note:
//   * Respect GLFW key names
//   * https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.keyCode
//   * It is best to replace keyCode with code, but many browsers don't implement it.

package main

import (
	"log"
	"os"
	"sort"
	"strconv"
	"strings"
	"text/template"
)

var (
	nameToCodes       map[string][]string
	keyCodeToNameEdge map[int]string
)

func init() {
	nameToCodes = map[string][]string{
		"Comma":        {"Comma"},
		"Period":       {"Period"},
		"Alt":          {"AltLeft", "AltRight"},
		"CapsLock":     {"CapsLock"},
		"Control":      {"ControlLeft", "ControlRight"},
		"Shift":        {"ShiftLeft", "ShiftRight"},
		"Enter":        {"Enter"},
		"Space":        {"Space"},
		"Tab":          {"Tab"},
		"Delete":       {"Delete"},
		"End":          {"End"},
		"Home":         {"Home"},
		"Insert":       {"Insert"},
		"PageDown":     {"PageDown"},
		"PageUp":       {"PageUp"},
		"Down":         {"ArrowDown"},
		"Left":         {"ArrowLeft"},
		"Right":        {"ArrowRight"},
		"Up":           {"ArrowUp"},
		"Escape":       {"Escape"},
		"Backspace":    {"Backspace"},
		"Apostrophe":   {"Quote"},
		"Minus":        {"Minus"},
		"Slash":        {"Slash"},
		"Semicolon":    {"Semicolon"},
		"Equal":        {"Equal"},
		"LeftBracket":  {"BracketLeft"},
		"Backslash":    {"Backslash"},
		"RightBracket": {"BracketRight"},
		"GraveAccent":  {"Backquote"},
		"NumLock":      {"NumLock"},
		"Pause":        {"Pause"},
		"PrintScreen":  {"PrintScreen"},
		"ScrollLock":   {"ScrollLock"},
		"Menu":         {"ContextMenu"},
	}
	// ASCII: 0 - 9
	for c := '0'; c <= '9'; c++ {
		nameToCodes[string(c)] = []string{"Digit" + string(c)}
	}
	// ASCII: A - Z
	for c := 'A'; c <= 'Z'; c++ {
		nameToCodes[string(c)] = []string{"Key" + string(c)}
	}
	// Function keys
	for i := 1; i <= 12; i++ {
		nameToCodes["F"+strconv.Itoa(i)] = []string{"F" + strconv.Itoa(i)}
	}
	// Numpad
	// https://www.w3.org/TR/uievents-code/#key-numpad-section
	for c := '0'; c <= '9'; c++ {
		nameToCodes["KP"+string(c)] = []string{"Numpad" + string(c)}
	}
	nameToCodes["KPDecimal"] = []string{"NumpadDecimal"}
	nameToCodes["KPDivide"] = []string{"NumpadDivide"}
	nameToCodes["KPMultiply"] = []string{"NumpadMultiply"}
	nameToCodes["KPSubtract"] = []string{"NumpadSubtract"}
	nameToCodes["KPAdd"] = []string{"NumpadAdd"}
	nameToCodes["KPEnter"] = []string{"NumpadEnter"}
	nameToCodes["KPEqual"] = []string{"NumpadEqual"}
}

func init() {
	keyCodeToNameEdge = map[int]string{
		0xbc: "Comma",
		0xbe: "Period",
		0x12: "Alt",
		0x14: "CapsLock",
		0x11: "Control",
		0x10: "Shift",
		0x0D: "Enter",
		0x20: "Space",
		0x09: "Tab",
		0x2E: "Delete",
		0x23: "End",
		0x24: "Home",
		0x2D: "Insert",
		0x22: "PageDown",
		0x21: "PageUp",
		0x28: "Down",
		0x25: "Left",
		0x27: "Right",
		0x26: "Up",
		0x1B: "Escape",
		0xde: "Apostrophe",
		0xbd: "Minus",
		0xbf: "Slash",
		0xba: "Semicolon",
		0xbb: "Equal",
		0xdb: "LeftBracket",
		0xdc: "Backslash",
		0xdd: "RightBracket",
		0xc0: "GraveAccent",
		0x08: "Backspace",
		0x90: "NumLock",
		0x6e: "KPDecimal",
		0x6f: "KPDivide",
		0x6a: "KPMultiply",
		0x6d: "KPSubtract",
		0x6b: "KPAdd",
		0x13: "Pause",
		0x91: "ScrollLock",
		0x5d: "Menu",

		// On Edge, this key does not work. PrintScreen works only on keyup event.
		// 0x2C: "PrintScreen",

		// On Edge, it is impossible to tell KPEnter and Enter / KPEqual and Equal.
		// 0x0d: "KPEnter",
		// 0x0c: "KPEqual",
	}
	// ASCII: 0 - 9
	for c := '0'; c <= '9'; c++ {
		keyCodeToNameEdge[int(c)] = string(c)
	}
	// ASCII: A - Z
	for c := 'A'; c <= 'Z'; c++ {
		keyCodeToNameEdge[int(c)] = string(c)
	}
	// Function keys
	for i := 1; i <= 12; i++ {
		keyCodeToNameEdge[0x70+i-1] = "F" + strconv.Itoa(i)
	}
	// Numpad keys
	for c := '0'; c <= '9'; c++ {
		keyCodeToNameEdge[0x60+int(c-'0')] = "KP" + string(c)
	}
}

const ebitenKeysTmpl = `{{.License}}

{{.DoNotEdit}}

package ebiten

import (
	"strings"

	"github.com/hajimehoshi/ebiten/internal/input"
)

// A Key represents a keyboard key.
// These keys represent pysical keys of US keyboard.
// For example, KeyQ represents Q key on US keyboards and ' (quote) key on Dvorak keyboards.
type Key int

// Keys.
const (
{{range $index, $name := .KeyNames}}Key{{$name}} Key = Key(input.Key{{$name}})
{{end}}	KeyMax Key = Key{{.LastKeyName}}
)

// String returns a string representing the key.
//
// If k is an undefined key, String returns an empty string.
func (k Key) String() string {
	switch k {
	{{range $name := .KeyNames}}case Key{{$name}}:
		return {{$name | printf "%q"}}
	{{end}}}
	return ""
}

func keyNameToKey(name string) (Key, bool) {
	switch strings.ToLower(name) {
	{{range $name := .KeyNames}}case {{$name | printf "%q" | ToLower}}:
		return Key{{$name}}, true
	{{end}}}
	return 0, false
}
`

const inputKeysTmpl = `{{.License}}

{{.DoNotEdit}}

package input

type Key int

const (
{{range $index, $name := .KeyNames}}Key{{$name}}{{if eq $index 0}} Key = iota{{end}}
{{end}}
)
`

const inputKeysGlfwTmpl = `{{.License}}

{{.DoNotEdit}}

{{.BuildTag}}

package input

import (
	glfw "github.com/go-gl/glfw/v3.2/glfw"
)

var glfwKeyCodeToKey = map[glfw.Key]Key{
{{range $index, $name := .KeyNamesWithoutMods}}glfw.Key{{$name}}: Key{{$name}},
{{end}}
	glfw.KeyLeftAlt:      KeyAlt,
	glfw.KeyRightAlt:     KeyAlt,
	glfw.KeyLeftControl:  KeyControl,
	glfw.KeyRightControl: KeyControl,
	glfw.KeyLeftShift:    KeyShift,
	glfw.KeyRightShift:   KeyShift,
}
`

const inputKeysJSTmpl = `{{.License}}

{{.DoNotEdit}}

{{.BuildTag}}

package input

var keyToCodes = map[Key][]string{
{{range $name, $codes := .NameToCodes}}Key{{$name}}: []string{
{{range $code := $codes}}"{{$code}}",{{end}}
},
{{end}}
}

var keyCodeToKeyEdge = map[int]Key{
{{range $code, $name := .KeyCodeToNameEdge}}{{$code}}: Key{{$name}},
{{end}}
}
`

type KeyNames []string

func (k KeyNames) digit(name string) int {
	if len(name) != 1 {
		return -1
	}
	c := name[0]
	if c < '0' || '9' < c {
		return -1
	}
	return int(c - '0')
}

func (k KeyNames) alphabet(name string) rune {
	if len(name) != 1 {
		return -1
	}
	c := rune(name[0])
	if c < 'A' || 'Z' < c {
		return -1
	}
	return c
}

func (k KeyNames) function(name string) int {
	if len(name) < 2 {
		return -1
	}
	if name[0] != 'F' {
		return -1
	}
	i, err := strconv.Atoi(name[1:])
	if err != nil {
		return -1
	}
	return i
}

func (k KeyNames) Len() int {
	return len(k)
}

func (k KeyNames) Less(i, j int) bool {
	k0, k1 := k[i], k[j]
	d0, d1 := k.digit(k0), k.digit(k1)
	a0, a1 := k.alphabet(k0), k.alphabet(k1)
	f0, f1 := k.function(k0), k.function(k1)
	if d0 != -1 {
		if d1 != -1 {
			return d0 < d1
		}
		return true
	}
	if a0 != -1 {
		if d1 != -1 {
			return false
		}
		if a1 != -1 {
			return a0 < a1
		}
		return true
	}
	if d1 != -1 {
		return false
	}
	if a1 != -1 {
		return false
	}
	if f0 != -1 && f1 != -1 {
		return f0 < f1
	}
	return k0 < k1
}

func (k KeyNames) Swap(i, j int) {
	k[i], k[j] = k[j], k[i]
}

const license = `// Copyright 2013 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
`

func main() {
	// Follow the standard comment rule (https://golang.org/s/generatedcode).
	doNotEdit := "// Code generated by genkeys.go using 'go generate'. DO NOT EDIT."

	namesSet := map[string]struct{}{}
	namesWithoutModsSet := map[string]struct{}{}
	codes := []string{}
	for name, cs := range nameToCodes {
		namesSet[name] = struct{}{}
		codes = append(codes, cs...)
		if name != "Alt" && name != "Control" && name != "Shift" {
			namesWithoutModsSet[name] = struct{}{}
		}
	}
	names := []string{}
	namesWithoutMods := []string{}
	for n := range namesSet {
		names = append(names, n)
	}
	for n := range namesWithoutModsSet {
		namesWithoutMods = append(namesWithoutMods, n)
	}

	sort.Sort(KeyNames(names))
	sort.Sort(KeyNames(namesWithoutMods))
	sort.Strings(codes)

	for path, tmpl := range map[string]string{
		"keys.go":                     ebitenKeysTmpl,
		"internal/input/keys.go":      inputKeysTmpl,
		"internal/input/keys_glfw.go": inputKeysGlfwTmpl,
		"internal/input/keys_js.go":   inputKeysJSTmpl,
	} {
		f, err := os.Create(path)
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()

		funcs := template.FuncMap{
			"ToLower": strings.ToLower,
		}
		tmpl, err := template.New(path).Funcs(funcs).Parse(tmpl)
		if err != nil {
			log.Fatal(err)
		}

		// The build tag can't be included in the templates because of `go vet`.
		// Pass the build tag and extract this in the template to make `go vet` happy.
		buildTag := ""
		switch path {
		case "internal/input/keys_glfw.go":
			buildTag = "// +build darwin freebsd linux windows" +
				"\n// +build !js" +
				"\n// +build !android" +
				"\n// +build !ios"
		case "internal/input/keys_js.go":
			buildTag = "// +build js"
		}
		// NOTE: According to godoc, maps are automatically sorted by key.
		if err := tmpl.Execute(f, map[string]interface{}{
			"License":             license,
			"DoNotEdit":           doNotEdit,
			"BuildTag":            buildTag,
			"NameToCodes":         nameToCodes,
			"KeyCodeToNameEdge":   keyCodeToNameEdge,
			"Codes":               codes,
			"KeyNames":            names,
			"LastKeyName":         names[len(names)-1],
			"KeyNamesWithoutMods": namesWithoutMods,
		}); err != nil {
			log.Fatal(err)
		}
	}
}
<commit_msg>input: Refactoring<commit_after>// Copyright 2015 Hajime Hoshi
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build ignore

// Note:
//   * Respect GLFW key names
//   * https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.keyCode
//   * It is best to replace keyCode with code, but many browsers don't implement it.

package main

import (
	"log"
	"os"
	"sort"
	"strconv"
	"strings"
	"text/template"
)

var (
	nameToJSKeyCodes  map[string][]string
	keyCodeToNameEdge map[int]string
)

func init() {
	nameToJSKeyCodes = map[string][]string{
		"Comma":        {"Comma"},
		"Period":       {"Period"},
		"Alt":          {"AltLeft", "AltRight"},
		"CapsLock":     {"CapsLock"},
		"Control":      {"ControlLeft", "ControlRight"},
		"Shift":        {"ShiftLeft", "ShiftRight"},
		"Enter":        {"Enter"},
		"Space":        {"Space"},
		"Tab":          {"Tab"},
		"Delete":       {"Delete"},
		"End":          {"End"},
		"Home":         {"Home"},
		"Insert":       {"Insert"},
		"PageDown":     {"PageDown"},
		"PageUp":       {"PageUp"},
		"Down":         {"ArrowDown"},
		"Left":         {"ArrowLeft"},
		"Right":        {"ArrowRight"},
		"Up":           {"ArrowUp"},
		"Escape":       {"Escape"},
		"Backspace":    {"Backspace"},
		"Apostrophe":   {"Quote"},
		"Minus":        {"Minus"},
		"Slash":        {"Slash"},
		"Semicolon":    {"Semicolon"},
		"Equal":        {"Equal"},
		"LeftBracket":  {"BracketLeft"},
		"Backslash":    {"Backslash"},
		"RightBracket": {"BracketRight"},
		"GraveAccent":  {"Backquote"},
		"NumLock":      {"NumLock"},
		"Pause":        {"Pause"},
		"PrintScreen":  {"PrintScreen"},
		"ScrollLock":   {"ScrollLock"},
		"Menu":         {"ContextMenu"},
	}
	// ASCII: 0 - 9
	for c := '0'; c <= '9'; c++ {
		nameToJSKeyCodes[string(c)] = []string{"Digit" + string(c)}
	}
	// ASCII: A - Z
	for c := 'A'; c <= 'Z'; c++ {
		nameToJSKeyCodes[string(c)] = []string{"Key" + string(c)}
	}
	// Function keys
	for i := 1; i <= 12; i++ {
		nameToJSKeyCodes["F"+strconv.Itoa(i)] = []string{"F" + strconv.Itoa(i)}
	}
	// Numpad
	// https://www.w3.org/TR/uievents-code/#key-numpad-section
	for c := '0'; c <= '9'; c++ {
		nameToJSKeyCodes["KP"+string(c)] = []string{"Numpad" + string(c)}
	}
	nameToJSKeyCodes["KPDecimal"] = []string{"NumpadDecimal"}
	nameToJSKeyCodes["KPDivide"] = []string{"NumpadDivide"}
	nameToJSKeyCodes["KPMultiply"] = []string{"NumpadMultiply"}
	nameToJSKeyCodes["KPSubtract"] = []string{"NumpadSubtract"}
	nameToJSKeyCodes["KPAdd"] = []string{"NumpadAdd"}
	nameToJSKeyCodes["KPEnter"] = []string{"NumpadEnter"}
	nameToJSKeyCodes["KPEqual"] = []string{"NumpadEqual"}
}

func init() {
	keyCodeToNameEdge = map[int]string{
		0xbc: "Comma",
		0xbe: "Period",
		0x12: "Alt",
		0x14: "CapsLock",
		0x11: "Control",
		0x10: "Shift",
		0x0D: "Enter",
		0x20: "Space",
		0x09: "Tab",
		0x2E: "Delete",
		0x23: "End",
		0x24: "Home",
		0x2D: "Insert",
		0x22: "PageDown",
		0x21: "PageUp",
		0x28: "Down",
		0x25: "Left",
		0x27: "Right",
		0x26: "Up",
		0x1B: "Escape",
		0xde: "Apostrophe",
		0xbd: "Minus",
		0xbf: "Slash",
		0xba: "Semicolon",
		0xbb: "Equal",
		0xdb: "LeftBracket",
		0xdc: "Backslash",
		0xdd: "RightBracket",
		0xc0: "GraveAccent",
		0x08: "Backspace",
		0x90: "NumLock",
		0x6e: "KPDecimal",
		0x6f: "KPDivide",
		0x6a: "KPMultiply",
		0x6d: "KPSubtract",
		0x6b: "KPAdd",
		0x13: "Pause",
		0x91: "ScrollLock",
		0x5d: "Menu",

		// On Edge, this key does not work. PrintScreen works only on keyup event.
		// 0x2C: "PrintScreen",

		// On Edge, it is impossible to tell KPEnter and Enter / KPEqual and Equal.
		// 0x0d: "KPEnter",
		// 0x0c: "KPEqual",
	}
	// ASCII: 0 - 9
	for c := '0'; c <= '9'; c++ {
		keyCodeToNameEdge[int(c)] = string(c)
	}
	// ASCII: A - Z
	for c := 'A'; c <= 'Z'; c++ {
		keyCodeToNameEdge[int(c)] = string(c)
	}
	// Function keys
	for i := 1; i <= 12; i++ {
		keyCodeToNameEdge[0x70+i-1] = "F" + strconv.Itoa(i)
	}
	// Numpad keys
	for c := '0'; c <= '9'; c++ {
		keyCodeToNameEdge[0x60+int(c-'0')] = "KP" + string(c)
	}
}

const ebitenKeysTmpl = `{{.License}}

{{.DoNotEdit}}

package ebiten

import (
	"strings"

	"github.com/hajimehoshi/ebiten/internal/input"
)

// A Key represents a keyboard key.
// These keys represent pysical keys of US keyboard.
// For example, KeyQ represents Q key on US keyboards and ' (quote) key on Dvorak keyboards.
type Key int

// Keys.
const (
{{range $index, $name := .KeyNames}}Key{{$name}} Key = Key(input.Key{{$name}})
{{end}}	KeyMax Key = Key{{.LastKeyName}}
)

// String returns a string representing the key.
//
// If k is an undefined key, String returns an empty string.
func (k Key) String() string {
	switch k {
	{{range $name := .KeyNames}}case Key{{$name}}:
		return {{$name | printf "%q"}}
	{{end}}}
	return ""
}

func keyNameToKey(name string) (Key, bool) {
	switch strings.ToLower(name) {
	{{range $name := .KeyNames}}case {{$name | printf "%q" | ToLower}}:
		return Key{{$name}}, true
	{{end}}}
	return 0, false
}
`

const inputKeysTmpl = `{{.License}}

{{.DoNotEdit}}

package input

type Key int

const (
{{range $index, $name := .KeyNames}}Key{{$name}}{{if eq $index 0}} Key = iota{{end}}
{{end}}
)
`

const inputKeysGlfwTmpl = `{{.License}}

{{.DoNotEdit}}

{{.BuildTag}}

package input

import (
	glfw "github.com/go-gl/glfw/v3.2/glfw"
)

var glfwKeyCodeToKey = map[glfw.Key]Key{
{{range $index, $name := .KeyNamesWithoutMods}}glfw.Key{{$name}}: Key{{$name}},
{{end}}
	glfw.KeyLeftAlt:      KeyAlt,
	glfw.KeyRightAlt:     KeyAlt,
	glfw.KeyLeftControl:  KeyControl,
	glfw.KeyRightControl: KeyControl,
	glfw.KeyLeftShift:    KeyShift,
	glfw.KeyRightShift:   KeyShift,
}
`

const inputKeysJSTmpl = `{{.License}}

{{.DoNotEdit}}

{{.BuildTag}}

package input

var keyToCodes = map[Key][]string{
{{range $name, $codes := .NameToJSKeyCodes}}Key{{$name}}: []string{
{{range $code := $codes}}"{{$code}}",{{end}}
},
{{end}}
}

var keyCodeToKeyEdge = map[int]Key{
{{range $code, $name := .KeyCodeToNameEdge}}{{$code}}: Key{{$name}},
{{end}}
}
`

type KeyNames []string

func (k KeyNames) digit(name string) int {
	if len(name) != 1 {
		return -1
	}
	c := name[0]
	if c < '0' || '9' < c {
		return -1
	}
	return int(c - '0')
}

func (k KeyNames) alphabet(name string) rune {
	if len(name) != 1 {
		return -1
	}
	c := rune(name[0])
	if c < 'A' || 'Z' < c {
		return -1
	}
	return c
}

func (k KeyNames) function(name string) int {
	if len(name) < 2 {
		return -1
	}
	if name[0] != 'F' {
		return -1
	}
	i, err := strconv.Atoi(name[1:])
	if err != nil {
		return -1
	}
	return i
}

func (k KeyNames) Len() int {
	return len(k)
}

func (k KeyNames) Less(i, j int) bool {
	k0, k1 := k[i], k[j]
	d0, d1 := k.digit(k0), k.digit(k1)
	a0, a1 := k.alphabet(k0), k.alphabet(k1)
	f0, f1 := k.function(k0), k.function(k1)
	if d0 != -1 {
		if d1 != -1 {
			return d0 < d1
		}
		return true
	}
	if a0 != -1 {
		if d1 != -1 {
			return false
		}
		if a1 != -1 {
			return a0 < a1
		}
		return true
	}
	if d1 != -1 {
		return false
	}
	if a1 != -1 {
		return false
	}
	if f0 != -1 && f1 != -1 {
		return f0 < f1
	}
	return k0 < k1
}

func (k KeyNames) Swap(i, j int) {
	k[i], k[j] = k[j], k[i]
}

const license = `// Copyright 2013 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
`

func main() {
	// Follow the standard comment rule (https://golang.org/s/generatedcode).
	doNotEdit := "// Code generated by genkeys.go using 'go generate'. DO NOT EDIT."

	namesSet := map[string]struct{}{}
	namesWithoutModsSet := map[string]struct{}{}
	codes := []string{}
	for name, cs := range nameToJSKeyCodes {
		namesSet[name] = struct{}{}
		codes = append(codes, cs...)
		if name != "Alt" && name != "Control" && name != "Shift" {
			namesWithoutModsSet[name] = struct{}{}
		}
	}
	names := []string{}
	namesWithoutMods := []string{}
	for n := range namesSet {
		names = append(names, n)
	}
	for n := range namesWithoutModsSet {
		namesWithoutMods = append(namesWithoutMods, n)
	}

	sort.Sort(KeyNames(names))
	sort.Sort(KeyNames(namesWithoutMods))
	sort.Strings(codes)

	for path, tmpl := range map[string]string{
		"keys.go":                     ebitenKeysTmpl,
		"internal/input/keys.go":      inputKeysTmpl,
		"internal/input/keys_glfw.go": inputKeysGlfwTmpl,
		"internal/input/keys_js.go":   inputKeysJSTmpl,
	} {
		f, err := os.Create(path)
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()

		funcs := template.FuncMap{
			"ToLower": strings.ToLower,
		}
		tmpl, err := template.New(path).Funcs(funcs).Parse(tmpl)
		if err != nil {
			log.Fatal(err)
		}

		// The build tag can't be included in the templates because of `go vet`.
		// Pass the build tag and extract this in the template to make `go vet` happy.
		buildTag := ""
		switch path {
		case "internal/input/keys_glfw.go":
			buildTag = "// +build darwin freebsd linux windows" +
				"\n// +build !js" +
				"\n// +build !android" +
				"\n// +build !ios"
		case "internal/input/keys_js.go":
			buildTag = "// +build js"
		}
		// NOTE: According to godoc, maps are automatically sorted by key.
		if err := tmpl.Execute(f, map[string]interface{}{
			"License":             license,
			"DoNotEdit":           doNotEdit,
			"BuildTag":            buildTag,
			"NameToJSKeyCodes":    nameToJSKeyCodes,
			"KeyCodeToNameEdge":   keyCodeToNameEdge,
			"Codes":               codes,
			"KeyNames":            names,
			"LastKeyName":         names[len(names)-1],
			"KeyNamesWithoutMods": namesWithoutMods,
		}); err != nil {
			log.Fatal(err)
		}
	}
}
<|endoftext|>


<commit_before>package common

import (
	"fmt"
	"github.com/meshbird/meshbird/secure"
	log "github.com/mgutz/logxi/v1"
	"os"
	"sync"
)

type LocalNode struct {
	Node

	secret *secure.NetworkSecret
	config *Config
	state  *State

	mutex     sync.Mutex
	waitGroup sync.WaitGroup

	services map[string]Service

	logger log.Logger
}

func NewLocalNode(cfg *Config) (*LocalNode, error) {
	var err error
	n := new(LocalNode)
	n.logger = log.NewLogger(log.NewConcurrentWriter(os.Stderr), "[localnode] ")

	n.secret, err = secure.NetworkSecretUnmarshal(cfg.SecretKey)
	if err != nil {
		return nil, err
	}

	n.config = cfg
	n.config.NetworkID = n.secret.InfoHash()
	n.state = NewState(n.secret)

	n.services = make(map[string]Service)

	n.AddService(&NetTable{})
	n.AddService(&ListenerService{})
	n.AddService(&DiscoveryDHT{})
	n.AddService(&InterfaceService{})
	n.AddService(&STUNService{})
	n.AddService(&UPnPService{})
	n.AddService(&HttpService{})
	return n, nil
}

func (n *LocalNode) Config() Config {
	return *n.config
}

func (n *LocalNode) State() State {
	return *n.state
}

func (n *LocalNode) AddService(srv Service) {
	n.services[srv.Name()] = srv
}

func (n *LocalNode) Start() error {
	for name, service := range n.services {
		if n.logger.IsInfo() {
			n.logger.Info("Initializing %s...", name)
		}
		if err := service.Init(n); err != nil {
			return fmt.Errorf("Initialision of %s finished with error: %s", service.Name(), err)
		}
		n.waitGroup.Add(1)
		go func(srv Service) {
			defer n.waitGroup.Done()
			if n.logger.IsInfo() {
				n.logger.Info(fmt.Sprintf("[%s] service run", srv.Name()))
			}
			if err := srv.Run(); err != nil {
				n.logger.Error(fmt.Sprintf("[%s] error: %s", srv.Name(), err))
			}
		}(service)
	}
	return nil
}

func (n *LocalNode) Service(name string) Service {
	service, ok := n.services[name]
	if !ok {
		n.logger.Fatal(fmt.Sprintf("Service %s not found", name))
	}
	return service
}

func (n *LocalNode) WaitStop() {
	n.waitGroup.Wait()
}

func (n *LocalNode) Stop() error {
	if n.logger.IsInfo() {
		n.logger.Info("Closing up local node")
	}
	for _, service := range n.services {
		service.Stop()
	}
	return nil
}

func (n *LocalNode) NetworkSecret() *secure.NetworkSecret {
	return n.secret
}

func (n *LocalNode) NetTable() *NetTable {
	service, ok := n.services["net-table"]
	if !ok {
		panic("net-table not found")
	}
	return service.(*NetTable)
}
<commit_msg>Small fix for localnode logging<commit_after>package common

import (
	"fmt"
	"github.com/meshbird/meshbird/secure"
	log "github.com/mgutz/logxi/v1"
	"os"
	"sync"
)

type LocalNode struct {
	Node

	secret *secure.NetworkSecret
	config *Config
	state  *State

	mutex     sync.Mutex
	waitGroup sync.WaitGroup

	services map[string]Service

	logger log.Logger
}

func NewLocalNode(cfg *Config) (*LocalNode, error) {
	var err error
	n := new(LocalNode)
	n.logger = log.NewLogger(log.NewConcurrentWriter(os.Stderr), "[localnode] ")

	n.secret, err = secure.NetworkSecretUnmarshal(cfg.SecretKey)
	if err != nil {
		return nil, err
	}

	n.config = cfg
	n.config.NetworkID = n.secret.InfoHash()
	n.state = NewState(n.secret)

	n.services = make(map[string]Service)

	n.AddService(&NetTable{})
	n.AddService(&ListenerService{})
	n.AddService(&DiscoveryDHT{})
	n.AddService(&InterfaceService{})
	n.AddService(&STUNService{})
	n.AddService(&UPnPService{})
	n.AddService(&HttpService{})
	return n, nil
}

func (n *LocalNode) Config() Config {
	return *n.config
}

func (n *LocalNode) State() State {
	return *n.state
}

func (n *LocalNode) AddService(srv Service) {
	n.services[srv.Name()] = srv
}

func (n *LocalNode) Start() error {
	for name, service := range n.services {
		if n.logger.IsInfo() {
			n.logger.Info(fmt.Sprintf("Initializing %s...", name))
		}
		if err := service.Init(n); err != nil {
			return fmt.Errorf("Initialision of %s finished with error: %s", service.Name(), err)
		}
		n.waitGroup.Add(1)
		go func(srv Service) {
			defer n.waitGroup.Done()
			if n.logger.IsInfo() {
				n.logger.Info(fmt.Sprintf("[%s] service run", srv.Name()))
			}
			if err := srv.Run(); err != nil {
				n.logger.Error(fmt.Sprintf("[%s] error: %s", srv.Name(), err))
			}
		}(service)
	}
	return nil
}

func (n *LocalNode) Service(name string) Service {
	service, ok := n.services[name]
	if !ok {
		n.logger.Fatal(fmt.Sprintf("Service %s not found", name))
	}
	return service
}

func (n *LocalNode) WaitStop() {
	n.waitGroup.Wait()
}

func (n *LocalNode) Stop() error {
	if n.logger.IsInfo() {
		n.logger.Info("Closing up local node")
	}
	for _, service := range n.services {
		service.Stop()
	}
	return nil
}

func (n *LocalNode) NetworkSecret() *secure.NetworkSecret {
	return n.secret
}

func (n *LocalNode) NetTable() *NetTable {
	service, ok := n.services["net-table"]
	if !ok {
		panic("net-table not found")
	}
	return service.(*NetTable)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"

	"github.com/Tomohiro/gyazo"
)

// GYAZO_TOKEN="Your Gyazo access token" go run list.go
func main() {
	token := os.Getenv("GYAZO_TOKEN")
	if token == "" {
		fmt.Fprintf(os.Stderr, "Environment variable `GYAZO_TOKEN` is empty.")
		os.Exit(1)
	}
	client, _ := gyazo.NewClient(token)
	images, _ := client.List(nil)
	for _, v := range *images {
		fmt.Println(v.PermalinkURL)
	}
}
<commit_msg>Update example<commit_after>package main

import (
	"fmt"
	"os"

	"github.com/Tomohiro/gyazo"
)

// GYAZO_TOKEN="Your Gyazo access token" go run list.go
func main() {
	token := os.Getenv("GYAZO_TOKEN")
	if token == "" {
		fmt.Fprintf(os.Stderr, "Environment variable `GYAZO_TOKEN` is empty.")
		os.Exit(1)
	}
	client, _ := gyazo.NewClient(token)
	list, _ := client.List(&gyazo.ListOptions{Page: 1})
	for _, v := range *list.Images {
		fmt.Printf("%+v \n", v)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"os"

	"github.com/kyokomi/paypal"
	"github.com/k0kubun/pp"
)

func main() {
	log.SetFlags(log.Llongfile)

	clientID := os.Getenv("PAYPAL_CLIENTID")
	if clientID == "" {
		log.Fatalln("get env")
	}
	secret := os.Getenv("PAYPAL_SECRET")
	if secret == "" {
		log.Fatalln("get env")
	}

	opts := paypal.NewOptions(clientID, secret)
	opts.Sandbox = true
	client := paypal.NewClient(opts)

	req := paypal.PaymentCreateRequest{}
	req.Intent = "sale"
	req.Payer.PaymentMethod = "paypal"
	req.RedirectURLs.CancelURL = "http://localhost:8000//paypal/payment/cancel"
	req.RedirectURLs.ReturnURL = "http://localhost:8000/paypal/payment/execute"
	req.Transactions = []paypal.Transaction{
		{
			Amount: paypal.Amount{
				Total:    "9.99",
				Currency: "USD",
			},
			Description: "example paypal",
		},
	}

	adminToken, err := client.OAuth2.GetToken()
	if err != nil {
		log.Println(err)
	}
	pp.Println(adminToken)

	client.Admin = adminToken
	if response, err := client.Payment.Create(req); err != nil {
		log.Println(err)
	} else {
		pp.Println(response)
	}
}
<commit_msg>fix example<commit_after>package main

import (
	"log"
	"os"

	"fmt"
	"time"

	"github.com/k0kubun/pp"
	"github.com/kyokomi/paypal"
)

func main() {
	log.SetFlags(log.Llongfile)

	clientID := os.Getenv("PAYPAL_CLIENTID")
	if clientID == "" {
		log.Fatalln("get env")
	}
	secret := os.Getenv("PAYPAL_SECRET")
	if secret == "" {
		log.Fatalln("get env")
	}

	opts := paypal.NewOptions(clientID, secret)
	opts.Sandbox = true
	client := paypal.NewClient(opts)

	req := paypal.PaymentCreateRequest{}
	req.Intent = "sale"
	req.Payer.PaymentMethod = "paypal"
	req.RedirectURLs.CancelURL = "http://localhost:8000//paypal/payment/cancel"
	req.RedirectURLs.ReturnURL = "http://localhost:8000/paypal/payment/execute"
	req.Transactions = []paypal.Transaction{
		{
			Amount: paypal.Amount{
				Total:    "9.99",
				Currency: "USD",
			},
			Description: "example paypal",
		},
	}

	adminToken, err := client.OAuth2.GetToken()
	if err != nil {
		log.Println(err)
	}
	pp.Println(adminToken)

	client.Admin = adminToken
	if response, err := client.Payment.Create(req); err != nil {
		log.Println(err)
	} else {
		pp.Println(response)

		executeReq := paypal.PaymentExecuteRequest{}
		executeReq.PayerID = response.Payer.PayerInfo.PayerID
		if err := client.Payment.Execute(response.ID, executeReq); err != nil {
			log.Println(err)
		}

		payoutReq := paypal.PaymentPayoutRequest{}
		payoutReq.SenderBatchHeader.EmailSubject = "test example"
		payoutReq.Items = make([]paypal.PayoutItem, 0)
		item := paypal.PayoutItem{}
		item.Note = "test"
		item.Receiver = "kyokomi1220dev-performer@gmail.com"
		item.RecipientType = paypal.RECIPIENT_EMAIL
		item.SenderItemID = fmt.Sprintf("%d", time.Now().UnixNano())
		item.Amount.Value = "9.01"
		item.Amount.Currency = "USD"
		payoutReq.Items = append(payoutReq.Items, item)
		if err := client.Payment.Payout(true, payoutReq); err != nil {
			log.Println(err)
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"net/http"

	"github.com/gonfire/fire"
	"github.com/gonfire/fire/auth"
	"github.com/gonfire/fire/tools"
)

type post struct {
	fire.Base `json:"-" bson:",inline" fire:"posts"`
	Slug      string `json:"slug" valid:"required" bson:"slug"`
	Title     string `json:"title" valid:"required"`
	Body      string `json:"body" valid:"-"`
}

func main() {
	// create store
	store := fire.MustCreateStore("mongodb://localhost/fire-example")

	// create policy
	policy := auth.DefaultPolicy("abcd1234abcd1234")

	// enable OAuth2 password grant
	policy.PasswordGrant = true

	// create authenticator
	authenticator := auth.New(store, policy)

	// create group
	group := fire.NewGroup()

	// register post controller
	group.Add(&fire.Controller{
		Model:      &post{},
		Store:      store,
		Filters:    []string{"slug"},
		Sorters:    []string{"slug"},
		Authorizer: auth.Callback("default"),
		Validator:  fire.ModelValidator(),
	})

	// create new router
	router := http.NewServeMux()

	// create oauth2 and api endpoint
	authEndpoint := authenticator.Endpoint("/oauth2/")
	apiEndpoint := group.Endpoint("/api/")

	// create spa asset server
	spaEndpoint := tools.DefaultAssetServer("../.test/assets/")

	// create protector, logger
	protector := tools.DefaultProtector()
	logger := tools.DefaultRequestLogger()

	// create authorizer
	authorizer := authenticator.Authorizer("")

	// mount authenticator, controller group, asset server
	router.Handle("/oauth2/", fire.Compose(authEndpoint, protector, logger))
	router.Handle("/api/", fire.Compose(apiEndpoint, protector, logger, authorizer))
	router.Handle("/", fire.Compose(spaEndpoint, protector, logger))

	// run app
	http.ListenAndServe("localhost:8080", router)
}
<commit_msg>removed example<commit_after><|endoftext|>


<commit_before>package main

import (
	"fmt"

	"github.com/gemsi/grok"
)

func main() {
	fmt.Println("# Default Capture :\n")
	g := grok.New()
	values, _ := g.Parse("%{COMMONAPACHELOG}", `127.0.0.1 - - [23/Apr/2014:22:58:32 +0200] "GET /index.php HTTP/1.1" 404 207`)
	for k, v := range values {
		fmt.Printf("%+15s: %s\n", k, v)
	}

	fmt.Println("\n\n# Named Capture :\n")
	g = grok.New(grok.NAMEDCAPTURE)
	values, _ = g.Parse("%{COMMONAPACHELOG}", `127.0.0.1 - - [23/Apr/2014:22:58:32 +0200] "GET /index.php HTTP/1.1" 404 207`)
	for k, v := range values {
		fmt.Printf("%+15s: %s\n", k, v)
	}
}
<commit_msg>grok.AddPattern example added<commit_after>package main

import (
	"fmt"

	"github.com/gemsi/grok"
)

func main() {
	fmt.Println("# Default Capture :\n")
	g := grok.New()
	values, _ := g.Parse("%{COMMONAPACHELOG}", `127.0.0.1 - - [23/Apr/2014:22:58:32 +0200] "GET /index.php HTTP/1.1" 404 207`)
	for k, v := range values {
		fmt.Printf("%+15s: %s\n", k, v)
	}

	fmt.Println("\n\n# Named Capture :\n")
	g = grok.New(grok.NAMEDCAPTURE)
	values, _ = g.Parse("%{COMMONAPACHELOG}", `127.0.0.1 - - [23/Apr/2014:22:58:32 +0200] "GET /index.php HTTP/1.1" 404 207`)
	for k, v := range values {
		fmt.Printf("%+15s: %s\n", k, v)
	}

	fmt.Println("\n\n# Add custom patterns :\n")
	// We add 3 patterns to our Grok instance, to structure an IRC message
	g = grok.New(grok.NAMEDCAPTURE)
	g.AddPattern("IRCUSER", `\A@(\w+)`)
	g.AddPattern("IRCBODY", `.*`)
	g.AddPattern("IRCMSG", `%{IRCUSER:user} .* : %{IRCBODY:message}`)
	values, _ = g.Parse("%{IRCMSG}", `@vjeantet said : Hello !`)
	for k, v := range values {
		fmt.Printf("%+15s: %s\n", k, v)
	}
}
<|endoftext|>