<commit_before>package boil

import (
	"bytes"
	"database/sql"
	"fmt"
	"strings"

	"github.com/nullbio/sqlboiler/strmangle"
)

type where struct {
	clause      string
	orSeperator bool
	args        []interface{}
}

type plainSQL struct {
	sql  string
	args []interface{}
}

type join struct {
	on   string
	args []interface{}
}

// Query holds the state for the built up query
type Query struct {
	executor   Executor
	plainSQL   plainSQL
	delete     bool
	update     map[string]interface{}
	selectCols []string
	count      bool
	from       []string
	innerJoins []join
	where      []where
	groupBy    []string
	orderBy    []string
	having     []string
	limit      int
	offset     int
}

func buildQuery(q *Query) (string, []interface{}) {
	var buf *bytes.Buffer
	var args []interface{}

	switch {
	case len(q.plainSQL.sql) != 0:
		return q.plainSQL.sql, q.plainSQL.args
	case q.delete:
		buf, args = buildDeleteQuery(q)
	default:
		buf, args = buildSelectQuery(q)
	}

	return buf.String(), args
}

func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
	buf := &bytes.Buffer{}

	buf.WriteString("SELECT ")

	if q.count {
		buf.WriteString("COUNT(")
	}
	if len(q.selectCols) > 0 {
		buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.selectCols), `, `))
	} else {
		buf.WriteByte('*')
	}
	// close sql COUNT function
	if q.count {
		buf.WriteString(")")
	}

	buf.WriteString(" FROM ")
	buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.from), ","))

	where, args := whereClause(q)
	buf.WriteString(where)

	if len(q.orderBy) != 0 {
		buf.WriteString(" ORDER BY ")
		buf.WriteString(strings.Join(q.orderBy, ","))
	}

	if q.limit != 0 {
		fmt.Fprintf(buf, " LIMIT %d", q.limit)
	}
	if q.offset != 0 {
		fmt.Fprintf(buf, " OFFSET %d", q.offset)
	}

	buf.WriteByte(';')
	return buf, args
}

func buildDeleteQuery(q *Query) (*bytes.Buffer, []interface{}) {
	buf := &bytes.Buffer{}

	buf.WriteString("DELETE FROM ")
	fmt.Fprintf(buf, `"%s"`, q.from)

	where, args := whereClause(q)
	buf.WriteString(where)

	buf.WriteByte(';')

	return buf, args
}

// ExecQuery executes a query that does not need a row returned
func ExecQuery(q *Query) (sql.Result, error) {
	qs, args := buildQuery(q)
	if DebugMode {
		fmt.Fprintln(DebugWriter, qs)
	}
	return q.executor.Exec(qs, args...)
}

// ExecQueryOne executes the query for the One finisher and returns a row
func ExecQueryOne(q *Query) *sql.Row {
	qs, args := buildQuery(q)
	if DebugMode {
		fmt.Fprintln(DebugWriter, qs)
	}
	return q.executor.QueryRow(qs, args...)
}

// ExecQueryAll executes the query for the All finisher and returns multiple rows
func ExecQueryAll(q *Query) (*sql.Rows, error) {
	qs, args := buildQuery(q)
	if DebugMode {
		fmt.Fprintln(DebugWriter, qs)
	}
	return q.executor.Query(qs, args...)
}

// SetSQL on the query.
func SetSQL(q *Query, sql string, args ...interface{}) {
	q.plainSQL = plainSQL{sql: sql, args: args}
}

// SetCount on the query.
func SetCount(q *Query) {
	q.count = true
}

// SetDelete on the query.
func SetDelete(q *Query) {
	q.delete = true
}

// SetExecutor on the query.
func SetExecutor(q *Query, exec Executor) {
	q.executor = exec
}

// AppendSelect on the query.
func AppendSelect(q *Query, columns ...string) {
	q.selectCols = append(q.selectCols, columns...)
}

// SetSelect replaces the current select clause.
func SetSelect(q *Query, columns ...string) {
	q.selectCols = append([]string(nil), columns...)
}

// Select returns the select columns in the query.
func Select(q *Query) []string {
	cols := make([]string, len(q.selectCols))
	copy(cols, q.selectCols)
	return cols
}

// AppendFrom on the query.
func AppendFrom(q *Query, from ...string) {
	q.from = append(q.from, from...)
}

// SetFrom replaces the current from statements.
func SetFrom(q *Query, from ...string) {
	q.from = append([]string(nil), from...)
}

// AppendInnerJoin on the query.
func AppendInnerJoin(q *Query, on string, args ...interface{}) {
	q.innerJoins = append(q.innerJoins, join{on: on, args: args})
}

// SetInnerJoin on the query.
func SetInnerJoin(q *Query, on string, args ...interface{}) {
	q.innerJoins = append([]join(nil), join{on: on, args: args})
}

// AppendWhere on the query.
func AppendWhere(q *Query, clause string, args ...interface{}) {
	q.where = append(q.where, where{clause: clause, args: args})
}

// SetWhere on the query.
func SetWhere(q *Query, clause string, args ...interface{}) {
	q.where = append([]where(nil), where{clause: clause, args: args})
}

// SetLastWhereAsOr sets the or seperator for the last element in the where slice
func SetLastWhereAsOr(q *Query) {
	q.where[len(q.where)-1].orSeperator = true
}

// ApplyGroupBy on the query.
func ApplyGroupBy(q *Query, clause string) {
	q.groupBy = append(q.groupBy, clause)
}

// SetGroupBy on the query.
func SetGroupBy(q *Query, clause string) {
	q.groupBy = append([]string(nil), clause)
}

// ApplyOrderBy on the query.
func ApplyOrderBy(q *Query, clause string) {
	q.orderBy = append(q.orderBy, clause)
}

// SetOrderBy on the query.
func SetOrderBy(q *Query, clause string) {
	q.orderBy = append([]string(nil), clause)
}

// ApplyHaving on the query.
func ApplyHaving(q *Query, clause string) {
	q.having = append(q.having, clause)
}

// SetHaving on the query.
func SetHaving(q *Query, clause string) {
	q.having = append([]string(nil), clause)
}

// SetLimit on the query.
func SetLimit(q *Query, limit int) {
	q.limit = limit
}

// SetOffset on the query.
func SetOffset(q *Query, offset int) {
	q.offset = offset
}

func whereClause(q *Query) (string, []interface{}) {
	if len(q.where) == 0 {
		return "", nil
	}

	buf := &bytes.Buffer{}
	var args []interface{}

	buf.WriteString(" WHERE ")
	for i := 0; i < len(q.where); i++ {
		buf.WriteString(fmt.Sprintf("%s", q.where[i].clause))
		args = append(args, q.where[i].args...)
		if i >= len(q.where)-1 {
			continue
		}
		if q.where[i].orSeperator {
			buf.WriteString(" OR ")
		} else {
			buf.WriteString(" AND ")
		}
	}

	return buf.String(), args
}
<commit_msg>Add Update back for UpdateAll<commit_after>package boil

import (
	"bytes"
	"database/sql"
	"fmt"
	"strings"

	"github.com/nullbio/sqlboiler/strmangle"
)

type where struct {
	clause      string
	orSeperator bool
	args        []interface{}
}

type plainSQL struct {
	sql  string
	args []interface{}
}

type join struct {
	on   string
	args []interface{}
}

// Query holds the state for the built up query
type Query struct {
	executor   Executor
	plainSQL   plainSQL
	delete     bool
	update     map[string]interface{}
	selectCols []string
	count      bool
	from       []string
	innerJoins []join
	where      []where
	groupBy    []string
	orderBy    []string
	having     []string
	limit      int
	offset     int
}

func buildQuery(q *Query) (string, []interface{}) {
	var buf *bytes.Buffer
	var args []interface{}

	switch {
	case len(q.plainSQL.sql) != 0:
		return q.plainSQL.sql, q.plainSQL.args
	case q.delete:
		buf, args = buildDeleteQuery(q)
	case len(q.update) > 0:
		buf, args = buildUpdateQuery(q)
	default:
		buf, args = buildSelectQuery(q)
	}

	return buf.String(), args
}

func buildSelectQuery(q *Query) (*bytes.Buffer, []interface{}) {
	buf := &bytes.Buffer{}

	buf.WriteString("SELECT ")

	if q.count {
		buf.WriteString("COUNT(")
	}
	if len(q.selectCols) > 0 {
		buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.selectCols), `, `))
	} else {
		buf.WriteByte('*')
	}
	// close sql COUNT function
	if q.count {
		buf.WriteString(")")
	}

	buf.WriteString(" FROM ")
	buf.WriteString(strings.Join(strmangle.IdentQuoteSlice(q.from), ","))

	where, args := whereClause(q)
	buf.WriteString(where)

	if len(q.orderBy) != 0 {
		buf.WriteString(" ORDER BY ")
		buf.WriteString(strings.Join(q.orderBy, ","))
	}

	if q.limit != 0 {
		fmt.Fprintf(buf, " LIMIT %d", q.limit)
	}
	if q.offset != 0 {
		fmt.Fprintf(buf, " OFFSET %d", q.offset)
	}

	buf.WriteByte(';')
	return buf, args
}

func buildDeleteQuery(q *Query) (*bytes.Buffer, []interface{}) {
	buf := &bytes.Buffer{}

	buf.WriteString("DELETE FROM ")
	fmt.Fprintf(buf, `"%s"`, q.from)

	where, args := whereClause(q)
	buf.WriteString(where)

	buf.WriteByte(';')

	return buf, args
}

func buildUpdateQuery(q *Query) (*bytes.Buffer, []interface{}) {
	buf := &bytes.Buffer{}

	buf.WriteByte(';')
	return buf, nil
}

// ExecQuery executes a query that does not need a row returned
func ExecQuery(q *Query) (sql.Result, error) {
	qs, args := buildQuery(q)
	if DebugMode {
		fmt.Fprintln(DebugWriter, qs)
	}
	return q.executor.Exec(qs, args...)
}

// ExecQueryOne executes the query for the One finisher and returns a row
func ExecQueryOne(q *Query) *sql.Row {
	qs, args := buildQuery(q)
	if DebugMode {
		fmt.Fprintln(DebugWriter, qs)
	}
	return q.executor.QueryRow(qs, args...)
}

// ExecQueryAll executes the query for the All finisher and returns multiple rows
func ExecQueryAll(q *Query) (*sql.Rows, error) {
	qs, args := buildQuery(q)
	if DebugMode {
		fmt.Fprintln(DebugWriter, qs)
	}
	return q.executor.Query(qs, args...)
}

// SetSQL on the query.
func SetSQL(q *Query, sql string, args ...interface{}) {
	q.plainSQL = plainSQL{sql: sql, args: args}
}

// SetCount on the query.
func SetCount(q *Query) {
	q.count = true
}

// SetDelete on the query.
func SetDelete(q *Query) {
	q.delete = true
}

// SetUpdate on the query.
func SetUpdate(q *Query, cols map[string]interface{}) {
	q.update = cols
}

// SetExecutor on the query.
func SetExecutor(q *Query, exec Executor) {
	q.executor = exec
}

// AppendSelect on the query.
func AppendSelect(q *Query, columns ...string) {
	q.selectCols = append(q.selectCols, columns...)
}

// SetSelect replaces the current select clause.
func SetSelect(q *Query, columns ...string) {
	q.selectCols = append([]string(nil), columns...)
}

// Select returns the select columns in the query.
func Select(q *Query) []string {
	cols := make([]string, len(q.selectCols))
	copy(cols, q.selectCols)
	return cols
}

// AppendFrom on the query.
func AppendFrom(q *Query, from ...string) {
	q.from = append(q.from, from...)
}

// SetFrom replaces the current from statements.
func SetFrom(q *Query, from ...string) {
	q.from = append([]string(nil), from...)
}

// AppendInnerJoin on the query.
func AppendInnerJoin(q *Query, on string, args ...interface{}) {
	q.innerJoins = append(q.innerJoins, join{on: on, args: args})
}

// SetInnerJoin on the query.
func SetInnerJoin(q *Query, on string, args ...interface{}) {
	q.innerJoins = append([]join(nil), join{on: on, args: args})
}

// AppendWhere on the query.
func AppendWhere(q *Query, clause string, args ...interface{}) {
	q.where = append(q.where, where{clause: clause, args: args})
}

// SetWhere on the query.
func SetWhere(q *Query, clause string, args ...interface{}) {
	q.where = append([]where(nil), where{clause: clause, args: args})
}

// SetLastWhereAsOr sets the or seperator for the last element in the where slice
func SetLastWhereAsOr(q *Query) {
	q.where[len(q.where)-1].orSeperator = true
}

// ApplyGroupBy on the query.
func ApplyGroupBy(q *Query, clause string) {
	q.groupBy = append(q.groupBy, clause)
}

// SetGroupBy on the query.
func SetGroupBy(q *Query, clause string) {
	q.groupBy = append([]string(nil), clause)
}

// ApplyOrderBy on the query.
func ApplyOrderBy(q *Query, clause string) {
	q.orderBy = append(q.orderBy, clause)
}

// SetOrderBy on the query.
func SetOrderBy(q *Query, clause string) {
	q.orderBy = append([]string(nil), clause)
}

// ApplyHaving on the query.
func ApplyHaving(q *Query, clause string) {
	q.having = append(q.having, clause)
}

