mdr

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

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

Go to latest
Published: Mar 18, 2021 License: BSD-2-Clause Imports: 25 Imported by: 1

README

mdr ===

mdr

Build Status Travis build status.

License details are at the end of this document. This document is (c) 2012-2015 David Rook.

Comments can be sent to hotei1352@gmail.com .

This is a package of "utility" code I wrote. I use it frequently. If you have received one of my other packages from github (ansiterm, bits, etc ...) you may have gotten mdr as a dependency. It pulls in a fairly large range of standard lib packages so if you only need a smallish set of things it might make sense to just copy them individually or possibly make a package subset from mdr. If you find it useful - or find a bug - please send an email.

Installation

If you have a working go installation on a Unix-like OS:

go get github.com/hotei/mdr

Features

Functions/Methods are grouped (loosely) in the following categories

  • Hash Helpers for CRC64, MD5, SHA256 etc
    • return string digest of a buffer
    • return string digest of a file
  • Random number generators
    • Uniform
    • Uniform numbers between two values (float64 and int)
    • Poisson
    • FlipCoin
    • Normal and Normal Z (unit normal)
    • Crypto-Quality random []byte
  • archives
    • whether the file is a "collection" of files (like tar or zip) or just "itself"
    • determining compression types given file name
  • Formatting helpers
    • add commas to integer numbers
    • print dates as human friendly times (1 day instead of 86400 seconds)
    • test dates for "legality" and leapyears
    • progress displays - spinner or progressbar (if endpoint known)
    • StarDate
    • validating decimal or hex strings
  • Getting obscure properties of files from the os
    • User and Group numbers
    • Number of links
  • Integer and float64 helpers
    • test if value is in range between two values
    • convert an int to and from []byte of various sizes
    • compute max and min of a []int
    • compute max and min points given []Point (Bounds)
    • creating Bezier interpolations (quadratic)
  • Polar <--> Rectangular coordinate conversion
  • Parallel computation helpers
    • JobSplit figures out how to split a job into pieces for each CPU to work on
  • Directory operations
    • maps of paths to SHA256 of contents

If you want details you can see them at this link: mdr

Change Log

  • 2015-08-18 builds with 1.5rc1
    • added Travis
  • 2015-05-01 updated progress bar functions
    • builds with 1.4.2
  • 2013-04-10 updated docs, posted at github.com/hotei/MDR.git
  • additions
  • 2010-04-20 started, working

Resources

  • [go language reference] 1
  • [go standard library package docs] 2
  • [Source for mdr package on github] 3

License

The 'mdr' go package is distributed under the Simplified BSD License:

Copyright (c) 2010-2015 David Rook. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// EOF README-mdr-pkg.md (this is a markdown document and tested OK with blackfriday)

deadcode results:

deadcode: mdr_dirNode.go:15:1: unused is unused
SLOC output

  Languages  Files  Code  Comment  Blank  Total  CodeLns
      Total     39  4199      913    615   5727   100.0%
         Go     33  3878      887    532   5297    92.5%
   Markdown      3   230        0     56    286     5.0%
       Make      1    71       26     23    120     2.1%
       Text      2    20        0      4     24     0.4%
built with go version go1.13.7 linux/amd64

package mdr

var CompileDateTime = "2020-02-24 10:38:41.833744657 -0500 EST m=+0.000034756" var CompilerVersion = " go version go1.13.7 linux/amd64"

Documentation

Overview

doc.go (c) 2013-2015 David Rook - all rights reserved

Eclectic Set of Utility Functions

Features
========
  Most of the functions are short and easily understood
  Examples available for the less obvious

Real BUGS -##0{ None Known - but beware of limitations

Limitations
-----------
  GetKey() doesn't hide key entry

Also see README-mdr.md for more info

While the polyline can be used to depict GPS coordinates that is NOT a requirement. Use []GPSloc aka GPSlist if you need that (3D) capability.

Index

Examples

Constants

View Source
const (
	G_datetimeFmt = "2006-01-02:15_04_05"
)

Variables

