<commit_before>package main

import (
	"time"
	"encoding/json"
	"github.com/julienschmidt/httprouter"
	"net/http"
	"log"
	"os"
	//"io"
	"fmt"
	"database/sql"
	_ "github.com/lib/pq"
	"gopkg.in/antage/eventsource.v1"
)

var conn *sql.DB
var es eventsource.EventSource

func SetHeaders(w *http.ResponseWriter) {
	(*w).Header().Set("Access-Control-Allow-Origin", "*")
	(*w).Header().Set("Content-Type", "application/json")
}

func GetBlog(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT * FROM blog")
	data := []BlogPost{}
	for rows.Next() {
		post := BlogPost{}
		rows.Scan(&post.Id, &post.Titel, &post.Text, &post.Auteur, &post.Img_url, &post.Ctime, &post.Image)
		data = append(data, post)
	}
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func GetPost(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	row := conn.QueryRow("SELECT * FROM blog WHERE id = $1 LIMIT 1", ps.ByName("id"))
	data := BlogPost{}
	row.Scan(&data.Id, &data.Titel, &data.Text, &data.Auteur, &data.Img_url, &data.Ctime, &data.Image)
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func GetLatestSpinData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT * FROM spindata ORDER BY tijd DESC LIMIT 1")
	spin := SpinData{}
	rows.Next()
	rows.Scan(&spin.Id, &spin.Tijd, &spin.Mode, &spin.Hellingsgraad, &spin.Snelheid, &spin.Batterij, &spin.BallonCount)
	buf,_ := json.Marshal(spin)
	SetHeaders(&w)
	w.Write(buf)
}

func GetLatestSpinBatterij(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	row := conn.QueryRow("SELECT batterij FROM spindata ORDER BY tijd DESC LIMIT 1")
	var data int
	row.Scan(&data)
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func GetLatestSpinMode(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	row := conn.QueryRow("SELECT mode FROM spindata ORDER BY tijd DESC LIMIT 1")
	var data string
	row.Scan(&data)
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func GetArchivedSpinData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT * FROM spindata")
	data := []SpinData{}
	for rows.Next() {
		spin := SpinData{}
		rows.Scan(&spin.Id, &spin.Tijd, &spin.Mode, &spin.Hellingsgraad, &spin.Snelheid, &spin.Batterij, &spin.BallonCount)
		data = append(data, spin)
	}
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func GetArchivedSpinBatterij(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT batterij FROM spindata")
	data := make([]int, 0)
	var scanInt int
	for rows.Next() {
		rows.Scan(&scanInt)
		data = append(data, scanInt)
	}
	buf,_ := json.Marshal(data)
	fmt.Printf(string(buf))
	SetHeaders(&w)
	w.Write(buf)
}

func GetArchivedSpinMode(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT mode FROM spindata")
	data := make([]string, 0)
	var scanStr string
	for rows.Next() {
		rows.Scan(&scanStr)
		data = append(data, scanStr)
	}
	buf,_ := json.Marshal(data)
	fmt.Printf(string(buf))
	SetHeaders(&w)
	w.Write(buf)
}

func GetLatestServoData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	row := conn.QueryRow("SELECT * FROM servodata ORDER BY tijd DESC LIMIT 1")
	servo := ServoData{}
	row.Scan(&servo.Id, &servo.ServoId, &servo.Tijd, &servo.Voltage, &servo.Positie, &servo.Load, &servo.Temperatuur)
	buf,_ := json.Marshal(servo)
	SetHeaders(&w)
	w.Write(buf)
}

func GetArchivedServoData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT * FROM servodata")
	data := []ServoData{}
	for rows.Next() {
		servo := ServoData{}
		rows.Scan(&servo.Id, &servo.ServoId, &servo.Tijd, &servo.Voltage, &servo.Positie, &servo.Load, &servo.Temperatuur)
		data = append(data, servo)
	}
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func GetLogs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT * FROM logs")
	data := []LogData{}
	for rows.Next() {
		log := LogData{}
		rows.Scan(&log.Id, &log.Log)
		data = append(data, log)
	}
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func Test(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	buf,_ := json.Marshal("test")
	SetHeaders(&w)
	w.Write(buf)
}

func PostBlog(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	//r.ParseMultipartForm(32 << 20)
	/*file, handler, err := r.FormFile("uploadfile")
	defer file.Close()
	if err == nil {
		fmt.Fprintf(w, "%v", handler.Header)
		f, err := os.OpenFile("./img/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			w.WriteHeader(500)
			return
		}
		defer f.Close()
		io.Copy(f, file)
	}

	err = nil*/

	//_,err := conn.Query("INSERT INTO blog (titel, text, auteur, ctime, image) VALUES ($1, $2, $3, $4, $5)", r.FormValue("titel"), r.FormValue("text"), r.FormValue("auteur"), time.Now(), "http://idp-api.herokuapp.com/img/"+handler.Filename)
	_,err := conn.Query("INSERT INTO blog (titel, text, auteur, ctime) VALUES ($1, $2, $3, $4)", r.FormValue("onderwerp"), r.FormValue("bericht"), r.FormValue("naam"), time.Now())
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte(err.Error()))
		return
	}
	w.Header().Set("Content-Type", "text/html")
	w.WriteHeader(201)
	w.Write([]byte("<meta http-equiv=\"refresh\" content=\"1; url=http://knightspider.herokuapp.com/#/blog\">successful"))
}

func PostSpinData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	_,err := conn.Query("INSERT INTO spindata (tijd, mode, hellingsgraad, snelheid, batterij, balloncount) VALUES ($1, $2, $3, $4, $5, $6)", time.Now(),
		r.FormValue("mode"), r.FormValue("hellingsgraad"), r.FormValue("snelheid"), r.FormValue("batterij"), r.FormValue("ballonCount"))
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte(err.Code.Name()))
		return
	}
	w.WriteHeader(201)
	w.Write([]byte("successful"))
}

func PostServoData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	_,err := conn.Query("INSERT INTO servodata (servo_id, tijd, voltage, positie, load, temperatuur) VALUES ($1, $2, $3, $4, $5, $6)",
		r.FormValue("servo_id"), time.Now(), r.FormValue("voltage"), r.FormValue("positie"), r.FormValue("load"), r.FormValue("Temperatuur"))
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte(err.Error()))
		return
	}
	w.WriteHeader(201)
	w.Write([]byte("successful"))
}

func PostLog(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	_,err := conn.Query("INSERT INTO logs (log) VALUES ($1)",
		r.FormValue("log"))
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte(err.Error()))
		return
	}
	es.SendEventMessage(r.FormValue("log"), "log", "")
	w.WriteHeader(201)
	w.Write([]byte(r.FormValue("log")))
}

func Head(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	SetHeaders(&w)
	w.WriteHeader(204)
}

func main() {
	conn,_ = sql.Open("postgres", os.Getenv("DATABASE_URL"))
	defer conn.Close()

	es = eventsource.New(
		&eventsource.Settings{
			Timeout: 5 * time.Second,
			CloseOnTimeout: false,
			IdleTimeout: 30 * time.Minute,
		},
		func(req *http.Request) [][]byte {
			return [][]byte{
				[]byte("X-Accel-Buffering: no"),
				[]byte("Access-Control-Allow-Origin: *"),
			}
		},
	)
	defer es.Close()

	router := httprouter.New()
	router.HEAD("/*path", Head)
	router.GET("/test", Test)
	router.GET("/blog", GetBlog)
	router.GET("/blog/:id", GetPost)
	router.GET("/spin/latest", GetLatestSpinData)
	router.GET("/spin/latest/batterij", GetLatestSpinBatterij)
	router.GET("/spin/latest/mode", GetLatestSpinMode)
	router.GET("/spin/archive", GetArchivedSpinData)
	router.GET("/spin/archive/batterij", GetArchivedSpinBatterij)
	router.GET("/spin/archive/mode", GetArchivedSpinMode)
	router.GET("/servo/latest", GetLatestServoData)
	router.GET("/servo/archive", GetArchivedServoData)
	router.GET("/log", GetLogs)
	router.POST("/blog", PostBlog)
	router.POST("/spin", PostSpinData)
	router.POST("/servo", PostServoData)
	router.POST("/log", PostLog)

	http.Handle("/subscribe", es)
	http.Handle("/", router)

	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}
	fmt.Printf("Starting server at localhost:%s...", port)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}<commit_msg>less debug data<commit_after>package main

import (
	"time"
	"encoding/json"
	"github.com/julienschmidt/httprouter"
	"net/http"
	"log"
	"os"
	//"io"
	"fmt"
	"database/sql"
	_ "github.com/lib/pq"
	"gopkg.in/antage/eventsource.v1"
)

var conn *sql.DB
var es eventsource.EventSource

func SetHeaders(w *http.ResponseWriter) {
	(*w).Header().Set("Access-Control-Allow-Origin", "*")
	(*w).Header().Set("Content-Type", "application/json")
}

func GetBlog(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT * FROM blog")
	data := []BlogPost{}
	for rows.Next() {
		post := BlogPost{}
		rows.Scan(&post.Id, &post.Titel, &post.Text, &post.Auteur, &post.Img_url, &post.Ctime, &post.Image)
		data = append(data, post)
	}
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func GetPost(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	row := conn.QueryRow("SELECT * FROM blog WHERE id = $1 LIMIT 1", ps.ByName("id"))
	data := BlogPost{}
	row.Scan(&data.Id, &data.Titel, &data.Text, &data.Auteur, &data.Img_url, &data.Ctime, &data.Image)
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func GetLatestSpinData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT * FROM spindata ORDER BY tijd DESC LIMIT 1")
	spin := SpinData{}
	rows.Next()
	rows.Scan(&spin.Id, &spin.Tijd, &spin.Mode, &spin.Hellingsgraad, &spin.Snelheid, &spin.Batterij, &spin.BallonCount)
	buf,_ := json.Marshal(spin)
	SetHeaders(&w)
	w.Write(buf)
}

func GetLatestSpinBatterij(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	row := conn.QueryRow("SELECT batterij FROM spindata ORDER BY tijd DESC LIMIT 1")
	var data int
	row.Scan(&data)
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func GetLatestSpinMode(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	row := conn.QueryRow("SELECT mode FROM spindata ORDER BY tijd DESC LIMIT 1")
	var data string
	row.Scan(&data)
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func GetArchivedSpinData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT * FROM spindata")
	data := []SpinData{}
	for rows.Next() {
		spin := SpinData{}
		rows.Scan(&spin.Id, &spin.Tijd, &spin.Mode, &spin.Hellingsgraad, &spin.Snelheid, &spin.Batterij, &spin.BallonCount)
		data = append(data, spin)
	}
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func GetArchivedSpinBatterij(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT batterij FROM spindata")
	data := make([]int, 0)
	var scanInt int
	for rows.Next() {
		rows.Scan(&scanInt)
		data = append(data, scanInt)
	}
	buf,_ := json.Marshal(data)
	fmt.Printf(string(buf))
	SetHeaders(&w)
	w.Write(buf)
}

func GetArchivedSpinMode(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT mode FROM spindata")
	data := make([]string, 0)
	var scanStr string
	for rows.Next() {
		rows.Scan(&scanStr)
		data = append(data, scanStr)
	}
	buf,_ := json.Marshal(data)
	fmt.Printf(string(buf))
	SetHeaders(&w)
	w.Write(buf)
}

func GetLatestServoData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	row := conn.QueryRow("SELECT * FROM servodata ORDER BY tijd DESC LIMIT 1")
	servo := ServoData{}
	row.Scan(&servo.Id, &servo.ServoId, &servo.Tijd, &servo.Voltage, &servo.Positie, &servo.Load, &servo.Temperatuur)
	buf,_ := json.Marshal(servo)
	SetHeaders(&w)
	w.Write(buf)
}

func GetArchivedServoData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT * FROM servodata")
	data := []ServoData{}
	for rows.Next() {
		servo := ServoData{}
		rows.Scan(&servo.Id, &servo.ServoId, &servo.Tijd, &servo.Voltage, &servo.Positie, &servo.Load, &servo.Temperatuur)
		data = append(data, servo)
	}
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func GetLogs(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	rows,_ := conn.Query("SELECT * FROM logs")
	data := []LogData{}
	for rows.Next() {
		log := LogData{}
		rows.Scan(&log.Id, &log.Log)
		data = append(data, log)
	}
	buf,_ := json.Marshal(data)
	SetHeaders(&w)
	w.Write(buf)
}

func Test(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	buf,_ := json.Marshal("test")
	SetHeaders(&w)
	w.Write(buf)
}

func PostBlog(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	//r.ParseMultipartForm(32 << 20)
	/*file, handler, err := r.FormFile("uploadfile")
	defer file.Close()
	if err == nil {
		fmt.Fprintf(w, "%v", handler.Header)
		f, err := os.OpenFile("./img/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			w.WriteHeader(500)
			return
		}
		defer f.Close()
		io.Copy(f, file)
	}

	err = nil*/

	//_,err := conn.Query("INSERT INTO blog (titel, text, auteur, ctime, image) VALUES ($1, $2, $3, $4, $5)", r.FormValue("titel"), r.FormValue("text"), r.FormValue("auteur"), time.Now(), "http://idp-api.herokuapp.com/img/"+handler.Filename)
	_,err := conn.Query("INSERT INTO blog (titel, text, auteur, ctime) VALUES ($1, $2, $3, $4)", r.FormValue("onderwerp"), r.FormValue("bericht"), r.FormValue("naam"), time.Now())
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte(err.Error()))
		return
	}
	w.Header().Set("Content-Type", "text/html")
	w.WriteHeader(201)
	w.Write([]byte("<meta http-equiv=\"refresh\" content=\"1; url=http://knightspider.herokuapp.com/#/blog\">successful"))
}

