util

package module
v0.0.0-...-e88be9e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 30, 2017 License: MIT Imports: 23 Imported by: 0

README

util

util is some utilities used by me!

Documentation

Index

Constants

View Source
const (
	Fcstart = 101
	Fcstop  = 102
	Fostart = 111
	Fostop  = 112
	Ffstart = 21
	Ffstop  = 22
)

code of string format

Variables

View Source
var (
	// Sf is the alias of fmt.Sprintf
	Sf = fmt.Sprintf
	// Ff is the alias of fmt.Fprintf
	Ff = fmt.Fprintf
)
View Source
var (

	// LogColorStringFuncs maps to a serious of [*]ColorString functions with key as golog.Level
	LogColorStringFuncs = map[string]func(a ...interface{}) string{

		"disable": fmt.Sprint,
		"error":   errorColorStr,
		"warn":    warnColorStr,
		"info":    infoColorStr,
		"debug":   debugColorStr,
		"debug2":  debugColorStr2,
		"debug3":  debugColorStr2,
		"goro":    goroColorStr,
	}

	// LogfMapFuncs are the maps of Glog functions
	LogfMapFuncs = map[string]func(string, ...interface{}){
		"error": Glog.Errorf,
		"warn":  Glog.Warnf,
		"info":  Glog.Infof,
		"debug": Glog.Debugf,
		"fatal": Glog.Fatalf,
	}

	// LogMapFuncs are the maps of Glog functions
	LogMapFuncs = map[string]func(...interface{}){
		"error": Glog.Error,
		"warn":  Glog.Warn,
		"info":  Glog.Info,
		"debug": Glog.Debug,
		"fatal": Glog.Fatal,
		"print": Glog.Print,
	}
)
View Source
var (

	// Verbose activates display of messages on console
	Verbose = true

	// ColorsOn activates use of colors on console
	ColorsOn = true

	// Format is the format of message
	Format = map[int]string{

		Fcstart: "# Start to configure. -- %q\n",
		Fcstop:  "# Configuration has been concluded. -- %q\n",

		Fostart: "# Start to get case-options. -- %q\n",
		Fostop:  "# Case-options has been concluded. -- %q\n",

		Ffstart: "* Function %q start.\n",
		Ffstop:  "* Function %q stop.\n",
	}
)
View Source
var (
	Pfstart = PfCyan
	Pfstop  = PfBlue
	Pfsep   = Pfdyel2
	Prun    = PfYel
	Pchk    = Pfgreen2
	Pstat   = Pfyel
	Plog    = Pf
	Pinfo   = Pfcyan2
	Pwarn   = Pforan
	Perr    = Pfred
	Pdebug  = Pfgreen2
)

specified function for output

View Source
var (

	// Glog is a logger of golog
	Glog = golog.New() // Logger.Child("util")
)

Functions

func AlignToRight

func AlignToRight(s string, size int) string

AlignToRight returns a string aligned to right

func AlignedString

func AlignedString(str string, lenres int, filledChar string, alignFlag AlginedFlag) (res string)

AlignedString returns the aligned string what you want

str 		: the original string
lenres 		: the length of `res` string
filledChar 	: fill `filedChar` in the spaces of `res` string
align		= 1 	: align at the left (default)
			= 0		: align at the center
			= -1	: align at the right

outputs

res		: the aligned string

func Amax

func Amax(x ...float64) (idx int, xmax float64, err error)

Amax return the maximum absolute value and the corressponding index of loation in x[]

func AppendToFile

func AppendToFile(fn string, buffer ...*bytes.Buffer)

AppendToFile appends data to an existent (or new) file

func ArgsTable

func ArgsTable(title string, data ...interface{}) string

ArgsTable prints a nice table with input arguments

Input:
 title -- title of table; e.g. INPUT ARGUMENTS
 data  -- sets of THREE items in the following order:
               description, key, value, ...
               description, key, value, ...
                    ...
               description, key, value, ...

func ArgsTableN

func ArgsTableN(title string, nledsp int, isleft bool, heads []string, data ...interface{}) string

ArgsTableN prints a nice table with input arguments

 Input:
  title -- title of table; e.g. INPUT ARGUMENTS
	 heads -- heads of table; e.g. []string{ col1,  col2, ... }
	 nledsp -- length of leading spaces in every row
  data  -- sets of THREE items in the following order:
                column1, column2, column3, ...
                column1, column2, column3, ...
                     ...
                column1, column2, column3, ...