View Source
var (
	PiX2             = math.Pi * 2.0
	RadiansPerDegree = math.Pi / 180.0
	Km2miles         = 0.621371
	M2ft             = 3.28084          // meters -> feet
	TwoTo31th        = float64(1 << 31) // 2 ^ 31
	GaiaKm           = 6371.0           //  Earth's radius in kilometers.
)
View Source
var (
	ForceRangeFlag    bool = true // forces out of range values to fit
	CantHappenError        = errors.New("Can't-happen")
	DivideByZeroError      = errors.New("Divide By Zero")
	OutOfRangeError        = errors.New("Value outside expected range")
	InvalidTableError      = errors.New("Not a valid table")
)
View Source
var CantCreateRec = errors.New("mdr: cant create Rec256 ")
View Source
var CompileDateTime = "2021-03-12 10:59:21.107357431 -0500 EST m=+0.000032378"
View Source
var CompilerVersion = " go version go1.16 linux/amd64"
View Source
var DegPerRad = 180.0 / math.Pi
View Source
var Fit_crc_table [16]uint16 = [16]uint16{
	0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401,
	0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400,
}
View Source
var (
	G_crcTable *crc64.Table
)
View Source
var (
	Paranoid = false
)
View Source
var (
	// these would normally be C static vars inside Spinner()
	UpdateDelayMs = 1000 // delay in millisec between updates

)

Functions

func AbsF64

func AbsF64(a float64) float64

AbsF64 returns the absolute value of a float64

func AbsInt64

func AbsInt64(a int64) int64

AbsInt64 returns the absolute value of an int64

func BufCRC64

func BufCRC64(bufr []byte) uint64

syntax sugar

func BufMD5

func BufMD5(buf []byte) string

func BufSHA256

func BufSHA256(buf []byte) string

func Celcius

func Celcius(c int16) int16

func Centigrade

func Centigrade(f int16) int16

func CloseToF64

func CloseToF64(a, b, near float64) bool

func CommaFmtInt64

func CommaFmtInt64(n int64) string

CommaFmtInt64 returns a comma inserted number string

12345 becomes "12,345" NOTE! uses USA format, not internationalized
Name of a generic function might be DecimalFmtdInt64()

func ConfineLoHi

func ConfineLoHi(lo, i, hi int) int

func Crash

func Crash(reason string)

func DegreeFromSemicircle

func DegreeFromSemicircle(semi int32) float64

func DequoteFloat64

func DequoteFloat64(s string) (float64, error)

convert() dequotes "123.4" and returns a float64

func DigestToString

func DigestToString(digest []byte) string

func ExtractFloat32

func ExtractFloat32(s string) float32

ExtractFloat32 assumes convention of period for decimal

func ExtractFloat64

func ExtractFloat64(s string) float64

ExtractFloat64 assumes convention of period for decimal

func ExtractInt16

func ExtractInt16(s string) int16

func ExtractInt32

func ExtractInt32(s string) int32

func ExtractInt64

func ExtractInt64(s string) int64

func ExtractInt8

func ExtractInt8(s string) int8

func ExtractUint16

func ExtractUint16(s string) uint16

func ExtractUint32

func ExtractUint32(s string) uint32

func ExtractUint64

func ExtractUint64(s string) uint64

func ExtractUint8

func ExtractUint8(s string) uint8

func Factorial

func Factorial(n int) int

Factorial computes value recursively. BUG(mdr) Factorial using recursion may not be the best choice ... BUG(mdr) check for overflow in Factorial or limit choice of n to good range

since it gets big quickly

func Fahrenheit

func Fahrenheit(c int16) int16

func FatalError

func FatalError(err error)

func FileCRC64

func FileCRC64(fname string) (uint64, error)

reads file in 512KB chunks

func FileGID

func FileGID(fname string) (int, error)

return files groupid number

func FileIsRegular

func FileIsRegular(fname string) (bool, error)

BUG(mdr) FileIsRegular now OBE (since go 1.1)

func FileLength

func FileLength(fname string) (int64, error)

func FileLinkCt

func FileLinkCt(fname string) (int, error)

func FileMD5

