Example #1
0
func TestGeoLookup(t *testing.T) {
	na, err := NewNetAcuity("netacuity.sea1.office.priv:5400")
	if err != nil {
		t.Fatal(err)
	}

	na.SetTimeout(time.Second)

	geo, err := na.QueryGeo("74.125.239.110")
	if err != nil {
		t.Fatal(err)
	}

	if "usa" != geo.Country {
		t.Errorf("Expected usa == %s", geo.Country)
	}

	//Accuracy of 1 degree is good enough for lat/long
	lat := math.Trunc(geo.Latitude)
	if 37 != lat {
		t.Errorf("Expected 37 (37.389) == %v", lat)
	}

	long := math.Trunc(geo.Longitude)
	if -122 != long {
		t.Errorf("Expected -122 (122.075) == %v", long)
	}
}
Example #2
0
func natural(n uint) uint {
	//
	randomNumber = productModM(randomNumber, a)
	randomNumber += c
	if randomNumber >= modulus {
		randomNumber -= modulus
	}
	if n == 0 {
		n = MaxNat
	}
	var r float64
	if n == MaxNat {
		r = maxNatF
	} else if n <= modulus {
		r = float64(n)
	} else {
		n -= modulus
		r = float64(n) + modulusF
	}
	r = (float64(randomNumber) / modulusF) * r
	if r <= modulusF {
		return uint(math.Trunc(r))
	}
	r -= modulusF
	return uint(math.Trunc(r)) + modulus
}
Example #3
0
// FloatPrecision float指定精度; round为true时, 表示支持四舍五入
func FloatPrecision(f float64, prec int, round bool) float64 {
	pow10N := math.Pow10(prec)
	if round {
		return math.Trunc((f+0.5/pow10N)*pow10N) / pow10N
	}
	return math.Trunc((f)*pow10N) / pow10N
}
Example #4
0
func (p *pIterator) next() bool {
	if !(p.countToIdx < p.h.totalCount) {
		if p.seenLastValue {
			return false
		}

		p.seenLastValue = true
		p.percentile = 100

		return true
	}

	if p.subBucketIdx == -1 && !p.iterator.next() {
		return false
	}

	var done = false
	for !done {
		currentPercentile := (100.0 * float64(p.countToIdx)) / float64(p.h.totalCount)
		if p.countAtIdx != 0 && p.percentileToIteratorTo <= currentPercentile {
			p.percentile = p.percentileToIteratorTo
			halfDistance := math.Trunc(math.Pow(2, math.Trunc(math.Log2(100.0/(100.0-p.percentileToIteratorTo)))+1))
			percentileReportingTicks := float64(p.ticksPerHalfDistance) * halfDistance
			p.percentileToIteratorTo += 100.0 / percentileReportingTicks
			return true
		}
		done = !p.iterator.next()
	}

	return true
}
func fromLLtoPixel(ll [2]float64, zoom uint64) [2]float64 {
	d := gp.zc[zoom]
	e := math.Trunc((d[0] + ll[0]*gp.Bc[zoom]) + 0.5)
	f := minmax(math.Sin(ll[1]*math.Pi/180.0), -0.9999, 0.9999)
	g := math.Trunc((d[1] + 0.5*math.Log((1+f)/(1-f))*-gp.Cc[zoom]) + 0.5)
	return [2]float64{e, g}
}
Example #6
0
func smoothedNoise(x float64, y float64, seed int64) float64 {
	xint := int64(math.Trunc(x))
	yint := int64(math.Trunc(y))

	corners := (noise(xint-1, yint-1, seed) + noise(xint+1, yint-1, seed) + noise(xint-1, yint+1, seed) + noise(xint+1, yint+1, seed)) / 16
	sides := (noise(xint-1, yint, seed) + noise(xint+1, yint, seed) + noise(xint, yint-1, seed) + noise(xint, yint+1, seed)) / 8
	center := noise(xint, yint, seed) / 4
	return corners + sides + center
}
func isPrime(nbr float64) bool {
	for i := math.Trunc(math.Sqrt(nbr)) + 1; i >= 2; i-- {
		var tmp float64 = nbr / i
		if tmp == math.Trunc(tmp) {
			return false
		}
	}
	return true
}
Example #8
0
func Val(a Any) uint {
	//
	var n uint = 1
	switch a.(type) {
	case Valuator:
		n = (a.(Valuator)).Val()
	case bool:
		if !a.(bool) {
			n = 0
		}
	case int8:
		i := a.(int8)
		if i < 0 {
			i = -i
		}
		n = uint(i)
	case int16:
		i := a.(int16)
		if i < 0 {
			i = -i
		}
		n = uint(i)
	case int32:
		i := a.(int32)
		if i < 0 {
			i = -i
		}
		n = uint(i)
	case int:
		i := a.(int)
		if i < 0 {
			i = -i
		}
		n = uint(i)
	case byte:
		n = uint(a.(byte))
	case uint16:
		n = uint(a.(uint16))
	case uint32:
		n = uint(a.(uint32))
	case uint:
		n = a.(uint)
	case float32:
		n = nat(math.Trunc(float64(a.(float32) + 0.5)))
	case float64:
		n = nat(math.Trunc(a.(float64) + 0.5))
	case complex64:
		c := a.(complex64)
		n = nat(math.Trunc(math.Sqrt(float64(real(c)*real(c)+imag(c)*imag(c))) + 0.5))
	case complex128:
		c := a.(complex128)
		n = nat(math.Trunc(math.Sqrt(real(c)*real(c)+imag(c)*imag(c)) + 0.5))
	case string:
		// TODO sum of bytes of the string ? Hash-Code ?
	}
	return n
}
func main() {
	for k := math.Trunc(math.Sqrt(NBR)) + 1; k >= 2; k-- {
		var tmp float64 = NBR / k
		if tmp == math.Trunc(tmp) && isPrime(k) {
			fmt.Println("Largest prime factor = ", k)
			return
		}
	}

	fmt.Println("Error.")
}
Example #10
0
File: web.go Project: kalafut/gmw
func durationToString(d time.Duration) string {
	hours := int(math.Trunc(d.Hours()))
	minutes := int(math.Trunc(d.Minutes())) - 60*hours
	seconds := int(d.Seconds()) % 60

	if hours > 0 {
		return fmt.Sprintf("%d:%d:%02d", hours, minutes, seconds)
	}

	return fmt.Sprintf("%d:%02d", minutes, seconds)
}
Example #11
0
func (c ColorCube) GetColor(x, y, z int) color.RGBA {
	if x > c.SideSize || y >= c.SideSize || z >= c.SideSize {
		panic("index out of range")
	}

	ratio := float64(MAX_SIDE_SIZE-1) / float64(c.SideSize-1)
	xIndex := uint8(math.Trunc(float64(x) * ratio))
	yIndex := uint8(math.Trunc(float64(y) * ratio))
	zIndex := uint8(math.Trunc(float64(z) * ratio))
	return color.RGBA{xIndex, yIndex, zIndex, 255}
}
Example #12
0
func scale(x, y float64) (int, int) {
	//
	rx, ry := int(math.Trunc(mX*(x-x0))+0.5), int(math.Trunc(mY*(y-y0))+0.5)
	ry = int(scr.NY()) - ry
	if scr.UnderX() {
		if minInt <= rx && rx < maxInt && minInt <= ry && ry < maxInt {
			return rx, ry
		}
	} else if x0 <= x && x < x0+width && y0 <= y && y < y0+height {
		return rx, ry
	}
	return maxInt, maxInt
}
Example #13
0
// interp2d returns noise for x,y interpolated from
// the given 2D noise function.
func interp2d(x, y float64, seed int64, interp func(a, b, x float64) float64) float64 {
	intx, fracx := int(x), x-math.Trunc(x)
	inty, fracy := int(y), y-math.Trunc(y)

	v1 := smooth2d(intx, inty, seed)
	v2 := smooth2d(intx+1, inty, seed)
	i1 := interp(v1, v2, fracx)

	v3 := smooth2d(intx, inty+1, seed)
	v4 := smooth2d(intx+1, inty+1, seed)
	i2 := interp(v3, v4, fracx)

	return interp(i1, i2, fracy)
}
Example #14
0
func abc() {
	type T struct {
		a int
		b int
		c float64
	}

	type SliceHeader struct {
		addr uintptr
		len  int
		cap  int
	}

	t := &T{a: 1, b: 2, c: 3.2}
	p := unsafe.Sizeof(*t)
	println("t size:", int(p))
	fmt.Println("t value:", t)

	sl := &SliceHeader{
		addr: uintptr(unsafe.Pointer(t)),
		len:  int(p),
		cap:  int(p),
	}

	b := *(*[]byte)(unsafe.Pointer(sl))
	println("byte size: ", len(b))
	fmt.Println("byte content: ", b)

	b[0] = 12
	b[7] = 0
	b[8] = 24

	fmt.Println("last t value: ", t)
	fmt.Println("last byte content: ", b)

	ft := 10.1234567
	ftval := 0.0
	lastVal := math.Pow10(-4)
	addVal := math.Pow10(-5)
	fmt.Printf("add val: %f\n", addVal)
	tmp := math.Mod(math.Trunc(ft/addVal), 10)
	fmt.Printf("tmp val: %f\n", tmp)
	if tmp >= 5 {
		ftval = ft + lastVal
	} else {
		ftval = ft
	}
	fmt.Println(math.Trunc(ftval/lastVal) / math.Pow10(4))

}
Example #15
0
// LeastSquares function
// A timeseries is anomalous if the average of the last three datapoints
// on a projected least squares model is greater than three sigma.
func LeastSquares(timeseries []TimePoint) bool {
	m, c := LinearRegressionLSE(timeseries)
	var errs []float64
	for _, val := range timeseries {
		projected := m*float64(val.GetTimestamp()) + c
		errs = append(errs, val.GetValue()-projected)
	}
	l := len(errs)
	if l < 3 {
		return false
	}
	stdDev := Std(errs)
	t := (errs[l-1] + errs[l-2] + errs[l-3]) / 3
	return math.Abs(t) > stdDev*3 && math.Trunc(stdDev) != 0 && math.Trunc(t) != 0
}
Example #16
0
func (atlas *FontAtlas) Draw(text string, b Bounds) {
	atlas.LoadGlyphs(text)

	gl.Enable(gl.BLEND)
	defer gl.Disable(gl.BLEND)
	gl.BlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)

	gl.Enable(gl.TEXTURE_2D)
	defer gl.Disable(gl.TEXTURE_2D)
	gl.BindTexture(gl.TEXTURE_2D, atlas.Texture)

	x := b.Min.X + atlas.drawPadding
	y := (b.Max.Y+b.Min.Y)/2 + (ceilPxf(atlas.maxBounds.Min.Y)+ceilPxf(atlas.maxBounds.Max.Y))/2

	p := rune(0)
	for _, r := range text {
		glyph := atlas.Rendered[r]

		dx := float32(glyph.Loc.Dx())
		dy := float32(glyph.Loc.Dy())

		px := x + ceilPxf(glyph.Bounds.Min.X) - glyphPadding
		py := y + ceilPxf(glyph.Bounds.Min.Y) - glyphPadding

		// this is not the ideal way of positioning the letters
		// will create positioning artifacts
		// but it the result is more
		px = float32(math.Trunc(float64(px)))
		py = float32(math.Trunc(float64(py)))

		gl.Begin(gl.QUADS)
		{
			gl.TexCoord2f(glyph.RelLoc.Min.X, glyph.RelLoc.Min.Y)
			gl.Vertex2f(px, py)
			gl.TexCoord2f(glyph.RelLoc.Max.X, glyph.RelLoc.Min.Y)
			gl.Vertex2f(px+dx, py)
			gl.TexCoord2f(glyph.RelLoc.Max.X, glyph.RelLoc.Max.Y)
			gl.Vertex2f(px+dx, py+dy)
			gl.TexCoord2f(glyph.RelLoc.Min.X, glyph.RelLoc.Max.Y)
			gl.Vertex2f(px, py+dy)
		}
		gl.End()

		k := atlas.Face.Kern(p, r)
		p = r
		x += ceilPxf(glyph.Advance + k)
	}
}
Example #17
0
// fillAvgPct caches the average, 95th percentile of the DayStore.
func (ds *DayStore) fillAvgPct() {
	ds.validAvgPct = true

	// If no past Hourly data has been flushed to the window,
	// return the average and 95th percentile of the past hour.
	if ds.size == 0 {
		ds.cachedAverage, _ = ds.Hour.Average()
		ds.cachedNinetyFifth, _ = ds.Hour.Percentile(0.95)
		return
	}
	// Otherwise, ignore the past one hour and use the window values

	// generate a slice of the window
	day := ds.window.Slice()

	// calculate the average value of the hourly averages
	// also create a sortable slice of float64
	var sum uint64
	var nf []float64
	for _, elem := range day {
		he := elem.(hourEntry)
		sum += he.average
		nf = append(nf, float64(he.ninetyFifth))
	}
	ds.cachedAverage = sum / uint64(ds.size)

	// sort and calculate the 95th percentile
	sort.Float64s(nf)
	pcIdx := int(math.Trunc(0.95 * float64(ds.size+1)))
	if pcIdx >= len(nf) {
		pcIdx = len(nf) - 1
	}
	ds.cachedNinetyFifth = uint64(nf[pcIdx])
}
Example #18
0
// RoundFloat rounds float val to the nearest integer value with float64 format, like MySQL Round function.
// RoundFloat uses default rounding mode, see https://dev.mysql.com/doc/refman/5.7/en/precision-math-rounding.html
// so rounding use "round half away from zero".
// e.g, 1.5 -> 2, -1.5 -> -2.
func RoundFloat(f float64) float64 {
	if math.Abs(f) < 0.5 {
		return 0
	}

	return math.Trunc(f + math.Copysign(0.5, f))
}
Example #19
0
/**
 * Test that the parameters provided to scrypt will satisfy all its requirements.
 */
func verifyParameterValidity(parameters HashConfiguration) error {
	// Check that N is in the allowed range and a power of 2
	exponent := math.Log2(float64(parameters.N))
	isWhole := exponent == math.Trunc(exponent)
	if parameters.N < MinN || parameters.N > MaxN || !isWhole {
		return ErrInvalidNValue
	}
	// Check that r and p are positive integers less than 2^30 and that r * p < 2^30
	if parameters.R < MinR || parameters.R > MaxR {
		return ErrInvalidRValue
	}
	if parameters.P < MinP || parameters.P > MaxP {
		return ErrInvalidPValue
	}
	product := parameters.R * parameters.P
	if product <= 0 || product > MaxP {
		return ErrInvalidRPValues
	}
	// Check that the salt is long enough
	if parameters.SaltLen < MinSaltLen {
		return ErrSaltTooShort
	}
	// Check that the key length is large enough
	if parameters.KeyLen < MinKeyLen {
		return ErrKeyTooShort
	}
	return nil
}
Example #20
0
// Round returns the half away from zero rounded value of x with prec precision.
//
// Special cases are:
// 	Round(±0) = +0
// 	Round(±Inf) = ±Inf
// 	Round(NaN) = NaN
func Round(x float64, prec int) float64 {
	if x == 0 {
		// Make sure zero is returned
		// without the negative bit set.
		return 0
	}
	// Fast path for positive precision on integers.
	if prec >= 0 && x == math.Trunc(x) {
		return x
	}
	pow := math.Pow10(prec)
	intermed := x * pow
	if math.IsInf(intermed, 0) {
		return x
	}
	if x < 0 {
		x = math.Ceil(intermed - 0.5)
	} else {
		x = math.Floor(intermed + 0.5)
	}

	if x == 0 {
		return 0
	}

	return x / pow
}
Example #21
0
func IsPentagonal(n int) bool {
	tmp := (math.Sqrt(1+24*float64(n)) + 1) / 6
	if tmp == math.Trunc(tmp) {
		return true
	}
	return false
}
Example #22
0
func logic() {
	switch game.state {
	case LOGO:
		logo.update()
	case MENU:
		go menu.events()
		go bg.fadeout()
		go text.fadeout()
		go menu.update()
	case CREDITS:
		credits.events()
	case UPGRADE:
		upgrade.events()
	case OPTIONS:
		options.events()
	case PLAY:
		game.check_pause()
		bonus.fadeout()
		field.fadeout()
		lines.fadeout()
		plane.move()
		lines.move_lines()
		field.add_tick_bombs()
		field.rotate_bombs()
		plane.check_collision()
		game.slomo()
		if plane.out() {
			game.level_cash++
			plane.teleport()

		}
		update_timer()
		break
	case PAUSE:
		game.check_pause()
		pause_menu.events()
		break
	case LIFE_LOST:
		update_timer()
		interval = int(math.Trunc(elapsed.Seconds() * 100))
		if interval >= 50 && !life_removed {
			start_timer()
			plane.life--
			life_removed = true
			interval = 0
			break
		}
		if interval >= 50 && life_removed {
			life_removed = false
			game.state = PLAY
			plane.visible = true
			plane.teleport()
			start_timer()
			break
		}
	case GAME_OVER:
		game.game_over_event()
		break
	}
}
Example #23
0
// Creates a summary from a set of log files.
func Summarize(logfiles []string) (string, error) {
	l := new(combiner)
	l.logfiles = logfiles

	err := l.proc()
	if err != nil {
		return "", err
	}

	l.initSample()

	hcnt := len(l.headers)

	for _, ts := range l.sortedIndex {
		for i, field := range l.entries[ts] {
			// Adjust for the smallest set.
			if i >= hcnt {
				break
			}
			name := l.headers[i]

			// It isn't clear to me how to utilize the metrics library
			// when working with floats, so I decided to truncate them.
			// I found this Float64bits(f float64) uint64, but an unsigned
			// integer is about as helpful as a float.
			value, _ := strconv.ParseFloat(field, 64)
			value = math.Trunc(value)
			l.sample[name].Update(int64(value))
		}
	}

	return l.report(), nil
}
Example #24
0
// quantile returns a value representing the kth of q quantiles.
// May alter the order of data.
func quantile(data []time.Duration, k, q int) (quantile time.Duration, ok bool) {
	if len(data) < 1 {
		return 0, false
	}
	if k > q {
		return 0, false
	}
	if k < 0 || q < 1 {
		return 0, false
	}

	sort.Sort(byDuration(data))

	if k == 0 {
		return data[0], true
	}
	if k == q {
		return data[len(data)-1], true
	}

	bucketSize := float64(len(data)-1) / float64(q)
	i := float64(k) * bucketSize

	lower := int(math.Trunc(i))
	var upper int
	if i > float64(lower) && lower+1 < len(data) {
		// If the quantile lies between two elements
		upper = lower + 1
	} else {
		upper = lower
	}
	weightUpper := i - float64(lower)
	weightLower := 1 - weightUpper
	return time.Duration(weightLower*float64(data[lower]) + weightUpper*float64(data[upper])), true
}
Example #25
0
// fillCache caches the average, max and percentiles of the StatStore.
// Assumes a write lock is taken by the caller.
func (ss *StatStore) fillCache() {
	// Calculate the average and max, flatten values into a slice
	sum := uint64(0)
	curMax := uint64(0)
	vals := []float64{}
	for elem := ss.buffer.Front(); elem != nil; elem = elem.Next() {
		entry := elem.Value.(tpBucket)

		// Calculate the weighted sum of all tpBuckets
		sum += uint64(entry.count) * entry.value

		// Compare the bucket max with the total max
		if entry.max > curMax {
			curMax = entry.max
		}

		// Create a slice of values to generate percentiles
		for i := uint8(0); i < entry.count; i++ {
			vals = append(vals, float64(entry.value))
		}
	}
	ss.cachedAverage = sum / uint64(ss.tpCount)
	ss.cachedMax = curMax

	// Calculate all supported percentiles
	sort.Float64s(vals)
	ss.cachedPercentiles = []uint64{}
	for _, spc := range ss.supportedPercentiles {
		pcIdx := int(math.Trunc(spc * float64(ss.tpCount)))
		ss.cachedPercentiles = append(ss.cachedPercentiles, uint64(vals[pcIdx]))
	}

	ss.validCache = true
}
Example #26
0
func GenerateUUID() string {

	// http://www.broofa.com/Tools/Math.uuid.htm

	chars := strings.Split("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", "")
	uuid := make([]string, 36)
	rnd := 0
	var r int

	for i := 0; i < 36; i++ {
		if i == 8 || i == 13 || i == 18 || i == 23 {
			uuid[i] = "-"
		} else if i == 14 {
			uuid[i] = "4"
		} else {
			if rnd <= 0x02 {
				rnd = 0x2000000 + int(math.Trunc(rand.Float64()*float64(0x1000000)))
			}
			r = rnd & 0xf
			rnd = rnd >> 4
			if i == 19 {
				uuid[i] = chars[(r&0x3)|0x8]
			} else {
				uuid[i] = chars[r]
			}
		}
	}
	return strings.Join(uuid, "")
}
Example #27
0
func (ip indexPart) Resolve(v Value) Value {
	switch v := v.(type) {
	case List:
		if n, ok := ip.idx.(Number); ok {
			f := float64(n)
			if f == math.Trunc(f) && f >= 0 {
				u := uint64(f)
				if u < v.Len() {
					if ip.key {
						return ip.idx
					}
					return v.Get(u)
				}
			}
		}

	case Map:
		if ip.key && v.Has(ip.idx) {
			return ip.idx
		}
		if !ip.key {
			return v.Get(ip.idx)
		}
	}

	return nil
}
Example #28
0
func (b *Bonus) apply_effect() {
	b.show_text = true
	switch b.effect {
	case SLOMO:
		game.slomo_flag = true
		b.active = true
		b.active_effect = SLOMO
		game.saved_score += int(math.Trunc(elapsed.Seconds() * 100))
		start_timer()
	case FREEZE:
		lines.move = false
	case LIFE_UP:
		if plane.life != 3 {
			plane.life++
		}
	case SHIELD:
		plane.shielded = true
	case MORE_BOMBS:
		field.create_bombs(3)
	case MIRROR_MODE:
		game.mirror_mode = true
		b.active_effect = MIRROR_MODE
		b.active = true
	case MOVE_BLOCKS:
		lines.move = true
	case LIFE_DOWN:
		plane.death()
	}
}
Example #29
0
func (t *Table) autoWidth() error {
	//each column
	var wa columns.Columns
	colsvisbile := t.columnsvisible
	for i := range colsvisbile {
		if colsvisbile[i].IsAutoSize() || t.autoSize > 0 {
			colsvisbile[i].MaxLen = len(colsvisbile[i].Caption)

			wa.Add(colsvisbile[i])
		}
	}
	if len(wa) == 0 {
		return nil
	}
	for _, data := range t.Data {
		for i := range wa {
			curval := fmt.Sprintf("%v", data[wa[i].Name])
			curlen := utf8.RuneCountInString(curval)
			if curlen > wa[i].MaxLen {
				wa[i].MaxLen = curlen
			}
		}
	}
	//autosize table
	if t.autoSize > 0 {
		termwidth := t.autoSize - utf8.RuneCountInString(Borders[t.border][BKVertical])*colsvisbile.Len() - utf8.RuneCountInString(Borders[t.border][BKVerticalBorder])*2
		nowwidths := make([]int, colsvisbile.Len())
		allcolswidth := 0
		for i := range colsvisbile {
			if colsvisbile[i].MaxLen > colsvisbile[i].Width || colsvisbile[i].IsAutoSize() {
				nowwidths[i] = colsvisbile[i].MaxLen
			} else {
				nowwidths[i] = colsvisbile[i].Width
			}
			allcolswidth += nowwidths[i]
		}
		//todo: allcolswidth - borders
		twAll := 0
		for i := range colsvisbile {
			colsvisbile[i].MaxLen = int(math.Trunc(float64(termwidth) * (float64(nowwidths[i]) / float64(allcolswidth))))
			twAll += colsvisbile[i].MaxLen
		}
		i := 0
		//distrib mod
		for {
			if twAll >= termwidth || twAll <= 0 {
				break
			}
			if i+1 >= colsvisbile.Len() {
				i = 0
			}
			colsvisbile[i].MaxLen = colsvisbile[i].MaxLen + 1

			twAll = twAll + 1
			i = i + 1
		}
	}
	return nil
}
Example #30
0
func decodeDateTime(buf []byte) time.Time {
	days := int32(binary.LittleEndian.Uint32(buf))
	tm := binary.LittleEndian.Uint32(buf[4:])
	ns := int(math.Trunc(float64(tm%300)/0.3+0.5)) * 1000000
	secs := int(tm / 300)
	return time.Date(1900, 1, 1+int(days),
		0, 0, secs, ns, time.UTC)
}