func PostSpinData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	_,err := conn.Query("INSERT INTO spindata (tijd, mode, hellingsgraad, snelheid, batterij, balloncount) VALUES ($1, $2, $3, $4, $5, $6)", time.Now(),
		r.FormValue("mode"), r.FormValue("hellingsgraad"), r.FormValue("snelheid"), r.FormValue("batterij"), r.FormValue("ballonCount"))
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte(err.Error()))
		return
	}
	w.WriteHeader(201)
	w.Write([]byte("successful"))
}

func PostServoData(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	_,err := conn.Query("INSERT INTO servodata (servo_id, tijd, voltage, positie, load, temperatuur) VALUES ($1, $2, $3, $4, $5, $6)",
		r.FormValue("servo_id"), time.Now(), r.FormValue("voltage"), r.FormValue("positie"), r.FormValue("load"), r.FormValue("Temperatuur"))
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte(err.Error()))
		return
	}
	w.WriteHeader(201)
	w.Write([]byte("successful"))
}

func PostLog(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	_,err := conn.Query("INSERT INTO logs (log) VALUES ($1)",
		r.FormValue("log"))
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte(err.Error()))
		return
	}
	es.SendEventMessage(r.FormValue("log"), "log", "")
	w.WriteHeader(201)
	w.Write([]byte(r.FormValue("log")))
}

func Head(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	SetHeaders(&w)
	w.WriteHeader(204)
}

func main() {
	conn,_ = sql.Open("postgres", os.Getenv("DATABASE_URL"))
	defer conn.Close()

	es = eventsource.New(
		&eventsource.Settings{
			Timeout: 5 * time.Second,
			CloseOnTimeout: false,
			IdleTimeout: 30 * time.Minute,
		},
		func(req *http.Request) [][]byte {
			return [][]byte{
				[]byte("X-Accel-Buffering: no"),
				[]byte("Access-Control-Allow-Origin: *"),
			}
		},
	)
	defer es.Close()

	router := httprouter.New()
	router.HEAD("/*path", Head)
	router.GET("/test", Test)
	router.GET("/blog", GetBlog)
	router.GET("/blog/:id", GetPost)
	router.GET("/spin/latest", GetLatestSpinData)
	router.GET("/spin/latest/batterij", GetLatestSpinBatterij)
	router.GET("/spin/latest/mode", GetLatestSpinMode)
	router.GET("/spin/archive", GetArchivedSpinData)
	router.GET("/spin/archive/batterij", GetArchivedSpinBatterij)
	router.GET("/spin/archive/mode", GetArchivedSpinMode)
	router.GET("/servo/latest", GetLatestServoData)
	router.GET("/servo/archive", GetArchivedServoData)
	router.GET("/log", GetLogs)
	router.POST("/blog", PostBlog)
	router.POST("/spin", PostSpinData)
	router.POST("/servo", PostServoData)
	router.POST("/log", PostLog)

	http.Handle("/subscribe", es)
	http.Handle("/", router)

	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}
	fmt.Printf("Starting server at localhost:%s...", port)
	log.Fatal(http.ListenAndServe(":"+port, nil))
}<|endoftext|>


<commit_before>package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/davecgh/go-spew/spew"
	"github.com/leanovate/microtools/logging"
	homedir "github.com/mitchellh/go-homedir"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"github.com/untoldwind/amintk/gtk"
	"github.com/untoldwind/trustless-gtk3/state"
	"github.com/untoldwind/trustless-gtk3/ui"
	"github.com/untoldwind/trustless/config"
	"github.com/untoldwind/trustless/daemon"
	"github.com/untoldwind/trustless/secrets"
	"github.com/untoldwind/trustless/secrets/pgp"
	"github.com/untoldwind/trustless/secrets/remote"
)

var rootCommand = &cobra.Command{
	Use:   "Trustless GTK3",
	Short: "GTK3 frontend of trustless",
	Run:   run,
}

var cmdSettings config.Settings
var cfgFile string
var startDaemon bool

func showError(err error) {
	fmt.Fprintf(os.Stderr, "ERROR: %s\n", err.Error())

	if cmdSettings.Debug {
		fmt.Fprintln(os.Stderr)
		spew.Fdump(os.Stderr, err)
	}
	os.Exit(1)
}

func init() {
	cobra.OnInitialize(initConfig)

	rootCommand.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default ./trustless.toml, $HOME/.trustless/trustless.toml")
	rootCommand.PersistentFlags().String("node-id", "", "ID of this node")
	rootCommand.PersistentFlags().String("store-url", "", "URL of the store to open (only file:// URLs are supported)")
	rootCommand.PersistentFlags().String("store-scheme", "openpgp", "Storage scheme (openpgp, openpgp+scrypt)")
	rootCommand.PersistentFlags().String("log-file", "", "Log to file instead stdout")
	rootCommand.PersistentFlags().String("log-format", "text", "Log format to use (test, json, logstash)")
	rootCommand.PersistentFlags().Bool("debug", false, "Enable debug information")
	rootCommand.PersistentFlags().Duration("unlock-timeout", 5*time.Minute, "AUtomatic lock timeout")
	rootCommand.PersistentFlags().Bool("unlock-timeout-hard", false, "Enable hard timeout")
	rootCommand.PersistentFlags().BoolVar(&startDaemon, "daemon", false, "Start daemon")

	viper.BindPFlags(rootCommand.PersistentFlags())
}

func initConfig() {
	viper.SetEnvPrefix("TRUSTLESS")
	viper.AutomaticEnv()

	if err := viper.Unmarshal(&cmdSettings); err != nil {

		showError(err)
	}

	if cmdSettings.Debug {
		fmt.Fprintln(os.Stderr, "---- Settings [snip]----")
		spew.Fdump(os.Stderr, cmdSettings)
		fmt.Fprintln(os.Stderr, "---- Settings [snap] ----")
	}

}

func createLogger() logging.Logger {
	loggingOptions := logging.Options{
		Backend:   "logrus",
		LogFile:   cmdSettings.LogFile,
		LogFormat: cmdSettings.LogFormat,
		Level:     logging.Info,
	}
	if cmdSettings.Debug {
		loggingOptions.Level = logging.Debug
	}
	return logging.NewLogrusLogger(loggingOptions).
		WithContext(map[string]interface{}{"process": "trustless-gtk3"})
}

func readConfig() (*config.Settings, error) {
	var settings config.Settings

	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	} else {
		home, err := homedir.Dir()
		if err != nil {
			showError(err)
		}
		viper.AddConfigPath(".")
		viper.AddConfigPath(home)
		viper.AddConfigPath(filepath.Join(home, ".config"))
		viper.SetConfigName("trustless")
	}

	if err := viper.ReadInConfig(); err != nil {
		if err := writeDefaultConfig(); err != nil {
			return nil, err
		}
	}

	if err := viper.Unmarshal(&settings); err != nil {
		return nil, err
	}

	if settings.Debug {
		fmt.Fprintln(os.Stderr, "---- Settings [snip]----")
		spew.Fdump(os.Stderr, settings)
		fmt.Fprintln(os.Stderr, "---- Settings [snap] ----")
	}

	return &settings, nil
}

func writeDefaultConfig() error {
	if viper.GetString("store-url") == "" {
		viper.Set("store-url", config.DefaultStoreURL())
	}
	if viper.GetString("node-id") == "" {
		nodeId, err := config.GenerateNodeID()
		if err != nil {
			return err
		}
		viper.Set("node-id", nodeId)
	}
	home, err := homedir.Dir()
	if err != nil {
		showError(err)
	}
	os.MkdirAll(filepath.Join(home, ".config"), 0700)

	return viper.WriteConfigAs(filepath.Join(home, ".config", "trustless.toml"))
}

func run(cmd *cobra.Command, args []string) {
	gtk.Init(nil)

	logger := createLogger()
	var secrets secrets.Secrets

	if remote.RemoteAvailable(logger) {
		logger.Info("Use remote store")
		secrets = remote.NewRemoteSecrets(logger)
	} else {
		logger.Info("Starting own daemon")
		settings, err := readConfig()
		if err != nil {
			showError(err)
		}
		scrypted := false
		switch settings.StoreScheme {
		case "openpgp+scrypt":
			scrypted = true
		}

		secrets, err = pgp.NewPGPSecrets(settings.StoreURL, scrypted, settings.NodeID, 4096, settings.UnlockTimeout, settings.UnlockTimeoutHard, logger)
		if err != nil {
			showError(err)
		}
		defer secrets.Lock(context.Background())

		if startDaemon {
			daemon := daemon.NewDaemon(secrets, logger)

			if err := daemon.Start(); err != nil {
				showError(err)
			}
			defer daemon.Stop()
		}
	}

	store, err := state.NewStore(secrets, logger)
	if err != nil {
		logger.ErrorErr(err)
		showError(err)
	}

	window, err := ui.NewMainWindow(store, logger)
	if err != nil {
		logger.ErrorErr(err)
		showError(err)
	}
	window.ShowAll()

	gtk.Main()
}

func main() {
	if err := rootCommand.Execute(); err != nil {
		showError(err)
	}
}
<commit_msg>Fix start by explorer<commit_after>package main

import (
	"context"
	"fmt"
	"os"
	"path/filepath"
	"time"

	"github.com/davecgh/go-spew/spew"
	"github.com/leanovate/microtools/logging"
	homedir "github.com/mitchellh/go-homedir"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"github.com/untoldwind/amintk/gtk"
	"github.com/untoldwind/trustless-gtk3/state"
	"github.com/untoldwind/trustless-gtk3/ui"
	"github.com/untoldwind/trustless/config"
	"github.com/untoldwind/trustless/daemon"
	"github.com/untoldwind/trustless/secrets"
	"github.com/untoldwind/trustless/secrets/pgp"
	"github.com/untoldwind/trustless/secrets/remote"
)

var rootCommand = &cobra.Command{
	Use:   "Trustless GTK3",
	Short: "GTK3 frontend of trustless",
	Run:   run,
}

var cmdSettings config.Settings
var cfgFile string
var startDaemon bool

func showError(err error) {
	fmt.Fprintf(os.Stderr, "ERROR: %s\n", err.Error())

	if cmdSettings.Debug {
		fmt.Fprintln(os.Stderr)
		spew.Fdump(os.Stderr, err)
	}
	os.Exit(1)
}

func init() {
	cobra.MousetrapHelpText = ""
	cobra.OnInitialize(initConfig)

	rootCommand.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default ./trustless.toml, $HOME/.trustless/trustless.toml")
	rootCommand.PersistentFlags().String("node-id", "", "ID of this node")
	rootCommand.PersistentFlags().String("store-url", "", "URL of the store to open (only file:// URLs are supported)")
	rootCommand.PersistentFlags().String("store-scheme", "openpgp", "Storage scheme (openpgp, openpgp+scrypt)")
	rootCommand.PersistentFlags().String("log-file", "", "Log to file instead stdout")
	rootCommand.PersistentFlags().String("log-format", "text", "Log format to use (test, json, logstash)")
	rootCommand.PersistentFlags().Bool("debug", false, "Enable debug information")
	rootCommand.PersistentFlags().Duration("unlock-timeout", 5*time.Minute, "AUtomatic lock timeout")
	rootCommand.PersistentFlags().Bool("unlock-timeout-hard", false, "Enable hard timeout")
	rootCommand.PersistentFlags().BoolVar(&startDaemon, "daemon", false, "Start daemon")

	viper.BindPFlags(rootCommand.PersistentFlags())
}

func initConfig() {
	viper.SetEnvPrefix("TRUSTLESS")
	viper.AutomaticEnv()

	if err := viper.Unmarshal(&cmdSettings); err != nil {

		showError(err)
	}

	if cmdSettings.Debug {
		fmt.Fprintln(os.Stderr, "---- Settings [snip]----")
		spew.Fdump(os.Stderr, cmdSettings)
		fmt.Fprintln(os.Stderr, "---- Settings [snap] ----")
	}

}

func createLogger() logging.Logger {
	loggingOptions := logging.Options{
		Backend:   "logrus",
		LogFile:   cmdSettings.LogFile,
		LogFormat: cmdSettings.LogFormat,
		Level:     logging.Info,
	}
	if cmdSettings.Debug {
		loggingOptions.Level = logging.Debug
	}
	return logging.NewLogrusLogger(loggingOptions).
		WithContext(map[string]interface{}{"process": "trustless-gtk3"})
}