func FileMD5(fname string) (string, error)

Compute md5 for given file Test is Test_005

func FileNameIsCollection

func FileNameIsCollection(fname string) (bool, string)

func FileSHA256

func FileSHA256(fname string) (string, error)

Compute sha256 for given file Test is Test_005

func FileUID

func FileUID(fname string) (int, error)

return files userid number

func Fit2Time

func Fit2Time(t uint32) time.Time

func FitCRC_Calc16

func FitCRC_Calc16(data []byte, size uint32) uint16

func FitCRC_Get16

func FitCRC_Get16(crc uint16, bite byte) uint16

func FitCRC_Update16

func FitCRC_Update16(crc uint16, data_ptr []byte, size uint32) uint16

func FlipCoin

func FlipCoin() bool

FlipCoin returns true with 50% probability

func Float16To64

func Float16To64(v int16) float64

func ForceRangeF64

func ForceRangeF64(a, b, c float64) float64

true IFF a <= b <= c || a >= b >= c, note a < c not required

func ForceRangeI64

func ForceRangeI64(a, b, c int64) int64

func GenFlipCoin

func GenFlipCoin() bool

expect to see about 50% head, 50% tails (HasTest)

func GenRandF64Between

func GenRandF64Between(lo, hi float64) float64

GenRandF64Between endpoints may occur in output

func GenRandIntBetween

func GenRandIntBetween(lo, hi int) int

GenRandIntBetween endpoints may occur in output

func GenRandIntBtw

func GenRandIntBtw(lo, hi int) int

RandIntBtw endpoints may occur (HasTest widget).

func GenRandomNormal

func GenRandomNormal(mu, stdev float64) float64

GenRandomNormal returns a float64 with average mu and standard deviation stdev depending on mu and stdev picked the values returned could be virtually any float64

func GenRandomPoisson

func GenRandomPoisson(lambda float64) int

GenRandomPoisson returns an int with Poisson distribution typically used to determine the number of time units before some event occurs

func GenRandomUniform

func GenRandomUniform(r float64) float64

GenRandomUniform returns a float64 in range {0 .. r}

func GenRandomUniformLoHi

func GenRandomUniformLoHi(low, high float64) float64

GenRandomUniformLo returns a float64 in range {low .. high} high > low is NOT required, not sure if this is right or should panic 8888 ?

func GenRandomZNormal

func GenRandomZNormal() float64

GenRandomZNormal returns a float64 with average of 0 and standard deviation of 1.0 as implemented the range of values returned will be in [-60..60]

func GetAllArgs

func GetAllArgs() []string

GetAllArgs is a helper with filters to collect args from input stream limited to RAM for size of return []string.Note that if used with 'find' in a pipeline it must wait till find is done to proceed.

func GetKey

func GetKey() string

BUG(mdr): GetKey() key is visible during entry

func HasInterface

func HasInterface(hostIPStr string) bool

checkInterfaces - see if listener is bound to correct interface first is localhost, second should be IP4 of active card, third is IP6 localhost, fourth is IP6 for active card (on this system) on BSD it's [ IP4 IP6 LocalHostIP4 LocalHostIP6 LocalHostIP4]

Order isn't important as long as requested inteface is there somewhere actual check needs to do a string match of interfaces we have with a target of the requested interface. If target isn't present then stop.

func HumanTime

func HumanTime(t time.Duration) (rs string)

turns duration into decimal minutes,hours,days as appropriate, maximum duration is about 290 years Test_002

func IPFromUint32

func IPFromUint32(adr uint32) net.IP

IPFromUint32 beware - also presumes knowledge of net.IP internals order

Inverse of Uint32FromIP

func InRangeF64

func InRangeF64(a, b, c float64) bool

true IFF a <= b <= c || a >= b >= c, note a < c not required

func InRangeI

func InRangeI(a, b, c int) bool

func InRangeInt64

func InRangeInt64(a, b, c int64) bool

true IFF a <= b <= c || a >= b >= c, note a < c not required

func Int64FromLSBytes

func Int64FromLSBytes(b []byte) int64

Int64FromLSBytes converts an 8 byte array into an int64