// SetHaving on the query.
func SetHaving(q *Query, clause string) {
	q.having = append([]string(nil), clause)
}

// SetLimit on the query.
func SetLimit(q *Query, limit int) {
	q.limit = limit
}

// SetOffset on the query.
func SetOffset(q *Query, offset int) {
	q.offset = offset
}

func whereClause(q *Query) (string, []interface{}) {
	if len(q.where) == 0 {
		return "", nil
	}

	buf := &bytes.Buffer{}
	var args []interface{}

	buf.WriteString(" WHERE ")
	for i := 0; i < len(q.where); i++ {
		buf.WriteString(fmt.Sprintf("%s", q.where[i].clause))
		args = append(args, q.where[i].args...)
		if i >= len(q.where)-1 {
			continue
		}
		if q.where[i].orSeperator {
			buf.WriteString(" OR ")
		} else {
			buf.WriteString(" AND ")
		}
	}

	return buf.String(), args
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/sha1"
	"flag"
	"fmt"
	"log"
	"net/http"
	"sort"
)

func main() {
	var wxToken = flag.String("wxtoken", "", "WeiXin Token")
	var host = flag.String("host", "127.0.0.1", "listen host")
	var port = flag.String("port", "80", "listen port")
	var refresh = []byte(`<html>
<meta http-equiv="refresh" content="0;url=https://kaiiak.github.io/">
</html>`)

	flag.Parse()
	http.HandleFunc("/wx", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodGet {
			if *wxToken == "" {
				log.Println("token不能为空")
				w.Write(refresh)
				return
			}
			var arg []string
			var sum string
			arg = append(arg, *wxToken)
			arg = append(arg, r.FormValue("timestamp"))
			arg = append(arg, r.FormValue("nonce"))
			sort.Strings(arg)
			for i := 0; i < len(arg); i++ {
				sum += arg[i]
			}
			log.Println(sum)
			h := sha1.New()
			if _, err := h.Write([]byte(sum)); err != nil {
				log.Println(err)
				w.Write(refresh)
			}
			if fmt.Sprintf("%x",h.Sum(nil)) != r.FormValue("signature") {
				log.Println("sha1不匹配！")
				w.Write(refresh)
				return
			}
			w.Write([]byte(r.FormValue("echostr")))
			log.Println("验证成功！")
		}
	})
	http.ListenAndServe(*host+":"+*port, nil)
}
<commit_msg>change  router<commit_after>package main

import (
	"crypto/sha1"
	"flag"
	"fmt"
	"log"
	"net/http"
	"sort"
)

func main() {
	var wxToken = flag.String("wxtoken", "", "WeiXin Token")
	var host = flag.String("host", "127.0.0.1", "listen host")
	var port = flag.String("port", "80", "listen port")
	var refresh = []byte(`<html>
<meta http-equiv="refresh" content="0;url=https://kaiiak.github.io/">
</html>`)

	flag.Parse()
	http.HandleFunc("/wx/verify", func(w http.ResponseWriter, r *http.Request) {
		if r.Method == http.MethodGet {
			if *wxToken == "" {
				log.Println("token不能为空")
				w.Write(refresh)
				return
			}
			var arg []string
			var sum string
			arg = append(arg, *wxToken)
			arg = append(arg, r.FormValue("timestamp"))
			arg = append(arg, r.FormValue("nonce"))
			sort.Strings(arg)
			for i := 0; i < len(arg); i++ {
				sum += arg[i]
			}
			log.Println(sum)
			h := sha1.New()
			if _, err := h.Write([]byte(sum)); err != nil {
				log.Println(err)
				w.Write(refresh)
			}
			if fmt.Sprintf("%x", h.Sum(nil)) != r.FormValue("signature") {
				log.Println("sha1不匹配！")
				w.Write(refresh)
				return
			}
			w.Write([]byte(r.FormValue("echostr")))
			log.Println("验证成功！")
		}
	})
	http.ListenAndServe(*host+":"+*port, nil)
}
<|endoftext|>


<commit_before>package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

var url = "localhost:3000"

func main() {
    http.HandleFunc("/", serveRest)
    http.ListenAndServe(url,nil)
}

func serveRest(w http.ResponseWriter, r *http.Request) {
    response, err := getJsonResponse()
    if err != nil {
        panic(err)
    }

    fmt.Fprintf(w, string(response))
}

func getJsonResponse() ([] byte, error) {
    return json.MarshalIndent(nil, "", "  ")
}<commit_msg>Go working get / response using net/http<commit_after>package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

var (
    url = "localhost:3000"
)
type ArrayPayload struct {
    Movies Movies `json:"movies"`
}

type SinglePayload struct {
    Movie Movie `json:"movie"`
}

type Movies []Movie

type Movie struct {
    Title string `json:"title"`
    Themoviedbid int `json:"themoviedbid"`
}

func main() {
    http.HandleFunc("/", serveRest)
    http.ListenAndServe(url,nil)
}

func serveRest(w http.ResponseWriter, r *http.Request) {
    response, err := getJsonResponse()
    fmt.Printf(string(response))
    if err != nil {
        panic(err)
    }

    fmt.Fprintf(w, string(response))
}

func getJsonResponse() ([] byte, error) {
    // Single Payload
    // movie := Movie{"Fight Club", 550}
    // p := SinglePayload{movie}

    // Array Payload
    movie1 := Movie{"Fight Club", 550}
    movie2 := Movie{"The Matrix", 120}
    movies := []Movie{movie1, movie2}
    p := ArrayPayload{movies}
    return json.MarshalIndent(p, "", "  ")
}<|endoftext|>


<commit_before>//
// DISCLAIMER
//
// Copyright 2017 ArangoDB GmbH, Cologne, Germany
//
// 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.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
// Author Ewout Prangsma
//

package service

import (
	"context"
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	"time"

	logging "github.com/op/go-logging"
)

// NewProcessRunner creates a runner that starts processes on the local OS.
func NewProcessRunner(log *logging.Logger) Runner {
	return &processRunner{
		log: log,
	}
}

// processRunner implements a ProcessRunner that starts processes on the local OS.
type processRunner struct {
	log *logging.Logger
}

type process struct {
	log     *logging.Logger
	p       *os.Process
	isChild bool
}

func (r *processRunner) GetContainerDir(hostDir, defaultContainerDir string) string {
	return hostDir
}

// GetRunningServer checks if there is already a server process running in the given server directory.
// If that is the case, its process is returned.
// Otherwise nil is returned.
func (r *processRunner) GetRunningServer(serverDir string) (Process, error) {
	lockContent, err := ioutil.ReadFile(filepath.Join(serverDir, "data", "LOCK"))
	if os.IsNotExist(err) {
		r.log.Debugf("Cannot find %s", filepath.Join(serverDir, "data", "LOCK"))
		return nil, nil
	} else if err != nil {
		return nil, maskAny(err)
	}
	pid, err := strconv.Atoi(string(lockContent))
	if err != nil {
		// No valid contents in LOCK file
		return nil, nil
	}
	p, err := os.FindProcess(pid)
	if err != nil {
		// Cannot find pid
		r.log.Debugf("Cannot find process %d", pid)
		return nil, nil
	}
	if err := p.Signal(syscall.Signal(0)); err != nil {
		// Process does not seem to exist anymore
		r.log.Debugf("Cannot signal process %d", pid)
		return nil, nil
	}
	// Apparently we still have a server.
	return &process{log: r.log, p: p, isChild: false}, nil
}

func (r *processRunner) Start(ctx context.Context, processType ProcessType, command string, args []string, volumes []Volume, ports []int, containerName, serverDir string) (Process, error) {
	c := exec.Command(command, args...)
	if err := c.Start(); err != nil {
		return nil, maskAny(err)
	}
	return &process{log: r.log, p: c.Process, isChild: true}, nil
}

func (r *processRunner) CreateStartArangodbCommand(myDataDir string, index int, masterIP, masterPort, starterImageName string, clusterConfig ClusterConfig) string {
	if masterIP == "" {
		masterIP = "127.0.0.1"
	}
	addr := masterIP
	if masterPort != "" {
		addr = net.JoinHostPort(addr, masterPort)
	}
	var dataDir string
	if strings.HasSuffix(myDataDir, "1") {
		dataDir = fmt.Sprintf("%s%d", myDataDir[:len(myDataDir)-1], index)
	} else {
		dataDir = fmt.Sprintf("./db%d", index)
	}
	return fmt.Sprintf("arangodb --starter.data-dir=%s --starter.join %s", dataDir, addr)
}

// Cleanup after all processes are dead and have been cleaned themselves
func (r *processRunner) Cleanup() error {
	// Nothing here
	return nil
}

// ProcessID returns the pid of the process (if not running in docker)
func (p *process) ProcessID() int {
	proc := p.p
	if proc != nil {
		return proc.Pid
	}
	return 0
}

// ContainerID returns the ID of the docker container that runs the process.
func (p *process) ContainerID() string {
	return ""
}

// ContainerIP returns the IP address of the docker container that runs the process.
func (p *process) ContainerIP() string {
	return ""
}

// HostPort returns the port on the host that is used to access the given port of the process.
func (p *process) HostPort(containerPort int) (int, error) {
	return containerPort, nil
}

func (p *process) Wait() {
	if proc := p.p; proc != nil {
		p.log.Debugf("Waiting on %d", proc.Pid)
		if p.isChild {
			_, err := proc.Wait()
			p.log.Debugf("Wait on %d returned %v\n", proc.Pid, err)
		} else {
			// Cannot wait on non-child process, so let's do it the hard way
			for {
				if err := proc.Signal(syscall.Signal(0)); err != nil {
					// Process does not seem to exist anymore
					p.log.Debugf("Wait on %d ended at process seems to be gone", proc.Pid)
					break
				}
				time.Sleep(time.Second)
			}
		}
	}
}

func (p *process) Terminate() error {
	if proc := p.p; proc != nil {
		if err := proc.Signal(syscall.SIGTERM); err != nil {
			if err.Error() == "os: process already finished" {
				// Race condition on OSX
				return nil
			}
			return maskAny(err)
		}
	}
	return nil
}

func (p *process) Kill() error {
	if proc := p.p; proc != nil {
		if err := proc.Kill(); err != nil {
			return maskAny(err)
		}
	}
	return nil
}

func (p *process) Hup() error {
	if proc := p.p; proc != nil {
		if err := proc.Signal(syscall.SIGHUP); err != nil {
			return maskAny(err)
		}
	}
	return nil
}

// Remove all traces of this process
func (p *process) Cleanup() error {
	// Nothing todo here
	return nil
}
<commit_msg>Log start<commit_after>//
// DISCLAIMER
//
// Copyright 2017 ArangoDB GmbH, Cologne, Germany
//
// 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.
//
// Copyright holder is ArangoDB GmbH, Cologne, Germany
//
// Author Ewout Prangsma
//

package service

import (
	"context"
	"fmt"
	"io/ioutil"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"
	"time"

	logging "github.com/op/go-logging"
)

// NewProcessRunner creates a runner that starts processes on the local OS.
func NewProcessRunner(log *logging.Logger) Runner {
	return &processRunner{
		log: log,
	}
}

// processRunner implements a ProcessRunner that starts processes on the local OS.
type processRunner struct {
	log *logging.Logger
}

type process struct {
	log     *logging.Logger
	p       *os.Process
	isChild bool
}

func (r *processRunner) GetContainerDir(hostDir, defaultContainerDir string) string {
	return hostDir
}

// GetRunningServer checks if there is already a server process running in the given server directory.
// If that is the case, its process is returned.
// Otherwise nil is returned.
func (r *processRunner) GetRunningServer(serverDir string) (Process, error) {
	lockContent, err := ioutil.ReadFile(filepath.Join(serverDir, "data", "LOCK"))
	if os.IsNotExist(err) {
		r.log.Debugf("Cannot find %s", filepath.Join(serverDir, "data", "LOCK"))
		return nil, nil
	} else if err != nil {
		return nil, maskAny(err)
	}
	pid, err := strconv.Atoi(string(lockContent))
	if err != nil {
		// No valid contents in LOCK file
		return nil, nil
	}
	p, err := os.FindProcess(pid)
	if err != nil {
		// Cannot find pid
		r.log.Debugf("Cannot find process %d", pid)
		return nil, nil
	}
	if err := p.Signal(syscall.Signal(0)); err != nil {
		// Process does not seem to exist anymore
		r.log.Debugf("Cannot signal process %d", pid)
		return nil, nil
	}
	// Apparently we still have a server.
	return &process{log: r.log, p: p, isChild: false}, nil
}

func (r *processRunner) Start(ctx context.Context, processType ProcessType, command string, args []string, volumes []Volume, ports []int, containerName, serverDir string) (Process, error) {
	c := exec.Command(command, args...)
	if err := c.Start(); err != nil {
		return nil, maskAny(err)
	}
	r.log.Infof("Starting: %s %s", command, strings.Join(args, " "))
	return &process{log: r.log, p: c.Process, isChild: true}, nil
}

func (r *processRunner) CreateStartArangodbCommand(myDataDir string, index int, masterIP, masterPort, starterImageName string, clusterConfig ClusterConfig) string {
	if masterIP == "" {
		masterIP = "127.0.0.1"
	}
	addr := masterIP
	if masterPort != "" {
		addr = net.JoinHostPort(addr, masterPort)
	}
	var dataDir string
	if strings.HasSuffix(myDataDir, "1") {
		dataDir = fmt.Sprintf("%s%d", myDataDir[:len(myDataDir)-1], index)
	} else {
		dataDir = fmt.Sprintf("./db%d", index)
	}
	return fmt.Sprintf("arangodb --starter.data-dir=%s --starter.join %s", dataDir, addr)
}

