<commit_before>package glib

// #include <gio/gio.h>
// #include <glib.h>
// #include <glib-object.h>
// #include "glib.go.h"
import "C"
import "unsafe"

// Permission is a representation of GIO's GPermission.
type Permission struct {
	*Object
}

// Native returns a pointer to the underlying GPermission.
func (v *Permission) Native() *C.GPermission {
	if v == nil || v.GObject == nil {
		return nil
	}
	return C.toGPermission(unsafe.Pointer(v.GObject))
}

func marshalPermission(p uintptr) (interface{}, error) {
	c := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))
	return wrapPermission(wrapObject(unsafe.Pointer(c))), nil
}

func wrapPermission(obj *Object) *Permission {
	return &Permission{obj}
}

func WrapPermission(ptr unsafe.Pointer) *Permission {
	return &Permission{wrapObject(ptr)}
}

// GetAllowed is a wrapper around g_permission_get_allowed().
func (v *Permission) GetAllowed() bool {
	c := C.g_permission_get_allowed(v.Native())
	return gobool(c)
}

// GetCanAcquire is a wrapper around g_permission_get_can_acquire().
func (v *Permission) GetCanAcquire() bool {
	c := C.g_permission_get_can_acquire(v.Native())
	return gobool(c)
}

// GetCanRelease is a wrapper around g_permission_get_can_release().
func (v *Permission) GetCanRelease() bool {
	c := C.g_permission_get_can_release(v.Native())
	return gobool(c)
}

// Acquire is a wrapper around g_permission_acquire().
// func (v *Permission) Acquire(cancellable *Cancellable) error {
// 	var err *C.GError
// 	c := C.g_permission_acquire(v.Native(), cancellable.Native(), &err)
// 	acquired := gobool(c)
// 	if !acquired {
// 		defer C.g_error_free(err)
// 		return errors.New(C.GoString((*C.char)(err.message)))
// 	}
// 	return nil
// }

// AcquireAsync is a wrapper around g_permission_acquire_async().
// func (v *Permission) AcquireAsync(cancellable *Cancellable, callback AsyncReadyCallback, data uintptr) {
// 	C.g_permission_acquire_async(v.Native(), cancellable.Native(), , C.gpointer(data))
// }

// AcquireFinish is a wrapper around g_permission_acquire_finish().
// func (v *Permission) AcquireFinish(result *AsyncResult) error {
// 	var err *C.GError
// 	c := C.g_permission_acquire_finish(v.Native(), , &err)
// 	acquired := gobool(c)
// 	if !acquired {
// 		defer C.g_error_free(err)
// 		return errors.New(C.GoString((*C.char)(err.message)))
// 	}
// 	return nil
// }

// Release is a wrapper around g_permission_release().
// func (v *Permission) Release(cancellable *Cancellable) error {
// 	var err *C.GError
// 	c := C.g_permission_release(v.Native(), cancellable.Native(), &err)
// 	released := gobool(c)
// 	if !released {
// 		defer C.g_error_free(err)
// 		return errors.New(C.GoString((*C.char)(err.message)))
// 	}
// 	return nil
// }

// ReleaseAsync is a wrapper around g_permission_release_async().
// func (v *Permission) ReleaseAsync(cancellable *Cancellable, callback AsyncReadyCallback, data uintptr) {
// 	C.g_permission_release_async(v.Native(), cancellable.Native(), , C.gpointer(data))
// }

// ReleaseFinish is a wrapper around g_permission_release_finish().
// func (v *Permission) ReleaseFinish(result *AsyncResult) error {
// 	var err *C.GError
// 	c := C.g_permission_release_finish(v.Native(), , &err)
// 	released := gobool(c)
// 	if !released {
// 		defer C.g_error_free(err)
// 		return errors.New(C.GoString((*C.char)(err.message)))
// 	}
// 	return nil
// }

// ImplUpdate is a wrapper around g_permission_impl_update().
func (v *Permission) ImplUpdate(allowed, canAcquire, canRelease bool) {
	C.g_permission_impl_update(v.Native(), gbool(allowed), gbool(canAcquire), gbool(canRelease))
}
<commit_msg>adding GPermission bindings<commit_after>package glib

// #include <gio/gio.h>
// #include <glib.h>
// #include <glib-object.h>
// #include "glib.go.h"
import "C"
import "unsafe"

// Permission is a representation of GIO's GPermission.
type Permission struct {
	*Object
}

// Native returns a pointer to the underlying GPermission.
func (v *Permission) Native() *C.GPermission {
	if v == nil || v.GObject == nil {
		return nil
	}
	return C.toGPermission(unsafe.Pointer(v.GObject))
}

func marshalPermission(p uintptr) (interface{}, error) {
	c := C.g_value_get_object((*C.GValue)(unsafe.Pointer(p)))
	return wrapPermission(wrapObject(unsafe.Pointer(c))), nil
}

func wrapPermission(obj *Object) *Permission {
	return &Permission{obj}
}

func WrapPermission(ptr unsafe.Pointer) *Permission {
	return &Permission{wrapObject(ptr)}
}

// GetAllowed is a wrapper around g_permission_get_allowed().
func (v *Permission) GetAllowed() bool {
	c := C.g_permission_get_allowed(v.Native())
	return gobool(c)
}

// GetCanAcquire is a wrapper around g_permission_get_can_acquire().
func (v *Permission) GetCanAcquire() bool {
	c := C.g_permission_get_can_acquire(v.Native())
	return gobool(c)
}

// GetCanRelease is a wrapper around g_permission_get_can_release().
func (v *Permission) GetCanRelease() bool {
	c := C.g_permission_get_can_release(v.Native())
	return gobool(c)
}

// Acquire is a wrapper around g_permission_acquire().
func (v *Permission) Acquire(cancellable *Cancellable) error {
	var err *C.GError
	c := C.g_permission_acquire(v.Native(), cancellable.native(), &err)
	acquired := gobool(c)
	if !acquired {
		defer C.g_error_free(err)
		return errors.New(C.GoString((*C.char)(err.message)))
	}
	return nil
}

// AcquireAsync is a wrapper around g_permission_acquire_async().
// func (v *Permission) AcquireAsync(cancellable *Cancellable, callback AsyncReadyCallback, data uintptr) {
// 	C.g_permission_acquire_async(v.Native(), cancellable.native(), , C.gpointer(data))
// }

// AcquireFinish is a wrapper around g_permission_acquire_finish().
// func (v *Permission) AcquireFinish(result *AsyncResult) error {
// 	var err *C.GError
// 	c := C.g_permission_acquire_finish(v.Native(), , &err)
// 	acquired := gobool(c)
// 	if !acquired {
// 		defer C.g_error_free(err)
// 		return errors.New(C.GoString((*C.char)(err.message)))
// 	}
// 	return nil
// }

// Release is a wrapper around g_permission_release().
func (v *Permission) Release(cancellable *Cancellable) error {
	var err *C.GError
	c := C.g_permission_release(v.Native(), cancellable.native(), &err)
	released := gobool(c)
	if !released {
		defer C.g_error_free(err)
		return errors.New(C.GoString((*C.char)(err.message)))
	}
	return nil
}

// ReleaseAsync is a wrapper around g_permission_release_async().
// func (v *Permission) ReleaseAsync(cancellable *Cancellable, callback AsyncReadyCallback, data uintptr) {
// 	C.g_permission_release_async(v.Native(), cancellable.native(), , C.gpointer(data))
// }

// ReleaseFinish is a wrapper around g_permission_release_finish().
// func (v *Permission) ReleaseFinish(result *AsyncResult) error {
// 	var err *C.GError
// 	c := C.g_permission_release_finish(v.Native(), , &err)
// 	released := gobool(c)
// 	if !released {
// 		defer C.g_error_free(err)
// 		return errors.New(C.GoString((*C.char)(err.message)))
// 	}
// 	return nil
// }

// ImplUpdate is a wrapper around g_permission_impl_update().
func (v *Permission) ImplUpdate(allowed, canAcquire, canRelease bool) {
	C.g_permission_impl_update(v.Native(), gbool(allowed), gbool(canAcquire), gbool(canRelease))
}
<|endoftext|>


<commit_before>// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package libkb

// Version is the current version (should be MAJOR.MINOR.PATCH)
const Version = "1.0.31"
<commit_msg>Bump version<commit_after>// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package libkb

// Version is the current version (should be MAJOR.MINOR.PATCH)
const Version = "1.0.32"
<|endoftext|>


<commit_before>package libkb

import (
	"fmt"
)

// NOTE: This file is the source of truth for our version number, but we have a
//       script that reads it at packaging/version.sh. If you refactor this
//       file, update that script.

// Version as MAJOR.MINOR.PATCH
const Version = "1.0.0"

// Build number
const Build = "25"

// VersionString returns semantic version string.
func VersionString() string {
	return fmt.Sprintf("%s-%s", Version, Build)
}
<commit_msg>New version 1.0.0-26<commit_after>package libkb

import (
	"fmt"
)

// NOTE: This file is the source of truth for our version number, but we have a
//       script that reads it at packaging/version.sh. If you refactor this
//       file, update that script.

// Version as MAJOR.MINOR.PATCH
const Version = "1.0.0"

// Build number
const Build = "26"

// VersionString returns semantic version string.
func VersionString() string {
	return fmt.Sprintf("%s-%s", Version, Build)
}
<|endoftext|>


<commit_before>package models

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

type Config struct {
	Color           bool
	Demangle        bool
	ForceBase       uint64
	ForceInterpBase uint64
	LoadPrefix      string
	LoopCollapse    int
	TraceExec       bool
	TraceMatch      []string
	TraceMatchDepth int
	TraceMem        bool
	TraceMemBatch   bool
	TraceReg        bool
	TraceSys        bool
	Verbose         bool
	Strsize         int

	PrefixArgs []string
}

func (c *Config) PrefixPath(path string, force bool) string {
	if c.LoadPrefix == "" {
		return path
	}
	if filepath.IsAbs(path) {
		target := filepath.Join(c.LoadPrefix, path)
		link, err := os.Lstat(target)
		if err == nil && link.Mode()&os.ModeSymlink != 0 {
			path, err := os.Readlink(target)
			if err == nil {
				if !strings.HasPrefix(path, "/") {
					path = filepath.Join(filepath.Dir(target), path)
				}
				return c.PrefixPath(path, force)
			}
		}
		exists := !os.IsNotExist(err)
		if force || exists {
			return target
		}
	} else {
		link, err := os.Lstat(path)
		if err == nil && link.Mode()&os.ModeSymlink != 0 {
			if linked, err := os.Readlink(path); err != nil {
				if !strings.HasPrefix(linked, "/") {
					linked = filepath.Join(filepath.Dir(path), linked)
				}
				return c.PrefixPath(linked, force)
			}
		}
	}
	return path
}
<commit_msg>tweak symlink resolving<commit_after>package models

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

type Config struct {
	Color           bool
	Demangle        bool
	ForceBase       uint64
	ForceInterpBase uint64
	LoadPrefix      string
	LoopCollapse    int
	TraceExec       bool
	TraceMatch      []string
	TraceMatchDepth int
	TraceMem        bool
	TraceMemBatch   bool
	TraceReg        bool
	TraceSys        bool
	Verbose         bool
	Strsize         int

	PrefixArgs []string
}

func (c *Config) resolveSymlink(path, target string, force bool) string {
	link, err := os.Lstat(path)
	if err == nil && link.Mode()&os.ModeSymlink != 0 {
		if linked, err := os.Readlink(path); err != nil {
			if !strings.HasPrefix(linked, "/") {
				linked = filepath.Join(filepath.Dir(path), linked)
				return c.PrefixPath(path, false)
			}
			return c.PrefixPath(linked, force)
		}
	}
	exists := !os.IsNotExist(err)
	if force || exists {
		return target
	}
	return path
}