func Int64FromMSBytes

func Int64FromMSBytes(b []byte) int64

Int64FromMSBytes converts an 8 byte slice (BigEndian - MSB First) into an int64

func KmBetween

func KmBetween(a, b GPS2dT) float64

func KmBetweenGC

func KmBetweenGC(a, b GPS2dT) float64

KmBetweenGC calculates the shortest path between two GPS coordinates. Assumes both points are at sealevel.

NOTE! Earth is not a sphere. Haversine has more error in E-W calculations than N-S.

Distance of 1 degree differs ( E.W. vs N.S. )

Error is 6:40,000 E.W. vs 0:40000 N.S.
https://en.wikipedia.org/wiki/Earth_radius source for GaiaKm

Uses haversine method to calculate great circle distances

func LSBytesFromInt64

func LSBytesFromInt64(n int64) []byte

LSBytesFromInt64 converts an int64 into an 8 byte array, LSB first (LittleEndian) test is Test_011

func LSBytesFromUint32

func LSBytesFromUint32(u uint32) []byte

convert uint32 to [0:4]byte slice in LSB first order reverse function is ThirtyTwoBit()

func LeapYear

func LeapYear(when time.Time) bool

true if when is a leap year

func LoHi

func LoHi(ary []int) (lo int, hi int)

LoHi returns the min and max of an array of ints

func LoadSHA256Names

func LoadSHA256Names(fname string) ([]string, error)

LoadSHA256Names returns the array of pathnames

func LoadSHA256asDirMap

func LoadSHA256asDirMap(fname string) (map[string]*DirNode, error)

LoadSHA256asDirMap returns *dirMap[directoryPath]*DirNode

uses scanner to allow large file.256 to be used as input

Used when its necessary to compute something with directory as input

func LoadSHA256asList

func LoadSHA256asList(fname string) ([]string, error)

LoadSHA256asList returns lines of file as []string , nil on success

each line is known to split without error

comments are stripped

func LoadSHA256asMap

func LoadSHA256asMap(fname string) (map[string]string, error)

LoadSHA256asMap returns map[SHA256]path , nil on success

func MSBytesFromInt64

func MSBytesFromInt64(n int64) []byte

MSBytesFromInt64 converts int64 to [0:8]byte slice with MSB first (BigEndian) reverse function is

func MSBytesFromUint32

func MSBytesFromUint32(u uint32) []byte

convert uint32 to [0:4]byte slice in MSB first (aka 'Net') order reverse function is ThirtyTwoNet()

func MaxI

func MaxI(a, b int) int

func MiFromCm

func MiFromCm(cm uint32) float64

MiFromCm turns centimeters into miles

func MinI

func MinI(a, b int) int

func MphFromMMs

func MphFromMMs(mms uint32) float64

MphFromMMs converts millimeters per second to miles per hour

func MphFromMps

func MphFromMps(mps float64) float64

MphFromMps converts meters per second to miles per hour

func Polar

func Polar(loc Pointi) (theta, r float64)

Polar returns the polar coords (angle and radius) for a Cartesian point.

func PolarAngle

func PolarAngle(loc Pointi) float64

PolarAngle returns the angle produced by a line from Point{0,0} to loc.

func PseudoRandomBlock

func PseudoRandomBlock(blksize int) []byte

returns buffer of specified size filled with random bytes test funcs are Test_010 and Benchmark_010

func Radians

func Radians(degrees float64) float64

radians returns the equivalent to degrees.

func RangeLoHiF64Slice

func RangeLoHiF64Slice(v []float64) (lo, hi float64)

Return the lo and hi of given array

func Reverse

func Reverse(b []byte)

func RmPrefix

func RmPrefix(s, pre string) string

RmPrefix() removes prefix from a string, if it exists test_?

func RmSuffix

func RmSuffix(s, suf string) string

RmSuffix() removes suffix from a string, if it exists test_?

func SetTtyRawMode

func SetTtyRawMode()

this works, but see also go.crypto/ssh/terminal

func SingleCharRead

func SingleCharRead() byte