// Cleanup after all processes are dead and have been cleaned themselves
func (r *processRunner) Cleanup() error {
	// Nothing here
	return nil
}

// ProcessID returns the pid of the process (if not running in docker)
func (p *process) ProcessID() int {
	proc := p.p
	if proc != nil {
		return proc.Pid
	}
	return 0
}

// ContainerID returns the ID of the docker container that runs the process.
func (p *process) ContainerID() string {
	return ""
}

// ContainerIP returns the IP address of the docker container that runs the process.
func (p *process) ContainerIP() string {
	return ""
}

// HostPort returns the port on the host that is used to access the given port of the process.
func (p *process) HostPort(containerPort int) (int, error) {
	return containerPort, nil
}

func (p *process) Wait() {
	if proc := p.p; proc != nil {
		p.log.Debugf("Waiting on %d", proc.Pid)
		if p.isChild {
			_, err := proc.Wait()
			p.log.Debugf("Wait on %d returned %v\n", proc.Pid, err)
		} else {
			// Cannot wait on non-child process, so let's do it the hard way
			for {
				if err := proc.Signal(syscall.Signal(0)); err != nil {
					// Process does not seem to exist anymore
					p.log.Debugf("Wait on %d ended at process seems to be gone", proc.Pid)
					break
				}
				time.Sleep(time.Second)
			}
		}
	}
}

func (p *process) Terminate() error {
	if proc := p.p; proc != nil {
		if err := proc.Signal(syscall.SIGTERM); err != nil {
			if err.Error() == "os: process already finished" {
				// Race condition on OSX
				return nil
			}
			return maskAny(err)
		}
	}
	return nil
}

func (p *process) Kill() error {
	if proc := p.p; proc != nil {
		if err := proc.Kill(); err != nil {
			return maskAny(err)
		}
	}
	return nil
}

func (p *process) Hup() error {
	if proc := p.p; proc != nil {
		if err := proc.Signal(syscall.SIGHUP); err != nil {
			return maskAny(err)
		}
	}
	return nil
}

// Remove all traces of this process
func (p *process) Cleanup() error {
	// Nothing todo here
	return nil
}
<|endoftext|>


<commit_before>package service

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"regexp"
	"strings"

	"golang.org/x/net/html"
	"golang.org/x/net/publicsuffix"
)

type AhrefsService interface {
	SignIn(string, string) string
}

type ahrefsService struct{}

var client *http.Client

func makeRequest(method string, reader io.Reader) ([]byte, error) {
	req, err := http.NewRequest(method, "https://ahrefs.com/user/login", reader)

	if err != nil {
		return nil, err
	}

	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("Referer", "https://ahrefs.com/user/login")
	req.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
	req.Header.Add("Accept-Language", "en-US,en;q=0.5")
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko")
	res, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	if res.StatusCode == 500 {
		return nil, errors.New("Internal Server Error")
	}
	defer res.Body.Close()
	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	return data, nil
}
func (ahrefsService) SignIn(email, password string) error {
	cJar, err := cookiejar.New(&cookiejar.Options{
		PublicSuffixList: publicsuffix.List,
	})
	if err != nil {
		return err
	}

	client = &http.Client{
		Jar: cJar,
	}
	token := ""
	data, err := makeRequest("GET", nil)
	if err != nil {
		return err
	}
	re := regexp.MustCompile(`.*<meta name="_token" content="(.*)" />.*`)
	token = re.FindStringSubmatch(string(data))[1]
	fmt.Println(token)

	form := url.Values{}
	form.Add("_token", token)
	form.Add("email", email)
	form.Add("password", password)
	form.Add("return_to", "https://ahrefs.com/")
	data, err = makeRequest("POST", strings.NewReader(form.Encode()))
	if err != nil {
		return err
	}
	return nil
}

func NewService() ahrefsService {
	return ahrefsService{}
}

func getElementByName(name string, n *html.Node) (element *html.Node, ok bool) {
	for _, a := range n.Attr {
		if a.Key == "name" && a.Val == name {
			return n, true
		}
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		if element, ok = getElementByName(name, c); ok {
			return
		}
	}
	return
}

func getElementId(id string, n *html.Node) (element *html.Node, ok bool) {
	for _, a := range n.Attr {
		if a.Key == "id" && a.Val == id {
			return n, true
		}
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		if element, ok = getElementByName(id, c); ok {
			return
		}
	}
	return
}
<commit_msg>Small cleanup<commit_after>package service

import (
	"errors"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/cookiejar"
	"net/url"
	"regexp"
	"strings"

	"golang.org/x/net/html"
)

type AhrefsService interface {
	SignIn(string, string) string
}

type ahrefsService struct{}

var client *http.Client

func makeRequest(method, url string, reader io.Reader) ([]byte, error) {
	req, err := http.NewRequest(method, url, reader)

	if err != nil {
		return nil, err
	}

	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Add("Referer", "https://ahrefs.com/user/login")
	req.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
	req.Header.Add("Accept-Language", "en-US,en;q=0.5")
	req.Header.Add("Connection", "keep-alive")
	req.Header.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko")
	res, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	if res.StatusCode == 500 {
		return nil, errors.New("Internal Server Error")
	}
	defer res.Body.Close()
	data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}
	return data, nil
}
func (ahrefsService) SignIn(email, password string) error {
	cJar, err := cookiejar.New(nil)
	if err != nil {
		return err
	}

	client = &http.Client{
		Jar: cJar,
	}
	token := ""
	data, err := makeRequest("GET", "https://ahrefs.com/user/login", nil)
	if err != nil {
		return err
	}
	re := regexp.MustCompile(`.*<meta name="_token" content="(.*)" />.*`)
	token = re.FindStringSubmatch(string(data))[1]

	form := url.Values{}
	form.Add("_token", token)
	form.Add("email", email)
	form.Add("password", password)
	form.Add("return_to", "https://ahrefs.com/")
	data, err = makeRequest("POST", "https://ahrefs.com/user/login", strings.NewReader(form.Encode()))
	if err != nil {
		return err
	}
	return nil
}

func NewService() ahrefsService {
	return ahrefsService{}
}

func getElementByName(name string, n *html.Node) (element *html.Node, ok bool) {
	for _, a := range n.Attr {
		if a.Key == "name" && a.Val == name {
			return n, true
		}
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		if element, ok = getElementByName(name, c); ok {
			return
		}
	}
	return
}

func getElementId(id string, n *html.Node) (element *html.Node, ok bool) {
	for _, a := range n.Attr {
		if a.Key == "id" && a.Val == id {
			return n, true
		}
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		if element, ok = getElementByName(id, c); ok {
			return
		}
	}
	return
}
<|endoftext|>


<commit_before>package formbuilder

import (
	"errors"
	"fmt"
	"os"
	"strings"

	ncommon "github.com/admpub/nging/application/library/common"

	"github.com/coscms/forms"
	"github.com/coscms/forms/common"
	"github.com/coscms/forms/config"
	"github.com/coscms/forms/fields"

	"github.com/webx-top/echo"
	"github.com/webx-top/echo/middleware/render/driver"
)

var (
	ErrJSONConfigFileNameInvalid = errors.New("*.form.json name invalid")
)

func New(ctx echo.Context, model interface{}, options ...Option) *FormBuilder {
	f := &FormBuilder{
		Forms: forms.NewForms(forms.New()),
		on: MethodHooks{
			echo.POST: {BindModel, ValidModel},
		},
		ctx: ctx,
	}
	f.SetModel(model)
	f.Style = common.BOOTSTRAP
	for _, option := range options {
		if option == nil {
			continue
		}
		option(ctx, f)
	}
	f.SetLabelFunc(func(txt string) string {
		return ctx.T(txt)
	})
	f.AddBeforeRender(func() {
		nextURL := ctx.Form(ncommon.DefaultReturnToURLVarName)
		if len(nextURL) > 0 {
			f.Elements(fields.HiddenField(ncommon.DefaultReturnToURLVarName).SetValue(nextURL))
		}
	})
	csrfToken, ok := ctx.Get(`csrf`).(string)
	if ok {
		f.AddBeforeRender(func() {
			f.Elements(fields.HiddenField(`csrf`).SetValue(csrfToken))
		})
	}
	ctx.Set(`forms`, f.Forms)
	return f
}

type FormBuilder struct {
	*forms.Forms
	on         MethodHooks
	exit       bool
	err        error
	ctx        echo.Context
	configFile string
}

func (f *FormBuilder) Exited() bool {
	return f.exit
}

func (f *FormBuilder) Exit(exit bool) *FormBuilder {
	f.exit = exit
	return f
}

func (f *FormBuilder) SetError(err error) *FormBuilder {
	f.err = err
	return f
}

func (f *FormBuilder) HasError() bool {
	return f.err != nil
}

func (f *FormBuilder) Error() error {
	return f.err
}

func (f *FormBuilder) ParseConfigFile() error {
	jsonFile := f.configFile
	var cfg *config.Config
	renderer := f.ctx.Renderer().(driver.Driver)
	jsonFile += `.form.json`
	jsonFile = renderer.TmplPath(f.ctx, jsonFile)
	if len(jsonFile) == 0 {
		return ErrJSONConfigFileNameInvalid
	}
	b, err := renderer.RawContent(jsonFile)
	if err != nil {
		if !os.IsNotExist(err) && !strings.Contains(err.Error(), `file does not exist`) || renderer.Manager() == nil {
			return fmt.Errorf(`read file %s: %w`, jsonFile, err)
		}
		cfg = f.ToConfig()
		var jsonb []byte
		jsonb, err = f.ToJSONBlob(cfg)
		if err != nil {
			return fmt.Errorf(`[form.ToJSONBlob] %s: %w`, jsonFile, err)
		}
		err = renderer.Manager().SetTemplate(jsonFile, jsonb)
		if err != nil {
			return fmt.Errorf(`%s: %w`, jsonFile, err)
		}
		f.ctx.Logger().Infof(f.ctx.T(`生成表单配置文件“%v”成功。`), jsonFile)
	} else {
		cfg, err = forms.Unmarshal(b, jsonFile)
		if err != nil {
			return fmt.Errorf(`[forms.Unmarshal] %s: %w`, jsonFile, err)
		}
	}
	if cfg == nil {
		cfg = f.NewConfig()
	}
	f.Init(cfg)
	return err
}

func (f *FormBuilder) RecvSubmission() error {
	method := strings.ToUpper(f.ctx.Method())
	if err := f.on.Fire(method, f.ctx, f); err != nil {
		return err
	}
	if err := f.on.Fire(`*`, f.ctx, f); err != nil {
		return err
	}
	return nil
}

func (f *FormBuilder) Generate() *FormBuilder {
	f.ParseFromConfig()
	return f
}
<commit_msg>update<commit_after>package formbuilder

import (
	"errors"
	"fmt"
	"os"
	"strings"

	ncommon "github.com/admpub/nging/application/library/common"

	"github.com/coscms/forms"
	"github.com/coscms/forms/common"
	"github.com/coscms/forms/config"
	"github.com/coscms/forms/fields"

	"github.com/webx-top/echo"
	"github.com/webx-top/echo/middleware/render/driver"
)

var (
	ErrJSONConfigFileNameInvalid = errors.New("*.form.json name invalid")
)

func New(ctx echo.Context, model interface{}, options ...Option) *FormBuilder {
	f := &FormBuilder{
		Forms: forms.NewForms(forms.New()),
		on: MethodHooks{
			echo.POST: {BindModel, ValidModel},
			echo.PUT:  {BindModel, ValidModel},
		},
		ctx: ctx,
	}
	f.SetModel(model)
	f.Style = common.BOOTSTRAP
	for _, option := range options {
		if option == nil {
			continue
		}
		option(ctx, f)
	}
	f.SetLabelFunc(func(txt string) string {
		return ctx.T(txt)
	})
	f.AddBeforeRender(func() {
		nextURL := ctx.Form(ncommon.DefaultReturnToURLVarName)
		if len(nextURL) > 0 {
			f.Elements(fields.HiddenField(ncommon.DefaultReturnToURLVarName).SetValue(nextURL))
		}
	})
	csrfToken, ok := ctx.Get(`csrf`).(string)
	if ok {
		f.AddBeforeRender(func() {
			f.Elements(fields.HiddenField(`csrf`).SetValue(csrfToken))
		})
	}
	ctx.Set(`forms`, f.Forms)
	return f
}

type FormBuilder struct {
	*forms.Forms
	on         MethodHooks
	exit       bool
	err        error
	ctx        echo.Context
	configFile string
}

func (f *FormBuilder) Exited() bool {
	return f.exit
}

func (f *FormBuilder) Exit(exit bool) *FormBuilder {
	f.exit = exit
	return f
}

func (f *FormBuilder) SetError(err error) *FormBuilder {
	f.err = err
	return f
}

func (f *FormBuilder) HasError() bool {
	return f.err != nil
}

func (f *FormBuilder) Error() error {
	return f.err
}