func Atob

func Atob(val string) (bres bool)

Atob converts string to bool

func Atof

func Atof(val string) (res float64)

Atof converts string to float64

func Atoi

func Atoi(val string) (res int)

Atoi converts string to integer

func BtoStr

func BtoStr(bs []byte) string

BtoStr convert []byte to string

func Btoa

func Btoa(flag bool) string

Btoa converts flag to string

Note: true  => "true"
      false => "false"

func Btoi

func Btoi(flag bool) int

Btoi converts flag to interger

Note: true  => 1
      false => 0

func BytesSizeToString

func BytesSizeToString(byteCount int) string

BytesSizeToString convert bytes to a human-readable size

func CallerInfo

func CallerInfo(idx int)

CallerInfo returns the file and line positions where an error occurred

idx -- use idx=2 to get the caller of Panic

func CallerName

func CallerName(idx int) string

CallerName return the name of function calling

func CheckErr

func CheckErr(err error)

CheckErr check error

func CountChars

func CountChars(str string) (nc, ne, n int)

CountChars returns the number of each other of chinses and english characters

func DblSf

func DblSf(msg string, slice []float64) string

DblSf is the Sprintf for a slice of float64 (without brackets)

func DebugPrintCaller

func DebugPrintCaller()

DebugPrintCaller print the name of function called and calling

func EnableLoggerOutToFile

func EnableLoggerOutToFile(levelname string)

EnableLoggerOutToFile enables the "Glog" out to os.Stderr and os.File

func Err

func Err(msg string, prm ...interface{}) error

Err returns a new error

func FieldValueFromTagMap

func FieldValueFromTagMap(e interface{}, tag string, ignoredFields ...string) (out map[string]interface{}, err error)

FieldValueFromTagMap returns a string to interface map that uses as key the tag name, key: tag name for the given field value: the value of the field

func FieldValueMap

func FieldValueMap(e interface{}, ignoredFields ...string) (out map[string]interface{}, err error)

FieldValueMap returns a string to interface map, key: field as defined on the struct value: the value of the field

func FnExt

func FnExt(fn string) string

FnExt returns the extension of a file name. The extension is the suffix beginning at the final dot in the final element of path; it is empty if there is no dot.

func FnKey

func FnKey(fn string) string

FnKey returns the file name key (without path and extension, if any)

func GetColStr

func GetColStr(s string, size int, isleft bool) string

GetColStr return string use in field

func GetErrMessage

func GetErrMessage(err error) string

GetErrMessage get error message if error

func GetFieldsInfo

func GetFieldsInfo(obj interface{},
	tagname string,
	ignoreFields ...string) (fields, types, kinds, tags []string, err error)

GetFieldsInfo return information of fields

func GetSizes

func GetSizes(h []string) []int

GetSizes is filled and returns len(e), e is element of slice h

func GetTags

func GetTags(obj interface{}, tag string) map[string]string

GetTags returns map["Field"]="tag_value"

func GetTypes

func GetTypes(obj interface{}) map[string]string

GetTypes returns map["Field"]="Type"

func Hstring

func Hstring(str string, explen int, fillchar string, align int) (rstr string)

Hstring return the formatted string what you wants. parameters

str 		: the original string
explen 		: the length of 'rstr' string
fillchar 	: fill 'fillchar' in the spaces of 'rstr' string
align		= 1 	: align at the left (default)
			= 0		: align at the center
			= -1	: align at the right

outputs

rstr		: the return string
err			: the error if therer are errors

func Imax

func Imax(a, b int) int

Imax returns the maximum value

func Imin

func Imin(a, b int) int

Imin returns the minimum value

func InitLogger

func InitLogger()

InitLogger initialize logger's environment

func IntRange

func IntRange(args ...int) <-chan int

IntRange using args [start, stop, step] to generate a set of serial numbers

func IntSf

func IntSf(msg string, slice []int) string

IntSf is the Sprintf for a slice of integers (without brackets)

func IsChineseChar

func IsChineseChar(str string) bool

IsChineseChar judges whether the chinese character exists ?

func IsFileExist

func IsFileExist(filename string) bool

IsFileExist checks whether a file exist

func Isum

func Isum(vals ...int) int

Isum returns the summation

func Itob

func Itob(val int) bool

Itob converts from integer to bool

Note: only zero returns false
      anything else returns true

func LogColorString