SingleCharRead might return newline if no other input

otherwise first character if more than one on a line

^D will cause EOF to be printed and ? as the char returned - better choice is ...

func SixteenBit

func SixteenBit(n []byte) uint16

SixteenBit converts from little endian two byte slice to int16 aka Uint16FromLSBytes

func Smooth

func Smooth(d []int64, n int) []float64

Smooth creates a new array with smoothed float64 values where n is number of

values over which to average.  Returns an array of same size as original,
so the first and last 'n' values will be "short", ie more sensitive to
any variation.

func Spinner

func Spinner()

keep user entertained while something happens behind the curtain

see example from mdr_test.go for usage
Choose Spinner() if progress bar can't be used because endpoint not known

func StarDate

func StarDate(when time.Time) float64

returns decimal year to nearest 52 minutes - usually printed with %9.4f

func StringIsMember

func StringIsMember(s string, ary []string) bool

StringIsMember() returns true if s is a member of list ary. working test_?

func StringsCombine

func StringsCombine(a, b []string) []string

StringsCombine() returns a list which combines two lists of strings. test_?

func StringsIntersection

func StringsIntersection(a, b []string) []string

StringsIntersection() returns a list where all members appear in both a,b. test_?

func StringsSimilar

func StringsSimilar(a, b []string) bool

StringsSimilar() returns true if both string lists have the same members duplicate members are ignored. To be SAME the member count must be equal. test_?

func StringsUnion

func StringsUnion(a, b []string) []string

func StringsUnique

func StringsUnique(tags []string) (rv []string)

StringsUnique returns a list with duplicate members removed. test_?

func ThirtyTwoBit

func ThirtyTwoBit(n []byte) uint32

convert from LITTLE endian four byte slice to int32 reverse function is LSBytesFromUint32

AKA Uint32FromLSBytes

func ThirtyTwoNet

func ThirtyTwoNet(n []byte) uint32

ThirtyTwoNet is a synonym for Uint32FromMSBytes

func UdevRandomBlock

func UdevRandomBlock(blksize int) []byte

returns a buffer of specified size filled with random bits from /dev/urandom there is a limited supply (about 4096 bits) so read will fail if urandom has not had time to accumulate enough bits to satisfy the read. Max readable under optimum conditios ? actual test => 1020,1932,1020 1 ms sleep not enough(1940fail), 10 not enough (1020fail), 50 not enough 1020fail

func Uint32FromIP

func Uint32FromIP(ip net.IP) uint32

Uint32FromIP returns a uint32 from IPv4 so we can use as index to map

-BEWARE- there are magic numbers that
  presume knowledge of net.IP internals order

func Uint32FromMSBytes

func Uint32FromMSBytes(b []byte) uint32

convert from BIG endian four byte slice to int32 reverse function is MSBytesFromUint32

func ValidDate

func ValidDate(year, month, day, hour, minute, second int) bool

ValidDate tries to determine validity of given date. It's not very much use in pre-Gregorian times and doesn't do BCE at all. https://en.wikipedia.org/wiki/Julian_calendar may help understanding, or may just confuse one further :-)

func ValidDecChar

func ValidDecChar(c byte) bool

func ValidDecString

func ValidDecString(s string) bool

func ValidHexChar

func ValidHexChar(c byte) bool

func ValidHexString

func ValidHexString(s string) bool

Types

type ArchiveType

type ArchiveType int
const (
	ArchiveNoMatchType ArchiveType = iota
	ArchiveTarType
	ArchiveZipType
	ArchiveJarType // not quite Zip but similar
	ArchiveCpioType
	ArchiveMailboxType
)

func WhichArchiveType

func WhichArchiveType(s string) ArchiveType

examine name to determine archive method used should match magic numbers but that's a different function

type BBox

type BBox struct {
	MinX, MinY, MaxX, MaxY float64
}

============================================================================ BBox

func (BBox) Centroid

func (bb BBox) Centroid() Pointe

func (BBox) Contains

func (bb BBox) Contains(pt Pointe) bool

func (BBox) Corners

func (bb BBox) Corners() []Pointe