func readConfig() (*config.Settings, error) {
	var settings config.Settings

	if cfgFile != "" {
		viper.SetConfigFile(cfgFile)
	} else {
		home, err := homedir.Dir()
		if err != nil {
			showError(err)
		}
		viper.AddConfigPath(".")
		viper.AddConfigPath(home)
		viper.AddConfigPath(filepath.Join(home, ".config"))
		viper.SetConfigName("trustless")
	}

	if err := viper.ReadInConfig(); err != nil {
		if err := writeDefaultConfig(); err != nil {
			return nil, err
		}
	}

	if err := viper.Unmarshal(&settings); err != nil {
		return nil, err
	}

	if settings.Debug {
		fmt.Fprintln(os.Stderr, "---- Settings [snip]----")
		spew.Fdump(os.Stderr, settings)
		fmt.Fprintln(os.Stderr, "---- Settings [snap] ----")
	}

	return &settings, nil
}

func writeDefaultConfig() error {
	if viper.GetString("store-url") == "" {
		viper.Set("store-url", config.DefaultStoreURL())
	}
	if viper.GetString("node-id") == "" {
		nodeId, err := config.GenerateNodeID()
		if err != nil {
			return err
		}
		viper.Set("node-id", nodeId)
	}
	home, err := homedir.Dir()
	if err != nil {
		showError(err)
	}
	os.MkdirAll(filepath.Join(home, ".config"), 0700)

	return viper.WriteConfigAs(filepath.Join(home, ".config", "trustless.toml"))
}

func run(cmd *cobra.Command, args []string) {
	gtk.Init(nil)

	logger := createLogger()
	var secrets secrets.Secrets

	if remote.RemoteAvailable(logger) {
		logger.Info("Use remote store")
		secrets = remote.NewRemoteSecrets(logger)
	} else {
		logger.Info("Starting own daemon")
		settings, err := readConfig()
		if err != nil {
			showError(err)
		}
		scrypted := false
		switch settings.StoreScheme {
		case "openpgp+scrypt":
			scrypted = true
		}

		secrets, err = pgp.NewPGPSecrets(settings.StoreURL, scrypted, settings.NodeID, 4096, settings.UnlockTimeout, settings.UnlockTimeoutHard, logger)
		if err != nil {
			showError(err)
		}
		defer secrets.Lock(context.Background())

		if startDaemon {
			daemon := daemon.NewDaemon(secrets, logger)

			if err := daemon.Start(); err != nil {
				showError(err)
			}
			defer daemon.Stop()
		}
	}

	store, err := state.NewStore(secrets, logger)
	if err != nil {
		logger.ErrorErr(err)
		showError(err)
	}

	window, err := ui.NewMainWindow(store, logger)
	if err != nil {
		logger.ErrorErr(err)
		showError(err)
	}
	window.ShowAll()

	gtk.Main()
}

func main() {
	if err := rootCommand.Execute(); err != nil {
		showError(err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"net/http"
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/codegangsta/negroni"
	"github.com/meatballhat/negroni-logrus"
	"gopkg.in/unrolled/render.v1"

	"github.com/alphagov/metadata-api/content_api"
)

var (
	bearerToken = getEnvDefault("BEARER_TOKEN", "foo")
	contentAPI  = getEnvDefault("CONTENT_API", "content-api")
	port        = getEnvDefault("PORT", "3000")

	renderer = render.New(render.Options{})
)

func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
	renderer.JSON(w, http.StatusOK, map[string]string{"status": "OK"})
}

func InfoHandler(contentAPI, bearerToken string) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		slug := r.URL.Path[len("/info"):]

		if len(slug) <= 1 || slug == "/" {
			renderError(w, http.StatusNotFound, "not found")
			return
		}

		artefact, err := content_api.FetchArtefact(contentAPI, bearerToken, slug)
		if err != nil {
			renderError(w, http.StatusInternalServerError, err.Error())
			return
		}

		metadata := &Metadata{
			Artefact:     artefact,
			ResponseInfo: &ResponseInfo{Status: "ok"},
		}

		renderer.JSON(w, http.StatusOK, metadata)
	}
}

func main() {
	httpMux := http.NewServeMux()
	httpMux.HandleFunc("/healthcheck", HealthCheckHandler)
	httpMux.HandleFunc("/info", InfoHandler(contentAPI, bearerToken))

	middleware := negroni.New()
	middleware.Use(negronilogrus.NewCustomMiddleware(
		logrus.InfoLevel, &logrus.JSONFormatter{}, "metadata-api"))
	middleware.UseHandler(httpMux)

	middleware.Run(":" + port)
}

func renderError(w http.ResponseWriter, status int, errorString string) {
	renderer.JSON(w, status, &Metadata{ResponseInfo: &ResponseInfo{Status: errorString}})
}

func getEnvDefault(key string, defaultVal string) string {
	val := os.Getenv(key)
	if val == "" {
		return defaultVal
	}

	return val
}
<commit_msg>Use `HTTP_PORT` to be specific what the ENV variable is doing<commit_after>package main

import (
	"net/http"
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/codegangsta/negroni"
	"github.com/meatballhat/negroni-logrus"
	"gopkg.in/unrolled/render.v1"

	"github.com/alphagov/metadata-api/content_api"
)

var (
	bearerToken = getEnvDefault("BEARER_TOKEN", "foo")
	contentAPI  = getEnvDefault("CONTENT_API", "content-api")
	port        = getEnvDefault("HTTP_PORT", "3000")

	renderer = render.New(render.Options{})
)

func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
	renderer.JSON(w, http.StatusOK, map[string]string{"status": "OK"})
}

func InfoHandler(contentAPI, bearerToken string) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		slug := r.URL.Path[len("/info"):]

		if len(slug) <= 1 || slug == "/" {
			renderError(w, http.StatusNotFound, "not found")
			return
		}

		artefact, err := content_api.FetchArtefact(contentAPI, bearerToken, slug)
		if err != nil {
			renderError(w, http.StatusInternalServerError, err.Error())
			return
		}

		metadata := &Metadata{
			Artefact:     artefact,
			ResponseInfo: &ResponseInfo{Status: "ok"},
		}

		renderer.JSON(w, http.StatusOK, metadata)
	}
}

func main() {
	httpMux := http.NewServeMux()
	httpMux.HandleFunc("/healthcheck", HealthCheckHandler)
	httpMux.HandleFunc("/info", InfoHandler(contentAPI, bearerToken))

	middleware := negroni.New()
	middleware.Use(negronilogrus.NewCustomMiddleware(
		logrus.InfoLevel, &logrus.JSONFormatter{}, "metadata-api"))
	middleware.UseHandler(httpMux)

	middleware.Run(":" + port)
}

func renderError(w http.ResponseWriter, status int, errorString string) {
	renderer.JSON(w, status, &Metadata{ResponseInfo: &ResponseInfo{Status: errorString}})
}

func getEnvDefault(key string, defaultVal string) string {
	val := os.Getenv(key)
	if val == "" {
		return defaultVal
	}

	return val
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"fmt"
	"sort"
)

func main() {

	items := create(
		"items",
		[]string{"item_id", "item_name", "type_id", "price"},
	)
	items.insert(1, "apple", 1, 300)
	items.insert(2, "orange", 1, 130)
	items.insert(3, "cabbage", 2, 200)
	items.insert(4, "saury", 3, 220)
	items.insert(5, "seaweed", nil, 250)
	items.insert(6, "mushroom", 4, 180)

	types := create(
		"types",
		[]string{"type_id", "type_name"},
	)
	types.insert(1, "fruit")
	types.insert(2, "vegetable")
	types.insert(3, "fish")

	fmt.Println(items)
	fmt.Println(from("items"))
	fmt.Println(from("items").selectQ("item_name", "price"))
	fmt.Println(from("items").lessThan("price", 250))
	fmt.Println(from("items").leftJoin("types", "type_id"))
	fmt.Println(
		from(
			from("items").lessThan("price", 250),
		).leftJoin(
			from("types").lessThan("type_id", 3), "type_id",
		),
	)
}

var tables = map[string]*table{}

type column struct {
	parent string
	name   string
}

func newColumn(parent string, name string) *column {
	return &column{parent: parent, name: name}
}

type tuple struct {
	values []interface{}
}

func newTuple(vals []interface{}) *tuple {
	return &tuple{values: vals}
}

type relation struct {
	columns []*column
	tuples  []*tuple
}

func newRelation(cols []*column, tups []*tuple) *relation {
	return &relation{columns: cols, tuples: tups}
}

// TODO: rewrite by interfaces
//       this implementation is to use immediate string values as arguments
func from(x interface{}) *relation {
	if r, ok := x.(*relation); ok {
		return r
	}
	tblName := fmt.Sprint(x)
	t := tables[tblName]
	cols := []*column{}
	for _, c := range t.columns {
		cols = append(cols, newColumn(tblName, c.name))
	}
	return newRelation(cols, t.tuples)
}

func (r *relation) findColumn(name string) int {
	for i, c := range r.columns {
		if c.name == name {
			return i
		}
	}
	// we can simplify checking the existence of n in r,
	// by r.findColumn(n) <= len(r.columns) before random accesses
	return len(r.columns)
}

func (r *relation) selectQ(colNames ...string) *relation {
	idxs := []int{}
	newCols := []*column{}
	for _, cn := range colNames {
		idx := r.findColumn(cn)
		idxs = append(idxs, idx)
		if idx < len(r.columns) {
			newCols = append(newCols, r.columns[idx])
		}
	}
	newTups := []*tuple{}
	for _, tup := range r.tuples {
		vals := []interface{}{}
		for _, idx := range idxs {
			// TODO: Can I avoid to refer the nil pointer?
			if idx < len(tup.values) {
				vals = append(vals, tup.values[idx])
			} else {
				vals = append(vals, nil)
			}
		}
		newTups = append(newTups, newTuple(vals))
	}
	return newRelation(newCols, newTups)
}

func (r *relation) leftJoin(x interface{}, colName string) *relation {
	j := from(x)
	newCols := []*column{}
	newCols = append(newCols, r.columns...)
	newCols = append(newCols, j.columns...)
	rIdx := r.findColumn(colName)
	if len(r.columns) <= rIdx {
		return newRelation(newCols, []*tuple{})
	}
	newTups := []*tuple{}
	for _, rTup := range r.tuples {
		keyVal := rTup.values[rIdx]
		jRel := j.equal(colName, keyVal)
		if len(jRel.tuples) == 0 {
			vals := []interface{}{}
			vals = append(vals, rTup.values...)
			for len(vals) < len(newCols) {
				vals = append(vals, nil)
			}
			newTups = append(newTups, newTuple(vals))
		}
		for _, jTup := range jRel.tuples {
			vals := []interface{}{}
			vals = append(vals, rTup.values...)
			vals = append(vals, jTup.values...)
			newTups = append(newTups, newTuple(vals))
		}
	}
	return newRelation(newCols, newTups)
}

func (r *relation) lessThan(colName string, n int) *relation {
	idx := r.findColumn(colName)
	if idx >= len(r.columns) {
		return newRelation(r.columns, []*tuple{})
	}
	newTups := []*tuple{}
	for _, tup := range r.tuples {
		v, ok := tup.values[idx].(int)
		if ok && v < n {
			newTups = append(newTups, tup)
		}
	}
	return newRelation(r.columns, newTups)
}

func (r *relation) equal(colName string, key interface{}) *relation {
	// null check should be by isNull condition
	if key == nil {
		return newRelation(r.columns, []*tuple{})
	}
	idx := r.findColumn(colName)
	if idx >= len(r.columns) {
		return newRelation(r.columns, []*tuple{})
	}
	newTups := []*tuple{}
	for _, tup := range r.tuples {
		if tup.values[idx] == key {
			newTups = append(newTups, tup)
		}
	}
	return newRelation(r.columns, newTups)
}

type tupleSorter struct {
	tuples  []*tuple
	compare func(t1, t2 *tuple) bool
}

func (ts *tupleSorter) Len() int {
	return len(ts.tuples)
}

func (ts *tupleSorter) Swap(i, j int) {
	ts.tuples[i], ts.tuples[j] = ts.tuples[j], ts.tuples[i]
}

func (ts *tupleSorter) Less(i, j int) bool {
	return ts.compare(ts.tuples[i], ts.tuples[j])
}

func (r *relation) orderBy(colName string) *relation {
	idx := r.findColumn(colName)
	if idx >= len(r.columns) {
		return r
	}
	compare := func(t1, t2 *tuple) bool {
		n1, ok1 := t1.values[idx].(int)
		n2, ok2 := t2.values[idx].(int)
		if ok1 && ok2 {
			return n1 < n2
		}
		s1, ok1 := t1.values[idx].(string)
		s2, ok2 := t2.values[idx].(string)
		if ok1 && ok2 {
			return s1 < s2
		}
		return true
	}
	newTups := []*tuple{}
	newTups = append(newTups, r.tuples...)
	ts := &tupleSorter{tuples: newTups, compare: compare}
	sort.Sort(ts)
	return newRelation(r.columns, ts.tuples)
}