func LogColorString(levelname, s string) string

LogColorString gives a colorful string w.r.t. levelname

func Max

func Max(a, b float64) float64

Max returns the maximum value

func Min

func Min(a, b float64) float64

Min returns the minimum value

func Names

func Names(e interface{}, ignoredFields ...string) (out []string, err error)

Names returns an array with all the field names (with the same order) as defined on the struct

func NamesFromTag

func NamesFromTag(e interface{}, tag string, ignoredFields ...string) (out []string, err error)

NamesFromTag returns an array with all the tag names for each field

func NewLogFile

func NewLogFile() (*os.File, error)

NewLogFile get a new logging file handler

func OpenFileR

func OpenFileR(fn string) (fil *os.File, err error)

OpenFileR opens a file for reading data

func Panic

func Panic(msg string, prm ...interface{})

Panic panicks

func PathKey

func PathKey(fn string) string

PathKey returs the full path except the extension

func Pf

func Pf(format string, prm ...interface{})

Pf prints formatted string

func PfBlue

func PfBlue(format string, prm ...interface{})

PfBlue prints formatted string in high intensity blue

func PfCyan

func PfCyan(format string, prm ...interface{})

PfCyan prints formatted string in high intensity cyan

func PfGreen

func PfGreen(format string, prm ...interface{})

PfGreen prints formatted string in high intensity green

func PfMag

func PfMag(format string, prm ...interface{})

PfMag prints formatted string in high intensity magenta

func PfRed

func PfRed(format string, prm ...interface{})

PfRed prints formatted string in high intensity red

func PfWhite

func PfWhite(format string, prm ...interface{})

PfWhite prints formatted string in high intensity white

func PfYel

func PfYel(format string, prm ...interface{})

PfYel prints formatted string in high intensity yello

func Pfblue

func Pfblue(format string, prm ...interface{})

Pfblue prints formatted string in blue

func Pfblue2

func Pfblue2(format string, prm ...interface{})

Pfblue2 prints formatted string in another shade of blue

func Pfcyan

func Pfcyan(format string, prm ...interface{})

Pfcyan prints formatted string in cyan

func Pfcyan2

func Pfcyan2(format string, prm ...interface{})

Pfcyan2 prints formatted string in another shade of cyan

func Pfdgreen

func Pfdgreen(format string, prm ...interface{})

Pfdgreen prints formatted string in dark green

func Pfdyel

func Pfdyel(format string, prm ...interface{})

Pfdyel prints formatted string in dark yellow

func Pfdyel2

func Pfdyel2(format string, prm ...interface{})

Pfdyel2 prints formatted string in another shade of dark yellow

func Pfgreen

func Pfgreen(format string, prm ...interface{})

Pfgreen prints formatted string in green

func Pfgreen2

func Pfgreen2(format string, prm ...interface{})

Pfgreen2 prints formatted string in another shade of green

func Pfgrey

func Pfgrey(format string, prm ...interface{})

Pfgrey prints formatted string in grey

func Pfgrey2

func Pfgrey2(format string, prm ...interface{})

Pfgrey2 prints formatted string in another shade of grey

func Pflmag

func Pflmag(format string, prm ...interface{})

Pflmag prints formatted string in light magenta

func Pfmag

func Pfmag(format string, prm ...interface{})

Pfmag prints formatted string in magenta

func Pforan

func Pforan(format string, prm ...interface{})

Pforan prints formatted string in orange

func Pfpink

func Pfpink(format string, prm ...interface{})

Pfpink prints formatted string in pink

func Pfpurple

func Pfpurple(format string, prm ...interface{})

Pfpurple prints formatted string in purple

func Pfred

func Pfred(format string, prm ...interface{})

Pfred prints formatted string in red

func Pfyel

func Pfyel(format string, prm ...interface{})

Pfyel prints formatted string in yellow

func Pl

func Pl()

Pl prints new line

func PrintSepline

func PrintSepline(n int)

PrintSepline print the separate-line

func ReadFile

func ReadFile(fn string) (b []byte, err error)

ReadFile reads bytes from a file

func ReadLines

func ReadLines(b []byte, cb ReadLinesCallback)

ReadLines reads lines from a []byte and calls ReadLinesCallback to process each line being read

func ReadLinesFile

func ReadLinesFile(fil *os.File, cb ReadLinesCallback) (oserr error)

ReadLinesFile reads lines from a file and calls ReadLinesCallback to process each line being read