Corners() returns all 4 corners though only two are needed to define a box. Easier to draw if you have all 4, and they are in drawable order.

func (*BBox) ExpandByPolyLine

func (bb *BBox) ExpandByPolyLine(parts PolyLine)

func (*BBox) ExpandByPts

func (bb *BBox) ExpandByPts(pts []Pointe)

func (BBox) Intersects

func (bb BBox) Intersects(xx BBox) bool

Intersects() returns true if box areas overlap at any point. Failed when one box completely encloses the other so add second test Should return true if one encloses the other

func (BBox) Sane

func (bb BBox) Sane() bool

BUG(mdr): !Sane or just not init??? BBox.Sane() makes basic checks, usually employed only if Paranoid turned on

see BBox.Contains() above as example

func (BBox) String

func (bb BBox) String() string

type ByName

type ByName []FileRec

func (ByName) Len

func (a ByName) Len() int

func (ByName) Less

func (a ByName) Less(i, j int) bool

func (ByName) Swap

func (a ByName) Swap(i, j int)

type CompressType

type CompressType int
const (
	CompressNoMatchType CompressType = iota
	CompressZipType
	CompressGzipType
	CompressBz2Type
	CompressZcompressType // .Z not common except possibly in Japan
	CompresszPackType     // .z deprecated - very rare in last 20 years
	CompressBz1Type       // .bz deprecated - very rare in last 20+ years
	CompressShrinkType    // found in zip files of old
	CompressCompactType   // ?? deprecated
	CompressFreezeType    // ?? deprecated
	Compress7zType        // new kid on the block
	CompressXvType        // even newer kid on the block
)

func WhichCompressType

func WhichCompressType(s string) CompressType

examine name to determine compression method used should match magic numbers but that's a different function

type DblPair

type DblPair struct {
	Left, Right float64
}

type DirNode

type DirNode struct {
	Pathname       string
	IsSortedByName bool
	Files          []FileRec
	Size           int64
	SHA256         string
}

func (*DirNode) AddFile

func (d *DirNode) AddFile(f FileRec)

func (*DirNode) DeleteFile

func (d *DirNode) DeleteFile(fname string)

func (*DirNode) Dump

func (d *DirNode) Dump()

func (*DirNode) Finalize

func (d *DirNode) Finalize() (string, int64)

Finalize computes the total size and SHA256 of the leaf

func (*DirNode) IndexOf

func (d *DirNode) IndexOf(fname string) int

special case speedup if we check last returned value +1 first? better handles case where we're stepping through list ??? Returns -1 if not found

func (*DirNode) IndexOfBrute

func (d *DirNode) IndexOfBrute(fname string) int

brute force works

func (*DirNode) IsSortedProperly

func (d *DirNode) IsSortedProperly() bool

func (*DirNode) SortFilesByName

func (d *DirNode) SortFilesByName()

func (*DirNode) UnTouchAll

func (d *DirNode) UnTouchAll()

func (*DirNode) Update

func (d *DirNode) Update(fname string) error

calls AddFile if file not currently in DirNode name should be just the base part of path

type FileRec

type FileRec struct {
	R Rec256
	//	fname   string // needed to sort on
	Touched bool
}

func (FileRec) Dump

func (fr FileRec) Dump()

type GPS2dList

type GPS2dList []GPS2dT

============================================================================= GPS2dList

func (GPS2dList) BBox

func (g2 GPS2dList) BBox() BBox

func (GPS2dList) PolyLine

func (g2 GPS2dList) PolyLine() PolyLine

type GPS2dT

type GPS2dT struct {
	Lon float64 // degrees
	Lat float64 // degrees
}

func (GPS2dT) KmTo

func (x GPS2dT) KmTo(y GPS2dT) float64

func (GPS2dT) Point

func (g GPS2dT) Point() Pointe

func (GPS2dT) String

func (pt GPS2dT) String() string

func (GPS2dT) ValidGPS2d

func (g GPS2dT) ValidGPS2d() bool

type GPS3dT

type GPS3dT struct {
	Lon float64 // degrees
	Lat float64 // degrees
	Up  float64 // meters
}