func (f *FormBuilder) ParseConfigFile() error {
	jsonFile := f.configFile
	var cfg *config.Config
	renderer := f.ctx.Renderer().(driver.Driver)
	jsonFile += `.form.json`
	jsonFile = renderer.TmplPath(f.ctx, jsonFile)
	if len(jsonFile) == 0 {
		return ErrJSONConfigFileNameInvalid
	}
	b, err := renderer.RawContent(jsonFile)
	if err != nil {
		if !os.IsNotExist(err) && !strings.Contains(err.Error(), `file does not exist`) || renderer.Manager() == nil {
			return fmt.Errorf(`read file %s: %w`, jsonFile, err)
		}
		cfg = f.ToConfig()
		var jsonb []byte
		jsonb, err = f.ToJSONBlob(cfg)
		if err != nil {
			return fmt.Errorf(`[form.ToJSONBlob] %s: %w`, jsonFile, err)
		}
		err = renderer.Manager().SetTemplate(jsonFile, jsonb)
		if err != nil {
			return fmt.Errorf(`%s: %w`, jsonFile, err)
		}
		f.ctx.Logger().Infof(f.ctx.T(`生成表单配置文件“%v”成功。`), jsonFile)
	} else {
		cfg, err = forms.Unmarshal(b, jsonFile)
		if err != nil {
			return fmt.Errorf(`[forms.Unmarshal] %s: %w`, jsonFile, err)
		}
	}
	if cfg == nil {
		cfg = f.NewConfig()
	}
	f.Init(cfg)
	return err
}

func (f *FormBuilder) RecvSubmission() error {
	method := strings.ToUpper(f.ctx.Method())
	if err := f.on.Fire(method, f.ctx, f); err != nil {
		return err
	}
	if err := f.on.Fire(`*`, f.ctx, f); err != nil {
		return err
	}
	return nil
}

func (f *FormBuilder) Generate() *FormBuilder {
	f.ParseFromConfig()
	return f
}
<|endoftext|>


<commit_before>package prometheus

import (
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/gogo/protobuf/proto"
	"github.com/golang/snappy"
	"github.com/grafana/metrictank/cluster"
	"github.com/grafana/metrictank/input"
	"github.com/prometheus/common/model"
	"github.com/prometheus/prometheus/prompb"
	"github.com/raintank/worldping-api/pkg/log"
	"github.com/rakyll/globalconf"
	schema "gopkg.in/raintank/schema.v1"
)

var (
	addr        string
	Enabled     bool
	partitionID int
)

type prometheusWriteHandler struct {
	input.Handler
	quit chan struct{}
}

func New() *prometheusWriteHandler {
	return &prometheusWriteHandler{}
}

func (p *prometheusWriteHandler) Name() string {
	return "prometheus"
}

func (p *prometheusWriteHandler) Start(handler input.Handler, fatal chan struct{}) error {
	p.Handler = handler
	p.quit = fatal
	ConfigSetup()

	mux := http.NewServeMux()
	mux.HandleFunc("/write", p.handle)
	server := http.Server{
		Addr:    addr,
		Handler: mux,
	}
	go server.ListenAndServe()
	return nil
}

func (p *prometheusWriteHandler) MaintainPriority() {
	cluster.Manager.SetPriority(0)
}

func (p *prometheusWriteHandler) Stop() {
	log.Info("prometheus-in: shutting down")
}

func (p *prometheusWriteHandler) handle(w http.ResponseWriter, req *http.Request) {
	defer req.Body.Close()
	if req.Body != nil {
		compressed, err := ioutil.ReadAll(req.Body)

		if err != nil {
			w.WriteHeader(400)
			w.Write([]byte(fmt.Sprintf("Read Error, %v", err)))
			log.Error(3, "Read Error, %v", err)
			return
		}
		reqBuf, err := snappy.Decode(nil, compressed)
		if err != nil {
			w.WriteHeader(400)
			w.Write([]byte(fmt.Sprintf("Decode Error, %v", err)))
			log.Error(3, "Decode Error, %v", err)
			return
		}

		var req prompb.WriteRequest
		if err := proto.Unmarshal(reqBuf, &req); err != nil {
			w.WriteHeader(400)
			w.Write([]byte(fmt.Sprintf("Unmarshal Error, %v", err)))
			log.Error(3, "Unmarshal Error, %v", err)
			return
		}

		for _, ts := range req.Timeseries {
			var name string
			var tagSet []string

			for _, l := range ts.Labels {
				if l.Name == model.MetricNameLabel {
					name = l.Value
				} else {
					tagSet = append(tagSet, l.Name+"="+l.Value)
				}
			}
			if name != "" {
				for _, sample := range ts.Samples {
					md := &schema.MetricData{
						Name:     name,
						Metric:   name,
						Interval: 0,
						Value:    sample.Value,
						Unit:     "unknown",
						Time:     (sample.Timestamp / 1000),
						Mtype:    "gauge",
						Tags:     tagSet,
						OrgId:    1,
					}
					md.SetId()
					p.Process(md, int32(partitionID))
				}
			} else {
				log.Warn("prometheus metric received with empty name")
			}
		}
		if err != nil {
			w.WriteHeader(500)
			w.Write([]byte(err.Error()))
			return
		}
		w.Write([]byte("ok"))
		return
	}
	w.WriteHeader(400)
	w.Write([]byte("no data"))
}

func ConfigSetup() {
	inPrometheus := flag.NewFlagSet("prometheus-in", flag.ExitOnError)
	inPrometheus.BoolVar(&Enabled, "enabled", false, "")
	inPrometheus.StringVar(&addr, "addr", ":8000", "http listen address")
	inPrometheus.IntVar(&partitionID, "partition", 0, "partition Id.")
	globalconf.Register("prometheus-in", inPrometheus)
}
<commit_msg>update interval to sane default value<commit_after>package prometheus

import (
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/gogo/protobuf/proto"
	"github.com/golang/snappy"
	"github.com/grafana/metrictank/cluster"
	"github.com/grafana/metrictank/input"
	"github.com/prometheus/common/model"
	"github.com/prometheus/prometheus/prompb"
	"github.com/raintank/worldping-api/pkg/log"
	"github.com/rakyll/globalconf"
	schema "gopkg.in/raintank/schema.v1"
)

var (
	addr        string
	Enabled     bool
	partitionID int
)

type prometheusWriteHandler struct {
	input.Handler
	quit chan struct{}
}

func New() *prometheusWriteHandler {
	return &prometheusWriteHandler{}
}

func (p *prometheusWriteHandler) Name() string {
	return "prometheus"
}

func (p *prometheusWriteHandler) Start(handler input.Handler, fatal chan struct{}) error {
	p.Handler = handler
	p.quit = fatal
	ConfigSetup()

	mux := http.NewServeMux()
	mux.HandleFunc("/write", p.handle)
	server := http.Server{
		Addr:    addr,
		Handler: mux,
	}
	go server.ListenAndServe()
	return nil
}

func (p *prometheusWriteHandler) MaintainPriority() {
	cluster.Manager.SetPriority(0)
}

func (p *prometheusWriteHandler) Stop() {
	log.Info("prometheus-in: shutting down")
}

func (p *prometheusWriteHandler) handle(w http.ResponseWriter, req *http.Request) {
	defer req.Body.Close()
	if req.Body != nil {
		compressed, err := ioutil.ReadAll(req.Body)

		if err != nil {
			w.WriteHeader(400)
			w.Write([]byte(fmt.Sprintf("Read Error, %v", err)))
			log.Error(3, "Read Error, %v", err)
			return
		}
		reqBuf, err := snappy.Decode(nil, compressed)
		if err != nil {
			w.WriteHeader(400)
			w.Write([]byte(fmt.Sprintf("Decode Error, %v", err)))
			log.Error(3, "Decode Error, %v", err)
			return
		}

		var req prompb.WriteRequest
		if err := proto.Unmarshal(reqBuf, &req); err != nil {
			w.WriteHeader(400)
			w.Write([]byte(fmt.Sprintf("Unmarshal Error, %v", err)))
			log.Error(3, "Unmarshal Error, %v", err)
			return
		}

		for _, ts := range req.Timeseries {
			var name string
			var tagSet []string

			for _, l := range ts.Labels {
				if l.Name == model.MetricNameLabel {
					name = l.Value
				} else {
					tagSet = append(tagSet, l.Name+"="+l.Value)
				}
			}
			if name != "" {
				for _, sample := range ts.Samples {
					md := &schema.MetricData{
						Name:     name,
						Metric:   name,
						Interval: 15,
						Value:    sample.Value,
						Unit:     "unknown",
						Time:     (sample.Timestamp / 1000),
						Mtype:    "gauge",
						Tags:     tagSet,
						OrgId:    1,
					}
					md.SetId()
					p.Process(md, int32(partitionID))
				}
			} else {
				log.Warn("prometheus metric received with empty name")
			}
		}
		if err != nil {
			w.WriteHeader(500)
			w.Write([]byte(err.Error()))
			return
		}
		w.Write([]byte("ok"))
		return
	}
	w.WriteHeader(400)
	w.Write([]byte("no data"))
}

func ConfigSetup() {
	inPrometheus := flag.NewFlagSet("prometheus-in", flag.ExitOnError)
	inPrometheus.BoolVar(&Enabled, "enabled", false, "")
	inPrometheus.StringVar(&addr, "addr", ":8000", "http listen address")
	inPrometheus.IntVar(&partitionID, "partition", 0, "partition Id.")
	globalconf.Register("prometheus-in", inPrometheus)
}
<|endoftext|>


<commit_before>package dna

import "testing"

func (h Histogram) Equal(o Histogram) bool {
	return h.sameLength(o) && h.sameMappings(o)
}

func (h Histogram) sameLength(o Histogram) bool {
	return len(h) == len(o)
}

func (h Histogram) sameMappings(o Histogram) (res bool) {
	res = true
	for k := range h {
		if h[k] != o[k] {
			res = false
		}
	}
	return
}

var tallyTests = []struct {
	strand     string
	nucleotide byte
	expected   int
}{
	{"", 'A', 0},
	{"ACT", 'G', 0},
	{"CCCCC", 'C', 5},
	{"GGGGGTAACCCGG", 'T', 1},
}

func TestNucleotideCounts(t *testing.T) {
	for _, tt := range tallyTests {
		dna := DNA(tt.strand)
		if count, err := dna.Count(tt.nucleotide); err != nil {
			t.Fatal(err)
		} else if count != tt.expected {
			t.Fatalf("Got \"%v\", expected \"%v\"", count, tt.expected)
		}
	}
}

func TestHasErrorForInvalidNucleotides(t *testing.T) {
	dna := DNA("GATTACA")
	if _, err := dna.Count('X'); err == nil {
		t.Fatalf("X is an invalid nucleotide, but no error was raised")
	}
}

// In most cases, this test is pointless.
// Very occasionally it matters.
// Just roll with it.
func TestCountingDoesntChangeCount(t *testing.T) {
	dna := DNA("CGATTGGG")
	dna.Count('T')
	count1, err := dna.Count('T')
	if err != nil {
		t.Fatal(err)
	}
	count2, err := dna.Count('T')
	if err != nil {
		t.Fatal(err)
	}
	if count1 != count2 || count2 != 2 {
		t.Fatalf("Got %v, expected %v", []int{count1, count2}, []int{2, 2})
	}
}

type histogramTest struct {
	strand   string
	expected Histogram
}

var histogramTests = []histogramTest{
	{
		"",
		Histogram{'A': 0, 'C': 0, 'T': 0, 'G': 0},
	},
	{
		"GGGGGGGG",
		Histogram{'A': 0, 'C': 0, 'T': 0, 'G': 8},
	},
	{
		"AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC",
		Histogram{'A': 20, 'C': 12, 'T': 21, 'G': 17},
	},
}

func TestSequenceHistograms(t *testing.T) {
	for _, tt := range histogramTests {
		dna := DNA(tt.strand)
		if !dna.Counts().Equal(tt.expected) {
			t.Fatalf("DNA{ \"%v\" }: Got \"%v\", expected \"%v\"", tt.strand, dna.Counts(), tt.expected)
		}
	}
}

func BenchmarkSequenceHistograms(b *testing.B) {
	b.StopTimer()
	for _, tt := range histogramTests {
		for i := 0; i < b.N; i++ {
			dna := DNA(tt.strand)
			b.StartTimer()

			dna.Counts()

			b.StopTimer()
		}
	}
}

const targetTestVersion = 1

func TestTestVersion(t *testing.T) {
	if testVersion != targetTestVersion {
		t.Errorf("Found testVersion = %v, want %v.", testVersion, targetTestVersion)
	}
}
<commit_msg>nucleotide-count: Improve test code<commit_after>package dna

import (
	"reflect"
	"testing"
)

var tallyTests = []struct {
	strand     DNA
	nucleotide byte
	expected   int
}{
	{"", 'A', 0},
	{"ACT", 'G', 0},
	{"CCCCC", 'C', 5},
	{"GGGGGTAACCCGG", 'T', 1},
}

func TestNucleotideCounts(t *testing.T) {
	for _, tt := range tallyTests {
		if count, err := tt.strand.Count(tt.nucleotide); err != nil {
			t.Fatal(err)
		} else if count != tt.expected {
			t.Fatalf("Got \"%v\", expected \"%v\"", count, tt.expected)
		}
	}
}

func TestHasErrorForInvalidNucleotides(t *testing.T) {
	dna := DNA("GATTACA")
	if _, err := dna.Count('X'); err == nil {
		t.Fatalf("X is an invalid nucleotide, but no error was raised")
	}
}