func RemoveAll

func RemoveAll(key string)

RemoveAll deletes all files matching filename specified by key (be careful)

func Rpad

func Rpad(s string, padding int) string

Rpad adds padding to the right of a string.

func Spaces

func Spaces(num int) string

Spaces returns the number of spaces

func SplitFloats

func SplitFloats(str string) (res []float64)

SplitFloats splits space-separated float numbers

func SplitInts

func SplitInts(str string) (res []int)

SplitInts splits space-separated integers

func SplitKeys

func SplitKeys(keys string) []string

SplitKeys splits keys separeted by spaces

func SplitSpacesQuoted

func SplitSpacesQuoted(str string) (res []string)

SplitSpacesQuoted splits string with quoted substrings. e.g. " a,b, 'c', \"d\" "

func SplitWithinParentheses

func SplitWithinParentheses(s string) (res []string)

SplitWithinParentheses extracts arguments (substrings) within brackets e.g.: "(arg1, (arg2.1, arg2.2), arg3, arg4, (arg5.1,arg5.2, arg5.3 ) )"

func Startfunc

func Startfunc(fid int)

Startfunc print the message at the start of function

func Stopfunc

func Stopfunc(fid int)

Stopfunc print the message at the start of function

func StrSf

func StrSf(msg string, slice []string) string

StrSf is the Sprintf for a slice of string (without brackets)

func StrSpaces

func StrSpaces(n int) (l string)

StrSpaces returns a line with spaces

func StrThickLine

func StrThickLine(n int) (l string)

StrThickLine returns a thick line (using '=')

func StrThinLine

func StrThinLine(n int) (l string)

StrThinLine returns a thin line (using '-')

func StrValues

func StrValues(e interface{}, ignoredFields ...string) ([]string, error)

StrValues returns an string array with all the values

func StrValuesWithFunc

func StrValuesWithFunc(e interface{},
	cb ValuesCallback,
	ignoredFields ...string) (out []string, err error)

StrValuesWithFunc returns an interface array with all the string-values

func Sum

func Sum(vals ...float64) float64

Sum returns the summation

func TodayFilename

func TodayFilename() string

TodayFilename get a filename based on the date, file logs works that way the most times but these are just a sugar.

func Values

func Values(e interface{}, ignoredFields ...string) (out []interface{}, err error)

Values returns an interface array with all the values

func ValuesWithFunc

func ValuesWithFunc(e interface{},
	cb ValuesCallback,
	ignoredFields ...string) (out []interface{}, err error)

ValuesWithFunc returns an interface array with all the values

func WriteBytesToFile

func WriteBytesToFile(fn string, b []byte)

WriteBytesToFile writes slice of bytes to a new file

func WriteFile

func WriteFile(fn string, buffer ...*bytes.Buffer)

WriteFile writes data to a new file with given bytes.Buffer(s)

Types

type AlginedFlag

type AlginedFlag int8

AlginedFlag is the type to assign align-format

const (
	AlginedLeft AlginedFlag = iota
	AlginedMiddle
	AlignedRight
)

Align format

type FuncCallerInfo

type FuncCallerInfo struct {
	PackageName string
	FileName    string
	FuncName    string
	Line        int
}

FuncCallerInfo describes the information of callers of function

func RetrieveCallerInfo

func RetrieveCallerInfo(idx int) *FuncCallerInfo

RetrieveCallerInfo retrieve the information of callers of function

type ReadLinesCallback

type ReadLinesCallback func(idx int, line string) (stop bool)

ReadLinesCallback is used in ReadLines to process line by line during reading of a file

type ValuesCallback

type ValuesCallback func(f reflect.StructField, v interface{}) (value interface{}, isIgnored bool)

ValuesCallback is used in (Str)ValuesWithFunc to process line by line during retriving of

a field-value
example:

var cb ValuesCallback = func(fieldName string, v interface{}) (value interface{}, isIgnored bool) { switch fieldName { case "Model", "Details":

value, isIgnored = nil, true

case "UINumber":

a := v.(string)
value, isIgnored = interface{}(a[0:2]+"-"+a[2:]), false

case "Date":

value, isIgnored = interface{}(v.(time.Time).Format(ShortDateFormat)), false

case "Total":

	value, isIgnored = interface{}(fmt.Sprintf("%.1f", v.(float64))), false
}

default:

value, isIgnored = v, false

return value, isIgnored }

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL