Documentation ¶
Index ¶
- func Archive(inFilePath string, writer io.Writer, progress ProgressFunc) (err error)
- func ArchiveFile(inFilePath string, outFilePath string, progress ProgressFunc) (err error)
- func ArithmeticMean(list []float64) (mean float64)
- func BinaryLog(d []byte)
- func BinaryRead(r io.Reader, args ...interface{}) (err error)
- func BinaryWrite(w io.Writer, args ...interface{})
- func BoundingBox(pairs []PairType) (lf, rt, tp, bt float64)
- func CaptureOutput(fl **os.File) (get func() *strings.Builder, err error)
- func CaptureStdOutAndErr() (get func() (outStr, errStr string), err error)
- func Cluster(pairs []PairType, minPts int, gapX float64) [][]PairType
- func FileCopy(srcFileStr, dstFileStr string) (err error)
- func Float64ToStr(v float64, precision int) (str string)
- func Float64ToStrSig(val float64, dec, sep string, sigDig, grpLen int) (str string)
- func GeometricMean(list []float64) (mean float64)
- func Int32ToStr(v int32) string
- func IntToStr(v int64) (str string)
- func JSONGet(r io.Reader, valPtr interface{}) (err error)
- func JSONGetFile(fileStr string, valPtr interface{}) (err error)
- func JSONPut(w io.Writer, val interface{}) (err error)
- func JSONPutFile(fileStr string, val interface{}) (err error)
- func LinearPointSlope(x, y, slope float64) (intercept float64)
- func LinearY(slope, intercept, x float64) (y float64)
- func LogWriter(p Printer) io.WriteCloser
- func ParseAddrPort(str string) (ip net.IP, port uint16, err error)
- func RootMeanSquare(list []float64) (rms float64)
- func RootMeanSquareLinear(xList, yList []float64, intercept, slope float64) (rms float64)
- func Shell(wr io.Writer, rdr io.Reader, cmdStr string, args ...string) (err error)
- func ShellBuf(inBuf []byte, cmdStr string, args ...string) (outBuf []byte, err error)
- func Sort(Len int, Less func(int, int) bool, Swap func(int, int))
- func StrCurrency100(amt100 int64) (str string)
- func StrDelimit(str string, sepstr string, sepcount int) string
- func StrDotPair(fullLen int, lfStr, rtStr string) string
- func StrDotPairFormat(fullLen int, lfStr, rtFmtStr string, args ...interface{}) string
- func StrDots(str string, fullLen int) string
- func StrHeader(fullLen int, fill string, str string) (hdrStr string)
- func StrHeaderFormat(fullLen int, fill string, format string, args ...interface{}) (hdrStr string)
- func StrIf(cond bool, aStr string, bStr string) string
- func ToInt32(str string) (v int32, err error)
- func ToUint32(str string) (v uint32, err error)
- func Unarchive(reader io.ReaderAt, readerSize int64, outFilePath string, ...) (err error)
- func UnarchiveFile(inFilePath string, outFilePath string, progress ProgressFunc) (err error)
- type Address
- type AverageType
- type Distance
- type Duration
- type JSONBuilder
- func (j *JSONBuilder) ArrayClose()
- func (j *JSONBuilder) ArrayOpen()
- func (j *JSONBuilder) Element(val interface{})
- func (j *JSONBuilder) Error() (err error)
- func (j *JSONBuilder) KeyArrayOpen(key string)
- func (j *JSONBuilder) KeyElement(key string, val interface{})
- func (j *JSONBuilder) KeyObjectOpen(key string)
- func (j *JSONBuilder) ObjectClose()
- func (j *JSONBuilder) ObjectOpen()
- func (j *JSONBuilder) Reset()
- func (j *JSONBuilder) String() (jsonStr string)
- type LinearEquationType
- type PairType
- type Printer
- type ProgressFunc
- type RangeType
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Archive ¶
func Archive(inFilePath string, writer io.Writer, progress ProgressFunc) (err error)
Archive compresses a file/directory to a writer
If the path ends with a separator, then the contents of the folder at that path are at the root level of the archive, otherwise, the root of the archive contains the folder as its only item (with contents inside).
If progress is not nil, it is called for each file added to the archive.
Example ¶
Demonstrate archiving a directory
package main import ( "fmt" "io/ioutil" "os" "path/filepath" "github.com/jung-kurt/etc/go/util" ) func main() { var err error const dirStr = "test" const zipStr = "test.zip" os.RemoveAll(dirStr) os.Remove(zipStr) err = os.Mkdir(dirStr, 0755) if err == nil { for j := 0; j < 3 && err == nil; j++ { fileStr := filepath.Join(dirStr, fmt.Sprintf("file%02d.txt", j)) err = ioutil.WriteFile(fileStr, []byte(fileStr), 0644) } if err == nil { err = util.ArchiveFile(dirStr, "test.zip", func(fileStr string) { fmt.Printf("archiving %s...\n", fileStr) }) if err == nil { fmt.Printf("successfully created %s\n", zipStr) os.RemoveAll(dirStr) err = util.UnarchiveFile(zipStr, dirStr, func(fileStr string) { fmt.Printf("extracting %s...\n", fileStr) }) if err == nil { fmt.Printf("successfully unarchived %s\n", zipStr) } os.RemoveAll(dirStr) os.Remove(zipStr) } } } if err != nil { fmt.Printf("archive error: %s\n", err) } }
Output: archiving test/file00.txt... archiving test/file01.txt... archiving test/file02.txt... successfully created test.zip extracting test/file00.txt... extracting test/file01.txt... extracting test/file02.txt... successfully unarchived test.zip
func ArchiveFile ¶
func ArchiveFile(inFilePath string, outFilePath string, progress ProgressFunc) (err error)
ArchiveFile compresses a file/directory to a file
See Archive() doc
func ArithmeticMean ¶
ArithmeticMean returns the sum of the values in list divided by the number of values.
func BinaryLog ¶
func BinaryLog(d []byte)
BinaryLog logs the binary data specified by d in combined hexadecimal/ascii lines of up to sixteen bytes.
Example ¶
Demonstrate the binary read, write, and log routines
package main import ( "bytes" "log" "os" "github.com/jung-kurt/etc/go/util" ) func main() { type recType struct { a uint8 b uint16 c uint32 d uint64 e int8 f int16 g int32 h int64 } var err error show := func(hdrStr string, r recType) { log.Printf("%s", hdrStr) log.Printf("a: %d, b: %d, c: %d, d: %d, e: %d, f: %d, g: %d, h: %d", r.a, r.b, r.c, r.d, r.e, r.f, r.g, r.h) } load := func() (sl []byte) { var r recType var buf bytes.Buffer r = recType{a: 12, b: 142, c: 48456, d: 6581, e: -2, f: -765, g: 2776, h: -54232} show("BinaryWrite", r) util.BinaryWrite(&buf, r.a, r.b, r.c, r.d, r.e, r.f, r.g, r.h) sl = buf.Bytes() return } log.SetFlags(0) log.SetOutput(os.Stdout) sl := load() log.Printf("packed bytes") util.BinaryLog(sl) var r recType err = util.BinaryRead(bytes.NewReader(sl), &r.a, &r.b, &r.c, &r.d, &r.e, &r.f, &r.g, &r.h) if err == nil { show("BinaryRead", r) } else { log.Printf("error reading packed bytes: %s", err) } }
Output: BinaryWrite a: 12, b: 142, c: 48456, d: 6581, e: -2, f: -765, g: 2776, h: -54232 packed bytes 00000000 0c 8e 00 48 bd 00 00 b5 19 00 00 00 00 00 00 fe |...H............| 00000000 03 fd d8 0a 00 00 28 2c ff ff ff ff ff ff |......(,......| BinaryRead a: 12, b: 142, c: 48456, d: 6581, e: -2, f: -765, g: 2776, h: -54232
func BinaryRead ¶
BinaryRead unpacks the bytes from r into the values pointed to by the arguments specified by args. Little endian format is used. An error is returned if a problem occurs.
func BinaryWrite ¶
BinaryWrite packs the values specified by args to the writer specified by w. Little endian format is used.
func BoundingBox ¶
BoundingBox returns the smallest and greatest values of X and Y in the specified slice of coordinates.
func CaptureOutput ¶
CaptureOutput begins buffering the content that is written to fl. It returns a retrieval function and an error. If no error occurs when setting up the buffering, that is, err is nil, the retrieval function can be called to stop the buffering and obtain the populated string buffer.
Example ¶
package main import ( "fmt" "os" "strings" "github.com/jung-kurt/etc/go/util" ) func main() { var err error var getOut, getErr func() *strings.Builder var errBuf, outBuf *strings.Builder getOut, err = util.CaptureOutput(&os.Stdout) if err == nil { getErr, err = util.CaptureOutput(&os.Stderr) if err == nil { for j := 0; j < 5; j++ { fmt.Printf("line %d\n", j) fmt.Fprintf(os.Stderr, "error %d\n", j) } errBuf = getErr() outBuf = getOut() fmt.Printf("--- Stderr (%d) ---\n%s", errBuf.Len(), errBuf.String()) fmt.Printf("--- Stdout (%d)---\n%s", outBuf.Len(), outBuf.String()) } } if err != nil { fmt.Fprintf(os.Stderr, "%s\n", err) } }
Output: --- Stderr (40) --- error 0 error 1 error 2 error 3 error 4 --- Stdout (35)--- line 0 line 1 line 2 line 3 line 4
func CaptureStdOutAndErr ¶
CaptureStdOutAndErr begins buffering the content that is written to stdout and stderr. It returns a retrieval function and an error. If no error occurs when setting up the buffering, that is, err is nil, the retrieval function can be called to stop the buffering and obtain the accumulated output. The return values of the retrieval function are the content written to stdout and stderr respectively.
Example ¶
package main import ( "fmt" "os" "github.com/jung-kurt/etc/go/util" ) func main() { get, err := util.CaptureStdOutAndErr() if err == nil { for j := 0; j < 3; j++ { fmt.Printf("line %d\n", j) fmt.Fprintf(os.Stderr, "error %d\n", j) } outStr, errStr := get() // This terminates buffering and returns accumulated content fmt.Printf("--- Stderr (%d) ---\n%s", len(errStr), errStr) fmt.Printf("--- Stdout (%d)---\n%s", len(outStr), outStr) } if err != nil { fmt.Fprintf(os.Stderr, "%s\n", err) } }
Output: --- Stderr (24) --- error 0 error 1 error 2 --- Stdout (21)--- line 0 line 1 line 2
func Cluster ¶
Cluster breaks apart pairs into zero or more slices that each contain at least minPts pairs and have gaps between X values no greater than gapX. Elements in pairs must be ordered from low X value to high.
Example ¶
This example demonstrates data point clustering
package main import ( "fmt" "math/rand" "github.com/jung-kurt/etc/go/util" ) func main() { var list []util.PairType var clList [][]util.PairType var x float64 rnd := rand.New(rand.NewSource(42)) for j := 0; j < 100; j++ { x += 6 * rnd.Float64() list = append(list, util.PairType{X: x, Y: x}) } clList = util.Cluster(list, 6, 4) for _, list = range clList { fmt.Printf("[") for _, val := range list { fmt.Printf("%8.3f", val.X) } lf, rt, _, _ := util.BoundingBox(list) fmt.Printf("] (%.3f - %.3f)\n", lf, rt) } }
Output: [ 2.238 2.634 6.259 7.512 7.775 10.074] (2.238 - 10.074) [ 27.848 29.156 31.326 32.053 36.037 38.834] (27.848 - 38.834) [ 58.879 59.595 61.636 63.355 64.718 68.633 68.885] (58.879 - 68.885) [ 166.203 169.399 170.803 173.522 175.232 175.467 177.020] (166.203 - 177.020) [ 223.779 227.606 230.851 233.541 234.132 237.015] (223.779 - 237.015)
func FileCopy ¶
FileCopy copies the source file identified by srcFileStr to the destination file identified by dstFileStr. If the destination file exists it is overwritten, otherwise it is created. Permission bits are carried over from the source file.
Example ¶
This example tests the file copy routine
package main import ( "bytes" "fmt" "io/ioutil" "os" "github.com/jung-kurt/etc/go/util" ) func main() { var err error var a, b []byte a = []byte("12345678") err = ioutil.WriteFile("_a", a, 0600) if err == nil { err = util.FileCopy("_a", "_b") if err == nil { b, err = ioutil.ReadFile("_b") if err == nil { if bytes.Equal(a, b) { // OK } else { err = fmt.Errorf("destination file unequal to source file") } } os.Remove("_b") } os.Remove("_a") } if err == nil { fmt.Printf("file copy successful\n") } else { fmt.Printf("%s\n", err) } }
Output: file copy successful
func Float64ToStr ¶
Float64ToStr returns a string with commas, for example, 1234 -> "1,234"
func Float64ToStrSig ¶
Float64ToStrSig returns a string representation of val adjusted to the specified number of significant digits.
Example ¶
This example demonstrates float formatting. page-breaking.
package main import ( "bytes" "fmt" "math" "github.com/jung-kurt/etc/go/util" ) func main() { var val float64 var str string var buf bytes.Buffer val = -math.Pi * 1000000 for j := 0; j < 15; j++ { buf.Reset() fmt.Fprintf(&buf, "[%20f]", val) for prec := 1; prec < 6; prec++ { str = util.Float64ToStrSig(val, ".", ",", prec, 3) fmt.Fprintf(&buf, " [%s]", str) } fmt.Println(buf.String()) val /= 10 } }
Output: [ -3141592.653590] [-3,000,000] [-3,100,000] [-3,140,000] [-3,142,000] [-3,141,600] [ -314159.265359] [-300,000] [-310,000] [-314,000] [-314,200] [-314,160] [ -31415.926536] [-30,000] [-31,000] [-31,400] [-31,420] [-31,416] [ -3141.592654] [-3,000] [-3,100] [-3,140] [-3,142] [-3,141.6] [ -314.159265] [-300] [-310] [-314] [-314.2] [-314.16] [ -31.415927] [-30] [-31] [-31.4] [-31.42] [-31.416] [ -3.141593] [-3] [-3.1] [-3.14] [-3.142] [-3.1416] [ -0.314159] [-0.3] [-0.31] [-0.314] [-0.3142] [-0.31416] [ -0.031416] [-0.03] [-0.031] [-0.0314] [-0.03142] [-0.031416] [ -0.003142] [-0.003] [-0.0031] [-0.00314] [-0.003142] [-0.0031416] [ -0.000314] [-0.0003] [-0.00031] [-0.000314] [-0.0003142] [-0.00031416] [ -0.000031] [-0.00003] [-0.000031] [-0.0000314] [-0.00003142] [-0.000031416] [ -0.000003] [-0.000003] [-0.0000031] [-0.00000314] [-0.000003142] [-0.0000031416] [ -0.000000] [-0.0000003] [-0.00000031] [-0.000000314] [-0.0000003142] [-0.00000031416] [ -0.000000] [-0.00000003] [-0.000000031] [-0.0000000314] [-0.00000003142] [-0.000000031416]
func GeometricMean ¶
GeometricMean returns the nth root of the product of the n values in list.
Example ¶
This example demonstrates the GeometricMean function
package main import ( "fmt" "github.com/jung-kurt/etc/go/util" ) func main() { list := []float64{3.1, 2.8, 3.0, 2.9, 2.9, 3.7} fmt.Printf("Geometric %.6f, Arithmetic %.6f, RMS %.6f", util.GeometricMean(list), util.ArithmeticMean(list), util.RootMeanSquare(list)) }
Output: Geometric 3.053326, Arithmetic 3.066667, RMS 3.081125
func Int32ToStr ¶
Int32ToStr returns a string with commas, for example 1234 -> "1,234"
func JSONGet ¶
JSONGet reads a JSON-encoded structure from the reader specified by r and places it into the buffer pointed to by valPtr
func JSONGetFile ¶
JSONGetFile reads a JSON-encoded structure from the file specified by fileStr and places it into the buffer pointed to by valPtr
func JSONPut ¶
JSONPut writes the value specified by val to the writer specified by w
Example ¶
This example demonstrates JSON handling
package main import ( "fmt" "io/ioutil" "os" "github.com/jung-kurt/etc/go/util" ) func main() { const fileStr = "example.json" type cfgType struct { Addr util.Address DstA, DstB, DstC, DstD, DstE, DstF util.Distance Wait util.Duration } var str = `{"Addr": "10.20.30.40:50","DstA": "3.5in","DstB": "2.54cm", "DstC": "72cm", "DstD": "1.23m", "DstE": "0.5ft", "DstF": "48mm", "Wait": "12s"}` var err error var cfg cfgType show := func(lfStr, rtStr string, args ...interface{}) { fmt.Println(util.StrDotPairFormat(24, lfStr, rtStr, args...)) } showDst := func(lfStr string, val util.Distance) { show(lfStr, "%s", util.Float64ToStrSig(val.In(), ".", ",", 3, 3)) } err = ioutil.WriteFile(fileStr, []byte(str), 0644) if err == nil { err = util.JSONGetFile(fileStr, &cfg) if err == nil { fmt.Println(util.StrHeaderFormat(24, "", " %s ", "JSON Fields")) show("Addr", "%s", cfg.Addr) showDst("DstA", cfg.DstA) showDst("DstB", cfg.DstB) showDst("DstC", cfg.DstC) showDst("DstD", cfg.DstD) showDst("DstE", cfg.DstE) showDst("DstF", cfg.DstF) show("Wait", "%.2f", cfg.Wait.Dur().Seconds()) err = util.JSONPutFile(fileStr, cfg) if err == nil { os.Remove(fileStr) } } } if err != nil { fmt.Printf("Error %s\n", err) } }
Output: ----- JSON Fields ------ Addr......10.20.30.40:50 DstA................3.50 DstB................1.00 DstC................28.3 DstD................48.4 DstE................6.00 DstF................1.89 Wait...............12.00
func JSONPutFile ¶
JSONPutFile writes the value specified by val to the file specified by fileStr. The fie is overwritten if it already exists.
func LinearPointSlope ¶
LinearPointSlope returns the y-intercept of the straight line joining the specified arbitrary point (not necessarily an intercept) and the line's slope.
func LinearY ¶
LinearY returns the value of the linear function defined by intercept and slope at the specified x value.
func LogWriter ¶
func LogWriter(p Printer) io.WriteCloser
LogWriter returns the log instance wrapped as a WriteCloser suitable for logging shell command output. The return value's Close() method should be called after use. This code was adapted from https://play.golang.org/p/ruQZM8Bhf- In an environment in which p is used by multiple goroutines (such as the standard library log), this can result in interleaved output lines. If p is nil, log.Print() from the standard library is used instead.
Example ¶
Demonstrate the use of the logging mechanism as an io.Writer
package main import ( "fmt" "log" "os" "github.com/jung-kurt/etc/go/util" ) func main() { lg := log.New(os.Stdout, "", 0) lw := util.LogWriter(lg) lg.Printf("simple log line") // lw implements the io.Writer interface fmt.Fprintf(lw, "Line one\nLine two\n") fmt.Fprintf(lw, "Line three\n") fmt.Fprintf(lw, "\n") fmt.Fprintf(lw, "\n\nLast line\n") lw.Close() log.SetFlags(0) log.SetOutput(os.Stdout) lw = util.LogWriter(nil) fmt.Fprintf(lw, "written with log.Print() from the standard library\n") lw.Close() lg.Printf("another simple log line") }
Output: simple log line Line one Line two Line three Last line written with log.Print() from the standard library another simple log line
func ParseAddrPort ¶
ParseAddrPort takes a string like "20.30.40.50:60" and returns the IP address and port if successful, otherwise an error. The colon and port must be specified.
func RootMeanSquare ¶
RootMeanSquare returns the RMS value for the specified slice of values. From https://en.wikipedia.org/wiki/Root_mean_square: In Estimation theory, the root mean square error of an estimator is a measure of the imperfection of the fit of the estimator to the data.
func RootMeanSquareLinear ¶
RootMeanSquareLinear returns the RMS value for the specified regression variables.
Example ¶
Demonstrate linear regression root mean square
package main import ( "fmt" "math/rand" "github.com/jung-kurt/etc/go/util" ) func main() { var xList, yList []float64 rnd := rand.New(rand.NewSource(42)) eq := util.LinearEquationType{Slope: 1.32, Intercept: 54.6} for j := 0; j < 12; j++ { x := float64(j) xList = append(xList, x) y := eq.Slope*x + eq.Intercept + (0.2*rnd.Float64() - 0.1) yList = append(yList, y) } fmt.Printf("RMS: %.3f\n", util.RootMeanSquareLinear(xList, yList, eq.Intercept, eq.Slope)) fmt.Printf("Intercept: %.3f\n", util.LinearPointSlope(100, 100, eq.Slope)) fmt.Printf("LinearY(12): %.3f\n", util.LinearY(eq.Slope, eq.Intercept, 12)) fmt.Printf("Distance to (100, 100): %.3f\n", eq.DistanceToPoint(100, 100)) fmt.Printf("Perpendicular: %s\n", eq.Perpendicular(100)) eq.Intercept = -12 fmt.Printf("Shifted equation: %s\n", eq) ceq := util.LinearEquationType{Slope: 0, Intercept: 5} fmt.Printf("Distance to constant line: %.3f\n", ceq.DistanceToPoint(6, 6)) }
Output: RMS: 0.052 Intercept: -32.000 LinearY(12): 70.440 Distance to (100, 100): 52.294 Perpendicular: y = -0.757576 x + 262.357576 Shifted equation: y = 1.320000 x - 12.000000 Distance to constant line: 1.000
func Shell ¶
Shell executes the command specified by cmdStr. Standard input to the command is streamed from rdr. Standard output from the command is streamed to wr. Any content that the command writes to standard error is converted to the returned error code. Any practical number of string arguments to the command can follow cmdStr.
Example ¶
This example tests the Shell routine
package main import ( "fmt" "runtime" "github.com/jung-kurt/etc/go/util" ) func main() { var err error if runtime.GOOS == "linux" { var w []byte w, err = util.ShellBuf([]byte(""), "ls", "-1") if err == nil { if len(w) > 0 { // OK } else { err = fmt.Errorf("empty output from ShellBuf()") } } } if err == nil { fmt.Printf("OK\n") } else { fmt.Printf("%s\n", err) } }
Output: OK
func ShellBuf ¶
ShellBuf executes the command specified by cmdStr. Standard input to the command is read from inBuf. Standard output from the command is returned as outBuf. Any content that the command writes to standard error is converted to the returned error code. Any practical number of string arguments to the command can follow cmdStr.
func Sort ¶
Sort orders elements generically. Len specifies the number of items to be sorted. Less is a callback that returns true if the item indexed by the first integer is less than the item indexed by the second integer. Swap exchanges the items identified by the two index values.
Example ¶
This example demonstrates the generic sorting function
package main import ( "fmt" "github.com/jung-kurt/etc/go/util" ) func main() { var list = []string{"red", "green", "blue"} util.Sort(len(list), func(a, b int) bool { return list[a] < list[b] }, func(a, b int) { list[a], list[b] = list[b], list[a] }) for _, str := range list { fmt.Println(str) } }
Output: blue green red
func StrCurrency100 ¶
StrCurrency100 converts -123456789 to -$1,234,567.89
func StrDelimit ¶
StrDelimit converts 'ABCDEFG' to, for example, 'A,BCD,EFG'
Example ¶
This example demonstrates various string functions.
package main import ( "fmt" "math" "github.com/jung-kurt/etc/go/util" ) func eprintf(err error, format string, args ...interface{}) { if err == nil { fmt.Printf(format, args...) } else { fmt.Printf("%s\n", err) } } func main() { var valInt32 int32 var valUint32 uint32 var valInt64 int64 var str string var err error valInt64 = int64(math.Round(math.Pi * 1000000)) valInt32 = int32(math.Round(math.Pi * 1000000)) fmt.Println(util.Float64ToStr(math.Pi*1000000, 3)) fmt.Println(util.Int32ToStr(valInt32)) fmt.Println(util.Int32ToStr(-valInt32)) str = util.Int32ToStr(-valInt32) valInt32, err = util.ToInt32(str) eprintf(err, "%d\n", valInt32) str = util.Int32ToStr(-valInt32) valUint32, err = util.ToUint32(str) eprintf(err, "%d\n", valUint32) fmt.Println(util.StrCurrency100(valInt64)) fmt.Println(util.StrCurrency100(-valInt64)) fmt.Println(util.StrCurrency100(31)) fmt.Println(util.StrDots("left", -20)) fmt.Println(util.StrDots("right", 20)) fmt.Println(util.StrDots("two", 2)) fmt.Println(util.StrDots("two", 3)) fmt.Println(util.StrDotPairFormat(20, "Prologue", "%d", 12)) fmt.Println(util.StrDotPairFormat(4, "Prologue", "%d", 12)) fmt.Println(util.StrDotPair(20, "Epilogue", "467")) fmt.Println(util.StrDotPair(2, "Epilogue", "467")) fmt.Println(util.StrIf(math.Pi > 3, "G", "L")) fmt.Println(util.StrIf(math.Pi < 3, "L", "G")) }
Output: 3,141,592.654 3,141,593 -3,141,593 -3141593 3141593 $31,415.93 -$31,415.93 $0.31 left ............... .............. right tw two Prologue..........12 Prologue..12 Epilogue.........467 Epilogue..467 G G
func StrDotPair ¶
StrDotPair fills in the blank space between two strings with dots. The total length displayed is indicated by fullLen. The left and right strings are specified by lfStr and rtStr respectively. At least two dots are shown, even if this means the total length exceeds fullLen.
func StrDotPairFormat ¶
StrDotPairFormat fills in the blank space between two strings with dots. The total length displayed is indicated by fullLen. The left string is specified by lfStr. The right string is formatted. At least two dots are shown, even if this means the total length exceeds fullLen.
func StrDots ¶
StrDots fills in blank spaces with dots. A negative value for fullLen indicates a left justified string; positive indicates right. For example, ("abc", -12) returns "abc ........", ("abc", 12) returns "........ abc". If the length of str is longer than the absolute value of fullLen, it is truncated to that value.
func StrHeader ¶
StrHeader centers the string specified by str in a string of length fullLen. The first character in fill surrounds the centered string. If fill is empty, a dash is used. At least two fill characters are used on each side of str, so the returned string may be longer than fullLen.
func StrHeaderFormat ¶
StrHeaderFormat centers the formatted string specified by format and args in a string of length fullLen. The first character in fill surrounds the centered string. If fill is empty, a dash is used. At least two fill characters are used on each side of str, so the returned string may be longer than fullLen.
func Unarchive ¶
func Unarchive(reader io.ReaderAt, readerSize int64, outFilePath string, progress ProgressFunc) (err error)
Unarchive decompresses a reader to a directory
The data's size is required because the zip reader needs it.
The archive's content will be extracted directly to outFilePath.
If progress is not nil, it is called for each file extracted from the archive.
func UnarchiveFile ¶
func UnarchiveFile(inFilePath string, outFilePath string, progress ProgressFunc) (err error)
UnarchiveFile decompresses a file to a directory
See Unarchive() doc
Types ¶
type Address ¶
type Address string
Address is used specify a network address. It includes JSON marshaling and unmarshaling methods to facilitate use with JSON data.
func (Address) MarshalJSON ¶
MarshalJSON implements the encoding/json Marshaler interface.
func (*Address) UnmarshalJSON ¶
UnmarshalJSON implements the encoding/json Unmarshaler interface.
type AverageType ¶
type AverageType struct {
// contains filtered or unexported fields
}
AverageType manages the calculation of a running average
Example ¶
Demonstrate weighted averages
package main import ( "fmt" "math/rand" "github.com/jung-kurt/etc/go/util" ) func main() { var ave util.AverageType rnd := rand.New(rand.NewSource(42)) for j := 0; j < 12; j++ { ave.Add(3+2*rnd.Float64(), 0.2+rnd.Float64()) } fmt.Printf("Weighted average: %.3f\n", ave.Value()) }
Output: Weighted average: 4.094
func (*AverageType) Add ¶
func (avg *AverageType) Add(val, weight float64)
Add adds a value to a running average. weight is quietly constrained to the range [0, 1].
func (AverageType) Value ¶
func (avg AverageType) Value() float64
Value returns the current average of submitted values
type Distance ¶
type Distance float64
Distance is used specify measurable distances. It includes JSON marshaling and unmarshaling methods to facilitate use with JSON data.
func (Distance) MarshalJSON ¶
MarshalJSON implements the encoding/json Marshaler interface.
func (*Distance) UnmarshalJSON ¶
UnmarshalJSON implements the encoding/json Unmarshaler interface.
type Duration ¶
Duration is used specify durations of time. It includes JSON marshaling and unmarshaling methods to facilitate use with JSON data.
func (Duration) Dur ¶
Dur returns the time.Duration value of the value specified by the Duration receiver.
func (Duration) MarshalJSON ¶
MarshalJSON implements the encoding/json Marshaler interface.
func (*Duration) UnmarshalJSON ¶
UnmarshalJSON implements the encoding/json Unmarshaler interface.
type JSONBuilder ¶
type JSONBuilder struct {
// contains filtered or unexported fields
}
JSONBuilder facilitates the incremental construction of a JSON string. Its zero-value is ready for use.
Example ¶
package main import ( "fmt" "os" "github.com/jung-kurt/etc/go/util" ) func main() { var bld util.JSONBuilder report := func() { err := bld.Error() if err == nil { fmt.Printf("%s\n", bld.String()) } else { fmt.Fprintf(os.Stderr, "%s\n", err) bld.Reset() } } bld.ObjectOpen() bld.KeyElement("ID", 42) bld.KeyElement("Name", "Prairie") report() // Close object automatically bld.ObjectOpen() // { bld.KeyObjectOpen("Alpha") // {{ bld.KeyArrayOpen("List") // {{[ bld.Element("Shiawassee") // {{[ bld.Element(true) // {{[ bld.Element(3.14) // {{[ bld.ArrayClose() // {{ bld.KeyElement("Name", "Brilla") // {{ bld.ObjectClose() // { bld.KeyElement("Beta", 1234) // { bld.ObjectClose() // report() // JSON-encodable structures can be elements bld.Element(struct { ID int Name string }{22, "Tess"}) report() }
Output: {"ID":42,"Name":"Prairie"} {"Alpha":{"List":["Shiawassee",true,3.14],"Name":"Brilla"},"Beta":1234} {"ID":22,"Name":"Tess"}
func (*JSONBuilder) ArrayClose ¶
func (j *JSONBuilder) ArrayClose()
ArrayClose closes the currently open array.
func (*JSONBuilder) ArrayOpen ¶
func (j *JSONBuilder) ArrayOpen()
ArrayOpen opens an array for subsequent element population. This may be successfully called when an array is currently open or when nothing else has been added to the builder instance.
func (*JSONBuilder) Element ¶
func (j *JSONBuilder) Element(val interface{})
Element adds the specified element to the builder instance. This may be successfully called when an array is currently open or when nothing else has been added to the builder instance.
func (*JSONBuilder) Error ¶
func (j *JSONBuilder) Error() (err error)
Error returns the current internal error value. If no error has occurred nil is returned.
func (*JSONBuilder) KeyArrayOpen ¶
func (j *JSONBuilder) KeyArrayOpen(key string)
KeyArrayOpen opens an object for subsequent element population and associates it with the specified key. This may be successfully called when an object is currently open.
func (*JSONBuilder) KeyElement ¶
func (j *JSONBuilder) KeyElement(key string, val interface{})
KeyElement assigns a key/value pair in the open object.
func (*JSONBuilder) KeyObjectOpen ¶
func (j *JSONBuilder) KeyObjectOpen(key string)
KeyObjectOpen opens an object for subsequent key/value population and associates it with the specified key. This may be successfully called when an object is currently open.
func (*JSONBuilder) ObjectClose ¶
func (j *JSONBuilder) ObjectClose()
ObjectClose closes the currently open object.
func (*JSONBuilder) ObjectOpen ¶
func (j *JSONBuilder) ObjectOpen()
ObjectOpen opens an object for subsequent key/value population. This may be successfully called when an array is currently open or when nothing else has been added to the builder instance.
func (*JSONBuilder) Reset ¶
func (j *JSONBuilder) Reset()
Reset preapres the JSONBuilder receiver for reuse.
func (*JSONBuilder) String ¶
func (j *JSONBuilder) String() (jsonStr string)
String returns the completed JSON object in compact string form. All open containers (arrays and objects) are closed in proper order. The receiver instance is reset and is available for reuse after this call returns.
type LinearEquationType ¶
type LinearEquationType struct {
Slope, Intercept float64
}
LinearEquationType describes a line with its slope and intercept
func Linear ¶
func Linear(x1, y1, x2, y2 float64) (eq LinearEquationType)
Linear returns the y-intercept and slope of the straight line joining the two specified points. For scaling purposes, associate the arguments as follows: x1: observed low value, y1: desired low value, x2: observed high value, y2: desired high value.
func (LinearEquationType) DistanceToPoint ¶
func (eq LinearEquationType) DistanceToPoint(x, y float64) (d float64)
DistanceToPoint returns the shortest distance from the specified point to eq.
Example ¶
This example demonstrates the DistanceToPoint method
package main import ( "fmt" "github.com/jung-kurt/etc/go/util" ) func main() { le := util.Linear(1, 1, 3, 2) for j := -1; j < 5; j++ { fmt.Printf("%.3f\n", le.DistanceToPoint(float64(j), 2)) } }
Output: 1.789 1.342 0.894 0.447 0.000 0.447
func (LinearEquationType) Perpendicular ¶
func (eq LinearEquationType) Perpendicular(x float64) (p LinearEquationType)
Perpendicular returns an equation that is perpendicular to eq and intersects it at x.
func (LinearEquationType) PerpendicularPoint ¶
func (eq LinearEquationType) PerpendicularPoint(x, y float64) (p LinearEquationType)
PerpendicularPoint returns an equation that is perpendicular to eq and includes the point specified by x and y.
func (LinearEquationType) String ¶
func (eq LinearEquationType) String() string
String implements the fmt Stringer interface
type PairType ¶
type PairType struct {
X, Y float64
}
PairType defines a two-dimensional coordianate.
type Printer ¶
type Printer interface {
Print(v ...interface{})
}
Printer supports basic output of all types. It is supported by the log.Logger type.
type ProgressFunc ¶
type ProgressFunc func(archivePath string)
ProgressFunc is the type of the function called for each archive file.
type RangeType ¶
type RangeType struct {
Min, Max float64
}
RangeType holds the minimum and maximum values of a range.
Example ¶
Demonstrate range of values
package main import ( "fmt" "github.com/jung-kurt/etc/go/util" ) func main() { var rng util.RangeType rng.Set(7, true) rng.Set(3, false) rng.Set(8, false) rng.Set(8, false) rng.Set(0, false) rng.Set(2, false) fmt.Printf("Range: %.3f - %.3f\n", rng.Min, rng.Max) }
Output: Range: 0.000 - 8.000