func (c *Config) PrefixPath(path string, force bool) string {
	if c.LoadPrefix == "" {
		return path
	}
	target := path
	if filepath.IsAbs(path) {
		target = filepath.Join(c.LoadPrefix, path)
	}
	return c.resolveSymlink(path, target, force)
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package definition

import (
	"errors"
	"fmt"
	"net"
	"unicode/utf8"
)

// Network ...
type Network struct {
	Name   string `json:"name"`
	Subnet string `json:"subnet"`
	Public bool   `json:"public"`
}

// Validate checks if a Network is valid
func (n *Network) Validate() error {
	_, _, err := net.ParseCIDR(n.Subnet)
	if err != nil {
		return errors.New("Network CIDR is not valid")
	}

	if n.Name == "" {
		return errors.New("Network name should not be null")
	}

	// Check if network name is > 50 characters
	if utf8.RuneCountInString(n.Name) > AWSMAXNAME {
		return fmt.Errorf("Network name can't be greater than %d characters", AWSMAXNAME)
	}

	return nil
}
<commit_msg>adding additional field to specify a nat gateway for a network<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package definition

import (
	"errors"
	"fmt"
	"net"
	"unicode/utf8"
)

// Network ...
type Network struct {
	Name       string `json:"name"`
	Subnet     string `json:"subnet"`
	Public     bool   `json:"public"`
	NatGateway string `json:"nat_gateway"`
}

// Validate checks if a Network is valid
func (n *Network) Validate() error {
	_, _, err := net.ParseCIDR(n.Subnet)
	if err != nil {
		return errors.New("Network CIDR is not valid")
	}

	if n.Name == "" {
		return errors.New("Network name should not be null")
	}

	// Check if network name is > 50 characters
	if utf8.RuneCountInString(n.Name) > AWSMAXNAME {
		return fmt.Errorf("Network name can't be greater than %d characters", AWSMAXNAME)
	}

	if n.Public && n.NatGateway != "" {
		return errors.New("Public Network should not specify a nat gateway")
	}

	return nil
}
<|endoftext|>


<commit_before>package dstruc

import (
	"fmt"
	"reflect"
)

func u1() {
	points := [][2]int{{4, 6}, {}, {-7, 11}, {15, 17}, {14, -8}}
	for _, point := range points {
		fmt.Printf(" (%d %d)\n", point[0], point[1])
	}
	points2 := []struct{ x, y int }{{4, 6}, {}, {-7, 11}, {15, 17}, {14, -8}}
	for _, point := range points2 {
		fmt.Printf(" (x, y) is (%d %d)\n", point.x, point.y)
	}
}

type Person struct {
	Title     string
	Forenames []string
	Surename  string
}

type Author struct {
	Names Person
	Title []string
	Yob   int
}

// Union test union struct
func Union() {
	author1 := Author{
		Person{" Mr ", []string{"Robert", " Louis", " Balfour"}, "Stevenson"},
		[]string{" Kidnapped ", " Treasure Island "},
		1850}
	fmt.Println("Author1 is ", author1)
	author1.Names.Title = ""
	author1.Names.Forenames = []string{" Oscar ", " Fingal ", " O'Flahertie ", " Wills"}
	author1.Names.Surename = " Wilde "
	author1.Title = []string{" The Picture of  Dorian Gray "}
	author1.Yob += 4
	fmt.Println("Modified Author1 is ", author1)
}

type Author2 struct {
	Person
	Title []string
	Yob   int
}

func Union2() {

	author2 := Author2{
		Person{" Mr ", []string{"Robert", " Louis", " Balfour"}, "Stevenson"},
		[]string{" Kidnapped ", " Treasure Island "},
		1850}
	fmt.Println("author2 is ", author2)
	author2.Title = []string{" The Picture of  Dorian Gray "}
	author2.Person.Title = ""
	author2.Forenames = []string{" Oscar ", " Fingal ", " O'Flahertie ", " Wills"}
	author2.Surename = " Wilde "
	author2.Yob += 4
	fmt.Println(author2)
	tstruct := tranStruct(author2)
	fmt.Println("Author1 ", tstruct.Surename)

}

func tranStruct(i interface{}) Author2 {
	v := reflect.ValueOf(i)
	fmt.Printf("Reflect test %v |\n", v)
	if value, ok := i.(Author); ok {
		fmt.Printf("Interface %v is struct Author2.\n", value)
	} else {
		fmt.Printf("Interface %v is not struct Author.\n", i)
	}
	val := i.(Author2)
	return val
}

type Tasks struct {
	slice []string
	Count
}
type Count struct{ X int }

func (tasks *Tasks) Add(task string) {
	tasks.slice = append(tasks.slice, task)

}
<commit_msg>Toger#More type method from package reflect<commit_after>package dstruc

import (
	"fmt"
	"reflect"
)

func u1() {
	points := [][2]int{{4, 6}, {}, {-7, 11}, {15, 17}, {14, -8}}
	for _, point := range points {
		fmt.Printf(" (%d %d)\n", point[0], point[1])
	}
	points2 := []struct{ x, y int }{{4, 6}, {}, {-7, 11}, {15, 17}, {14, -8}}
	for _, point := range points2 {
		fmt.Printf(" (x, y) is (%d %d)\n", point.x, point.y)
	}
}

type Person struct {
	Title     string
	Forenames []string
	Surename  string
}

type Author struct {
	Names Person
	Title []string
	Yob   int
}

// Union test union struct
func Union() {
	author1 := Author{
		Person{" Mr ", []string{"Robert", " Louis", " Balfour"}, "Stevenson"},
		[]string{" Kidnapped ", " Treasure Island "},
		1850}
	fmt.Println("Author1 is ", author1)
	author1.Names.Title = ""
	author1.Names.Forenames = []string{" Oscar ", " Fingal ", " O'Flahertie ", " Wills"}
	author1.Names.Surename = " Wilde "
	author1.Title = []string{" The Picture of  Dorian Gray "}
	author1.Yob += 4
	fmt.Println("Modified Author1 is ", author1)
}

type Author2 struct {
	Person
	Title []string
	Yob   int
}

func Union2() {

	author2 := Author2{
		Person{" Mr ", []string{"Robert", " Louis", " Balfour"}, "Stevenson"},
		[]string{" Kidnapped ", " Treasure Island "},
		1850}
	fmt.Println("author2 is ", author2)
	author2.Title = []string{" The Picture of  Dorian Gray "}
	author2.Person.Title = ""
	author2.Forenames = []string{" Oscar ", " Fingal ", " O'Flahertie ", " Wills"}
	author2.Surename = " Wilde "
	author2.Yob += 4
	fmt.Println(author2)
	tstruct := tranStruct(author2)
	fmt.Println("Author1 ", tstruct.Surename)

}

func tranStruct(i interface{}) Author2 {
	v := reflect.ValueOf(i)
	fmt.Printf("Elem of interface i is %v |\n", reflect.ValueOf(&v).Elem())
	fmt.Printf("Kind of interface i is %v |\n", v.Kind())
	fmt.Printf("Type of interface i is %v |\n", v.Type())
	if value, ok := i.(Author); ok {
		fmt.Printf("Interface %v is struct Author2.\n", value)
	} else {
		fmt.Printf("Interface %v is not struct Author.\n", i)
	}
	val := i.(Author2)
	return val
}

type Tasks struct {
	slice []string
	Count
}
type Count struct{ X int }

func (tasks *Tasks) Add(task string) {
	tasks.slice = append(tasks.slice, task)

}
<|endoftext|>


<commit_before>package cockroach

import (
	"database/sql"
	"net/url"
	"strings"

	_ "github.com/go-sql-driver/mysql"
	"github.com/micro/go-micro/errors"
	"github.com/micro/go-micro/store"
	roachStore "github.com/micro/go-micro/store/cockroach"
	"github.com/micro/go-micro/util/log"
	"github.com/micro/micro/config/db"
)

var (
	defaultUrl    = "postgres://postgres:@172.17.153.138:5432/postgres?search_path=public&sslmode=disable"
	defaultSchema = "public"
)

type cockroach struct {
	db *sql.DB
	st store.Store
}

func init() {
	db.Register(new(cockroach))
}

func (m *cockroach) Init(opts db.Options) error {
	var err error
	defer func() {
		if err != nil {
			log.Fatal(err)
		}
	}()

	var d *sql.DB

	if opts.Url != "" {
		defaultUrl = opts.Url
	}

	u, _ := url.Parse(defaultUrl)
	parts := strings.Split(u.Path, "/")
	if len(parts) != 2 {
		err = errors.InternalServerError("go.micro.config.Init", "Invalid database url for cockroach: %s", u.Path)
		return err
	}

	schema := u.Query().Get("search_path")
	if len(schema) == 0 {
		err = errors.InternalServerError("go.micro.config.Init", "needs a schema with search_path")
		return err
	}

	m.db = d
	m.st = roachStore.NewStore(
		store.Nodes(opts.Url),
		store.Namespace(schema))

	return nil
}

func (m *cockroach) Create(record *store.Record) error {
	return m.st.Write(record)
}

func (m *cockroach) Read(key string) (*store.Record, error) {
	s, err := m.st.Read(key)
	if err != nil {
		return nil, err
	}

	return s[0], nil
}

func (m *cockroach) Delete(key string) error {
	return m.st.Delete(key)
}

func (m *cockroach) Update(record *store.Record) error {
	return m.st.Write(record)
}

func (m *cockroach) List(opts ...db.ListOption) ([]*store.Record, error) {
	return m.st.List()
}

func (m *cockroach) String() string {
	return "cockroach"
}
<commit_msg>update cockroach url<commit_after>package cockroach

import (
	"database/sql"
	"net/url"
	"strings"

	_ "github.com/go-sql-driver/mysql"
	"github.com/micro/go-micro/errors"
	"github.com/micro/go-micro/store"
	roachStore "github.com/micro/go-micro/store/cockroach"
	"github.com/micro/go-micro/util/log"
	"github.com/micro/micro/config/db"
)

var (
	defaultUrl    = "postgres://root:@127.0.0.1:26257/micro?search_path=config"
)

type cockroach struct {
	db *sql.DB
	st store.Store
}

func init() {
	db.Register(new(cockroach))
}

func (m *cockroach) Init(opts db.Options) error {
	var err error
	defer func() {
		if err != nil {
			log.Fatal(err)
		}
	}()

	var d *sql.DB

	if opts.Url != "" {
		defaultUrl = opts.Url
	}

	u, _ := url.Parse(defaultUrl)
	parts := strings.Split(u.Path, "/")
	if len(parts) != 2 {
		err = errors.InternalServerError("go.micro.config.Init", "Invalid database url for cockroach: %s", u.Path)
		return err
	}

	schema := u.Query().Get("search_path")
	if len(schema) == 0 {
		err = errors.InternalServerError("go.micro.config.Init", "needs a schema with search_path")
		return err
	}

	m.db = d
	m.st = roachStore.NewStore(
		store.Nodes(opts.Url),
		store.Namespace(schema))

	return nil
}

func (m *cockroach) Create(record *store.Record) error {
	return m.st.Write(record)
}

func (m *cockroach) Read(key string) (*store.Record, error) {
	s, err := m.st.Read(key)
	if err != nil {
		return nil, err
	}

	return s[0], nil
}

func (m *cockroach) Delete(key string) error {
	return m.st.Delete(key)
}

func (m *cockroach) Update(record *store.Record) error {
	return m.st.Write(record)
}

func (m *cockroach) List(opts ...db.ListOption) ([]*store.Record, error) {
	return m.st.List()
}

func (m *cockroach) String() string {
	return "cockroach"
}
<|endoftext|>


<commit_before>// A cron app that will my cron jobs.

package main

import (
	"bufio"
	"regexp"
	"flag"
	"log"
	"os/exec"
	"io"
	"os"
	"strings"
	"io/ioutil"

	"github.com/robfig/cron"
)

var (
	debugMode = flag.Bool("debug", false, "Enable debug logging.")
	configPath = flag.String("conf", "/crontab", "Path to the crontab config.")
)

var (
    Debug   *log.Logger
    Info    *log.Logger
    Warning *log.Logger
    Error   *log.Logger
    Fatal   *log.Logger
)

// Initializes logging. Logging is done to stdout (< ERROR) and sterr (>= ERROR)
// Fatal error messages should use Fatal.Fatal()
func initLogging(d, i, w, e, f io.Writer) {
    Debug = log.New(d, "[DEBUG] ", log.Ldate|log.Ltime|log.Lshortfile)
    Info = log.New(i,   "[INFO]  ", log.Ldate|log.Ltime|log.Lshortfile)
    Warning = log.New(w, "[WARN]  ", log.Ldate|log.Ltime|log.Lshortfile)
    Error = log.New(e, "[ERROR] ", log.Ldate|log.Ltime|log.Lshortfile)
    Fatal = log.New(f, "[FATAL] ", log.Ldate|log.Ltime|log.Lshortfile)
}

// Creates a function that runs a command.
func createCmdFunc(cmd string, args []string) func() {
	return func() {
		c := exec.Command(cmd, args...)
		Info.Println("Running:", cmd, strings.Join(args, " "))
		o, err := c.CombinedOutput()
		if len(o) > 0 {
			Debug.Println(string(o))
		}
		if err != nil {
			Error.Println(err)
			return
		}
		Info.Println("Completed:", cmd, strings.Join(args, " "))
		Debug.Println(string(o))
	}
}

// Parses the config file and starts the server.
func startCron() error {
	c, err := os.Open(*configPath)
	if err != nil {
		return err
	}
	defer c.Close()

	server := cron.New()

	scanner := bufio.NewScanner(c)

	r := regexp.MustCompile("\\s")

	for scanner.Scan() {
		line := r.Split(strings.Trim(scanner.Text(), " \t"), -1)

		var sched, cmd string
		var args []string
		if strings.HasPrefix(line[0], "@every") {
			sched = strings.Join(line[:2], " ")
			cmd = line[2]
			args = line[3:]
		} else if strings.HasPrefix(line[0], "@") {
			sched = line[0]
			cmd = line[1]
			args = line[2:]
		} else {
			sched = strings.Join(line[:5], " ")
			cmd = line[5]
			args = line[6:]
		}

		// Make the schedule have minute not second resolution.
		server.AddFunc("0 " + sched, createCmdFunc(cmd, args))
	}

	server.Start()

	return nil
}

func main() {
	flag.Parse()

	debug := ioutil.Discard
	if *debugMode {
		debug = os.Stdout
	}

	initLogging(debug, os.Stdout, os.Stdout, os.Stderr, os.Stderr)

	err := startCron()
	if err != nil {
		Error.Fatal("Could not start cron:", err)
	}

	select{}
}
<commit_msg>gofmt on gocron/main.go<commit_after>// A cron app that will my cron jobs.

package main

import (
	"bufio"
	"flag"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"regexp"
	"strings"

	"github.com/robfig/cron"
)

var (
	debugMode  = flag.Bool("debug", false, "Enable debug logging.")
	configPath = flag.String("conf", "/crontab", "Path to the crontab config.")
)

var (
	Debug   *log.Logger
	Info    *log.Logger
	Warning *log.Logger
	Error   *log.Logger
	Fatal   *log.Logger
)

// Initializes logging. Logging is done to stdout (< ERROR) and sterr (>= ERROR)
// Fatal error messages should use Fatal.Fatal()
func initLogging(d, i, w, e, f io.Writer) {
	Debug = log.New(d, "[DEBUG] ", log.Ldate|log.Ltime|log.Lshortfile)
	Info = log.New(i, "[INFO]  ", log.Ldate|log.Ltime|log.Lshortfile)
	Warning = log.New(w, "[WARN]  ", log.Ldate|log.Ltime|log.Lshortfile)
	Error = log.New(e, "[ERROR] ", log.Ldate|log.Ltime|log.Lshortfile)
	Fatal = log.New(f, "[FATAL] ", log.Ldate|log.Ltime|log.Lshortfile)
}

// Creates a function that runs a command.
func createCmdFunc(cmd string, args []string) func() {
	return func() {
		c := exec.Command(cmd, args...)
		Info.Println("Running:", cmd, strings.Join(args, " "))
		o, err := c.CombinedOutput()
		if len(o) > 0 {
			Debug.Println(string(o))
		}
		if err != nil {
			Error.Println(err)
			return
		}
		Info.Println("Completed:", cmd, strings.Join(args, " "))
		Debug.Println(string(o))
	}
}

// Parses the config file and starts the server.
func startCron() error {
	c, err := os.Open(*configPath)
	if err != nil {
		return err
	}
	defer c.Close()

	server := cron.New()

	scanner := bufio.NewScanner(c)

	r := regexp.MustCompile("\\s")

	for scanner.Scan() {
		line := r.Split(strings.Trim(scanner.Text(), " \t"), -1)

		var sched, cmd string
		var args []string
		if strings.HasPrefix(line[0], "@every") {
			sched = strings.Join(line[:2], " ")
			cmd = line[2]
			args = line[3:]
		} else if strings.HasPrefix(line[0], "@") {
			sched = line[0]
			cmd = line[1]
			args = line[2:]
		} else {
			sched = strings.Join(line[:5], " ")
			cmd = line[5]
			args = line[6:]
		}

		// Make the schedule have minute not second resolution.
		server.AddFunc("0 "+sched, createCmdFunc(cmd, args))
	}

	server.Start()

	return nil
}

func main() {
	flag.Parse()

	debug := ioutil.Discard
	if *debugMode {
		debug = os.Stdout
	}

	initLogging(debug, os.Stdout, os.Stdout, os.Stderr, os.Stderr)

	err := startCron()
	if err != nil {
		Error.Fatal("Could not start cron:", err)
	}

	select {}
}
<|endoftext|>


<commit_before>package loop_objects

import (
	"math"

	"github.com/phil-mansfield/gotetra/math/rand"
	"github.com/phil-mansfield/gotetra/los/geom"
	rgeom "github.com/phil-mansfield/gotetra/render/geom"
	"github.com/phil-mansfield/gotetra/los/main/gtet_util/loop"
)

type Profile struct {
	loop.Sphere // Handles intersection checks.
	R0 [3]float64
	RMin, RMax float64
	Counts []float64

	dlr, lrMin, rMin2, rMax2 float64

	vecBuf []rgeom.Vec
	randBuf []float64
	gen *rand.Generator

	ptRad float64
	pts int
}

// type-checking
var (
	_ loop.Object = &Profile{}
)

func NewParticleProfile(
	r0 [3]float64, rMin, rMax float64, rBins int,
) *Profile {
	return newProfile(r0, rMin, rMax, rBins, 0, -1)
}

func NewTetraProfile(
	r0 [3]float64, rMin, rMax float64, rBins, pts int,
) *Profile {
	return newProfile(r0, rMin, rMax, rBins, pts, -1)
}

func NewSphereProfile(
	r0 [3]float64, rMin, rMax float64, rBins, pts int, ptRad float64,
) *Profile {
	return newProfile(r0, rMin, rMax, rBins, pts, ptRad)
}

func newProfile(
	r0 [3]float64, rMin, rMax float64, rBins, pts int, ptRad float64,
) *Profile {
	p := &Profile{}

	p.Sphere.Init(r0, rMin, rMax)
	p.R0 = r0
	p.RMin = rMin
	p.RMax = rMax

	p.Counts = make([]float64, rBins)
	p.dlr = (math.Log(p.RMax) - math.Log(p.RMin)) / float64(len(p.Counts))
	p.lrMin = math.Log(p.RMin)
	p.rMin2 = p.RMin * p.RMin
	p.rMax2 = p.RMax * p.RMax

	if ptRad < 0 && pts > 0 {
		tetPts := int(math.Ceil(float64(pts*pts*pts) / 6))
		p.vecBuf = make([]rgeom.Vec, tetPts)
		p.randBuf = make([]float64, 3*tetPts)
		p.gen = rand.NewTimeSeed(rand.Xorshift)
	} else if ptRad > 0 && pts > 0 {
		p.gen = rand.NewTimeSeed(rand.Xorshift)
		p.pts = pts
		p.ptRad = ptRad
	}

	return p
}

func (p *Profile) ThreadCopy(id, threads int) loop.Object {
	panic("NYI")
}

func (p *Profile) ThreadMerge(objs []loop.Object) {
	panic("NYI")
}

func (p *Profile) UsePoint(x, y, z float64) {
	if p.ptRad > 0 {
		p.useSphere(x, y, z)
	} else {
		p.usePoint(x, y, z)
	}
}

func (p *Profile) usePoint(x, y, z float64) {
	x0, y0, z0 := p.R0[0], p.R0[1], p.R0[2]
	dx, dy, dz := x - x0, y - y0, z - z0
	r2 := dx*dx + dy*dy + dz*dz
	if r2 <= p.rMin2 || r2 >= p.rMax2 { return }
	lr := math.Log(r2) / 2
	ir := int(((lr) - p.lrMin) / p.dlr)
	p.Counts[ir]++
}

func (p *Profile) useSphere(x, y, z float64) {
	n := 0
	for n < p.pts {
		px := p.gen.Uniform(-1, +1)
		py := p.gen.Uniform(-1, +1)
		pz := p.gen.Uniform(-1, +1)

		if x*2 + y*y + z*z > p.ptRad*p.ptRad { continue }
		p.usePoint(x + px, y + py, z + pz)
		n++
	}
}

func (p *Profile) UseTetra(t *geom.Tetra) {
	tet := &rgeom.Tetra{}
	t0, t1 := rgeom.Vec(t[0]), rgeom.Vec(t[1])
	t2, t3 := rgeom.Vec(t[2]), rgeom.Vec(t[3])
	tet.Init(&t0, &t1, &t2, &t3)
	tet.RandomSample(p.gen, p.randBuf, p.vecBuf)

	for _, pt := range p.vecBuf {
		x, y, z := float64(pt[0]), float64(pt[1]), float64(pt[2])
		p.UsePoint(x, y, z)
	}
}

func (p *Profile) Params() loop.Params {
	return loop.Params{
		UsesTetra: len(p.vecBuf) != 0,
	}
}
<commit_msg>Added sphereical kernel profiles to gtet_prof.go<commit_after>package loop_objects

import (
	"math"

	"github.com/phil-mansfield/gotetra/math/rand"
	"github.com/phil-mansfield/gotetra/los/geom"
	rgeom "github.com/phil-mansfield/gotetra/render/geom"
	"github.com/phil-mansfield/gotetra/los/main/gtet_util/loop"
)

type Profile struct {
	loop.Sphere // Handles intersection checks.
	R0 [3]float64
	RMin, RMax float64
	Counts []float64

	dlr, lrMin, rMin2, rMax2 float64

	vecBuf []rgeom.Vec
	randBuf []float64
	gen *rand.Generator

	ptRad float64
	pts int
}

// type-checking
var (
	_ loop.Object = &Profile{}
)

func NewParticleProfile(
	r0 [3]float64, rMin, rMax float64, rBins int,
) *Profile {
	return newProfile(r0, rMin, rMax, rBins, 0, -1)
}

func NewTetraProfile(
	r0 [3]float64, rMin, rMax float64, rBins, pts int,
) *Profile {
	return newProfile(r0, rMin, rMax, rBins, pts, -1)
}

func NewSphereProfile(
	r0 [3]float64, rMin, rMax float64, rBins, pts int, ptRad float64,
) *Profile {
	return newProfile(r0, rMin, rMax, rBins, pts, ptRad)
}

func newProfile(
	r0 [3]float64, rMin, rMax float64, rBins, pts int, ptRad float64,
) *Profile {
	p := &Profile{}

	p.Sphere.Init(r0, rMin, rMax)
	p.R0 = r0
	p.RMin = rMin
	p.RMax = rMax

	p.Counts = make([]float64, rBins)
	p.dlr = (math.Log(p.RMax) - math.Log(p.RMin)) / float64(len(p.Counts))
	p.lrMin = math.Log(p.RMin)
	p.rMin2 = p.RMin * p.RMin
	p.rMax2 = p.RMax * p.RMax

	if ptRad < 0 && pts > 0 {
		tetPts := int(math.Ceil(float64(pts*pts*pts) / 6))
		p.vecBuf = make([]rgeom.Vec, tetPts)
		p.randBuf = make([]float64, 3*tetPts)
		p.gen = rand.NewTimeSeed(rand.Xorshift)
	} else if ptRad > 0 && pts > 0 {
		p.gen = rand.NewTimeSeed(rand.Xorshift)
		p.pts = pts*pts*pts
		p.ptRad = ptRad
	}

	return p
}

func (p *Profile) ThreadCopy(id, threads int) loop.Object {
	panic("NYI")
}

func (p *Profile) ThreadMerge(objs []loop.Object) {
	panic("NYI")
}

func (p *Profile) UsePoint(x, y, z float64) {
	if p.ptRad > 0 {
		p.useSphere(x, y, z)
	} else {
		p.usePoint(x, y, z)
	}
}

func (p *Profile) usePoint(x, y, z float64) {
	x0, y0, z0 := p.R0[0], p.R0[1], p.R0[2]
	dx, dy, dz := x - x0, y - y0, z - z0
	r2 := dx*dx + dy*dy + dz*dz
	if r2 <= p.rMin2 || r2 >= p.rMax2 { return }
	lr := math.Log(r2) / 2
	ir := int(((lr) - p.lrMin) / p.dlr)
	p.Counts[ir]++
}

func (p *Profile) useSphere(x, y, z float64) {
	n := 0
	for n < p.pts {
		px := p.gen.Uniform(-1, +1)
		py := p.gen.Uniform(-1, +1)
		pz := p.gen.Uniform(-1, +1)

		if x*2 + y*y + z*z > p.ptRad*p.ptRad { continue }
		p.usePoint(x + px, y + py, z + pz)
		n++
	}
}

func (p *Profile) UseTetra(t *geom.Tetra) {
	tet := &rgeom.Tetra{}
	t0, t1 := rgeom.Vec(t[0]), rgeom.Vec(t[1])
	t2, t3 := rgeom.Vec(t[2]), rgeom.Vec(t[3])
	tet.Init(&t0, &t1, &t2, &t3)
	tet.RandomSample(p.gen, p.randBuf, p.vecBuf)

	for _, pt := range p.vecBuf {
		x, y, z := float64(pt[0]), float64(pt[1]), float64(pt[2])
		p.UsePoint(x, y, z)
	}
}

func (p *Profile) Params() loop.Params {
	return loop.Params{
		UsesTetra: len(p.vecBuf) != 0,
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"math/rand"
	"os"
)

var (
	numRead int
	readLen int
	numGene int
	geneLen int

	reads []string
)

func generateReads() {

	fid, err := os.Create("reads.fastq")
	if err != nil {
		panic(err)
	}
	defer fid.Close()

	var buf bytes.Buffer

	for i := 0; i < numRead; i++ {
		fid.WriteString(fmt.Sprintf("read_%d\n", i))

		buf.Reset()
		for j := 0; j < readLen; j++ {
			x := rand.Float64()
			switch {
			case x < 0.25:
				buf.Write([]byte("A"))
			case x < 0.5:
				buf.Write([]byte("T"))
			case x < 0.75:
				buf.Write([]byte("G"))
			default:
				buf.Write([]byte("C"))
			}
		}
		fid.Write(buf.Bytes())

		if i < 10 {
			reads = append(reads, string(buf.Bytes()))
		}

		fid.WriteString("\n+\n")
		for j := 0; j < readLen; j++ {
			fid.WriteString("!")
		}
		fid.WriteString("\n")
	}
}

func writeRand(w io.Writer, n int) {

	for j := 0; j < n; j++ {
		x := rand.Float64()
		switch {
		case x < 0.25:
			w.Write([]byte("A"))
		case x < 0.5:
			w.Write([]byte("T"))
		case x < 0.75:
			w.Write([]byte("G"))
		default:
			w.Write([]byte("C"))
		}
	}
}

func generateGenes() {

	fid, err := os.Create("genes.txt")
	if err != nil {
		panic(err)
	}
	defer fid.Close()

	for i := 0; i < numGene; i++ {
		fid.WriteString(fmt.Sprintf("gene_%d\t", i))

		if i < len(reads) {
			writeRand(fid, i)
			fid.WriteString(reads[i])
			writeRand(fid, geneLen-(readLen+i))
		} else {
			writeRand(fid, geneLen)
		}
		fid.WriteString("\n")
	}
}

func main() {

	flag.IntVar(&numRead, "NumRead", 10000, "Number of reads")
	flag.IntVar(&readLen, "ReadLen", 100, "Read length")
	flag.IntVar(&numGene, "NumGene", 10000, "Number of genes")
	flag.IntVar(&geneLen, "GeneLen", 1000, "Gene length")

	flag.Parse()

	generateReads()
	generateGenes()
}
<commit_msg>Further changes to data generation<commit_after>package main

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"math/rand"
	"os"
)

var (
	numRead int
	readLen int
	numGene int
	geneLen int

	reads []string
)

func generateReads() {

	fid, err := os.Create("reads.fastq")
	if err != nil {
		panic(err)
	}
	defer fid.Close()

	var buf bytes.Buffer

	for i := 0; i < numRead; i++ {
		fid.WriteString(fmt.Sprintf("read_%d\n", i))

		buf.Reset()
		for j := 0; j < readLen; j++ {
			x := rand.Float64()
			switch {
			case x < 0.25:
				buf.Write([]byte("A"))
			case x < 0.5:
				buf.Write([]byte("T"))
			case x < 0.75:
				buf.Write([]byte("G"))
			default:
				buf.Write([]byte("C"))
			}
		}
		fid.Write(buf.Bytes())

		if i < 10 {
			reads = append(reads, string(buf.Bytes()))
		}

		fid.WriteString("\n+\n")
		for j := 0; j < readLen; j++ {
			fid.WriteString("!")
		}
		fid.WriteString("\n")
	}
}

func writeRand(w io.Writer, n int) {

	for j := 0; j < n; j++ {
		x := rand.Float64()
		switch {
		case x < 0.25:
			w.Write([]byte("A"))
		case x < 0.5:
			w.Write([]byte("T"))
		case x < 0.75:
			w.Write([]byte("G"))
		default:
			w.Write([]byte("C"))
		}
	}
}

func generateGenes() {

	fid, err := os.Create("genes.txt")
	if err != nil {
		panic(err)
	}
	defer fid.Close()

	for i := 0; i < numGene; i++ {
		fid.WriteString(fmt.Sprintf("gene_%d\t", i))

		if i < len(reads) {
			j := i % 10
			writeRand(fid, j)
			fid.WriteString(reads[i])
			writeRand(fid, geneLen-(readLen+j))
		} else {
			writeRand(fid, geneLen)
		}
		fid.WriteString("\n")
	}
}

func main() {

	flag.IntVar(&numRead, "NumRead", 10000, "Number of reads")
	flag.IntVar(&readLen, "ReadLen", 100, "Read length")
	flag.IntVar(&numGene, "NumGene", 10000, "Number of genes")
	flag.IntVar(&geneLen, "GeneLen", 1000, "Gene length")

	flag.Parse()

	generateReads()
	generateGenes()
}
<|endoftext|>


<commit_before>// Copyright © 2016 Steve Francia <spf@spf13.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.

package jwalterweatherman

import (
	"fmt"
	"io"
	"log"
)

type Threshold int

func (t Threshold) String() string {
	return prefixes[t]
}

const (
	LevelTrace Threshold = iota
	LevelDebug
	LevelInfo
	LevelWarn
	LevelError
	LevelCritical
	LevelFatal
)

var prefixes map[Threshold]string = map[Threshold]string{
	LevelTrace:    "TRACE",
	LevelDebug:    "DEBUG",
	LevelInfo:     "INFO",
	LevelWarn:     "WARN",
	LevelError:    "ERROR",
	LevelCritical: "CRITICAL",
	LevelFatal:    "FATAL",
}

// Notepad is where you leave a note!
type Notepad struct {
	TRACE    *log.Logger
	DEBUG    *log.Logger
	INFO     *log.Logger
	WARN     *log.Logger
	ERROR    *log.Logger
	CRITICAL *log.Logger
	FATAL    *log.Logger

	LOG      *log.Logger
	FEEDBACK *Feedback

	loggers         [7]**log.Logger
	logHandle       io.Writer
	outHandle       io.Writer
	logThreshold    Threshold
	stdoutThreshold Threshold
	prefix          string
	flags           int

	// One per Threshold
	logCounters [7]*logCounter
}

// NewNotepad create a new notepad.
func NewNotepad(outThreshold Threshold, logThreshold Threshold, outHandle, logHandle io.Writer, prefix string, flags int) *Notepad {
	n := &Notepad{}

	n.loggers = [7]**log.Logger{&n.TRACE, &n.DEBUG, &n.INFO, &n.WARN, &n.ERROR, &n.CRITICAL, &n.FATAL}
	n.outHandle = outHandle
	n.logHandle = logHandle
	n.stdoutThreshold = outThreshold
	n.logThreshold = logThreshold

	if len(prefix) != 0 {
		n.prefix = "[" + prefix + "] "
	} else {
		n.prefix = ""
	}

	n.flags = flags

	n.LOG = log.New(n.logHandle,
		"LOG:   ",
		n.flags)
	n.FEEDBACK = &Feedback{out: log.New(outHandle, "", 0), log: n.LOG}

	n.init()
	return n
}

// init creates the loggers for each level depending on the notepad thresholds.
func (n *Notepad) init() {
	logAndOut := io.MultiWriter(n.outHandle, n.logHandle)

	for t, logger := range n.loggers {
		threshold := Threshold(t)
		counter := &logCounter{}
		n.logCounters[t] = counter
		prefix := n.prefix + threshold.String() + " "

		switch {
		case threshold >= n.logThreshold && threshold >= n.stdoutThreshold:
			*logger = log.New(io.MultiWriter(counter, logAndOut), prefix, n.flags)

		case threshold >= n.logThreshold:
			*logger = log.New(io.MultiWriter(counter, n.logHandle), prefix, n.flags)

		case threshold >= n.stdoutThreshold:
			*logger = log.New(io.MultiWriter(counter, n.outHandle), prefix, n.flags)

		default:
			*logger = log.New(counter, prefix, n.flags)
		}
	}
}

// SetLogThreshold changes the threshold above which messages are written to the
// log file.
func (n *Notepad) SetLogThreshold(threshold Threshold) {
	n.logThreshold = threshold
	n.init()
}

// SetLogOutput changes the file where log messages are written.
func (n *Notepad) SetLogOutput(handle io.Writer) {
	n.logHandle = handle
	n.init()
}

// GetStdoutThreshold returns the defined Treshold for the log logger.
func (n *Notepad) GetLogThreshold() Threshold {
	return n.logThreshold
}

// SetStdoutThreshold changes the threshold above which messages are written to the
// standard output.
func (n *Notepad) SetStdoutThreshold(threshold Threshold) {
	n.stdoutThreshold = threshold
	n.init()
}

// GetStdoutThreshold returns the Treshold for the stdout logger.
func (n *Notepad) GetStdoutThreshold() Threshold {
	return n.stdoutThreshold
}

// SetPrefix changes the prefix used by the notepad. Prefixes are displayed between
// brackets at the begining of the line. An empty prefix won't be displayed at all.
func (n *Notepad) SetPrefix(prefix string) {
	if len(prefix) != 0 {
		n.prefix = "[" + prefix + "] "
	} else {
		n.prefix = ""
	}
	n.init()
}

// SetFlags choose which flags the logger will display (after prefix and message
// level). See the package log for more informations on this.
func (n *Notepad) SetFlags(flags int) {
	n.flags = flags
	n.init()
}

// Feedback writes plainly to the outHandle while
// logging with the standard extra information (date, file, etc).
type Feedback struct {
	out *log.Logger
	log *log.Logger
}

func (fb *Feedback) Println(v ...interface{}) {
	fb.output(fmt.Sprintln(v...))
}

func (fb *Feedback) Printf(format string, v ...interface{}) {
	fb.output(fmt.Sprintf(format, v...))
}

func (fb *Feedback) Print(v ...interface{}) {
	fb.output(fmt.Sprint(v...))
}

func (fb *Feedback) output(s string) {
	if fb.out != nil {
		fb.out.Output(2, s)
	}
	if fb.log != nil {
		fb.log.Output(2, s)
	}
}
<commit_msg>Don't write prefix and flags to counter<commit_after>// Copyright © 2016 Steve Francia <spf@spf13.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.

package jwalterweatherman

import (
	"fmt"
	"io"
	"log"
)

type Threshold int

func (t Threshold) String() string {
	return prefixes[t]
}

const (
	LevelTrace Threshold = iota
	LevelDebug
	LevelInfo
	LevelWarn
	LevelError
	LevelCritical
	LevelFatal
)

var prefixes map[Threshold]string = map[Threshold]string{
	LevelTrace:    "TRACE",
	LevelDebug:    "DEBUG",
	LevelInfo:     "INFO",
	LevelWarn:     "WARN",
	LevelError:    "ERROR",
	LevelCritical: "CRITICAL",
	LevelFatal:    "FATAL",
}

// Notepad is where you leave a note!
type Notepad struct {
	TRACE    *log.Logger
	DEBUG    *log.Logger
	INFO     *log.Logger
	WARN     *log.Logger
	ERROR    *log.Logger
	CRITICAL *log.Logger
	FATAL    *log.Logger

	LOG      *log.Logger
	FEEDBACK *Feedback

	loggers         [7]**log.Logger
	logHandle       io.Writer
	outHandle       io.Writer
	logThreshold    Threshold
	stdoutThreshold Threshold
	prefix          string
	flags           int

	// One per Threshold
	logCounters [7]*logCounter
}

// NewNotepad create a new notepad.
func NewNotepad(outThreshold Threshold, logThreshold Threshold, outHandle, logHandle io.Writer, prefix string, flags int) *Notepad {
	n := &Notepad{}

	n.loggers = [7]**log.Logger{&n.TRACE, &n.DEBUG, &n.INFO, &n.WARN, &n.ERROR, &n.CRITICAL, &n.FATAL}
	n.outHandle = outHandle
	n.logHandle = logHandle
	n.stdoutThreshold = outThreshold
	n.logThreshold = logThreshold

	if len(prefix) != 0 {
		n.prefix = "[" + prefix + "] "
	} else {
		n.prefix = ""
	}

	n.flags = flags

	n.LOG = log.New(n.logHandle,
		"LOG:   ",
		n.flags)
	n.FEEDBACK = &Feedback{out: log.New(outHandle, "", 0), log: n.LOG}

	n.init()
	return n
}

// init creates the loggers for each level depending on the notepad thresholds.
func (n *Notepad) init() {
	logAndOut := io.MultiWriter(n.outHandle, n.logHandle)

	for t, logger := range n.loggers {
		threshold := Threshold(t)
		counter := &logCounter{}
		n.logCounters[t] = counter
		prefix := n.prefix + threshold.String() + " "

		switch {
		case threshold >= n.logThreshold && threshold >= n.stdoutThreshold:
			*logger = log.New(io.MultiWriter(counter, logAndOut), prefix, n.flags)

		case threshold >= n.logThreshold:
			*logger = log.New(io.MultiWriter(counter, n.logHandle), prefix, n.flags)

		case threshold >= n.stdoutThreshold:
			*logger = log.New(io.MultiWriter(counter, n.outHandle), prefix, n.flags)

		default:
			// counter doesn't care about prefix and flags, so don't use them
			// for performance.
			*logger = log.New(counter, "", 0)
		}
	}
}

// SetLogThreshold changes the threshold above which messages are written to the
// log file.
func (n *Notepad) SetLogThreshold(threshold Threshold) {
	n.logThreshold = threshold
	n.init()
}

// SetLogOutput changes the file where log messages are written.
func (n *Notepad) SetLogOutput(handle io.Writer) {
	n.logHandle = handle
	n.init()
}

// GetStdoutThreshold returns the defined Treshold for the log logger.
func (n *Notepad) GetLogThreshold() Threshold {
	return n.logThreshold
}

// SetStdoutThreshold changes the threshold above which messages are written to the
// standard output.
func (n *Notepad) SetStdoutThreshold(threshold Threshold) {
	n.stdoutThreshold = threshold
	n.init()
}

// GetStdoutThreshold returns the Treshold for the stdout logger.
func (n *Notepad) GetStdoutThreshold() Threshold {
	return n.stdoutThreshold
}

// SetPrefix changes the prefix used by the notepad. Prefixes are displayed between
// brackets at the begining of the line. An empty prefix won't be displayed at all.
func (n *Notepad) SetPrefix(prefix string) {
	if len(prefix) != 0 {
		n.prefix = "[" + prefix + "] "
	} else {
		n.prefix = ""
	}
	n.init()
}

// SetFlags choose which flags the logger will display (after prefix and message
// level). See the package log for more informations on this.
func (n *Notepad) SetFlags(flags int) {
	n.flags = flags
	n.init()
}

// Feedback writes plainly to the outHandle while
// logging with the standard extra information (date, file, etc).
type Feedback struct {
	out *log.Logger
	log *log.Logger
}

func (fb *Feedback) Println(v ...interface{}) {
	fb.output(fmt.Sprintln(v...))
}

func (fb *Feedback) Printf(format string, v ...interface{}) {
	fb.output(fmt.Sprintf(format, v...))
}

func (fb *Feedback) Print(v ...interface{}) {
	fb.output(fmt.Sprint(v...))
}

func (fb *Feedback) output(s string) {
	if fb.out != nil {
		fb.out.Output(2, s)
	}
	if fb.log != nil {
		fb.log.Output(2, s)
	}
}
<|endoftext|>


<commit_before>package openapi

import (
	"context"
	"fmt"
	"net/http"
)

type Channel struct {
	ID            *string       `json:"id,omitempty"`
	TeamID        *string       `json:"team_id,omitempty"`
	VChannelID    *string       `json:"vchannel_id,omitempty"`
	UserID        *string       `json:"uid,omitempty"`
	Name          *string       `json:"name,omitempty"`
	Type          *VChannelType `json:"type,omitempty"`
	Private       *bool         `json:"private,omitempty"`
	General       *bool         `json:"general,omitempty"`
	Topic         *string       `json:"topic,omitempty"`
	IsMember      *bool         `json:"is_member,omitempty"`
	IsActive      *bool         `json:"is_active,omitempty"`
	MemberUserIDs []string      `json:"member_uids,omitempty"`
	LatestTS      *VChannelTS   `json:"latest_ts,omitempty"`
}

type ChannelService service

type ChannelInfoOptions struct {
	ChannelID string
}

// Info implements `GET /channel.info`
func (c *ChannelService) Info(ctx context.Context, opt *ChannelInfoOptions) (*Channel, *http.Response, error) {
	endpoint := fmt.Sprintf("channel.info?channel_id=%s", opt.ChannelID)
	req, err := c.client.newRequest("GET", endpoint, nil)
	if err != nil {
		return nil, nil, err
	}

	var channel Channel
	resp, err := c.client.do(ctx, req, &channel)
	if err != nil {
		return nil, resp, err
	}
	return &channel, resp, nil
}

// List implements `GET /channel.list`
func (c *ChannelService) List(ctx context.Context) ([]*Channel, *http.Response, error) {
	req, err := c.client.newRequest("GET", "channel.list", nil)
	if err != nil {
		return nil, nil, err
	}

	var channels []*Channel
	resp, err := c.client.do(ctx, req, &channels)
	if err != nil {
		return nil, resp, err
	}
	return channels, resp, nil
}
<commit_msg>feat(openapi): implement `channel.create`<commit_after>package openapi

import (
	"context"
	"fmt"
	"net/http"
)

type Channel struct {
	ID            *string       `json:"id,omitempty"`
	TeamID        *string       `json:"team_id,omitempty"`
	VChannelID    *string       `json:"vchannel_id,omitempty"`
	UserID        *string       `json:"uid,omitempty"`
	Name          *string       `json:"name,omitempty"`
	Type          *VChannelType `json:"type,omitempty"`
	Private       *bool         `json:"private,omitempty"`
	General       *bool         `json:"general,omitempty"`
	Topic         *string       `json:"topic,omitempty"`
	IsMember      *bool         `json:"is_member,omitempty"`
	IsActive      *bool         `json:"is_active,omitempty"`
	MemberUserIDs []string      `json:"member_uids,omitempty"`
	LatestTS      *VChannelTS   `json:"latest_ts,omitempty"`
}

type ChannelService service

type ChannelInfoOptions struct {
	ChannelID string
}

// Info implements `GET /channel.info`
func (c *ChannelService) Info(ctx context.Context, opt *ChannelInfoOptions) (*Channel, *http.Response, error) {
	endpoint := fmt.Sprintf("channel.info?channel_id=%s", opt.ChannelID)
	req, err := c.client.newRequest("GET", endpoint, nil)
	if err != nil {
		return nil, nil, err
	}

	var channel Channel
	resp, err := c.client.do(ctx, req, &channel)
	if err != nil {
		return nil, resp, err
	}
	return &channel, resp, nil
}

// List implements `GET /channel.list`
func (c *ChannelService) List(ctx context.Context) ([]*Channel, *http.Response, error) {
	req, err := c.client.newRequest("GET", "channel.list", nil)
	if err != nil {
		return nil, nil, err
	}

	var channels []*Channel
	resp, err := c.client.do(ctx, req, &channels)
	if err != nil {
		return nil, resp, err
	}
	return channels, resp, nil
}

type ChannelCreateOptions struct {
	Name    string  `json:"name"`
	Topic   *string `json:"topic,omitempty"`
	Private *bool   `json:"private,omitempty"`
}

func (c *ChannelService) Create(ctx context.Context, opt *ChannelCreateOptions) (*Channel, *http.Response, error) {
	req, err := c.client.newRequest("POST", "channel.create", opt)
	if err != nil {
		return nil, nil, err
	}

	var channel Channel
	resp, err := c.client.do(ctx, req, &channel)
	if err != nil {
		return nil, resp, err
	}
	return &channel, resp, nil
}
<|endoftext|>


<commit_before>package npm

import (
	"os/exec"

	simpleJson "github.com/bitly/go-simplejson"
)

type PackageManager interface {
	Login(userName string, password string, email string, registry string) error
	Logout(registry string) error
	View(packageName string, registry string) (*PackageInfo, error)
	Install(packageName string, registry string) error
	Publish(path string, tag string, registry string) error
}

type NPM struct{}

func NewNPM() *NPM {
	return &NPM{}
}

func (npm *NPM) Login(userName string, password string, email string, registry string) error {
	args := []string{"-u", userName, "-p", password, "-e", email}

	if registry != "" {
		args = append(args, "-r", registry)
	}

	return exec.Command("npm-cli-login", args...).Run()
}

func (npm *NPM) Logout(registry string) error {
	args := []string{"logout"}

	if registry != "" {
		args = append(args, "--registry", registry)
	}

	return exec.Command("npm", args...).Run()
}

func (npm *NPM) View(packageName string, registry string) (*PackageInfo, error) {
	args := []string{"view", packageName, "--json"}

	if registry != "" {
		args = append(args, "--registry", registry)
	}

	out, err := exec.Command("npm", args...).Output()
	if err != nil {
		return &PackageInfo{}, err
	}

	js, err := simpleJson.NewJson(out)
	if err != nil {
		return &PackageInfo{}, err
	}

	var info PackageInfo
	info.Name, err = js.Get("name").String()
	info.Version, err = js.Get("version").String()
	info.Homepage, err = js.Get("homepage").String()

	return &info, err
}

func (npm *NPM) Install(packageName string, registry string) error {
	args := []string{"install", packageName}

	if registry != "" {
		args = append(args, "--registry", registry)
	}

	return exec.Command("npm", args...).Run()
}

func (npm *NPM) Publish(path string, tag string, registry string) error {
	args := []string{"publish", path}

	if tag != "" {
		args = append(args, "--tag", tag)
	}
	if registry != "" {
		args = append(args, "--registry", registry)
	}

	return exec.Command("npm", args...).Run()
}
<commit_msg>add stdout/err to npm commands<commit_after>package npm

import (
	"os"
	"os/exec"

	simpleJson "github.com/bitly/go-simplejson"
)

type PackageManager interface {
	Login(userName string, password string, email string, registry string) error
	Logout(registry string) error
	View(packageName string, registry string) (*PackageInfo, error)
	Install(packageName string, registry string) error
	Publish(path string, tag string, registry string) error
}

type NPM struct{}

func NewNPM() *NPM {
	return &NPM{}
}

func (npm *NPM) Login(userName string, password string, email string, registry string) error {
	args := []string{"-u", userName, "-p", password, "-e", email}

	if registry != "" {
		args = append(args, "-r", registry)
	}

	cmd := exec.Command("npm-cli-login", args...)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	return cmd.Run()
}

func (npm *NPM) Logout(registry string) error {
	args := []string{"logout"}

	if registry != "" {
		args = append(args, "--registry", registry)
	}

	return npm.npm(args...).Run()
}

func (npm *NPM) View(packageName string, registry string) (*PackageInfo, error) {
	args := []string{"view", packageName, "--json"}

	if registry != "" {
		args = append(args, "--registry", registry)
	}

	cmd := exec.Command("npm", args...)
	cmd.Stderr = os.Stderr
	out, err := cmd.Output()
	if err != nil {
		return &PackageInfo{}, err
	}

	js, err := simpleJson.NewJson(out)
	if err != nil {
		return &PackageInfo{}, err
	}

	var info PackageInfo
	info.Name, err = js.Get("name").String()
	info.Version, err = js.Get("version").String()
	info.Homepage, err = js.Get("homepage").String()

	return &info, err
}

func (npm *NPM) Install(packageName string, registry string) error {
	args := []string{"install", packageName}

	if registry != "" {
		args = append(args, "--registry", registry)
	}

	return npm.npm(args...).Run()
}

func (npm *NPM) Publish(path string, tag string, registry string) error {
	args := []string{"publish", path}

	if tag != "" {
		args = append(args, "--tag", tag)
	}
	if registry != "" {
		args = append(args, "--registry", registry)
	}

	return npm.npm(args...).Run()
}

func (npm *NPM) npm(args ...string) *exec.Cmd {
	cmd := exec.Command("npm", args...)
	cmd.Stdout = os.Stderr
	cmd.Stderr = os.Stderr

	return cmd
}
<|endoftext|>


<commit_before>package master

import (
	"database/sql"
	"fmt"
	. "github.com/KIT-MAMID/mamid/model"
	"github.com/stretchr/testify/assert"
	"testing"
)

/*
Testing the cluster allocator:

Mocking: Bus (Mismatch Messages, Constraint Status)

Fixtures:
 * Flexible infrastructure for creating test scenarios
 * Elegant way to compare pre- and post-state of the database?

What to test?

count methods

priority queue builders

idempotence: test after...
  run of removal
  run of add
  => cancels out every run of the entire algorithm

completeness of the object graph? do we fetch it at the beginning? what about locking?

mismatch generation => use mock of Bus?

*/

// Create a scenario from a running setup:
//  pg_dump --insert -Oa <additional, optional connection parameter> <dbname>

func TestClutserAllocator_findUnusedPort(t *testing.T) {

	unusedPort, found := findUnusedPort([]PortNumber{2, 3, 5}, 2, 6)
	assert.EqualValues(t, 4, unusedPort, "should find lowest free port number")

	unusedPort, found = findUnusedPort([]PortNumber{}, 2, 5)
	assert.EqualValues(t, 2, unusedPort, "should use minPort when no port used")

	unusedPort, found = findUnusedPort([]PortNumber{0}, 2, 5)
	assert.EqualValues(t, 2, unusedPort)

	var uninitialized []PortNumber
	unusedPort, found = findUnusedPort(uninitialized, 2, 5)
	assert.EqualValues(t, 2, unusedPort)

	unusedPort, found = findUnusedPort([]PortNumber{2, 3, 4}, 2, 5)
	assert.Equal(t, false, found, "should not find a port if no port free")

}

func saveDB(dsn string, driver string) (dump map[string][]string, err error) {
	dump = make(map[string][]string)
	db, err := sql.Open(driver, dsn)
	if err != nil {
		return
	}
	defer db.Close()
	tables, err := db.Query("select tablename from pg_tables WHERE schemaname='public' ORDER by tablename")
	//tables, err := db.Query("select repl_set_name from mongods")

	defer tables.Close()
	if err != nil {
		return
	}
	for tables.Next() {
		var table string
		err = tables.Scan(&table)
		if err != nil {
			return dump, err
		}
		res, err := db.Query(fmt.Sprintf(`SELECT
		pg_attribute.attname
		FROM pg_index, pg_class, pg_attribute, pg_namespace
		WHERE
		pg_class.oid='%s'::regclass AND
		indrelid = pg_class.oid AND
		nspname = 'public' AND
		pg_class.relnamespace = pg_namespace.oid AND
		pg_attribute.attrelid = pg_class.oid AND
		pg_attribute.attnum = any(pg_index.indkey)
		AND indisprimary;`, table))
		if err != nil {
			return dump, err
		}
		var key string
		res.Next()
		res.Scan(&key)
		res.Close()
		tableContents, tableContentErr := db.Query(fmt.Sprintf("SELECT * FROM %s ORDER BY %s", table, key))
		if tableContentErr != nil {
			return dump, tableContentErr
		}
		cols, colGetError := tableContents.Columns()
		if colGetError != nil {
			return dump, colGetError
		}
		dest := make([]interface{}, len(cols))
		rawResult := make([][]byte, len(cols))
		result := make([]string, len(cols))
		for i, _ := range rawResult {
			dest[i] = &rawResult[i] // Put pointers to each string in the interface slice
		}
		for tableContents.Next() {
			tableGetContentsErr := tableContents.Scan(dest...)
			if tableGetContentsErr != nil {
				return dump, err
			}
			for i, raw := range rawResult {
				if raw == nil {
					result[i] = "\\N"
				} else {
					result[i] = string(raw)
				}
			}
		}
		tableContents.Close()
		dump[table] = result
	}
	return
}

func TestTestSaveDB(t *testing.T) {
	// Check equality
	db, dsn, err := InitializeTestDBFromFile("cluster_allocator_test_fixture_allocate_full.sql")
	assert.NoError(t, err)
	dump, err := saveDB(dsn, db.Driver)
	assert.NoError(t, err)
	db, dsn, err = InitializeTestDBFromFile("cluster_allocator_test_fixture_allocate_full.sql")
	assert.NoError(t, err)
	dump2, err := saveDB(dsn, db.Driver)
	assert.NoError(t, err)
	assert.Equal(t, dump, dump2)

	//Check non-equality
	db, dsn, err = InitializeTestDBFromFile("cluster_allocator_test_fixture_allocated_degraded.sql")
	assert.NoError(t, err)
	dump2, err = saveDB(dsn, db.Driver)
	assert.NoError(t, err)
	assert.NotEqual(t, dump, dump2)
}

func TestClusterAllocator_CompileMongodLayout_Idempotence_Simple(t *testing.T) {
	db, dsn, err := InitializeTestDBFromFile("cluster_allocator_test_fixture_allocate_full.sql")
	assert.NoError(t, err)
	dump, err := saveDB(dsn, db.Driver)
	assert.NoError(t, err)
	var alloc ClusterAllocator
	tx := db.Begin()
	alloc.CompileMongodLayout(tx)
	dump2, err := saveDB(dsn, db.Driver)
	assert.NoError(t, err)
	assert.Equal(t, dump, dump2)
	alloc.CompileMongodLayout(tx)
	dump2, err = saveDB(dsn, db.Driver)
	assert.NoError(t, err)
	assert.Equal(t, dump, dump2)
}
<commit_msg>FIX: master: missing defer db.CloaseAndDrop() in clusterallocator tests<commit_after>package master

import (
	"database/sql"
	"fmt"
	. "github.com/KIT-MAMID/mamid/model"
	"github.com/stretchr/testify/assert"
	"testing"
)

/*
Testing the cluster allocator:

Mocking: Bus (Mismatch Messages, Constraint Status)

Fixtures:
 * Flexible infrastructure for creating test scenarios
 * Elegant way to compare pre- and post-state of the database?

What to test?

count methods

priority queue builders

idempotence: test after...
  run of removal
  run of add
  => cancels out every run of the entire algorithm

completeness of the object graph? do we fetch it at the beginning? what about locking?

mismatch generation => use mock of Bus?

*/

// Create a scenario from a running setup:
//  pg_dump --insert -Oa <additional, optional connection parameter> <dbname>

func TestClutserAllocator_findUnusedPort(t *testing.T) {

	unusedPort, found := findUnusedPort([]PortNumber{2, 3, 5}, 2, 6)
	assert.EqualValues(t, 4, unusedPort, "should find lowest free port number")

	unusedPort, found = findUnusedPort([]PortNumber{}, 2, 5)
	assert.EqualValues(t, 2, unusedPort, "should use minPort when no port used")

	unusedPort, found = findUnusedPort([]PortNumber{0}, 2, 5)
	assert.EqualValues(t, 2, unusedPort)

	var uninitialized []PortNumber
	unusedPort, found = findUnusedPort(uninitialized, 2, 5)
	assert.EqualValues(t, 2, unusedPort)

	unusedPort, found = findUnusedPort([]PortNumber{2, 3, 4}, 2, 5)
	assert.Equal(t, false, found, "should not find a port if no port free")

}

func saveDB(dsn string, driver string) (dump map[string][]string, err error) {
	dump = make(map[string][]string)
	db, err := sql.Open(driver, dsn)
	if err != nil {
		return
	}
	defer db.Close()
	tables, err := db.Query("select tablename from pg_tables WHERE schemaname='public' ORDER by tablename")
	//tables, err := db.Query("select repl_set_name from mongods")

	defer tables.Close()
	if err != nil {
		return
	}
	for tables.Next() {
		var table string
		err = tables.Scan(&table)
		if err != nil {
			return dump, err
		}
		res, err := db.Query(fmt.Sprintf(`SELECT
		pg_attribute.attname
		FROM pg_index, pg_class, pg_attribute, pg_namespace
		WHERE
		pg_class.oid='%s'::regclass AND
		indrelid = pg_class.oid AND
		nspname = 'public' AND
		pg_class.relnamespace = pg_namespace.oid AND
		pg_attribute.attrelid = pg_class.oid AND
		pg_attribute.attnum = any(pg_index.indkey)
		AND indisprimary;`, table))
		if err != nil {
			return dump, err
		}
		var key string
		res.Next()
		res.Scan(&key)
		res.Close()
		tableContents, tableContentErr := db.Query(fmt.Sprintf("SELECT * FROM %s ORDER BY %s", table, key))
		if tableContentErr != nil {
			return dump, tableContentErr
		}
		cols, colGetError := tableContents.Columns()
		if colGetError != nil {
			return dump, colGetError
		}
		dest := make([]interface{}, len(cols))
		rawResult := make([][]byte, len(cols))
		result := make([]string, len(cols))
		for i, _ := range rawResult {
			dest[i] = &rawResult[i] // Put pointers to each string in the interface slice
		}
		for tableContents.Next() {
			tableGetContentsErr := tableContents.Scan(dest...)
			if tableGetContentsErr != nil {
				return dump, err
			}
			for i, raw := range rawResult {
				if raw == nil {
					result[i] = "\\N"
				} else {
					result[i] = string(raw)
				}
			}
		}
		tableContents.Close()
		dump[table] = result
	}
	return
}

func TestTestSaveDB(t *testing.T) {
	// Check equality
	db, dsn, err := InitializeTestDBFromFile("cluster_allocator_test_fixture_allocate_full.sql")
	defer db.CloseAndDrop()
	assert.NoError(t, err)
	dump, err := saveDB(dsn, db.Driver)
	assert.NoError(t, err)
	db, dsn, err = InitializeTestDBFromFile("cluster_allocator_test_fixture_allocate_full.sql")
	defer db.CloseAndDrop()
	assert.NoError(t, err)
	dump2, err := saveDB(dsn, db.Driver)
	assert.NoError(t, err)
	assert.Equal(t, dump, dump2)

	//Check non-equality
	db, dsn, err = InitializeTestDBFromFile("cluster_allocator_test_fixture_allocated_degraded.sql")
	defer db.CloseAndDrop()
	assert.NoError(t, err)
	dump2, err = saveDB(dsn, db.Driver)
	assert.NoError(t, err)
	assert.NotEqual(t, dump, dump2)
}

func TestClusterAllocator_CompileMongodLayout_Idempotence_Simple(t *testing.T) {
	db, dsn, err := InitializeTestDBFromFile("cluster_allocator_test_fixture_allocate_full.sql")
	defer db.CloseAndDrop()
	assert.NoError(t, err)
	dump, err := saveDB(dsn, db.Driver)
	assert.NoError(t, err)
	var alloc ClusterAllocator
	tx := db.Begin()
	alloc.CompileMongodLayout(tx)
	dump2, err := saveDB(dsn, db.Driver)
	assert.NoError(t, err)
	assert.Equal(t, dump, dump2)
	alloc.CompileMongodLayout(tx)
	dump2, err = saveDB(dsn, db.Driver)
	assert.NoError(t, err)
	assert.Equal(t, dump, dump2)
}
<|endoftext|>


<commit_before>// +build windows

package pushaction_test

import (
	. "code.cloudfoundry.org/cli/actor/pushaction"
	"code.cloudfoundry.org/cli/actor/pushaction/manifest"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"
)

var _ = Describe("CommandLineSettings with provided path", func() {
	const currentDirectory = "C:\\some\\current-directory"

	Describe("ApplicationPath with provided path", func() {
		DescribeTable("ApplicationPath", func(providedAppPath string, expectedPath string) {
			settings := CommandLineSettings{
				CurrentDirectory: currentDirectory,
				ProvidedAppPath:  providedAppPath,
			}

			Expect(settings.ApplicationPath()).To(Equal(expectedPath))
		},

			Entry("path = provided path; provided path is absolute", "C:\\some\\path", "C:\\some\\path"),
			Entry("path = full path to provided path; provided path is relative", ".\\some-path", "C:\\some\\current-directory\\some-path"),
		)
	})

	Describe("OverrideManifestSettings", func() {
		DescribeTable("Path", func(providedAppPath string, manifestPath string, expectedPath string) {
			settings := CommandLineSettings{
				CurrentDirectory: currentDirectory,
				ProvidedAppPath:  providedAppPath,
			}

			app := settings.OverrideManifestSettings(manifest.Application{
				Path: manifestPath,
			})

			Expect(app.Path).To(Equal(expectedPath))
		},

			Entry("path = current directory; provided and manifest paths are empty", "", "", currentDirectory),
			Entry("path = manfiest path; provided is empty and manifest path is not empty", "", "some-manifest-path", "some-manifest-path"),
			Entry("path = absolute provided path; provided relative path is not empty and manifest path is empty", "some-provided-path", "", "C:\\some\\current-directory\\some-provided-path"),
			Entry("path = absolute provided path; provided relative path and manifest path are not empty", "some-provided-path", "some-manifest-path", "C:\\some\\current-directory\\some-provided-path"),
			Entry("path = provided path; provided path is absolute", "C:\\some-provided-path", "", "C:\\some-provided-path"),
		)
	})
})
<commit_msg>fix another manifest path for windows<commit_after>// +build windows

package pushaction_test

import (
	. "code.cloudfoundry.org/cli/actor/pushaction"
	"code.cloudfoundry.org/cli/util/manifest"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"
)

var _ = Describe("CommandLineSettings with provided path", func() {
	const currentDirectory = "C:\\some\\current-directory"

	Describe("ApplicationPath with provided path", func() {
		DescribeTable("ApplicationPath", func(providedAppPath string, expectedPath string) {
			settings := CommandLineSettings{
				CurrentDirectory: currentDirectory,
				ProvidedAppPath:  providedAppPath,
			}

			Expect(settings.ApplicationPath()).To(Equal(expectedPath))
		},

			Entry("path = provided path; provided path is absolute", "C:\\some\\path", "C:\\some\\path"),
			Entry("path = full path to provided path; provided path is relative", ".\\some-path", "C:\\some\\current-directory\\some-path"),
		)
	})

	Describe("OverrideManifestSettings", func() {
		DescribeTable("Path", func(providedAppPath string, manifestPath string, expectedPath string) {
			settings := CommandLineSettings{
				CurrentDirectory: currentDirectory,
				ProvidedAppPath:  providedAppPath,
			}

			app := settings.OverrideManifestSettings(manifest.Application{
				Path: manifestPath,
			})

			Expect(app.Path).To(Equal(expectedPath))
		},

			Entry("path = current directory; provided and manifest paths are empty", "", "", currentDirectory),
			Entry("path = manfiest path; provided is empty and manifest path is not empty", "", "some-manifest-path", "some-manifest-path"),
			Entry("path = absolute provided path; provided relative path is not empty and manifest path is empty", "some-provided-path", "", "C:\\some\\current-directory\\some-provided-path"),
			Entry("path = absolute provided path; provided relative path and manifest path are not empty", "some-provided-path", "some-manifest-path", "C:\\some\\current-directory\\some-provided-path"),
			Entry("path = provided path; provided path is absolute", "C:\\some-provided-path", "", "C:\\some-provided-path"),
		)
	})
})
<|endoftext|>


<commit_before>package openstack

import (
	"fmt"
	"net/url"

	"github.com/rackspace/gophercloud"
	tokens2 "github.com/rackspace/gophercloud/openstack/identity/v2/tokens"
	tokens3 "github.com/rackspace/gophercloud/openstack/identity/v3/tokens"
	"github.com/rackspace/gophercloud/openstack/utils"
)

const (
	v20 = "v2.0"
	v30 = "v3.0"
)

// NewClient prepares an unauthenticated ProviderClient instance.
// Most users will probably prefer using the AuthenticatedClient function instead.
// This is useful if you wish to explicitly control the version of the identity service that's used for authentication explicitly,
// for example.
func NewClient(endpoint string) (*gophercloud.ProviderClient, error) {
	u, err := url.Parse(endpoint)
	if err != nil {
		return nil, err
	}
	hadPath := u.Path != ""
	u.Path, u.RawQuery, u.Fragment = "", "", ""
	base := u.String()

	endpoint = gophercloud.NormalizeURL(endpoint)
	base = gophercloud.NormalizeURL(base)

	if hadPath {
		return &gophercloud.ProviderClient{
			IdentityBase:     base,
			IdentityEndpoint: endpoint,
		}, nil
	}

	return &gophercloud.ProviderClient{
		IdentityBase:     base,
		IdentityEndpoint: "",
	}, nil
}

// AuthenticatedClient logs in to an OpenStack cloud found at the identity endpoint specified by options, acquires a token, and
// returns a Client instance that's ready to operate.
// It first queries the root identity endpoint to determine which versions of the identity service are supported, then chooses
// the most recent identity service available to proceed.
func AuthenticatedClient(options gophercloud.AuthOptions) (*gophercloud.ProviderClient, error) {
	client, err := NewClient(options.IdentityEndpoint)
	if err != nil {
		return nil, err
	}

	err = Authenticate(client, options)
	if err != nil {
		return nil, err
	}
	return client, nil
}

// Authenticate or re-authenticate against the most recent identity service supported at the provided endpoint.
func Authenticate(client *gophercloud.ProviderClient, options gophercloud.AuthOptions) error {
	versions := []*utils.Version{
		&utils.Version{ID: v20, Priority: 20, Suffix: "/v2.0/"},
		&utils.Version{ID: v30, Priority: 30, Suffix: "/v3/"},
	}

	chosen, endpoint, err := utils.ChooseVersion(client.IdentityBase, client.IdentityEndpoint, versions)
	if err != nil {
		return err
	}

	switch chosen.ID {
	case v20:
		return v2auth(client, endpoint, options)
	case v30:
		return v3auth(client, endpoint, options)
	default:
		// The switch statement must be out of date from the versions list.
		return fmt.Errorf("Unrecognized identity version: %s", chosen.ID)
	}
}

// AuthenticateV2 explicitly authenticates against the identity v2 endpoint.
func AuthenticateV2(client *gophercloud.ProviderClient, options gophercloud.AuthOptions) error {
	return v2auth(client, "", options)
}

func v2auth(client *gophercloud.ProviderClient, endpoint string, options gophercloud.AuthOptions) error {
	v2Client := NewIdentityV2(client)
	if endpoint != "" {
		v2Client.Endpoint = endpoint
	}

	result := tokens2.Create(v2Client, tokens2.AuthOptions{AuthOptions: options})

	token, err := result.ExtractToken()
	if err != nil {
		return err
	}

	catalog, err := result.ExtractServiceCatalog()
	if err != nil {
		return err
	}

	client.TokenID = token.ID
	client.EndpointLocator = func(opts gophercloud.EndpointOpts) (string, error) {
		return V2EndpointURL(catalog, opts)
	}

	return nil
}

// AuthenticateV3 explicitly authenticates against the identity v3 service.
func AuthenticateV3(client *gophercloud.ProviderClient, options gophercloud.AuthOptions) error {
	return v3auth(client, "", options)
}

func v3auth(client *gophercloud.ProviderClient, endpoint string, options gophercloud.AuthOptions) error {
	// Override the generated service endpoint with the one returned by the version endpoint.
	v3Client := NewIdentityV3(client)
	if endpoint != "" {
		v3Client.Endpoint = endpoint
	}

	token, err := tokens3.Create(v3Client, options, nil).Extract()
	if err != nil {
		return err
	}
	client.TokenID = token.ID

	client.EndpointLocator = func(opts gophercloud.EndpointOpts) (string, error) {
		return V3EndpointURL(v3Client, opts)
	}

	return nil
}

// NewIdentityV2 creates a ServiceClient that may be used to interact with the v2 identity service.
func NewIdentityV2(client *gophercloud.ProviderClient) *gophercloud.ServiceClient {
	v2Endpoint := client.IdentityBase + "v2.0/"

	return &gophercloud.ServiceClient{
		ProviderClient: client,
		Endpoint:       v2Endpoint,
	}
}

// NewIdentityV3 creates a ServiceClient that may be used to access the v3 identity service.
func NewIdentityV3(client *gophercloud.ProviderClient) *gophercloud.ServiceClient {
	v3Endpoint := client.IdentityBase + "v3/"

	return &gophercloud.ServiceClient{
		ProviderClient: client,
		Endpoint:       v3Endpoint,
	}
}

// NewObjectStorageV1 creates a ServiceClient that may be used with the v1 object storage package.
func NewObjectStorageV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {
	eo.ApplyDefaults("object-store")
	url, err := client.EndpointLocator(eo)
	if err != nil {
		return nil, err
	}
	return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil
}

// NewComputeV2 creates a ServiceClient that may be used with the v2 compute package.
func NewComputeV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {
	eo.ApplyDefaults("compute")
	url, err := client.EndpointLocator(eo)
	if err != nil {
		return nil, err
	}
	return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil
}

// NewNetworkV2 creates a ServiceClient that may be used with the v2 network package.
func NewNetworkV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {
	eo.ApplyDefaults("network")
	url, err := client.EndpointLocator(eo)
	if err != nil {
		return nil, err
	}
	return &gophercloud.ServiceClient{
		ProviderClient: client,
		Endpoint:       url,
		ResourceBase:   url + "v2.0/",
	}, nil
}

// NewBlockStorageV1 creates a ServiceClient that may be used to access the v1 block storage service.
func NewBlockStorageV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {
	eo.ApplyDefaults("volume")
	url, err := client.EndpointLocator(eo)
	if err != nil {
		return nil, err
	}
	return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil
}
<commit_msg>openstack cdn client<commit_after>package openstack

import (
	"fmt"
	"net/url"

	"github.com/rackspace/gophercloud"
	tokens2 "github.com/rackspace/gophercloud/openstack/identity/v2/tokens"
	tokens3 "github.com/rackspace/gophercloud/openstack/identity/v3/tokens"
	"github.com/rackspace/gophercloud/openstack/utils"
)

const (
	v20 = "v2.0"
	v30 = "v3.0"
)

// NewClient prepares an unauthenticated ProviderClient instance.
// Most users will probably prefer using the AuthenticatedClient function instead.
// This is useful if you wish to explicitly control the version of the identity service that's used for authentication explicitly,
// for example.
func NewClient(endpoint string) (*gophercloud.ProviderClient, error) {
	u, err := url.Parse(endpoint)
	if err != nil {
		return nil, err
	}
	hadPath := u.Path != ""
	u.Path, u.RawQuery, u.Fragment = "", "", ""
	base := u.String()

	endpoint = gophercloud.NormalizeURL(endpoint)
	base = gophercloud.NormalizeURL(base)

	if hadPath {
		return &gophercloud.ProviderClient{
			IdentityBase:     base,
			IdentityEndpoint: endpoint,
		}, nil
	}

	return &gophercloud.ProviderClient{
		IdentityBase:     base,
		IdentityEndpoint: "",
	}, nil
}

// AuthenticatedClient logs in to an OpenStack cloud found at the identity endpoint specified by options, acquires a token, and
// returns a Client instance that's ready to operate.
// It first queries the root identity endpoint to determine which versions of the identity service are supported, then chooses
// the most recent identity service available to proceed.
func AuthenticatedClient(options gophercloud.AuthOptions) (*gophercloud.ProviderClient, error) {
	client, err := NewClient(options.IdentityEndpoint)
	if err != nil {
		return nil, err
	}

	err = Authenticate(client, options)
	if err != nil {
		return nil, err
	}
	return client, nil
}

// Authenticate or re-authenticate against the most recent identity service supported at the provided endpoint.
func Authenticate(client *gophercloud.ProviderClient, options gophercloud.AuthOptions) error {
	versions := []*utils.Version{
		&utils.Version{ID: v20, Priority: 20, Suffix: "/v2.0/"},
		&utils.Version{ID: v30, Priority: 30, Suffix: "/v3/"},
	}

	chosen, endpoint, err := utils.ChooseVersion(client.IdentityBase, client.IdentityEndpoint, versions)
	if err != nil {
		return err
	}

	switch chosen.ID {
	case v20:
		return v2auth(client, endpoint, options)
	case v30:
		return v3auth(client, endpoint, options)
	default:
		// The switch statement must be out of date from the versions list.
		return fmt.Errorf("Unrecognized identity version: %s", chosen.ID)
	}
}

// AuthenticateV2 explicitly authenticates against the identity v2 endpoint.
func AuthenticateV2(client *gophercloud.ProviderClient, options gophercloud.AuthOptions) error {
	return v2auth(client, "", options)
}

func v2auth(client *gophercloud.ProviderClient, endpoint string, options gophercloud.AuthOptions) error {
	v2Client := NewIdentityV2(client)
	if endpoint != "" {
		v2Client.Endpoint = endpoint
	}

	result := tokens2.Create(v2Client, tokens2.AuthOptions{AuthOptions: options})

	token, err := result.ExtractToken()
	if err != nil {
		return err
	}

	catalog, err := result.ExtractServiceCatalog()
	if err != nil {
		return err
	}

	client.TokenID = token.ID
	client.EndpointLocator = func(opts gophercloud.EndpointOpts) (string, error) {
		return V2EndpointURL(catalog, opts)
	}

	return nil
}

// AuthenticateV3 explicitly authenticates against the identity v3 service.
func AuthenticateV3(client *gophercloud.ProviderClient, options gophercloud.AuthOptions) error {
	return v3auth(client, "", options)
}

func v3auth(client *gophercloud.ProviderClient, endpoint string, options gophercloud.AuthOptions) error {
	// Override the generated service endpoint with the one returned by the version endpoint.
	v3Client := NewIdentityV3(client)
	if endpoint != "" {
		v3Client.Endpoint = endpoint
	}

	token, err := tokens3.Create(v3Client, options, nil).Extract()
	if err != nil {
		return err
	}
	client.TokenID = token.ID

	client.EndpointLocator = func(opts gophercloud.EndpointOpts) (string, error) {
		return V3EndpointURL(v3Client, opts)
	}

	return nil
}

// NewIdentityV2 creates a ServiceClient that may be used to interact with the v2 identity service.
func NewIdentityV2(client *gophercloud.ProviderClient) *gophercloud.ServiceClient {
	v2Endpoint := client.IdentityBase + "v2.0/"

	return &gophercloud.ServiceClient{
		ProviderClient: client,
		Endpoint:       v2Endpoint,
	}
}

// NewIdentityV3 creates a ServiceClient that may be used to access the v3 identity service.
func NewIdentityV3(client *gophercloud.ProviderClient) *gophercloud.ServiceClient {
	v3Endpoint := client.IdentityBase + "v3/"

	return &gophercloud.ServiceClient{
		ProviderClient: client,
		Endpoint:       v3Endpoint,
	}
}

// NewObjectStorageV1 creates a ServiceClient that may be used with the v1 object storage package.
func NewObjectStorageV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {
	eo.ApplyDefaults("object-store")
	url, err := client.EndpointLocator(eo)
	if err != nil {
		return nil, err
	}
	return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil
}

// NewComputeV2 creates a ServiceClient that may be used with the v2 compute package.
func NewComputeV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {
	eo.ApplyDefaults("compute")
	url, err := client.EndpointLocator(eo)
	if err != nil {
		return nil, err
	}
	return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil
}

// NewNetworkV2 creates a ServiceClient that may be used with the v2 network package.
func NewNetworkV2(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {
	eo.ApplyDefaults("network")
	url, err := client.EndpointLocator(eo)
	if err != nil {
		return nil, err
	}
	return &gophercloud.ServiceClient{
		ProviderClient: client,
		Endpoint:       url,
		ResourceBase:   url + "v2.0/",
	}, nil
}

// NewBlockStorageV1 creates a ServiceClient that may be used to access the v1 block storage service.
func NewBlockStorageV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {
	eo.ApplyDefaults("volume")
	url, err := client.EndpointLocator(eo)
	if err != nil {
		return nil, err
	}
	return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil
}

// NewCDNV1 creates a ServiceClient that may be used to access the OpenStack v1
// CDN service.
func NewCDNV1(client *gophercloud.ProviderClient, eo gophercloud.EndpointOpts) (*gophercloud.ServiceClient, error) {
	eo.ApplyDefaults("cdn")
	url, err := client.EndpointLocator(eo)
	if err != nil {
		return nil, err
	}
	return &gophercloud.ServiceClient{ProviderClient: client, Endpoint: url}, nil
}
<|endoftext|>


<commit_before>package quiclatest

import "github.com/ami-GS/gQUIC/latest/qtype"

type Session struct {
	// tls config
	// connection
	DestConnID      qtype.ConnectionID
	SrcConnID       qtype.ConnectionID
	DoneHandShake   bool
	conn            *Connection
	recvPacketChann chan Packet
	streamManager   *StreamManager
}

func NewSession(conn *Connection, dstConnID, srcConnID qtype.ConnectionID) *Session {
	sess := &Session{
		DestConnID:      dstConnID,
		SrcConnID:       srcConnID,
		conn:            conn,
		recvPacketChann: make(chan Packet),
	}
	sess.streamManager = &StreamManager{
		streamMap: make(map[uint64]Stream),
		sess:      sess,
	}
	return sess

}

func (s *Session) SendPacket(packet Packet) error {
	wire, err := packet.GetWire()
	if err != nil {
		return err
	}
	return s.conn.Write(wire)
}
func (s *Session) RecvPacketLoop() {
	for {
		select {
		case p := <-s.recvPacketChann:
			// TODO: parallel?
			s.ReceivePacket(p)
		default:
		}
	}
}

func (s *Session) ReceivePacket(p Packet) {
	//TODO: apply packets
}
<commit_msg>add Packet and Frame handler<commit_after>package quiclatest

import "github.com/ami-GS/gQUIC/latest/qtype"

type Session struct {
	// tls config
	// connection
	DestConnID      qtype.ConnectionID
	SrcConnID       qtype.ConnectionID
	DoneHandShake   bool
	conn            *Connection
	recvPacketChann chan Packet
	streamManager   *StreamManager
}

func NewSession(conn *Connection, dstConnID, srcConnID qtype.ConnectionID) *Session {
	sess := &Session{
		DestConnID:      dstConnID,
		SrcConnID:       srcConnID,
		conn:            conn,
		recvPacketChann: make(chan Packet),
	}
	sess.streamManager = &StreamManager{
		streamMap: make(map[uint64]Stream),
		sess:      sess,
	}
	return sess

}

func (s *Session) SendPacket(packet Packet) error {
	wire, err := packet.GetWire()
	if err != nil {
		return err
	}
	return s.conn.Write(wire)
}
func (s *Session) RecvPacketLoop() {
	for {
		select {
		case p := <-s.recvPacketChann:
			// TODO: parallel?
			s.HandlePacket(p)
		default:
		}
	}
}

func (s *Session) HandlePacket(p Packet) {
	switch p.(type) {
	case InitialPacket:
		// must come from only client
		// RetryPacket
	case RetryPacket:
		// must come from only server
		// InitialPacket again

	}

	s.HandleFrames(p.GetFrames())
}

func (s *Session) HandleFrames(fs []Frame) error {
	for _, frame := range fs {
		switch f := frame.(type) {
		case PaddingFrame:
		case ConnectionCloseFrame:
		case ApplicationCloseFrame:
		case MaxDataFrame:
		case MaxStreamIDFrame:
		case PingFrame:
		case BlockedFrame:
		case StreamIDBlockedFrame:
		case NewConnectionIDFrame:
		case AckFrame:
		case PathChallengeFrame:
		case PathResponseFrame:
		case StreamFrame:
			s.streamManager.handleStreamFrame(&f)
		case RstStreamFrame:
			s.streamManager.handleRstStreamFrame(&f)
		case MaxStreamDataFrame:
			s.streamManager.handleMaxStreamDataFrame(&f)
		case StreamBlockedFrame:
			s.streamManager.handleStreamBlockedFrame(&f)
		case StopSendingFrame:
			s.streamManager.handleStopSendingFrame(&f)
		default:
			// error
			return nil
		}
	}
	return nil
}
<|endoftext|>


<commit_before>package lib

import (
	"encoding/base64"
	"fmt"
	"math/big"
	"regexp"
	"sort"
	"strings"

	"github.com/okeuday/erlang_go/v2/erlang"
)

type UpdateSequence struct {
	Node  string
	Range []*big.Int
	Seq   int
}

func convertNode(t interface{}) string {
	return string(t.(erlang.OtpErlangAtom))
}

func convertRange(t interface{}) []*big.Int {
	value := t.(erlang.OtpErlangList).Value
	decoded := make([]*big.Int, len(value))
	for i, r := range value {
		switch rType := r.(type) {
		case uint8:
			decoded[i] = big.NewInt(int64(rType))
		case int32:
			decoded[i] = big.NewInt(int64(rType))
		case *big.Int:
			decoded[i] = rType
		default:
			fmt.Printf("%v == %T\n", rType, rType)
			// todo return err
			decoded[i] = big.NewInt(0)
		}
	}
	return decoded
}

func convertSeq(t interface{}) int {
	switch rType := t.(type) {
	case uint8:
		return int(rType)
	case int32:
		return int(rType)
	case erlang.OtpErlangTuple:
		return int(rType[0].(uint8))
	default:
		fmt.Printf("%v == %T\n", rType, rType)
		// todo return err
		return -1
	}
}

func convert(terms interface{}) []UpdateSequence {
	res := make([]UpdateSequence, 0)
	value := terms.(erlang.OtpErlangList).Value
	for _, term := range value {
		conv := term.(erlang.OtpErlangTuple)
		//log.Printf("c: %v", conv)

		t := UpdateSequence{
			Node:  convertNode(conv[0]),
			Range: convertRange(conv[1]),
			Seq:   convertSeq(conv[2]),
		}

		//log.Printf("converted: %v", t)
		res = append(res, t)
	}
	return res
}

func DecodeUpdateSeq(updateSeq string) ([]UpdateSequence, error) {
	//start := time.Now()
	//defer func() {
	//	fmt.Printf("Duration: %s\n", time.Since(start))
	//}()

	encoded := string(regexp.MustCompile("^\\d+-").ReplaceAll([]byte(updateSeq), []byte{}))

	b1 := strings.Replace(encoded, "-", "+", -1)
	b2 := strings.Replace(b1, "_", "/", -1)

	padding := strings.Repeat("=", (4-len(b2)%4)%4)

	var sb strings.Builder
	sb.WriteString(b2)
	sb.WriteString(padding)

	payload := make([]byte, base64.StdEncoding.DecodedLen(len(sb.String())))
	n, err := base64.StdEncoding.Decode(payload, []byte(sb.String()))
	if err != nil {
		return nil, err
	}
	terms, err := erlang.BinaryToTerm(payload[:n])
	if err != nil {
		return nil, err
	}
	decoded := convert(terms)
	sort.Slice(decoded, func(i, j int) bool {
		return decoded[i].Range[0].Cmp(decoded[j].Range[0]) < 0
	})
	return decoded, nil
}
<commit_msg>Fix the panic when trying to convert an int32 to an uint8<commit_after>package lib

import (
	"encoding/base64"
	"fmt"
	"math/big"
	"regexp"
	"sort"
	"strings"

	"github.com/okeuday/erlang_go/v2/erlang"
)

type UpdateSequence struct {
	Node  string
	Range []*big.Int
	Seq   int
}

func convertNode(t interface{}) string {
	return string(t.(erlang.OtpErlangAtom))
}

func convertRange(t interface{}) []*big.Int {
	value := t.(erlang.OtpErlangList).Value
	decoded := make([]*big.Int, len(value))
	for i, r := range value {
		switch rType := r.(type) {
		case uint8:
			decoded[i] = big.NewInt(int64(rType))
		case int32:
			decoded[i] = big.NewInt(int64(rType))
		case *big.Int:
			decoded[i] = rType
		default:
			fmt.Printf("%v == %T\n", rType, rType)
			// todo return err
			decoded[i] = big.NewInt(0)
		}
	}
	return decoded
}

func convertSeq(t interface{}) int {
	switch rType := t.(type) {
	case uint8:
		return int(rType)
	case int32:
		return int(rType)
	case erlang.OtpErlangTuple:
		// we should be able to use recursion,
		// but we're not entirely sure why this is
		// required in the first place.
		// so let's try to have a plain stack trace
		// in case the issue #106 isn't fixed, yet.
		//return convertSeq(rType[0])
		switch ttype := rType[0].(type) {
		case uint8:
			return int(ttype)
		case int32:
			return int(ttype)
		default:
			fmt.Printf("%v == %T\n", ttype, ttype)
			// todo return err
			return -1
		}
	default:
		fmt.Printf("%v == %T\n", rType, rType)
		// todo return err
		return -1
	}
}

func convert(terms interface{}) []UpdateSequence {
	res := make([]UpdateSequence, 0)
	value := terms.(erlang.OtpErlangList).Value
	for _, term := range value {
		conv := term.(erlang.OtpErlangTuple)
		//log.Printf("c: %v", conv)

		t := UpdateSequence{
			Node:  convertNode(conv[0]),
			Range: convertRange(conv[1]),
			Seq:   convertSeq(conv[2]),
		}

		//log.Printf("converted: %v", t)
		res = append(res, t)
	}
	return res
}

func DecodeUpdateSeq(updateSeq string) ([]UpdateSequence, error) {
	//start := time.Now()
	//defer func() {
	//	fmt.Printf("Duration: %s\n", time.Since(start))
	//}()

	encoded := string(regexp.MustCompile("^\\d+-").ReplaceAll([]byte(updateSeq), []byte{}))

	b1 := strings.Replace(encoded, "-", "+", -1)
	b2 := strings.Replace(b1, "_", "/", -1)

	padding := strings.Repeat("=", (4-len(b2)%4)%4)

	var sb strings.Builder
	sb.WriteString(b2)
	sb.WriteString(padding)

	payload := make([]byte, base64.StdEncoding.DecodedLen(len(sb.String())))
	n, err := base64.StdEncoding.Decode(payload, []byte(sb.String()))
	if err != nil {
		return nil, err
	}
	terms, err := erlang.BinaryToTerm(payload[:n])
	if err != nil {
		return nil, err
	}
	decoded := convert(terms)
	sort.Slice(decoded, func(i, j int) bool {
		return decoded[i].Range[0].Cmp(decoded[j].Range[0]) < 0
	})
	return decoded, nil
}
<|endoftext|>