func (r *relation) String() string {
	var buf bytes.Buffer
	for _, c := range r.columns {
		buf.WriteByte('|')
		if c.parent != "" {
			buf.WriteString(c.parent)
			buf.WriteByte('.')
		}
		buf.WriteString(c.name)
	}
	buf.WriteString("|\n")
	for _, t := range r.tuples {
		for _, v := range t.values {
			buf.WriteByte('|')
			buf.WriteString(fmt.Sprint(v))
		}
		buf.WriteString("|\n")
	}
	return buf.String()
}

type table struct {
	relation
	name string
}

func newTable(name string, cols []*column) *table {
	t := &table{}
	t.name = name
	t.columns = cols
	t.tuples = []*tuple{}
	return t
}

func create(name string, colNames []string) *table {
	cols := []*column{}
	for _, cn := range colNames {
		cols = append(cols, newColumn("", cn))
	}
	t := newTable(name, cols)
	tables[name] = t
	return t
}

func (t *table) insert(vals ...interface{}) *table {
	t.tuples = append(t.tuples, newTuple(vals))
	return t
}
<commit_msg>Create a skeleton for grouping functions<commit_after>package main

import (
	"bytes"
	"fmt"
	"sort"
)

func main() {

	items := create(
		"items",
		[]string{"item_id", "item_name", "type_id", "price"},
	)
	items.insert(1, "apple", 1, 300)
	items.insert(2, "orange", 1, 130)
	items.insert(3, "cabbage", 2, 200)
	items.insert(4, "saury", 3, 220)
	items.insert(5, "seaweed", nil, 250)
	items.insert(6, "mushroom", 4, 180)

	types := create(
		"types",
		[]string{"type_id", "type_name"},
	)
	types.insert(1, "fruit")
	types.insert(2, "vegetable")
	types.insert(3, "fish")

	fmt.Println(items)
	fmt.Println(from("items"))
	fmt.Println(from("items").selectQ("item_name", "price"))
	fmt.Println(from("items").lessThan("price", 250))
	fmt.Println(from("items").leftJoin("types", "type_id"))
	fmt.Println(
		from(
			from("items").lessThan("price", 250),
		).leftJoin(
			from("types").lessThan("type_id", 3), "type_id",
		),
	)
}

var tables = map[string]*table{}

type column struct {
	parent string
	name   string
}

func newColumn(parent string, name string) *column {
	return &column{parent: parent, name: name}
}

type tuple struct {
	values []interface{}
}

func newTuple(vals []interface{}) *tuple {
	return &tuple{values: vals}
}

type relation struct {
	columns []*column
	tuples  []*tuple
}

func newRelation(cols []*column, tups []*tuple) *relation {
	return &relation{columns: cols, tuples: tups}
}

// TODO: rewrite by interfaces
//       this implementation is to use immediate string values as arguments
func from(x interface{}) *relation {
	if r, ok := x.(*relation); ok {
		return r
	}
	tblName := fmt.Sprint(x)
	t := tables[tblName]
	cols := []*column{}
	for _, c := range t.columns {
		cols = append(cols, newColumn(tblName, c.name))
	}
	return newRelation(cols, t.tuples)
}

func (r *relation) findColumn(name string) int {
	for i, c := range r.columns {
		if c.name == name {
			return i
		}
	}
	// we can simplify checking the existence of n in r,
	// by r.findColumn(n) <= len(r.columns) before random accesses
	return len(r.columns)
}

func (r *relation) selectQ(colNames ...string) *relation {
	idxs := []int{}
	newCols := []*column{}
	for _, cn := range colNames {
		idx := r.findColumn(cn)
		idxs = append(idxs, idx)
		if idx < len(r.columns) {
			newCols = append(newCols, r.columns[idx])
		}
	}
	newTups := []*tuple{}
	for _, tup := range r.tuples {
		vals := []interface{}{}
		for _, idx := range idxs {
			// TODO: Can I avoid to refer the nil pointer?
			if idx < len(tup.values) {
				vals = append(vals, tup.values[idx])
			} else {
				vals = append(vals, nil)
			}
		}
		newTups = append(newTups, newTuple(vals))
	}
	return newRelation(newCols, newTups)
}

func (r *relation) leftJoin(x interface{}, colName string) *relation {
	j := from(x)
	newCols := []*column{}
	newCols = append(newCols, r.columns...)
	newCols = append(newCols, j.columns...)
	rIdx := r.findColumn(colName)
	if len(r.columns) <= rIdx {
		return newRelation(newCols, []*tuple{})
	}
	newTups := []*tuple{}
	for _, rTup := range r.tuples {
		keyVal := rTup.values[rIdx]
		jRel := j.equal(colName, keyVal)
		if len(jRel.tuples) == 0 {
			vals := []interface{}{}
			vals = append(vals, rTup.values...)
			for len(vals) < len(newCols) {
				vals = append(vals, nil)
			}
			newTups = append(newTups, newTuple(vals))
		}
		for _, jTup := range jRel.tuples {
			vals := []interface{}{}
			vals = append(vals, rTup.values...)
			vals = append(vals, jTup.values...)
			newTups = append(newTups, newTuple(vals))
		}
	}
	return newRelation(newCols, newTups)
}

func (r *relation) lessThan(colName string, n int) *relation {
	idx := r.findColumn(colName)
	if idx >= len(r.columns) {
		return newRelation(r.columns, []*tuple{})
	}
	newTups := []*tuple{}
	for _, tup := range r.tuples {
		v, ok := tup.values[idx].(int)
		if ok && v < n {
			newTups = append(newTups, tup)
		}
	}
	return newRelation(r.columns, newTups)
}

func (r *relation) equal(colName string, key interface{}) *relation {
	// null check should be by isNull condition
	if key == nil {
		return newRelation(r.columns, []*tuple{})
	}
	idx := r.findColumn(colName)
	if idx >= len(r.columns) {
		return newRelation(r.columns, []*tuple{})
	}
	newTups := []*tuple{}
	for _, tup := range r.tuples {
		if tup.values[idx] == key {
			newTups = append(newTups, tup)
		}
	}
	return newRelation(r.columns, newTups)
}

type tupleSorter struct {
	tuples  []*tuple
	compare func(t1, t2 *tuple) bool
}

func (ts *tupleSorter) Len() int {
	return len(ts.tuples)
}

func (ts *tupleSorter) Swap(i, j int) {
	ts.tuples[i], ts.tuples[j] = ts.tuples[j], ts.tuples[i]
}

func (ts *tupleSorter) Less(i, j int) bool {
	return ts.compare(ts.tuples[i], ts.tuples[j])
}

func (r *relation) orderBy(colName string) *relation {
	idx := r.findColumn(colName)
	if idx >= len(r.columns) {
		return r
	}
	compare := func(t1, t2 *tuple) bool {
		n1, ok1 := t1.values[idx].(int)
		n2, ok2 := t2.values[idx].(int)
		if ok1 && ok2 {
			return n1 < n2
		}
		s1, ok1 := t1.values[idx].(string)
		s2, ok2 := t2.values[idx].(string)
		if ok1 && ok2 {
			return s1 < s2
		}
		return true
	}
	newTups := []*tuple{}
	newTups = append(newTups, r.tuples...)
	ts := &tupleSorter{tuples: newTups, compare: compare}
	sort.Sort(ts)
	return newRelation(r.columns, ts.tuples)
}

type aggregator func([]interface{}) interface{}

func (r *relation) groupBy(colName string, aggs ...aggregator) *relation {
	return nil
}

func (r *relation) String() string {
	var buf bytes.Buffer
	for _, c := range r.columns {
		buf.WriteByte('|')
		if c.parent != "" {
			buf.WriteString(c.parent)
			buf.WriteByte('.')
		}
		buf.WriteString(c.name)
	}
	buf.WriteString("|\n")
	for _, t := range r.tuples {
		for _, v := range t.values {
			buf.WriteByte('|')
			buf.WriteString(fmt.Sprint(v))
		}
		buf.WriteString("|\n")
	}
	return buf.String()
}

type table struct {
	relation
	name string
}

func newTable(name string, cols []*column) *table {
	t := &table{}
	t.name = name
	t.columns = cols
	t.tuples = []*tuple{}
	return t
}

func create(name string, colNames []string) *table {
	cols := []*column{}
	for _, cn := range colNames {
		cols = append(cols, newColumn("", cn))
	}
	t := newTable(name, cols)
	tables[name] = t
	return t
}

func (t *table) insert(vals ...interface{}) *table {
	t.tuples = append(t.tuples, newTuple(vals))
	return t
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strconv"

	"github.com/ogier/pflag"
	"github.com/yuya-takeyama/argf"
)

var (
	name    = "csvp"
	version = "0.8.1"

	flagset         = pflag.NewFlagSet(name, pflag.ContinueOnError)
	indexesList     = flagset.StringP("indexes", "i", "", "")
	headersList     = flagset.StringP("headers", "h", "", "")
	isTSV           = flagset.BoolP("tsv", "t", false, "")
	delimiter       = flagset.StringP("delimiter", "d", ",", "")
	outputDelimiter = flagset.StringP("output-delimiter", "D", "\t", "")
	isHelp          = flagset.BoolP("help", "", false, "")
	isVersion       = flagset.BoolP("version", "", false, "")
)

func printUsage() {
	fmt.Fprintf(os.Stderr, `
Usage: %s [OPTION]... [FILE]...
Print selected parts of CSV from each FILE to standard output.

Options:
  -i, --indexes=LIST
                 select only these indexes
  -h, --headers=LIST
                 select only these headers
  -t, --tsv
                 equivalent to -d'\t'
  -d, --delimiter=DELIM
                 use DELIM instead of comma for field delimiter
  -D, --output-delimiter=STRING
                 use STRING as the output delimiter (default: \t)
  --help
                 display this help text and exit
  --version
                 output version information and exit
`[1:], name)
}

func printVersion() {
	fmt.Fprintln(os.Stderr, version)
}

func printErr(err interface{}) {
	fmt.Fprintf(os.Stderr, "%s: %s\n", name, err)
}

func guideToHelp() {
	fmt.Fprintf(os.Stderr, "Try '%s --help' for more information.\n", name)
}

type Option struct {
	IndexesList     string
	HeadersList     string
	IsTSV           bool
	Delimiter       string
	OutputDelimiter string
	IsHelp          bool
	IsVersion       bool
	Files           []string
}

func toDelimiter(s string) (r rune, err error) {
	s, err = strconv.Unquote(`"` + s + `"`)
	if err != nil {
		return 0, err
	}

	runes := []rune(s)
	if len(runes) != 1 {
		return 0, fmt.Errorf("the delimiter must be a single character")
	}
	return runes[0], nil
}

func do(c *CSVScanner) error {
	for c.Scan() {
		fmt.Println(c.Text())
	}
	return c.Err()
}

func _main() int {
	flagset.SetOutput(ioutil.Discard)
	if err := flagset.Parse(os.Args[1:]); err != nil {
		printErr(err)
		guideToHelp()
		return 2
	}
	switch {
	case *isHelp:
		printUsage()
		return 0
	case *isVersion:
		printVersion()
		return 0
	}

	var selector Selector
	switch {
	case *indexesList != "" && *headersList != "":
		printErr("only one type of list may be specified")
		guideToHelp()
		return 2
	case *indexesList != "":
		selector = NewIndexes(*indexesList)
	case *headersList != "":
		selector = NewHeaders(*headersList)
	default:
		selector = NewAll()
	}

	r, err := argf.From(flagset.Args())
	if err != nil {
		printErr(err)
		guideToHelp()
		return 2
	}

	c := NewCSVScanner(selector, r)
	c.SetOutputDelimiter(*outputDelimiter)
	switch {
	case *isTSV:
		c.SetDelimiter('\t')
	default:
		ch, err := toDelimiter(*delimiter)
		if err != nil {
			printErr(err)
			guideToHelp()
			return 2
		}
		c.SetDelimiter(ch)
	}

	if err = do(c); err != nil {
		printErr(err)
		return 1
	}
	return 0
}

func main() {
	e := _main()
	os.Exit(e)
}
<commit_msg>Remove Option<commit_after>package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"strconv"

	"github.com/ogier/pflag"
	"github.com/yuya-takeyama/argf"
)

var (
	name    = "csvp"
	version = "0.8.1"

	flagset         = pflag.NewFlagSet(name, pflag.ContinueOnError)
	indexesList     = flagset.StringP("indexes", "i", "", "")
	headersList     = flagset.StringP("headers", "h", "", "")
	isTSV           = flagset.BoolP("tsv", "t", false, "")
	delimiter       = flagset.StringP("delimiter", "d", ",", "")
	outputDelimiter = flagset.StringP("output-delimiter", "D", "\t", "")
	isHelp          = flagset.BoolP("help", "", false, "")
	isVersion       = flagset.BoolP("version", "", false, "")
)

func printUsage() {
	fmt.Fprintf(os.Stderr, `
Usage: %s [OPTION]... [FILE]...
Print selected parts of CSV from each FILE to standard output.

Options:
  -i, --indexes=LIST
                 select only these indexes
  -h, --headers=LIST
                 select only these headers
  -t, --tsv
                 equivalent to -d'\t'
  -d, --delimiter=DELIM
                 use DELIM instead of comma for field delimiter
  -D, --output-delimiter=STRING
                 use STRING as the output delimiter (default: \t)
  --help
                 display this help text and exit
  --version
                 output version information and exit
`[1:], name)
}

func printVersion() {
	fmt.Fprintln(os.Stderr, version)
}

func printErr(err interface{}) {
	fmt.Fprintf(os.Stderr, "%s: %s\n", name, err)
}

func guideToHelp() {
	fmt.Fprintf(os.Stderr, "Try '%s --help' for more information.\n", name)
}

func toDelimiter(s string) (r rune, err error) {
	s, err = strconv.Unquote(`"` + s + `"`)
	if err != nil {
		return 0, err
	}

	runes := []rune(s)
	if len(runes) != 1 {
		return 0, fmt.Errorf("the delimiter must be a single character")
	}
	return runes[0], nil
}

func do(c *CSVScanner) error {
	for c.Scan() {
		fmt.Println(c.Text())
	}
	return c.Err()
}

func _main() int {
	flagset.SetOutput(ioutil.Discard)
	if err := flagset.Parse(os.Args[1:]); err != nil {
		printErr(err)
		guideToHelp()
		return 2
	}
	switch {
	case *isHelp:
		printUsage()
		return 0
	case *isVersion:
		printVersion()
		return 0
	}

	var selector Selector
	switch {
	case *indexesList != "" && *headersList != "":
		printErr("only one type of list may be specified")
		guideToHelp()
		return 2
	case *indexesList != "":
		selector = NewIndexes(*indexesList)
	case *headersList != "":
		selector = NewHeaders(*headersList)
	default:
		selector = NewAll()
	}

	r, err := argf.From(flagset.Args())
	if err != nil {
		printErr(err)
		guideToHelp()
		return 2
	}

	c := NewCSVScanner(selector, r)
	c.SetOutputDelimiter(*outputDelimiter)
	switch {
	case *isTSV:
		c.SetDelimiter('\t')
	default:
		ch, err := toDelimiter(*delimiter)
		if err != nil {
			printErr(err)
			guideToHelp()
			return 2
		}
		c.SetDelimiter(ch)
	}

	if err = do(c); err != nil {
		printErr(err)
		return 1
	}
	return 0
}

func main() {
	e := _main()
	os.Exit(e)
}
<|endoftext|>


<commit_before>package main

import (
	"log"
	"os"

	"github.com/alecthomas/kingpin"

	"github.com/0xazure/pdify/generator"
)

const VERSION = "0.2.0"

var (
	input  = kingpin.Arg("input", "Source folder.").Required().String()
	output = kingpin.Flag("output", "Output file name.").Short('o').String()
)

func main() {
	logger := log.New(os.Stderr, "pdify: ", 0)

	kingpin.Version(VERSION)
	kingpin.Parse()

	g := generator.New(*input)

	err := g.Generate()
	if err != nil {
		logger.Fatal(err)
	}

	err = g.Write(*output)
	if err != nil {
		logger.Fatal(err)
	}

	os.Exit(0)
}
<commit_msg>Rename version const to conform with conventions<commit_after>package main

import (
	"log"
	"os"

	"github.com/alecthomas/kingpin"

	"github.com/0xazure/pdify/generator"
)

const Version = "0.2.0"

var (
	input  = kingpin.Arg("input", "Source folder.").Required().String()
	output = kingpin.Flag("output", "Output file name.").Short('o').String()
)

func main() {
	logger := log.New(os.Stderr, "pdify: ", 0)

	kingpin.Version(VERSION)
	kingpin.Parse()

	g := generator.New(*input)

	err := g.Generate()
	if err != nil {
		logger.Fatal(err)
	}

	err = g.Write(*output)
	if err != nil {
		logger.Fatal(err)
	}

	os.Exit(0)
}
<|endoftext|>


<commit_before>package main

// The import section defines libraries that we are going to use in our program.
import (
	"fmt"
	"log"
	"net/http"
	"math/rand"

	"encoding/json"
	"github.com/gorilla/mux"
	"github.com/ory-am/common/env"
	"github.com/ory-am/common/pkg"
	"github.com/pborman/uuid"
	"github.com/rs/cors"
	"math"
	"strconv"

	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
	. "github.com/ory-am/workshop-dbg/store"
	"github.com/ory-am/workshop-dbg/store/memory"
	"github.com/ory-am/workshop-dbg/store/postgres"
)

// In a 12 factor app, we must obey the environment variables.
var envHost = env.Getenv("HOST", "")
var envPort = env.Getenv("PORT", "5678")
var databaseURL = env.Getenv("DATABASE_URL", "")
var thisID = uuid.New()

// MyContacts is an exemplary list of contacts.
var MyContacts = Contacts{
	// Each contact hs identified by its ID which is prepended with "my-id":
	// We are doing this because it is easier to manage and simpler to read.
	"john-bravo": &Contact{
		Name:       "Andreas Preuss",
		Department: "IT",
		Company:    "ACME Inc",
	},
	"cathrine-mueller": &Contact{
		Name:       "Cathrine Müller",
		Department: "HR",
		Company:    "Grove AG",
	},
	"maximilian-schmidt": &Contact{
		Name:       "Maximilian Schmidt",
		Department: "PR",
		Company:    "Titanpad AG",
	},
	"uwe-charly": &Contact{
		Name:       "Uwe Charly",
		Department: "FAC",
		Company:    "KPMG",
	},
	"Thomas-Aidan": &Contact{
		Name:       "Thomas Aidan",
		Department: "INO",
		Company:    "OuterSpace",
	},
	"frank-sec": &Contact{
		Name:       "Frank Secure",
		Department: "Unknown",
		Company:    "Secret",
	},
	"juergen-elsner": &Contact{
		Name:       "Jürgen Elsner",
		Department: "DaCS",
		Company:    "DBG",
	},
}

var memoryStore = &memory.InMemoryStore{Contacts: MyContacts}

// The main routine is going the "entry" point.
func main() {
	// Create a new router.
	router := mux.NewRouter()

	// RESTful defines operations
	// * GET for fetching data
	// * POST for inserting data
	// * PUT for updating existing data
	// * DELETE for deleting data
	router.HandleFunc("/memory/contacts", ListContacts(memoryStore)).Methods("GET")
	router.HandleFunc("/memory/contacts", AddContact(memoryStore)).Methods("POST")
	router.HandleFunc("/memory/contacts/{id}", UpdateContact(memoryStore)).Methods("PUT")
	router.HandleFunc("/memory/contacts/{id}", DeleteContact(memoryStore)).Methods("DELETE")

	// Connect to database store
	db, err := sqlx.Connect("postgres", databaseURL)
	if err != nil {
		log.Printf("Could not connect to database because %s", err)
	} else {
		databaseStore := &postgres.PostgresStore{DB: db}
		if err := databaseStore.CreateSchemas(); err != nil {
			log.Printf("Could not set up relations %s", err)
		} else {
			router.HandleFunc("/database/contacts", ListContacts(databaseStore)).Methods("GET")
			router.HandleFunc("/database/contacts", AddContact(databaseStore)).Methods("POST")
			router.HandleFunc("/database/contacts/{id}", UpdateContact(databaseStore)).Methods("PUT")
			router.HandleFunc("/database/contacts/{id}", DeleteContact(databaseStore)).Methods("DELETE")
		}
	}

	// The info endpoint is for showing demonstration purposes only and is not subject to any task.
	router.HandleFunc("/info", InfoHandler).Methods("GET")
	router.HandleFunc("/pi", ComputePi).Methods("GET")
	router.HandleFunc("/allocate", Allocate).Methods("GET")

	// Print where to point the browser at.
	fmt.Printf("Listening on %s\n", "http://localhost:5678")

	// Cross origin resource requests
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedMethods: []string{"GET", "POST", "DELETE", "PUT"}},
	)

	// Start up the server and check for errors.
	listenOn := fmt.Sprintf("%s:%s", envHost, envPort)
	if err := http.ListenAndServe(listenOn, c.Handler(router)); err != nil {
		log.Fatalf("Could not set up server because %s", err)
	}
}

// ListContacts takes a contact list and outputs it.
func ListContacts(store ContactStorer) func(rw http.ResponseWriter, r *http.Request) {
	return func(rw http.ResponseWriter, r *http.Request) {

		// Write contact list to output
		contacts, err := store.FetchContacts()
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		pkg.WriteIndentJSON(rw, contacts)
	}
}

// AddContact will add a contact to the list
func AddContact(contacts ContactStorer) func(rw http.ResponseWriter, r *http.Request) {
	return func(rw http.ResponseWriter, r *http.Request) {

		// We parse the request's information into contactToBeAdded
		contactToBeAdded, err := ReadContactData(rw, r)

		// Abort handling the request if an error occurs.
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		// Save newContact to the list of contacts.
		if err = contacts.CreateContact(&contactToBeAdded); err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		// Output our newly created contact
		pkg.WriteIndentJSON(rw, contactToBeAdded)
	}
}

// DeleteContact will delete a contact from the list
func DeleteContact(contacts ContactStorer) func(rw http.ResponseWriter, r *http.Request) {
	return func(rw http.ResponseWriter, r *http.Request) {
		// Fetch the ID of the contact that is going to be deleted
		contactToBeDeleted := mux.Vars(r)["id"]

		// Delete the contact from the list
		if err := contacts.DeleteContact(contactToBeDeleted); err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		// Per specification, RESTful may return an empty response when a DELETE request was successful
		rw.WriteHeader(http.StatusNoContent)
	}
}

// UpdateContact will update a contact on the list
func UpdateContact(store ContactStorer) func(rw http.ResponseWriter, r *http.Request) {
	return func(rw http.ResponseWriter, r *http.Request) {
		// We parse the request's information into newContactData.
		newContactData, err := ReadContactData(rw, r)

		// Abort handling the request if an error occurs.
		if err != nil {
			http.Error(rw, err.Error(), http.StatusBadRequest)
			return
		}

		// Update the data in the contact list.
		if err := store.UpdateContact(&newContactData); err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		// Set the new data
		pkg.WriteIndentJSON(rw, newContactData)
	}
}

// ReadContactData is a helper function for parsing a HTTP request body. It returns a contact on success and an
// error if something went wrong.
func ReadContactData(rw http.ResponseWriter, r *http.Request) (contact Contact, err error) {
	err = json.NewDecoder(r.Body).Decode(&contact)
	if err != nil {
		http.Error(rw, fmt.Sprintf("Could not read input data because %s", err), http.StatusBadRequest)
		return contact, err
	}

	return contact, nil
}

func Allocate(rw http.ResponseWriter, r *http.Request) {
	n, err := strconv.Atoi(r.URL.Query().Get("n"))
	if err != nil {
		n = 0
	}
	m := make([][]byte, n + 1)

	for i := 0; i < n; i++ {
		z := make([]byte, n + 1)
		_, _ = rand.Read(z)
		m[i] = z
	}

	pkg.WriteIndentJSON(rw, struct {
		Result string `json:"result"`
		N int `json:"n"`
	}{
		Result: "Processed!",
		N: n,
	})
}

func ComputePi(rw http.ResponseWriter, r *http.Request) {
	n, err := strconv.Atoi(r.URL.Query().Get("n"))
	if err != nil {
		n = 0
	}

	pkg.WriteIndentJSON(rw, struct {
		Pi string `json:"pi"`
		N  int    `json:"n"`
	}{
		Pi: strconv.FormatFloat(pi(n), 'E', -1, 64),
		N:  n,
	})
}

func InfoHandler(rw http.ResponseWriter, r *http.Request) {
	rw.Write([]byte(thisID))
}

// pi launches n goroutines to compute an
// approximation of pi.
func pi(n int) float64 {
	ch := make(chan float64)
	for k := 0; k <= n; k++ {
		go term(ch, float64(k))
	}
	f := 0.0
	for k := 0; k <= n; k++ {
		f += <-ch
	}
	return f
}

func term(ch chan float64, k float64) {
	ch <- 4 * math.Pow(-1, k) / (2*k + 1)
}
<commit_msg>added memory allocation example<commit_after>package main

// The import section defines libraries that we are going to use in our program.
import (
	"fmt"
	"log"
	"net/http"
	"crypto/rand"

	"encoding/json"
	"github.com/gorilla/mux"
	"github.com/ory-am/common/env"
	"github.com/ory-am/common/pkg"
	"github.com/pborman/uuid"
	"github.com/rs/cors"
	"math"
	"strconv"

	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
	. "github.com/ory-am/workshop-dbg/store"
	"github.com/ory-am/workshop-dbg/store/memory"
	"github.com/ory-am/workshop-dbg/store/postgres"
)

// In a 12 factor app, we must obey the environment variables.
var envHost = env.Getenv("HOST", "")
var envPort = env.Getenv("PORT", "5678")
var databaseURL = env.Getenv("DATABASE_URL", "")
var thisID = uuid.New()

// MyContacts is an exemplary list of contacts.
var MyContacts = Contacts{
	// Each contact hs identified by its ID which is prepended with "my-id":
	// We are doing this because it is easier to manage and simpler to read.
	"john-bravo": &Contact{
		Name:       "Andreas Preuss",
		Department: "IT",
		Company:    "ACME Inc",
	},
	"cathrine-mueller": &Contact{
		Name:       "Cathrine Müller",
		Department: "HR",
		Company:    "Grove AG",
	},
	"maximilian-schmidt": &Contact{
		Name:       "Maximilian Schmidt",
		Department: "PR",
		Company:    "Titanpad AG",
	},
	"uwe-charly": &Contact{
		Name:       "Uwe Charly",
		Department: "FAC",
		Company:    "KPMG",
	},
	"Thomas-Aidan": &Contact{
		Name:       "Thomas Aidan",
		Department: "INO",
		Company:    "OuterSpace",
	},
	"frank-sec": &Contact{
		Name:       "Frank Secure",
		Department: "Unknown",
		Company:    "Secret",
	},
	"juergen-elsner": &Contact{
		Name:       "Jürgen Elsner",
		Department: "DaCS",
		Company:    "DBG",
	},
}

var memoryStore = &memory.InMemoryStore{Contacts: MyContacts}

// The main routine is going the "entry" point.
func main() {
	// Create a new router.
	router := mux.NewRouter()

	// RESTful defines operations
	// * GET for fetching data
	// * POST for inserting data
	// * PUT for updating existing data
	// * DELETE for deleting data
	router.HandleFunc("/memory/contacts", ListContacts(memoryStore)).Methods("GET")
	router.HandleFunc("/memory/contacts", AddContact(memoryStore)).Methods("POST")
	router.HandleFunc("/memory/contacts/{id}", UpdateContact(memoryStore)).Methods("PUT")
	router.HandleFunc("/memory/contacts/{id}", DeleteContact(memoryStore)).Methods("DELETE")

	// Connect to database store
	db, err := sqlx.Connect("postgres", databaseURL)
	if err != nil {
		log.Printf("Could not connect to database because %s", err)
	} else {
		databaseStore := &postgres.PostgresStore{DB: db}
		if err := databaseStore.CreateSchemas(); err != nil {
			log.Printf("Could not set up relations %s", err)
		} else {
			router.HandleFunc("/database/contacts", ListContacts(databaseStore)).Methods("GET")
			router.HandleFunc("/database/contacts", AddContact(databaseStore)).Methods("POST")
			router.HandleFunc("/database/contacts/{id}", UpdateContact(databaseStore)).Methods("PUT")
			router.HandleFunc("/database/contacts/{id}", DeleteContact(databaseStore)).Methods("DELETE")
		}
	}

	// The info endpoint is for showing demonstration purposes only and is not subject to any task.
	router.HandleFunc("/info", InfoHandler).Methods("GET")
	router.HandleFunc("/pi", ComputePi).Methods("GET")
	router.HandleFunc("/allocate", Allocate).Methods("GET")

	// Print where to point the browser at.
	fmt.Printf("Listening on %s\n", "http://localhost:5678")

	// Cross origin resource requests
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedMethods: []string{"GET", "POST", "DELETE", "PUT"}},
	)

	// Start up the server and check for errors.
	listenOn := fmt.Sprintf("%s:%s", envHost, envPort)
	if err := http.ListenAndServe(listenOn, c.Handler(router)); err != nil {
		log.Fatalf("Could not set up server because %s", err)
	}
}

// ListContacts takes a contact list and outputs it.
func ListContacts(store ContactStorer) func(rw http.ResponseWriter, r *http.Request) {
	return func(rw http.ResponseWriter, r *http.Request) {

		// Write contact list to output
		contacts, err := store.FetchContacts()
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		pkg.WriteIndentJSON(rw, contacts)
	}
}

// AddContact will add a contact to the list
func AddContact(contacts ContactStorer) func(rw http.ResponseWriter, r *http.Request) {
	return func(rw http.ResponseWriter, r *http.Request) {

		// We parse the request's information into contactToBeAdded
		contactToBeAdded, err := ReadContactData(rw, r)

		// Abort handling the request if an error occurs.
		if err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		// Save newContact to the list of contacts.
		if err = contacts.CreateContact(&contactToBeAdded); err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		// Output our newly created contact
		pkg.WriteIndentJSON(rw, contactToBeAdded)
	}
}

// DeleteContact will delete a contact from the list
func DeleteContact(contacts ContactStorer) func(rw http.ResponseWriter, r *http.Request) {
	return func(rw http.ResponseWriter, r *http.Request) {
		// Fetch the ID of the contact that is going to be deleted
		contactToBeDeleted := mux.Vars(r)["id"]

		// Delete the contact from the list
		if err := contacts.DeleteContact(contactToBeDeleted); err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		// Per specification, RESTful may return an empty response when a DELETE request was successful
		rw.WriteHeader(http.StatusNoContent)
	}
}

// UpdateContact will update a contact on the list
func UpdateContact(store ContactStorer) func(rw http.ResponseWriter, r *http.Request) {
	return func(rw http.ResponseWriter, r *http.Request) {
		// We parse the request's information into newContactData.
		newContactData, err := ReadContactData(rw, r)

		// Abort handling the request if an error occurs.
		if err != nil {
			http.Error(rw, err.Error(), http.StatusBadRequest)
			return
		}

		// Update the data in the contact list.
		if err := store.UpdateContact(&newContactData); err != nil {
			http.Error(rw, err.Error(), http.StatusInternalServerError)
			return
		}

		// Set the new data
		pkg.WriteIndentJSON(rw, newContactData)
	}
}

// ReadContactData is a helper function for parsing a HTTP request body. It returns a contact on success and an
// error if something went wrong.
func ReadContactData(rw http.ResponseWriter, r *http.Request) (contact Contact, err error) {
	err = json.NewDecoder(r.Body).Decode(&contact)
	if err != nil {
		http.Error(rw, fmt.Sprintf("Could not read input data because %s", err), http.StatusBadRequest)
		return contact, err
	}

	return contact, nil
}

func Allocate(rw http.ResponseWriter, r *http.Request) {
	n, err := strconv.Atoi(r.URL.Query().Get("n"))
	if err != nil {
		n = 0
	}
	m := make([][]byte, n + 1)

	for i := 0; i < n; i++ {
		z := make([]byte, n + 1)
		_, _ = rand.Read(z)
		m[i] = z
	}

	pkg.WriteIndentJSON(rw, struct {
		Result string `json:"result"`
		N int `json:"n"`
	}{
		Result: "Processed!",
		N: n,
	})
}

func ComputePi(rw http.ResponseWriter, r *http.Request) {
	n, err := strconv.Atoi(r.URL.Query().Get("n"))
	if err != nil {
		n = 0
	}

	pkg.WriteIndentJSON(rw, struct {
		Pi string `json:"pi"`
		N  int    `json:"n"`
	}{
		Pi: strconv.FormatFloat(pi(n), 'E', -1, 64),
		N:  n,
	})
}

func InfoHandler(rw http.ResponseWriter, r *http.Request) {
	rw.Write([]byte(thisID))
}

// pi launches n goroutines to compute an
// approximation of pi.
func pi(n int) float64 {
	ch := make(chan float64)
	for k := 0; k <= n; k++ {
		go term(ch, float64(k))
	}
	f := 0.0
	for k := 0; k <= n; k++ {
		f += <-ch
	}
	return f
}

func term(ch chan float64, k float64) {
	ch <- 4 * math.Pow(-1, k) / (2*k + 1)
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"os"
	"os/signal"
	"runtime"
	"syscall"

	"github.com/ehalpern/go-mysql-elasticsearch/river"
	"github.com/juju/errors"
	"fmt"
)

var configFile = flag.String("config", "./etc/river.toml", "replication config file")
var serviceOp = flag.String("service", "", "install|remove|[re]start|stop|status")
var dbHost = flag.String("db_host", "", "DB host and port")
var dbUser = flag.String("db_user", "", "DB user")
var dbPass = flag.String("db_pass", "", "DB password")
var dbSlaveId = flag.Int("db_slave_id", 0, "MySQL slave id")
var esHost = flag.String("es_host", "", "Elasticsearch host and port")
var esMaxActions = flag.Int("es_max_actions", 0, "maximum elasticsearch bulk update size")
var dataDir = flag.String("data_dir", "", "path do store data")

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)

	flag.Parse()

	if serviceOp != "" {
		s := NewService()
		var status string
		var err error

		switch *serviceOp {
		case "install":
			status, err = s.Install("-config", configFile)
		case "remove":
			status, err = s.Remove()
		case "start":
			status, err = s.Start()
		case "stop":
			status, err = s.Stop()
		case "status":
			status, err = s.Status()
		default:
			err = flag.Usage()
		}
		if err != nil {
			errlog.Println("Error: ", err)
			os.Exit(1)
		}
		fmt.Println(status)
		os.Exit(1)
	}

	cfg, err := river.NewConfigWithFile(*configFile)
	if err != nil {
		println(errors.ErrorStack(err))
		return
	}

	if len(*dbHost) > 0 {
		cfg.DbHost = *dbHost
	}
	if len(*dbUser) > 0 {
		cfg.DbUser = *dbUser
	}
	if len(*dbPass) > 0 {
		cfg.DbPassword = *dbPass
	}
	if *dbSlaveId > 0 {
		cfg.DbSlaveID = uint32(*dbSlaveId)
	}
	if len(*esHost) > 0 {
		cfg.EsHost = *esHost
	}
	if len(*dataDir) > 0 {
		cfg.DataDir = *dataDir
	}
	if *esMaxActions > 0 {
		cfg.EsMaxActions = *esMaxActions
	}

	r, err := river.NewRiver(cfg)
	if err != nil {
		println(errors.ErrorStack(err))
		return
	}

	if err = r.Run(); err != nil {
		println(errors.ErrorStack(err))
	}

	<-interrupt
	r.Close()
}
<commit_msg>Fix bug<commit_after>package main

import (
	"flag"
	"os"
	"os/signal"
	"runtime"
	"syscall"

	"github.com/ehalpern/go-mysql-elasticsearch/river"
	"github.com/juju/errors"
	"fmt"
)

var configFile = flag.String("config", "./etc/river.toml", "replication config file")
var serviceOp = flag.String("service", "", "install|remove|[re]start|stop|status")
var dbHost = flag.String("db_host", "", "DB host and port")
var dbUser = flag.String("db_user", "", "DB user")
var dbPass = flag.String("db_pass", "", "DB password")
var dbSlaveId = flag.Int("db_slave_id", 0, "MySQL slave id")
var esHost = flag.String("es_host", "", "Elasticsearch host and port")
var esMaxActions = flag.Int("es_max_actions", 0, "maximum elasticsearch bulk update size")
var dataDir = flag.String("data_dir", "", "path do store data")

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)

	flag.Parse()

	if *serviceOp != "" {
		s := NewService()
		var status string
		var err error

		switch *serviceOp {
		case "install":
			status, err = s.Install("-config", *configFile)
		case "remove":
			status, err = s.Remove()
		case "start":
			status, err = s.Start()
		case "stop":
			status, err = s.Stop()
		case "status":
			status, err = s.Status()
		default:
			flag.Usage()
			err = errors.Errorf("unrecognized -service option " + *serviceOp)
		}
		if err != nil {
			errlog.Println("Error: ", err)
			os.Exit(1)
		}
		fmt.Println(status)
		os.Exit(1)
	}

	cfg, err := river.NewConfigWithFile(*configFile)
	if err != nil {
		println(errors.ErrorStack(err))
		return
	}

	if len(*dbHost) > 0 {
		cfg.DbHost = *dbHost
	}
	if len(*dbUser) > 0 {
		cfg.DbUser = *dbUser
	}
	if len(*dbPass) > 0 {
		cfg.DbPassword = *dbPass
	}
	if *dbSlaveId > 0 {
		cfg.DbSlaveID = uint32(*dbSlaveId)
	}
	if len(*esHost) > 0 {
		cfg.EsHost = *esHost
	}
	if len(*dataDir) > 0 {
		cfg.DataDir = *dataDir
	}
	if *esMaxActions > 0 {
		cfg.EsMaxActions = *esMaxActions
	}

	r, err := river.NewRiver(cfg)
	if err != nil {
		println(errors.ErrorStack(err))
		return
	}

	if err = r.Run(); err != nil {
		println(errors.ErrorStack(err))
	}

	<-interrupt
	r.Close()
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/zankich/concourse-scratch/client1"
	"github.com/zankich/concourse-scratch/client2"
)

func main() {
	fmt.Println(ReturnThree())
}

func ReturnThree() int {
	return client1.ReturnOne() + client2.ReturnTwo()
}
<commit_msg>Display version number with -v flag<commit_after>package main

import (
	"fmt"
	"github.com/zankich/concourse-scratch/client1"
	"github.com/zankich/concourse-scratch/client2"
	"io/ioutil"
	"os"
)

func main() {
	if len(os.Args) == 2 && (os.Args[1] == "-v" || os.Args[1] == "--version") {
		if buf, err := ioutil.ReadFile("version"); err != nil {
			fmt.Println(err)
		} else {
			fmt.Println(string(buf))
		}
		os.Exit(0)
	}
	fmt.Printf("The answer is: %d!\n", ReturnThree())
}

func ReturnThree() int {
	return client1.ReturnOne() + client2.ReturnTwo()
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/push"
	"log"
	"strconv"
)

const (
	version = "0.01"
	jobName = "tesla_collector"
)

var (
	configPath      = flag.String("configPath", "config.json", "Path to configuration file.")
	pushgatewayAddr = flag.String("pushgateway_address", "", "URL of pushgateway.")
	odometerMetric  = prometheus.NewGaugeVec(prometheus.GaugeOpts{
		Name: "odometric_metric",
		Help: "Current odometer value per vehicle.",
	}, []string{"vehicle_id", "vehicle_name"})
)

func main() {
	log.Printf("Tesla Go version %v\n", version)

	config := LoadConfig(*configPath)
	client := NewTeslaClient()

	if err := client.Authenticate(config); err != nil {
		log.Fatalf("Failed to authenticate: %s", err)
	} else {
		log.Println("Authentication complete.")
	}

	vehicles, err := client.ListVehicles()
	if err != nil {
		log.Fatalf("ListVehicles operation failed: %s", err)
	}

	for _, v := range vehicles {
		resp, err := client.GetVehicleState(v)
		if err != nil {
			log.Fatalf("Error while getting drive state of v %s: %s", v.ID, err)
		}
		odometerMetric.WithLabelValues(strconv.FormatInt(v.ID, 10), v.DisplayName).Set(resp.Odometer)
	}

	if err := push.Collectors(jobName, nil, *pushgatewayAddr, odometerMetric); err != nil {
		log.Fatalf("Failed to push metrics: %s", err)
	}
}
<commit_msg>Add mistakenly forgotten flag.Parse() call.<commit_after>package main

import (
	"flag"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/push"
	"log"
	"strconv"
)

const (
	version = "0.01"
	jobName = "tesla_collector"
)

var (
	configPath      = flag.String("configPath", "config.json", "Path to configuration file.")
	pushgatewayAddr = flag.String("pushgateway_address", "", "URL of pushgateway.")
	odometerMetric  = prometheus.NewGaugeVec(prometheus.GaugeOpts{
		Name: "odometric_metric",
		Help: "Current odometer value per vehicle.",
	}, []string{"vehicle_id", "vehicle_name"})
)

func main() {
	flag.Parse()
	log.Printf("Tesla Go version %v\n", version)

	config := LoadConfig(*configPath)
	client := NewTeslaClient()

	if err := client.Authenticate(config); err != nil {
		log.Fatalf("Failed to authenticate: %s", err)
	} else {
		log.Println("Authentication complete.")
	}

	vehicles, err := client.ListVehicles()
	if err != nil {
		log.Fatalf("ListVehicles operation failed: %s", err)
	}

	for _, v := range vehicles {
		resp, err := client.GetVehicleState(v)
		if err != nil {
			log.Fatalf("Error while getting drive state of v %s: %s", v.ID, err)
		}
		odometerMetric.WithLabelValues(strconv.FormatInt(v.ID, 10), v.DisplayName).Set(resp.Odometer)
	}

	if err := push.Collectors(jobName, nil, *pushgatewayAddr, odometerMetric); err != nil {
		log.Fatalf("Failed to push metrics: %s", err)
	}
}
<|endoftext|>


<commit_before>package main

import "fmt"

func main() {
    fmt.Printf("hello, world\n")
}
<commit_msg>Simple server<commit_after>package main

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

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
    })

    log.Fatal(http.ListenAndServe(":8080", nil))

}
<|endoftext|>


<commit_before>package main

import odin "github.com/jwaldrip/odin/cli"

// VERSION is the odin version
var VERSION = "1.4.0"

var cli = odin.New(VERSION, "a command line DSL for go-lang", func(cmd odin.Command) { cmd.Usage() })

func main() {
	cli.Start()
}
<commit_msg>use new usage command<commit_after>package main

import "github.com/jwaldrip/odin/cli"

// VERSION is the odin version
var VERSION = "1.4.0"

var app = cli.New(VERSION, "a command line DSL for go-lang", cli.ShowUsage)

func main() {
	app.Start()
}
<|endoftext|>


<commit_before>/*
gitlab-git-http-server handles 'smart' Git HTTP requests for GitLab

This HTTP server can service 'git clone', 'git push' etc. commands
from Git clients that use the 'smart' Git HTTP protocol (git-upload-pack
and git-receive-pack). It is intended to be deployed behind NGINX
(for request routing and SSL termination) with access to a GitLab
backend (for authentication and authorization) and local disk access
to Git repositories managed by GitLab. In GitLab, this role was previously
performed by gitlab-grack.

This file contains the main() function. Actual Git HTTP requests are handled by
the gitHandler type, implemented in githandler.go.
*/
package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"syscall"
)

var Version string // Set at build time in the Makefile

func main() {
	printVersion := flag.Bool("version", false, "Print version and exit")
	listenAddr := flag.String("listenAddr", "localhost:8181", "Listen address for HTTP server")
	listenNetwork := flag.String("listenNetwork", "tcp", "Listen 'network' (tcp, tcp4, tcp6, unix)")
	listenUmask := flag.Int("listenUmask", 022, "Umask for Unix socket, default: 022")
	authBackend := flag.String("authBackend", "http://localhost:8080", "Authentication/authorization backend")
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		fmt.Fprintf(os.Stderr, "\n  %s [OPTIONS] REPO_ROOT\n\nOptions:\n", os.Args[0])
		flag.PrintDefaults()
	}
	flag.Parse()

	if *printVersion {
		fmt.Printf("gitlab-git-http-server %s\n", Version)
		os.Exit(0)
	}

	repoRoot := flag.Arg(0)
	if repoRoot == "" {
		flag.Usage()
		os.Exit(1)
	}
	log.Printf("repoRoot: %s", repoRoot)

	// Good housekeeping for Unix sockets: unlink before binding
	if *listenNetwork == "unix" {
		if err := os.Remove(*listenAddr); err != nil && !os.IsNotExist(err) {
			log.Fatal(err)
		}
	}

	// Change the umask only around net.Listen()
	oldUmask := syscall.Umask(*listenUmask)
	listener, err := net.Listen(*listenNetwork, *listenAddr)
	syscall.Umask(oldUmask)
	if err != nil {
		log.Fatal(err)
	}

	http.Handle("/", newGitHandler(repoRoot, *authBackend))
	log.Fatal(http.Serve(listener, nil))
}
<commit_msg>Add optional Golang profiler<commit_after>/*
gitlab-git-http-server handles 'smart' Git HTTP requests for GitLab

This HTTP server can service 'git clone', 'git push' etc. commands
from Git clients that use the 'smart' Git HTTP protocol (git-upload-pack
and git-receive-pack). It is intended to be deployed behind NGINX
(for request routing and SSL termination) with access to a GitLab
backend (for authentication and authorization) and local disk access
to Git repositories managed by GitLab. In GitLab, this role was previously
performed by gitlab-grack.

This file contains the main() function. Actual Git HTTP requests are handled by
the gitHandler type, implemented in githandler.go.
*/
package main

import (
	"flag"
	"fmt"
	"log"
	"net"
	"net/http"
	_ "net/http/pprof"
	"os"
	"syscall"
)

var Version string // Set at build time in the Makefile

func main() {
	printVersion := flag.Bool("version", false, "Print version and exit")
	listenAddr := flag.String("listenAddr", "localhost:8181", "Listen address for HTTP server")
	listenNetwork := flag.String("listenNetwork", "tcp", "Listen 'network' (tcp, tcp4, tcp6, unix)")
	listenUmask := flag.Int("listenUmask", 022, "Umask for Unix socket, default: 022")
	authBackend := flag.String("authBackend", "http://localhost:8080", "Authentication/authorization backend")
	pprofListenAddr := flag.String("pprofListenAddr", "", "pprof listening address, e.g. 'localhost:6060'")
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		fmt.Fprintf(os.Stderr, "\n  %s [OPTIONS] REPO_ROOT\n\nOptions:\n", os.Args[0])
		flag.PrintDefaults()
	}
	flag.Parse()

	if *printVersion {
		fmt.Printf("gitlab-git-http-server %s\n", Version)
		os.Exit(0)
	}

	repoRoot := flag.Arg(0)
	if repoRoot == "" {
		flag.Usage()
		os.Exit(1)
	}
	log.Printf("repoRoot: %s", repoRoot)

	// Good housekeeping for Unix sockets: unlink before binding
	if *listenNetwork == "unix" {
		if err := os.Remove(*listenAddr); err != nil && !os.IsNotExist(err) {
			log.Fatal(err)
		}
	}

	// Change the umask only around net.Listen()
	oldUmask := syscall.Umask(*listenUmask)
	listener, err := net.Listen(*listenNetwork, *listenAddr)
	syscall.Umask(oldUmask)
	if err != nil {
		log.Fatal(err)
	}

	// The profiler will only be activated by HTTP requests. HTTP
	// requests can only reach the profiler if we start a listener. So by
	// having no profiler HTTP listener by default, the profiler is
	// effectively disabled by default.
	if *pprofListenAddr != "" {
		go func() {
			log.Print(http.ListenAndServe(*pprofListenAddr, nil))
		}()
	}

	// Because net/http/pprof installs itself in the DefaultServeMux
	// we create a fresh one for the Git server.
	serveMux := http.NewServeMux()
	serveMux.Handle("/", newGitHandler(repoRoot, *authBackend))
	log.Fatal(http.Serve(listener, serveMux))
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"runtime/debug"
	"sort"
	"strings"

	"github.com/crillab/gophersat/bf"
	"github.com/crillab/gophersat/solver"
)

func main() {
	debug.SetGCPercent(300)
	if len(os.Args) > 2 {
		fmt.Fprintf(os.Stderr, "Syntax : %s [file.cnf|file.bf]\n", os.Args[0])
		os.Exit(1)
	}
	f := os.Stdin
	if len(os.Args) == 2 {
		var err error
		f, err = os.Open(os.Args[1])
		if err != nil {
			fmt.Fprintf(os.Stderr, "Could not open %s: %v\n", os.Args[1], err.Error())
			os.Exit(1)
		}
		defer f.Close()
	}
	if err := parseAndSolve(f); err != nil {
		fmt.Fprintf(os.Stdout, "could not solve problem: %v\n", err)
		os.Exit(1)
	}
}

func parseAndSolve(r io.Reader) error {
	content, err := ioutil.ReadAll(r)
	if err != nil {
		return fmt.Errorf("could not read data: %v", err)
	}
	r2 := strings.NewReader(string(content))
	f, errBF := bf.Parse(r2)
	if errBF == nil {
		return solveBF(f)
	}
	r2 = strings.NewReader(string(content))
	pb, errCNF := solver.ParseCNF(r2)
	if errCNF == nil {
		return solveCNF(pb)
	}
	r2 = strings.NewReader(string(content))
	pb, errOPB := solver.ParseOPB(r2)
	if errOPB != nil {
		return fmt.Errorf("could not parse content as DIMACS (%v), as boolean formula (%v), nor as a pseudo-boolean problem (%v)", errCNF, errBF, errOPB)
	}
	return minimize(pb)
}

func minimize(pb *solver.Problem) error {
	fmt.Printf("c ======================================================================================\n")
	fmt.Printf("c | Number of clauses   : %9d                                                    |\n", len(pb.Clauses))
	fmt.Printf("c | Number of variables : %9d                                                    |\n", pb.NbVars)
	s := solver.New(pb)
	s.Verbose = true
	s.Minimize()
	fmt.Printf("c nb conflicts: %d\nc nb restarts: %d\nc nb decisions: %d\n", s.Stats.NbConflicts, s.Stats.NbRestarts, s.Stats.NbDecisions)
	fmt.Printf("c nb unit learned: %d\nc nb binary learned: %d\nc nb learned: %d\n", s.Stats.NbUnitLearned, s.Stats.NbBinaryLearned, s.Stats.NbLearned)
	fmt.Printf("c nb clauses deleted: %d\n", s.Stats.NbDeleted)
	s.OutputModel()
	return nil
}

func solveCNF(pb *solver.Problem) error {
	fmt.Printf("c ======================================================================================\n")
	fmt.Printf("c | Number of clauses   : %9d                                                    |\n", len(pb.Clauses))
	fmt.Printf("c | Number of variables : %9d                                                    |\n", pb.NbVars)
	s := solver.New(pb)
	s.Verbose = true
	s.Solve()
	fmt.Printf("c nb conflicts: %d\nc nb restarts: %d\nc nb decisions: %d\n", s.Stats.NbConflicts, s.Stats.NbRestarts, s.Stats.NbDecisions)
	fmt.Printf("c nb unit learned: %d\nc nb binary learned: %d\nc nb learned: %d\n", s.Stats.NbUnitLearned, s.Stats.NbBinaryLearned, s.Stats.NbLearned)
	fmt.Printf("c nb clauses deleted: %d\n", s.Stats.NbDeleted)
	s.OutputModel()
	return nil
}

func countModels(pb *solver.Problem) error {
	fmt.Printf("c ======================================================================================\n")
	fmt.Printf("c | Number of clauses   : %9d                                                    |\n", len(pb.Clauses))
	fmt.Printf("c | Number of variables : %9d                                                    |\n", pb.NbVars)
	s := solver.New(pb)
	s.Verbose = true
	fmt.Printf("%d models found\n", s.CountModels())
	return nil
}

func solveBF(f bf.Formula) error {
	if model := bf.Solve(f); model == nil {
		fmt.Println("UNSATISFIABLE")
	} else {
		fmt.Println("SATISFIABLE")
		keys := make(sort.StringSlice, 0, len(model))
		for k := range model {
			keys = append(keys, k)
		}
		sort.Sort(keys)
		for _, k := range keys {
			fmt.Printf("%s: %t\n", k, model[k])
		}
	}
	return nil
}
<commit_msg>added comment to easily switch profiling<commit_after>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"runtime/debug"
	"sort"
	"strings"

	"github.com/crillab/gophersat/bf"
	"github.com/crillab/gophersat/solver"
)

func main() {
	// defer profile.Start().Stop()
	debug.SetGCPercent(300)
	if len(os.Args) > 2 {
		fmt.Fprintf(os.Stderr, "Syntax : %s [file.cnf|file.bf]\n", os.Args[0])
		os.Exit(1)
	}
	f := os.Stdin
	if len(os.Args) == 2 {
		var err error
		f, err = os.Open(os.Args[1])
		if err != nil {
			fmt.Fprintf(os.Stderr, "Could not open %s: %v\n", os.Args[1], err.Error())
			os.Exit(1)
		}
		defer f.Close()
	}
	if err := parseAndSolve(f); err != nil {
		fmt.Fprintf(os.Stdout, "could not solve problem: %v\n", err)
		os.Exit(1)
	}
}

func parseAndSolve(r io.Reader) error {
	content, err := ioutil.ReadAll(r)
	if err != nil {
		return fmt.Errorf("could not read data: %v", err)
	}
	r2 := strings.NewReader(string(content))
	f, errBF := bf.Parse(r2)
	if errBF == nil {
		return solveBF(f)
	}
	r2 = strings.NewReader(string(content))
	pb, errCNF := solver.ParseCNF(r2)
	if errCNF == nil {
		return solveCNF(pb)
	}
	r2 = strings.NewReader(string(content))
	pb, errOPB := solver.ParseOPB(r2)
	if errOPB != nil {
		return fmt.Errorf("could not parse content as DIMACS (%v), as boolean formula (%v), nor as a pseudo-boolean problem (%v)", errCNF, errBF, errOPB)
	}
	return minimize(pb)
}

func minimize(pb *solver.Problem) error {
	fmt.Printf("c ======================================================================================\n")
	fmt.Printf("c | Number of clauses   : %9d                                                    |\n", len(pb.Clauses))
	fmt.Printf("c | Number of variables : %9d                                                    |\n", pb.NbVars)
	s := solver.New(pb)
	s.Verbose = true
	s.Minimize()
	fmt.Printf("c nb conflicts: %d\nc nb restarts: %d\nc nb decisions: %d\n", s.Stats.NbConflicts, s.Stats.NbRestarts, s.Stats.NbDecisions)
	fmt.Printf("c nb unit learned: %d\nc nb binary learned: %d\nc nb learned: %d\n", s.Stats.NbUnitLearned, s.Stats.NbBinaryLearned, s.Stats.NbLearned)
	fmt.Printf("c nb clauses deleted: %d\n", s.Stats.NbDeleted)
	s.OutputModel()
	return nil
}

func solveCNF(pb *solver.Problem) error {
	fmt.Printf("c ======================================================================================\n")
	fmt.Printf("c | Number of clauses   : %9d                                                    |\n", len(pb.Clauses))
	fmt.Printf("c | Number of variables : %9d                                                    |\n", pb.NbVars)
	s := solver.New(pb)
	s.Verbose = true
	s.Solve()
	fmt.Printf("c nb conflicts: %d\nc nb restarts: %d\nc nb decisions: %d\n", s.Stats.NbConflicts, s.Stats.NbRestarts, s.Stats.NbDecisions)
	fmt.Printf("c nb unit learned: %d\nc nb binary learned: %d\nc nb learned: %d\n", s.Stats.NbUnitLearned, s.Stats.NbBinaryLearned, s.Stats.NbLearned)
	fmt.Printf("c nb clauses deleted: %d\n", s.Stats.NbDeleted)
	s.OutputModel()
	return nil
}

func countModels(pb *solver.Problem) error {
	fmt.Printf("c ======================================================================================\n")
	fmt.Printf("c | Number of clauses   : %9d                                                    |\n", len(pb.Clauses))
	fmt.Printf("c | Number of variables : %9d                                                    |\n", pb.NbVars)
	s := solver.New(pb)
	s.Verbose = true
	fmt.Printf("%d models found\n", s.CountModels())
	return nil
}

func solveBF(f bf.Formula) error {
	if model := bf.Solve(f); model == nil {
		fmt.Println("UNSATISFIABLE")
	} else {
		fmt.Println("SATISFIABLE")
		keys := make(sort.StringSlice, 0, len(model))
		for k := range model {
			keys = append(keys, k)
		}
		sort.Sort(keys)
		for _, k := range keys {
			fmt.Printf("%s: %t\n", k, model[k])
		}
	}
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"regexp"
	"strings"

	md "github.com/shurcooL/github_flavored_markdown"
	"sync"
	"bytes"
)

var filePath string
var dirPath string
var linksRegExp = regexp.MustCompile(`(?:\{\{)(.{1,})(?:\}\})`)
var charset = []byte("<meta charset=\"UTF-8\">")

func main() {
	flag.StringVar(&filePath, "f", "", "mdg -f path/to/file")
	flag.StringVar(&dirPath, "d", ".", "mdg -d path/to/folder")
	flag.Parse()

	// list is a []string of markdown files
	fileList := seekPrefixedFiles(".md")

	var wg sync.WaitGroup
	for _, file := range fileList {
		wg.Add(1)
		go process(file, fileList, &wg)
	}
	wg.Wait();
}

func process(file string, fileList []string, wg *sync.WaitGroup) {
	f, err := os.Open(file)
	if err != nil {
		log.Println("Cannot open file", err)
		return
	}

	fileContent, err := ioutil.ReadAll(f)
	if err != nil {
		log.Println("Cannot read content of file", err)
		return
	}

	fileMenu := generateMenu(fileList)
	for _, v := range fileContent {
		fileMenu = append(fileMenu, v)
	}
	//fileMenu = replaceTokens(fileMenu)
	fileMenu = compileMarkdown(fileMenu)
	fileMenu = appendCSS(fileMenu)

	// Ensure UTF-8 Encoding is properly appended to the document
	fileMenu = ensureCharset(fileMenu)

	// basically I need to write the file like that once it's compiled lol
	if _, err := os.Stat("html"); os.IsNotExist(err) {
		os.Mkdir("html", 0777)
	}

	newFname := newFileName(file)
	ioutil.WriteFile(newFname, fileMenu, 0777)

	err = os.Rename(newFname, "html/" + newFname)
	if err != nil {
		log.Println(err)
		return
	}
	wg.Done()
}

func ensureCharset(file []byte) []byte {
	return append(charset, file...)
}

func generateMenu(fileList []string) []byte {
	if len(fileList) > 40 {
		return []byte("")
	}

	menu := "#### Menu\n"
	for _, file := range fileList {
		f := strings.TrimSuffix(file, ".md")
		menu += fmt.Sprintf("- [%s](%s.html)\n", f, f)
	}
	menu += "\n---\n\n"

	return []byte(menu)
}

func newFileName(name string) string {
	name = strings.TrimSuffix(name, ".md")
	return name + ".html"
}

func appendCSS(stream []byte) []byte {
	css, err := Asset("github-markdown.html")
	if err != nil {
		panic(err)
	}

	stream = append(css, stream...)

	return stream
}

func replaceTokens(stream []byte) []byte {
	buffer := bytes.NewBuffer(stream)
	temp := buffer.Bytes()

	for _, match := range linksRegExp.FindAll(temp, -1) {
		stripped := bytes.Trim(match, "{}")
		linked := []byte(string(stripped) + ".html")
		temp = bytes.Replace(temp, match, linked, -1)
	}

	return temp
}

func compileMarkdown(text []byte) []byte {
	return md.Markdown(text)
}

func seekPrefixedFiles(prefix string) []string {
	files, err := ioutil.ReadDir(dirPath)
	if err != nil {
		panic(err)
	}

	var list []string
	for _, file := range files {
		if strings.HasSuffix(file.Name(), prefix) {
			list = append(list, file.Name())
		}
	}

	return list
}
<commit_msg>Added menu flag<commit_after>package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"regexp"
	"strings"

	md "github.com/shurcooL/github_flavored_markdown"
	"sync"
	"bytes"
)

var filePath string
var dirPath string
var shouldMenu string
var linksRegExp = regexp.MustCompile(`(?:\{\{)(.{1,})(?:\}\})`)
var charset = []byte("<meta charset=\"UTF-8\">")

func main() {
	flag.StringVar(&filePath, "f", "", "mdg -f path/to/file")
	flag.StringVar(&dirPath, "d", ".", "mdg -d path/to/folder")
	flag.StringVar(&shouldMenu, "m", "true", "mdg -m false")
	flag.Parse()

	// list is a []string of markdown files
	fileList := seekPrefixedFiles(".md")

	var wg sync.WaitGroup
	for _, file := range fileList {
		wg.Add(1)
		go process(file, fileList, &wg)
	}
	wg.Wait();
}

func process(file string, fileList []string, wg *sync.WaitGroup) {
	f, err := os.Open(file)
	if err != nil {
		log.Println("Cannot open file", err)
		return
	}

	fileContent, err := ioutil.ReadAll(f)
	if err != nil {
		log.Println("Cannot read content of file", err)
		return
	}

	var fileMenu []byte
	if shouldMenu == "true" {
		fileMenu = generateMenu(fileList)
		for _, v := range fileContent {
			fileMenu = append(fileMenu, v)
		}
	} else {
		fileMenu = fileContent
	}

	fileMenu = compileMarkdown(fileMenu)
	fileMenu = appendCSS(fileMenu)

	// Ensure UTF-8 Encoding is properly appended to the document
	fileMenu = ensureCharset(fileMenu)

	// basically I need to write the file like that once it's compiled lol
	if _, err := os.Stat("html"); os.IsNotExist(err) {
		os.Mkdir("html", 0777)
	}

	newFname := newFileName(file)
	ioutil.WriteFile(newFname, fileMenu, 0777)

	err = os.Rename(newFname, "html/" + newFname)
	if err != nil {
		log.Println(err)
		return
	}
	wg.Done()
}

func ensureCharset(file []byte) []byte {
	return append(charset, file...)
}

func generateMenu(fileList []string) []byte {
	if len(fileList) > 40 {
		return []byte("")
	}

	menu := "#### Menu\n"
	for _, file := range fileList {
		f := strings.TrimSuffix(file, ".md")
		menu += fmt.Sprintf("- [%s](%s.html)\n", f, f)
	}
	menu += "\n---\n\n"

	return []byte(menu)
}

func newFileName(name string) string {
	name = strings.TrimSuffix(name, ".md")
	return name + ".html"
}

func appendCSS(stream []byte) []byte {
	css, err := Asset("github-markdown.html")
	if err != nil {
		panic(err)
	}

	stream = append(css, stream...)

	return stream
}

func replaceTokens(stream []byte) []byte {
	buffer := bytes.NewBuffer(stream)
	temp := buffer.Bytes()

	for _, match := range linksRegExp.FindAll(temp, -1) {
		stripped := bytes.Trim(match, "{}")
		linked := []byte(string(stripped) + ".html")
		temp = bytes.Replace(temp, match, linked, -1)
	}

	return temp
}

func compileMarkdown(text []byte) []byte {
	return md.Markdown(text)
}

func seekPrefixedFiles(prefix string) []string {
	files, err := ioutil.ReadDir(dirPath)
	if err != nil {
		panic(err)
	}

	var list []string
	for _, file := range files {
		if strings.HasSuffix(file.Name(), prefix) {
			list = append(list, file.Name())
		}
	}

	return list
}
<|endoftext|>