// In most cases, this test is pointless.
// Very occasionally it matters.
// Just roll with it.
func TestCountingDoesntChangeCount(t *testing.T) {
	dna := DNA("CGATTGGG")
	dna.Count('T')
	count1, err := dna.Count('T')
	if err != nil {
		t.Fatal(err)
	}
	count2, err := dna.Count('T')
	if err != nil {
		t.Fatal(err)
	}
	if count1 != count2 || count2 != 2 {
		t.Fatalf("Got %v, expected %v", []int{count1, count2}, []int{2, 2})
	}
}

type histogramTest struct {
	strand   DNA
	expected Histogram
}

var histogramTests = []histogramTest{
	{
		"",
		Histogram{'A': 0, 'C': 0, 'T': 0, 'G': 0},
	},
	{
		"GGGGGGGG",
		Histogram{'A': 0, 'C': 0, 'T': 0, 'G': 8},
	},
	{
		"AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC",
		Histogram{'A': 20, 'C': 12, 'T': 21, 'G': 17},
	},
}

func TestSequenceHistograms(t *testing.T) {
	for _, tt := range histogramTests {
		if !reflect.DeepEqual(tt.strand.Counts(), tt.expected) {
			t.Fatalf("DNA{ %q }: Got %v, expected %v", tt.strand, tt.strand.Counts(), tt.expected)
		}
	}
}

func BenchmarkSequenceHistograms(b *testing.B) {
	b.StopTimer()
	for _, tt := range histogramTests {
		for i := 0; i < b.N; i++ {
			b.StartTimer()

			tt.strand.Counts()

			b.StopTimer()
		}
	}
}

const targetTestVersion = 1

func TestTestVersion(t *testing.T) {
	if testVersion != targetTestVersion {
		t.Errorf("Found testVersion = %v, want %v.", testVersion, targetTestVersion)
	}
}
<|endoftext|>


<commit_before>package stats

import (
	"errors"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// Prometheus represents a promethus stats collector.
type Prometheus struct {
	prefix string

	reg      *prometheus.Registry
	counters map[string]*prometheus.CounterVec
	gauges   map[string]*prometheus.GaugeVec
	timings  map[string]*prometheus.SummaryVec
}

// NewPrometheus creates a new Prometheus stats instance.
func NewPrometheus(prefix string) *Prometheus {
	return &Prometheus{
		prefix:   prefix,
		reg:      prometheus.NewRegistry(),
		counters: map[string]*prometheus.CounterVec{},
		gauges:   map[string]*prometheus.GaugeVec{},
		timings:  map[string]*prometheus.SummaryVec{},
	}
}

// Handler gets the prometheus HTTP handler.
func (s *Prometheus) Handler() http.Handler {
	return promhttp.HandlerFor(s.reg, promhttp.HandlerOpts{})
}

// Inc increments a count by the value.
func (s *Prometheus) Inc(name string, value int64, rate float32, tags ...interface{}) error {
	lblNames, lbls := formatPrometheusTags(tags)

	key := s.createKey(name, lblNames)
	m, ok := s.counters[key]
	if !ok {
		m = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: s.formatFQN(s.prefix),
				Name:      s.formatFQN(name),
				Help:      name,
			},
			lblNames,
		)

		err := s.reg.Register(m)
		if err == nil {
			s.counters[key] = m
		} else {
			existsErr, ok := err.(prometheus.AlreadyRegisteredError)
			if !ok {
				return err
			}

			m, ok = existsErr.ExistingCollector.(*prometheus.CounterVec)
			if !ok {
				return fmt.Errorf("stats: expected the collector to be instance of *CounterVec, got %T instead", existsErr.ExistingCollector)
			}
		}
	}

	m.With(lbls).Add(float64(value))

	return nil
}

// Dec decrements a count by the value.
func (s *Prometheus) Dec(name string, value int64, rate float32, tags ...interface{}) error {
	return errors.New("prometheus: decrement not supported")
}

// Gauge measures the value of a metric.
func (s *Prometheus) Gauge(name string, value float64, rate float32, tags ...interface{}) error {
	lblNames, lbls := formatPrometheusTags(tags)

	key := s.createKey(name, lblNames)
	m, ok := s.gauges[key]
	if !ok {
		m = prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Namespace: s.formatFQN(s.prefix),
				Name:      s.formatFQN(name),
				Help:      name,
			},
			lblNames,
		)

		err := s.reg.Register(m)
		if err == nil {
			s.gauges[key] = m
		} else {
			existsErr, ok := err.(prometheus.AlreadyRegisteredError)
			if !ok {
				return err
			}

			m, ok = existsErr.ExistingCollector.(*prometheus.GaugeVec)
			if !ok {
				return fmt.Errorf("stats: expected the collector to be instance of *GaugeVec, got %T instead", existsErr.ExistingCollector)
			}
		}
	}

	m.With(lbls).Set(value)

	return nil
}

// Timing sends the value of a Duration.
func (s *Prometheus) Timing(name string, value time.Duration, rate float32, tags ...interface{}) error {
	lblNames, lbls := formatPrometheusTags(tags)

	key := s.createKey(name, lblNames)
	m, ok := s.timings[key]
	if !ok {
		m = prometheus.NewSummaryVec(
			prometheus.SummaryOpts{
				Namespace:  s.formatFQN(s.prefix),
				Name:       s.formatFQN(name),
				Help:       name,
				Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
			},
			lblNames,
		)

		err := s.reg.Register(m)
		if err == nil {
			s.timings[key] = m
		} else {
			existsErr, ok := err.(prometheus.AlreadyRegisteredError)
			if !ok {
				return err
			}

			m, ok = existsErr.ExistingCollector.(*prometheus.SummaryVec)
			if !ok {
				return fmt.Errorf("stats: expected the collector to be instance of *SummaryVec, got %T instead", existsErr.ExistingCollector)
			}
		}
	}

	m.With(lbls).Observe(float64(value) / float64(time.Millisecond))

	return nil
}

// Close closes the client and flushes buffered stats, if applicable
func (s *Prometheus) Close() error {
	return nil
}

// createKey creates a unique metric key.
func (s *Prometheus) createKey(name string, lblNames []string) string {
	return name + strings.Join(lblNames, ":")
}

// formatFQN formats FQN strings.
func (s *Prometheus) formatFQN(name string) string {
	r := strings.NewReplacer(".", "_", "-", "_")

	return r.Replace(name)
}

// formatPrometheusTags create a prometheus Label map from tags.
func formatPrometheusTags(tags []interface{}) ([]string, prometheus.Labels) {
	tags = deduplicateTags(normalizeTags(tags))

	b := make([]byte, 0, 65) // The largest needed buffer is 65 bytes for a signed int64.

	names := make([]string, 0, len(tags)/2)
	lbls := make(prometheus.Labels, len(tags)/2)
	for i := 0; i < len(tags); i += 2 {
		key, ok := tags[i].(string) // The stats key must be a string.
		if !ok {
			key = fmt.Sprintf("STATS_ERROR: key %v is not a string", tags[i])
		}
		names = append(names, key)

		lbl, ok := toString(tags[i+1], b)
		if !ok {
			lbl = string(b)
		}
		lbls[key] = lbl
	}

	return names, lbls
}

// toString converts the given value to a string. It either returns the new string and true
// or fills the passed byte slice and returns an empty string and false. The user needs to check
// the returned boolean and take the string (if true) or get data from the slice.
// This is the optimization: filling the buffer allows to re-use the memory and avoid
// allocations when converting floats. Returning the string directly avoids copying strings.
func toString(v interface{}, b []byte) (string, bool) {
	switch vv := v.(type) {
	case string:
		return vv, true
	case bool:
		strconv.AppendBool(b, vv)
	case float32:
		strconv.AppendFloat(b, float64(vv), 'f', -1, 64)
	case float64:
		strconv.AppendFloat(b, vv, 'f', -1, 64)
	case int:
		strconv.AppendInt(b, int64(vv), 10)
	case int8:
		strconv.AppendInt(b, int64(vv), 10)
	case int16:
		strconv.AppendInt(b, int64(vv), 10)
	case int32:
		strconv.AppendInt(b, int64(vv), 10)
	case int64:
		strconv.AppendInt(b, vv, 10)
	case uint:
		strconv.AppendUint(b, uint64(vv), 10)
	case uint8:
		strconv.AppendUint(b, uint64(vv), 10)
	case uint16:
		strconv.AppendUint(b, uint64(vv), 10)
	case uint32:
		strconv.AppendUint(b, uint64(vv), 10)
	case uint64:
		strconv.AppendUint(b, vv, 10)
	default:
		return fmt.Sprintf("STATS_ERROR: cannot convert value %v to string", vv), true
	}

	return "", false
}
<commit_msg>[FIX] Added a compatibility fix that is able to format all types to string. (#121)<commit_after>package stats

import (
	"errors"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// Prometheus represents a promethus stats collector.
type Prometheus struct {
	prefix string

	reg      *prometheus.Registry
	counters map[string]*prometheus.CounterVec
	gauges   map[string]*prometheus.GaugeVec
	timings  map[string]*prometheus.SummaryVec
}

// NewPrometheus creates a new Prometheus stats instance.
func NewPrometheus(prefix string) *Prometheus {
	return &Prometheus{
		prefix:   prefix,
		reg:      prometheus.NewRegistry(),
		counters: map[string]*prometheus.CounterVec{},
		gauges:   map[string]*prometheus.GaugeVec{},
		timings:  map[string]*prometheus.SummaryVec{},
	}
}

// Handler gets the prometheus HTTP handler.
func (s *Prometheus) Handler() http.Handler {
	return promhttp.HandlerFor(s.reg, promhttp.HandlerOpts{})
}

// Inc increments a count by the value.
func (s *Prometheus) Inc(name string, value int64, rate float32, tags ...interface{}) error {
	lblNames, lbls := formatPrometheusTags(tags)

	key := s.createKey(name, lblNames)
	m, ok := s.counters[key]
	if !ok {
		m = prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: s.formatFQN(s.prefix),
				Name:      s.formatFQN(name),
				Help:      name,
			},
			lblNames,
		)

		err := s.reg.Register(m)
		if err == nil {
			s.counters[key] = m
		} else {
			existsErr, ok := err.(prometheus.AlreadyRegisteredError)
			if !ok {
				return err
			}

			m, ok = existsErr.ExistingCollector.(*prometheus.CounterVec)
			if !ok {
				return fmt.Errorf("stats: expected the collector to be instance of *CounterVec, got %T instead", existsErr.ExistingCollector)
			}
		}
	}

	m.With(lbls).Add(float64(value))

	return nil
}

// Dec decrements a count by the value.
func (s *Prometheus) Dec(name string, value int64, rate float32, tags ...interface{}) error {
	return errors.New("prometheus: decrement not supported")
}

// Gauge measures the value of a metric.
func (s *Prometheus) Gauge(name string, value float64, rate float32, tags ...interface{}) error {
	lblNames, lbls := formatPrometheusTags(tags)

	key := s.createKey(name, lblNames)
	m, ok := s.gauges[key]
	if !ok {
		m = prometheus.NewGaugeVec(
			prometheus.GaugeOpts{
				Namespace: s.formatFQN(s.prefix),
				Name:      s.formatFQN(name),
				Help:      name,
			},
			lblNames,
		)

		err := s.reg.Register(m)
		if err == nil {
			s.gauges[key] = m
		} else {
			existsErr, ok := err.(prometheus.AlreadyRegisteredError)
			if !ok {
				return err
			}

			m, ok = existsErr.ExistingCollector.(*prometheus.GaugeVec)
			if !ok {
				return fmt.Errorf("stats: expected the collector to be instance of *GaugeVec, got %T instead", existsErr.ExistingCollector)
			}
		}
	}

	m.With(lbls).Set(value)

	return nil
}

// Timing sends the value of a Duration.
func (s *Prometheus) Timing(name string, value time.Duration, rate float32, tags ...interface{}) error {
	lblNames, lbls := formatPrometheusTags(tags)

	key := s.createKey(name, lblNames)
	m, ok := s.timings[key]
	if !ok {
		m = prometheus.NewSummaryVec(
			prometheus.SummaryOpts{
				Namespace:  s.formatFQN(s.prefix),
				Name:       s.formatFQN(name),
				Help:       name,
				Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
			},
			lblNames,
		)

		err := s.reg.Register(m)
		if err == nil {
			s.timings[key] = m
		} else {
			existsErr, ok := err.(prometheus.AlreadyRegisteredError)
			if !ok {
				return err
			}

			m, ok = existsErr.ExistingCollector.(*prometheus.SummaryVec)
			if !ok {
				return fmt.Errorf("stats: expected the collector to be instance of *SummaryVec, got %T instead", existsErr.ExistingCollector)
			}
		}
	}

	m.With(lbls).Observe(float64(value) / float64(time.Millisecond))

	return nil
}

// Close closes the client and flushes buffered stats, if applicable
func (s *Prometheus) Close() error {
	return nil
}

// createKey creates a unique metric key.
func (s *Prometheus) createKey(name string, lblNames []string) string {
	return name + strings.Join(lblNames, ":")
}

// formatFQN formats FQN strings.
func (s *Prometheus) formatFQN(name string) string {
	r := strings.NewReplacer(".", "_", "-", "_")

	return r.Replace(name)
}

// formatPrometheusTags create a prometheus Label map from tags.
func formatPrometheusTags(tags []interface{}) ([]string, prometheus.Labels) {
	tags = deduplicateTags(normalizeTags(tags))

	b := make([]byte, 0, 65) // The largest needed buffer is 65 bytes for a signed int64.

	names := make([]string, 0, len(tags)/2)
	lbls := make(prometheus.Labels, len(tags)/2)
	for i := 0; i < len(tags); i += 2 {
		key, ok := tags[i].(string) // The stats key must be a string.
		if !ok {
			key = fmt.Sprintf("STATS_ERROR: key %v is not a string", tags[i])
		}
		names = append(names, key)

		lbl, ok := toString(tags[i+1], b)
		if !ok {
			lbl = string(b)
		}
		lbls[key] = lbl
	}

	return names, lbls
}

// toString converts the given value to a string. It either returns the new string and true
// or fills the passed byte slice and returns an empty string and false. The user needs to check
// the returned boolean and take the string (if true) or get data from the slice.
// This is the optimization: filling the buffer allows to re-use the memory and avoid
// allocations when converting floats. Returning the string directly avoids copying strings.
// The function falls back to fmt.Sprintf to format unknown values.
func toString(v interface{}, b []byte) (string, bool) {
	switch vv := v.(type) {
	case string:
		return vv, true
	case bool:
		strconv.AppendBool(b, vv)
	case float32:
		strconv.AppendFloat(b, float64(vv), 'f', -1, 64)
	case float64:
		strconv.AppendFloat(b, vv, 'f', -1, 64)
	case int:
		strconv.AppendInt(b, int64(vv), 10)
	case int8:
		strconv.AppendInt(b, int64(vv), 10)
	case int16:
		strconv.AppendInt(b, int64(vv), 10)
	case int32:
		strconv.AppendInt(b, int64(vv), 10)
	case int64:
		strconv.AppendInt(b, vv, 10)
	case uint:
		strconv.AppendUint(b, uint64(vv), 10)
	case uint8:
		strconv.AppendUint(b, uint64(vv), 10)
	case uint16:
		strconv.AppendUint(b, uint64(vv), 10)
	case uint32:
		strconv.AppendUint(b, uint64(vv), 10)
	case uint64:
		strconv.AppendUint(b, vv, 10)
	default:
		return fmt.Sprintf("%v", vv), true
	}

	return "", false
}
<|endoftext|>


<commit_before>package storage

import (
	_ "github.com/lib/pq"
	"log"
	"database/sql"
	"fmt"
	"time"
)

const TABLE_USERS = `create table if not exists users
(
  id           serial,
  created_date timestamp default now(),
  chat_id      bigint unique     not null,
  access_token text unique     not null
);`

type Postgres struct {
	db *sql.DB
}

type User struct {
	id          int
	createdDate time.Time
	chatId      int
	accessToken string
}

func NewPostgres(url string) *Postgres {
	db, err := sql.Open("postgres", url)
	if err != nil {
		log.Fatal(err)
	}

	_, err = db.Exec(TABLE_USERS)
	if err != nil {
		log.Fatal(err)
	}

	return &Postgres{
		db,
	}
}

func (postgres *Postgres) Add(chatId int64, accessToken string) error {
	result, err := postgres.db.Exec("insert into users (chat_id, access_token) values ($1, $2)", chatId, accessToken)
	if err != nil {
		return err
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		return err
	}

	fmt.Printf("User %d created successfully (%d row affected)\n", chatId, rowsAffected)

	return nil
}

func (postgres *Postgres) Get(chatId int64) (string, error) {
	stmt, err := postgres.db.Prepare("select u.access_token from users u where u.chat_id=$1")
	if err != nil {
		return "", err
	}

	defer stmt.Close()

	row := stmt.QueryRow(chatId)

	var accessToken string
	err = row.Scan(&accessToken)
	if err != nil {
		return "", err
	}

	return accessToken, nil
}

func (postgres *Postgres) Delete(chatId int64) error {
	result, err := postgres.db.Exec("delete from users where chat_id=$1", chatId)
	if err != nil {
		return err
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		return err
	}

	fmt.Printf("User %d deleted successfully (%d row affected)\n", chatId, rowsAffected)

	return nil
}
<commit_msg>fix bug select access token from DB<commit_after>package storage

import (
	_ "github.com/lib/pq"
	"log"
	"database/sql"
	"fmt"
	"time"
)

const TABLE_USERS = `create table if not exists users
(
  id           serial,
  created_date timestamp default now(),
  chat_id      bigint unique     not null,
  access_token text unique     not null
);`

type Postgres struct {
	db *sql.DB
}

type User struct {
	id          int
	createdDate time.Time
	chatId      int
	accessToken string
}

func NewPostgres(url string) *Postgres {
	db, err := sql.Open("postgres", url)
	if err != nil {
		log.Fatal(err)
	}

	_, err = db.Exec(TABLE_USERS)
	if err != nil {
		log.Fatal(err)
	}

	return &Postgres{
		db,
	}
}

func (postgres *Postgres) Add(chatId int64, accessToken string) error {
	result, err := postgres.db.Exec("insert into users (chat_id, access_token) values ($1, $2)", chatId, accessToken)
	if err != nil {
		return err
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		return err
	}

	fmt.Printf("User %d created successfully (%d row affected)\n", chatId, rowsAffected)

	return nil
}

func (postgres *Postgres) Get(chatId int64) (string, error) {
	stmt, err := postgres.db.Prepare("select u.access_token from users u where u.chat_id=$1")
	if err != nil {
		return "", err
	}

	defer stmt.Close()

	row := stmt.QueryRow(chatId)

	var accessToken string
	err = row.Scan(&accessToken)
	if err == sql.ErrNoRows {
		return "", nil
	} else {
		return "", err
	}

	return accessToken, nil
}

func (postgres *Postgres) Delete(chatId int64) error {
	result, err := postgres.db.Exec("delete from users where chat_id=$1", chatId)
	if err != nil {
		return err
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		return err
	}

	fmt.Printf("User %d deleted successfully (%d row affected)\n", chatId, rowsAffected)

	return nil
}
<|endoftext|>


<commit_before>// Package google implements logging in through Google's OpenID Connect provider.
package google

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"time"

	"github.com/coreos/go-oidc"
	"github.com/sirupsen/logrus"
	"golang.org/x/oauth2"

	"github.com/dexidp/dex/connector"
)

// Config holds configuration options for OpenID Connect logins.
type Config struct {
	Issuer       string `json:"issuer"`
	ClientID     string `json:"clientID"`
	ClientSecret string `json:"clientSecret"`
	RedirectURI  string `json:"redirectURI"`

	Scopes []string `json:"scopes"` // defaults to "profile" and "email"

	// Optional list of whitelisted domains
	// If this field is nonempty, only users from a listed domain will be allowed to log in
	HostedDomains []string `json:"hostedDomains"`
}

// Open returns a connector which can be used to login users through an upstream
// OpenID Connect provider.
func (c *Config) Open(id string, logger logrus.FieldLogger) (conn connector.Connector, err error) {
	ctx, cancel := context.WithCancel(context.Background())

	provider, err := oidc.NewProvider(ctx, c.Issuer)
	if err != nil {
		cancel()
		return nil, fmt.Errorf("failed to get provider: %v", err)
	}

	scopes := []string{oidc.ScopeOpenID}
	if len(c.Scopes) > 0 {
		scopes = append(scopes, c.Scopes...)
	} else {
		scopes = append(scopes, "profile", "email")
	}

	clientID := c.ClientID
	return &googleConnector{
		redirectURI: c.RedirectURI,
		oauth2Config: &oauth2.Config{
			ClientID:     clientID,
			ClientSecret: c.ClientSecret,
			Endpoint:     provider.Endpoint(),
			Scopes:       scopes,
			RedirectURL:  c.RedirectURI,
		},
		verifier: provider.Verifier(
			&oidc.Config{ClientID: clientID},
		),
		logger:        logger,
		cancel:        cancel,
		hostedDomains: c.HostedDomains,
	}, nil
}

var (
	_ connector.CallbackConnector = (*googleConnector)(nil)
	_ connector.RefreshConnector  = (*googleConnector)(nil)
)

type googleConnector struct {
	redirectURI   string
	oauth2Config  *oauth2.Config
	verifier      *oidc.IDTokenVerifier
	ctx           context.Context
	cancel        context.CancelFunc
	logger        logrus.FieldLogger
	hostedDomains []string
}

func (c *googleConnector) Close() error {
	c.cancel()
	return nil
}

func (c *googleConnector) LoginURL(s connector.Scopes, callbackURL, state string) (string, error) {
	if c.redirectURI != callbackURL {
		return "", fmt.Errorf("expected callback URL %q did not match the URL in the config %q", callbackURL, c.redirectURI)
	}

	var opts []oauth2.AuthCodeOption
	if len(c.hostedDomains) > 0 {
		preferredDomain := c.hostedDomains[0]
		if len(c.hostedDomains) > 1 {
			preferredDomain = "*"
		}
		opts = append(opts, oauth2.SetAuthURLParam("hd", preferredDomain))
	}

	if s.OfflineAccess {
		opts = append(opts, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", "consent"))
	}
	return c.oauth2Config.AuthCodeURL(state, opts...), nil
}

type oauth2Error struct {
	error            string
	errorDescription string
}

func (e *oauth2Error) Error() string {
	if e.errorDescription == "" {
		return e.error
	}
	return e.error + ": " + e.errorDescription
}

func (c *googleConnector) HandleCallback(s connector.Scopes, r *http.Request) (identity connector.Identity, err error) {
	q := r.URL.Query()
	if errType := q.Get("error"); errType != "" {
		return identity, &oauth2Error{errType, q.Get("error_description")}
	}
	token, err := c.oauth2Config.Exchange(r.Context(), q.Get("code"))
	if err != nil {
		return identity, fmt.Errorf("google: failed to get token: %v", err)
	}

	return c.createIdentity(r.Context(), identity, token)
}

// Refresh is implemented for backwards compatibility, even though it's a no-op.
func (c *googleConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) {
	t := &oauth2.Token{
		RefreshToken: string(identity.ConnectorData),
		Expiry:       time.Now().Add(-time.Hour),
	}
	token, err := c.oauth2Config.TokenSource(ctx, t).Token()
	if err != nil {
		return identity, fmt.Errorf("google: failed to get token: %v", err)
	}

	return c.createIdentity(ctx, identity, token)
}

func (c *googleConnector) createIdentity(ctx context.Context, identity connector.Identity, token *oauth2.Token) (connector.Identity, error) {
	rawIDToken, ok := token.Extra("id_token").(string)
	if !ok {
		return identity, errors.New("google: no id_token in token response")
	}
	idToken, err := c.verifier.Verify(ctx, rawIDToken)
	if err != nil {
		return identity, fmt.Errorf("google: failed to verify ID Token: %v", err)
	}

	var claims struct {
		Username      string `json:"name"`
		Email         string `json:"email"`
		EmailVerified bool   `json:"email_verified"`
		HostedDomain  string `json:"hd"`
	}
	if err := idToken.Claims(&claims); err != nil {
		return identity, fmt.Errorf("oidc: failed to decode claims: %v", err)
	}

	if len(c.hostedDomains) > 0 {
		found := false
		for _, domain := range c.hostedDomains {
			if claims.HostedDomain == domain {
				found = true
				break
			}
		}

		if !found {
			return identity, fmt.Errorf("oidc: unexpected hd claim %v", claims.HostedDomain)
		}
	}

	identity = connector.Identity{
		UserID:        idToken.Subject,
		Username:      claims.Username,
		Email:         claims.Email,
		EmailVerified: claims.EmailVerified,
		ConnectorData: []byte(token.RefreshToken),
	}
	return identity, nil
}
<commit_msg>No need to configure issuer<commit_after>// Package google implements logging in through Google's OpenID Connect provider.
package google

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"time"

	"github.com/coreos/go-oidc"
	"github.com/sirupsen/logrus"
	"golang.org/x/oauth2"

	"github.com/dexidp/dex/connector"
)

const (
	issuerURL = "https://accounts.google.com"
)

// Config holds configuration options for OpenID Connect logins.
type Config struct {
	ClientID     string `json:"clientID"`
	ClientSecret string `json:"clientSecret"`
	RedirectURI  string `json:"redirectURI"`

	Scopes []string `json:"scopes"` // defaults to "profile" and "email"

	// Optional list of whitelisted domains
	// If this field is nonempty, only users from a listed domain will be allowed to log in
	HostedDomains []string `json:"hostedDomains"`
}

// Open returns a connector which can be used to login users through an upstream
// OpenID Connect provider.
func (c *Config) Open(id string, logger logrus.FieldLogger) (conn connector.Connector, err error) {
	ctx, cancel := context.WithCancel(context.Background())

	provider, err := oidc.NewProvider(ctx, issuerURL)
	if err != nil {
		cancel()
		return nil, fmt.Errorf("failed to get provider: %v", err)
	}

	scopes := []string{oidc.ScopeOpenID}
	if len(c.Scopes) > 0 {
		scopes = append(scopes, c.Scopes...)
	} else {
		scopes = append(scopes, "profile", "email")
	}

	clientID := c.ClientID
	return &googleConnector{
		redirectURI: c.RedirectURI,
		oauth2Config: &oauth2.Config{
			ClientID:     clientID,
			ClientSecret: c.ClientSecret,
			Endpoint:     provider.Endpoint(),
			Scopes:       scopes,
			RedirectURL:  c.RedirectURI,
		},
		verifier: provider.Verifier(
			&oidc.Config{ClientID: clientID},
		),
		logger:        logger,
		cancel:        cancel,
		hostedDomains: c.HostedDomains,
	}, nil
}

var (
	_ connector.CallbackConnector = (*googleConnector)(nil)
	_ connector.RefreshConnector  = (*googleConnector)(nil)
)

type googleConnector struct {
	redirectURI   string
	oauth2Config  *oauth2.Config
	verifier      *oidc.IDTokenVerifier
	ctx           context.Context
	cancel        context.CancelFunc
	logger        logrus.FieldLogger
	hostedDomains []string
}

func (c *googleConnector) Close() error {
	c.cancel()
	return nil
}

func (c *googleConnector) LoginURL(s connector.Scopes, callbackURL, state string) (string, error) {
	if c.redirectURI != callbackURL {
		return "", fmt.Errorf("expected callback URL %q did not match the URL in the config %q", callbackURL, c.redirectURI)
	}

	var opts []oauth2.AuthCodeOption
	if len(c.hostedDomains) > 0 {
		preferredDomain := c.hostedDomains[0]
		if len(c.hostedDomains) > 1 {
			preferredDomain = "*"
		}
		opts = append(opts, oauth2.SetAuthURLParam("hd", preferredDomain))
	}

	if s.OfflineAccess {
		opts = append(opts, oauth2.AccessTypeOffline, oauth2.SetAuthURLParam("prompt", "consent"))
	}
	return c.oauth2Config.AuthCodeURL(state, opts...), nil
}

type oauth2Error struct {
	error            string
	errorDescription string
}

func (e *oauth2Error) Error() string {
	if e.errorDescription == "" {
		return e.error
	}
	return e.error + ": " + e.errorDescription
}

func (c *googleConnector) HandleCallback(s connector.Scopes, r *http.Request) (identity connector.Identity, err error) {
	q := r.URL.Query()
	if errType := q.Get("error"); errType != "" {
		return identity, &oauth2Error{errType, q.Get("error_description")}
	}
	token, err := c.oauth2Config.Exchange(r.Context(), q.Get("code"))
	if err != nil {
		return identity, fmt.Errorf("google: failed to get token: %v", err)
	}

	return c.createIdentity(r.Context(), identity, token)
}

// Refresh is implemented for backwards compatibility, even though it's a no-op.
func (c *googleConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) {
	t := &oauth2.Token{
		RefreshToken: string(identity.ConnectorData),
		Expiry:       time.Now().Add(-time.Hour),
	}
	token, err := c.oauth2Config.TokenSource(ctx, t).Token()
	if err != nil {
		return identity, fmt.Errorf("google: failed to get token: %v", err)
	}

	return c.createIdentity(ctx, identity, token)
}

func (c *googleConnector) createIdentity(ctx context.Context, identity connector.Identity, token *oauth2.Token) (connector.Identity, error) {
	rawIDToken, ok := token.Extra("id_token").(string)
	if !ok {
		return identity, errors.New("google: no id_token in token response")
	}
	idToken, err := c.verifier.Verify(ctx, rawIDToken)
	if err != nil {
		return identity, fmt.Errorf("google: failed to verify ID Token: %v", err)
	}

	var claims struct {
		Username      string `json:"name"`
		Email         string `json:"email"`
		EmailVerified bool   `json:"email_verified"`
		HostedDomain  string `json:"hd"`
	}
	if err := idToken.Claims(&claims); err != nil {
		return identity, fmt.Errorf("oidc: failed to decode claims: %v", err)
	}

	if len(c.hostedDomains) > 0 {
		found := false
		for _, domain := range c.hostedDomains {
			if claims.HostedDomain == domain {
				found = true
				break
			}
		}

		if !found {
			return identity, fmt.Errorf("oidc: unexpected hd claim %v", claims.HostedDomain)
		}
	}

	identity = connector.Identity{
		UserID:        idToken.Subject,
		Username:      claims.Username,
		Email:         claims.Email,
		EmailVerified: claims.EmailVerified,
		ConnectorData: []byte(token.RefreshToken),
	}
	return identity, nil
}
<|endoftext|>


<commit_before>package stripe

import (
	"net/url"
	"strconv"
)

type Customer struct {
	Id                string `json:"id"`
	Object            string `json:"object"`
  Livemode          bool   `json:"livemode"`
  Created           int64  `json:"created"`
  AccountBalance    int64  `json:"account_balance"`
  Currency          string `json:"currency"`
  DefaultCard       string `json:"default_card"`
  Delinquent        bool   `json:"delinquent"`
  //Discount          Discount `json:"discount"`
  Email             string `json:"email"`
  //Subscription      Subscription `json:"subscription"`
}

// Delete deletes a customer.
//
// For more information: https://stripe.com/docs/api#delete_customer
func (c *Customer) Delete() (*DeleteResponse, error) {
  response := DeleteResponse{}
  err := delete("/customers/" + c.Id, nil, &response)
  return &response, err
}

// Update updates a customer.
//
// For more information: https://stripe.com/docs/api#update_customer
func (c *Customer) Update(params *CustomerParams) (*Customer, error) {
  values := url.Values{}
  parseCustomerParams(params, &values)
  err := post("/customers/" + c.Id, values, c)
  return c, err
}

// The CustomerClient is the receiver for most standard customer related endpoints.
type CustomerClient struct{}

// Create creates a customer.
//
// For more information: https://stripe.com/docs/api#create_customer
func (c *CustomerClient) Create(params *CustomerParams) (*Customer, error) {
  customer := Customer{}
  values := url.Values{}
  parseCustomerParams(params, &values)
  err := post("/customers", values, &customer)
  return &customer, err
}

// Retrieve loads a customer.
//
// For more information: https://stripe.com/docs/api#retrieve_customer
func (c *CustomerClient) Retrieve(id string) (*Customer, error) {
  customer := Customer{}
  err := get("/customers/" + id, nil, &customer)
  return &customer, err
}

// Update updates a customer.
//
// For more information: https://stripe.com/docs/api#update_customer
func (c *CustomerClient) Update(id string, params *CustomerParams) (*Customer, error) {
  customer := Customer{}
  values := url.Values{}
  parseCustomerParams(params, &values)
  err := post("/customers/" + id, values, &customer)
  return &customer, err
}

// Delete deletes a customer.
//
// For more information: https://stripe.com/docs/api#delete_customer
func (c *CustomerClient) Delete(id string) (*DeleteResponse, error) {
  response := DeleteResponse{}
  err := delete("/customers/" + id, nil, &response)
  return &response, err
}

// List lists the first 10 customers for a customer. It calls ListCount with 10 as
// the count and 0 as the offset, which are the defaults in the Stripe API.
//
// For more information: https://stripe.com/docs/api#list_customers
func (c *CustomerClient) List() ([]*Customer, error) {
	return c.ListCount(10, 0)
}

// ListCount lists `count` customers for a customer starting at `offset`.
//
// For more information: https://stripe.com/docs/api#list_customers
func (c *CustomerClient) ListCount(count, offset int) ([]*Customer, error) {
	type customers struct{ Data []*Customer }
	list := customers{}

	params := url.Values{
		"count"   : {strconv.Itoa(count)},
		"offset"  : {strconv.Itoa(offset)},
	}

	err := get("/customers", params, &list)
	return list.Data, err
}

// parseCustomerParams takes a pointer to a CustomerParams and a pointer to a url.Values,
// it iterates over everything in the CustomerParams struct and Adds what is there
// to the url.Values.
func parseCustomerParams(params *CustomerParams, values *url.Values) {

  // Use parseCardParams from cards.go to setup the card param
  parseCardParams(params.CardParams, values, true)

  if params.AccountBalance != 0 {
    values.Add("account_balance", strconv.Itoa(params.AccountBalance))
  }

  if params.Coupon != "" {
    values.Add("coupon", params.Coupon)
  }

  if params.Description != "" {
    values.Add("description", params.Description)
  }

  if params.Email != "" {
    values.Add("email", params.Email)
  }

  if params.Plan != "" {
    values.Add("plan", params.Plan)
  }

  if params.Quantity != 0 {
    values.Add("quantity", strconv.Itoa(params.Quantity))
  }

  if params.TrialEnd != 0 {
    values.Add("trial_end", strconv.Itoa(params.TrialEnd))
  }
}
<commit_msg>fixed customer update with card params<commit_after>package stripe

import (
	"net/url"
	"strconv"
)

type Customer struct {
	Id                string `json:"id"`
	Object            string `json:"object"`
  Livemode          bool   `json:"livemode"`
  Created           int64  `json:"created"`
  AccountBalance    int64  `json:"account_balance"`
  Currency          string `json:"currency"`
  DefaultCard       string `json:"default_card"`
  Delinquent        bool   `json:"delinquent"`
  //Discount          Discount `json:"discount"`
  Email             string `json:"email"`
  //Subscription      Subscription `json:"subscription"`
}

// Delete deletes a customer.
//
// For more information: https://stripe.com/docs/api#delete_customer
func (c *Customer) Delete() (*DeleteResponse, error) {
  response := DeleteResponse{}
  err := delete("/customers/" + c.Id, nil, &response)
  return &response, err
}

// Update updates a customer.
//
// For more information: https://stripe.com/docs/api#update_customer
func (c *Customer) Update(params *CustomerParams) (*Customer, error) {
  values := url.Values{}
  parseCustomerParams(params, &values)
  err := post("/customers/" + c.Id, values, c)
  return c, err
}

// The CustomerClient is the receiver for most standard customer related endpoints.
type CustomerClient struct{}

// Create creates a customer.
//
// For more information: https://stripe.com/docs/api#create_customer
func (c *CustomerClient) Create(params *CustomerParams) (*Customer, error) {
  customer := Customer{}
  values := url.Values{}
  parseCustomerParams(params, &values)
  err := post("/customers", values, &customer)
  return &customer, err
}

// Retrieve loads a customer.
//
// For more information: https://stripe.com/docs/api#retrieve_customer
func (c *CustomerClient) Retrieve(id string) (*Customer, error) {
  customer := Customer{}
  err := get("/customers/" + id, nil, &customer)
  return &customer, err
}

// Update updates a customer.
//
// For more information: https://stripe.com/docs/api#update_customer
func (c *CustomerClient) Update(id string, params *CustomerParams) (*Customer, error) {
  customer := Customer{}
  values := url.Values{}
  parseCustomerParams(params, &values)
  err := post("/customers/" + id, values, &customer)
  return &customer, err
}

// Delete deletes a customer.
//
// For more information: https://stripe.com/docs/api#delete_customer
func (c *CustomerClient) Delete(id string) (*DeleteResponse, error) {
  response := DeleteResponse{}
  err := delete("/customers/" + id, nil, &response)
  return &response, err
}

// List lists the first 10 customers for a customer. It calls ListCount with 10 as
// the count and 0 as the offset, which are the defaults in the Stripe API.
//
// For more information: https://stripe.com/docs/api#list_customers
func (c *CustomerClient) List() ([]*Customer, error) {
	return c.ListCount(10, 0)
}

// ListCount lists `count` customers for a customer starting at `offset`.
//
// For more information: https://stripe.com/docs/api#list_customers
func (c *CustomerClient) ListCount(count, offset int) ([]*Customer, error) {
	type customers struct{ Data []*Customer }
	list := customers{}

	params := url.Values{
		"count"   : {strconv.Itoa(count)},
		"offset"  : {strconv.Itoa(offset)},
	}

	err := get("/customers", params, &list)
	return list.Data, err
}

// parseCustomerParams takes a pointer to a CustomerParams and a pointer to a url.Values,
// it iterates over everything in the CustomerParams struct and Adds what is there
// to the url.Values.
func parseCustomerParams(params *CustomerParams, values *url.Values) {

  // Use parseCardParams from cards.go to setup the card param
  if params.CardParams != nil {
    parseCardParams(params.CardParams, values, true)
  }

  if params.AccountBalance != 0 {
    values.Add("account_balance", strconv.Itoa(params.AccountBalance))
  }

  if params.Coupon != "" {
    values.Add("coupon", params.Coupon)
  }

  if params.Description != "" {
    values.Add("description", params.Description)
  }

  if params.Email != "" {
    values.Add("email", params.Email)
  }

  if params.Plan != "" {
    values.Add("plan", params.Plan)
  }

  if params.Quantity != 0 {
    values.Add("quantity", strconv.Itoa(params.Quantity))
  }

  if params.TrialEnd != 0 {
    values.Add("trial_end", strconv.Itoa(params.TrialEnd))
  }
}
<|endoftext|>


<commit_before>package controllers

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gorilla/mux"
	. "github.com/smartystreets/goconvey/convey"
)

func TestGetTables(t *testing.T) {
	Convey("Get tables without custom where clause", t, func() {
		r, err := http.NewRequest("GET", "/tables", nil)
		w := httptest.NewRecorder()
		So(err, ShouldBeNil)
		validate(w, r, GetTables)
	})

	Convey("Get tables with custom where clause", t, func() {
		r, err := http.NewRequest("GET", "/tables?c.relname=prest", nil)
		w := httptest.NewRecorder()
		So(err, ShouldBeNil)
		validate(w, r, GetTables)
	})
}