============================================================================ GPS3d

type HeadingDeg

type HeadingDeg float64

func (HeadingDeg) String

func (h HeadingDeg) String() string

type IntPair

type IntPair struct {
	X, Y int
}

func JobSplit

func JobSplit(n int, NumCPUs int) []IntPair

split n into NumCPUs ranges,

JobSplit(10,1) -> returns [ {0,9} ]
JobSplit(10,2) -> returns [ {0,4},{5,9} ]
JobSplit(10,3) -> returns [ {0,3}, {4,6}, {7,9} ]
    if not all slices are same length, longer ones will occur first

Test_001 See also ExampleJobSplit()

Example
// 888_test.go

// go test '-bench=.'   # expression matches everything, runs all benchmarks
// go test -run="Test_000" to run just one function

package main

import (
	"fmt"
	//"testing"
	//"time"
)

// ///////////////////////  E X A M P L E S  ////////////////////////////
func workerFunction(w IntPair) {
	fmt.Printf("work on items from %d through %d\n", w.X, w.Y)
}

func main() {
	nCPU := 4
	totalWork := 100
	jobrange := JobSplit(totalWork, nCPU)
	for i := 0; i < nCPU; i++ {
		go workerFunction(jobrange[i])
	}
}

/*
func ExampleProgressBar() {
	var (
		status    int64
		endNumber int64 = 100
	)

	progChan := make(chan int64, 2)
	go ProgressBar(50, progChan, endNumber) // start the display handler
	progChan <- 0                           // make first progress display visible
	for {
		//      ... do something to advance status towards endNumber ...
		time.Sleep(time.Second)
		status += 10
		progChan <- status
		if status >= endNumber {
			break
		}
	}
	progChan <- -1 // close up shop
}
*/
Output:

type Ints

type Ints []int

func PermutedInts

func PermutedInts(a Ints) []Ints

PermutedInts returns all the permutaions of the original array length of array must be in range of [0..6]

func (Ints) ContainsI

func (a Ints) ContainsI(b int) bool

func (Ints) RotH2T

func (a Ints) RotH2T() Ints

RotT2H rotates the head of an array to tail position

abcd => bcda

func (Ints) RotT2H

func (a Ints) RotT2H() Ints

RotT2H rotates the tail of an array to head position

abcd => dabc

type Pointe

type Pointe struct {
	X float64
	Y float64
}

============================================================================ Pointe

func (Pointe) GPS2d

func (pt Pointe) GPS2d() GPS2dT

func (Pointe) KmTo

func (pt Pointe) KmTo(pt2 Pointe) float64

func (Pointe) String

func (pt Pointe) String() string

func (Pointe) ValidGPS2d

func (pt Pointe) ValidGPS2d() bool

type PointeList

type PointeList []Pointe

============================================================================ PointeList

type Pointi

type Pointi struct {
	X int
	Y int
}

============================================================================ Pointi

func Cartesian

func Cartesian(angle, radius float64) Pointi

Cartesian returns Cartesian point from polar point. NoteBene: NOT the usual [in trig x=cos(a) y=sin(a)] because y axis is inverted in 'conventional' computer graphics.

func RangeMinMaxPoint

func RangeMinMaxPoint(v PointiList) (minPt, maxPt Pointi)

RangeMinMaxPoint returns bounds of point array. probably a better name would help... 8888

func (*Pointi) RotateOnPivotPt

func (loc *Pointi) RotateOnPivotPt(p Pointi, radians float64)

RotateOnPivotPt rotate a point using another point as a pivot (mimic mechanical compass drawing).

func (*Pointi) ZRotate

func (loc *Pointi) ZRotate(radians float64)

ZRotate rotates a point about 0,0 (z axis). intended for use in computer graphics (ring5 pkg)

type PointiList

type PointiList []Pointi

============================================================================ PointiList

func CreateBezierPts

func CreateBezierPts(p1, p2, p3 Pointi, segments int) PointiList

CreateBezierPts start, control, end pts for quadratic bezier. segments is the number of line segments to create, more means smoother curve. Intended use is mostly with ring5 package, but MIGHT be genericly useful.

func (PointiList) Split

func (pts PointiList) Split() (xs []int, ys []int)

Split separates the X and Y values into their own arrays

type PolyLine

type PolyLine [][]Pointe

========================================================================

func Join

func Join(a, b PolyLine) PolyLine

TODO(mdr): Variadic version ?

func MakePoly

func MakePoly(pts GPS2dList) PolyLine

func (PolyLine) AddNewPart

func (pl PolyLine) AddNewPart(part []Pointe) PolyLine

func (PolyLine) BBox

func (pl PolyLine) BBox() BBox

BBox() returns the smallest box which encloses all the points of the PolyLine

func (PolyLine) Centroid

func (pl PolyLine) Centroid() Pointe

Centroid() returns the "center of gravity" of the shape

func (*PolyLine) ExtendBy

func (pl *PolyLine) ExtendBy(part []Pointe)

func (*PolyLine) ExtendByPolyLine

func (pl *PolyLine) ExtendByPolyLine(pl2 PolyLine)

func (PolyLine) NumParts

func (pl PolyLine) NumParts() int

func (PolyLine) NumPoints

func (pl PolyLine) NumPoints() int

NumPts() returns the number of points in all parts.

type ProgStateT

type ProgStateT struct {
	Label string

	ShowCount bool
	ShowTime  bool
	// contains filtered or unexported fields
}

func OneProgressBar

func OneProgressBar(goal int64) *ProgStateT

func (*ProgStateT) Stop

func (ps *ProgStateT) Stop()

func (*ProgStateT) Tag

func (ps *ProgStateT) Tag(t string)

func (*ProgStateT) Update

func (ps *ProgStateT) Update(val int64)

type Rec256

type Rec256 struct {
	Size            int64
	SHA, Date, Name string
}

func Split256

func Split256(line string) (Rec256, error)

func (Rec256) Dump

func (r Rec256) Dump()

type SemiT

type SemiT int32

============================================================================ SemiT

func (SemiT) Degrees

func (semi SemiT) Degrees() float64

type Shape

type Shape struct {
	shp.Shape
	Tags map[string]string
}

============================================================================ Shape

func LoadSHP

func LoadSHP(path string) ([]Shape, error)

func (Shape) GetPoints

func (shape Shape) GetPoints() PolyLine

type SliceI64

type SliceI64 []int64

============================================================================ SliceI64

func (SliceI64) SliceI64Avg

func (d SliceI64) SliceI64Avg() float64

func (SliceI64) Smooth

func (d SliceI64) Smooth(n int) []float64

create new array with smoothed values where n is number of values to average over

type Table

type Table struct {
	Name    string
	Data    []DblPair
	RevData []DblPair
	// contains filtered or unexported fields
}
var NormalZtable *Table

func (*Table) Dump

func (d *Table) Dump()

func (*Table) Eval

func (d *Table) Eval(v float64) (rc float64, err error)

func (*Table) ReverseEval

func (d *Table) ReverseEval(val float64) (rc []float64, err error)

returns multiple hits where appropriate

func (*Table) Setup

func (d *Table) Setup() error

type VerboseType

type VerboseType bool
var (
	Verbose VerboseType
)

func (VerboseType) Printf

func (v VerboseType) Printf(s string, a ...interface{})

Notes

Bugs

  • GetKey() key is visible during entry

  • remove duplicates if necessary, these happen in adjacent spots when a value is on the end of a pair, can happen elsewhere as well, but not treating those yet. This method is quick, but inadequate for long run. Need insertion sort or map for final solution. currently just document that the resulting array may not have unique values

  • ? be paranoid and check if we have any slashes in fname?

  • Factorial using recursion may not be the best choice ...

  • check for overflow in Factorial or limit choice of n to good range

    since it gets big quickly
    
  • FileIsRegular now OBE (since go 1.1)

  • !Sane or just not init??? BBox.Sane() makes basic checks, usually employed only if Paranoid turned on

    see BBox.Contains() above as example
    
  • or is this an error ?

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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