func TestGetTablesByDatabaseAndSchema(t *testing.T) {
	router := mux.NewRouter()
	router.HandleFunc("/{database}/{schema}", GetTablesByDatabaseAndSchema).Methods("GET")
	server := httptest.NewServer(router)
	defer server.Close()
	Convey("Get tables by database and schema without custom where clause", t, func() {
		doValidRequest(server.URL + "/prest/public")
	})

	Convey("Get tables by database and schema with custom where clause", t, func() {
		doValidRequest(server.URL + "/prest/public?t.tablename=test")
	})
}
<commit_msg>select in tables test<commit_after>package controllers

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gorilla/mux"
	. "github.com/smartystreets/goconvey/convey"
)

func TestGetTables(t *testing.T) {
	Convey("Get tables without custom where clause", t, func() {
		r, err := http.NewRequest("GET", "/tables", nil)
		w := httptest.NewRecorder()
		So(err, ShouldBeNil)
		validate(w, r, GetTables)
	})

	Convey("Get tables with custom where clause", t, func() {
		r, err := http.NewRequest("GET", "/tables?c.relname=test", nil)
		w := httptest.NewRecorder()
		So(err, ShouldBeNil)
		validate(w, r, GetTables)
	})
}

func TestGetTablesByDatabaseAndSchema(t *testing.T) {
	router := mux.NewRouter()
	router.HandleFunc("/{database}/{schema}", GetTablesByDatabaseAndSchema).Methods("GET")
	server := httptest.NewServer(router)
	defer server.Close()
	Convey("Get tables by database and schema without custom where clause", t, func() {
		doValidRequest(server.URL + "/prest/public")
	})

	Convey("Get tables by database and schema with custom where clause", t, func() {
		doValidRequest(server.URL + "/prest/public?t.tablename=test")
	})
}

func TestSelectFromTable(t *testing.T) {
	router := mux.NewRouter()
	router.HandleFunc("/{database}/{schema}/{table}", SelectFromTables).Methods("GET")
	server := httptest.NewServer(router)
	defer server.Close()
	Convey("execute select in a table without custom where clause", t, func() {
		doValidRequest(server.URL + "/prest/public")
	})

	Convey("execute select in a table with custom where clause", t, func() {
		doValidRequest(server.URL + "/prest/public/test?name=nuveo")
	})
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Santiago Arias | Remy Jourde
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package users

import (
	"errors"
	"net/http"

	"appengine"

	"github.com/santiaago/gonawin/extract"
	"github.com/santiaago/gonawin/helpers"
	templateshlp "github.com/santiaago/gonawin/helpers/templates"
	mdl "github.com/santiaago/gonawin/models"
)

// User score handler, returns the JSON data of the requested user.
func Score(w http.ResponseWriter, r *http.Request, u *mdl.User) error {
	if r.Method != "GET" {
		return &helpers.BadRequest{Err: errors.New(helpers.ErrorCodeNotSupported)}
	}

	c := appengine.NewContext(r)
	extract := extract.NewContext(c, "User Score Handler:", r)

	user, err := extract.User()
	if err != nil {
		return err
	}

	scores := user.TournamentsScores(c)

	data := struct {
		Scores []*mdl.ScoreOverall
	}{
		scores,
	}

	return templateshlp.RenderJson(w, c, data)
}
<commit_msg>refactor score ctrl<commit_after>/*
 * Copyright (c) 2014 Santiago Arias | Remy Jourde
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

package users

import (
	"errors"
	"net/http"

	"appengine"

	"github.com/santiaago/gonawin/extract"
	"github.com/santiaago/gonawin/helpers"
	templateshlp "github.com/santiaago/gonawin/helpers/templates"
	mdl "github.com/santiaago/gonawin/models"
)

// Score handler, returns the score data of the requested user.
//
func Score(w http.ResponseWriter, r *http.Request, u *mdl.User) error {
	if r.Method != "GET" {
		return &helpers.BadRequest{Err: errors.New(helpers.ErrorCodeNotSupported)}
	}

	c := appengine.NewContext(r)
	extract := extract.NewContext(c, "User Score Handler:", r)

	var user *mdl.User
	var err error
	if user, err = extract.User(); err != nil {
		return err
	}

	scores := user.TournamentsScores(c)

	vm := buildScoreUserViewModel(scores)

	return templateshlp.RenderJson(w, c, vm)
}

type scoreUserViewModel struct {
	Scores []*mdl.ScoreOverall
}

func buildScoreUserViewModel(scores []*mdl.ScoreOverall) scoreUserViewModel {
	return scoreUserViewModel{scores}
}
<|endoftext|>


<commit_before>package system

import (
	"fmt"
	"path"
	"testing"

	"github.com/goesd/support/assert"
)

const (
	fixturePath = "fixtures"
)

func TestLoadTGFF(t *testing.T) {
	plat, app, err := LoadTGFF(findFixture("002_040"))

	assert.Success(err, t)
	assert.Equal(len(plat.Cores), 2, t)
	assert.Equal(len(app.Tasks), 40, t)

	tasks := []struct {
		children []uint32
	}{
		{[]uint32{1}},
		{[]uint32{2, 3, 23, 32}},
		{[]uint32{4, 10, 11, 12}},
		{[]uint32{9, 10, 26}},
		{[]uint32{5, 6, 7, 8}},

		{[]uint32{10, 11, 27}},
		{[]uint32{}},
		{[]uint32{9}},
		{[]uint32{9}},
		{[]uint32{13, 14, 15}},

		{[]uint32{12}},
		{[]uint32{12, 31}},
		{[]uint32{17, 18, 24}},
		{[]uint32{16, 25}},
		{[]uint32{36}},

		{[]uint32{19, 20, 23, 29}},
		{[]uint32{31}},
		{[]uint32{22, 35}},
		{[]uint32{21, 23}},
		{[]uint32{20, 24}},

		{[]uint32{24, 26}},
		{[]uint32{27}},
		{[]uint32{28, 29}},
		{[]uint32{31}},
		{[]uint32{30}},

		{[]uint32{37, 38}},
		{[]uint32{}},
		{[]uint32{33, 34}},
		{[]uint32{29}},
		{[]uint32{}},

		{[]uint32{}},
		{[]uint32{36}},
		{[]uint32{}},
		{[]uint32{}},
		{[]uint32{}},

		{[]uint32{}},
		{[]uint32{}},
		{[]uint32{}},
		{[]uint32{39}},
		{[]uint32{}},
	}

	for i, task := range tasks {
		assert.Equal(app.Tasks[i].Children, task.children, t)
	}
}

func TestExtractTaskNumber(t *testing.T) {
	scenarios := []struct {
		name    string
		total   uint32
		result  uint32
		success bool
	}{
		{"t0_0", 50, 0, true},
		{"t0_42", 50, 42, true},
		{"t0_42", 43, 42, true},
		{"t0_42", 42, 0, false},
		{"t1_42", 50, 0, false},
		{"t0_-2", 50, 0, false},
	}

	for _, s := range scenarios {
		result, err := extractTaskID(s.name, s.total)

		if s.success {
			assert.Success(err, t)
		} else {
			assert.Failure(err, t)
		}

		assert.Equal(result, s.result, t)
	}
}

func BenchmarkLoadTGFF(b *testing.B) {
	path := findFixture("002_040")

	for i := 0; i < b.N; i++ {
		LoadTGFF(path)
	}
}

func findFixture(name string) string {
	return path.Join(fixturePath, fmt.Sprintf("%s.tgff", name))
}
<commit_msg>Fixed TestLoadTGFF<commit_after>package system

import (
	"fmt"
	"path"
	"testing"

	"github.com/goesd/support/assert"
)

const (
	fixturePath = "fixtures"
)

func TestLoadTGFF(t *testing.T) {
	plat, app, err := LoadTGFF(findFixture("002_040"))

	assert.Success(err, t)
	assert.Equal(len(plat.Cores), 2, t)
	assert.Equal(len(app.Tasks), 40, t)

	tasks := []struct {
		children []uint32
	}{
		{[]uint32{1}},
		{[]uint32{2, 3, 23, 32}},
		{[]uint32{4, 10, 11, 12}},
		{[]uint32{9, 10, 26}},
		{[]uint32{5, 6, 7, 8}},

		{[]uint32{10, 11, 27}},
		{nil},
		{[]uint32{9}},
		{[]uint32{9}},
		{[]uint32{13, 14, 15}},

		{[]uint32{12}},
		{[]uint32{12, 31}},
		{[]uint32{17, 18, 24}},
		{[]uint32{16, 25}},
		{[]uint32{36}},

		{[]uint32{19, 20, 23, 29}},
		{[]uint32{31}},
		{[]uint32{22, 35}},
		{[]uint32{21, 23}},
		{[]uint32{20, 24}},

		{[]uint32{24, 26}},
		{[]uint32{27}},
		{[]uint32{28, 29}},
		{[]uint32{31}},
		{[]uint32{30}},

		{[]uint32{37, 38}},
		{nil},
		{[]uint32{33, 34}},
		{[]uint32{29}},
		{nil},

		{nil},
		{[]uint32{36}},
		{nil},
		{nil},
		{nil},

		{nil},
		{nil},
		{nil},
		{[]uint32{39}},
		{nil},
	}

	for i, task := range tasks {
		assert.Equal(app.Tasks[i].Children, task.children, t)
	}
}

func TestExtractTaskNumber(t *testing.T) {
	scenarios := []struct {
		name    string
		total   uint32
		result  uint32
		success bool
	}{
		{"t0_0", 50, 0, true},
		{"t0_42", 50, 42, true},
		{"t0_42", 43, 42, true},
		{"t0_42", 42, 0, false},
		{"t1_42", 50, 0, false},
		{"t0_-2", 50, 0, false},
	}

	for _, s := range scenarios {
		result, err := extractTaskID(s.name, s.total)

		if s.success {
			assert.Success(err, t)
		} else {
			assert.Failure(err, t)
		}

		assert.Equal(result, s.result, t)
	}
}

func BenchmarkLoadTGFF(b *testing.B) {
	path := findFixture("002_040")

	for i := 0; i < b.N; i++ {
		LoadTGFF(path)
	}
}

func findFixture(name string) string {
	return path.Join(fixturePath, fmt.Sprintf("%s.tgff", name))
}
<|endoftext|>


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

// +build windows,!appengine

package logrus

import (
	"io"
	"os"
	"syscall"
	"unsafe"
)

var kernel32 = syscall.NewLazyDLL("kernel32.dll")

var (
	procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
)

// IsTerminal returns true if stderr's file descriptor is a terminal.
func IsTerminal(f io.Writer) bool {
	switch v := f.(type) {
	case *os.File:
		var st uint32
		r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(v.Fd()), uintptr(unsafe.Pointer(&st)), 0)
		return r != 0 && e == 0
	default:
		return false
	}
}
<commit_msg>Enable ANSI colors on Windows 10 and newer<commit_after>// Based on ssh/terminal:
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// +build windows,!appengine

package logrus

import (
	"bytes"
	"errors"
	"io"
	"os"
	"os/exec"
	"strconv"
	"strings"
	"syscall"
	"unsafe"
)

var kernel32 = syscall.NewLazyDLL("kernel32.dll")

var (
	procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
	procSetConsoleMode = kernel32.NewProc("SetConsoleMode")
)

const (
	enableProcessedOutput           = 0x0001
	enableWrapAtEolOutput           = 0x0002
	enableVirtualTerminalProcessing = 0x0004
)

func getVersion() (float64, error) {
	stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{}
	cmd := exec.Command("cmd", "ver")
	cmd.Stdout = stdout
	cmd.Stderr = stderr
	err := cmd.Run()
	if err != nil {
		return -1, err
	}

	version := strings.Replace(stdout.String(), "\n", "", -1)
	version = strings.Replace(version, "\r\n", "", -1)

	x1 := strings.Index(version, "[Version")

	if x1 == -1 || strings.Index(version, "]") == -1 {
		return -1, errors.New("Can't determine Windows version")
	}

	return strconv.ParseFloat(version[x1+9:x1+13], 64)
}

func init() {
	ver, err := getVersion()
	if err != nil {
		panic(err)
	}

	// Activate Virtual Processing for Windows CMD
	// Info: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx
	if ver >= 10 {
		handle := syscall.Handle(os.Stderr.Fd())
		procSetConsoleMode.Call(uintptr(handle), enableProcessedOutput|enableWrapAtEolOutput|enableVirtualTerminalProcessing)
	}
}

// IsTerminal returns true if stderr's file descriptor is a terminal.
func IsTerminal(f io.Writer) bool {
	switch v := f.(type) {
	case *os.File:
		var st uint32
		r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(v.Fd()), uintptr(unsafe.Pointer(&st)), 0)
		return r != 0 && e == 0
	default:
		return false
	}
}
<|endoftext|>


<commit_before>// errchk $G $D/$F.go

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

package main

const none = 0  // same const identifier declared twice should not be accepted
const none = 1  // ERROR "redeclared"
<commit_msg>Tweak comments so that this test passes with gccgo.<commit_after>// errchk $G $D/$F.go

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

package main

// same const identifier declared twice should not be accepted
const none = 0  // GCCGO_ERROR "previous"
const none = 1  // ERROR "redeclared|redef"
<|endoftext|>