code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1 value |
|---|---|---|---|---|---|
package subscribe
import "encoding/binary"
var LimitMaxValue uint64 = 0x100000000 //2^32
type BitMap interface {
Existed(value uint64) bool
Put(value uint64) error
Remove(value uint64)
Resize(value uint64) error
Range() (min, max uint64)
Size() int
Count() int
}
func indexAndMask(value uint64) (index uint64, mask byte) {
index = value >> 3
mod := (byte)(value & 0x07)
if mod == 0 {
index -= 1
mask = 0x01 << 7
} else {
mask = 0x01 << (mod - 1)
}
return
}
func normalizedWithLimit(value, offset, limit uint64) (uint64, bool) {
value = value - offset
return value, (value > 0 && value <= limit)
}
//value - offset must range from 1 to LimitMaxValue
func normalized(value, offset uint64) (uint64, bool) {
return normalizedWithLimit(value, offset, LimitMaxValue)
}
//caculate the sum of 1(from redis)
func caculateBitCount(p []byte) int {
count := 0
size := len(p)
left := size
for left >= 28 {
var v1, v2, v3, v4, v5, v6, v7 uint32
v1 = binary.BigEndian.Uint32(p[size-left : size-left+4])
v2 = binary.BigEndian.Uint32(p[size-left+4 : size-left+8])
v3 = binary.BigEndian.Uint32(p[size-left+8 : size-left+12])
v4 = binary.BigEndian.Uint32(p[size-left+12 : size-left+16])
v5 = binary.BigEndian.Uint32(p[size-left+16 : size-left+20])
v6 = binary.BigEndian.Uint32(p[size-left+20 : size-left+24])
v7 = binary.BigEndian.Uint32(p[size-left+24 : size-left+28])
v1 = v1 - ((v1 >> 1) & 0x55555555)
v1 = (v1 & 0x33333333) + ((v1 >> 2) & 0x33333333)
v2 = v2 - ((v2 >> 1) & 0x55555555)
v2 = (v2 & 0x33333333) + ((v2 >> 2) & 0x33333333)
v3 = v3 - ((v3 >> 1) & 0x55555555)
v3 = (v3 & 0x33333333) + ((v3 >> 2) & 0x33333333)
v4 = v4 - ((v4 >> 1) & 0x55555555)
v4 = (v4 & 0x33333333) + ((v4 >> 2) & 0x33333333)
v5 = v5 - ((v5 >> 1) & 0x55555555)
v5 = (v5 & 0x33333333) + ((v5 >> 2) & 0x33333333)
v6 = v6 - ((v6 >> 1) & 0x55555555)
v6 = (v6 & 0x33333333) + ((v6 >> 2) & 0x33333333)
v7 = v7 - ((v7 >> 1) & 0x55555555)
v7 = (v7 & 0x33333333) + ((v7 >> 2) & 0x33333333)
bitCount := ((((v1 + (v1 >> 4)) & 0x0F0F0F0F) +
((v2 + (v2 >> 4)) & 0x0F0F0F0F) +
((v3 + (v3 >> 4)) & 0x0F0F0F0F) +
((v4 + (v4 >> 4)) & 0x0F0F0F0F) +
((v5 + (v5 >> 4)) & 0x0F0F0F0F) +
((v6 + (v6 >> 4)) & 0x0F0F0F0F) +
((v7 + (v7 >> 4)) & 0x0F0F0F0F)) * 0x01010101) >> 24
count += int(bitCount)
left -= 28
}
if left > 0 {
for _, b := range p[size-left : size] {
num := byte(0)
mask := byte(0x80)
for k := 7; k >= 0; k-- {
num += (b & mask) >> k
mask = mask >> 1
}
count += int(num)
}
}
return count
} | sxg/subscribe/bitmap.go | 0.580233 | 0.45647 | bitmap.go | starcoder |
package portable
import (
"image"
"image/color"
"math"
)
func bilinear(src image.Image, x, y float32) color.Color {
switch src := src.(type) {
case *image.RGBA:
return bilinearRGBA(src, x, y)
case *image.Alpha:
return bilinearAlpha(src, x, y)
case *image.Uniform:
return src.C
default:
return bilinearGeneral(src, x, y)
}
}
func bilinearGeneral(src image.Image, x, y float32) color.RGBA64 {
p := findLinearSrc(src.Bounds(), x, y)
r00, g00, b00, a00 := src.At(p.low.X, p.low.Y).RGBA()
r01, g01, b01, a01 := src.At(p.high.X, p.low.Y).RGBA()
r10, g10, b10, a10 := src.At(p.low.X, p.high.Y).RGBA()
r11, g11, b11, a11 := src.At(p.high.X, p.high.Y).RGBA()
fr := float32(r00) * p.frac00
fg := float32(g00) * p.frac00
fb := float32(b00) * p.frac00
fa := float32(a00) * p.frac00
fr += float32(r01) * p.frac01
fg += float32(g01) * p.frac01
fb += float32(b01) * p.frac01
fa += float32(a01) * p.frac01
fr += float32(r10) * p.frac10
fg += float32(g10) * p.frac10
fb += float32(b10) * p.frac10
fa += float32(a10) * p.frac10
fr += float32(r11) * p.frac11
fg += float32(g11) * p.frac11
fb += float32(b11) * p.frac11
fa += float32(a11) * p.frac11
return color.RGBA64{
R: uint16(fr + 0.5),
G: uint16(fg + 0.5),
B: uint16(fb + 0.5),
A: uint16(fa + 0.5),
}
}
func bilinearRGBA(src *image.RGBA, x, y float32) color.RGBA {
p := findLinearSrc(src.Bounds(), x, y)
// Slice offsets for the surrounding pixels.
off00 := src.PixOffset(p.low.X, p.low.Y)
off01 := src.PixOffset(p.high.X, p.low.Y)
off10 := src.PixOffset(p.low.X, p.high.Y)
off11 := src.PixOffset(p.high.X, p.high.Y)
fr := float32(src.Pix[off00+0]) * p.frac00
fg := float32(src.Pix[off00+1]) * p.frac00
fb := float32(src.Pix[off00+2]) * p.frac00
fa := float32(src.Pix[off00+3]) * p.frac00
fr += float32(src.Pix[off01+0]) * p.frac01
fg += float32(src.Pix[off01+1]) * p.frac01
fb += float32(src.Pix[off01+2]) * p.frac01
fa += float32(src.Pix[off01+3]) * p.frac01
fr += float32(src.Pix[off10+0]) * p.frac10
fg += float32(src.Pix[off10+1]) * p.frac10
fb += float32(src.Pix[off10+2]) * p.frac10
fa += float32(src.Pix[off10+3]) * p.frac10
fr += float32(src.Pix[off11+0]) * p.frac11
fg += float32(src.Pix[off11+1]) * p.frac11
fb += float32(src.Pix[off11+2]) * p.frac11
fa += float32(src.Pix[off11+3]) * p.frac11
return color.RGBA{
R: uint8(fr + 0.5),
G: uint8(fg + 0.5),
B: uint8(fb + 0.5),
A: uint8(fa + 0.5),
}
}
func bilinearAlpha(src *image.Alpha, x, y float32) color.Alpha {
p := findLinearSrc(src.Bounds(), x, y)
// Slice offsets for the surrounding pixels.
off00 := src.PixOffset(p.low.X, p.low.Y)
off01 := src.PixOffset(p.high.X, p.low.Y)
off10 := src.PixOffset(p.low.X, p.high.Y)
off11 := src.PixOffset(p.high.X, p.high.Y)
fa := float32(src.Pix[off00]) * p.frac00
fa += float32(src.Pix[off01]) * p.frac01
fa += float32(src.Pix[off10]) * p.frac10
fa += float32(src.Pix[off11]) * p.frac11
return color.Alpha{A: uint8(fa + 0.5)}
}
type bilinearSrc struct {
// Top-left and bottom-right interpolation sources
low, high image.Point
// Fraction of each pixel to take. The 0 suffix indicates
// top/left, and the 1 suffix indicates bottom/right.
frac00, frac01, frac10, frac11 float32
}
func floor(x float32) float32 { return float32(math.Floor(float64(x))) }
func ceil(x float32) float32 { return float32(math.Ceil(float64(x))) }
func findLinearSrc(b image.Rectangle, sx, sy float32) bilinearSrc {
maxX := float32(b.Max.X)
maxY := float32(b.Max.Y)
minX := float32(b.Min.X)
minY := float32(b.Min.Y)
lowX := floor(sx - 0.5)
lowY := floor(sy - 0.5)
if lowX < minX {
lowX = minX
}
if lowY < minY {
lowY = minY
}
highX := ceil(sx - 0.5)
highY := ceil(sy - 0.5)
if highX >= maxX {
highX = maxX - 1
}
if highY >= maxY {
highY = maxY - 1
}
// In the variables below, the 0 suffix indicates top/left, and the
// 1 suffix indicates bottom/right.
// Center of each surrounding pixel.
x00 := lowX + 0.5
y00 := lowY + 0.5
x01 := highX + 0.5
y01 := lowY + 0.5
x10 := lowX + 0.5
y10 := highY + 0.5
x11 := highX + 0.5
y11 := highY + 0.5
p := bilinearSrc{
low: image.Pt(int(lowX), int(lowY)),
high: image.Pt(int(highX), int(highY)),
}
// Literally, edge cases. If we are close enough to the edge of
// the image, curtail the interpolation sources.
if lowX == highX && lowY == highY {
p.frac00 = 1.0
} else if sy-minY <= 0.5 && sx-minX <= 0.5 {
p.frac00 = 1.0
} else if maxY-sy <= 0.5 && maxX-sx <= 0.5 {
p.frac11 = 1.0
} else if sy-minY <= 0.5 || lowY == highY {
p.frac00 = x01 - sx
p.frac01 = sx - x00
} else if sx-minX <= 0.5 || lowX == highX {
p.frac00 = y10 - sy
p.frac10 = sy - y00
} else if maxY-sy <= 0.5 {
p.frac10 = x11 - sx
p.frac11 = sx - x10
} else if maxX-sx <= 0.5 {
p.frac01 = y11 - sy
p.frac11 = sy - y01
} else {
p.frac00 = (x01 - sx) * (y10 - sy)
p.frac01 = (sx - x00) * (y11 - sy)
p.frac10 = (x11 - sx) * (sy - y00)
p.frac11 = (sx - x10) * (sy - y01)
}
return p
} | vendor/src/golang.org/x/mobile/sprite/portable/bilinear.go | 0.804175 | 0.729387 | bilinear.go | starcoder |
package practice
/*
Practice Recursion, Memoization and Goroutines:
Fib: Fib(n) = Fib(n - 1) + Fib(n - 2) where Fib(0) = 0 and Fib(1) = 1
Fib(0) = 0
Fib(1) = 1
Fib(2) = 1
Fib(3) = 2
Fib(4) = 3
Fib(5) = 5
Fib(6) = 8
Fib(7) = 13
Fib(8) = 21
*/
//RecursiveFib -- Typical recursive solution
func RecursiveFib(num int) int {
if num == 0 {
return 0
}
if num == 1 {
return 1
}
return RecursiveFib(num-1) + RecursiveFib(num-2)
}
//IterativeFib -- Iterative solution for fib
func IterativeFib(num int) int {
if num == 0 {
return 0
}
a := 0
b := 1
for i := 2; i < num; i++ {
c := a + b
a, b = b, c
}
return a + b
}
/*TopDownMemoizationFib -- Fib using top down memoization
Study the recursive tree. Where do you see identical nodes [tree of fib(5)]?
There are lots of identical nodes. For example, fib(3) appears twice and fib(2)
appears three times. Why should we recompute these from scratch each time?
In fact, when we call fib(n), we shouldn't have to do much more than O(n) calls, since
there's only O(n) possible values we can throw at fib. Each time we computer fib, we
should just cache this result and use it later.
*/
func TopDownMemoizationFib(num int) int {
var cache = make(map[int]int)
return fibonacciTDM(num, cache)
}
func fibonacciTDM(num int, cache map[int]int) int {
if num == 0 || num == 1 {
return num
}
answer, ok := cache[num]
if !ok {
cache[num] = fibonacciTDM(num-1, cache) + fibonacciTDM(num-2, cache)
answer = cache[num]
}
return answer
}
/*
BottomUpMemoizationFib -- Fib using bottom up memoziotion
We can also take this approach and implement it with bottom-up dynamic programming.
Think about doing the same recursive memoized approach, but in reverse.
First, we compute fib(1) and fib(0), which are already known from the base cases.
Then we use those to compute fib(2). Then we use the prior answers to compute fib(3)
and fib(4)
*/
func BottomUpMemoizationFib(num int) int {
if num == 0 {
return num
}
if num == 1 {
return 1
}
var cache = make(map[int]int)
cache[0] = 0
cache[1] = 1
for i := 2; i < num; i++ {
cache[i] = cache[i-1] + cache[i-2]
}
return cache[num-1] + cache[num-2]
} | chapter8/practice/practice.go | 0.612657 | 0.441553 | practice.go | starcoder |
package bn256
import (
"errors"
"math/big"
"github.com/MadBase/MadNet/crypto/bn256/cloudflare"
)
// numBytes specifies the number of bytes in a GFp object
const numBytes = 32
// ErrNotUint256 occurs when we work with a uint with more than 256 bits
var ErrNotUint256 = errors.New("big.Ints are not at most 256-bit unsigned integers")
// ErrInvalidData occurs data is invalid
var ErrInvalidData = errors.New("invalid data")
// MarshalBigInt converts a 256-bit uint into a byte slice.
func MarshalBigInt(x *big.Int) ([]byte, error) {
if x == nil {
return nil, ErrInvalidData
}
xBytes := x.Bytes()
xBytesLen := len(xBytes)
if xBytesLen > numBytes {
return nil, ErrNotUint256
}
byteSlice := make([]byte, numBytes)
for j := 1; j <= xBytesLen; j++ {
byteSlice[numBytes-j] = xBytes[xBytesLen-j]
}
return byteSlice, nil
}
// MarshalG1Big is used to compare the result from Go code generated
// by Solidity with the original Go code in cloudflare directory.
func MarshalG1Big(hashPoint [2]*big.Int) ([]byte, error) {
// Note: assuming hashPoint is a value G1 point
bigZero := big.NewInt(0)
hashMarsh := make([]byte, 2*numBytes)
x := hashPoint[0]
y := hashPoint[1]
if x == nil || y == nil {
return nil, ErrInvalidData
}
if x.Cmp(bigZero) == 0 {
return hashMarsh, nil
}
tmpBytes, err := MarshalBigInt(x)
if err != nil {
return nil, err
}
for k := 0; k < numBytes; k++ {
hashMarsh[k] = tmpBytes[k]
}
tmpBytes, err = MarshalBigInt(y)
if err != nil {
return nil, err
}
for k := 0; k < numBytes; k++ {
hashMarsh[numBytes+k] = tmpBytes[k]
}
return hashMarsh, nil
}
// MarshalG2Big is used to compare the result from Go code generated
// by Solidity with the original Go code in cloudflare directory.
func MarshalG2Big(hashPoint [4]*big.Int) ([]byte, error) {
// Note: assuming hashPoint is a value G2 point
bigZero := big.NewInt(0)
hashMarsh := make([]byte, 4*numBytes)
xi := hashPoint[0]
x := hashPoint[1]
yi := hashPoint[2]
y := hashPoint[3]
if x == nil || xi == nil || y == nil || yi == nil {
return nil, ErrInvalidData
}
if xi.Cmp(bigZero) == 0 {
return hashMarsh, nil
}
tmpBytes, err := MarshalBigInt(xi)
if err != nil {
return nil, err
}
for k := 0; k < numBytes; k++ {
hashMarsh[k] = tmpBytes[k]
}
tmpBytes, err = MarshalBigInt(x)
if err != nil {
return nil, err
}
for k := 0; k < numBytes; k++ {
hashMarsh[numBytes+k] = tmpBytes[k]
}
tmpBytes, err = MarshalBigInt(yi)
if err != nil {
return nil, err
}
for k := 0; k < numBytes; k++ {
hashMarsh[2*numBytes+k] = tmpBytes[k]
}
tmpBytes, err = MarshalBigInt(y)
if err != nil {
return nil, err
}
for k := 0; k < numBytes; k++ {
hashMarsh[3*numBytes+k] = tmpBytes[k]
}
return hashMarsh, nil
}
// G1ToBigIntArray converts cloudflare.G2 into big.Int array for testing purposes.
func G1ToBigIntArray(g1 *cloudflare.G1) ([2]*big.Int, error) {
if g1 == nil {
return [2]*big.Int{}, ErrInvalidData
}
g1Bytes := g1.Marshal()
g1X := new(big.Int).SetBytes(g1Bytes[:numBytes])
g1Y := new(big.Int).SetBytes(g1Bytes[numBytes : 2*numBytes])
g1BigInt := [2]*big.Int{g1X, g1Y}
return g1BigInt, nil
}
// BigIntArrayToG1 converts Ethereum big.Int G1 arrays into cloudflare.G1
// elements for computing purposes.
func BigIntArrayToG1(g1BigInt [2]*big.Int) (*cloudflare.G1, error) {
g1Bytes, err := MarshalG1Big(g1BigInt)
if err != nil {
return nil, err
}
g1 := new(cloudflare.G1)
_, err = g1.Unmarshal(g1Bytes)
if err != nil {
return nil, err
}
return g1, nil
}
// BigIntArrayToG2 converts Ethereum big.Int G2 arrays into cloudflare.G2
// elements for computing purposes.
func BigIntArrayToG2(g2BigInt [4]*big.Int) (*cloudflare.G2, error) {
g2Bytes, err := MarshalG2Big(g2BigInt)
if err != nil {
return nil, err
}
g2 := new(cloudflare.G2)
_, err = g2.Unmarshal(g2Bytes)
if err != nil {
return nil, err
}
return g2, nil
}
// BigIntArraySliceToG1 converts Ethereum big.Int G1 array slice into
// cloudflare.G1 slice for computing purposes.
func BigIntArraySliceToG1(g1BigIntArray [][2]*big.Int) ([]*cloudflare.G1, error) {
m := len(g1BigIntArray)
g1Array := make([]*cloudflare.G1, m)
for j := 0; j < m; j++ {
g1Big := g1BigIntArray[j]
g1, err := BigIntArrayToG1(g1Big)
if err != nil {
return nil, err
}
g1Array[j] = g1
}
return g1Array, nil
}
// G2ToBigIntArray converts cloudflare.G2 into big.Int array for testing purposes.
func G2ToBigIntArray(g2 *cloudflare.G2) ([4]*big.Int, error) {
if g2 == nil {
return [4]*big.Int{}, ErrInvalidData
}
g2Bytes := g2.Marshal()
g2XI := new(big.Int).SetBytes(g2Bytes[:numBytes])
g2X := new(big.Int).SetBytes(g2Bytes[numBytes : 2*numBytes])
g2YI := new(big.Int).SetBytes(g2Bytes[2*numBytes : 3*numBytes])
g2Y := new(big.Int).SetBytes(g2Bytes[3*numBytes : 4*numBytes])
g2BigInt := [4]*big.Int{g2XI, g2X, g2YI, g2Y}
return g2BigInt, nil
}
// MarshalBigIntSlice returns a byte slice for encoding that we will use to
// check that we hash to the correct value. All of these values are assumed
// to be uint256.
func MarshalBigIntSlice(bigSlice []*big.Int) ([]byte, error) {
n := len(bigSlice)
byteSlice := make([]byte, numBytes*n)
for k := 0; k < n; k++ {
x := bigSlice[k]
tmpBytes, err := MarshalBigInt(x)
if err != nil {
return nil, err
}
for j := 0; j < numBytes; j++ {
byteSlice[k*numBytes+j] = tmpBytes[j]
}
}
return byteSlice, nil
}
// MarshalG1BigSlice creates a byte slice from G1Big slice.
// This is used in testing purposes.
func MarshalG1BigSlice(g1BigSlice [][2]*big.Int) ([]byte, error) {
n := len(g1BigSlice)
byteSlice := make([]byte, 2*numBytes*n)
for k := 0; k < n; k++ {
x := g1BigSlice[k]
tmpBytes, err := MarshalG1Big(x)
if err != nil {
return nil, err
}
for j := 0; j < 2*numBytes; j++ {
byteSlice[k*2*numBytes+j] = tmpBytes[j]
}
}
return byteSlice, nil
} | crypto/bn256/bn256.go | 0.662687 | 0.479138 | bn256.go | starcoder |
package geom
import (
"fmt"
"math"
"strconv"
"strings"
)
var Origin = Vec{0, 0, 0}
// Vec holds x, y, z values.
type Vec struct {
X, Y, Z float64
}
func ArrayToVec(a [3]float64) Vec {
return Vec{a[0], a[1], a[2]}
}
// Scaled multiplies by a scalar
func (a Vec) Scaled(n float64) Vec {
return Vec{a.X * n, a.Y * n, a.Z * n}
}
// By multiplies by a Vector3
func (a Vec) By(b Vec) Vec {
return Vec{a.X * b.X, a.Y * b.Y, a.Z * b.Z}
}
// Plus adds Vector3s together
func (a Vec) Plus(b Vec) Vec {
return Vec{a.X + b.X, a.Y + b.Y, a.Z + b.Z}
}
// Ave returns the average of X, Y, and Z
func (a Vec) Ave() float64 {
return (a.X + a.Y + a.Z) / 3
}
// Max returns the highest of X, Y, and Z
func (a Vec) Greatest() float64 {
return math.Max(a.X, math.Max(a.Y, a.Z))
}
// Dot returns the dot product of two vectors
func (a Vec) Dot(b Vec) float64 {
return a.X*b.X + a.Y*b.Y + a.Z*b.Z
}
// Cross returns the cross product of vectors a and b
func (a Vec) Cross(b Vec) Vec {
return Vec{a.Y*b.Z - a.Z*b.Y, a.Z*b.X - a.X*b.Z, a.X*b.Y - a.Y*b.X}
}
// Minus subtracts another vector from this one
func (a Vec) Minus(b Vec) Vec {
return Vec{a.X - b.X, a.Y - b.Y, a.Z - b.Z}
}
// Len finds the length of the vector
func (a Vec) Len() float64 {
return math.Sqrt(a.X*a.X + a.Y*a.Y + a.Z*a.Z)
}
// Lerp linearly interpolates between two vectors
func (a Vec) Lerp(b Vec, n float64) Vec {
m := 1 - n
return Vec{a.X*m + b.X*n, a.Y*m + b.Y*n, a.Z*m + b.Z*n}
}
// Equals compares two vectors
func (a Vec) Equals(b Vec) bool {
return a.X == b.X && a.Y == b.Y && a.Z == b.Z
}
// Abs converts X, Y, and Z to absolute values
func (a Vec) Abs() Vec {
return Vec{math.Abs(a.X), math.Abs(a.Y), math.Abs(a.Z)}
}
// String returns a string representation of this vector
func (a *Vec) String() string {
if a == nil {
return ""
}
x := strconv.FormatFloat(a.X, 'f', -1, 64)
y := strconv.FormatFloat(a.Y, 'f', -1, 64)
z := strconv.FormatFloat(a.Z, 'f', -1, 64)
return strings.Join([]string{x, y, z}, ",")
}
func (a Vec) Min(b Vec) Vec {
x := math.Min(a.X, b.X)
y := math.Min(a.Y, b.Y)
z := math.Min(a.Z, b.Z)
return Vec{x, y, z}
}
func (a Vec) Max(b Vec) Vec {
x := math.Max(a.X, b.X)
y := math.Max(a.Y, b.Y)
z := math.Max(a.Z, b.Z)
return Vec{x, y, z}
}
func (a Vec) Axis(n int) float64 {
switch n {
case 0:
return a.X
case 1:
return a.Y
default:
return a.Z
}
}
func (a Vec) GreaterEqual(b Vec) bool {
return a.X >= b.X && a.Y >= b.Y && a.Z >= b.Z
}
func (a Vec) LessEqual(b Vec) bool {
return a.X <= b.X && a.Y <= b.Y && a.Z <= b.Z
}
func (a Vec) Array() [3]float64 {
return [3]float64{a.X, a.Y, a.Z}
}
func (a Vec) Projected(d Dir) Vec {
b := Vec(d)
return b.Scaled(a.Dot(b))
}
// Unit normalizes a Vector3 into a Direction.
func (a Vec) Unit() (Dir, bool) {
d := a.Len()
return Dir{a.X / d, a.Y / d, a.Z / d}, d > 0
}
// Set sets the vector from a string value
func (a *Vec) Set(b Vec) {
a.X = b.X
a.Y = b.Y
a.Z = b.Z
}
// UnmarshalText unmarshals a byte slice into a Vector3 value
func (a *Vec) UnmarshalText(b []byte) error {
v, err := ParseVec(string(b))
if err != nil {
return err
}
a.Set(v)
return nil
}
func ParseVec(s string) (v Vec, err error) {
xyz := strings.Split(s, ",")
if len(xyz) != 3 {
return v, fmt.Errorf("pbr: 3 values required for Vector3, received %v", len(xyz))
}
v.X, err = strconv.ParseFloat(xyz[0], 64)
if err != nil {
return v, err
}
v.Y, err = strconv.ParseFloat(xyz[1], 64)
if err != nil {
return v, err
}
v.Z, err = strconv.ParseFloat(xyz[2], 64)
return v, err
} | pkg/geom/vec.go | 0.875095 | 0.690592 | vec.go | starcoder |
package mvt
import (
"log"
"github.com/go-spatial/geom"
)
// PrepareGeo converts the geometry's coordinates to tile pixel coordinates. tile should be the
// extent of the tile, in the same projection as geo. pixelExtent is the dimension of the
// (square) tile in pixels usually 4096, see DefaultExtent.
// This function treats the tile extent elements as left, top, right, bottom. This is fine
// when working with a north-positive projection such as lat/long (epsg:4326)
// and world mercator (epsg:3395), but a south-positive projection (ie. epsg:2054) or west-postive
// projection would then flip the geomtery. To properly render these coordinate systems, simply
// swap the X's or Y's in the tile extent.
func PrepareGeo(geo geom.Geometry, tile *geom.Extent, pixelExtent float64) geom.Geometry {
switch g := geo.(type) {
case geom.Point:
return preparept(g, tile, pixelExtent)
case geom.MultiPoint:
pts := g.Points()
if len(pts) == 0 {
return nil
}
mp := make(geom.MultiPoint, len(pts))
for i, pt := range g {
mp[i] = preparept(pt, tile, pixelExtent)
}
return mp
case geom.LineString:
return preparelinestr(g, tile, pixelExtent)
case geom.MultiLineString:
var ml geom.MultiLineString
for _, l := range g.LineStrings() {
nl := preparelinestr(l, tile, pixelExtent)
if len(nl) > 0 {
ml = append(ml, nl)
}
}
return ml
case geom.Polygon:
return preparePolygon(g, tile, pixelExtent)
case geom.MultiPolygon:
var mp geom.MultiPolygon
for _, p := range g.Polygons() {
np := preparePolygon(p, tile, pixelExtent)
if len(np) > 0 {
mp = append(mp, np)
}
}
return mp
}
return nil
}
func preparept(g geom.Point, tile *geom.Extent, pixelExtent float64) geom.Point {
px := int64((g.X() - tile.MinX()) / tile.XSpan() * pixelExtent)
py := int64((tile.MaxY() - g.Y()) / tile.YSpan() * pixelExtent)
return geom.Point{float64(px), float64(py)}
}
func preparelinestr(g geom.LineString, tile *geom.Extent, pixelExtent float64) (ls geom.LineString) {
pts := g
// If the linestring
if len(pts) < 2 {
// Not enought points to make a line.
return nil
}
ls = make(geom.LineString, len(pts))
for i := 0; i < len(pts); i++ {
ls[i] = preparept(pts[i], tile, pixelExtent)
}
return ls
}
func preparePolygon(g geom.Polygon, tile *geom.Extent, pixelExtent float64) (p geom.Polygon) {
lines := geom.MultiLineString(g.LinearRings())
p = make(geom.Polygon, 0, len(lines))
if len(lines) == 0 {
return p
}
for _, line := range lines.LineStrings() {
ln := preparelinestr(line, tile, pixelExtent)
if len(ln) < 2 {
if debug {
// skip lines that have been reduced to less then 2 points.
log.Println("skipping line 2", line, len(ln))
}
continue
}
// TODO: check the last and first point to make sure
// they are not the same, per the mvt spec
p = append(p, ln)
}
return p
} | vendor/github.com/go-spatial/geom/encoding/mvt/prepare.go | 0.672117 | 0.684646 | prepare.go | starcoder |
package sprite
import (
"golang-games/PuzzleBlock/vec3"
"github.com/veandco/go-sdl2/img"
"github.com/veandco/go-sdl2/sdl"
)
// Sprite is a struct that contains the basic building blocks for game entities
type Sprite struct {
Tex *sdl.Texture
Src *sdl.Rect
Dst *sdl.Rect
Pos vec3.Vector3
Vel vec3.Vector3
W, H int
ScaleX, ScaleY float64
NFrames, NSequences int
CFrame, CSequence int
Drawing bool
AnimSpeed int
Animating bool
AnimTimer float64
}
// NewSprite returns a pointer to a newly created Sprite object
func NewSprite(path string, pos, vel vec3.Vector3, w, h int, scaleX, scaleY float64, nFrames, nSequences, cFrame, cSequence int, drawing bool, animSpeed int, animating bool, renderer *sdl.Renderer) *Sprite {
s := &Sprite{}
image, err := img.Load(path)
if err != nil {
panic(err)
}
texture, err := renderer.CreateTextureFromSurface(image)
if err != nil {
panic(err)
}
s.Tex = texture
s.Pos = pos
s.Vel = vel
s.W = w
s.H = h
s.ScaleX = scaleX
s.ScaleY = scaleY
s.NFrames = nFrames
s.NSequences = nSequences
s.CFrame = cFrame
s.CSequence = cSequence
s.Drawing = drawing
s.AnimSpeed = animSpeed
s.Animating = animating
s.AnimTimer = 0
s.Src = &sdl.Rect{X: 0, Y: 0, W: int32(s.W), H: int32(s.H)}
s.Dst = &sdl.Rect{X: int32(s.Pos.X), Y: int32(s.Pos.Y), W: int32(s.W), H: int32(s.H)}
return s
}
// Update sets the sprite's src and dst rectangles depending on where it is in the animation
func (s *Sprite) Update(time float64) {
if s.Animating == true && s.AnimSpeed > 0 {
s.AnimTimer += time
if s.AnimTimer >= float64(s.AnimSpeed) {
s.CFrame++
s.CFrame %= s.NFrames
s.AnimTimer = 0
}
}
s.Src.X = int32(s.CFrame * s.W)
s.Src.Y = int32(s.CSequence * s.H)
s.Src.W = int32(s.W)
s.Src.H = int32(s.H)
s.Pos.X += s.Vel.X
s.Pos.Y += s.Vel.Y
s.Pos.Z += s.Vel.Z
s.Dst.X = int32(s.Pos.X)
s.Dst.Y = int32(s.Pos.Y)
s.Dst.W = int32(float64(s.W) * s.ScaleX)
s.Dst.H = int32(float64(s.H) * s.ScaleY)
}
// SetColor sets the color values of a sprite
func (s *Sprite) SetColor(c sdl.Color) {
s.Tex.SetColorMod(c.R, c.G, c.B)
}
// SetAlpha sets the alpha value of a sprite
func (s *Sprite) SetAlpha(c sdl.Color) {
s.Tex.SetAlphaMod(c.A)
}
// SetColorAndAlpha sets the color and alpha values of a sprite
func (s *Sprite) SetColorAndAlpha(c sdl.Color) {
s.Tex.SetColorMod(c.R, c.G, c.B)
s.Tex.SetAlphaMod(c.A)
}
// Draw instructs the renderer to copy the sprite to the renderer buffer
func (s *Sprite) Draw(renderer *sdl.Renderer) {
if s.Drawing == true {
renderer.Copy(s.Tex, s.Src, s.Dst)
}
} | PuzzleBlock/sprite/sprite.go | 0.733261 | 0.401629 | sprite.go | starcoder |
package safe
import "math"
type Int struct{}
func (i Int) Add(x, y int) (int, bool) {
r := x + y
// Overflow if both arguments have the opposite sign of the result
if ((x ^ r) & (y ^ r)) < 0 {
return r, false
}
return r, true
}
func (i Int) Subtract(x, y int) (int, bool) {
r := x - y
// Overflow iff the arguments have different signs and
// the sign of the result is different than the sign of x
if ((x ^ y) & (x ^ r)) < 0 {
return r, false
}
return r, true
}
func (i Int) Muliply(x, y int) (int, bool) {
r := x * y
ax := abs(int64(x))
ay := abs(int64(y))
if (ax|ay)>>31 != 0 {
// Some bits greater than 2^31 that might cause overflow
// Check the result using the divide operator
// and check for the special case of Long.MIN_VALUE * -1
if ((y != 0) && (r/y != x)) ||
(x == math.MinInt64 && y == -1) {
return r, false
}
}
return r, true
}
func (i Int) Increment(v int) (int, bool) {
r := v + 1
if r < v {
return r, false
}
return r, true
}
func (i Int) Deccrement(v int) (int, bool) {
r := v - 1
if r > v {
return r, false
}
return r, true
}
func (i Int) Negate(v int) (int, bool) {
r := -v
if v == math.MinInt64 || -int64(v) != int64(r) {
return r, false
}
return r, true
}
type Int32 struct{}
func (i Int32) Add(x, y int32) (int32, bool) {
r := x + y
// Overflow if both arguments have the opposite sign of the result
if ((x ^ r) & (y ^ r)) < 0 {
return r, false
}
return r, true
}
func (i Int32) Subtract(x, y int32) (int32, bool) {
r := x - y
// Overflow iff the arguments have different signs and
// the sign of the result is different than the sign of x
if ((x ^ y) & (x ^ r)) < 0 {
return r, false
}
return r, true
}
func (i Int32) Muliply(x, y int32) (int32, bool) {
r := int64(x) * int64(y)
if int64(int32(r)) != r {
return int32(r), false
}
return int32(r), true
}
func (i Int32) Increment(v int32) (int32, bool) {
r := v + 1
if r < v {
return r, false
}
return r, true
}
func (i Int32) Deccrement(v int32) (int32, bool) {
r := v - 1
if r > v {
return r, false
}
return r, true
}
func (i Int32) Negate(v int32) (int32, bool) {
r := -v
if v == math.MinInt32 {
return r, false
}
return r, true
}
type Int64 struct{}
func (i Int64) Add(x, y int64) (int64, bool) {
r := x + y
// Overflow if both arguments have the opposite sign of the result
if ((x ^ r) & (y ^ r)) < 0 {
return r, false
}
return r, true
}
func (i Int64) Subtract(x, y int64) (int64, bool) {
r := x - y
// Overflow iff the arguments have different signs and
// the sign of the result is different than the sign of x
if ((x ^ y) & (x ^ r)) < 0 {
return r, false
}
return r, true
}
func (i Int64) Muliply(x, y int64) (int64, bool) {
r := x * y
ax := abs(x)
ay := abs(y)
if (ax|ay)>>31 != 0 {
// Some bits greater than 2^31 that might cause overflow
// Check the result using the divide operator
// and check for the special case of Long.MIN_VALUE * -1
if ((y != 0) && (r/y != x)) ||
(x == math.MinInt64 && y == -1) {
return r, false
}
}
return r, true
}
func (i Int64) Increment(v int64) (int64, bool) {
r := v + 1
if r < v {
return r, false
}
return r, true
}
func (i Int64) Deccrement(v int64) (int64, bool) {
r := v - 1
if r > v {
return r, false
}
return r, true
}
func (i Int64) Negate(v int64) (int64, bool) {
r := -v
if v == math.MinInt64 {
return r, false
}
return r, true
}
type Int16 struct{}
func (i Int16) Add(x, y int16) (int16, bool) {
r := x + y
// Overflow if both arguments have the opposite sign of the result
if ((x ^ r) & (y ^ r)) < 0 {
return r, false
}
return r, true
}
func (i Int16) Subtract(x, y int16) (int16, bool) {
r := x - y
// Overflow iff the arguments have different signs and
// the sign of the result is different than the sign of x
if ((x ^ y) & (x ^ r)) < 0 {
return r, false
}
return r, true
}
func (i Int16) Muliply(x, y int16) (int16, bool) {
r := int64(x) * int64(y)
if int64(int16(r)) != r {
return int16(r), false
}
return int16(r), true
}
func (i Int16) Increment(v int16) (int16, bool) {
r := v + 1
if r < v {
return r, false
}
return r, true
}
func (i Int16) Deccrement(v int16) (int16, bool) {
r := v - 1
if r > v {
return r, false
}
return r, true
}
func (i Int16) Negate(v int16) (int16, bool) {
r := -v
if v == math.MinInt16 {
return r, false
}
return r, true
}
type Int8 struct{}
func (i Int8) Add(x, y int8) (int8, bool) {
r := x + y
// Overflow if both arguments have the opposite sign of the result
if ((x ^ r) & (y ^ r)) < 0 {
return r, false
}
return r, true
}
func (i Int8) Subtract(x, y int8) (int8, bool) {
r := x - y
// Overflow iff the arguments have different signs and
// the sign of the result is different than the sign of x
if ((x ^ y) & (x ^ r)) < 0 {
return r, false
}
return r, true
}
func (i Int8) Muliply(x, y int8) (int8, bool) {
r := int64(x) * int64(y)
if int64(int8(r)) != r {
return int8(r), false
}
return int8(r), true
}
func (i Int8) Increment(v int8) (int8, bool) {
r := v + 1
if r < v {
return r, false
}
return r, true
}
func (i Int8) Deccrement(v int8) (int8, bool) {
r := v - 1
if r > v {
return r, false
}
return r, true
}
func (i Int8) Negate(v int8) (int8, bool) {
r := -v
if v == math.MinInt8 {
return r, false
}
return r, true
}
type Byte struct{}
func (i Byte) Add(x, y byte) (byte, bool) {
r := x + y
ir := int(x) + int(y)
// Overflow if both arguments have the opposite sign of the result
if int(r) != ir {
return r, false
}
return r, true
}
func (i Byte) Subtract(x, y byte) (byte, bool) {
r := x - y
ir := int(x) - int(y)
// Overflow iff the arguments have different signs and
// the sign of the result is different than the sign of x
if int(r) != ir {
return r, false
}
return r, true
}
func (i Byte) Muliply(x, y byte) (byte, bool) {
r := int64(x) * int64(y)
if int64(byte(r)) != r {
return byte(r), false
}
return byte(r), true
}
func (i Byte) Increment(v byte) (byte, bool) {
r := v + 1
if r < v {
return r, false
}
return r, true
}
func (i Byte) Deccrement(v int) (int, bool) {
r := v - 1
if r > v {
return r, false
}
return r, true
}
func abs(x int64) int64 {
if x < 0 {
return -x
}
return x
} | safe.go | 0.732783 | 0.509398 | safe.go | starcoder |
package metrics
// Recall measures the fraction of times a true class was predicted.
type Recall struct {
Class float64
}
// Apply Recall.
func (recall Recall) Apply(yTrue, yPred, weights []float64) (float64, error) {
var cm, err = MakeConfusionMatrix(yTrue, yPred, weights)
if err != nil {
return 0, err
}
var (
TP = cm.TruePositives(recall.Class)
FN = cm.FalseNegatives(recall.Class)
)
// If the class has never been predicted return 0
if TP+FN == 0 {
return 0, nil
}
return TP / (TP + FN), nil
}
// Classification method of Recall.
func (recall Recall) Classification() bool {
return true
}
// BiggerIsBetter method of Recall.
func (recall Recall) BiggerIsBetter() bool {
return true
}
// NeedsProbabilities method of Recall.
func (recall Recall) NeedsProbabilities() bool {
return false
}
// String method of Recall.
func (recall Recall) String() string {
return "recall"
}
// MicroRecall measures the global recall by using the total true positives and
// false negatives.
type MicroRecall struct{}
// Apply MicroRecall.
func (recall MicroRecall) Apply(yTrue, yPred, weights []float64) (float64, error) {
var cm, err = MakeConfusionMatrix(yTrue, yPred, weights)
if err != nil {
return 0, err
}
var (
TP float64
FN float64
)
for _, class := range cm.Classes() {
TP += cm.TruePositives(class)
FN += cm.FalsePositives(class)
}
return TP / (TP + FN), nil
}
// Classification method of MicroRecall.
func (recall MicroRecall) Classification() bool {
return true
}
// BiggerIsBetter method of MicroRecall.
func (recall MicroRecall) BiggerIsBetter() bool {
return true
}
// NeedsProbabilities method of MicroRecall.
func (recall MicroRecall) NeedsProbabilities() bool {
return false
}
// String method of MicroRecall.
func (recall MicroRecall) String() string {
return "micro_recall"
}
// MacroRecall measures the unweighted average recall across all classes.
// This does not take class imbalance into account.
type MacroRecall struct{}
// Apply MacroRecall.
func (recall MacroRecall) Apply(yTrue, yPred, weights []float64) (float64, error) {
var cm, err = MakeConfusionMatrix(yTrue, yPred, weights)
if err != nil {
return 0, err
}
var sum float64
for _, class := range cm.Classes() {
var recall, _ = Recall{Class: class}.Apply(yTrue, yPred, weights)
sum += recall
}
return sum / float64(cm.NClasses()), nil
}
// Classification method of MacroRecall.
func (recall MacroRecall) Classification() bool {
return true
}
// BiggerIsBetter method of MacroRecall.
func (recall MacroRecall) BiggerIsBetter() bool {
return true
}
// NeedsProbabilities method of MacroRecall.
func (recall MacroRecall) NeedsProbabilities() bool {
return false
}
// String method of MacroRecall.
func (recall MacroRecall) String() string {
return "macro_recall"
}
// WeightedRecall measures the weighted average recall across all classes.
// This does take class imbalance into account.
type WeightedRecall struct{}
// Apply WeightedRecall.
func (recall WeightedRecall) Apply(yTrue, yPred, weights []float64) (float64, error) {
var cm, err = MakeConfusionMatrix(yTrue, yPred, weights)
if err != nil {
return 0, err
}
var (
sum float64
n float64
)
for _, class := range cm.Classes() {
var (
recall, _ = Recall{Class: class}.Apply(yTrue, yPred, weights)
TP = cm.TruePositives(class)
FN = cm.FalseNegatives(class)
)
sum += (TP + FN) * recall
n += (TP + FN)
}
return sum / n, nil
}
// Classification method of WeightedRecall.
func (recall WeightedRecall) Classification() bool {
return true
}
// BiggerIsBetter method of WeightedRecall.
func (recall WeightedRecall) BiggerIsBetter() bool {
return true
}
// NeedsProbabilities method of WeightedRecall.
func (recall WeightedRecall) NeedsProbabilities() bool {
return false
}
// String method of WeightedRecall.
func (recall WeightedRecall) String() string {
return "weighted_recall"
} | metrics/recall.go | 0.935132 | 0.494934 | recall.go | starcoder |
package raycaster
import (
"github.com/mattkimber/gorender/internal/geometry"
"github.com/mattkimber/gorender/internal/manifest"
"math"
)
func getRenderDirection(angle float64, elevationAngle float64) geometry.Vector3 {
x, y, z := -math.Cos(geometry.DegToRad(angle)), math.Sin(geometry.DegToRad(angle)), math.Sin(geometry.DegToRad(elevationAngle))
return geometry.Vector3{X: x, Y: y, Z: z}.Normalise()
}
func getLightingDirection(angle float64, elevation float64, flipY bool) geometry.Vector3 {
x, y, z := -math.Cos(geometry.DegToRad(angle)), math.Sin(geometry.DegToRad(angle)), math.Sin(geometry.DegToRad(elevation))
if flipY {
y = -y
}
return geometry.Zero().Subtract(geometry.Vector3{X: x, Y: y, Z: z}).Normalise()
}
func getViewportPlane(angle float64, m manifest.Manifest, zError float64, size geometry.Point, elevationAngle float64) geometry.Plane {
cos, sin := math.Cos(geometry.DegToRad(angle)), math.Sin(geometry.DegToRad(angle))
midpointX := float64(size.X) / 2.0
if m.PadToFullLength {
midpointX -= ((m.Size.X) - float64(size.X)) / 2.0
}
midpoint := geometry.Vector3{X: midpointX, Y: float64(size.Y) / 2.0, Z: (m.Size.Z - zError) / 2.0}
direction := getRenderDirection(angle, elevationAngle)
viewpoint := midpoint.Add(direction.MultiplyByConstant(m.Size.X))
planeNormalXComponent := math.Abs(((m.Size.X) / 2.0) * cos * math.Sin(geometry.DegToRad(elevationAngle)))
planeNormalYComponent := math.Abs(((m.Size.Y) / 2.0) * sin * math.Sin(geometry.DegToRad(elevationAngle)))
planeNormalZComponent := m.Size.Z / 2.0
constant := planeNormalXComponent + planeNormalYComponent + planeNormalZComponent
constant = constant * (1.0 + zError)
planeNormal := geometry.UnitZ().MultiplyByConstant(constant)
renderNormalXComponent := math.Abs(((m.Size.X) / 2.0) * sin)
renderNormalYComponent := math.Abs(((m.Size.Y) / 2.0) * cos)
renderNormal := getRenderNormal(angle).MultiplyByConstant(renderNormalXComponent + renderNormalYComponent)
a := viewpoint.Subtract(renderNormal).Subtract(planeNormal)
b := viewpoint.Add(renderNormal).Subtract(planeNormal)
c := viewpoint.Add(renderNormal).Add(planeNormal)
d := viewpoint.Subtract(renderNormal).Add(planeNormal)
return geometry.Plane{A: a, B: b, C: c, D: d}
}
func getRenderNormal(angle float64) geometry.Vector3 {
x, y := -math.Cos(geometry.DegToRad(angle)), math.Sin(geometry.DegToRad(angle))
return geometry.Vector3{X: y, Y: -x}.Normalise()
} | internal/raycaster/setup.go | 0.887516 | 0.791741 | setup.go | starcoder |
package shapes
import (
"github.com/eriklupander/pathtracer/internal/app/geom"
"github.com/eriklupander/pathtracer/internal/app/material"
"math"
"math/rand"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func NewSphere() *Sphere {
return &Sphere{
Basic: Basic{
Id: rand.Int63(),
Transform: geom.New4x4(),
Inverse: geom.New4x4(),
InverseTranspose: geom.New4x4(),
Material: material.Material{
Color: geom.Tuple4{1, .5, .5},
Emission: geom.Tuple4{0, 0, 0},
RefractiveIndex: 1,
},
},
savedVec: geom.NewVector(0, 0, 0),
savedNormal: geom.NewVector(0, 0, 0),
savedRay: geom.NewRay(geom.NewPoint(0, 0, 0), geom.NewVector(0, 0, 0)),
xsCache: make([]Intersection, 2),
//xsEmpty: make([]Intersection, 0),
originPoint: geom.NewPoint(0, 0, 0),
CastShadow: true,
}
}
type Sphere struct {
Basic
parent Shape
savedRay geom.Ray
// cached stuff
originPoint geom.Tuple4
savedVec geom.Tuple4
xsCache []Intersection
xsEmpty []Intersection
savedNormal geom.Tuple4
CastShadow bool
}
func (s *Sphere) ID() int64 {
return s.Id
}
func (s *Sphere) CastsShadow() bool {
return s.CastShadow
}
func (s *Sphere) GetParent() Shape {
return s.parent
}
func (s *Sphere) NormalAtLocal(point geom.Tuple4, intersection *Intersection) geom.Tuple4 {
geom.SubPtr(point, s.originPoint, &s.savedNormal)
return s.savedNormal
}
func (s *Sphere) GetLocalRay() geom.Ray {
return s.savedRay
}
// IntersectLocal implements Sphere-ray intersection
func (s *Sphere) IntersectLocal(ray geom.Ray, xs *Intersections) {
s.savedRay = ray
//s.XsCache = s.XsCache[:0]
// this is a vector from the origin of the ray to the center of the sphere at 0,0,0
//SubPtr(r.Origin, s.originPoint, &s.savedVec)
// Note that doing the Subtraction inlined was much faster than letting SubPtr do it.
// Shouldn't the SubPtr be inlined by the compiler? Need to figure out what's going on here...
for i := 0; i < 4; i++ {
s.savedVec[i] = ray.Origin[i] - s.originPoint[i]
}
// This dot product is
a := geom.Dot(ray.Direction, ray.Direction)
// Take the dot of the direction and the vector from ray origin to sphere center times 2
b := 2.0 * geom.Dot(ray.Direction, s.savedVec)
// Take the dot of the two sphereToRay vectors and decrease by 1 (is that because the sphere is unit length 1?
c := geom.Dot(s.savedVec, s.savedVec) - 1.0
// calculate the discriminant
discriminant := (b * b) - 4*a*c
if discriminant < 0.0 {
return // s.xsEmpty
}
// finally, find the intersection distances on our ray. Some values:
t1 := (-b - math.Sqrt(discriminant)) / (2 * a)
t2 := (-b + math.Sqrt(discriminant)) / (2 * a)
s.xsCache[0].T = t1
s.xsCache[1].T = t2
s.xsCache[0].S = s
s.xsCache[1].S = s
*xs = append(*xs, s.xsCache[0], s.xsCache[1])
}
func (s *Sphere) GetTransform() geom.Mat4x4 {
return s.Transform
}
func (s *Sphere) GetInverse() geom.Mat4x4 {
return s.Inverse
}
func (s *Sphere) GetInverseTranspose() geom.Mat4x4 {
return s.InverseTranspose
}
func (s *Sphere) GetMaterial() material.Material {
return s.Material
}
// SetTransform passes a pointer to the Sphere on which to apply the translation matrix
func (s *Sphere) SetTransform(translation geom.Mat4x4) {
s.Transform = geom.Multiply(s.Transform, translation)
s.Inverse = geom.Inverse(s.Transform)
s.InverseTranspose = geom.Transpose(s.Inverse)
}
// SetMaterial passes a pointer to the Sphere on which to set the material
func (s *Sphere) SetMaterial(m material.Material) {
s.Material = m
}
func (s *Sphere) SetParent(shape Shape) {
s.parent = shape
} | internal/app/shapes/sphere.go | 0.788298 | 0.485112 | sphere.go | starcoder |
package vec
import (
"errors"
"math"
)
// Length returns the length of u-v.
func Length(u, v I2) float64 {
v = v.Sub(u)
return math.Sqrt(float64(v.Dot(v)))
}
// Edge describes an edge between two I2 vertices.
type Edge struct {
U, V I2
}
// Length is the length of the edge.
func (e Edge) Length() float64 {
v := e.V.Sub(e.U)
return math.Sqrt(float64(v.Dot(v)))
}
// Reverse is the edge flipped (V->U).
func (e Edge) Reverse() Edge {
return Edge{e.V, e.U}
}
// VertexSet is a set of vertices.
type VertexSet map[I2]bool
// Graph is an adjacency-set implementation of a graph.
type Graph struct {
V VertexSet // vertices
E map[I2]VertexSet // edges; E[u] = {v: u-v is an edge}
}
// NewGraph creates a new empty *Graph.
func NewGraph() *Graph { return &Graph{} }
// AddEdge adds the edge u-v to the graph.
func (g *Graph) AddEdge(u, v I2) {
if g.V == nil {
g.V = make(VertexSet)
}
if g.E == nil {
g.E = make(map[I2]VertexSet)
}
g.V[u] = true
g.V[v] = true
if g.E[u] == nil {
g.E[u] = make(VertexSet)
}
g.E[u][v] = true
}
// AllEdges runs a function for every edge.
func (g *Graph) AllEdges(f func(I2, I2) bool) bool {
for u, l := range g.E {
for v, y := range l {
if !y {
continue
}
if !f(u, v) {
return false
}
}
}
return true
}
// AllEdgesFacing calls f for every edge that is somewhat facing p.
func (g *Graph) AllEdgesFacing(p I2, f func(I2, I2) bool) bool {
return g.AllEdges(func(u, v I2) bool {
if SignedArea2(p, u, v) > 0 {
return f(u, v)
}
return true
})
}
// Edges returns all the edges as a slice.
func (g *Graph) Edges() (edges []Edge) {
g.AllEdges(func(u, v I2) bool {
edges = append(edges, Edge{u, v})
return true
})
return
}
// NumEdges counts the number of edges.
func (g *Graph) NumEdges() (n int) {
for _, l := range g.E {
n += len(l)
}
return
}
// Blocks determines if the graph intersects the straight line segment start-end.
// Only edges facing start are considered.
func (g *Graph) Blocks(start, end I2) bool {
return !g.AllEdgesFacing(start, func(u, v I2) bool {
_, y := SegmentIntersectI(u, v, start, end)
return !y
})
}
// FullyBlocks determines if the graph intersects the straight line segment
// start-end, including back-facing edges.
func (g *Graph) FullyBlocks(start, end I2) bool {
return !g.AllEdges(func(u, v I2) bool {
_, y := SegmentIntersectI(u, v, start, end)
return !y
})
}
// NearestBlock returns the intersection with the graph nearest to start.
func (g *Graph) NearestBlock(start, end I2) (I2, bool) {
found := false
min := math.Inf(1)
var pos I2
g.AllEdgesFacing(start, func(u, v I2) bool {
p, y := SegmentIntersectI(u, v, start, end)
if !y {
return true
}
if t := Length(start, p); t < min {
min = t
pos = p
found = true
}
return true
})
return pos, found
}
// NearestPoint finds the edge, and closest point along that edge, to the query point.
func (g *Graph) NearestPoint(p I2) (e Edge, q I2) {
d := int64(1<<63 - 1)
g.AllEdges(func(u, v I2) bool {
if r, t := SegmentNearestPoint(u, v, p); t < d {
d = t
e = Edge{u, v}
q = r
}
return true
})
return
}
// FindPath finds a path from start to end, even if start and end are not vertices.
// The path will only use vertices contained in the limits Rect.
func FindPath(obstacles, paths *Graph, start, end I2, limits Rect) ([]I2, error) {
// Is there a straight-line path?
if !obstacles.Blocks(start, end) {
return []I2{end}, nil
}
// Which vertices are start and end linked to?
// Lengths to the vertices visible from start are optimal, because
// the space is Euclidean.
dists := make(map[I2]float64)
prev := make(map[I2]I2)
endN := make(VertexSet)
q := VertexSet{end: true}
for v, y := range paths.V {
if !y || !limits.Contains(v) {
continue
}
q[v] = true
dists[v] = math.Inf(1)
if !obstacles.Blocks(start, v) {
dists[v] = Length(start, v)
prev[v] = start
}
if !obstacles.Blocks(v, end) {
endN[v] = true
}
}
if len(prev) == 0 || len(endN) == 0 {
return nil, errors.New("no paths possible")
}
// Dijkstra time.
dists[start] = 0
dists[end] = math.Inf(1)
relax := func(u, v I2) {
if !q[v] {
return
}
if t := Length(u, v) + dists[u]; t < dists[v] {
dists[v] = t
prev[v] = u
}
}
for len(q) > 0 {
dist := math.Inf(1)
var u I2
for v := range q {
if dists[v] < dist {
dist = dists[v]
u = v
}
}
if u == end || math.IsInf(dist, 1) {
break
}
delete(q, u)
for v := range paths.E[u] {
relax(u, v)
}
for v := range endN {
relax(v, end)
}
}
if _, ok := prev[end]; !ok {
return nil, errors.New("no path")
}
// Traverse the optimal path and then put it in the right order.
v := end
var path []I2
for v != start {
path = append(path, v)
v = prev[v]
}
for i := 0; i < len(path)/2; i++ {
path[i], path[len(path)-1-i] = path[len(path)-1-i], path[i]
}
return path, nil
} | graph.go | 0.830628 | 0.553807 | graph.go | starcoder |
package apimodel
import (
"github.com/alexandre-normand/glukit/app/util"
"time"
)
const (
INSULIN_TAG = "Insulin"
)
// Injection represents an insulin injection
type Injection struct {
Time Time `json:"time" datastore:"time,noindex"`
Units float32 `json:"units" datastore:"units,noindex"`
InsulinName string `json:"insulinName" datastore:"insulinName,noindex"`
InsulinType string `json:"insulinType" datastore:"insulinType,noindex"`
}
// This holds an array of injections for a whole day
type DayOfInjections struct {
Injections []Injection `datastore:"injections,noindex"`
StartTime time.Time `datastore:"startTime"`
EndTime time.Time `datastore:"endTime"`
}
func NewDayOfInjections(injections []Injection) DayOfInjections {
return DayOfInjections{injections, injections[0].GetTime().Truncate(DAY_OF_DATA_DURATION), injections[len(injections)-1].GetTime()}
}
// GetTime gets the time of a Timestamp value
func (element Injection) GetTime() time.Time {
return element.Time.GetTime()
}
type InjectionSlice []Injection
func (slice InjectionSlice) Len() int {
return len(slice)
}
func (slice InjectionSlice) Less(i, j int) bool {
return slice[i].Time.Timestamp < slice[j].Time.Timestamp
}
func (slice InjectionSlice) Swap(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
}
func (slice InjectionSlice) GetEpochTime(i int) (epochTime int64) {
return slice[i].Time.Timestamp / 1000
}
// ToDataPointSlice converts an InjectionSlice into a generic DataPoint array
func (slice InjectionSlice) ToDataPointSlice(matchingReads []GlucoseRead, glucoseUnit GlucoseUnit) (dataPoints []DataPoint) {
dataPoints = make([]DataPoint, len(slice))
for i := range slice {
localTime, err := slice[i].Time.Format()
if err != nil {
util.Propagate(err)
}
dataPoint := DataPoint{localTime, slice.GetEpochTime(i),
linearInterpolateY(matchingReads, slice[i].Time, glucoseUnit), slice[i].Units, INSULIN_TAG, "units"}
dataPoints[i] = dataPoint
}
return dataPoints
} | app/apimodel/injection.go | 0.753104 | 0.459197 | injection.go | starcoder |
package dsc
import (
"database/sql"
"reflect"
"time"
)
//Scanner represents a datastore data scanner. This abstraction provides the ability to convert and assign datastore record of data to provided destination
type Scanner interface {
//Returns all columns specified in select statement.
Columns() ([]string, error)
//ColumnTypes return column types
ColumnTypes() ([]ColumnType, error)
//Scans datastore record data to convert and assign it to provided destinations, a destination needs to be pointer.
Scan(dest ...interface{}) error
}
//ColumnValueProvider provides column values
type ColumnValueProvider interface {
ColumnValues() ([]interface{}, error)
}
//RecordMapper represents a datastore record mapper, it is responsible for mapping data record into application abstraction.
type RecordMapper interface {
//Maps data record by passing to the scanner references to the application abstraction
Map(scanner Scanner) (interface{}, error)
}
//ParametrizedSQL represents a parmetrized SQL with its binding values, in order of occurrence.
type ParametrizedSQL struct {
SQL string //Sql
Values []interface{} //binding parameter values
Type int
}
//DmlProvider represents dml generator, which is responsible for providing parametrized sql, it takes operation type:
//SqlTypeInsert = 0
//SqlTypeUpdate = 1
//SqlTypeDelete = 2
// and instance to the application abstraction
type DmlProvider interface {
Get(operationType int, instance interface{}) *ParametrizedSQL
KeySetter
KeyGetter
}
//Manager represents datastore manager.
type Manager interface {
Config() *Config
//ConnectionProvider returns connection provider
ConnectionProvider() ConnectionProvider
//Execute executes provided sql, with the arguments, '?' is used as placeholder for and arguments
Execute(sql string, parameters ...interface{}) (sql.Result, error)
//ExecuteAll executes all provided sql
ExecuteAll(sqls []string) ([]sql.Result, error)
//ExecuteOnConnection executes sql on passed in connection, this allowes to maintain transaction if supported
ExecuteOnConnection(connection Connection, sql string, parameters []interface{}) (sql.Result, error)
//ExecuteAllOnConnection executes all sql on passed in connection, this allowes to maintain transaction if supported
ExecuteAllOnConnection(connection Connection, sqls []string) ([]sql.Result, error)
//ReadSingle fetches a single record of data, it takes pointer to the result, sql query, binding parameters, record to application instance mapper
ReadSingle(resultPointer interface{}, query string, parameters []interface{}, mapper RecordMapper) (success bool, err error)
//ReadSingleOnConnection fetches a single record of data on connection, it takes connection, pointer to the result, sql query, binding parameters, record to application instance mapper
ReadSingleOnConnection(connection Connection, resultPointer interface{}, query string, parameters []interface{}, mapper RecordMapper) (success bool, err error)
//ReadAll reads all records, it takes pointer to the result slice , sql query, binding parameters, record to application instance mapper
ReadAll(resultSlicePointer interface{}, query string, parameters []interface{}, mapper RecordMapper) error
//ReadAllOnConnection reads all records, it takes connection, pointer to the result slice , sql query, binding parameters, record to application instance mapper
ReadAllOnConnection(connection Connection, resultSlicePointer interface{}, query string, parameters []interface{}, mapper RecordMapper) error
//ReadAllWithHandler reads data for passed in query and parameters, for each row reading handler will be called, to continue reading next row it needs to return true
ReadAllWithHandler(query string, parameters []interface{}, readingHandler func(scanner Scanner) (toContinue bool, err error)) error
//ReadAllOnWithHandlerOnConnection reads data for passed in query and parameters, on connection, for each row reading handler will be called, to continue reading next row, it needs to return true
ReadAllOnWithHandlerOnConnection(connection Connection, query string, parameters []interface{}, readingHandler func(scanner Scanner) (toContinue bool, err error)) error
//ReadAllOnWithHandlerOnConnection persists all passed in data to the table, it uses dml provider to generate DML for each row.
PersistAll(slicePointer interface{}, table string, provider DmlProvider) (inserted int, updated int, err error)
//PersistAllOnConnection persists all passed in data on connection to the table, it uses dml provider to generate DML for each row.
PersistAllOnConnection(connection Connection, dataPointer interface{}, table string, provider DmlProvider) (inserted int, updated int, err error)
//PersistSingle persists single row into table, it uses dml provider to generate DML to the row.
PersistSingle(dataPointer interface{}, table string, provider DmlProvider) (inserted int, updated int, err error)
//PersistSingleOnConnection persists single row on connection into table, it uses dml provider to generate DML to the row.
PersistSingleOnConnection(connection Connection, dataPointer interface{}, table string, provider DmlProvider) (inserted int, updated int, err error)
//connection persists all all row of data to passed in table, it uses key setter to optionally set back autoincrement value, and func to generate parametrized sql for the row.
PersistData(connection Connection, data interface{}, table string, keySetter KeySetter, sqlProvider func(item interface{}) *ParametrizedSQL) (int, error)
//DeleteAll deletes all record for passed in slice pointer from table, it uses key provider to take id/key for the record.
DeleteAll(slicePointer interface{}, table string, keyProvider KeyGetter) (deleted int, err error)
//DeleteAllOnConnection deletes all record on connection for passed in slice pointer from table, it uses key provider to take id/key for the record.
DeleteAllOnConnection(connection Connection, resultPointer interface{}, table string, keyProvider KeyGetter) (deleted int, err error)
//DeleteSingle deletes single row of data from table, it uses key provider to take id/key for the record.
DeleteSingle(resultPointer interface{}, table string, keyProvider KeyGetter) (success bool, err error)
//DeleteSingleOnConnection deletes single row of data on connection from table, it uses key provider to take id/key for the record.
DeleteSingleOnConnection(connection Connection, resultPointer interface{}, table string, keyProvider KeyGetter) (success bool, err error)
//ClassifyDataAsInsertableOrUpdatable classifies records are inserable and what are updatable.
ClassifyDataAsInsertableOrUpdatable(connection Connection, slicePointer interface{}, table string, provider DmlProvider) (insertables, updatables []interface{}, err error)
//TableDescriptorRegistry returns Table Descriptor Registry
TableDescriptorRegistry() TableDescriptorRegistry
}
//DatastoreDialect represents datastore dialects.
type DatastoreDialect interface {
GetDatastores(manager Manager) ([]string, error)
GetTables(manager Manager, datastore string) ([]string, error)
DropTable(manager Manager, datastore string, table string) error
CreateTable(manager Manager, datastore string, table string, specification interface{}) error
CanCreateDatastore(manager Manager) bool
CreateDatastore(manager Manager, datastore string) error
CanDropDatastore(manager Manager) bool
DropDatastore(manager Manager, datastore string) error
GetCurrentDatastore(manager Manager) (string, error)
//GetSequence returns a sequence number
GetSequence(manager Manager, name string) (int64, error)
//GetKeyName returns a name of TableColumn name that is a key, or coma separated list if complex key
GetKeyName(manager Manager, datastore, table string) string
//GetColumns returns TableColumn info
GetColumns(manager Manager, datastore, table string) ([]Column, error)
//IsAutoincrement returns true if autoicrement
IsAutoincrement(manager Manager, datastore, table string) bool
//Flag if data store can batch batch
CanPersistBatch() bool
//BulkInsert type
BulkInsertType() string
//DisableForeignKeyCheck disables fk check
DisableForeignKeyCheck(manager Manager, connection Connection) error
//EnableForeignKeyCheck disables fk check
EnableForeignKeyCheck(manager Manager, connection Connection) error
//IsKeyCheckSwitchSessionLevel returns true if key check is controlled on connection level (as opposed to globally on table level)
IsKeyCheckSwitchSessionLevel() bool
//Normalizes sql i.e for placeholders: dsc uses '?' for placeholder if some dialect use difference this method should take care of it
NormalizeSQL(SQL string) string
//EachTable iterate all current connection manager datastore tables
EachTable(manager Manager, handler func(table string) error) error
//ShowCreateTable returns DDL showing create table statement or error
ShowCreateTable(manager Manager, table string) (string, error)
//Init initializes connection
Init(manager Manager, connection Connection) error
//CanHandleTransaction returns true if driver can handle transaction
CanHandleTransaction() bool
//Checks if database is online
Ping(manager Manager) error
}
type ColumnType interface {
// Length returns the TableColumn type length for variable length TableColumn types such
// as text and binary field types. If the type length is unbounded the value will
// be math.MaxInt64 (any database limits will still apply).
// If the TableColumn type is not variable length, such as an int, or if not supported
// by the driver ok is false.
Length() (length int64, ok bool)
// DecimalSize returns the scale and precision of a decimal type.
// If not applicable or if not supported ok is false.
DecimalSize() (precision, scale int64, ok bool)
// ScanType returns a Go type suitable for scanning into using Rows.Scan.
// If a driver does not support this property ScanType will return
// the type of an empty interface.
ScanType() reflect.Type
// Nullable returns whether the TableColumn may be null.
// If a driver does not support this property ok will be false.
Nullable() (nullable, ok bool)
// DatabaseTypeName returns the database system name of the TableColumn type. If an empty
// string is returned the driver type name is not supported.
// Consult your driver documentation for a list of driver data types. Length specifiers
// are not included.
// Common type include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", "INT", "BIGINT".
DatabaseTypeName() string
}
//Column represents TableColumn type interface (compabible with *sql.ColumnType
type Column interface {
ColumnType
// Name returns the name or alias of the TableColumn.
Name() string
}
//TransactionManager represents a transaction manager.
type TransactionManager interface {
Begin() error
Commit() error
Rollback() error
}
//Connection represents a datastore connection
type Connection interface {
Config() *Config
ConnectionPool() chan Connection
//Close closes connection or it returns it back to the pool
Close() error
CloseNow() error //closes connecition, it does not return it back to the pool
Unwrap(target interface{}) interface{}
LastUsed() *time.Time
SetLastUsed(ts *time.Time)
TransactionManager
}
//ConnectionProvider represents a datastore connection provider.
type ConnectionProvider interface {
Get() (Connection, error)
Config() *Config
ConnectionPool() chan Connection
SpawnConnectionIfNeeded()
NewConnection() (Connection, error)
Close() error
}
//ManagerFactory represents a manager factory.
type ManagerFactory interface {
//Creates manager, takes config pointer.
Create(config *Config) (Manager, error)
//Creates manager from url, can url needs to point to Config JSON.
CreateFromURL(url string) (Manager, error)
}
//ManagerRegistry represents a manager registry.
type ManagerRegistry interface {
Get(name string) Manager
Register(name string, manager Manager)
}
//KeySetter represents id/key mutator.
type KeySetter interface {
//SetKey sets autoincrement/sql value to the application domain instance.
SetKey(instance interface{}, seq int64)
}
//KeyGetter represents id/key accessor.
type KeyGetter interface {
//Key returns key/id for the the application domain instance.
Key(instance interface{}) []interface{}
} | api.go | 0.615897 | 0.47591 | api.go | starcoder |
package si5351
// OutputIndex indicates one of the output clocks.
type OutputIndex int
// The output clocks.
const (
Clk0 OutputIndex = iota
Clk1
Clk2
Clk3
Clk4
Clk5
Clk6
Clk7
)
// Output describes the properties common to all of the Si5351's output clocks.
type Output struct {
Register OutputRegister
PowerDown bool
IntegerMode bool
Invert bool
PLL PLLIndex
InputSource ClockInputSource
Drive OutputDrive
bus Bus
}
// FractionalOutput represents an output that has a fractional frequency divider (CLK0-CLK5).
// Those outputs can also have a phase shift.
type FractionalOutput struct {
Output
FrequencyDivider FractionalRatio
PhaseShift uint8
}
// IntegerOutput represents an output that has an integer frequency divider (CLK6-CLK7).
type IntegerOutput struct {
Output
FrequencyDivider uint8
RDiv ClockDivider
}
// ClockInputSource describes the input source of an output clock.
type ClockInputSource uint8
// All possible input sources for an output clock.
const (
ClockInputCrystal ClockInputSource = iota
ClockInputClkin
ClockInputReserved
ClockInputMultisynth
)
// OutputDrive describes the drive strength of an Output.
type OutputDrive uint8
// All possible drive strengthes of an Output.
const (
OutputDrive2mA OutputDrive = iota
OutputDrive4mA
OutputDrive6mA
OutputDrive8mA
)
// OutputDisableState describes the state of an Output when it is disabled.
type OutputDisableState uint8
// All possible states a Clock can have when disabled.
const (
OutputDisableLow OutputDisableState = iota
OutputDisableHigh
OutputDisableHighZ
OutputDisableNever
)
// OutputRegister describes the registers used by a Clock.
type OutputRegister struct {
Control uint8
DisableState uint8
DisableStateOffset uint8
PhaseShift uint8
Divider uint8
DividerOffset uint8
}
// FractionalOutputRegisters contains the register descriptions for all outputs with fractional dividers.
var FractionalOutputRegisters = []OutputRegister{
{RegClk0Control, RegClk3_0DisableState, 0, RegClk0InitialPhaseOffset, RegMultisynth0Parameters, 0},
{RegClk1Control, RegClk3_0DisableState, 2, RegClk1InitialPhaseOffset, RegMultisynth1Parameters, 0},
{RegClk2Control, RegClk3_0DisableState, 4, RegClk2InitialPhaseOffset, RegMultisynth2Parameters, 0},
{RegClk3Control, RegClk3_0DisableState, 6, RegClk3InitialPhaseOffset, RegMultisynth3Parameters, 0},
{RegClk4Control, RegClk7_4DisableState, 0, RegClk4InitialPhaseOffset, RegMultisynth4Parameters, 0},
{RegClk5Control, RegClk7_4DisableState, 2, RegClk5InitialPhaseOffset, RegMultisynth5Parameters, 0},
}
func loadFractionalOutputs(bus Bus) []*FractionalOutput {
result := make([]*FractionalOutput, len(FractionalOutputRegisters))
for i, register := range FractionalOutputRegisters {
result[i] = &FractionalOutput{
Output: Output{
Register: register,
bus: bus,
},
}
}
return result
}
// IntegerOutputRegisters contains the register descriptions for all outputs with integer dividers.
var IntegerOutputRegisters = []OutputRegister{
{RegClk6Control, RegClk7_4DisableState, 4, 0, RegMultisynth6Parameters, 0},
{RegClk7Control, RegClk7_4DisableState, 6, 0, RegMultisynth7Parameters, 4},
}
func loadIntegerOutputs(bus Bus) []*IntegerOutput {
result := make([]*IntegerOutput, len(IntegerOutputRegisters))
for i, register := range IntegerOutputRegisters {
result[i] = &IntegerOutput{
Output: Output{
Register: register,
bus: bus,
},
}
}
return result
}
// SetupControl writes the control register of the Output.
func (o *Output) SetupControl(powerDown bool, integerMode bool, pll PLLIndex, invert bool, inputSource ClockInputSource, drive OutputDrive) error {
value := byte(pll<<5) | byte(inputSource<<2) | byte(drive)
if powerDown {
value |= (1 << 7)
}
if integerMode {
value |= (1 << 6)
}
if invert {
value |= (1 << 4)
}
o.bus.WriteReg(o.Register.Control, value)
if o.bus.Err() == nil {
o.PowerDown = powerDown
o.IntegerMode = integerMode
o.PLL = pll
o.Invert = invert
o.InputSource = inputSource
o.Drive = drive
}
return o.bus.Err()
}
// SetPowerDown sets the power down flag of the Output and writes it to the output's control register.
func (o *Output) SetPowerDown(powerDown bool) error {
value := byte(o.PLL<<5) | byte(o.InputSource<<2) | byte(o.Drive)
if powerDown {
value |= (1 << 7)
}
if o.IntegerMode {
value |= (1 << 6)
}
if o.Invert {
value |= (1 << 4)
}
o.bus.WriteReg(o.Register.Control, value)
if o.bus.Err() == nil {
o.PowerDown = powerDown
}
return o.bus.Err()
}
// SetIntegerMode sets the integer mode flag of the Output and writes it to the output's control register.
func (o *Output) SetIntegerMode(integerMode bool) error {
value := byte(o.PLL<<5) | byte(o.InputSource<<2) | byte(o.Drive)
if o.PowerDown {
value |= (1 << 7)
}
if integerMode {
value |= (1 << 6)
}
if o.Invert {
value |= (1 << 4)
}
o.bus.WriteReg(o.Register.Control, value)
if o.bus.Err() == nil {
o.IntegerMode = integerMode
}
return o.bus.Err()
}
// SetPLL sets the PLL of the Output and writes it to the output's control register.
func (o *Output) SetPLL(pll PLLIndex) error {
value := byte(pll<<5) | byte(o.InputSource<<2) | byte(o.Drive)
if o.PowerDown {
value |= (1 << 7)
}
if o.IntegerMode {
value |= (1 << 6)
}
if o.Invert {
value |= (1 << 4)
}
o.bus.WriteReg(o.Register.Control, value)
if o.bus.Err() == nil {
o.PLL = pll
}
return o.bus.Err()
}
// SetInvert sets the inversion flag of the Output and writes it to the output's control register.
func (o *Output) SetInvert(invert bool) error {
value := byte(o.PLL<<5) | byte(o.InputSource<<2) | byte(o.Drive)
if o.PowerDown {
value |= (1 << 7)
}
if o.IntegerMode {
value |= (1 << 6)
}
if invert {
value |= (1 << 4)
}
o.bus.WriteReg(o.Register.Control, value)
if o.bus.Err() == nil {
o.Invert = invert
}
return o.bus.Err()
}
// SetInputSource sets the clock input source of the Output and writes it to the output's control register.
func (o *Output) SetInputSource(inputSource ClockInputSource) error {
value := byte(o.PLL<<5) | byte(inputSource<<2) | byte(o.Drive)
if o.PowerDown {
value |= (1 << 7)
}
if o.IntegerMode {
value |= (1 << 6)
}
if o.Invert {
value |= (1 << 4)
}
o.bus.WriteReg(o.Register.Control, value)
if o.bus.Err() == nil {
o.InputSource = inputSource
}
return o.bus.Err()
}
// SetDrive sets the output drive strength of the Output and writes it to the output's control register.
func (o *Output) SetDrive(drive OutputDrive) error {
value := byte(o.PLL<<5) | byte(o.InputSource<<2) | byte(drive)
if o.PowerDown {
value |= (1 << 7)
}
if o.IntegerMode {
value |= (1 << 6)
}
if o.Invert {
value |= (1 << 4)
}
o.bus.WriteReg(o.Register.Control, value)
if o.bus.Err() == nil {
o.Drive = drive
}
return o.bus.Err()
}
// SetupDivider writes the frequency divider into the registers.
func (o *FractionalOutput) SetupDivider(divider FractionalRatio) error {
divider.WriteTo(o.bus.RegWriter(o.Register.Divider))
if o.bus.Err() == nil {
o.FrequencyDivider = divider
}
return o.bus.Err()
}
// SetupPhaseShift sets the phase shift of the Clock.
func (o *FractionalOutput) SetupPhaseShift(phaseShift uint8) error {
o.bus.WriteReg(o.Register.PhaseShift, byte(phaseShift&0x7F))
if o.bus.Err() == nil {
o.PhaseShift = phaseShift
}
return o.bus.Err()
} | pkg/si5351/output.go | 0.793106 | 0.40157 | output.go | starcoder |
package ytbx
import (
"fmt"
yamlv3 "gopkg.in/yaml.v3"
)
// Grab gets the value from the provided YAML tree using a path to traverse
// through the tree structure
func Grab(node *yamlv3.Node, pathString string) (*yamlv3.Node, error) {
path, err := ParsePathString(pathString, node)
if err != nil {
return nil, err
}
switch node.Kind {
case yamlv3.DocumentNode:
return grabByPath(node.Content[0], path)
default:
return grabByPath(node, path)
}
}
func grabByPath(node *yamlv3.Node, path Path) (*yamlv3.Node, error) {
pointer := node
pointerPath := Path{DocumentIdx: path.DocumentIdx}
for _, element := range path.PathElements {
switch {
// Key/Value Map, where the element name is the key for the map
case element.isMapElement():
if pointer.Kind != yamlv3.MappingNode {
return nil,
fmt.Errorf("failed to traverse tree, expected %s but found type %s at %s",
typeMap,
GetType(pointer),
pointerPath.ToGoPatchStyle(),
)
}
entry, err := getValueByKey(pointer, element.Name)
if err != nil {
return nil, err
}
pointer = entry
// Complex List, where each list entry is a Key/Value map and the entry is
// identified by name using an identifier (e.g. name, key, or id)
case element.isComplexListElement():
if pointer.Kind != yamlv3.SequenceNode {
return nil,
fmt.Errorf("failed to traverse tree, expected %s but found type %s at %s",
typeComplexList,
GetType(pointer),
pointerPath.ToGoPatchStyle(),
)
}
entry, err := getEntryByIdentifierAndName(pointer, element.Key, element.Name)
if err != nil {
return nil, err
}
pointer = entry
// Simple List (identified by index)
case element.isSimpleListElement():
if pointer.Kind != yamlv3.SequenceNode {
return nil,
fmt.Errorf("failed to traverse tree, expected %s but found type %s at %s",
typeSimpleList,
GetType(pointer),
pointerPath.ToGoPatchStyle(),
)
}
if element.Idx < 0 || element.Idx >= len(pointer.Content) {
return nil,
fmt.Errorf("failed to traverse tree, provided %s index %d is not in range: 0..%d",
typeSimpleList,
element.Idx,
len(pointer.Content)-1,
)
}
pointer = pointer.Content[element.Idx]
default:
return nil, fmt.Errorf("failed to traverse tree, the provided path %s seems to be invalid", path)
}
// Update the path that the current pointer to keep track of the traversing
pointerPath.PathElements = append(pointerPath.PathElements, element)
}
return pointer, nil
} | getting.go | 0.702632 | 0.432543 | getting.go | starcoder |
package plan
import (
"io"
"reflect"
"github.com/opentracing/opentracing-go"
"github.com/liquidata-inc/go-mysql-server/sql"
)
// An IndexedJoin is a join that uses index lookups for the secondary table.
type IndexedJoin struct {
// The primary and secondary table nodes. The normal meanings of Left and
// Right in BinaryNode aren't necessarily meaningful here -- the Left node is always the primary table, and the Right
// node is always the secondary. These may or may not correspond to the left and right tables in the written query.
BinaryNode
// The join condition.
Cond sql.Expression
// The index to use when looking up rows in the secondary table.
Index sql.Index
// The expression to evaluate to extract a key value from a row in the primary table.
primaryTableExpr []sql.Expression
// The type of join. Left and right refer to the lexical position in the written query, not primary / secondary. In
// the case of a right join, the right table will always be the primary.
joinType JoinType
}
func NewIndexedJoin(primaryTable, indexedTable sql.Node, joinType JoinType, cond sql.Expression, primaryTableExpr []sql.Expression, index sql.Index) *IndexedJoin {
return &IndexedJoin{
BinaryNode: BinaryNode{primaryTable, indexedTable},
joinType: joinType,
Cond: cond,
Index: index,
primaryTableExpr: primaryTableExpr,
}
}
func (ij *IndexedJoin) String() string {
pr := sql.NewTreePrinter()
joinType := ""
switch ij.joinType {
case JoinTypeLeft:
joinType = "Left"
case JoinTypeRight:
joinType = "Right"
}
_ = pr.WriteNode("%sIndexedJoin(%s)", joinType, ij.Cond)
_ = pr.WriteChildren(ij.Left.String(), ij.Right.String())
return pr.String()
}
func (ij *IndexedJoin) Schema() sql.Schema {
return append(ij.Left.Schema(), ij.Right.Schema()...)
}
func (ij *IndexedJoin) RowIter(ctx *sql.Context, row sql.Row) (sql.RowIter, error) {
var indexedTable *IndexedTableAccess
Inspect(ij.Right, func(node sql.Node) bool {
if it, ok := node.(*IndexedTableAccess); ok {
indexedTable = it
return false
}
return true
})
if indexedTable == nil {
return nil, ErrNoIndexedTableAccess.New(ij.Right)
}
return indexedJoinRowIter(ctx, ij.Left, ij.Right, indexedTable, ij.primaryTableExpr, ij.Cond, ij.Index, ij.joinType)
}
func (ij *IndexedJoin) WithChildren(children ...sql.Node) (sql.Node, error) {
if len(children) != 2 {
return nil, sql.ErrInvalidChildrenNumber.New(ij, len(children), 2)
}
return NewIndexedJoin(children[0], children[1], ij.joinType, ij.Cond, ij.primaryTableExpr, ij.Index), nil
}
func indexedJoinRowIter(ctx *sql.Context, left sql.Node, right sql.Node, indexAccess *IndexedTableAccess, primaryTableExpr []sql.Expression, cond sql.Expression, index sql.Index, joinType JoinType) (sql.RowIter, error) {
var leftName, rightName string
if leftTable, ok := left.(sql.Nameable); ok {
leftName = leftTable.Name()
} else {
leftName = reflect.TypeOf(left).String()
}
if rightTable, ok := right.(sql.Nameable); ok {
rightName = rightTable.Name()
} else {
rightName = reflect.TypeOf(right).String()
}
span, ctx := ctx.Span("plan.indexedJoin", opentracing.Tags{
"left": leftName,
"right": rightName,
})
l, err := left.RowIter(ctx, nil)
if err != nil {
span.Finish()
return nil, err
}
return sql.NewSpanIter(span, &indexedJoinIter{
primary: l,
secondaryProvider: right,
secondaryIndexAccess: indexAccess,
ctx: ctx,
cond: cond,
primaryTableExpr: primaryTableExpr,
index: index,
joinType: joinType,
rowSize: len(left.Schema()) + len(right.Schema()),
}), nil
}
// indexedJoinIter is an iterator that iterates over every row in the primary table and performs an index lookup in
// the secondary table for each value
type indexedJoinIter struct {
primary sql.RowIter
primaryRow sql.Row
index sql.Index
secondaryIndexAccess *IndexedTableAccess
secondaryProvider sql.Node
secondary sql.RowIter
primaryTableExpr []sql.Expression
cond sql.Expression
joinType JoinType
ctx *sql.Context
foundMatch bool
rowSize int
}
func (i *indexedJoinIter) loadPrimary() error {
if i.primaryRow == nil {
r, err := i.primary.Next()
if err != nil {
return err
}
i.primaryRow = r
i.foundMatch = false
}
return nil
}
func (i *indexedJoinIter) loadSecondary() (sql.Row, error) {
if i.secondary == nil {
// evaluate the primary row against the primary table expression to get the secondary table lookup key
var key []interface{}
for _, expr := range i.primaryTableExpr {
col, err := expr.Eval(i.ctx, i.primaryRow)
if err != nil {
return nil, err
}
key = append(key, col)
}
lookup, err := i.index.Get(key...)
if err != nil {
return nil, err
}
err = i.secondaryIndexAccess.SetIndexLookup(i.ctx, lookup)
if err != nil {
return nil, err
}
span, ctx := i.ctx.Span("plan.IndexedJoin indexed lookup")
rowIter, err := i.secondaryProvider.RowIter(ctx, nil)
if err != nil {
span.Finish()
return nil, err
}
i.secondary = sql.NewSpanIter(span, rowIter)
}
secondaryRow, err := i.secondary.Next()
if err != nil {
if err == io.EOF {
i.secondary = nil
i.primaryRow = nil
return nil, io.EOF
}
return nil, err
}
return secondaryRow, nil
}
func (i *indexedJoinIter) Next() (sql.Row, error) {
for {
if err := i.loadPrimary(); err != nil {
return nil, err
}
primary := i.primaryRow
secondary, err := i.loadSecondary()
if err != nil {
if err == io.EOF {
if !i.foundMatch && (i.joinType == JoinTypeLeft || i.joinType == JoinTypeRight) {
return i.buildRow(primary, nil), nil
}
continue
}
return nil, err
}
row := i.buildRow(primary, secondary)
matches, err := conditionIsTrue(i.ctx, row, i.cond)
if err != nil {
return nil, err
}
if !matches {
continue
}
i.foundMatch = true
return row, nil
}
}
func conditionIsTrue(ctx *sql.Context, row sql.Row, cond sql.Expression) (bool, error) {
v, err := cond.Eval(ctx, row)
if err != nil {
return false, err
}
// Expressions containing nil evaluate to nil, not false
return v == true, nil
}
// buildRow builds the result set row using the rows from the primary and secondary tables
func (i *indexedJoinIter) buildRow(primary, secondary sql.Row) sql.Row {
row := make(sql.Row, i.rowSize)
copy(row, primary)
copy(row[len(primary):], secondary)
return row
}
func (i *indexedJoinIter) Close() (err error) {
if i.primary != nil {
if err = i.primary.Close(); err != nil {
if i.secondary != nil {
_ = i.secondary.Close()
}
return err
}
}
if i.secondary != nil {
err = i.secondary.Close()
i.secondary = nil
}
return err
} | sql/plan/indexed_join.go | 0.598077 | 0.423398 | indexed_join.go | starcoder |
package ptr
import "time"
// ToDef returns the value of the int pointer passed in or default value if the pointer is nil.
func ToDef[T any](v *T, def T) T {
if v == nil {
return def
}
return *v
}
// ToIntDef returns the value of the int pointer passed in or default value if the pointer is nil.
func ToIntDef(v *int, def int) int {
if v == nil {
return def
}
return *v
}
// ToInt8Def returns the value of the int8 pointer passed in or default value if the pointer is nil.
func ToInt8Def(v *int8, def int8) int8 {
if v == nil {
return def
}
return *v
}
// ToInt16Def returns the value of the int16 pointer passed in or default value if the pointer is nil.
func ToInt16Def(v *int16, def int16) int16 {
if v == nil {
return def
}
return *v
}
// ToInt32Def returns the value of the int32 pointer passed in or default value if the pointer is nil.
func ToInt32Def(v *int32, def int32) int32 {
if v == nil {
return def
}
return *v
}
// ToInt64Def returns the value of the int64 pointer passed in or default value if the pointer is nil.
func ToInt64Def(v *int64, def int64) int64 {
if v == nil {
return def
}
return *v
}
// ToUIntDef returns the value of the uint pointer passed in or default value if the pointer is nil.
func ToUIntDef(v *uint, def uint) uint {
if v == nil {
return def
}
return *v
}
// ToUInt8Def returns the value of the uint8 pointer passed in or default value if the pointer is nil.
func ToUInt8Def(v *uint8, def uint8) uint8 {
if v == nil {
return def
}
return *v
}
// ToUInt16Def returns the value of the uint16 pointer passed in or default value if the pointer is nil.
func ToUInt16Def(v *uint16, def uint16) uint16 {
if v == nil {
return def
}
return *v
}
// ToUInt32Def returns the value of the uint32 pointer passed in or default value if the pointer is nil.
func ToUInt32Def(v *uint32, def uint32) uint32 {
if v == nil {
return def
}
return *v
}
// ToUInt64Def returns the value of the uint64 pointer passed in or default value if the pointer is nil.
func ToUInt64Def(v *uint64, def uint64) uint64 {
if v == nil {
return def
}
return *v
}
// ToByteDef returns the value of the byte pointer passed in or default value if the pointer is nil.
func ToByteDef(v *byte, def byte) byte {
if v == nil {
return def
}
return *v
}
// ToRuneDef returns the value of the rune pointer passed in or default value if the pointer is nil.
func ToRuneDef(v *rune, def rune) rune {
if v == nil {
return def
}
return *v
}
// ToBoolDef returns the value of the bool pointer passed in or default value if the pointer is nil.
func ToBoolDef(v *bool, def bool) bool {
if v == nil {
return def
}
return *v
}
// ToStringDef returns the value of the string pointer passed in or default value if the pointer is nil.
func ToStringDef(v *string, def string) string {
if v == nil {
return def
}
return *v
}
// ToFloat32Def returns the value of the float32 pointer passed in or default value if the pointer is nil.
func ToFloat32Def(v *float32, def float32) float32 {
if v == nil {
return def
}
return *v
}
// ToFloat64Def returns the value of the float64 pointer passed in or default value if the pointer is nil.
func ToFloat64Def(v *float64, def float64) float64 {
if v == nil {
return def
}
return *v
}
// ToComplex64Def returns the value of the complex64 pointer passed in or default value if the pointer is nil.
func ToComplex64Def(v *complex64, def complex64) complex64 {
if v == nil {
return def
}
return *v
}
// ToComplex128Def returns the value of the complex128 pointer passed in or default value if the pointer is nil.
func ToComplex128Def(v *complex128, def complex128) complex128 {
if v == nil {
return def
}
return *v
}
// ToDurationDef returns the value of the time.Duration pointer passed in or default value if the pointer is nil.
func ToDurationDef(v *time.Duration, def time.Duration) time.Duration {
if v == nil {
return def
}
return *v
}
// ToTimeDef returns the value of the time.Time pointer passed in or default value if the pointer is nil.
func ToTimeDef(v *time.Time, def time.Time) time.Time {
if v == nil {
return def
}
return *v
} | todef.go | 0.742422 | 0.434581 | todef.go | starcoder |
package tdigest
import (
"encoding/binary"
"errors"
"fmt"
"math"
)
const smallEncoding int32 = 2
// Marshal serializes the digest into a byte array so it can be
// saved to disk or sent over the wire. buf is used as a backing array, but
// the returned array may be different if it does not fit.
func (t TDigest) Marshal(buf []byte) []byte {
var scratch [8]byte
binary.BigEndian.PutUint32(scratch[:], uint32(smallEncoding))
buf = append(buf, scratch[:4]...)
binary.BigEndian.PutUint64(scratch[:], math.Float64bits(t.compression))
buf = append(buf, scratch[:8]...)
binary.BigEndian.PutUint32(scratch[:], uint32(t.summary.Len()))
buf = append(buf, scratch[:4]...)
var x float64
t.summary.ForEach(func(mean float64, count uint32) bool {
delta := mean - x
x = mean
var scratch [4]byte
binary.BigEndian.PutUint32(scratch[:], math.Float32bits(float32(delta)))
buf = append(buf, scratch[:4]...)
return true
})
t.summary.ForEach(func(mean float64, count uint32) bool {
buf = encodeUint32(buf, count)
return true
})
return buf
}
// and deserializes it. It will panic if the byte slice is not large enough to
// decode.
func FromBytes(buf []byte) (t *TDigest, err error) {
encoding := int32(binary.BigEndian.Uint32(buf))
buf = buf[4:]
if encoding != smallEncoding {
return nil, fmt.Errorf("Unsupported encoding version: %d", encoding)
}
compression := math.Float64frombits(binary.BigEndian.Uint64(buf))
buf = buf[8:]
t = New(compression)
numCentroids := int32(binary.BigEndian.Uint32(buf))
buf = buf[4:]
if numCentroids < 0 || numCentroids > 1<<22 {
return nil, errors.New("bad number of centroids in serialization")
}
means := make([]float64, numCentroids)
var x float64
for i := 0; i < int(numCentroids); i++ {
delta := float64(math.Float32frombits(binary.BigEndian.Uint32(buf)))
buf = buf[4:]
x += delta
means[i] = x
}
for i := 0; i < int(numCentroids); i++ {
var decUint uint32
decUint, buf, err = decodeUint32(buf)
if err != nil {
return nil, err
}
err = t.AddWeighted(means[i], decUint)
if err != nil {
return nil, err
}
}
return t, nil
}
func encodeUint32(buf []byte, n uint32) []byte {
var b [binary.MaxVarintLen32]byte
l := binary.PutUvarint(b[:], uint64(n))
return append(buf, b[:l]...)
}
func decodeUint32(buf []byte) (uint32, []byte, error) {
v, n := binary.Uvarint(buf)
if v > 0xffffffff {
return 0, nil, fmt.Errorf("value too large: %d", v)
}
return uint32(v), buf[n:], nil
} | serialization.go | 0.646683 | 0.486697 | serialization.go | starcoder |
package meta
import (
"encoding/json"
"fmt"
"math"
"math/rand"
"time"
"github.com/MaxHalford/xgp"
"github.com/MaxHalford/xgp/metrics"
)
// GradientBoosting implements gradient boosting on top of genetic programming.
type GradientBoosting struct {
xgp.GPConfig
NRounds uint
NEarlyStoppingRounds uint
LearningRate float64
LineSearcher LineSearcher
Loss metrics.DiffMetric
RowSampling float64
ColSampling float64
Programs []xgp.Program
Steps []float64
UsedCols [][]int
ValScores []float64
TrainScores []float64
YMean float64
UseBestRounds bool
MonitorEvery uint
RNG *rand.Rand
}
// NewGradientBoosting returns a GradientBoosting.
func NewGradientBoosting(
conf xgp.GPConfig,
nRounds uint,
nEarlyStoppingRounds uint,
learningRate float64,
lineSearcher LineSearcher,
loss metrics.DiffMetric,
rowSampling float64,
colSampling float64,
useBestRounds bool,
monitorEvery uint,
rng *rand.Rand,
) (*GradientBoosting, error) {
return &GradientBoosting{
GPConfig: conf,
NRounds: nRounds,
NEarlyStoppingRounds: nEarlyStoppingRounds,
LearningRate: learningRate,
LineSearcher: lineSearcher,
Loss: loss,
RowSampling: rowSampling,
ColSampling: colSampling,
Programs: make([]xgp.Program, 0),
Steps: make([]float64, 0),
UsedCols: make([][]int, 0),
ValScores: make([]float64, 0),
TrainScores: make([]float64, 0),
UseBestRounds: useBestRounds,
MonitorEvery: monitorEvery,
RNG: rng,
}, nil
}
// Logistic function.
func expit(y []float64) []float64 {
var p = make([]float64, len(y))
for i, yi := range y {
p[i] = 1 / (1 + math.Exp(-yi))
}
return p
}
func sign(y []float64) []float64 {
var classes = make([]float64, len(y))
for i, yi := range y {
if yi > 0 {
classes[i] = 1
}
}
return classes
}
func (gb GradientBoosting) shouldMonitor(round uint) bool {
return round == 0 || (round+1)%gb.MonitorEvery == 0
}
// bestRound returns the number of the round where the validation score is the
// lowest. If there are no validation scores then the number of the round with
// the lowest training score is returned.
func (gb GradientBoosting) bestRound() int {
var (
scores []float64
round int
best = math.Inf(1)
)
if len(gb.ValScores) > 0 {
scores = gb.ValScores
} else {
scores = gb.TrainScores
}
for i, score := range scores {
if score < best {
best = score
round = i
}
}
return round
}
// Fit iteratively trains a GP on the gradient of the loss.
func (gb *GradientBoosting) Fit(
// Required arguments
X [][]float64,
Y []float64,
// Optional arguments (can safely be nil)
W []float64,
XVal [][]float64,
YVal []float64,
WVal []float64,
verbose bool,
) error {
var start = time.Now()
// We use symbolic regression even if the task is classication
if gb.Loss.Classification() {
gb.LossMetric = metrics.MSE{}
}
// Start from the target mean
gb.YMean = mean(Y)
var YPred = make([]float64, len(Y))
for i := range YPred {
YPred[i] = gb.YMean
}
// Store the best validation score in order to check for early stopping
var (
bestVal = math.Inf(1)
earlyStopCounter = gb.NEarlyStoppingRounds
)
for i := uint(0); i < gb.NRounds; i++ {
// Compute the gradients
var (
grads []float64
err error
)
if gb.Loss.Classification() {
grads, err = gb.Loss.Gradients(Y, expit(YPred))
} else {
grads, err = gb.Loss.Gradients(Y, YPred)
}
if err != nil {
return err
}
// Subsample
var features [][]float64
if gb.RowSampling < 1 || gb.ColSampling < 1 {
if gb.ColSampling < 1 {
p := uint(gb.ColSampling * float64(len(X)))
cols := randomInts(p, 0, len(X), gb.RNG)
gb.UsedCols = append(gb.UsedCols, cols)
features = selectCols(X, cols)
}
if gb.RowSampling < 1 {
n := uint(gb.RowSampling * float64(len(X)))
features = selectRows(X, randomInts(n, 0, len(X), gb.RNG))
}
} else {
features = X
}
// Train a GP on the negative gradients
gp, err := gb.NewGP()
if err != nil {
return err
}
err = gp.Fit(features, grads, W, nil, nil, nil, false)
if err != nil {
return err
}
// Extract the best obtained Program
prog, err := gp.BestProgram()
if err != nil {
return err
}
gb.Programs = append(gb.Programs, prog)
// Make predictions
update, err := prog.Predict(features, false)
if err != nil {
return err
}
// Find a good step size using line search
var step = 1.0
if gb.LineSearcher != nil {
var yy = make([]float64, len(YPred))
step = gb.LineSearcher.Solve(
func(step float64) float64 {
for i, u := range update {
yy[i] -= gb.LearningRate * step * u
}
var loss, _ = gb.Loss.Apply(Y, yy, nil)
return loss
},
)
}
gb.Steps = append(gb.Steps, step)
for i, u := range update {
YPred[i] -= gb.LearningRate * step * u
}
// Compute training score
var trainScore float64
if gb.EvalMetric.Classification() {
if gb.EvalMetric.NeedsProbabilities() {
trainScore, err = gb.EvalMetric.Apply(Y, expit(YPred), nil)
} else {
trainScore, err = gb.EvalMetric.Apply(Y, sign(YPred), nil)
}
} else {
trainScore, err = gb.EvalMetric.Apply(Y, YPred, nil)
}
if err != nil {
return err
}
gb.TrainScores = append(gb.TrainScores, trainScore)
// If there is no validation set then stop and display training progress
if XVal == nil || YVal == nil || gb.EvalMetric == nil {
if verbose && gb.shouldMonitor(i) {
fmt.Printf(
"%s -- train %s: %.5f -- round %d\n",
fmtDuration(time.Since(start)),
gb.EvalMetric.String(),
trainScore,
i+1,
)
}
continue
}
// Compute validation score
YValPred, err := gb.Predict(XVal, gb.EvalMetric.NeedsProbabilities())
if err != nil {
return err
}
valScore, err := gb.EvalMetric.Apply(YVal, YValPred, nil)
if err != nil {
return err
}
gb.ValScores = append(gb.ValScores, valScore)
// Display training and validation progress
if verbose && gb.shouldMonitor(i) {
fmt.Printf(
"%s -- train %s: %.5f -- val %s: %.5f -- round %d\n",
fmtDuration(time.Since(start)),
gb.EvalMetric.String(),
trainScore,
gb.EvalMetric.String(),
valScore,
i+1,
)
}
// Check for early stopping
if valScore < bestVal {
earlyStopCounter = gb.NEarlyStoppingRounds
bestVal = valScore
} else {
earlyStopCounter--
}
if earlyStopCounter == 0 {
if verbose {
fmt.Println("Early stopping")
}
break
}
}
// Only keep the best rounds
if gb.UseBestRounds {
var b = gb.bestRound() + 1
gb.Programs = gb.Programs[:b]
gb.Steps = gb.Steps[:b]
if len(gb.UsedCols) > b {
gb.UsedCols = gb.UsedCols[:b]
}
if len(gb.ValScores) > b {
gb.ValScores = gb.ValScores[:b]
}
gb.TrainScores = gb.TrainScores[:b]
}
return nil
}
// Predict accumulates the predictions of each stored Program.
func (gb GradientBoosting) Predict(X [][]float64, proba bool) ([]float64, error) {
// Start from the target mean
var YPred = make([]float64, len(X[0]))
for i := range YPred {
YPred[i] = gb.YMean
}
// Accumulate predictions
for i, prog := range gb.Programs {
var features [][]float64
if len(gb.UsedCols) > 0 {
features = selectCols(X, gb.UsedCols[i])
} else {
features = X
}
update, err := prog.Predict(features, false)
if err != nil {
return nil, err
}
for j, u := range update {
YPred[j] -= gb.LearningRate * gb.Steps[i] * u
}
}
// Transform in case of classification
if gb.Loss.Classification() {
YPred = expit(YPred)
if !proba {
YPred = sign(YPred)
}
}
return YPred, nil
}
type serialGradientBoosting struct {
NRounds uint `json:"n_rounds"`
NEarlyStoppingRounds uint `json:"n_early_stopping_round"`
LearningRate float64 `json:"learning_rate"`
Loss string `json:"loss_metric"`
RowSampling float64 `json:"row_sampling"`
ColSampling float64 `json:"col_sampling"`
Programs []xgp.Program `json:"programs"`
Steps []float64 `json:"steps"`
UsedCols [][]int `json:"used_columns"`
ValScores []float64 `json:"val_scores"`
TrainScores []float64 `json:"train_scores"`
YMean float64 `json:"y_mean"`
}
// MarshalJSON serializes a GradientBoosting.
func (gb GradientBoosting) MarshalJSON() ([]byte, error) {
return json.Marshal(&serialGradientBoosting{
NRounds: gb.NRounds,
NEarlyStoppingRounds: gb.NEarlyStoppingRounds,
LearningRate: gb.LearningRate,
Loss: gb.Loss.String(),
Programs: gb.Programs,
Steps: gb.Steps,
ValScores: gb.ValScores,
TrainScores: gb.TrainScores,
YMean: gb.YMean,
})
}
// UnmarshalJSON parses a GradientBoosting.
func (gb *GradientBoosting) UnmarshalJSON(bytes []byte) error {
var serial = &serialGradientBoosting{}
if err := json.Unmarshal(bytes, serial); err != nil {
return err
}
loss, err := metrics.ParseMetric(serial.Loss, 1)
if err != nil {
return err
}
dloss, ok := loss.(metrics.DiffMetric)
if !ok {
return fmt.Errorf("The '%s' metric can't be used for gradient boosting because it is"+
" not differentiable", loss.String())
}
gb.NRounds = serial.NRounds
gb.NEarlyStoppingRounds = serial.NEarlyStoppingRounds
gb.LearningRate = serial.LearningRate
gb.Loss = dloss
gb.Programs = serial.Programs
gb.Steps = serial.Steps
gb.ValScores = serial.ValScores
gb.TrainScores = serial.TrainScores
gb.YMean = serial.YMean
return nil
} | meta/gradient_boosting.go | 0.748168 | 0.446736 | gradient_boosting.go | starcoder |
package bungieapigo
// If you're showing an unlock value in the UI, this is the format in which it should be shown. You'll
// have to build your own algorithms on the client side to determine how best to render these
// options.
type DestinyUnlockValueUIStyle int
const (
// Generally, Automatic means "Just show the number"
DestinyUnlockValueUIStyleAutomatic = 0
// Show the number as a fractional value. For this to make sense, the value being displayed should
// have a comparable upper bound, like the progress to the next level of a Progression.
DestinyUnlockValueUIStyleFraction = 1
// Show the number as a checkbox. 0 Will mean unchecked, any other value will mean checked.
DestinyUnlockValueUIStyleCheckbox = 2
// Show the number as a percentage. For this to make sense, the value being displayed should have a
// comparable upper bound, like the progress to the next level of a Progression.
DestinyUnlockValueUIStylePercentage = 3
// Show the number as a date and time. The number will be the number of seconds since the Unix Epoch
// (January 1st, 1970 at midnight UTC). It'll be up to you to convert this into a date and time format
// understandable to the user in their time zone.
DestinyUnlockValueUIStyleDateTime = 4
// Show the number as a floating point value that represents a fraction, where 0 is min and 1 is max.
// For this to make sense, the value being displayed should have a comparable upper bound, like the
// progress to the next level of a Progression.
DestinyUnlockValueUIStyleFractionFloat = 5
// Show the number as a straight-up integer.
DestinyUnlockValueUIStyleInteger = 6
// Show the number as a time duration. The value will be returned as seconds.
DestinyUnlockValueUIStyleTimeDuration = 7
// Don't bother showing the value at all, it's not easily human-interpretable, and used for some
// internal purpose.
DestinyUnlockValueUIStyleHidden = 8
// Example: "1.5x"
DestinyUnlockValueUIStyleMultiplier = 9
// Show the value as a series of green pips, like the wins in a Trials of Osiris score card.
DestinyUnlockValueUIStyleGreenPips = 10
// Show the value as a series of red pips, like the losses in a Trials of Osiris score card.
DestinyUnlockValueUIStyleRedPips = 11
// Show the value as a percentage. For example: "51%" - Does no division, only appends '%'
DestinyUnlockValueUIStyleExplicitPercentage = 12
// Show the value as a floating-point number. For example: "4.52" NOTE: Passed along from
// Investment as whole number with last two digits as decimal values (452 -> 4.52)
DestinyUnlockValueUIStyleRawFloat = 13
) | pkg/models/DestinyUnlockValueUiStyle.go | 0.615435 | 0.602529 | DestinyUnlockValueUiStyle.go | starcoder |
package shuffle
const constA = 654188429
const constB = 104729
// A FeistelWord abstract the underlying unsigned type to represent a word in the Feistel context.
type FeistelWord uint64
// MaxFeistelWord is the maximum possible value of the FesitelWord type.
const MaxFeistelWord = ^FeistelWord(0)
// A FeistelFunc is the type that define a function to be used in each round of the Feistel application.
type FeistelFunc func(FeistelWord, FeistelWord) FeistelWord
// Feistel is where the state of Feistel network is stored, contains the keys to be applied on each round and a function of type FeistelFunc.
type Feistel struct {
keys []FeistelWord
f FeistelFunc
}
func defaultRoundFunction(v, key FeistelWord) FeistelWord {
return (v * constA) ^ (key * constB)
}
// NewFeistel constructs a new Feistel context with the given keys and FeistelFunc.
func NewFeistel(keys []FeistelWord, f FeistelFunc) *Feistel {
return &Feistel{keys, f}
}
// NewFeistelDefault constructs a new Feistel context with the given keys and using a default FeistelFunc.
func NewFeistelDefault(keys []FeistelWord) *Feistel {
return &Feistel{keys, defaultRoundFunction}
}
func (f *Feistel) core(a, b, amask, bmask FeistelWord) (FeistelWord, FeistelWord) {
var a2 FeistelWord
mask := (amask | bmask)
rounds := len(f.keys)
/* passtrhu when there are not rounds */
if rounds == 0 {
return a & mask, b & mask
}
a1 := b
b1 := a ^ f.f(b, (f.keys[0]&amask)|(f.keys[rounds-1]&bmask))&mask
for round := 1; round < rounds; round++ {
a2 = a1
a1 = b1
b1 = (a2 ^ f.f(b1, (f.keys[round]&amask)|(f.keys[rounds-1-round]&bmask))) & mask
}
return a1, b1
}
// Cipher applys the Feistel cipher step to a word described in its left and right parts.
func (f *Feistel) Cipher(left, right, mask FeistelWord) (FeistelWord, FeistelWord) {
return f.core(left, right, mask, 0)
}
// Decipher applys the Fesitel decipher step to a word described in its left and right parts.
func (f *Feistel) Decipher(left, right, mask FeistelWord) (FeistelWord, FeistelWord) {
right, left = f.core(right, left, 0, mask)
return left, right
} | feistel.go | 0.7773 | 0.572723 | feistel.go | starcoder |
package tiles
import "errors"
// Tile is a simple struct for holding the XYZ coordinates for use in mapping
type Tile struct {
X, Y, Z int
}
// ToPixel return the NW pixel of this tile
func (t Tile) ToPixel() Pixel {
return Pixel{
X: t.X * TileSize,
Y: t.Y * TileSize,
Z: t.Z,
}
}
// ToPixelWithOffset returns a pixel at the origin with an offset added. Useful for getting the center pixel of a tile or another non-origin pixel.
func (t Tile) ToPixelWithOffset(offset Pixel) (pixel Pixel) {
pixel = t.ToPixel()
pixel.X += offset.X
pixel.Y += offset.Y
return
}
// Quadkey returns the string representation of a Bing Maps quadkey. See more https://msdn.microsoft.com/en-us/library/bb259689.aspx
// Panics if the tile is invalid or if it can't write to the internal buffer
func (t Tile) Quadkey() Quadkey {
//bytes.Buffer was bottleneck
z := t.Z
var qk [ZMax]byte
for i := z; i > 0; i-- {
q := 0
m := 1 << uint(i-1)
if (t.X & m) != 0 {
q++
}
if (t.Y & m) != 0 {
q += 2
}
// strconv.Itoa(q) was the bottleneck
var d byte
switch q {
case 0:
d = '0'
case 1:
d = '1'
case 2:
d = '2'
case 3:
d = '3'
default:
panic("Invalid tile.Quadkey()")
}
qk[z-i] = d
}
return Quadkey(qk[:z]) // current bottleneck
}
// FromQuadkeyString returns a tile that represents the given quadkey string. Returns an error if quadkey string is invalid.
func FromQuadkeyString(qk string) (tile Tile, err error) {
tile.Z = len(qk)
for i := tile.Z; i > 0; i-- {
m := 1 << uint(i-1)
c := len(qk) - i
q := qk[c]
switch q {
case '0':
case '1':
tile.X |= m
case '2':
tile.Y |= m
case '3':
tile.X |= m
tile.Y |= m
default:
err = errors.New("Invalid Quadkey " + qk)
tile = Tile{} // zero tile
return
}
}
return
}
// FromCoordinate take float lat/lons and a zoom and return a tile
// Clips the coordinates if they are outside of Min/MaxLat/Lon
func FromCoordinate(lat, lon float64, zoom int) Tile {
c := ClippedCoords(lat, lon)
p := c.ToPixel(zoom)
t, _ := p.ToTile()
return t
} | tile.go | 0.811564 | 0.564399 | tile.go | starcoder |
package compare_expressions
import (
"fmt"
"github.com/Knetic/govaluate"
"github.com/pkg/errors"
"regexp"
"strings"
)
/**
This is the main function that is to be called to verify if 2 expressions are duplicate or not.
Usage:
parameters: expr1 a == 1 && b == 1 , expr1 b == 1 && a == 1
return (true, nil)
Note that the expressions provided should be restricted to have values mentioned below
Currently provides support for
operators ---- && ||
comparators ---- ==
values or right side of expressions ---- to be binary only. So it can be 1 or 0
attribute or left side of expression ---- can be any valid string name
*/
func CheckIfDuplicateExpressions(expr1 string, expr2 string) (bool, error) {
parameters, err := ValidateInput(expr1, expr2)
if err != nil {
fmt.Errorf("Error validating the input %v ", err.Error())
return false, err
}
var count []bool
combinedExpression := "(" + expr1 + ") == (" + expr2 + ")"
parametersMap := make(map[string]interface{})
err = GenerateTruthTable(combinedExpression, parameters, parametersMap, 0, &count)
if err != nil {
fmt.Errorf("Unable to generate truth table %v ", err.Error())
return false, err
}
countOfMatches := 0
for i := range count {
if count[i] {
countOfMatches++
}
}
if countOfMatches == len(count) {
return true, nil
}
return false, nil
}
/**
This function is to validate the input in the following way.
1. It checks if the given expressions have valid format
2. It checks if the given expressions have same number of parameters
Example:
parameters: expr1 a == 1 && b == 1,expr1 b == 1 && a == 1 return: ["a","b"], nil
parameters: expr1 a == 1 && b == 1,expr1 b == 1 && a == 1 and c == 1 "expressions have different number of parameters"
*/
func ValidateInput(expr1, expr2 string) ([]string, error) {
params1, err := ValidateFormat(expr1)
if err != nil {
return nil, err
}
params2, err := ValidateFormat(expr2)
if err != nil {
return nil, err
}
filteredList1 := FilterDuplicates(params1)
filteredList2 := FilterDuplicates(params2)
if err := ListContains(filteredList1, filteredList2); err != nil {
fmt.Printf("Error comparing lists")
return nil, err
}
if err := ListContains(filteredList2, filteredList1); err != nil {
fmt.Printf("Error comparing lists")
return nil, err
}
return params1, nil
}
/**
This function filters the duplicates from given array of string
*/
func FilterDuplicates(params []string) []string {
parametersMap := make(map[string]interface{})
list := []string{}
for _, entry := range params {
if _, value := parametersMap[entry]; !value {
parametersMap[entry] = true
list = append(list, entry)
}
}
return list
}
/**
This function validates the given input expression. It uses regular expressions to validate the format.
Expr should be something like "a == 1" and
Currently provides support for
operators ---- && ||
comparators ---- ==
values or right side of expressions ---- to be binary only. So it can be 1 or 0
attribute or left side of expression ---- can be any valid string name
*/
func ValidateFormat(expr string) ([]string, error) {
regex := regexp.MustCompile(`\s*[=]{2}?\s*[1|0]`)
replaceExpr := regex.ReplaceAllString(expr, " ")
result := strings.Fields(replaceExpr)
invalidRegex := regexp.MustCompile(`\s+[1.0.=]{1}\s*`)
invalidExpr := invalidRegex.MatchString(replaceExpr)
if invalidExpr {
return nil, errors.New(fmt.Sprintf("Invalid expression, Required Format 'variable == 1 or 0'"))
}
regex = regexp.MustCompile(`\s+&{2}?\s+`)
replaceExpr = regex.ReplaceAllString(replaceExpr, " ")
result = strings.Fields(replaceExpr)
regex = regexp.MustCompile(`\s+\|{2}?\s+`)
replaceExpr = regex.ReplaceAllString(replaceExpr, " ")
result = strings.Fields(replaceExpr)
andsFound := strings.Contains(replaceExpr, "&")
orsFound := strings.Contains(replaceExpr, "|")
if andsFound || orsFound {
return nil, errors.New(fmt.Sprintf("Invalid expression, Allowed combinators && or ||"))
}
regex = regexp.MustCompile(`[(|)]`)
replaceExpr = regex.ReplaceAllString(replaceExpr, " ")
result = strings.Fields(replaceExpr)
regex = regexp.MustCompile(`[\D+]`)
emptyExpression := regex.ReplaceAllString(replaceExpr, " ")
if emptyExpression != "" {
errors.New(fmt.Sprintf("Invalid expression, invalid characters=%v ", emptyExpression))
}
return result, nil
}
/**
This function checks whether all strings present in params2 is contained in params1
*/
func ListContains(params1, params2 []string) error {
if len(params1) != len(params2) {
return errors.New(fmt.Sprintf("expressions have different number of parameters, params1:%v , params2:%v", params1, params2))
}
count := 0
for _, v := range params1 {
for _, w := range params2 {
if v == w {
count++
}
}
}
if count != len(params2) {
return errors.New(fmt.Sprintf("expressions have different parameters, params1:%v , params2:%v", params1, params2))
}
return nil
}
/**
This function generates the truth table for the given expression and set of parameters present in the expression.
It used tail recursion to evaluate expression for all possible values to the set of parameters.
*/
func GenerateTruthTable(expr string, parameters []string, parametersMap map[string]interface{}, index int, count *[]bool) error {
if index == len(parameters) {
result, err := EvaluateExpression(expr, parametersMap)
if err != nil {
fmt.Errorf("Unable to evaluate expression, error: %v", err.Error())
return err
} else {
if result.(bool) {
*count = append(*count, true)
} else {
*count = append(*count, false)
}
return nil
}
}
parametersMap[parameters[index]] = 1
if err := GenerateTruthTable(expr, parameters, parametersMap, index+1, count); err != nil {
return err
}
parametersMap[parameters[index]] = 0
if err := GenerateTruthTable(expr, parameters, parametersMap, index+1, count); err != nil {
return err
}
return nil
}
/**
This function uses govaluate library to evaluate the provided boolean expression
*/
func EvaluateExpression(expr string, parameters map[string]interface{}) (interface{}, error) {
expression, err := govaluate.NewEvaluableExpression(expr)
if err != nil {
return nil, errors.New("Unable to initialize the expression. error:" + err.Error())
}
result, err := expression.Evaluate(parameters)
if err != nil {
return nil, errors.New("Unable to evaluate the expression. error:" + err.Error())
}
return result, nil
} | compare_expressions.go | 0.625667 | 0.473901 | compare_expressions.go | starcoder |
//go:generate go run generate.go
// Documentation source: "Event reference" by Mozilla Contributors, https://developer.mozilla.org/en-US/docs/Web/Events, licensed under CC-BY-SA 2.5.
//Package events defines the event binding system for Haiku(https://github.com/influx6/Haiku)
package events
import (
"github.com/influx6/haiku/trees"
)
// Abort Documentation is as below:
// A transaction has been aborted.
// https://developer.mozilla.org/docs/Web/Reference/Events/abort_indexedDB
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Abort(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("abort", selectorOverride, fx)
}
// AfterPrint Documentation is as below:
// The associated document has started printing or the print preview has been closed.
// https://developer.mozilla.org/docs/Web/Events/afterprint
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func AfterPrint(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("afterprint", selectorOverride, fx)
}
// AnimationEnd Documentation is as below:
// A CSS animation has completed.
// https://developer.mozilla.org/docs/Web/Events/animationend
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func AnimationEnd(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("animationend", selectorOverride, fx)
}
// AnimationIteration Documentation is as below:
// A CSS animation is repeated.
// https://developer.mozilla.org/docs/Web/Events/animationiteration
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func AnimationIteration(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("animationiteration", selectorOverride, fx)
}
// AnimationStart Documentation is as below:
// A CSS animation has started.
// https://developer.mozilla.org/docs/Web/Events/animationstart
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func AnimationStart(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("animationstart", selectorOverride, fx)
}
// AudioProcess Documentation is as below:
// The input buffer of a ScriptProcessorNode is ready to be processed.
// https://developer.mozilla.org/docs/Web/Events/audioprocess
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func AudioProcess(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("audioprocess", selectorOverride, fx)
}
// Audioend Documentation is as below:
// The user agent has finished capturing audio for speech recognition.
// https://developer.mozilla.org/docs/Web/Events/audioend
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Audioend(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("audioend", selectorOverride, fx)
}
// Audiostart Documentation is as below:
// The user agent has started to capture audio for speech recognition.
// https://developer.mozilla.org/docs/Web/Events/audiostart
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Audiostart(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("audiostart", selectorOverride, fx)
}
// BeforePrint Documentation is as below:
// The associated document is about to be printed or previewed for printing.
// https://developer.mozilla.org/docs/Web/Events/beforeprint
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func BeforePrint(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("beforeprint", selectorOverride, fx)
}
// BeforeUnload Documentation is as below:
// (no documentation)
// https://developer.mozilla.org/docs/Web/Events/beforeunload
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func BeforeUnload(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("beforeunload", selectorOverride, fx)
}
// BeginEvent Documentation is as below:
// A SMIL animation element begins.
// https://developer.mozilla.org/docs/Web/Events/beginEvent
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func BeginEvent(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("beginEvent", selectorOverride, fx)
}
// Blocked Documentation is as below:
// An open connection to a database is blocking a versionchange transaction on the same database.
// https://developer.mozilla.org/docs/Web/Reference/Events/blocked_indexedDB
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Blocked(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("blocked", selectorOverride, fx)
}
// Blur Documentation is as below:
// An element has lost focus (does not bubble).
// https://developer.mozilla.org/docs/Web/Events/blur
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Blur(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("blur", selectorOverride, fx)
}
// Boundary Documentation is as below:
// The spoken utterance reaches a word or sentence boundary
// https://developer.mozilla.org/docs/Web/Events/boundary
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Boundary(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("boundary", selectorOverride, fx)
}
// Cached Documentation is as below:
// The resources listed in the manifest have been downloaded, and the application is now cached.
// https://developer.mozilla.org/docs/Web/Events/cached
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Cached(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("cached", selectorOverride, fx)
}
// CanPlay Documentation is as below:
// The user agent can play the media, but estimates that not enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
// https://developer.mozilla.org/docs/Web/Events/canplay
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func CanPlay(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("canplay", selectorOverride, fx)
}
// CanPlayThrough Documentation is as below:
// The user agent can play the media, and estimates that enough data has been loaded to play the media up to its end without having to stop for further buffering of content.
// https://developer.mozilla.org/docs/Web/Events/canplaythrough
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func CanPlayThrough(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("canplaythrough", selectorOverride, fx)
}
// Change Documentation is as below:
// An element loses focus and its value changed since gaining focus.
// https://developer.mozilla.org/docs/Web/Events/change
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Change(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("change", selectorOverride, fx)
}
// ChargingChange Documentation is as below:
// The battery begins or stops charging.
// https://developer.mozilla.org/docs/Web/Events/chargingchange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func ChargingChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("chargingchange", selectorOverride, fx)
}
// ChargingTimeChange Documentation is as below:
// The chargingTime attribute has been updated.
// https://developer.mozilla.org/docs/Web/Events/chargingtimechange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func ChargingTimeChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("chargingtimechange", selectorOverride, fx)
}
// Checking Documentation is as below:
// The user agent is checking for an update, or attempting to download the cache manifest for the first time.
// https://developer.mozilla.org/docs/Web/Events/checking
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Checking(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("checking", selectorOverride, fx)
}
// Click Documentation is as below:
// A pointing device button has been pressed and released on an element.
// https://developer.mozilla.org/docs/Web/Events/click
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Click(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("click", selectorOverride, fx)
}
// Close Documentation is as below:
// A WebSocket connection has been closed.
// https://developer.mozilla.org/docs/Web/Reference/Events/close_websocket
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Close(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("close", selectorOverride, fx)
}
// Complete Documentation is as below:
// The rendering of an OfflineAudioContext is terminated.
// https://developer.mozilla.org/docs/Web/Events/complete
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Complete(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("complete", selectorOverride, fx)
}
// CompositionEnd Documentation is as below:
// The composition of a passage of text has been completed or canceled.
// https://developer.mozilla.org/docs/Web/Events/compositionend
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func CompositionEnd(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("compositionend", selectorOverride, fx)
}
// CompositionStart Documentation is as below:
// The composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition).
// https://developer.mozilla.org/docs/Web/Events/compositionstart
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func CompositionStart(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("compositionstart", selectorOverride, fx)
}
// CompositionUpdate Documentation is as below:
// A character is added to a passage of text being composed.
// https://developer.mozilla.org/docs/Web/Events/compositionupdate
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func CompositionUpdate(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("compositionupdate", selectorOverride, fx)
}
// ContextMenu Documentation is as below:
// The right button of the mouse is clicked (before the context menu is displayed).
// https://developer.mozilla.org/docs/Web/Events/contextmenu
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func ContextMenu(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("contextmenu", selectorOverride, fx)
}
// Copy Documentation is as below:
// The text selection has been added to the clipboard.
// https://developer.mozilla.org/docs/Web/Events/copy
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Copy(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("copy", selectorOverride, fx)
}
// Cut Documentation is as below:
// The text selection has been removed from the document and added to the clipboard.
// https://developer.mozilla.org/docs/Web/Events/cut
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Cut(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("cut", selectorOverride, fx)
}
// DOMContentLoaded Documentation is as below:
// The document has finished loading (but not its dependent resources).
// https://developer.mozilla.org/docs/Web/Events/DOMContentLoaded
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DOMContentLoaded(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("DOMContentLoaded", selectorOverride, fx)
}
// DblClick Documentation is as below:
// A pointing device button is clicked twice on an element.
// https://developer.mozilla.org/docs/Web/Events/dblclick
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DblClick(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("dblclick", selectorOverride, fx)
}
// DeviceLight Documentation is as below:
// Fresh data is available from a light sensor.
// https://developer.mozilla.org/docs/Web/Events/devicelight
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DeviceLight(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("devicelight", selectorOverride, fx)
}
// DeviceMotion Documentation is as below:
// Fresh data is available from a motion sensor.
// https://developer.mozilla.org/docs/Web/Events/devicemotion
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DeviceMotion(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("devicemotion", selectorOverride, fx)
}
// DeviceOrientation Documentation is as below:
// Fresh data is available from an orientation sensor.
// https://developer.mozilla.org/docs/Web/Events/deviceorientation
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DeviceOrientation(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("deviceorientation", selectorOverride, fx)
}
// DeviceProximity Documentation is as below:
// Fresh data is available from a proximity sensor (indicates an approximated distance between the device and a nearby object).
// https://developer.mozilla.org/docs/Web/Events/deviceproximity
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DeviceProximity(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("deviceproximity", selectorOverride, fx)
}
// DischargingTimeChange Documentation is as below:
// The dischargingTime attribute has been updated.
// https://developer.mozilla.org/docs/Web/Events/dischargingtimechange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DischargingTimeChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("dischargingtimechange", selectorOverride, fx)
}
// Downloading Documentation is as below:
// The user agent has found an update and is fetching it, or is downloading the resources listed by the cache manifest for the first time.
// https://developer.mozilla.org/docs/Web/Events/downloading
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Downloading(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("downloading", selectorOverride, fx)
}
// Drag Documentation is as below:
// An element or text selection is being dragged (every 350ms).
// https://developer.mozilla.org/docs/Web/Events/drag
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Drag(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("drag", selectorOverride, fx)
}
// DragEnd Documentation is as below:
// A drag operation is being ended (by releasing a mouse button or hitting the escape key).
// https://developer.mozilla.org/docs/Web/Events/dragend
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DragEnd(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("dragend", selectorOverride, fx)
}
// DragEnter Documentation is as below:
// A dragged element or text selection enters a valid drop target.
// https://developer.mozilla.org/docs/Web/Events/dragenter
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DragEnter(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("dragenter", selectorOverride, fx)
}
// DragLeave Documentation is as below:
// A dragged element or text selection leaves a valid drop target.
// https://developer.mozilla.org/docs/Web/Events/dragleave
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DragLeave(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("dragleave", selectorOverride, fx)
}
// DragOver Documentation is as below:
// An element or text selection is being dragged over a valid drop target (every 350ms).
// https://developer.mozilla.org/docs/Web/Events/dragover
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DragOver(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("dragover", selectorOverride, fx)
}
// DragStart Documentation is as below:
// The user starts dragging an element or text selection.
// https://developer.mozilla.org/docs/Web/Events/dragstart
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DragStart(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("dragstart", selectorOverride, fx)
}
// Drop Documentation is as below:
// An element is dropped on a valid drop target.
// https://developer.mozilla.org/docs/Web/Events/drop
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Drop(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("drop", selectorOverride, fx)
}
// DurationChange Documentation is as below:
// The duration attribute has been updated.
// https://developer.mozilla.org/docs/Web/Events/durationchange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func DurationChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("durationchange", selectorOverride, fx)
}
// Emptied Documentation is as below:
// The media has become empty; for example, this event is sent if the media has already been loaded (or partially loaded), and the load() method is called to reload it.
// https://developer.mozilla.org/docs/Web/Events/emptied
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Emptied(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("emptied", selectorOverride, fx)
}
// End Documentation is as below:
// The utterance has finished being spoken.
// https://developer.mozilla.org/docs/Web/Events/end_(SpeechSynthesis)
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func End(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("end", selectorOverride, fx)
}
// EndEvent Documentation is as below:
// A SMIL animation element ends.
// https://developer.mozilla.org/docs/Web/Events/endEvent
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func EndEvent(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("endEvent", selectorOverride, fx)
}
// Ended Documentation is as below:
// (no documentation)
// https://developer.mozilla.org/docs/Web/Events/ended_(Web_Audio)
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Ended(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("ended", selectorOverride, fx)
}
// Error Documentation is as below:
// An error occurs that prevents the utterance from being succesfully spoken.
// https://developer.mozilla.org/docs/Web/Events/error_(SpeechSynthesisError)
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Error(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("error", selectorOverride, fx)
}
// Focus Documentation is as below:
// An element has received focus (does not bubble).
// https://developer.mozilla.org/docs/Web/Events/focus
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Focus(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("focus", selectorOverride, fx)
}
// FocusIn Documentation is as below:
// An element is about to receive focus (bubbles).
// https://developer.mozilla.org/docs/Web/Events/focusin
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func FocusIn(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("focusin", selectorOverride, fx)
}
// FocusOut Documentation is as below:
// An element is about to lose focus (bubbles).
// https://developer.mozilla.org/docs/Web/Events/focusout
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func FocusOut(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("focusout", selectorOverride, fx)
}
// FullScreenChange Documentation is as below:
// An element was turned to fullscreen mode or back to normal mode.
// https://developer.mozilla.org/docs/Web/Events/fullscreenchange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func FullScreenChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("fullscreenchange", selectorOverride, fx)
}
// FullScreenError Documentation is as below:
// It was impossible to switch to fullscreen mode for technical reasons or because the permission was denied.
// https://developer.mozilla.org/docs/Web/Events/fullscreenerror
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func FullScreenError(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("fullscreenerror", selectorOverride, fx)
}
// GamepadConnected Documentation is as below:
// A gamepad has been connected.
// https://developer.mozilla.org/docs/Web/Events/gamepadconnected
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func GamepadConnected(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("gamepadconnected", selectorOverride, fx)
}
// GamepadDisconnected Documentation is as below:
// A gamepad has been disconnected.
// https://developer.mozilla.org/docs/Web/Events/gamepaddisconnected
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func GamepadDisconnected(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("gamepaddisconnected", selectorOverride, fx)
}
// Gotpointercapture Documentation is as below:
// Element receives pointer capture.
// https://developer.mozilla.org/docs/Web/Events/gotpointercapture
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Gotpointercapture(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("gotpointercapture", selectorOverride, fx)
}
// HashChange Documentation is as below:
// The fragment identifier of the URL has changed (the part of the URL after the #).
// https://developer.mozilla.org/docs/Web/Events/hashchange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func HashChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("hashchange", selectorOverride, fx)
}
// Input Documentation is as below:
// The value of an element changes or the content of an element with the attribute contenteditable is modified.
// https://developer.mozilla.org/docs/Web/Events/input
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Input(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("input", selectorOverride, fx)
}
// Invalid Documentation is as below:
// A submittable element has been checked and doesn't satisfy its constraints.
// https://developer.mozilla.org/docs/Web/Events/invalid
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Invalid(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("invalid", selectorOverride, fx)
}
// KeyDown Documentation is as below:
// A key is pressed down.
// https://developer.mozilla.org/docs/Web/Events/keydown
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func KeyDown(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("keydown", selectorOverride, fx)
}
// KeyPress Documentation is as below:
// A key is pressed down and that key normally produces a character value (use input instead).
// https://developer.mozilla.org/docs/Web/Events/keypress
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func KeyPress(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("keypress", selectorOverride, fx)
}
// KeyUp Documentation is as below:
// A key is released.
// https://developer.mozilla.org/docs/Web/Events/keyup
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func KeyUp(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("keyup", selectorOverride, fx)
}
// LanguageChange Documentation is as below:
// (no documentation)
// https://developer.mozilla.org/docs/Web/Events/languagechange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func LanguageChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("languagechange", selectorOverride, fx)
}
// LevelChange Documentation is as below:
// The level attribute has been updated.
// https://developer.mozilla.org/docs/Web/Events/levelchange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func LevelChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("levelchange", selectorOverride, fx)
}
// Load Documentation is as below:
// Progression has been successful.
// https://developer.mozilla.org/docs/Web/Reference/Events/load_(ProgressEvent)
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Load(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("load", selectorOverride, fx)
}
// LoadEnd Documentation is as below:
// Progress has stopped (after "error", "abort" or "load" have been dispatched).
// https://developer.mozilla.org/docs/Web/Events/loadend
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func LoadEnd(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("loadend", selectorOverride, fx)
}
// LoadStart Documentation is as below:
// Progress has begun.
// https://developer.mozilla.org/docs/Web/Events/loadstart
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func LoadStart(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("loadstart", selectorOverride, fx)
}
// LoadedData Documentation is as below:
// The first frame of the media has finished loading.
// https://developer.mozilla.org/docs/Web/Events/loadeddata
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func LoadedData(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("loadeddata", selectorOverride, fx)
}
// LoadedMetadata Documentation is as below:
// The metadata has been loaded.
// https://developer.mozilla.org/docs/Web/Events/loadedmetadata
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func LoadedMetadata(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("loadedmetadata", selectorOverride, fx)
}
// Lostpointercapture Documentation is as below:
// Element lost pointer capture.
// https://developer.mozilla.org/docs/Web/Events/lostpointercapture
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Lostpointercapture(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("lostpointercapture", selectorOverride, fx)
}
// Mark Documentation is as below:
// The spoken utterance reaches a named SSML "mark" tag.
// https://developer.mozilla.org/docs/Web/Events/mark
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Mark(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("mark", selectorOverride, fx)
}
// Message Documentation is as below:
// A message is received through an event source.
// https://developer.mozilla.org/docs/Web/Reference/Events/message_serversentevents
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Message(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("message", selectorOverride, fx)
}
// MouseDown Documentation is as below:
// A pointing device button (usually a mouse) is pressed on an element.
// https://developer.mozilla.org/docs/Web/Events/mousedown
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func MouseDown(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("mousedown", selectorOverride, fx)
}
// MouseEnter Documentation is as below:
// A pointing device is moved onto the element that has the listener attached.
// https://developer.mozilla.org/docs/Web/Events/mouseenter
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func MouseEnter(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("mouseenter", selectorOverride, fx)
}
// MouseLeave Documentation is as below:
// A pointing device is moved off the element that has the listener attached.
// https://developer.mozilla.org/docs/Web/Events/mouseleave
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func MouseLeave(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("mouseleave", selectorOverride, fx)
}
// MouseMove Documentation is as below:
// A pointing device is moved over an element.
// https://developer.mozilla.org/docs/Web/Events/mousemove
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func MouseMove(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("mousemove", selectorOverride, fx)
}
// MouseOut Documentation is as below:
// A pointing device is moved off the element that has the listener attached or off one of its children.
// https://developer.mozilla.org/docs/Web/Events/mouseout
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func MouseOut(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("mouseout", selectorOverride, fx)
}
// MouseOver Documentation is as below:
// A pointing device is moved onto the element that has the listener attached or onto one of its children.
// https://developer.mozilla.org/docs/Web/Events/mouseover
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func MouseOver(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("mouseover", selectorOverride, fx)
}
// MouseUp Documentation is as below:
// A pointing device button is released over an element.
// https://developer.mozilla.org/docs/Web/Events/mouseup
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func MouseUp(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("mouseup", selectorOverride, fx)
}
// NoUpdate Documentation is as below:
// The manifest hadn't changed.
// https://developer.mozilla.org/docs/Web/Events/noupdate
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func NoUpdate(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("noupdate", selectorOverride, fx)
}
// Nomatch Documentation is as below:
// The speech recognition service returns a final result with no significant recognition.
// https://developer.mozilla.org/docs/Web/Events/nomatch
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Nomatch(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("nomatch", selectorOverride, fx)
}
// Notificationclick Documentation is as below:
// A system notification spawned by ServiceWorkerRegistration.showNotification() has been clicked.
// https://developer.mozilla.org/docs/Web/Events/notificationclick
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Notificationclick(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("notificationclick", selectorOverride, fx)
}
// Obsolete Documentation is as below:
// The manifest was found to have become a 404 or 410 page, so the application cache is being deleted.
// https://developer.mozilla.org/docs/Web/Events/obsolete
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Obsolete(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("obsolete", selectorOverride, fx)
}
// Offline Documentation is as below:
// The browser has lost access to the network.
// https://developer.mozilla.org/docs/Web/Events/offline
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Offline(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("offline", selectorOverride, fx)
}
// Online Documentation is as below:
// The browser has gained access to the network (but particular websites might be unreachable).
// https://developer.mozilla.org/docs/Web/Events/online
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Online(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("online", selectorOverride, fx)
}
// Open Documentation is as below:
// An event source connection has been established.
// https://developer.mozilla.org/docs/Web/Reference/Events/open_serversentevents
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Open(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("open", selectorOverride, fx)
}
// OrientationChange Documentation is as below:
// The orientation of the device (portrait/landscape) has changed
// https://developer.mozilla.org/docs/Web/Events/orientationchange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func OrientationChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("orientationchange", selectorOverride, fx)
}
// PageHide Documentation is as below:
// A session history entry is being traversed from.
// https://developer.mozilla.org/docs/Web/Events/pagehide
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func PageHide(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pagehide", selectorOverride, fx)
}
// PageShow Documentation is as below:
// A session history entry is being traversed to.
// https://developer.mozilla.org/docs/Web/Events/pageshow
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func PageShow(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pageshow", selectorOverride, fx)
}
// Paste Documentation is as below:
// Data has been transfered from the system clipboard to the document.
// https://developer.mozilla.org/docs/Web/Events/paste
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Paste(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("paste", selectorOverride, fx)
}
// Pause Documentation is as below:
// The utterance is paused part way through.
// https://developer.mozilla.org/docs/Web/Events/pause_(SpeechSynthesis)
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Pause(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pause", selectorOverride, fx)
}
// Play Documentation is as below:
// Playback has begun.
// https://developer.mozilla.org/docs/Web/Events/play
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Play(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("play", selectorOverride, fx)
}
// Playing Documentation is as below:
// Playback is ready to start after having been paused or delayed due to lack of data.
// https://developer.mozilla.org/docs/Web/Events/playing
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Playing(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("playing", selectorOverride, fx)
}
// PointerLockChange Documentation is as below:
// The pointer was locked or released.
// https://developer.mozilla.org/docs/Web/Events/pointerlockchange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func PointerLockChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pointerlockchange", selectorOverride, fx)
}
// PointerLockError Documentation is as below:
// It was impossible to lock the pointer for technical reasons or because the permission was denied.
// https://developer.mozilla.org/docs/Web/Events/pointerlockerror
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func PointerLockError(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pointerlockerror", selectorOverride, fx)
}
// Pointercancel Documentation is as below:
// The pointer is unlikely to produce any more events.
// https://developer.mozilla.org/docs/Web/Events/pointercancel
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Pointercancel(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pointercancel", selectorOverride, fx)
}
// Pointerdown Documentation is as below:
// The pointer enters the active buttons state.
// https://developer.mozilla.org/docs/Web/Events/pointerdown
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Pointerdown(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pointerdown", selectorOverride, fx)
}
// Pointerenter Documentation is as below:
// Pointing device is moved inside the hit-testing boundary.
// https://developer.mozilla.org/docs/Web/Events/pointerenter
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Pointerenter(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pointerenter", selectorOverride, fx)
}
// Pointerleave Documentation is as below:
// Pointing device is moved out of the hit-testing boundary.
// https://developer.mozilla.org/docs/Web/Events/pointerleave
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Pointerleave(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pointerleave", selectorOverride, fx)
}
// Pointermove Documentation is as below:
// The pointer changed coordinates.
// https://developer.mozilla.org/docs/Web/Events/pointermove
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Pointermove(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pointermove", selectorOverride, fx)
}
// Pointerout Documentation is as below:
// The pointing device moved out of hit-testing boundary or leaves detectable hover range.
// https://developer.mozilla.org/docs/Web/Events/pointerout
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Pointerout(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pointerout", selectorOverride, fx)
}
// Pointerover Documentation is as below:
// The pointing device is moved into the hit-testing boundary.
// https://developer.mozilla.org/docs/Web/Events/pointerover
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Pointerover(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pointerover", selectorOverride, fx)
}
// Pointerup Documentation is as below:
// The pointer leaves the active buttons state.
// https://developer.mozilla.org/docs/Web/Events/pointerup
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Pointerup(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pointerup", selectorOverride, fx)
}
// PopState Documentation is as below:
// A session history entry is being navigated to (in certain cases).
// https://developer.mozilla.org/docs/Web/Events/popstate
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func PopState(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("popstate", selectorOverride, fx)
}
// Progress Documentation is as below:
// The user agent is downloading resources listed by the manifest.
// https://developer.mozilla.org/docs/Web/Reference/Events/progress_(appcache_event)
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Progress(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("progress", selectorOverride, fx)
}
// Push Documentation is as below:
// A Service Worker has received a push message.
// https://developer.mozilla.org/docs/Web/Events/push
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Push(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("push", selectorOverride, fx)
}
// Pushsubscriptionchange Documentation is as below:
// A PushSubscription has expired.
// https://developer.mozilla.org/docs/Web/Events/pushsubscriptionchange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Pushsubscriptionchange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("pushsubscriptionchange", selectorOverride, fx)
}
// RateChange Documentation is as below:
// The playback rate has changed.
// https://developer.mozilla.org/docs/Web/Events/ratechange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func RateChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("ratechange", selectorOverride, fx)
}
// ReadystateChange Documentation is as below:
// The readyState attribute of a document has changed.
// https://developer.mozilla.org/docs/Web/Events/readystatechange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func ReadystateChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("readystatechange", selectorOverride, fx)
}
// RepeatEvent Documentation is as below:
// A SMIL animation element is repeated.
// https://developer.mozilla.org/docs/Web/Events/repeatEvent
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func RepeatEvent(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("repeatEvent", selectorOverride, fx)
}
// Reset Documentation is as below:
// A form is reset.
// https://developer.mozilla.org/docs/Web/Events/reset
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Reset(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("reset", selectorOverride, fx)
}
// Resize Documentation is as below:
// The document view has been resized.
// https://developer.mozilla.org/docs/Web/Events/resize
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Resize(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("resize", selectorOverride, fx)
}
// Result Documentation is as below:
// The speech recognition service returns a result — a word or phrase has been positively recognized and this has been communicated back to the app.
// https://developer.mozilla.org/docs/Web/Events/result
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Result(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("result", selectorOverride, fx)
}
// Resume Documentation is as below:
// A paused utterance is resumed.
// https://developer.mozilla.org/docs/Web/Events/resume
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Resume(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("resume", selectorOverride, fx)
}
// SVGAbort Documentation is as below:
// Page loading has been stopped before the SVG was loaded.
// https://developer.mozilla.org/docs/Web/Events/SVGAbort
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func SVGAbort(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("SVGAbort", selectorOverride, fx)
}
// SVGError Documentation is as below:
// An error has occurred before the SVG was loaded.
// https://developer.mozilla.org/docs/Web/Events/SVGError
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func SVGError(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("SVGError", selectorOverride, fx)
}
// SVGLoad Documentation is as below:
// An SVG document has been loaded and parsed.
// https://developer.mozilla.org/docs/Web/Events/SVGLoad
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func SVGLoad(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("SVGLoad", selectorOverride, fx)
}
// SVGResize Documentation is as below:
// An SVG document is being resized.
// https://developer.mozilla.org/docs/Web/Events/SVGResize
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func SVGResize(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("SVGResize", selectorOverride, fx)
}
// SVGScroll Documentation is as below:
// An SVG document is being scrolled.
// https://developer.mozilla.org/docs/Web/Events/SVGScroll
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func SVGScroll(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("SVGScroll", selectorOverride, fx)
}
// SVGUnload Documentation is as below:
// An SVG document has been removed from a window or frame.
// https://developer.mozilla.org/docs/Web/Events/SVGUnload
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func SVGUnload(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("SVGUnload", selectorOverride, fx)
}
// SVGZoom Documentation is as below:
// An SVG document is being zoomed.
// https://developer.mozilla.org/docs/Web/Events/SVGZoom
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func SVGZoom(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("SVGZoom", selectorOverride, fx)
}
// Scroll Documentation is as below:
// The document view or an element has been scrolled.
// https://developer.mozilla.org/docs/Web/Events/scroll
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Scroll(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("scroll", selectorOverride, fx)
}
// Seeked Documentation is as below:
// A seek operation completed.
// https://developer.mozilla.org/docs/Web/Events/seeked
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Seeked(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("seeked", selectorOverride, fx)
}
// Seeking Documentation is as below:
// A seek operation began.
// https://developer.mozilla.org/docs/Web/Events/seeking
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Seeking(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("seeking", selectorOverride, fx)
}
// Select Documentation is as below:
// Some text is being selected.
// https://developer.mozilla.org/docs/Web/Events/select
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Select(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("select", selectorOverride, fx)
}
// Selectionchange Documentation is as below:
// The selection in the document has been changed.
// https://developer.mozilla.org/docs/Web/Events/selectionchange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Selectionchange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("selectionchange", selectorOverride, fx)
}
// Selectstart Documentation is as below:
// A selection just started.
// https://developer.mozilla.org/docs/Web/Events/selectstart
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Selectstart(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("selectstart", selectorOverride, fx)
}
// Show Documentation is as below:
// A contextmenu event was fired on/bubbled to an element that has a contextmenu attribute
// https://developer.mozilla.org/docs/Web/Events/show
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Show(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("show", selectorOverride, fx)
}
// Soundend Documentation is as below:
// Any sound — recognisable speech or not — has stopped being detected.
// https://developer.mozilla.org/docs/Web/Events/soundend
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Soundend(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("soundend", selectorOverride, fx)
}
// Soundstart Documentation is as below:
// Any sound — recognisable speech or not — has been detected.
// https://developer.mozilla.org/docs/Web/Events/soundstart
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Soundstart(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("soundstart", selectorOverride, fx)
}
// Speechend Documentation is as below:
// Speech recognised by the speech recognition service has stopped being detected.
// https://developer.mozilla.org/docs/Web/Events/speechend
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Speechend(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("speechend", selectorOverride, fx)
}
// Speechstart Documentation is as below:
// Sound that is recognised by the speech recognition service as speech has been detected.
// https://developer.mozilla.org/docs/Web/Events/speechstart
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Speechstart(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("speechstart", selectorOverride, fx)
}
// Stalled Documentation is as below:
// The user agent is trying to fetch media data, but data is unexpectedly not forthcoming.
// https://developer.mozilla.org/docs/Web/Events/stalled
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Stalled(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("stalled", selectorOverride, fx)
}
// Start Documentation is as below:
// The utterance has begun to be spoken.
// https://developer.mozilla.org/docs/Web/Events/start_(SpeechSynthesis)
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Start(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("start", selectorOverride, fx)
}
// Storage Documentation is as below:
// A storage area (localStorage or sessionStorage) has changed.
// https://developer.mozilla.org/docs/Web/Events/storage
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Storage(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("storage", selectorOverride, fx)
}
// Submit Documentation is as below:
// A form is submitted.
// https://developer.mozilla.org/docs/Web/Events/submit
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Submit(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("submit", selectorOverride, fx)
}
// Success Documentation is as below:
// A request successfully completed.
// https://developer.mozilla.org/docs/Web/Reference/Events/success_indexedDB
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Success(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("success", selectorOverride, fx)
}
// Suspend Documentation is as below:
// Media data loading has been suspended.
// https://developer.mozilla.org/docs/Web/Events/suspend
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Suspend(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("suspend", selectorOverride, fx)
}
// TimeUpdate Documentation is as below:
// The time indicated by the currentTime attribute has been updated.
// https://developer.mozilla.org/docs/Web/Events/timeupdate
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func TimeUpdate(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("timeupdate", selectorOverride, fx)
}
// Timeout Documentation is as below:
// (no documentation)
// https://developer.mozilla.org/docs/Web/Events/timeout
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Timeout(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("timeout", selectorOverride, fx)
}
// TouchCancel Documentation is as below:
// A touch point has been disrupted in an implementation-specific manners (too many touch points for example).
// https://developer.mozilla.org/docs/Web/Events/touchcancel
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func TouchCancel(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("touchcancel", selectorOverride, fx)
}
// TouchEnd Documentation is as below:
// A touch point is removed from the touch surface.
// https://developer.mozilla.org/docs/Web/Events/touchend
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func TouchEnd(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("touchend", selectorOverride, fx)
}
// TouchEnter Documentation is as below:
// A touch point is moved onto the interactive area of an element.
// https://developer.mozilla.org/docs/Web/Events/touchenter
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func TouchEnter(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("touchenter", selectorOverride, fx)
}
// TouchLeave Documentation is as below:
// A touch point is moved off the interactive area of an element.
// https://developer.mozilla.org/docs/Web/Events/touchleave
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func TouchLeave(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("touchleave", selectorOverride, fx)
}
// TouchMove Documentation is as below:
// A touch point is moved along the touch surface.
// https://developer.mozilla.org/docs/Web/Events/touchmove
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func TouchMove(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("touchmove", selectorOverride, fx)
}
// TouchStart Documentation is as below:
// A touch point is placed on the touch surface.
// https://developer.mozilla.org/docs/Web/Events/touchstart
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func TouchStart(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("touchstart", selectorOverride, fx)
}
// TransitionEnd Documentation is as below:
// A CSS transition has completed.
// https://developer.mozilla.org/docs/Web/Events/transitionend
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func TransitionEnd(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("transitionend", selectorOverride, fx)
}
// Unload Documentation is as below:
// The document or a dependent resource is being unloaded.
// https://developer.mozilla.org/docs/Web/Events/unload
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Unload(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("unload", selectorOverride, fx)
}
// UpdateReady Documentation is as below:
// The resources listed in the manifest have been newly redownloaded, and the script can use swapCache() to switch to the new cache.
// https://developer.mozilla.org/docs/Web/Events/updateready
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func UpdateReady(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("updateready", selectorOverride, fx)
}
// UpgradeNeeded Documentation is as below:
// An attempt was made to open a database with a version number higher than its current version. A versionchange transaction has been created.
// https://developer.mozilla.org/docs/Web/Reference/Events/upgradeneeded_indexedDB
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func UpgradeNeeded(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("upgradeneeded", selectorOverride, fx)
}
// UserProximity Documentation is as below:
// Fresh data is available from a proximity sensor (indicates whether the nearby object is near the device or not).
// https://developer.mozilla.org/docs/Web/Events/userproximity
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func UserProximity(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("userproximity", selectorOverride, fx)
}
// VersionChange Documentation is as below:
// A versionchange transaction completed.
// https://developer.mozilla.org/docs/Web/Reference/Events/versionchange_indexedDB
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func VersionChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("versionchange", selectorOverride, fx)
}
// VisibilityChange Documentation is as below:
// The content of a tab has become visible or has been hidden.
// https://developer.mozilla.org/docs/Web/Events/visibilitychange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func VisibilityChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("visibilitychange", selectorOverride, fx)
}
// Voiceschanged Documentation is as below:
// The list of SpeechSynthesisVoice objects that would be returned by the SpeechSynthesis.getVoices() method has changed (when the voiceschanged event fires.)
// https://developer.mozilla.org/docs/Web/Events/voiceschanged
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Voiceschanged(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("voiceschanged", selectorOverride, fx)
}
// VolumeChange Documentation is as below:
// The volume has changed.
// https://developer.mozilla.org/docs/Web/Events/volumechange
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func VolumeChange(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("volumechange", selectorOverride, fx)
}
// Waiting Documentation is as below:
// Playback has stopped because of a temporary lack of data.
// https://developer.mozilla.org/docs/Web/Events/waiting
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Waiting(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("waiting", selectorOverride, fx)
}
// Wheel Documentation is as below:
// A wheel button of a pointing device is rotated in any direction.
// https://developer.mozilla.org/docs/Web/Events/wheel
/* This event provides options() to be called when the events is triggered and an optional selector which will override the internal selector mechanism of the trees.Element i.e if the selectorOverride argument is an empty string then trees.Element will create an appropriate selector matching its type and uid value in this format (ElementType[uid='UID_VALUE']) but if the selector value is not empty then that becomes the default selector used
match the event with. */
func Wheel(fx trees.EventHandler, selectorOverride string) *trees.Event {
return trees.NewEvent("wheel", selectorOverride, fx)
} | trees/events/event.gen.go | 0.807537 | 0.449695 | event.gen.go | starcoder |
// Package ledger implements a modified map with three unique characteristics:
// 1. every unique state of the map is given a unique hash
// 2. prior states of the map are retained for a fixed period of time
// 2. given a previous hash, we can retrieve a previous state from the map, if it is still retained.
package ledger
import (
"encoding/base64"
"fmt"
"math"
"sync"
"time"
"github.com/hashicorp/go-multierror"
"github.com/spaolacci/murmur3"
"istio.io/pkg/cache"
)
// Ledger exposes a modified map with three unique characteristics:
// 1. every unique state of the map is given a unique hash
// 2. prior states of the map are retained until erased
// 3. given a previous hash, we can retrieve a previous state from the map, if it is still retained.
type Ledger interface {
// Put adds or overwrites a key in the Ledger
Put(key, value string) (string, error)
// Delete removes a key from the Ledger, which may still be read using GetPreviousValue
Delete(key string) (string, error)
// Get returns a the value of the key from the Ledger's current state
Get(key string) (string, error)
// RootHash is the hash of all keys and values currently in the Ledger
RootHash() string
// GetPreviousValue executes a get against a previous version of the ledger, using that version's root hash.
GetPreviousValue(previousRootHash, key string) (result string, err error)
// EraseRootHash re-claims any memory used by this version of history, preserving bits shared with other versions.
EraseRootHash(rootHash string) error
// Stats gives basic storage info regarding the ledger's underlying cache
Stats() cache.Stats
// GetAll returns the entire state of the ledger
GetAll() (map[string]string, error)
// GetAllPrevious returns the entire state of the ledger at an arbitrary version
GetAllPrevious(string) (map[string]string, error)
}
type smtLedger struct {
tree *smt
// history tracks the sequence of versions of the ledger for use while erasing
history *history
// keys in smt are hashed. this cache allows us to reverse the hash and reconstruct the keys
keyCache byteCache
firstObserved map[string][]byte
eraselock sync.Mutex
}
func Make() Ledger {
return &gcledger{
inner: &smtLedger{
tree: newSMT(hasher, nil),
history: newHistory(),
// keyCache should have ~512kB memory max, each entry is 128 bits = 2^23/2^7 = 2^16
keyCache: byteCache{cache: cache.NewLRU(forever, time.Minute, math.MaxUint16)},
firstObserved: make(map[string][]byte),
},
}
}
// makeOld returns a Ledger which will retain previous nodes after they are deleted.
// the retention parameter has been removed in favor of EraseRootHash, but is left
// here for backwards compatibility
func makeOld(_ time.Duration) Ledger {
return &smtLedger{
tree: newSMT(hasher, nil),
history: newHistory(),
// keyCache should have ~512kB memory max, each entry is 128 bits = 2^23/2^7 = 2^16
keyCache: byteCache{cache: cache.NewLRU(forever, time.Minute, math.MaxUint16)},
firstObserved: make(map[string][]byte),
}
}
func (s *smtLedger) EraseRootHash(rootHash string) error {
s.eraselock.Lock()
defer s.eraselock.Unlock()
// occurrences is a list of every time in (unerased) history when this hash has been observed
occurrences := s.history.Get(rootHash)
if len(occurrences) == 0 {
return fmt.Errorf("rootHash %s is not present in ledger history", rootHash)
}
var adjacentRoots [][]byte
for _, o := range occurrences {
if o.Next() == nil {
return fmt.Errorf("cannot erase current rootHash")
}
var prevVal []byte
if o.Prev() != nil {
prevVal = o.Prev().Value.([]byte)
}
adjacentRoots = append(adjacentRoots, prevVal, o.Next().Value.([]byte))
}
err := s.tree.Erase(occurrences[0].Value.([]byte), adjacentRoots)
if err != nil {
return err
}
s.history.lock.Lock()
for _, o := range occurrences {
s.history.Remove(o)
}
s.history.lock.Unlock()
s.history.Delete(rootHash)
return nil
}
// Put adds a key value pair to the ledger, overwriting previous values and marking them for
// removal after the retention specified in makeOld(). The implementation of Erase depends on
// the value for each key never regressing to old states.
func (s *smtLedger) Put(key, value string) (result string, err error) {
b, err := s.tree.Update([][]byte{s.coerceKeyToHashLen(key)}, [][]byte{stringToBytes(value)})
if err != nil {
return
}
_, result = s.history.Put(b)
return
}
// Delete removes a key value pair from the ledger, marking it for removal after the retention specified in makeOld()
func (s *smtLedger) Delete(key string) (string, error) {
// deletes are the only case where a tree or sub-tree can revert to a previous state.
b, err := s.tree.Delete(s.coerceKeyToHashLen(key))
if err != nil {
return "", err
}
_, res := s.history.Put(b)
return res, nil
}
// GetPreviousValue returns the value of key when the ledger's RootHash was previousHash, if it is still retained.
func (s *smtLedger) GetPreviousValue(previousRootHash, key string) (result string, err error) {
prevBytes, err := base64.StdEncoding.DecodeString(previousRootHash)
if err != nil {
return "", err
}
b, err := s.tree.GetPreviousValue(prevBytes, s.coerceKeyToHashLen(key))
result = string(trimLeadingZeroes(b))
return
}
// Get returns the current value of key.
func (s *smtLedger) Get(key string) (result string, err error) {
return s.GetPreviousValue(s.RootHash(), key)
}
// RootHash represents the hash of the current state of the ledger.
func (s *smtLedger) RootHash() string {
return hashToString(s.tree.Root())
}
func hashToString(h []byte) string {
return base64.StdEncoding.EncodeToString(h)
}
func (s *smtLedger) coerceKeyToHashLen(val string) []byte {
hasher := murmur3.New64()
_, _ = hasher.Write([]byte(val))
result := hasher.Sum(nil)
var h hash
copy(h[:], result)
s.keyCache.Set(h, [][]byte{stringToBytes(val)})
return result
}
func stringToBytes(val string) []byte {
return []byte(val)
}
func trimLeadingZeroes(in []byte) []byte {
var i int
for i = range in {
if in[i] != 0 {
break
}
}
return in[i:]
}
func (s *smtLedger) Stats() cache.Stats {
return s.tree.Stats()
}
func (s *smtLedger) GetAll() (map[string]string, error) {
return s.GetAllPrevious(s.RootHash())
}
func (s *smtLedger) GetAllPrevious(prevRoot string) (map[string]string, error) {
prevBytes, err := base64.StdEncoding.DecodeString(prevRoot)
if err != nil {
return nil, err
}
keys, values, err := s.tree.GetAllPrevious(prevBytes)
result := make(map[string]string)
for i := range keys {
var h hash
copy(h[:], keys[i])
if truekey, ok := s.keyCache.Get(h); ok {
result[string(trimLeadingZeroes(truekey[0]))] = string(trimLeadingZeroes(values[i]))
} else {
err = multierror.Append(err, fmt.Errorf("could not find original value for key %x", keys[i]))
}
}
return result, err
} | ledger/ledger.go | 0.840684 | 0.610076 | ledger.go | starcoder |
package squarestore
import "log"
/*Square represents the SquareStore structure, pointing to its first and last Nodes*/
type Square struct {
first *Node
last *Node
maxroot int64
}
/*Insert allows to insert an element at the end of the structure*/
func (s *Square) Insert(c interface{}) {
var n Node
if s.first == nil {
n.assembleFirst(c)
s.first = &n
s.last = &n
} else {
lastPosition := s.last.position + 1
n.assemble(s.last, s.getLeftNode(lastPosition), s.getDownNode(lastPosition), s.getDDownNode(lastPosition), c)
s.last = &n
}
}
/*Read allows to read the element stored in a given position, except if it is deactivated, in which case nil will be returned*/
func (s *Square) Read(position int64) *Node {
n := s.getNodeAt(position)
if n == nil || n.active == false {
return nil
}
return n
}
/*Activate allows to activate (logically undelete) the element stored in a given position*/
func (s *Square) Activate(position int64) {
s.getNodeAt(position).active = true
}
/*Deactivate allows to deactivate (logically delete) the element stored in a given position*/
func (s *Square) Deactivate(position int64) {
s.getNodeAt(position).active = false
}
func (s *Square) getNodeAt(position int64) *Node {
origin, path, steps, err := s.retrieveBestPath(position)
if err != nil {
log.Fatal(err)
return nil
}
var n *Node
stepSq := steps * steps
stepSqD := steps*steps - steps + 1
if origin == beginning {
n = s.first
if path == xAxis {
for i := int64(0); i < steps; i++ {
n = n.right
}
for i := stepSq + 1; i < position; i++ {
n = n.next
}
} else if path == yAxis {
for i := int64(0); i < steps; i++ {
n = n.up
}
for i := stepSq; i > position; i-- {
n = n.previous
}
} else {
for i := int64(0); i < steps; i++ {
n = n.dUp
}
if position > stepSqD {
for i := stepSqD; i < position; i++ {
n = n.next
}
} else if position < stepSqD {
for i := stepSqD; i > position; i-- {
n = n.previous
}
}
}
} else {
//TODO -> new Path: LAST??
n = s.last
if path == xAxis {
} else if path == yAxis {
} else {
}
}
return n
}
func (s *Square) getLeftNode(position int64) *Node {
if position == 1 {
return nil
}
if b, step := isInXAxis(position); b == true {
return s.getNodeAt(step*step + 1)
}
return nil
}
func (s *Square) getDownNode(position int64) *Node {
if position == 1 {
return nil
}
if b, step := isInYAxis(position); b == true {
s.maxroot = step + 1
return s.getNodeAt(step * step)
}
return nil
}
func (s *Square) getDDownNode(position int64) *Node {
if position == 1 {
return nil
}
if b, step := isInDiagonal(position); b == true {
return s.getNodeAt(step*step - step + 1)
}
return nil
} | square.go | 0.559049 | 0.415966 | square.go | starcoder |
package knadapt
// Chan describes one channel type of sodium-gated adaptation, with a specific
// set of rate constants.
type Chan struct {
On bool `desc:"if On, use this component of K-Na adaptation"`
Rise float32 `viewif:"On" desc:"Rise rate of fast time-scale adaptation as function of Na concentration -- directly multiplies -- 1/rise = tau for rise rate"`
Max float32 `viewif:"On" desc:"Maximum potential conductance of fast K channels -- divide nA biological value by 10 for the normalized units here"`
Tau float32 `viewif:"On" desc:"time constant in cycles for decay of adaptation, which should be milliseconds typically (tau is roughly how long it takes for value to change significantly -- 1.4x the half-life)"`
Dt float32 `view:"-" desc:"1/Tau rate constant"`
}
func (ka *Chan) Defaults() {
ka.On = true
ka.Rise = 0.01
ka.Max = 0.1
ka.Tau = 100
ka.Update()
}
func (ka *Chan) Update() {
ka.Dt = 1 / ka.Tau
}
// GcFmSpike updates the KNa conductance based on spike or not
func (ka *Chan) GcFmSpike(gKNa *float32, spike bool) {
if ka.On {
if spike {
*gKNa += ka.Rise * (ka.Max - *gKNa)
} else {
*gKNa -= ka.Dt * *gKNa
}
} else {
*gKNa = 0
}
}
// GcFmRate updates the KNa conductance based on rate-coded activation.
// act should already have the compensatory rate multiplier prior to calling.
func (ka *Chan) GcFmRate(gKNa *float32, act float32) {
if ka.On {
*gKNa += act*ka.Rise*(ka.Max-*gKNa) - (ka.Dt * *gKNa)
} else {
*gKNa = 0
}
}
// Params describes sodium-gated potassium channel adaptation mechanism.
// Evidence supports at least 3 different time constants:
// M-type (fast), Slick (medium), and Slack (slow)
type Params struct {
On bool `desc:"if On, apply K-Na adaptation"`
Rate float32 `viewif:"On" def:"0.8" desc:"extra multiplier for rate-coded activations on rise factors -- adjust to match discrete spiking"`
Fast Chan `view:"inline" desc:"fast time-scale adaptation"`
Med Chan `view:"inline" desc:"medium time-scale adaptation"`
Slow Chan `view:"inline" desc:"slow time-scale adaptation"`
}
func (ka *Params) Defaults() {
ka.Rate = 0.8
ka.Fast.Defaults()
ka.Med.Defaults()
ka.Slow.Defaults()
ka.Fast.Tau = 50
ka.Fast.Rise = 0.05
ka.Fast.Max = 0.1
ka.Med.Tau = 200
ka.Med.Rise = 0.02
ka.Med.Max = 0.2
ka.Slow.Tau = 1000
ka.Slow.Rise = 0.001
ka.Slow.Max = 0.2
ka.Update()
}
func (ka *Params) Update() {
ka.Fast.Update()
ka.Med.Update()
ka.Slow.Update()
}
// GcFmSpike updates all time scales of KNa adaptation from spiking
func (ka *Params) GcFmSpike(gKNaF, gKNaM, gKNaS *float32, spike bool) {
ka.Fast.GcFmSpike(gKNaF, spike)
ka.Med.GcFmSpike(gKNaM, spike)
ka.Slow.GcFmSpike(gKNaS, spike)
}
// GcFmRate updates all time scales of KNa adaptation from rate code activation
func (ka *Params) GcFmRate(gKNaF, gKNaM, gKNaS *float32, act float32) {
act *= ka.Rate
ka.Fast.GcFmRate(gKNaF, act)
ka.Med.GcFmRate(gKNaM, act)
ka.Slow.GcFmRate(gKNaS, act)
} | knadapt/knadapt.go | 0.856017 | 0.460653 | knadapt.go | starcoder |
package Common
import (
"time"
)
const tmFmtWithMS = "2006-01-02 15:04:05.999"
const tmFmtMissMS = "2006-01-02 15:04:05"
// format a time.Time to string as 2006-01-02 15:04:05.999
func FormatTime(t time.Time) string {
return t.Format(tmFmtWithMS)
}
// format a time.Time to string as 2006-01-02 15:04:05
func FormatTime19(t time.Time) string {
return t.Format(tmFmtMissMS)
}
// format time.Now() use FormatTime
func FormatNow() string {
return FormatTime(time.Now())
}
// format time.Now().UTC() use FormatTime
func FormatUTC() string {
return FormatTime(time.Now().UTC())
}
// parse a string to time.Time
func ParseTime(s string) (time.Time, error) {
if len(s) == len(tmFmtMissMS) {
return time.ParseInLocation(tmFmtMissMS, s, time.Local)
}
return time.ParseInLocation(tmFmtWithMS, s, time.Local)
}
// parse a string as "2006-01-02 15:04:05.999" to time.Time
func ParseTimeUTC(s string) (time.Time, error) {
if len(s) == len(tmFmtMissMS) {
return time.ParseInLocation(tmFmtMissMS, s, time.UTC)
}
return time.ParseInLocation(tmFmtWithMS, s, time.UTC)
}
// format a time.Time to number as 20060102150405999
func NumberTime(t time.Time) uint64 {
y, m, d := t.Date()
h, M, s := t.Clock()
ms := t.Nanosecond() / 1000000
return uint64(ms+s*1000+M*100000+h*10000000+d*1000000000) +
uint64(m)*100000000000 + uint64(y)*10000000000000
}
// format time.Now() use NumberTime
func NumberNow() uint64 {
return NumberTime(time.Now())
}
// format time.Now().UTC() use NumberTime
func NumberUTC() uint64 {
return NumberTime(time.Now().UTC())
}
// parse a uint64 as 20060102150405999 to time.Time
func parseNumber(t uint64, tl *time.Location) (time.Time, error) {
ns := int((t % 1000) * 1000000)
t /= 1000
s := int(t % 100)
t /= 100
M := int(t % 100)
t /= 100
h := int(t % 100)
t /= 100
d := int(t % 100)
t /= 100
m := time.Month(t % 100)
y := int(t / 100)
return time.Date(y, m, d, h, M, s, ns, tl), nil
}
func ParseNumber(t uint64) (time.Time, error) {
return parseNumber(t, time.Local)
}
func ParseNumberUTC(t uint64) (time.Time, error) {
return parseNumber(t, time.UTC)
} | Common/Time.go | 0.737253 | 0.472257 | Time.go | starcoder |
package data
type attributer interface {
track(g *Graph)
}
// Attributable provides functionality for objects that can have attributes.
type attributable struct {
firstAtt uint32
aMap attributeMap // map stores the vertex's attributes by label
}
func (v *attributable) FirstAttribute(g *Graph) *Attribute {
Assert(nilVertex, v != nil)
Assert(nilGraph, g != nil)
Assert(nilAttributeStore, g.attributeStore != nil)
return g.attributeStore.Find(v.firstAtt)
}
// Returns a map of the attributes that belong to the object
// Operations on the returned map will have no effect on persistence
func (v *attributable) Attributes(g *Graph) attributeMap {
Assert (nilVertex, v != nil)
Assert (nilGraph, g != nil)
if v.aMap == nil {
m := make(attributeMap)
a := v.FirstAttribute(g)
for a != nil {
m.add(a, g)
a = a.Next(g)
}
v.aMap = m
}
return v.aMap
}
// Updates or adds an attribute to the vertex.
// This method takes care of tracking any changes to attributes or the vertex to the stores
func (v *attributable) SetAttribute(a *Attribute, g *Graph) {
Assert (nilVertex, v != nil)
Assert (nilGraph, g != nil)
Assert (nilAttributeStore, g.attributeStore != nil)
m := v.Attributes(g)
key, _ := a.Key(g)
if m.hasKey(key) {
// update the existing attribute
currentA, _ := m.get(key)
currentA.t = a.t
currentA.data = a.data
g.attributeStore.Track(currentA)
} else {
// save the new attribute
a.Id = g.attributeStore.nextId()
a.next = v.firstAtt
v.firstAtt = a.Id
m.add(a, g)
g.attributeStore.Track(a)
v.track(g)
}
}
func (v *attributable) RemoveAttribute(a *Attribute, g *Graph) {
Assert(nilVertex, v != nil)
Assert(nilGraph, g != nil)
Assert(nilAttributeStore, g.attributeStore != nil)
Assert(nilVertexStore, g.vertexStore != nil)
m := v.Attributes(g)
if ! m.has(a, g) { // nothing to remove
return
}
if v.firstAtt == a.Id {
v.firstAtt = a.next
v.track(g)
g.attributeStore.Remove(a)
m.remove(a, g)
return
}
for _, attr := range m {
if attr.next == a.Id {
attr.next = a.next
g.attributeStore.Track(attr)
g.attributeStore.Remove(a)
m.remove(a, g)
break
}
}
}
func (v *attributable) RemoveAttributeByKey(key string, g *Graph) {
Assert(nilVertex, v != nil)
m := v.Attributes(g)
a, ok := m.get(key)
if ok {
v.RemoveAttribute(a, g)
}
}
func (v *attributable) track(g *Graph) {
panic("attributable.track() should be overwritten")
} | data/attributable.go | 0.750553 | 0.497192 | attributable.go | starcoder |
package driver
import (
"math"
"github.com/edgexfoundry/go-mod-core-contracts/v2/v2"
"github.com/spf13/cast"
)
// checkValueInRange checks value range is valid
func checkValueInRange(valueType string, reading interface{}) bool {
isValid := false
if valueType == v2.ValueTypeString || valueType == v2.ValueTypeBool {
return true
}
if valueType == v2.ValueTypeInt8 || valueType == v2.ValueTypeInt16 ||
valueType == v2.ValueTypeInt32 || valueType == v2.ValueTypeInt64 {
val := cast.ToInt64(reading)
isValid = checkIntValueRange(valueType, val)
}
if valueType == v2.ValueTypeUint8 || valueType == v2.ValueTypeUint16 ||
valueType == v2.ValueTypeUint32 || valueType == v2.ValueTypeUint64 {
val := cast.ToUint64(reading)
isValid = checkUintValueRange(valueType, val)
}
if valueType == v2.ValueTypeFloat32 || valueType == v2.ValueTypeFloat64 {
val := cast.ToFloat64(reading)
isValid = checkFloatValueRange(valueType, val)
}
return isValid
}
func checkUintValueRange(valueType string, val uint64) bool {
var isValid = false
switch valueType {
case v2.ValueTypeUint8:
if val >= 0 && val <= math.MaxUint8 {
isValid = true
}
case v2.ValueTypeUint16:
if val >= 0 && val <= math.MaxUint16 {
isValid = true
}
case v2.ValueTypeUint32:
if val >= 0 && val <= math.MaxUint32 {
isValid = true
}
case v2.ValueTypeUint64:
maxiMum := uint64(math.MaxUint64)
if val >= 0 && val <= maxiMum {
isValid = true
}
}
return isValid
}
func checkIntValueRange(valueType string, val int64) bool {
var isValid = false
switch valueType {
case v2.ValueTypeInt8:
if val >= math.MinInt8 && val <= math.MaxInt8 {
isValid = true
}
case v2.ValueTypeInt16:
if val >= math.MinInt16 && val <= math.MaxInt16 {
isValid = true
}
case v2.ValueTypeInt32:
if val >= math.MinInt32 && val <= math.MaxInt32 {
isValid = true
}
case v2.ValueTypeInt64:
if val >= math.MinInt64 && val <= math.MaxInt64 {
isValid = true
}
}
return isValid
}
func checkFloatValueRange(valueType string, val float64) bool {
var isValid = false
switch valueType {
case v2.ValueTypeFloat32:
if !math.IsNaN(val) && math.Abs(val) <= math.MaxFloat32 {
isValid = true
}
case v2.ValueTypeFloat64:
if !math.IsNaN(val) && !math.IsInf(val, 0) {
isValid = true
}
}
return isValid
} | internal/driver/readingchecker.go | 0.538255 | 0.474996 | readingchecker.go | starcoder |
package oslice
import "strings"
func New(less func(interface{}, interface{}) bool) *Slice {
return &Slice{less: less}
}
func NewStringSlice() *Slice {
return &Slice{less: func(a, b interface{}) bool {
return a.(string) < b.(string)
}}
}
func NewCaseFoldedSlice() *Slice {
return &Slice{less: func(a, b interface{}) bool {
return strings.ToLower(a.(string)) < strings.ToLower(b.(string))
}}
}
func NewIntSlice() *Slice {
return &Slice{less: func(a, b interface{}) bool {
return a.(int) < b.(int)
}}
}
type Slice struct {
slice []interface{}
less func(interface{}, interface{}) bool
}
func (slice *Slice) Clear() {
slice.slice = nil
}
func (slice *Slice) Add(x interface{}) {
if slice.slice == nil {
slice.slice = []interface{}{x}
} else if index := bisectLeft(slice.slice, slice.less, x);
index == len(slice.slice) {
slice.slice = append(slice.slice, x)
} else { // See Chapter 4's InsertStringSlice for the logic
updatedSlice := make([]interface{}, len(slice.slice)+1)
at := copy(updatedSlice, slice.slice[:index])
at += copy(updatedSlice[at:], []interface{}{x})
copy(updatedSlice[at:], slice.slice[index:])
slice.slice = updatedSlice
}
}
func (slice *Slice) Remove(x interface{}) bool {
index := bisectLeft(slice.slice, slice.less, x)
for ; index < len(slice.slice); index++ {
if !slice.less(slice.slice[index], x) &&
!slice.less(x, slice.slice[index]) {
slice.slice = append(slice.slice[:index],
slice.slice[index+1:]...)
return true
}
}
return false
}
func (slice *Slice) Index(x interface{}) int {
index := bisectLeft(slice.slice, slice.less, x)
if index >= len(slice.slice) ||
slice.less(slice.slice[index], x) ||
slice.less(x, slice.slice[index]) {
return -1
}
return index
}
func (slice *Slice) At(index int) interface{} {
return slice.slice[index]
}
func (slice *Slice) Len() int {
return len(slice.slice)
}
// Return's the index position where x belongs in the slice
func bisectLeft(slice []interface{},
less func(interface{}, interface{}) bool, x interface{}) int {
left, right := 0, len(slice)
for left < right {
middle := int((left + right) / 2)
if less(slice[middle], x) {
left = middle + 1
} else {
right = middle
}
}
return left
} | src/oslice/oslice.go | 0.847999 | 0.613584 | oslice.go | starcoder |
package measurements
import (
"math"
"sync"
)
// SimpleMovingVariance implements a simple moving variance calculation based on the simple moving average.
type SimpleMovingVariance struct {
average *SimpleExponentialMovingAverage
variance *SimpleExponentialMovingAverage
stdev float64 // square root of the estimated variance
normalized float64 // (input - mean) / stdev
mu sync.RWMutex
}
// NewSimpleMovingVariance will create a new exponential moving variance approximation based on the SimpleMovingAverage
func NewSimpleMovingVariance(
alphaAverage float64,
alphaVariance float64,
) (*SimpleMovingVariance, error) {
movingAverage, err := NewSimpleExponentialMovingAverage(alphaAverage)
if err != nil {
return nil, err
}
variance, err := NewSimpleExponentialMovingAverage(alphaVariance)
if err != nil {
return nil, err
}
return &SimpleMovingVariance{
average: movingAverage,
variance: variance,
}, nil
}
// Add a single sample and update the internal state.
// returns true if the internal state was updated, also return the current value.
func (m *SimpleMovingVariance) Add(value float64) (float64, bool) {
m.mu.Lock()
defer m.mu.Unlock()
changed := false
if m.average.seenSamples > 0 {
m.variance.Add(math.Pow(value-m.average.Get(), 2))
}
m.average.Add(value)
mean := m.average.Get()
variance := m.variance.Get()
stdev := math.Sqrt(variance)
normalized := m.normalized
if stdev != 0 {
// edge case
normalized = (value - mean) / stdev
}
if stdev != m.stdev || normalized != m.normalized {
changed = true
}
m.stdev = stdev
m.normalized = normalized
return stdev, changed
}
// Get the current value.
func (m *SimpleMovingVariance) Get() float64 {
m.mu.RLock()
defer m.mu.RUnlock()
return m.variance.Get()
}
// Reset the internal state as if no samples were ever added.
func (m *SimpleMovingVariance) Reset() {
m.mu.Lock()
m.average.Reset()
m.variance.Reset()
m.stdev = 0
m.normalized = 0
m.mu.Unlock()
}
// Update will update the value given an operation function
func (m *SimpleMovingVariance) Update(operation func(value float64) float64) {
m.mu.Lock()
defer m.mu.Unlock()
m.stdev = operation(m.variance.Get())
} | measurements/moving_variance.go | 0.863176 | 0.596227 | moving_variance.go | starcoder |
package pe
import (
"log"
"sync"
"time"
"github.com/gonum/matrix/mat64"
)
/*
physicsengine.go
by <NAME>
Package is geared towards processing physics based information. It's meant to be integrated with TSP for networking purposes.append
Ideally, this package is optimized for quick networking capabilities.
Features:
- Entity Update Processing
- Input Processing
- Entity Add/Delete
- Collision Detection
x Detect Circle - Circle
x Detect Square - Square
x Detect Circle - Square
- Network Events
- Standardize Event Processing Flagging
x Slim down structures for portability
- Create Group in SS with Game Engine
*/
const (
conEventChannelLimit = 10000 //Queue Memory Limit
conForcesChannelLimit = 10000 //Queue Memory Limit
conEntityLimit = 100000 //Initial Memory Map Allocation
//World Bounding Box Coordinates for BroadPhaseQuadTree -- Default
conXA = float64(-100000)
conXB = float64(100000)
conYA = float64(-100000)
conYB = float64(100000)
)
//PhysicsEngine -: data structure
type PhysicsEngine struct {
//Entities
entities map[int]*Entity
//Time
timePreviousStep time.Time
timeCurrentStep time.Time
timeDelta time.Duration
timeDT float64
//Event Management
eventChannel chan *Note //Queue of Notes to process
eventMux *sync.Mutex //Mutex to cut off Channel
//Apply Forces
forcesChannel chan *Note //Queue of Notes to process
} //End PhysicsEngine
//New -: Create a new PhysicsEngine
func New() *PhysicsEngine {
p := new(PhysicsEngine)
//Entities
p.entities = make(map[int]*Entity, conEntityLimit)
//Time Step
p.timePreviousStep = time.Now()
//Event Management
p.eventChannel = make(chan *Note, conEventChannelLimit)
p.eventMux = &sync.Mutex{}
//Apply Forces
p.forcesChannel = make(chan *Note, conForcesChannelLimit)
return p
} // End New()
//Step -: Take a single step in time for simulation
func (p *PhysicsEngine) Step() {
p.PreTime()
p.eventManagement()
p.applyForces()
p.updateEntities()
np := p.collisionHandling()
p.solveConstraints(np)
p.PostTime()
} //End Step()
//---------------------------------------------------------------------
//PreTime -: Run time calculations
func (p *PhysicsEngine) PreTime() {
p.timeCurrentStep = time.Now()
p.timeDelta = p.timeCurrentStep.Sub(p.timePreviousStep)
p.timeDT = p.timeDelta.Seconds()
} //End PreTime()
//PostTime -: Finish time calculations
func (p *PhysicsEngine) PostTime() {
p.timePreviousStep = p.timeCurrentStep
} //End PostTime()
//eventManagement -: Process incoming events
func (p *PhysicsEngine) eventManagement() {
p.eventMux.Lock()
for {
select {
case n := <-p.eventChannel: //Non-blocking Channel
{
if n.From == IDGameEngine {
p.eventGameEngine(n)
} else if n.From == IDClient {
p.eventClient(n)
} else {
continue
}
}
default:
{
p.eventMux.Unlock()
return
}
}
} //End for
} //End eventManagement()
//appleForces -: Update force & torque in all changed entities
func (p *PhysicsEngine) applyForces() {
for {
select {
case n := <-p.forcesChannel: //Non-blocking Channel
{
if n.Flag == FlagUpdateForces {
id := n.Data[0].(int)
f := n.Data[1].(*mat64.Vector)
t := n.Data[2].(float64)
if e, ok := p.entities[id]; ok {
e.ApplyForces(f, t)
} else {
log.Println("WARNING: Bad ID; Entity ID:", id, "does not exist!")
}
} else {
log.Println("WARNING: Bad Flag; ApplyForces Flag:", n.Flag)
continue
}
}
default:
{
return
}
}
} //End for
} //End applyForces
//updateEntities -: Update entities based on forces
func (p *PhysicsEngine) updateEntities() {
for _, e := range p.entities {
e.UpdatePosition(p.timeDT)
e.UpdateRotation(p.timeDT)
} //End for
} //End updateEntities()
//collisionHandling -: Generate Collision Pairs
func (p *PhysicsEngine) collisionHandling() []NarrowPair {
bp := broadphase(p)
np := narrowphase(p, bp)
return np
} //End collisionHandling()
//solveConstraints -:
func (p *PhysicsEngine) solveConstraints(np []NarrowPair) {
//Physics basically says that: For Elastic Collisions, just exchange the Velocity
// vector between the 2 entities Colliding.
// Note: We can add friction/dampening to slow it down.
for i := 0; i < len(np); i++ {
tv := np[i].a.LinearVelocity
np[i].a.LinearVelocity = np[i].b.LinearVelocity
np[i].b.LinearVelocity = tv
} //End for
//This is probably more complicated but it should work for now.
} //End solveConstraints()
//-------------------------------------------------------------------------------
//eventGameEngine -: Process Note from the GameEngine
func (p *PhysicsEngine) eventGameEngine(n *Note) {
switch n.Flag {
case FlagSpawn:
{
}
case FlagKill:
{
}
default:
{
log.Println("WARNING: Bad Note; GameEngine Flag:", n.Flag)
}
} //End Switch
} //End eventGameEngine()
//eventClient -: Process Note from the Client
func (p *PhysicsEngine) eventClient(n *Note) {
switch n.Flag {
case FlagInput:
{
}
default:
{
log.Println("WARNING: Bad Note; GameEngine Flag:", n.Flag)
}
} //End Switch
} //End eventClient() | physicsengine.go | 0.542863 | 0.410638 | physicsengine.go | starcoder |
package cards
type CardSuit byte
const (
Clubs CardSuit = iota
Diamonds
Hearts
Spades
)
type CardValue byte
const (
Ace CardValue = iota
Two
Three
Four
Five
Six
Seven
Eight
Nine
Ten
Jack
Queen
King
)
type Card struct {
Suit CardSuit
Value CardValue
}
type Rectangle struct {
X, Y, Width, Height int
}
var CardImageRectangles = map[Card]Rectangle{
{Suit: Clubs, Value: Ten}: {X: 560, Y: 760, Width: 140, Height: 190},
{Suit: Clubs, Value: Two}: {X: 280, Y: 1140, Width: 140, Height: 190},
{Suit: Clubs, Value: Three}: {X: 700, Y: 190, Width: 140, Height: 190},
{Suit: Clubs, Value: Four}: {X: 700, Y: 0, Width: 140, Height: 190},
{Suit: Clubs, Value: Five}: {X: 560, Y: 1710, Width: 140, Height: 190},
{Suit: Clubs, Value: Six}: {X: 560, Y: 1520, Width: 140, Height: 190},
{Suit: Clubs, Value: Seven}: {X: 560, Y: 1330, Width: 140, Height: 190},
{Suit: Clubs, Value: Eight}: {X: 560, Y: 1140, Width: 140, Height: 190},
{Suit: Clubs, Value: Nine}: {X: 560, Y: 950, Width: 140, Height: 190},
{Suit: Clubs, Value: Ace}: {X: 560, Y: 570, Width: 140, Height: 190},
{Suit: Clubs, Value: Jack}: {X: 560, Y: 380, Width: 140, Height: 190},
{Suit: Clubs, Value: King}: {X: 560, Y: 190, Width: 140, Height: 190},
{Suit: Clubs, Value: Queen}: {X: 560, Y: 0, Width: 140, Height: 190},
{Suit: Diamonds, Value: Ten}: {X: 420, Y: 190, Width: 140, Height: 190},
{Suit: Diamonds, Value: Two}: {X: 420, Y: 1710, Width: 140, Height: 190},
{Suit: Diamonds, Value: Three}: {X: 420, Y: 1520, Width: 140, Height: 190},
{Suit: Diamonds, Value: Four}: {X: 420, Y: 1330, Width: 140, Height: 190},
{Suit: Diamonds, Value: Five}: {X: 420, Y: 1140, Width: 140, Height: 190},
{Suit: Diamonds, Value: Six}: {X: 420, Y: 950, Width: 140, Height: 190},
{Suit: Diamonds, Value: Seven}: {X: 420, Y: 760, Width: 140, Height: 190},
{Suit: Diamonds, Value: Eight}: {X: 420, Y: 570, Width: 140, Height: 190},
{Suit: Diamonds, Value: Nine}: {X: 420, Y: 380, Width: 140, Height: 190},
{Suit: Diamonds, Value: Ace}: {X: 420, Y: 0, Width: 140, Height: 190},
{Suit: Diamonds, Value: Jack}: {X: 280, Y: 1710, Width: 140, Height: 190},
{Suit: Diamonds, Value: King}: {X: 280, Y: 1520, Width: 140, Height: 190},
{Suit: Diamonds, Value: Queen}: {X: 280, Y: 1330, Width: 140, Height: 190},
{Suit: Hearts, Value: Ten}: {X: 140, Y: 1520, Width: 140, Height: 190},
{Suit: Hearts, Value: Two}: {X: 700, Y: 380, Width: 140, Height: 190},
{Suit: Hearts, Value: Three}: {X: 280, Y: 950, Width: 140, Height: 190},
{Suit: Hearts, Value: Four}: {X: 280, Y: 760, Width: 140, Height: 190},
{Suit: Hearts, Value: Five}: {X: 280, Y: 570, Width: 140, Height: 190},
{Suit: Hearts, Value: Six}: {X: 280, Y: 380, Width: 140, Height: 190},
{Suit: Hearts, Value: Seven}: {X: 280, Y: 190, Width: 140, Height: 190},
{Suit: Hearts, Value: Eight}: {X: 280, Y: 0, Width: 140, Height: 190},
{Suit: Hearts, Value: Nine}: {X: 140, Y: 1710, Width: 140, Height: 190},
{Suit: Hearts, Value: Ace}: {X: 140, Y: 1330, Width: 140, Height: 190},
{Suit: Hearts, Value: Jack}: {X: 140, Y: 1140, Width: 140, Height: 190},
{Suit: Hearts, Value: King}: {X: 140, Y: 950, Width: 140, Height: 190},
{Suit: Hearts, Value: Queen}: {X: 140, Y: 760, Width: 140, Height: 190},
{Suit: Spades, Value: Ten}: {X: 0, Y: 60, Width: 140, Height: 190},
{Suit: Spades, Value: Two}: {X: 140, Y: 380, Width: 140, Height: 190},
{Suit: Spades, Value: Three}: {X: 140, Y: 190, Width: 140, Height: 190},
{Suit: Spades, Value: Four}: {X: 140, Y: 0, Width: 140, Height: 190},
{Suit: Spades, Value: Five}: {X: 0, Y: 710, Width: 140, Height: 190},
{Suit: Spades, Value: Six}: {X: 0, Y: 520, Width: 140, Height: 190},
{Suit: Spades, Value: Seven}: {X: 0, Y: 330, Width: 140, Height: 190},
{Suit: Spades, Value: Eight}: {X: 0, Y: 140, Width: 140, Height: 190},
{Suit: Spades, Value: Nine}: {X: 0, Y: 50, Width: 140, Height: 190},
{Suit: Spades, Value: Ace}: {X: 0, Y: 70, Width: 140, Height: 190},
{Suit: Spades, Value: Jack}: {X: 0, Y: 80, Width: 140, Height: 190},
{Suit: Spades, Value: King}: {X: 0, Y: 90, Width: 140, Height: 190},
{Suit: Spades, Value: Queen}: {X: 0, Y: 0, Width: 140, Height: 190},
} | src/cards/cards.go | 0.707 | 0.476823 | cards.go | starcoder |
package bpf
import (
"encoding/binary"
"fmt"
)
func aluOpConstant(ins ALUOpConstant, regA uint32) uint32 {
return aluOpCommon(ins.Op, regA, ins.Val)
}
func aluOpX(ins ALUOpX, regA uint32, regX uint32) (uint32, bool) {
// Guard against division or modulus by zero by terminating
// the program, as the OS BPF VM does
if regX == 0 {
switch ins.Op {
case ALUOpDiv, ALUOpMod:
return 0, false
}
}
return aluOpCommon(ins.Op, regA, regX), true
}
func aluOpCommon(op ALUOp, regA uint32, value uint32) uint32 {
switch op {
case ALUOpAdd:
return regA + value
case ALUOpSub:
return regA - value
case ALUOpMul:
return regA * value
case ALUOpDiv:
// Division by zero not permitted by NewVM and aluOpX checks
return regA / value
case ALUOpOr:
return regA | value
case ALUOpAnd:
return regA & value
case ALUOpShiftLeft:
return regA << value
case ALUOpShiftRight:
return regA >> value
case ALUOpMod:
// Modulus by zero not permitted by NewVM and aluOpX checks
return regA % value
case ALUOpXor:
return regA ^ value
default:
return regA
}
}
func jumpIf(ins JumpIf, value uint32) int {
var ok bool
inV := uint32(ins.Val)
switch ins.Cond {
case JumpEqual:
ok = value == inV
case JumpNotEqual:
ok = value != inV
case JumpGreaterThan:
ok = value > inV
case JumpLessThan:
ok = value < inV
case JumpGreaterOrEqual:
ok = value >= inV
case JumpLessOrEqual:
ok = value <= inV
case JumpBitsSet:
ok = (value & inV) != 0
case JumpBitsNotSet:
ok = (value & inV) == 0
}
if ok {
return int(ins.SkipTrue)
}
return int(ins.SkipFalse)
}
func loadAbsolute(ins LoadAbsolute, in []byte) (uint32, bool) {
offset := int(ins.Off)
size := int(ins.Size)
return loadCommon(in, offset, size)
}
func loadConstant(ins LoadConstant, regA uint32, regX uint32) (uint32, uint32) {
switch ins.Dst {
case RegA:
regA = ins.Val
case RegX:
regX = ins.Val
}
return regA, regX
}
func loadExtension(ins LoadExtension, in []byte) uint32 {
switch ins.Num {
case ExtLen:
return uint32(len(in))
default:
panic(fmt.Sprintf("unimplemented extension: %d", ins.Num))
}
}
func loadIndirect(ins LoadIndirect, in []byte, regX uint32) (uint32, bool) {
offset := int(ins.Off) + int(regX)
size := int(ins.Size)
return loadCommon(in, offset, size)
}
func loadMemShift(ins LoadMemShift, in []byte) (uint32, bool) {
offset := int(ins.Off)
if !inBounds(len(in), offset, 0) {
return 0, false
}
// Mask off high 4 bits and multiply low 4 bits by 4
return uint32(in[offset]&0x0f) * 4, true
}
func inBounds(inLen int, offset int, size int) bool {
return offset+size <= inLen
}
func loadCommon(in []byte, offset int, size int) (uint32, bool) {
if !inBounds(len(in), offset, size) {
return 0, false
}
switch size {
case 1:
return uint32(in[offset]), true
case 2:
return uint32(binary.BigEndian.Uint16(in[offset : offset+size])), true
case 4:
return uint32(binary.BigEndian.Uint32(in[offset : offset+size])), true
default:
panic(fmt.Sprintf("invalid load size: %d", size))
}
}
func loadScratch(ins LoadScratch, regScratch [16]uint32, regA uint32, regX uint32) (uint32, uint32) {
switch ins.Dst {
case RegA:
regA = regScratch[ins.N]
case RegX:
regX = regScratch[ins.N]
}
return regA, regX
}
func storeScratch(ins StoreScratch, regScratch [16]uint32, regA uint32, regX uint32) [16]uint32 {
switch ins.Src {
case RegA:
regScratch[ins.N] = regA
case RegX:
regScratch[ins.N] = regX
}
return regScratch
} | vendor/golang.org/x/net/bpf/vm_instructions.go | 0.667473 | 0.542015 | vm_instructions.go | starcoder |
package storage
import (
"github.com/tiglabs/raft/proto"
)
// Storage is an interface that may be implemented by the application to retrieve log entries from storage.
// If any Storage method returns an error, the raft instance will become inoperable and refuse to participate in elections;
// the application is responsible for cleanup and recovery in this case.
type Storage interface {
// InitialState returns the saved HardState information to init the repl state.
InitialState() (proto.HardState, error)
// Entries returns a slice of log entries in the range [lo,hi), the hi is not inclusive.
// MaxSize limits the total size of the log entries returned, but Entries returns at least one entry if any.
// If lo <= CompactIndex,then return isCompact true.
// If no entries,then return entries nil.
// Note: math.MaxUint32 is no limit.
Entries(lo, hi uint64, maxSize uint64) (entries []*proto.Entry, isCompact bool, err error)
// Term returns the term of entry i, which must be in the range [FirstIndex()-1, LastIndex()].
// The term of the entry before FirstIndex is retained for matching purposes even though the
// rest of that entry may not be available.
// If lo <= CompactIndex,then return isCompact true.
Term(i uint64) (term uint64, isCompact bool, err error)
// FirstIndex returns the index of the first log entry that is possibly available via Entries (older entries have been incorporated
// into the latest Snapshot; if storage only contains the dummy entry the first log entry is not available).
FirstIndex() (uint64, error)
// LastIndex returns the index of the last entry in the log.
LastIndex() (uint64, error)
// StoreEntries store the log entries to the repository.
// If first index of entries > LastIndex,then append all entries,
// Else write entries at first index and truncate the redundant log entries.
StoreEntries(entries []*proto.Entry) error
// StoreHardState store the raft state to the repository.
StoreHardState(st proto.HardState) error
// Truncate the log to index, The index is inclusive.
Truncate(index uint64) error
// Sync snapshot status.
ApplySnapshot(meta proto.SnapshotMeta) error
// Close the storage.
Close()
} | vendor/github.com/tiglabs/raft/storage/storage.go | 0.546496 | 0.407658 | storage.go | starcoder |
package datastore
import (
"io"
"log"
dsq "gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXwimPrM/go-datastore/query"
)
// Here are some basic datastore implementations.
// MapDatastore uses a standard Go map for internal storage.
type MapDatastore struct {
values map[Key][]byte
}
// NewMapDatastore constructs a MapDatastore
func NewMapDatastore() (d *MapDatastore) {
return &MapDatastore{
values: make(map[Key][]byte),
}
}
// Put implements Datastore.Put
func (d *MapDatastore) Put(key Key, value []byte) (err error) {
d.values[key] = value
return nil
}
// Get implements Datastore.Get
func (d *MapDatastore) Get(key Key) (value []byte, err error) {
val, found := d.values[key]
if !found {
return nil, ErrNotFound
}
return val, nil
}
// Has implements Datastore.Has
func (d *MapDatastore) Has(key Key) (exists bool, err error) {
_, found := d.values[key]
return found, nil
}
// GetSize implements Datastore.GetSize
func (d *MapDatastore) GetSize(key Key) (size int, err error) {
if v, found := d.values[key]; found {
return len(v), nil
}
return -1, ErrNotFound
}
// Delete implements Datastore.Delete
func (d *MapDatastore) Delete(key Key) (err error) {
if _, found := d.values[key]; !found {
return ErrNotFound
}
delete(d.values, key)
return nil
}
// Query implements Datastore.Query
func (d *MapDatastore) Query(q dsq.Query) (dsq.Results, error) {
re := make([]dsq.Entry, 0, len(d.values))
for k, v := range d.values {
re = append(re, dsq.Entry{Key: k.String(), Value: v})
}
r := dsq.ResultsWithEntries(q, re)
r = dsq.NaiveQueryApply(q, r)
return r, nil
}
func (d *MapDatastore) Batch() (Batch, error) {
return NewBasicBatch(d), nil
}
func (d *MapDatastore) Close() error {
return nil
}
// NullDatastore stores nothing, but conforms to the API.
// Useful to test with.
type NullDatastore struct {
}
// NewNullDatastore constructs a null datastoe
func NewNullDatastore() *NullDatastore {
return &NullDatastore{}
}
// Put implements Datastore.Put
func (d *NullDatastore) Put(key Key, value []byte) (err error) {
return nil
}
// Get implements Datastore.Get
func (d *NullDatastore) Get(key Key) (value []byte, err error) {
return nil, ErrNotFound
}
// Has implements Datastore.Has
func (d *NullDatastore) Has(key Key) (exists bool, err error) {
return false, nil
}
// Has implements Datastore.GetSize
func (d *NullDatastore) GetSize(key Key) (size int, err error) {
return -1, ErrNotFound
}
// Delete implements Datastore.Delete
func (d *NullDatastore) Delete(key Key) (err error) {
return nil
}
// Query implements Datastore.Query
func (d *NullDatastore) Query(q dsq.Query) (dsq.Results, error) {
return dsq.ResultsWithEntries(q, nil), nil
}
func (d *NullDatastore) Batch() (Batch, error) {
return NewBasicBatch(d), nil
}
func (d *NullDatastore) Close() error {
return nil
}
// LogDatastore logs all accesses through the datastore.
type LogDatastore struct {
Name string
child Datastore
}
// Shim is a datastore which has a child.
type Shim interface {
Datastore
Children() []Datastore
}
// NewLogDatastore constructs a log datastore.
func NewLogDatastore(ds Datastore, name string) *LogDatastore {
if len(name) < 1 {
name = "LogDatastore"
}
return &LogDatastore{Name: name, child: ds}
}
// Children implements Shim
func (d *LogDatastore) Children() []Datastore {
return []Datastore{d.child}
}
// Put implements Datastore.Put
func (d *LogDatastore) Put(key Key, value []byte) (err error) {
log.Printf("%s: Put %s\n", d.Name, key)
// log.Printf("%s: Put %s ```%s```", d.Name, key, value)
return d.child.Put(key, value)
}
// Get implements Datastore.Get
func (d *LogDatastore) Get(key Key) (value []byte, err error) {
log.Printf("%s: Get %s\n", d.Name, key)
return d.child.Get(key)
}
// Has implements Datastore.Has
func (d *LogDatastore) Has(key Key) (exists bool, err error) {
log.Printf("%s: Has %s\n", d.Name, key)
return d.child.Has(key)
}
// GetSize implements Datastore.GetSize
func (d *LogDatastore) GetSize(key Key) (size int, err error) {
log.Printf("%s: GetSize %s\n", d.Name, key)
return d.child.GetSize(key)
}
// Delete implements Datastore.Delete
func (d *LogDatastore) Delete(key Key) (err error) {
log.Printf("%s: Delete %s\n", d.Name, key)
return d.child.Delete(key)
}
// DiskUsage implements the PersistentDatastore interface.
func (d *LogDatastore) DiskUsage() (uint64, error) {
log.Printf("%s: DiskUsage\n", d.Name)
return DiskUsage(d.child)
}
// Query implements Datastore.Query
func (d *LogDatastore) Query(q dsq.Query) (dsq.Results, error) {
log.Printf("%s: Query\n", d.Name)
log.Printf("%s: q.Prefix: %s\n", d.Name, q.Prefix)
log.Printf("%s: q.KeysOnly: %v\n", d.Name, q.KeysOnly)
log.Printf("%s: q.Filters: %d\n", d.Name, len(q.Filters))
log.Printf("%s: q.Orders: %d\n", d.Name, len(q.Orders))
log.Printf("%s: q.Offset: %d\n", d.Name, q.Offset)
return d.child.Query(q)
}
// LogBatch logs all accesses through the batch.
type LogBatch struct {
Name string
child Batch
}
func (d *LogDatastore) Batch() (Batch, error) {
log.Printf("%s: Batch\n", d.Name)
if bds, ok := d.child.(Batching); ok {
b, err := bds.Batch()
if err != nil {
return nil, err
}
return &LogBatch{
Name: d.Name,
child: b,
}, nil
}
return nil, ErrBatchUnsupported
}
// Put implements Batch.Put
func (d *LogBatch) Put(key Key, value []byte) (err error) {
log.Printf("%s: BatchPut %s\n", d.Name, key)
// log.Printf("%s: Put %s ```%s```", d.Name, key, value)
return d.child.Put(key, value)
}
// Delete implements Batch.Delete
func (d *LogBatch) Delete(key Key) (err error) {
log.Printf("%s: BatchDelete %s\n", d.Name, key)
return d.child.Delete(key)
}
// Commit implements Batch.Commit
func (d *LogBatch) Commit() (err error) {
log.Printf("%s: BatchCommit\n", d.Name)
return d.child.Commit()
}
func (d *LogDatastore) Close() error {
log.Printf("%s: Close\n", d.Name)
if cds, ok := d.child.(io.Closer); ok {
return cds.Close()
}
return nil
}
func (d *LogDatastore) Check() error {
if c, ok := d.child.(CheckedDatastore); ok {
return c.Check()
}
return nil
}
func (d *LogDatastore) Scrub() error {
if c, ok := d.child.(ScrubbedDatastore); ok {
return c.Scrub()
}
return nil
}
func (d *LogDatastore) CollectGarbage() error {
if c, ok := d.child.(GCDatastore); ok {
return c.CollectGarbage()
}
return nil
} | vendor/gx/ipfs/Qmf4xQhNomPNhrtZc67qSnfJSjxjXs9LWvknJtSXwimPrM/go-datastore/basic_ds.go | 0.68941 | 0.595757 | basic_ds.go | starcoder |
package matrix
import (
"github.com/mcanalesmayo/jacobi-go/utils"
)
const (
// Hot is the value of a hot state of a cell
Hot = 1.0
// Cold is the value a cold state of a cell
Cold = 0.0
// TwoDimDividedMatrixType is the code to represent a TwoDimMatrix which is not ensured to be contiguous in memory
TwoDimDividedMatrixType = 0
// TwoDimContiguousMatrixType is the code to represent a TwoDimMatrix which is not ensured to be contiguous in memory
TwoDimContiguousMatrixType = 1
// OneDimMatrixType is the code to represent a OneDimMatrix
OneDimMatrixType = 2
)
// MatrixType defines the underlying representation of a matrix
type MatrixType int
// ToString returns a string representation of a matrix
func (matrixType MatrixType) ToString() string {
switch matrixType {
case OneDimMatrixType:
return "One dimension matrix"
case TwoDimDividedMatrixType:
return "Two dimensions matrix (not ensured to be contiguous)"
default:
return "Two dimensions contiguous matrix"
}
}
// Matrix defines a matrix
type Matrix interface {
utils.Stringable
MatrixCloneable
// GetCell retrieves the value in the (i, j) position
GetCell(i, j int) float64
// SetCell updates the value in the (i, j) position
SetCell(i, j int, value float64)
// GetNDim retrieves the length of the matrix
GetNDim() int
}
// Coords defines a 2D square
type Coords struct {
// Top-left corner and bottom-right corner
X0, Y0, X1, Y1 int
}
// MatrixDef defines a submatrix inside a Matrix
type MatrixDef struct {
Coords Coords
// Precomputed matrix size: len(matrix)
Size int
}
// MatrixCloneable represents a matrix that can be cloned
type MatrixCloneable interface {
// Clone returns a Matrix
Clone(matDef MatrixDef) Matrix
}
// CompareMatrices returns true if both matrices contain equal cells or both are nil,
// otherwise returns false
func CompareMatrices(matA, matB Matrix) bool {
matNDim := matA.GetNDim()
if matNDim != matB.GetNDim() {
return false
}
for i := 0; i < matNDim; i++ {
for j := 0; j < matNDim; j++ {
if !utils.CompareFloats(matA.GetCell(i, j), matB.GetCell(i, j), utils.Epsilon) {
return false
}
}
}
return true
} | model/matrix/matrix.go | 0.814016 | 0.714416 | matrix.go | starcoder |
package types
import (
"fmt"
"github.com/DataDrake/csv-analyze/tests"
"io"
"strconv"
"strings"
)
const boolResultFormat = "\tBoolean: True - %v, False - %v \n"
var possibleTrue = []string{"true", "t", "yes", "y"}
var possibleFalse = []string{"false", "f", "no", "n"}
func contains(vals []string, match string) bool {
for _, val := range vals {
if val == match {
return true
}
}
return false
}
// BooleanTest checks if a column contains only boolstamps and identifies their layout
type BooleanTest struct {
trues []string
falses []string
failed bool
}
// NewBooleanTest returns a fresh BooleanTest
func NewBooleanTest() tests.Test {
return &BooleanTest{make([]string, 0), make([]string, 0), false}
}
// Run attempts to convert the current cell to many different bool types
func (t *BooleanTest) Run(cell string) {
if !t.Passed() {
return
}
cell = strings.ToLower(strings.TrimSpace(cell))
for _, match := range possibleTrue {
if cell == match {
if !contains(t.trues, match) {
t.trues = append(t.trues, match)
}
return
}
}
for _, match := range possibleFalse {
if cell == match {
if !contains(t.falses, match) {
t.falses = append(t.falses, match)
}
return
}
}
if v, err := strconv.ParseUint(cell, 10, 64); err == nil {
if v == 0 {
if !contains(t.falses, cell) {
t.falses = append(t.falses, cell)
}
return
}
if v == 1 {
if !contains(t.trues, cell) {
t.trues = append(t.trues, cell)
}
return
}
}
if v, err := strconv.ParseFloat(cell, 64); err == nil {
if v == 0 {
if !contains(t.falses, cell) {
t.falses = append(t.falses, cell)
}
return
}
if v == 1 {
if !contains(t.trues, cell) {
t.trues = append(t.trues, cell)
}
return
}
}
t.failed = true
return
}
// Passed returns true if and only if all entries were bools
func (t *BooleanTest) Passed() bool {
return !t.failed
}
// PrintResult indicates either failure or the detected bool types
func (t *BooleanTest) PrintResult(out io.Writer) {
if !t.Passed() {
fmt.Fprintf(out, boolResultFormat, "fail", "fail")
return
}
fmt.Fprintf(out, boolResultFormat, t.trues, t.falses)
return
} | tests/types/bool.go | 0.560734 | 0.409752 | bool.go | starcoder |
package o
import (
. "github.com/alecthomas/chroma" // nolint
"github.com/alecthomas/chroma/lexers/internal"
)
// Omg Interface Definition Language lexer.
var OmgIdlLexer = internal.Register(MustNewLazyLexer(
&Config{
Name: "OmgIdl",
Aliases: []string{ "omg-idl", },
Filenames: []string{ "*.idl", "*.pidl", },
MimeTypes: []string{ },
},
func() Rules {
return Rules{
"values": {
{ Words(`(?i)`, `\b`, `true`, `false`), LiteralNumber, nil },
{ `([Ll]?)(")`, ByGroups(LiteralStringAffix, LiteralStringDouble), Push("string") },
{ `([Ll]?)(\')(\\[^\']+)(\')`, ByGroups(LiteralStringAffix, LiteralStringChar, LiteralStringEscape, LiteralStringChar), nil },
{ `([Ll]?)(\')(\\\')(\')`, ByGroups(LiteralStringAffix, LiteralStringChar, LiteralStringEscape, LiteralStringChar), nil },
{ `([Ll]?)(\'.\')`, ByGroups(LiteralStringAffix, LiteralStringChar), nil },
{ `[+-]?\d+(\.\d*)?[Ee][+-]?\d+`, LiteralNumberFloat, nil },
{ `[+-]?(\d+\.\d*)|(\d*\.\d+)([Ee][+-]?\d+)?`, LiteralNumberFloat, nil },
{ `(?i)[+-]?0x[0-9a-f]+`, LiteralNumberHex, nil },
{ `[+-]?[1-9]\d*`, LiteralNumberInteger, nil },
{ `[+-]?0[0-7]*`, LiteralNumberOct, nil },
{ `[\+\-\*\/%^&\|~]`, Operator, nil },
{ Words(``, ``, `<<`, `>>`), Operator, nil },
{ `((::)?\w+)+`, Name, nil },
{ `[{};:,<>\[\]]`, Punctuation, nil },
},
"annotation_params": {
Include("whitespace"),
{ `\(`, Punctuation, Push() },
Include("values"),
{ `=`, Punctuation, nil },
{ `\)`, Punctuation, Pop(1) },
},
"annotation_params_maybe": {
{ `\(`, Punctuation, Push("annotation_params") },
Include("whitespace"),
Default(Pop(1)),
},
"annotation_appl": {
{ `@((::)?\w+)+`, NameDecorator, Push("annotation_params_maybe") },
},
"enum": {
Include("whitespace"),
{ `[{,]`, Punctuation, nil },
{ `\w+`, NameConstant, nil },
Include("annotation_appl"),
{ `\}`, Punctuation, Pop(1) },
},
"root": {
Include("whitespace"),
{ Words(`(?i)`, `\b`, `typedef`, `const`, `in`, `out`, `inout`, `local`), KeywordDeclaration, nil },
{ Words(`(?i)`, `\b`, `void`, `any`, `native`, `bitfield`, `unsigned`, `boolean`, `char`, `wchar`, `octet`, `short`, `long`, `int8`, `uint8`, `int16`, `int32`, `int64`, `uint16`, `uint32`, `uint64`, `float`, `double`, `fixed`, `sequence`, `string`, `wstring`, `map`), KeywordType, nil },
{ Words(`(?i)`, `(\s+)(\w+)`, `@annotation`, `struct`, `union`, `bitset`, `interface`, `exception`, `valuetype`, `eventtype`, `component`), ByGroups(Keyword, TextWhitespace, NameClass), nil },
{ Words(`(?i)`, `\b`, `abstract`, `alias`, `attribute`, `case`, `connector`, `consumes`, `context`, `custom`, `default`, `emits`, `factory`, `finder`, `getraises`, `home`, `import`, `manages`, `mirrorport`, `multiple`, `Object`, `oneway`, `primarykey`, `private`, `port`, `porttype`, `provides`, `public`, `publishes`, `raises`, `readonly`, `setraises`, `supports`, `switch`, `truncatable`, `typeid`, `typename`, `typeprefix`, `uses`, `ValueBase`), Keyword, nil },
{ `(?i)(enum|bitmask)(\s+)(\w+)`, ByGroups(Keyword, TextWhitespace, NameClass), Push("enum") },
{ `(?i)(module)(\s+)(\w+)`, ByGroups(KeywordNamespace, TextWhitespace, NameNamespace), nil },
{ `(\w+)(\s*)(=)`, ByGroups(NameConstant, TextWhitespace, Operator), nil },
{ `[\(\)]`, Punctuation, nil },
Include("values"),
Include("annotation_appl"),
},
"keywords": {
{ Words(``, `\b`, `_Alignas`, `_Alignof`, `_Noreturn`, `_Generic`, `_Thread_local`, `_Static_assert`, `_Imaginary`, `noreturn`, `imaginary`, `complex`), Keyword, nil },
{ `(struct|union)(\s+)`, ByGroups(Keyword, Text), Push("classname") },
{ Words(``, `\b`, `asm`, `auto`, `break`, `case`, `const`, `continue`, `default`, `do`, `else`, `enum`, `extern`, `for`, `goto`, `if`, `register`, `restricted`, `return`, `sizeof`, `struct`, `static`, `switch`, `typedef`, `volatile`, `while`, `union`, `thread_local`, `alignas`, `alignof`, `static_assert`, `_Pragma`), Keyword, nil },
{ Words(``, `\b`, `inline`, `_inline`, `__inline`, `naked`, `restrict`, `thread`), KeywordReserved, nil },
{ `(__m(128i|128d|128|64))\b`, KeywordReserved, nil },
{ Words(`__`, `\b`, `asm`, `based`, `except`, `stdcall`, `cdecl`, `fastcall`, `declspec`, `finally`, `try`, `leave`, `w64`, `unaligned`, `raise`, `noop`, `identifier`, `forceinline`, `assume`), KeywordReserved, nil },
},
"types": {
{ Words(``, `\b`, `_Bool`, `_Complex`, `_Atomic`), KeywordType, nil },
{ Words(`__`, `\b`, `int8`, `int16`, `int32`, `int64`, `wchar_t`), KeywordReserved, nil },
{ Words(``, `\b`, `bool`, `int`, `long`, `float`, `short`, `double`, `char`, `unsigned`, `signed`, `void`), KeywordType, nil },
},
"whitespace": {
{ `^#if\s+0`, CommentPreproc, Push("if0") },
{ `^#`, CommentPreproc, Push("macro") },
{ `^(\s*(?:/[*].*?[*]/\s*)?)(#if\s+0)`, ByGroups(UsingSelf("root"), CommentPreproc), Push("if0") },
{ `^(\s*(?:/[*].*?[*]/\s*)?)(#)`, ByGroups(UsingSelf("root"), CommentPreproc), Push("macro") },
{ `\n`, Text, nil },
{ `\s+`, Text, nil },
{ `\\\n`, Text, nil },
{ `//(\n|[\w\W]*?[^\\]\n)`, CommentSingle, nil },
{ `/(\\\n)?[*][\w\W]*?[*](\\\n)?/`, CommentMultiline, nil },
{ `/(\\\n)?[*][\w\W]*`, CommentMultiline, nil },
},
"statements": {
Include("keywords"),
Include("types"),
{ `([LuU]|u8)?(")`, ByGroups(LiteralStringAffix, LiteralString), Push("string") },
{ `([LuU]|u8)?(')(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])(')`, ByGroups(LiteralStringAffix, LiteralStringChar, LiteralStringChar, LiteralStringChar), nil },
{ `0[xX]([0-9a-fA-F](\'?[0-9a-fA-F])*\.[0-9a-fA-F](\'?[0-9a-fA-F])*|\.[0-9a-fA-F](\'?[0-9a-fA-F])*|[0-9a-fA-F](\'?[0-9a-fA-F])*)[pP][+-]?[0-9a-fA-F](\'?[0-9a-fA-F])*[lL]?`, LiteralNumberFloat, nil },
{ `(-)?(\d(\'?\d)*\.\d(\'?\d)*|\.\d(\'?\d)*|\d(\'?\d)*)[eE][+-]?\d(\'?\d)*[fFlL]?`, LiteralNumberFloat, nil },
{ `(-)?((\d(\'?\d)*\.(\d(\'?\d)*)?|\.\d(\'?\d)*)[fFlL]?)|(\d(\'?\d)*[fFlL])`, LiteralNumberFloat, nil },
{ `(-)?0[xX][0-9a-fA-F](\'?[0-9a-fA-F])*(([uU][lL]{0,2})|[lL]{1,2}[uU]?)?`, LiteralNumberHex, nil },
{ `(-)?0[bB][01](\'?[01])*(([uU][lL]{0,2})|[lL]{1,2}[uU]?)?`, LiteralNumberBin, nil },
{ `(-)?0(\'?[0-7])+(([uU][lL]{0,2})|[lL]{1,2}[uU]?)?`, LiteralNumberOct, nil },
{ `(-)?\d(\'?\d)*(([uU][lL]{0,2})|[lL]{1,2}[uU]?)?`, LiteralNumberInteger, nil },
{ `[~!%^&*+=|?:<>/-]`, Operator, nil },
{ `[()\[\],.]`, Punctuation, nil },
{ `(true|false|NULL)\b`, NameBuiltin, nil },
{ `((?:[a-zA-Z_$]|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8})(?:[\w$]|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8})*)(\s*)(:)(?!:)`, ByGroups(NameLabel, Text, Punctuation), nil },
{ `(?:[a-zA-Z_$]|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8})(?:[\w$]|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8})*`, Name, nil },
},
"statement": {
Include("whitespace"),
Include("statements"),
{ `\}`, Punctuation, nil },
{ `[{;]`, Punctuation, Pop(1) },
},
"function": {
Include("whitespace"),
Include("statements"),
{ `;`, Punctuation, nil },
{ `\{`, Punctuation, Push() },
{ `\}`, Punctuation, Pop(1) },
},
"string": {
{ `"`, LiteralString, Pop(1) },
{ `\\([\\abfnrtv"\']|x[a-fA-F0-9]{2,4}|u[a-fA-F0-9]{4}|U[a-fA-F0-9]{8}|[0-7]{1,3})`, LiteralStringEscape, nil },
{ `[^\\"\n]+`, LiteralString, nil },
{ `\\\n`, LiteralString, nil },
{ `\\`, LiteralString, nil },
},
"macro": {
{ `(\s*(?:/[*].*?[*]/\s*)?)(include)(\s*(?:/[*].*?[*]/\s*)?)("[^"]+")([^\n]*)`, ByGroups(UsingSelf("root"), CommentPreproc, UsingSelf("root"), CommentPreprocFile, CommentSingle), nil },
{ `(\s*(?:/[*].*?[*]/\s*)?)(include)(\s*(?:/[*].*?[*]/\s*)?)(<[^>]+>)([^\n]*)`, ByGroups(UsingSelf("root"), CommentPreproc, UsingSelf("root"), CommentPreprocFile, CommentSingle), nil },
{ `[^/\n]+`, CommentPreproc, nil },
{ `/[*](.|\n)*?[*]/`, CommentMultiline, nil },
{ `//.*?\n`, CommentSingle, Pop(1) },
{ `/`, CommentPreproc, nil },
{ `(?<=\\)\n`, CommentPreproc, nil },
{ `\n`, CommentPreproc, Pop(1) },
},
"if0": {
{ `^\s*#if.*?(?<!\\)\n`, CommentPreproc, Push() },
{ `^\s*#el(?:se|if).*\n`, CommentPreproc, Pop(1) },
{ `^\s*#endif.*?(?<!\\)\n`, CommentPreproc, Pop(1) },
{ `.*?\n`, Comment, nil },
},
"classname": {
{ `(?:[a-zA-Z_$]|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8})(?:[\w$]|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8})*`, NameClass, Pop(1) },
{ `\s*(?=>)`, Text, Pop(1) },
Default(Pop(1)),
},
}
},
)) | lexers/o/omg_idl.go | 0.539469 | 0.419053 | omg_idl.go | starcoder |
package messages
import (
util "github.com/IBM/ibmcloud-volume-interface/lib/utils"
)
// messagesEn ...
var messagesEn = map[string]util.Message{
"AuthenticationFailed": {
Code: AuthenticationFailed,
Description: "Failed to authenticate the user.",
Type: util.Unauthenticated,
RC: 400,
Action: "Verify that you entered the correct IBM Cloud user name and password. If the error persists, the authentication service might be unavailable. Wait a few minutes and try again. ",
},
"ErrorRequiredFieldMissing": {
Code: "ErrorRequiredFieldMissing",
Description: "[%s] is required to complete the operation.",
Type: util.InvalidRequest,
RC: 400,
Action: "Review the error that is returned. Provide the missing information in your request and try again. ",
},
"FailedToPlaceOrder": {
Code: "FailedToPlaceOrder",
Description: "Failed to create volume with the storage provider",
Type: util.ProvisioningFailed,
RC: 500,
Action: "Review the error that is returned. If the volume creation service is currently unavailable, try to manually create the volume with the 'ibmcloud is volume-create' command.",
},
"FailedToDeleteVolume": {
Code: "FailedToDeleteVolume",
Description: "The volume ID '%d' could not be deleted from your VPC.",
Type: util.DeletionFailed,
RC: 500,
Action: "Verify that the volume ID exists. Run 'ibmcloud is volumes' to list available volumes in your account. If the ID is correct, try to delete the volume with the 'ibmcloud is volume-delete' command. ",
},
"FailedToExpandVolume": {
Code: "FailedToExpandVolume",
Description: "The volume ID '%d' could not be expanded from your VPC.",
Type: util.ExpansionFailed,
RC: 500,
Action: "Verify that the volume ID exists and attached to an instance. Run 'ibmcloud is volumes' to list available volumes in your account. If the ID is correct, check that expected capacity is valid and supported",
},
"FailedToUpdateVolume": {
Code: "FailedToUpdateVolume",
Description: "The volume ID '%d' could not be updated",
Type: util.UpdateFailed,
RC: 500,
Action: "Verify that the volume ID exists. Run 'ibmcloud is volumes' to list available volumes in your account.",
},
"FailedToDeleteSnapshot": {
Code: "FailedToDeleteSnapshot",
Description: "Failed to delete '%d' snapshot ID",
Type: util.DeletionFailed,
RC: 500,
Action: "Check whether the snapshot ID exists. You may need to verify by using 'ibmcloud is' cli",
},
"StorageFindFailedWithVolumeId": {
Code: "StorageFindFailedWithVolumeId",
Description: "A volume with the specified volume ID '%s' could not be found.",
Type: util.RetrivalFailed,
RC: 404,
Action: "Verify that the volume ID exists. Run 'ibmcloud is volumes' to list available volumes in your account.",
},
"StorageFindFailedWithVolumeName": {
Code: "StorageFindFailedWithVolumeName",
Description: "A volume with the specified volume name '%s' does not exist.",
Type: util.RetrivalFailed,
RC: 404,
Action: "Verify that the specified volume exists. Run 'ibmcloud is volumes' to list available volumes in your account.",
},
"StorageFindFailedWithSnapshotId": {
Code: "StorageFindFailedWithSnapshotId",
Description: "No volume could be found for the specified snapshot ID '%s'. Description: %s",
Type: util.RetrivalFailed,
RC: 400,
Action: "Please check the snapshot ID once, You many need to verify by using 'ibmcloud is' cli.",
},
"VolumeAttachFindFailed": {
Code: VolumeAttachFindFailed,
Description: "No volume attachment could be found for the specified volume ID '%s' and instance ID '%s'.",
Type: util.VolumeAttachFindFailed,
RC: 400,
Action: "Verify that a volume attachment for your instance exists. Run 'ibmcloud is in-vols INSTANCE_ID' to list active volume attachments for your instance ID. ",
},
"VolumeAttachFailed": {
Code: VolumeAttachFailed,
Description: "The volume ID '%s' could not be attached to the instance ID '%s'.",
Type: util.AttachFailed,
RC: 500,
Action: "Verify that the volume ID and instance ID exist. Run 'ibmcloud is volumes' to list available volumes, and 'ibmcloud is instances' to list available instances in your account. ",
},
"VolumeAttachTimedOut": {
Code: VolumeAttachTimedOut,
Description: "The volume ID '%s' could not be attached to the instance ID '%s'",
Type: util.AttachFailed,
RC: 500,
Action: "Verify that the volume ID and instance ID exist. Run 'ibmcloud is volumes' to list available volumes, and 'ibmcloud is instances' to list available instances in your account.",
},
"VolumeDetachFailed": {
Code: VolumeDetachFailed,
Description: "The volumd ID '%s' could not be detached from the instance ID '%s'.",
Type: util.DetachFailed,
RC: 500,
Action: "Verify that the specified instance ID has active volume attachments. Run 'ibmcloud is in-vols INSTANCE_ID' to list active volume attachments for your instance ID. ",
},
"VolumeDetachTimedOut": {
Code: VolumeDetachTimedOut,
Description: "The volume ID '%s' could not be detached from the instance ID '%s'",
Type: util.DetachFailed,
RC: 500,
Action: "Verify that the specified instance ID has active volume attachments. Run 'ibmcloud is in-vols INSTANCE_ID' to list active volume attachments for your instance ID.",
},
"InvalidVolumeID": {
Code: "InvalidVolumeID",
Description: "The specified volume ID '%s' is not valid.",
Type: util.InvalidRequest,
RC: 400,
Action: "Verify that the volume ID exists. Run 'ibmcloud is volumes' to list available volumes in your account.",
},
"InvalidVolumeName": {
Code: "InvalidVolumeName",
Description: "The specified volume name '%s' is not valid. ",
Type: util.InvalidRequest,
RC: 400,
Action: "Verify that the volume name exists. Run 'ibmcloud is volumes' to list available volumes in your account.",
},
"VolumeCapacityInvalid": {
Code: "VolumeCapacityInvalid",
Description: "The specified volume capacity '%d' is not valid. ",
Type: util.InvalidRequest,
RC: 400,
Action: "Verify the specified volume capacity. The volume capacity must be a positive number between 10 GB and 2000 GB. ",
},
"IopsInvalid": {
Code: "IopsInvalid",
Description: "The specified volume IOPS '%s' is not valid for the selected volume profile. ",
Type: util.InvalidRequest,
RC: 400,
Action: "Review available volume profiles and IOPS in the IBM Cloud Block Storage for VPC documentation https://cloud.ibm.com/docs/vpc-on-classic-block-storage?topic=vpc-on-classic-block-storage-block-storage-profiles.",
},
"VolumeProfileIopsInvalid": {
Code: "VolumeProfileIopsInvalid",
Description: "The specified IOPS value is not valid for the selected volume profile. ",
Type: util.InvalidRequest,
RC: 400,
Action: "Review available volume profiles and IOPS in the IBM Cloud Block Storage for VPC documentation https://cloud.ibm.com/docs/vpc-on-classic-block-storage?topic=vpc-on-classic-block-storage-block-storage-profiles.",
},
"EmptyResourceGroup": {
Code: "EmptyResourceGroup",
Description: "Resource group information could not be found.",
Type: util.InvalidRequest,
RC: 400,
Action: "Provide the name or ID of the resource group that you want to use for your volume. Run 'ibmcloud resource groups' to list the resource groups that you have access to. ",
},
"EmptyResourceGroupIDandName": {
Code: "EmptyResourceGroupIDandName",
Description: "Resource group ID or name could not be found.",
Type: util.InvalidRequest,
RC: 400,
Action: "Provide the name or ID of the resource group that you want to use for your volume. Run 'ibmcloud resource groups' to list the resource groups that you have access to.",
},
"SnapshotSpaceOrderFailed": {
Code: "SnapshotSpaceOrderFailed",
Description: "Snapshot space order failed for the given volume ID",
Type: util.ProvisioningFailed,
RC: 500,
Action: "Please check your input",
},
"VolumeNotInValidState": {
Code: "VolumeNotInValidState",
Description: "Volume %s did not get valid (available) status within timeout period.",
Type: util.ProvisioningFailed,
RC: 500,
Action: "Please check your input",
},
"VolumeDeletionInProgress": {
Code: "VolumeDeletionInProgress",
Description: "Volume %s deletion in progress.",
Type: util.ProvisioningFailed,
RC: 500,
Action: "Wait for volume deletion",
},
"ListVolumesFailed": {
Code: "ListVolumesFailed",
Description: "Unable to fetch list of volumes.",
Type: util.RetrivalFailed,
RC: 404,
Action: "Run 'ibmcloud is volumes' to list available volumes in your account.",
},
"InvalidListVolumesLimit": {
Code: "InvalidListVolumesLimit",
Description: "The value '%v' specified in the limit parameter of the list volume call is not valid.",
Type: util.InvalidRequest,
RC: 400,
Action: "Verify the limit parameter's value. The limit must be a positive number between 0 and 100.",
},
"StartVolumeIDNotFound": {
Code: "StartVolumeIDNotFound",
Description: "The volume ID '%s' specified in the start parameter of the list volume call could not be found.",
Type: util.InvalidRequest,
RC: 400,
Action: "Please verify that the start volume ID is correct and whether you have access to the volume ID.",
},
}
// InitMessages ...
func InitMessages() map[string]util.Message {
return messagesEn
} | common/messages/messages_en.go | 0.520009 | 0.467089 | messages_en.go | starcoder |
package interpreter
import (
"errors"
"fmt"
"math"
)
func getArity(fn string) (int, error) {
// minimum arity
if fn == "min" { return 2, nil }
if fn == "max" { return 2, nil }
// exact arity
if fn == "pow" { return 2, nil }
if fn == "abs" { return 1, nil }
if fn == "floor" { return 1, nil }
if fn == "ceil" { return 1, nil }
if fn == "round" { return 1, nil }
if fn == "trunc" { return 1, nil }
if fn == "sqrt" { return 1, nil }
if fn == "sin" { return 1, nil }
if fn == "cos" { return 1, nil }
if fn == "tan" { return 1, nil }
if fn == "asin" { return 1, nil }
if fn == "acos" { return 1, nil }
if fn == "atan" { return 1, nil }
return 0, fmt.Errorf("unknown function: '%s'", fn)
}
func variadicMin(args []float64) (float64, error) {
if len(args) < 2 {
return 0, errors.New("expected at least 2 arguments to 'min'")
}
min := args[0]
for i := 0; i < len(args); i++ {
min = math.Min(min, args[i])
}
return min, nil
}
func variadicMax(args []float64) (float64, error) {
if len(args) < 2 {
return 0, errors.New("expected at least 2 arguments to 'max'")
}
max := args[0]
for i := 0; i < len(args); i++ {
max = math.Max(max, args[i])
}
return max, nil
}
func evaluateFunction(fn string, args []float64) (float64, error) {
if fn == "min" { return variadicMin(args) }
if fn == "max" { return variadicMax(args) }
if fn == "pow" {
if args[0] == 0 && args[1] == 0 { return 1, nil }
return math.Pow(args[0], args[1]), nil
}
if fn == "abs" { return math.Abs(args[0]), nil }
if fn == "floor" { return math.Floor(args[0]), nil }
if fn == "ceil" { return math.Ceil(args[0]), nil }
if fn == "round" { return math.Round(args[0]), nil }
if fn == "trunc" { return math.Trunc(args[0]), nil }
if fn == "sqrt" {
if args[0] < 0 {
return 0, errors.New("expected non-negative argument to 'sqrt'")
}
return math.Sqrt(args[0]), nil
}
if fn == "sin" { return math.Sin(args[0]), nil }
if fn == "cos" { return math.Cos(args[0]), nil }
if fn == "tan" {
if math.Mod(math.Abs(args[0] - (math.Pi / 2)), math.Pi) < 1e-5 {
return 0, errors.New("undefined result of 'tan'")
}
return math.Tan(args[0]), nil
}
if fn == "asin" { return math.Asin(args[0]), nil }
if fn == "acos" { return math.Acos(args[0]), nil }
if fn == "atan" { return math.Atan(args[0]), nil }
return 0, fmt.Errorf("unknown function: '%s'", fn)
}
func evaluateUnaryOp(op string, operand float64) (float64, error) {
if op == "!" {
if operand == 0 { return 1, nil }
return 0, nil
}
if op == "-" {
return -operand, nil
}
return 0, fmt.Errorf("unknown unary operator: '%s'", op)
}
func evaluateBinaryOp(op string, lhs, rhs float64) (float64, error) {
if op == "*" { return lhs * rhs, nil }
if op == "/" {
if rhs == 0 { return 0, errors.New("division by zero encountered") }
return lhs / rhs, nil
}
if op == "%" {
if rhs == 0 { return 0, errors.New("mod by zero encountered") }
return math.Mod(math.Mod(lhs, rhs) + rhs, rhs), nil
}
if op == "+" { return lhs + rhs, nil }
if op == "-" { return lhs - rhs, nil }
if op == "==" {
if lhs == rhs { return 1, nil }
return 0, nil
}
if op == "!=" {
if lhs != rhs { return 1, nil }
return 0, nil
}
if op == "<" {
if lhs < rhs { return 1, nil }
return 0, nil
}
if op == "<=" {
if lhs <= rhs { return 1, nil }
return 0, nil
}
if op == ">" {
if lhs > rhs { return 1, nil }
return 0, nil
}
if op == ">=" {
if lhs >= rhs { return 1, nil }
return 0, nil
}
if op == "||" {
if (lhs != 0) || (rhs != 0) { return 1, nil }
return 0, nil
}
if op == "&&" {
if (lhs != 0) && (rhs != 0) { return 1, nil }
return 0, nil
}
return 0, fmt.Errorf("unknown binary operator: '%s'", op)
} | printerscript/interpreter/utils.go | 0.511473 | 0.406332 | utils.go | starcoder |
package q
import (
"fmt"
"math"
"github.com/itsubaki/q/pkg/math/matrix"
"github.com/itsubaki/q/pkg/math/rand"
"github.com/itsubaki/q/pkg/quantum/gate"
"github.com/itsubaki/q/pkg/quantum/qubit"
)
type Qubit int
func (q Qubit) Index() int {
return int(q)
}
func Index(qb ...Qubit) []int {
index := make([]int, 0)
for i := range qb {
index = append(index, qb[i].Index())
}
return index
}
type Q struct {
internal *qubit.Qubit
Seed []int64
Rand func(seed ...int64) float64
}
func New() *Q {
return &Q{
internal: nil,
Rand: rand.Crypto,
}
}
func (q *Q) New(v ...complex128) Qubit {
if q.internal == nil {
q.internal = qubit.New(v...)
q.internal.Seed = q.Seed
q.internal.Rand = q.Rand
return Qubit(0)
}
q.internal.TensorProduct(qubit.New(v...))
index := q.NumberOfBit() - 1
return Qubit(index)
}
func (q *Q) Zero() Qubit {
return q.New(1, 0)
}
func (q *Q) One() Qubit {
return q.New(0, 1)
}
func (q *Q) ZeroWith(n int) []Qubit {
r := make([]Qubit, 0)
for i := 0; i < n; i++ {
r = append(r, q.Zero())
}
return r
}
func (q *Q) OneWith(n int) []Qubit {
r := make([]Qubit, 0)
for i := 0; i < n; i++ {
r = append(r, q.One())
}
return r
}
func (q *Q) ZeroLog2(N int) []Qubit {
n := int(math.Log2(float64(N))) + 1
return q.ZeroWith(n)
}
func (q *Q) NumberOfBit() int {
return q.internal.NumberOfBit()
}
func (q *Q) Amplitude() []complex128 {
return q.internal.Amplitude()
}
func (q *Q) Probability() []float64 {
return q.internal.Probability()
}
func (q *Q) I(qb ...Qubit) *Q {
return q.Apply(gate.I(), qb...)
}
func (q *Q) H(qb ...Qubit) *Q {
return q.Apply(gate.H(), qb...)
}
func (q *Q) X(qb ...Qubit) *Q {
return q.Apply(gate.X(), qb...)
}
func (q *Q) Y(qb ...Qubit) *Q {
return q.Apply(gate.Y(), qb...)
}
func (q *Q) Z(qb ...Qubit) *Q {
return q.Apply(gate.Z(), qb...)
}
func (q *Q) S(qb ...Qubit) *Q {
return q.Apply(gate.S(), qb...)
}
func (q *Q) T(qb ...Qubit) *Q {
return q.Apply(gate.T(), qb...)
}
func (q *Q) U(alpha, beta, gamma, delta float64, qb ...Qubit) *Q {
return q.Apply(gate.U(alpha, beta, gamma, delta), qb...)
}
func (q *Q) RX(theta float64, qb ...Qubit) *Q {
return q.Apply(gate.RX(theta), qb...)
}
func (q *Q) RY(theta float64, qb ...Qubit) *Q {
return q.Apply(gate.RY(theta), qb...)
}
func (q *Q) RZ(theta float64, qb ...Qubit) *Q {
return q.Apply(gate.RZ(theta), qb...)
}
func (q *Q) Apply(m matrix.Matrix, qb ...Qubit) *Q {
if len(qb) < 1 {
q.internal.Apply(m)
return q
}
index := make(map[int]bool)
for _, i := range Index(qb...) {
index[i] = true
}
g := gate.I()
if _, ok := index[0]; ok {
g = m
}
for i := 1; i < q.NumberOfBit(); i++ {
if _, ok := index[i]; ok {
g = g.TensorProduct(m)
continue
}
g = g.TensorProduct(gate.I())
}
q.internal.Apply(g)
return q
}
func (q *Q) ControlledR(control []Qubit, target Qubit, k int) *Q {
n := q.NumberOfBit()
g := gate.ControlledR(n, Index(control...), target.Index(), k)
q.internal.Apply(g)
return q
}
func (q *Q) CR(control, target Qubit, k int) *Q {
return q.ControlledR([]Qubit{control}, target, k)
}
func (q *Q) ControlledZ(control []Qubit, target Qubit) *Q {
n := q.NumberOfBit()
g := gate.ControlledZ(n, Index(control...), target.Index())
q.internal.Apply(g)
return q
}
func (q *Q) CZ(control, target Qubit) *Q {
return q.ControlledZ([]Qubit{control}, target)
}
func (q *Q) CCZ(control0, control1, target Qubit) *Q {
return q.ControlledZ([]Qubit{control0, control1}, target)
}
func (q *Q) ControlledNot(control []Qubit, target Qubit) *Q {
n := q.NumberOfBit()
g := gate.ControlledNot(n, Index(control...), target.Index())
q.internal.Apply(g)
return q
}
func (q *Q) CNOT(control, target Qubit) *Q {
return q.ControlledNot([]Qubit{control}, target)
}
func (q *Q) CCNOT(control0, control1, target Qubit) *Q {
return q.ControlledNot([]Qubit{control0, control1}, target)
}
func (q *Q) CCCNOT(control0, control1, control2, target Qubit) *Q {
return q.ControlledNot([]Qubit{control0, control1, control2}, target)
}
func (q *Q) Toffoli(control0, control1, target Qubit) *Q {
return q.CCNOT(control0, control1, target)
}
func (q *Q) ConditionX(condition bool, qb ...Qubit) *Q {
if condition {
return q.X(qb...)
}
return q
}
func (q *Q) ConditionZ(condition bool, qb ...Qubit) *Q {
if condition {
return q.Z(qb...)
}
return q
}
func (q *Q) ControlledModExp2(a, j, N int, control Qubit, target []Qubit) *Q {
n := q.NumberOfBit()
g := gate.CModExp2(n, a, j, N, control.Index(), Index(target...))
q.internal.Apply(g)
return q
}
func (q *Q) CModExp2(a, N int, control []Qubit, target []Qubit) *Q {
for i := 0; i < len(control); i++ {
q.ControlledModExp2(a, i, N, control[i], target)
}
return q
}
func (q *Q) Swap(qb ...Qubit) *Q {
n := q.NumberOfBit()
l := len(qb)
for i := 0; i < l/2; i++ {
q0, q1 := qb[i], qb[(l-1)-i]
g := gate.Swap(n, q0.Index(), q1.Index())
q.internal.Apply(g)
}
return q
}
func (q *Q) QFT(qb ...Qubit) *Q {
l := len(qb)
for i := 0; i < l; i++ {
q.H(qb[i])
k := 2
for j := i + 1; j < l; j++ {
q.CR(qb[j], qb[i], k)
k++
}
}
return q
}
func (q *Q) InverseQFT(qb ...Qubit) *Q {
l := len(qb)
for i := l - 1; i > -1; i-- {
k := l - i
for j := l - 1; j > i; j-- {
q.CR(qb[j], qb[i], k)
k--
}
q.H(qb[i])
}
return q
}
func (q *Q) InvQFT(qb ...Qubit) *Q {
return q.InverseQFT(qb...)
}
func (q *Q) Measure(qb ...Qubit) *qubit.Qubit {
if len(qb) < 1 {
m := make([]*qubit.Qubit, 0)
for i := 0; i < q.NumberOfBit(); i++ {
m = append(m, q.internal.Measure(i))
}
return qubit.TensorProduct(m...)
}
m := make([]*qubit.Qubit, 0)
for i := 0; i < len(qb); i++ {
m = append(m, q.internal.Measure(qb[i].Index()))
}
return qubit.TensorProduct(m...)
}
func (q *Q) Clone() *Q {
if q.internal == nil {
return &Q{
internal: nil,
Seed: q.Seed,
Rand: q.Rand,
}
}
return &Q{
internal: q.internal.Clone(),
Seed: q.internal.Seed,
Rand: q.internal.Rand,
}
}
func (q *Q) String() string {
return q.internal.String()
}
func (q *Q) State(reg ...interface{}) []qubit.State {
index := make([][]int, 0)
for _, r := range reg {
switch r := r.(type) {
case Qubit:
index = append(index, []int{r.Index()})
case []Qubit:
index = append(index, Index(r...))
default:
panic(fmt.Sprintf("invalid type %T", r))
}
}
return q.internal.State(index...)
} | q.go | 0.752559 | 0.524577 | q.go | starcoder |
package gocbcore
const (
// Legacy flag format for JSON data.
lfJSON = 0
// Common flags mask
cfMask = 0xFF000000
// Common flags mask for data format
cfFmtMask = 0x0F000000
// Common flags mask for compression mode.
cfCmprMask = 0xE0000000
// Common flag format for sdk-private data.
cfFmtPrivate = 1 << 24 // nolint: deadcode,varcheck,unused
// Common flag format for JSON data.
cfFmtJSON = 2 << 24
// Common flag format for binary data.
cfFmtBinary = 3 << 24
// Common flag format for string data.
cfFmtString = 4 << 24
// Common flags compression for disabled compression.
cfCmprNone = 0 << 29
)
// DataType represents the type of data for a value
type DataType uint32
// CompressionType indicates the type of compression for a value
type CompressionType uint32
const (
// UnknownType indicates the values type is unknown.
UnknownType = DataType(0)
// JSONType indicates the value is JSON data.
JSONType = DataType(1)
// BinaryType indicates the value is binary data.
BinaryType = DataType(2)
// StringType indicates the value is string data.
StringType = DataType(3)
)
const (
// UnknownCompression indicates that the compression type is unknown.
UnknownCompression = CompressionType(0)
// NoCompression indicates that no compression is being used.
NoCompression = CompressionType(1)
)
// EncodeCommonFlags encodes a data type and compression type into a flags
// value using the common flags specification.
func EncodeCommonFlags(valueType DataType, compression CompressionType) uint32 {
var flags uint32
switch valueType {
case JSONType:
flags |= cfFmtJSON
case BinaryType:
flags |= cfFmtBinary
case StringType:
flags |= cfFmtString
case UnknownType:
// flags |= ?
}
switch compression {
case NoCompression:
// flags |= 0
case UnknownCompression:
// flags |= ?
}
return flags
}
// DecodeCommonFlags decodes a flags value into a data type and compression type
// using the common flags specification.
func DecodeCommonFlags(flags uint32) (DataType, CompressionType) {
// Check for legacy flags
if flags&cfMask == 0 {
// Legacy Flags
if flags == lfJSON {
// Legacy JSON
flags = cfFmtJSON
} else {
return UnknownType, UnknownCompression
}
}
valueType := UnknownType
compression := UnknownCompression
if flags&cfFmtMask == cfFmtBinary {
valueType = BinaryType
} else if flags&cfFmtMask == cfFmtString {
valueType = StringType
} else if flags&cfFmtMask == cfFmtJSON {
valueType = JSONType
}
if flags&cfCmprMask == cfCmprNone {
compression = NoCompression
}
return valueType, compression
} | commonflags.go | 0.629319 | 0.524638 | commonflags.go | starcoder |
package margaid
import (
"math"
"strconv"
"time"
"github.com/erkkah/margaid/svg"
)
// Ticker provides tick marks and labels for axes
type Ticker interface {
label(value float64) string
start(axis Axis, series *Series, steps int) float64
next(previous float64) (next float64, hasMore bool)
}
// TimeTicker returns time valued tick labels in the specified time format.
// TimeTicker assumes that time is linear.
func (m *Margaid) TimeTicker(format string) Ticker {
return &timeTicker{m, format, 1}
}
type timeTicker struct {
m *Margaid
format string
step float64
}
func (t *timeTicker) label(value float64) string {
formatted := TimeFromSeconds(value).Format(t.format)
return svg.EncodeText(formatted, svg.HAlignMiddle)
}
func (t *timeTicker) start(axis Axis, _ *Series, steps int) float64 {
minmax := t.m.ranges[axis]
scaleRange := minmax.max - minmax.min
scaleDuration := TimeFromSeconds(scaleRange).Sub(time.Unix(0, 0))
t.step = math.Pow(10.0, math.Trunc(math.Log10(scaleDuration.Seconds()/float64(steps))))
base := t.step
for int(scaleRange/t.step) > steps {
t.step += base
}
durationStep := time.Duration(t.step)
durationStart := time.Duration(minmax.min)
start := (durationStart * time.Second).Truncate(durationStep).Seconds()
if start < minmax.min {
start += t.step
}
return start
}
func (t *timeTicker) next(previous float64) (float64, bool) {
return previous + t.step, true
}
// ValueTicker returns tick labels by converting floats using strconv.FormatFloat
func (m *Margaid) ValueTicker(style byte, precision int, base int) Ticker {
return &valueTicker{
m: m,
step: 1,
style: style,
precision: precision,
base: base,
}
}
type valueTicker struct {
m *Margaid
projection Projection
step float64
style byte
precision int
base int
}
func (t *valueTicker) label(value float64) string {
return strconv.FormatFloat(value, t.style, t.precision, 64)
}
func (t *valueTicker) start(axis Axis, _ *Series, steps int) float64 {
t.projection = t.m.projections[axis]
minmax := t.m.ranges[axis]
scaleRange := minmax.max - minmax.min
startValue := 0.0
floatBase := float64(t.base)
if t.projection == Lin {
roundedLog := math.Round(math.Log(scaleRange/float64(steps)) / math.Log(floatBase))
t.step = math.Pow(floatBase, roundedLog)
base := t.step
for int(scaleRange/t.step) > steps {
t.step += base
}
wholeSteps := math.Ceil(minmax.min / t.step)
startValue = wholeSteps * t.step
return startValue
}
t.step = 0
startValue = math.Pow(floatBase, math.Round(math.Log(minmax.min)/math.Log(floatBase)))
for startValue < minmax.min {
startValue, _ = t.next(startValue)
}
return startValue
}
func (t *valueTicker) next(previous float64) (float64, bool) {
if t.projection == Lin {
return previous + t.step, true
}
floatBase := float64(t.base)
log := math.Log(previous) / math.Log(floatBase)
if log < 0 {
log = -math.Ceil(-log)
} else {
log = math.Floor(log)
}
increment := math.Pow(floatBase, log)
next := previous + increment
next /= increment
next = math.Round(next) * increment
return next, true
}
// LabeledTicker places tick marks and labels for all values
// of a series. The labels are provided by the labeler function.
func (m *Margaid) LabeledTicker(labeler func(float64) string) Ticker {
return &labeledTicker{
labeler: labeler,
}
}
type labeledTicker struct {
labeler func(float64) string
values []float64
index int
}
func (t *labeledTicker) label(value float64) string {
return svg.EncodeText(t.labeler(value), svg.HAlignMiddle)
}
func (t *labeledTicker) start(axis Axis, series *Series, _ int) float64 {
var values []float64
var get func(v Value) float64
if axis == X1Axis || axis == X2Axis {
get = func(v Value) float64 {
return v.X
}
}
if axis == Y1Axis || axis == Y2Axis {
get = func(v Value) float64 {
return v.Y
}
}
v := series.Values()
for v.Next() {
val := v.Get()
values = append(values, get(val))
}
t.values = values
return values[0]
}
func (t *labeledTicker) next(previous float64) (float64, bool) {
// Tickers are not supposed to have state.
// LabeledTicker breaks this, assuming a strict linear calling order.
if previous != t.values[t.index] {
return previous, false
}
t.index++
if t.index < len(t.values) {
return t.values[t.index], true
}
t.index = 0
return 0, false
} | tickers.go | 0.837188 | 0.491944 | tickers.go | starcoder |
package layers
import (
"encoding/binary"
"errors"
"github.com/photostorm/gopacket"
)
// PPP is the layer for PPP encapsulation headers.
type PPP struct {
BaseLayer
PPPType PPPType
HasPPTPHeader bool
}
// PPPEndpoint is a singleton endpoint for PPP. Since there is no actual
// addressing for the two ends of a PPP connection, we use a singleton value
// named 'point' for each endpoint.
var PPPEndpoint = gopacket.NewEndpoint(EndpointPPP, nil)
// PPPFlow is a singleton flow for PPP. Since there is no actual addressing for
// the two ends of a PPP connection, we use a singleton value to represent the
// flow for all PPP connections.
var PPPFlow = gopacket.NewFlow(EndpointPPP, nil, nil)
// LayerType returns LayerTypePPP
func (p *PPP) LayerType() gopacket.LayerType { return LayerTypePPP }
// LinkFlow returns PPPFlow.
func (p *PPP) LinkFlow() gopacket.Flow { return PPPFlow }
func decodePPP(data []byte, p gopacket.PacketBuilder) error {
ppp := &PPP{}
offset := 0
if data[0] == 0xff && data[1] == 0x03 {
offset = 2
ppp.HasPPTPHeader = true
}
if data[offset]&0x1 == 0 {
if data[offset+1]&0x1 == 0 {
return errors.New("PPP has invalid type")
}
ppp.PPPType = PPPType(binary.BigEndian.Uint16(data[offset : offset+2]))
ppp.Contents = data[offset : offset+2]
ppp.Payload = data[offset+2:]
} else {
ppp.PPPType = PPPType(data[offset])
ppp.Contents = data[offset : offset+1]
ppp.Payload = data[offset+1:]
}
p.AddLayer(ppp)
p.SetLinkLayer(ppp)
return p.NextDecoder(ppp.PPPType)
}
// SerializeTo writes the serialized form of this layer into the
// SerializationBuffer, implementing gopacket.SerializableLayer.
// See the docs for gopacket.SerializableLayer for more info.
func (p *PPP) SerializeTo(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error {
if p.PPPType&0x100 == 0 {
bytes, err := b.PrependBytes(2)
if err != nil {
return err
}
binary.BigEndian.PutUint16(bytes, uint16(p.PPPType))
} else {
bytes, err := b.PrependBytes(1)
if err != nil {
return err
}
bytes[0] = uint8(p.PPPType)
}
if p.HasPPTPHeader {
bytes, err := b.PrependBytes(2)
if err != nil {
return err
}
bytes[0] = 0xff
bytes[1] = 0x03
}
return nil
} | layers/ppp.go | 0.645232 | 0.416797 | ppp.go | starcoder |
package decoder
import (
"errors"
"fmt"
"github.com/IvanZagoskin/wkt/geometry"
"github.com/IvanZagoskin/wkt/parser"
"github.com/golang/geo/s2"
"io"
)
type Decoder struct {
parser *parser.Parser
}
func GeomString(g geometry.Type) string {
switch g {
case geometry.UndefinedGT: return "Undefined"
case geometry.PointGT: return "Point"
case geometry.MultyPointGT: return "Multipoint"
case geometry.LineStringGT: return "Linestring"
case geometry.CircularStringGT: return "CircularLinestring"
case geometry.MultiLineStringGT: return "MultiLineString"
case geometry.PolygonGT: return "Polygon"
case geometry.MultiPolygonGT: return "MultiPolygon"
default:
return fmt.Sprintf("%d", int(g))
}
}
func asS2LatLngs(points []*geometry.Point) []s2.LatLng {
xs := make([]s2.LatLng, len(points))
for i, p := range points {
xs[i] = s2.LatLngFromDegrees(p.Y, p.X)
}
return xs
}
func asS2Points(points []*geometry.Point) []s2.Point {
xs := make([]s2.Point, len(points))
for i, p := range points {
xs[i] = s2.PointFromLatLng(s2.LatLngFromDegrees(p.Y, p.X))
}
return xs
}
func asS2Polygon(lines []*geometry.LineString) *s2.Polygon {
loops := make([]*s2.Loop, len(lines))
for i, ls := range lines {
loops[i] = s2.LoopFromPoints(asS2Points(ls.Points))
}
return s2.PolygonFromLoops(loops)
}
func (d *Decoder) ParsePoint(r io.Reader) (s2.Point, error) {
g, err := d.ParseWKT(r)
if err != nil {
return s2.Point{}, err
}
if x, ok := g.(s2.Point); ok {
return x, nil
}
return s2.Point{}, errors.New("cast error")
}
func (d *Decoder) ParseLinestring(r io.Reader) (*s2.Polyline, error) {
g, err := d.ParseWKT(r)
if err != nil {
return nil, err
}
if x, ok := g.(*s2.Polyline); ok {
return x, nil
}
return nil, errors.New("cast error")
}
func (d *Decoder) ParsePolygon(r io.Reader) (*s2.Polygon, error) {
g, err := d.ParseWKT(r)
if err != nil {
return nil, err
}
if x, ok := g.(*s2.Polygon); ok {
return x, nil
}
return nil, errors.New("cast error")
}
func (d *Decoder) ParseMultiPoint(r io.Reader) ([]s2.Point, error) {
g, err := d.ParseWKT(r)
if err != nil {
return nil, err
}
if x, ok := g.([]s2.Point); ok {
return x, nil
}
return nil, errors.New("cast error")
}
func (d *Decoder) ParseMultiLinestring(r io.Reader) ([]s2.Polyline, error) {
g, err := d.ParseWKT(r)
if err != nil {
return nil, err
}
if x, ok := g.([]s2.Polyline); ok {
return x, nil
}
return nil, errors.New("cast error")
}
func (d *Decoder) ParseMultiPolygon(r io.Reader) ([]s2.Polygon, error) {
g, err := d.ParseWKT(r)
if err != nil {
return nil, err
}
if x, ok := g.([]s2.Polygon); ok {
return x, nil
}
return nil, errors.New("cast error")
}
func (d *Decoder) ParseWKT(r io.Reader) (interface{}, error) {
if r == nil {
return nil, fmt.Errorf("cannot parse nil as wkt")
}
g, err := d.parser.ParseWKT(r)
if err != nil {
return nil, err
}
switch geom := g.(type) {
case *geometry.Point:
return s2.PointFromLatLng(s2.LatLngFromDegrees(geom.X, geom.Y)), nil
case *geometry.LineString:
return s2.PolylineFromLatLngs(asS2LatLngs(geom.Points)), nil
case *geometry.Polygon:
return asS2Polygon(geom.LineStrings), nil
case *geometry.MultiPoint:
return asS2Points(geom.Points), nil
case *geometry.MultiLineString:
lines := make([]s2.Polyline, len(geom.Lines))
for i, ls := range geom.Lines {
lines[i] = *s2.PolylineFromLatLngs(asS2LatLngs(ls.Points))
}
return lines, nil
case *geometry.MultiPolygon:
polygons := make([]s2.Polygon, len(geom.Polygons))
for i, p := range geom.Polygons {
polygons[i] = *asS2Polygon(p.LineStrings)
}
return polygons, nil
default:
return nil, fmt.Errorf("unimplemented geometry type: %s", GeomString(g.GetGeometryType()))
}
}
func New() Decoder {
return Decoder{
parser: parser.New(),
}
} | decoder.go | 0.758242 | 0.594816 | decoder.go | starcoder |
package dbkit
import (
"fmt"
"sort"
"strings"
)
// DataType represents the various data types allowed for table columns
type DataType int
const (
// DataTypeAutoID maps to an auto increment id or closest matching construct in the database. A table can only have one AutoID columns and it must be the only column in the primary key.
DataTypeAutoID DataType = iota
// DataTypeInt64 is a 64bit integer value
DataTypeInt64
// DataTypeInt32 is a 32bit integer value
DataTypeInt32
// DataTypeFloat64 is a 64bit floating-point number
DataTypeFloat64
// DataTypeString is a string value
DataTypeString
// DataTypeTime is a time value (date+time)
DataTypeTime
// DataTypeDate is a date value (date)
DataTypeDate
// DataTypeBytes is a bytes value ([]byte)
DataTypeBytes
// DataTypeBool is a boolean value
DataTypeBool
// DataTypeTimeUUID is a TimeUUID value
DataTypeTimeUUID
// DataTypeTimeUUID is a UUID value
DataTypeUUID
// DataTypeJSON is a JSON value
DataTypeJSON
)
// Schema represents a database schema
type Schema struct {
PackageName string
Tables map[string]*Table
}
// Validate returns a list of validation errors from the schema
func (s *Schema) Validate(generators []generator) []error {
errors := make([]error, 0, 0)
for _, t := range s.Tables {
e := t.Validate(generators)
errors = append(errors, e...)
}
for _, g := range generators {
errors = append(errors, g.validate(s)...)
}
return errors
}
func (s *Schema) SortedTables() []*Table {
result := make([]*Table, 0, len(s.Tables))
for _, t := range s.Tables {
result = append(result, t)
}
sort.Sort(byName(result))
return result
}
type byName []*Table
func (s byName) Len() int {
return len(s)
}
func (s byName) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s byName) Less(i, j int) bool {
return s[i].DBTableName < s[j].DBTableName
}
// NewSchema creates a new schema
func NewSchema(packageName string) *Schema {
return &Schema{
PackageName: packageName,
Tables: make(map[string]*Table),
}
}
// ExtraField represents an extra go field added to the
// generated struct for a given table
type ExtraField struct {
Name string
GoTypeName string
Import string
}
// Table represents a table in a database schema
type Table struct {
DBTableName string
GoTableName string
GoLowerTableName string
StructName string
LowerStructName string
Columns []*Column
ExtraFields []*ExtraField
Indexes map[string]*Index
PrimaryIndex *Index
Logging bool
}
// Validate returns a list of validation errors from the table
func (t *Table) Validate(generators []generator) []error {
errors := make([]error, 0, 0)
// ensure primary index exists with at least one column
if t.PrimaryIndex == nil {
errors = append(errors, fmt.Errorf(t.DBTableName+": does not have a primary index"))
} else if len(t.PrimaryIndex.Columns) == 0 {
errors = append(errors, fmt.Errorf(t.DBTableName+": the primary index must have at least one column"))
}
// only one AutoID column
autoColCount := 0
for _, col := range t.Columns {
if col.Type == DataTypeAutoID {
autoColCount++
}
}
if (autoColCount == 1 && (t.PrimaryIndex != nil && (len(t.PrimaryIndex.Columns) != 1 || t.PrimaryIndex.Columns[0].Type != DataTypeAutoID))) || autoColCount > 1 {
errors = append(errors, fmt.Errorf(t.DBTableName+": a table can only have one AutoID column, and it must be the only column in the primary index."))
}
return errors
}
// NonAutoIDColumns builds a slice of columns that aren't of type AutoID
func (t *Table) NonAutoIDColumns() []*Column {
arr := make([]*Column, 0, len(t.Columns))
for _, c := range t.Columns {
if c.Type != DataTypeAutoID {
arr = append(arr, c)
}
}
return arr
}
// AutoIDColumn returns the AutoID column of the table (if any)
func (t *Table) AutoIDColumn() *Column {
for _, c := range t.Columns {
if c.Type == DataTypeAutoID {
return c
}
}
return nil
}
// IndexCombination is a column combinations suitable for index lookup.
type IndexCombination struct {
Name string
FuncArgs string
CallArgs string
Columns []*Column
Table Table
}
// IndexCombinations builds a list of column combinations suitable for index lookups.
func (t *Table) IndexCombinations() []*IndexCombination {
used := make(map[string]bool)
arr := make([]*IndexCombination, 0, 0)
for _, key := range sortedKeys(t.Indexes) {
index := t.Indexes[key]
for ix := range index.Columns {
combination := makeIndexCombination(index.Columns[:ix+1], *t)
if _, found := used[combination.Name]; !found {
arr = append(arr, combination)
used[combination.Name] = true
}
}
}
return arr
}
func sortedKeys(m map[string]*Index) []string {
result := make([]string, 0, len(m))
for k := range m {
result = append(result, k)
}
sort.Strings(result)
return result
}
func makeIndexCombination(columns []*Column, table Table) *IndexCombination {
combination := &IndexCombination{Columns: make([]*Column, 0, 0)}
for _, col := range columns {
combination.Columns = append(combination.Columns, col)
combination.Table = table
// build name
if combination.Name != "" {
combination.Name += "And"
}
combination.Name += col.GoName
// build funcargs
if combination.FuncArgs != "" {
combination.FuncArgs += ", "
}
combination.FuncArgs += col.GoLowerName + " " + col.GoType()
// build callargs
if combination.CallArgs != "" {
combination.CallArgs += ", "
}
combination.CallArgs += col.GoLowerName
}
return combination
}
// Index represents an index in a database table
type Index struct {
IsPrimary bool
Name string
Columns []*Column
Table *Table
}
// Column represents a column in a database table
type Column struct {
DBName string
GoName string
GoLowerName string
Type DataType
Nullable bool
}
// GoType returns the go typename as a string
func (c *Column) GoType() string {
prefix := ""
if c.Nullable {
prefix = "*"
}
switch c.Type {
case DataTypeAutoID:
return prefix + "int64"
case DataTypeInt64:
return prefix + "int64"
case DataTypeFloat64:
return prefix + "float64"
case DataTypeString:
return prefix + "string"
case DataTypeTime:
return prefix + "time.Time"
case DataTypeDate:
return prefix + "time.Time"
case DataTypeBytes:
return "[]byte"
case DataTypeBool:
return prefix + "bool"
case DataTypeInt32:
return prefix + "int32"
case DataTypeTimeUUID:
return "gocql.UUID"
case DataTypeUUID:
return "uuid.UUID"
case DataTypeJSON:
return "json.RawMessage"
default:
panic(fmt.Sprintf("don't know go type for: %v", c.Type))
}
}
// NewTable creates a new table in the schema
func (s *Schema) NewTable(dbTableName string, goTableName string, structName string) *Table {
t := &Table{}
t.DBTableName = dbTableName
t.GoTableName = goTableName
t.GoLowerTableName = strings.ToLower(goTableName[0:1]) + goTableName[1:]
t.StructName = structName
t.LowerStructName = strings.ToLower(structName[0:1]) + structName[1:]
t.Columns = make([]*Column, 0, 10)
t.Indexes = make(map[string]*Index)
s.Tables[dbTableName] = t
return t
}
// AddColumn adds a colum to the table
func (t *Table) AddColumn(dbName string, goName string, dataType DataType, nullable bool) {
goNameLower := strings.ToLower(goName[0:1]) + goName[1:]
if goNameLower == "iD" {
goNameLower = "id"
}
if goNameLower == "oS" {
goNameLower = "os"
}
if goNameLower == "type" {
goNameLower = "_type"
}
t.Columns = append(t.Columns, &Column{
DBName: dbName,
GoName: goName,
GoLowerName: goNameLower,
Type: dataType,
Nullable: nullable,
})
}
// SetPrimaryIndex sets the primary index on the table
func (t *Table) SetPrimaryIndex(columns ...string) {
t.PrimaryIndex = t.AddIndex("__primary__", columns...)
}
// AddIndex adds the index to the table
func (t *Table) AddIndex(name string, columns ...string) *Index {
index := &Index{Table: t}
index.Name = name
index.Columns = make([]*Column, 0, 0)
for _, n := range columns {
foundCol := t.GetColumn(n)
if foundCol == nil {
panic("could not find column " + n + " in table " + t.DBTableName)
}
index.Columns = append(index.Columns, foundCol)
}
t.Indexes[index.Name] = index
return index
}
// GetColumn gets the specified column
func (t *Table) GetColumn(name string) *Column {
for _, pc := range t.Columns {
if pc.DBName == name {
return pc
}
}
return nil
} | dbkit/schema.go | 0.657209 | 0.530541 | schema.go | starcoder |
package datastore
import "errors"
// Query is a query used to search for and return entities from a datastore
type Query interface {
// Execute performs the query and returns an Results to the results. For now this query is specific to the
// underlying Connection and Driver implementation.
Execute(query interface{}) (Results, error)
}
// NewQuery returns a Query type to be executed
func NewQuery(ctx Context) Query {
return &query{ctx}
}
// ErrNoSuchElement if requested element not available
var ErrNoSuchElement = errors.New("no such element")
// Results iterates or indexes into the results returned from a query
type Results interface {
// Next retrieves the next available result into entity and advances the Results to the next available entity.
// ErrNoSuchElement is returned if no more results.
Next(entity ValidEntity) error
// HasNext returns true if a call to next would yield a value or false if no more entities are available
HasNext() bool
//Len return the length of the results
Len() int
//Len return the length of the results
Get(idx int, entity ValidEntity) error
}
type query struct {
ctx Context
}
func (q *query) Execute(query interface{}) (Results, error) {
ctx := q.ctx
conn, err := ctx.Connection()
if err != nil {
return nil, err
}
results, err := conn.Query(query)
if err != nil {
return nil, err
}
return newResults(results), nil
}
type results struct {
data []JSONMessage
idx int
}
func (r *results) Len() int {
return len(r.data)
}
func (r *results) Get(idx int, entity ValidEntity) error {
if idx >= len(r.data) {
return ErrNoSuchElement
}
v := r.data[idx]
if err := SafeUnmarshal(v.Bytes(), entity); err != nil {
return err
}
entity.SetDatabaseVersion(v.Version())
return nil
}
func (r *results) Next(entity ValidEntity) error {
if !r.HasNext() {
return ErrNoSuchElement
}
v := r.data[r.idx]
r.idx = r.idx + 1
if err := SafeUnmarshal(v.Bytes(), entity); err != nil {
return err
}
entity.SetDatabaseVersion(v.Version())
return nil
}
func (r *results) HasNext() bool {
return r.idx < len(r.data)
}
func newResults(data []JSONMessage) Results {
return &results{data, 0}
} | datastore/query.go | 0.787686 | 0.402099 | query.go | starcoder |
package channel
import (
"fmt"
"gitlab.com/gomidi/midi/internal/midilib"
)
// NoteOffVelocity is offered as an alternative to NoteOff for
// a "real" noteoff message (type 8) that has velocity.
type NoteOffVelocity struct {
NoteOff
velocity uint8
}
// Velocity returns the velocity of the note-off message
func (n NoteOffVelocity) Velocity() uint8 {
return n.velocity
}
// set returns a new note-off message with velocity that is set to the parsed arguments
func (NoteOffVelocity) set(channel uint8, arg1, arg2 uint8) setter2 {
var n NoteOffVelocity
n.channel = channel
n.key, n.velocity = midilib.ParseTwoUint7(arg1, arg2)
return n
}
// Raw returns the bytes for the noteoff message.
// Since NoteOff.Raw() returns in fact a noteon message (type 9) with velocity of 0 to allow running status,
// NoteOffPedantic.Raw() is offered as an alternative to make sure a "real" noteoff message (type 8) is returned.
func (n NoteOffVelocity) Raw() []byte {
return channelMessage2(n.channel, 8, n.key, n.velocity)
}
// String returns human readable information about the note-off message that includes velocity.
func (n NoteOffVelocity) String() string {
return fmt.Sprintf("%T channel %v key %v velocity %v", n, n.Channel(), n.Key(), n.Velocity())
}
// NoteOff represents a note-off message by a note-on message with velocity of 0 (helps for running status).
// This is the normal way to go. If you need the velocity of a note-off message, use NoteOffVelocity.
type NoteOff struct {
channel uint8
key uint8
}
// Key returns the key of the note off message
func (n NoteOff) Key() uint8 {
return n.key
}
// Raw returns the bytes for the noteoff message.
// To allowing running status, here the bytes for a noteon message (type 9) with velocity = 0 are returned.
// If you need a "real" noteoff message, call NoteOffPedantic.Raw()
func (n NoteOff) Raw() []byte {
return channelMessage2(n.channel, 9, n.key, 0)
}
// Channel returns the channel of the note-off message
func (n NoteOff) Channel() uint8 {
return n.channel
}
// String returns human readable information about the note-off message.
func (n NoteOff) String() string {
return fmt.Sprintf("%T channel %v key %v", n, n.Channel(), n.Key())
}
// set returns a new note-off message that is set to the parsed arguments
func (NoteOff) set(channel uint8, arg1, arg2 uint8) setter2 {
var n NoteOff
n.channel = channel
n.key, _ = midilib.ParseTwoUint7(arg1, arg2)
return n
} | midimessage/channel/noteoff.go | 0.840913 | 0.404155 | noteoff.go | starcoder |
package iso20022
// Chain of parties involved in the settlement of a transaction, including receipts and deliveries, book transfers, treasury deals, or other activities, resulting in the movement of a security or amount of money from one account to another.
type ReceivingPartiesAndAccount1 struct {
// Party that buys goods or services, or a financial instrument.
ReceiverDetails *InvestmentAccount11 `xml:"RcvrDtls"`
// Party that acts on behalf of the buyer of securities when the buyer does not have a direct relationship with the receiving agent.
ReceiversCustodianDetails *PartyIdentificationAndAccount2 `xml:"RcvrsCtdnDtls,omitempty"`
// Party that the Receiver's custodian uses to effect the receipt of a security, when the Receiver's custodian does not have a direct relationship with the Receiver agent.
ReceiversIntermediaryDetails *PartyIdentificationAndAccount2 `xml:"RcvrsIntrmyDtls,omitempty"`
// Party that receives securities from the delivering agent via the place of settlement, eg, securities central depository.
ReceivingAgentDetails *PartyIdentificationAndAccount2 `xml:"RcvgAgtDtls"`
// Identifies the securities settlement system to be used.
SecuritiesSettlementSystem *Max35Text `xml:"SctiesSttlmSys,omitempty"`
// Place where settlement of the securities takes place.
PlaceOfSettlementDetails *PartyIdentificationAndAccount2 `xml:"PlcOfSttlmDtls"`
}
func (r *ReceivingPartiesAndAccount1) AddReceiverDetails() *InvestmentAccount11 {
r.ReceiverDetails = new(InvestmentAccount11)
return r.ReceiverDetails
}
func (r *ReceivingPartiesAndAccount1) AddReceiversCustodianDetails() *PartyIdentificationAndAccount2 {
r.ReceiversCustodianDetails = new(PartyIdentificationAndAccount2)
return r.ReceiversCustodianDetails
}
func (r *ReceivingPartiesAndAccount1) AddReceiversIntermediaryDetails() *PartyIdentificationAndAccount2 {
r.ReceiversIntermediaryDetails = new(PartyIdentificationAndAccount2)
return r.ReceiversIntermediaryDetails
}
func (r *ReceivingPartiesAndAccount1) AddReceivingAgentDetails() *PartyIdentificationAndAccount2 {
r.ReceivingAgentDetails = new(PartyIdentificationAndAccount2)
return r.ReceivingAgentDetails
}
func (r *ReceivingPartiesAndAccount1) SetSecuritiesSettlementSystem(value string) {
r.SecuritiesSettlementSystem = (*Max35Text)(&value)
}
func (r *ReceivingPartiesAndAccount1) AddPlaceOfSettlementDetails() *PartyIdentificationAndAccount2 {
r.PlaceOfSettlementDetails = new(PartyIdentificationAndAccount2)
return r.PlaceOfSettlementDetails
} | ReceivingPartiesAndAccount1.go | 0.654784 | 0.485295 | ReceivingPartiesAndAccount1.go | starcoder |
package transform
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"strconv"
"strings"
"github.com/Jeffail/gabs"
)
var truncationLength = 512
// InputToCommands reads from the given io.Reader (e.g. os.Stdin) and uses the
// data there to replace values like $1.uuid in the args. It returns a
// [][]string which is a set of rows, each with a slice of string values.
func InputToCommands(r io.Reader, args []string, explodeArrays bool) ([][]string, error) {
data, err := readData(r, explodeArrays)
if err != nil {
return nil, err
}
if len(data) == 0 {
return [][]string{args}, nil
}
cmds := make([][]string, len(data))
for rowI := range data {
cmds[rowI] = make([]string, len(args))
for argI := range args {
cmds[rowI][argI] = transform(data[rowI], args[argI])
}
}
return cmds, nil
}
// readData reads all data from the given reader and splits it into a
// [][]string: a slice of commands, each command having multiple positional
// arguments. If explodeArrays is true, arrays are treated as if they were
// simply given as a list of newline separated JSON objects.
func readData(r io.Reader, explodeArrays bool) ([][]string, error) {
var data [][]string
ProcessLoop:
dec := json.NewDecoder(r)
for dec.More() {
var m interface{}
err := dec.Decode(&m)
if err != nil {
if err == io.EOF {
break
}
switch err.(type) {
case *json.SyntaxError:
// Allow parsing as a string.
default:
return nil, err
}
}
switch raw := m.(type) {
case []interface{}:
if explodeArrays {
for _, obj := range raw {
jsonObj, ok := obj.(map[string]interface{})
if !ok {
return nil, errors.New("invalid piped data")
}
b, err := json.Marshal(jsonObj)
if err != nil {
return nil, err
}
// Every value gets appened in its own row.
data = append(data, []string{string(b)})
}
} else {
b, err := json.Marshal(raw)
if err != nil {
return nil, err
}
data = append(data, []string{string(b)})
}
case map[string]interface{}:
b, err := json.Marshal(raw)
if err != nil {
return nil, err
}
// Every value gets appened in its own row.
data = append(data, []string{string(b)})
case nil:
// Failed to parse as JSON; parse as a word.
subR := dec.Buffered()
scanner := bufio.NewScanner(subR)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
data = append(data, []string{scanner.Text()})
}
if err := scanner.Err(); err != nil {
log.Fatalf("reading standard input: %v", err)
}
// Restart the process loop with what is rest of the buffered data.
// Use a multireader so that if the original decoder didn't buffer
// it all we don't lose data.
r = io.MultiReader(subR, r)
goto ProcessLoop
default:
return nil, fmt.Errorf("unexpected type (%T): %v", raw, truncatedValue(raw))
}
}
return data, nil
}
// transform uses the data to transform the argument (e.g. foo $1.uuid -> foo
// uuid)
func transform(data []string, arg string) string {
return os.Expand(arg, dataLookup(data))
}
// dataLookup generates closures which lookup transformation values ($1.uuid)
// and returns their values based on the data passed to the generator.
func dataLookup(data []string) func(string) string {
return func(s string) string {
pos, jsonKeyQuery := parseTransform(s)
if pos > len(data) || pos < 0 {
return "<nil>"
}
item := data[pos-1]
// If just giving position, leave as-is.
if jsonKeyQuery == "" {
return item
}
return jsonQuery(item, jsonKeyQuery)
}
}
// parseTransform takes a string expected to be a substitution variable (e.g.
// $1.uuid) and splits it into its position and json query parts.
func parseTransform(s string) (position int, jsonQuery string) {
parts := strings.SplitN(s, ".", 2)
if len(parts) == 1 {
// Either the whole thing is a positional arg or the query.
pos, err := strconv.Atoi(s)
if err != nil {
return 1, s
}
return pos, ""
}
// Check if it starts with a position, otherwise it is all the query
pos, err := strconv.Atoi(parts[0])
if err != nil {
return 1, s
}
return pos, parts[1]
}
// jsonQuery queries the given data for the value of the field specified by the
// given query. If there is an error parsing the json or the field does not
// exist, the empty string is returned.
func jsonQuery(data, query string) string {
jsonParsed, err := gabs.ParseJSON([]byte(data))
if err != nil {
return "<nil>"
}
return fmt.Sprint(jsonParsed.Path(query).Data())
}
// truncatedValue is showing just part of the value in case its a huge binary or
// web page.
func truncatedValue(i interface{}) string {
s := fmt.Sprint(i)
if len(s) > truncationLength {
s = fmt.Sprintf("%q...\n[Value truncated]", s[:truncationLength])
}
return s
} | transform/transform.go | 0.618204 | 0.41117 | transform.go | starcoder |
package core
import (
"sync"
"github.com/OneOfOne/cmap/hashers"
)
// shardCount must be a power of 2.
// Higher shardCount will improve concurrency but will consume more memory.
const shardCount = 1 << 8
// shardMask is the mask we apply to hash functions below.
const shardMask = shardCount - 1
// targetMap is a concurrent safe sharded map to scale on multiple cores.
// It's a fully specialised version of cmap.CMap for our most commonly used types.
type targetMap struct {
shards []*targetLMap
}
// newTargetMap creates a new targetMap.
func newTargetMap() *targetMap {
cm := &targetMap{
shards: make([]*targetLMap, shardCount),
}
for i := range cm.shards {
cm.shards[i] = newTargetLMapSize(shardCount)
}
return cm
}
// Set is the equivalent of `map[key] = val`.
// It returns true if the item was inserted, false if it already existed (in which case it won't be inserted)
func (cm *targetMap) Set(target *BuildTarget) bool {
h := hashBuildLabel(target.Label)
return cm.shards[h&shardMask].Set(target)
}
// Get returns the target or, if the target isn't present, a channel that it can be waited on for.
// Exactly one of the target or channel will be returned.
func (cm *targetMap) Get(key BuildLabel) (val *BuildTarget, wait <-chan struct{}) {
h := hashBuildLabel(key)
return cm.shards[h&shardMask].Get(key)
}
// Values returns a slice of all the current values in the map.
// This is a view that an observer could potentially have had at some point around the calling of this function,
// but no particular consistency guarantees are made.
func (cm *targetMap) Values() BuildTargets {
ret := BuildTargets{}
for _, lm := range cm.shards {
ret = append(ret, lm.Values()...)
}
return ret
}
func hashBuildLabel(key BuildLabel) uint32 {
return hashers.Fnv32(key.Subrepo) ^ hashers.Fnv32(key.PackageName) ^ hashers.Fnv32(key.Name)
}
// A buildTargetPair represents a build target & an awaitable channel for one to exist.
type buildTargetPair struct {
Target *BuildTarget
Wait chan struct{}
}
// targetLMap is a simple sync.Mutex locked map.
// Used by targetMap internally for sharding.
type targetLMap struct {
m map[BuildLabel]buildTargetPair
l sync.Mutex
}
// newTargetLMapSize is the equivalent of `m := make(map[BuildLabel]buildTargetPair, cap)`
func newTargetLMapSize(cap int) *targetLMap {
return &targetLMap{
m: make(map[BuildLabel]buildTargetPair, cap),
}
}
// Set is the equivalent of `map[key] = val`.
// It returns true if the item was inserted, false if it already existed (in which case it won't be inserted)
func (lm *targetLMap) Set(target *BuildTarget) bool {
lm.l.Lock()
defer lm.l.Unlock()
if existing, present := lm.m[target.Label]; present {
if existing.Target != nil {
return false // already added
}
// Hasn't been added, but something is waiting for it to be.
lm.m[target.Label] = buildTargetPair{Target: target}
if existing.Wait != nil {
close(existing.Wait)
}
return true
}
lm.m[target.Label] = buildTargetPair{Target: target}
return true
}
// Get returns the target or, if the target isn't present, a channel that it can be waited on for.
// Exactly one of the target or channel will be returned.
func (lm *targetLMap) Get(key BuildLabel) (*BuildTarget, <-chan struct{}) {
lm.l.Lock()
defer lm.l.Unlock()
if v, ok := lm.m[key]; ok {
return v.Target, v.Wait
}
// Need to check again; something else could have added this.
if v, ok := lm.m[key]; ok {
return v.Target, v.Wait
}
ch := make(chan struct{})
lm.m[key] = buildTargetPair{Wait: ch}
return nil, ch
}
// Values returns a copy of all the targets currently in the map.
func (lm *targetLMap) Values() []*BuildTarget {
lm.l.Lock()
defer lm.l.Unlock()
ret := make([]*BuildTarget, 0, len(lm.m))
for _, v := range lm.m {
if v.Target != nil {
ret = append(ret, v.Target)
}
}
return ret
} | src/core/cmap_targets.go | 0.720958 | 0.414721 | cmap_targets.go | starcoder |
package graph
import (
"sort"
)
// ID is a unique ID of the Vertex/Node in the graph
type ID int
// byID implements sort.Interface for []ID
type byID []ID
func (a byID) Len() int { return len(a) }
func (a byID) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a byID) Less(i, j int) bool { return a[i] < a[j] }
// AdjacencyList Graph representation
type AdjacencyList map[ID]map[ID]struct{}
// Graph representation using an adjancency map
// no parallel edges supported
type Graph struct {
vertices map[ID]struct{}
edges AdjacencyList
directed bool
}
// DirectedGraph is a directed graph
type DirectedGraph struct {
Graph
}
// UndirectedGraph is a directed graph
type UndirectedGraph struct {
Graph
}
// VertexCount returns the number of vertices in the graph
func (g *Graph) VertexCount() int {
return len(g.vertices)
}
// Vertices returns a slice of vertixes in the graph
func (g *Graph) Vertices() []ID {
nodes := make([]ID, 0)
for k := range g.vertices {
nodes = append(nodes, k)
}
sort.Sort(byID(nodes))
return nodes
}
// EdgeCount returns the number of edges in the graph
func (g *Graph) EdgeCount() int {
return len(g.Edges())
}
// Edges returns a set of all the edges in the graph
func (g *Graph) Edges() []Edge {
edges := make([]Edge, 0)
for from, v := range g.edges {
for to := range v {
e := &Edge{
From: from, To: to}
edges = append(edges, *e)
}
}
return edges
}
// GetEdge returns the edge from u to v, or nil if not adjacent
func (g *Graph) GetEdge(u, v ID) *Edge {
if endpoints, ok := g.edges[u]; ok {
if _, ok := endpoints[v]; ok {
e := &Edge{
From: u,
To: v,
}
return e
}
}
return nil
}
// Degre returns the number of (outgoing) edges incident to vertex v in the graph
func (g *Graph) Degre(v ID) int {
return len(g.edges[v])
}
// IncidentEdges return all (outgoing) edges incident to vertex v in the graph
func (g *Graph) IncidentEdges(v ID) []Edge {
incidents := make([]Edge, 0)
for k := range g.edges[v] {
e := &Edge{
From: v,
To: k,
}
incidents = append(incidents, *e)
}
return incidents
}
// InsertVertex inserts and returns a new Vertex with element x
func (g *Graph) InsertVertex(v ID) bool {
if _, ok := g.vertices[v]; ok {
return false
}
g.vertices[v] = struct{}{}
return true
}
// RemoveVertex removes the Vertex from the graph.
func (g *Graph) RemoveVertex(v ID) {
// FIXME: get IncidentEdges() to remove them
delete(g.vertices, v)
}
// InsertEdge inserts and returns a new Edge from u to v with auxilary element x
func (g *Graph) InsertEdge(u, v ID) {
if _, ok := g.vertices[u]; !ok {
g.InsertVertex(u)
}
if _, ok := g.vertices[v]; !ok {
g.InsertVertex(v)
}
if _, ok := g.edges[u]; !ok {
g.edges[u] = make(map[ID]struct{})
}
g.edges[u][v] = struct{}{}
if !g.directed {
// For undirected graph add edge from v to u.
if _, ok := g.edges[v]; !ok {
g.edges[v] = make(map[ID]struct{})
}
g.edges[v][u] = struct{}{}
}
}
// RemoveEdge removes the eedge from the Graph
func (g *Graph) RemoveEdge(u, v ID) {
delete(g.edges[u], v)
if !g.directed {
delete(g.edges[v], u)
}
}
// Reverse returns reverted adjacencyList the graph
func (g Graph) Reverse() AdjacencyList {
reversedEdges := make(map[ID]map[ID]struct{})
for from := range g.edges {
for to := range g.edges[from] {
if _, ok := reversedEdges[to]; !ok {
reversedEdges[to] = make(map[ID]struct{})
}
reversedEdges[to][from] = struct{}{}
if !g.directed {
// For undirected graph add edge from v to u.
if _, ok := reversedEdges[from]; !ok {
reversedEdges[from] = make(map[ID]struct{})
}
reversedEdges[from][to] = struct{}{}
}
}
}
return reversedEdges
}
// // TopologicalSort returns a list of vertices of dicrected acyclic graph g in topological order
// func TopologicalSort(g Graph) {
// }
// NewGraph create a new Graph
func NewGraph(directed bool) *Graph {
return &Graph{
vertices: make(map[ID]struct{}),
edges: make(map[ID]map[ID]struct{}),
directed: directed,
}
} | pkg/graph/graph.go | 0.737064 | 0.475666 | graph.go | starcoder |
package cmd
import (
"testing"
"github.com/gomodule/redigo/redis"
"github.com/stretchr/testify/assert"
)
//ExampleKey verify the key command
type ExampleKey struct {
conn redis.Conn
}
//NewExampleKey create key object
func NewExampleKey(conn redis.Conn) *ExampleKey {
return &ExampleKey{
conn: conn,
}
}
//DelEqual verify that the return value of the del key operation is correct
func (ek *ExampleKey) DelEqual(t *testing.T, expectReply int, keys ...string) {
req := make([]interface{}, len(keys))
for i, eky := range keys {
req[i] = eky
}
reply, err := redis.Int(ek.conn.Do("Del", req...))
assert.Equal(t, expectReply, reply)
assert.NoError(t, err)
}
//DelEqualErr verify that the return error value of the del key operation is correct
func (ek *ExampleKey) DelEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := ek.conn.Do("del", args...)
assert.EqualError(t, err, errValue)
}
//ExistsEqual verify that the return value of the exists key operation is correct
func (ek *ExampleKey) ExistsEqual(t *testing.T, expectReply int, keys ...string) {
req := make([]interface{}, len(keys))
for i, eky := range keys {
req[i] = eky
}
reply, err := redis.Int(ek.conn.Do("exists", req...))
assert.Equal(t, expectReply, reply)
assert.NoError(t, err)
}
//ExistsEqualErr verify that the return error value of the exists key operation is correct
func (ek *ExampleKey) ExistsEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := ek.conn.Do("exists", args...)
assert.EqualError(t, err, errValue)
}
//TTLEqual verify that the return value of the ttl key operation is correct
func (ek *ExampleKey) TTLEqual(t *testing.T, key string, expectReply int) {
reply, err := redis.Int(ek.conn.Do("ttl", key))
assert.Equal(t, expectReply, reply)
assert.NoError(t, err)
}
//TTLEqualErr verify that the return error value of the ttl key operation is correct
func (ek *ExampleKey) TTLEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := ek.conn.Do("ttl", args...)
assert.EqualError(t, err, errValue)
}
//PTTLEqual verify that the return value of the ttl key operation is correct
func (ek *ExampleKey) PTTLEqual(t *testing.T, key string, expectReply int) {
reply, err := redis.Int(ek.conn.Do("ttl", key))
assert.Equal(t, expectReply, reply)
assert.NoError(t, err)
}
//PTTLEqualErr verify that the return error value of the ttl key operation is correct
func (ek *ExampleKey) PTTLEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := ek.conn.Do("ttl", args...)
assert.EqualError(t, err, errValue)
}
//Info TODO
func (ek *ExampleKey) Info(t *testing.T, key string, expectReply interface{}) {
}
//InfoEqualErr TODO
func (ek *ExampleKey) InfoEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := ek.conn.Do("info", args...)
assert.EqualError(t, err, errValue)
}
//ScanEqual verify that the return value of the scan key operation is correct
//default scan all key in store
func (ek *ExampleKey) ScanEqual(t *testing.T, match string, expectCount int) {
var reply interface{}
var err error
if match == "" {
reply, err = ek.conn.Do("Scan", 0, "count", 10000)
} else {
reply, err = ek.conn.Do("Scan", 0, "match", match, "count", 10000)
}
r, _ := redis.MultiBulk(reply, err)
strs, _ := redis.Strings(r[1], err)
assert.Equal(t, expectCount, len(strs))
assert.NoError(t, err)
}
//ScanEqualErr verify that the return err value of the scan key operation is correct
func (ek *ExampleKey) ScanEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := ek.conn.Do("scan", args...)
assert.EqualError(t, err, errValue)
}
//RandomKeyEqual verify that the return value of the random key operation is correct
func (ek *ExampleKey) RandomKeyEqual(t *testing.T) {
_, err := ek.conn.Do("RANDOMKEY")
assert.NoError(t, err)
}
//RandomKeyEqualErr verify that the return err value of the random key operation is correct
func (ek *ExampleKey) RandomKeyEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := ek.conn.Do("Randomkey", args...)
assert.EqualError(t, err, errValue)
}
//ExpireEqual verify that the return value of the expire key operation is correct
func (ek *ExampleKey) ExpireEqual(t *testing.T, key string, value, expectValue int) {
reply, err := redis.Int(ek.conn.Do("expire", key, value))
assert.NoError(t, err)
assert.Equal(t, expectValue, reply)
}
//ExpireEqualErr verify that the err return value of the expire key operation is correct
func (ek *ExampleKey) ExpireEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := ek.conn.Do("expire", args...)
assert.EqualError(t, err, errValue)
}
//ExpireAtEqual verify that the return value of the expire key operation is correct
func (ek *ExampleKey) ExpireAtEqual(t *testing.T, key string, value, expectValue int) {
reply, err := redis.Int(ek.conn.Do("expireat", key, value))
assert.NoError(t, err)
assert.Equal(t, expectValue, reply)
}
//AtExpireEqualErr verify that the err return value of the expire key operation is correct
func (ek *ExampleKey) ExpireAtEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := ek.conn.Do("expireat", args...)
assert.EqualError(t, err, errValue)
}
//PExpireEqual verify that the return value of the expire key operation is correct
func (ek *ExampleKey) PExpireEqual(t *testing.T, key string, value, expectValue int) {
reply, err := redis.Int(ek.conn.Do("pexpire", key, value))
assert.NoError(t, err)
assert.Equal(t, expectValue, reply)
}
//PExpireEqualErr verify that the err return value of the expire key operation is correct
func (ek *ExampleKey) PExpireEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := ek.conn.Do("pexpire", args...)
assert.EqualError(t, err, errValue)
}
//ExpireAtEqual verify that the return value of the expire key operation is correct
func (ek *ExampleKey) PExpireAtEqual(t *testing.T, key string, value, expectValue int) {
reply, err := redis.Int(ek.conn.Do("pexpireat", key, value))
assert.NoError(t, err)
assert.Equal(t, expectValue, reply)
}
//PExpireEqualAtErr verify that the err return value of the expire key operation is correct
func (ek *ExampleKey) PExpireAtEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := ek.conn.Do("pexpireat", args...)
assert.EqualError(t, err, errValue)
}
func (ek *ExampleKey) TypeEqual(t *testing.T, key string, expectValue interface{}) {
reply, err := redis.String(ek.conn.Do("type", key))
assert.NoError(t, err)
assert.Equal(t, expectValue, reply)
}
func (ek *ExampleKey) TypeEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := redis.String(ek.conn.Do("type", args...))
assert.EqualError(t, err, errValue)
}
func (ek *ExampleKey) KeysEqual(t *testing.T, key string, expectValue interface{}) {
}
func (ek *ExampleKey) KeysEqualErr(t *testing.T, errValue string, expectValue interface{}) {
}
func (ek *ExampleKey) ObjectEqual(t *testing.T, key string, expectValue interface{}) {
reply, err := redis.String(ek.conn.Do("object", "encoding", key))
assert.NoError(t, err)
assert.Equal(t, expectValue, reply)
}
func (ek *ExampleKey) ObjectEqualErr(t *testing.T, errValue string, args ...interface{}) {
tmp := []interface{}{"encoding"}
tmp = append(tmp, args...)
_, err := redis.String(ek.conn.Do("object", tmp...))
assert.EqualError(t, err, errValue)
}
//Persist verify that the return value of the expire key operation is correct
func (ek *ExampleKey) PersistEqual(t *testing.T, key string, expectValue int) {
reply, err := redis.Int(ek.conn.Do("persist", key))
assert.NoError(t, err)
assert.Equal(t, expectValue, reply)
}
//PersistEqualAtErr verify that the err return value of the expire key operation is correct
func (ek *ExampleKey) PersistEqualErr(t *testing.T, errValue string, args ...interface{}) {
_, err := ek.conn.Do("persist", args...)
assert.EqualError(t, err, errValue)
} | tools/autotest/cmd/key.go | 0.618089 | 0.65971 | key.go | starcoder |
package onshape
import (
"encoding/json"
)
// BTPTypeNameStandard291 struct for BTPTypeNameStandard291
type BTPTypeNameStandard291 struct {
BTPTypeName290
BtType *string `json:"btType,omitempty"`
Type *string `json:"type,omitempty"`
}
// NewBTPTypeNameStandard291 instantiates a new BTPTypeNameStandard291 object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewBTPTypeNameStandard291() *BTPTypeNameStandard291 {
this := BTPTypeNameStandard291{}
return &this
}
// NewBTPTypeNameStandard291WithDefaults instantiates a new BTPTypeNameStandard291 object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewBTPTypeNameStandard291WithDefaults() *BTPTypeNameStandard291 {
this := BTPTypeNameStandard291{}
return &this
}
// GetBtType returns the BtType field value if set, zero value otherwise.
func (o *BTPTypeNameStandard291) GetBtType() string {
if o == nil || o.BtType == nil {
var ret string
return ret
}
return *o.BtType
}
// GetBtTypeOk returns a tuple with the BtType field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTPTypeNameStandard291) GetBtTypeOk() (*string, bool) {
if o == nil || o.BtType == nil {
return nil, false
}
return o.BtType, true
}
// HasBtType returns a boolean if a field has been set.
func (o *BTPTypeNameStandard291) HasBtType() bool {
if o != nil && o.BtType != nil {
return true
}
return false
}
// SetBtType gets a reference to the given string and assigns it to the BtType field.
func (o *BTPTypeNameStandard291) SetBtType(v string) {
o.BtType = &v
}
// GetType returns the Type field value if set, zero value otherwise.
func (o *BTPTypeNameStandard291) GetType() string {
if o == nil || o.Type == nil {
var ret string
return ret
}
return *o.Type
}
// GetTypeOk returns a tuple with the Type field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *BTPTypeNameStandard291) GetTypeOk() (*string, bool) {
if o == nil || o.Type == nil {
return nil, false
}
return o.Type, true
}
// HasType returns a boolean if a field has been set.
func (o *BTPTypeNameStandard291) HasType() bool {
if o != nil && o.Type != nil {
return true
}
return false
}
// SetType gets a reference to the given string and assigns it to the Type field.
func (o *BTPTypeNameStandard291) SetType(v string) {
o.Type = &v
}
func (o BTPTypeNameStandard291) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
serializedBTPTypeName290, errBTPTypeName290 := json.Marshal(o.BTPTypeName290)
if errBTPTypeName290 != nil {
return []byte{}, errBTPTypeName290
}
errBTPTypeName290 = json.Unmarshal([]byte(serializedBTPTypeName290), &toSerialize)
if errBTPTypeName290 != nil {
return []byte{}, errBTPTypeName290
}
if o.BtType != nil {
toSerialize["btType"] = o.BtType
}
if o.Type != nil {
toSerialize["type"] = o.Type
}
return json.Marshal(toSerialize)
}
type NullableBTPTypeNameStandard291 struct {
value *BTPTypeNameStandard291
isSet bool
}
func (v NullableBTPTypeNameStandard291) Get() *BTPTypeNameStandard291 {
return v.value
}
func (v *NullableBTPTypeNameStandard291) Set(val *BTPTypeNameStandard291) {
v.value = val
v.isSet = true
}
func (v NullableBTPTypeNameStandard291) IsSet() bool {
return v.isSet
}
func (v *NullableBTPTypeNameStandard291) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableBTPTypeNameStandard291(val *BTPTypeNameStandard291) *NullableBTPTypeNameStandard291 {
return &NullableBTPTypeNameStandard291{value: val, isSet: true}
}
func (v NullableBTPTypeNameStandard291) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableBTPTypeNameStandard291) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | onshape/model_btp_type_name_standard_291.go | 0.639286 | 0.521167 | model_btp_type_name_standard_291.go | starcoder |
package test_function
func assert(want int, act int, code string)
func println(frmt ...string)
func ret3() int {
return 3
return 5
}
func add2(x int, y int) int {
return x + y
}
func sub2(x int, y int) int {
return x - y
}
func add6(a int, b int, c int, d int, e int, f int) int {
return a + b + c + d + e + f
}
func addx(x *int, y int) int {
return *x + y
}
func subChar(a byte, b byte, c byte) int {
return a - b - c
}
func fib(x int) int {
if x <= 1 {
return 1
}
return fib(x-1) + fib(x-2)
}
func subLong(a int64, b int64, c int64) int {
return a - b - c
}
func subShort(a int16, b int16, c int16) int {
return a - b - c
}
var g1 int
func g1Ptr() *int {
return &g1
}
func intToChar(x int) byte {
return x
}
func divLong(a int64, b int64) int {
return a / b
}
func boolFnAdd(x bool) bool {
return x + 1
}
func boolFnSub(x bool) bool {
return x - 1
}
func paramDecay(x []int) int {
return x[0]
}
func retNone() {
return
}
func falseFn() bool
func trueFn() bool
func charFn() byte
func shortFn() int16
// sliceの追加後
// func addAll(n ...int) int
// func printAll(s ...string) {
// println(s)
// }
func add_double(x float64, y float64) float64
func add_float(x float32, y float32) float32
func add_float3(x float32, y float32, z float32) float32 {
return x + y + z
}
func add_double3(x float64, y float64, z float64) float64 {
return x + y + z
}
func sprintf(buf string, format ...string) string
func strcmp(s1 string, s2 string) int
func fnptr(fn func(int, int) int, a int, b int) int {
return fn(a, b)
}
func add10_int(x1 int, x2 int, x3 int, x4 int, x5 int, x6 int, x7 int, x8 int, x9 int, x10 int) int
func add10_float(x1 float32, x2 float32, x3 float32, x4 float32, x5 float32, x6 float32, x7 float32, x8 float32, x9 float32, x10 float32) float32
func add10_double(x1 float64, x2 float64, x3 float64, x4 float64, x5 float64, x6 float64, x7 float64, x8 float64, x9 float64, x10 float64) float64
func many_args1(a int, b int, c int, d int, e int, f int, g int, h int) int {
return g / h
}
func many_args2(a float64, b float64, c float64, d float64, e float64,
f float64, g float64, h float64, i float64, j float64) float64 {
return i / j
}
func many_args3(a int, b float64, c int, d int, e float64, f int,
g float64, h int, i float64, j float64, k float64,
l float64, m float64, n int, o int, p float64) int {
return o / p
}
type Ty4 struct {
a int
b int
c int16
d int8
}
type Ty5 struct {
a int
b float32
c float64
}
type Ty6 struct {
a [3]uint8
}
type Ty7 struct {
a int64
b int64
c int64
}
func struct_test5(x Ty5, n int) int
func struct_test4(x Ty4, n int) int
func struct_test6(x Ty6, n int) int
func struct_test7(x Ty7, n int) int
func structTest14(x Ty4, n int) int {
switch n {
case 0:
return x.a
case 1:
return x.b
case 2:
return x.c
default:
return x.d
}
}
func structTest15(x Ty5, n int) int {
switch n {
case 0:
return x.a
case 1:
return x.b
default:
return x.c
}
}
type Ty20 struct {
a [10]int8
}
type Ty21 struct {
a [20]int8
}
func struct_test24() Ty4
func struct_test25() Ty5
func struct_test26() Ty6
func struct_test27() Ty20
func struct_test28() Ty21
func struct_test34() Ty4 {
return Ty4{10, 20, 30, 40}
}
func struct_test35() Ty5 {
return Ty5{10, 20, 30}
}
func struct_test36() Ty6 {
return Ty6{10, 20, 30}
}
func struct_test37() Ty20 {
return Ty20{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}
}
func struct_test38() Ty21 {
return Ty21{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
}
type Ty021 struct {
a string
b string
}
func struct_test39() Ty021 {
return Ty021{"aaa", "bbb"}
}
func add10_identList_int(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10 int) int
func add10_identList_float(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10 float32) float32
func add10_identList_double(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10 float64) float64
func many_args_list1(a, b, c, d, e, f, g, h int) int {
return g / h
}
func many_args_list2(a, b, c, d, e, f, g, h, i, j float64) float64 {
return i / j
}
func many_args_list3(a int, b float64, c, d int, e float64, f int,
g float64, h int, i, j, k float64,
l, m float64, n, o int, p float64) int {
return o / p
}
// func multi_return() (int, int, int) {
// return 3, 5, 6
// }
func main() {
assert(3, ret3(), "ret3()")
assert(8, add2(3, 5), "add2(3, 5)")
assert(2, sub2(5, 3), "sub2(5, 3)")
assert(21, add6(1, 2, 3, 4, 5, 6), "add6(1,2,3,4,5,6)")
assert(66, add6(1, 2, add6(3, 4, 5, 6, 7, 8), 9, 10, 11), "add6(1,2,add6(3,4,5,6,7,8),9,10,11)")
assert(136, add6(1, 2, add6(3, add6(4, 5, 6, 7, 8, 9), 10, 11, 12, 13), 14, 15, 16), "add6(1,2,add6(3,add6(4,5,6,7,8,9),10,11,12,13),14,15,16)")
assert(7, add2(3, 4), "add2(3,4)")
assert(1, sub2(4, 3), "sub2(4,3)")
assert(55, fib(9), "fib(9)")
assert(1, subChar(7, 3, 3), "subChar(7, 3, 3)")
assert(1, subLong(7, 3, 3), "subLong(7, 3, 3)")
assert(1, subShort(7, 3, 3), "subShort(7, 3, 3)")
g1 = 3
assert(3, *g1Ptr(), "*g1Ptr()")
assert(5, intToChar(261), "intToChar(261)")
assert(5, intToChar(261), "intToChar(261)")
assert(-5, divLong(-10, 2), "divLong(-10, 2)")
assert(1, boolFnAdd(3), "boolFnAdd(3)")
assert(0, boolFnSub(3), "boolFnSub(3)")
assert(1, boolFnAdd(-3), "boolFnAdd(-3)")
assert(0, boolFnSub(-3), "boolFnSub(-3)")
assert(1, boolFnAdd(0), "boolFnAdd(0)")
assert(1, boolFnSub(0), "boolFnSub(0)")
var x [2]int
x[0] = 3
assert(3, paramDecay(x), "var x [2]int ; x[0]=3; paramDecay(x)")
retNone()
assert(1, trueFn(), "trueFn()")
assert(0, falseFn(), "falseFn()")
assert(3, charFn(), "charFn()")
assert(5, shortFn(), "shortFn()")
// sliceの追加後
// assert(6, addAll(3, 1, 2, 3), "addAll(3,1,2,3)")
// assert(5, addAll(4, 1, 2, 3, -1), "addAll(4,1,2,3,-1)")
// printAll("1", "2", "3", "4")
// printAll("1", "2", "3", "4", "5", "6")
assert(6, int(add_float(2.3, 3.8)), "int(add_float(2.3, 3.8))")
assert(6, int(add_double(2.3, 3.8)), "int(add_double(2.3, 3.8))")
assert(7, int(add_float3(2.5, 2.5, 2.5)), "int(add_float3(2.5, 2.5, 2.5))")
assert(7, int(add_double3(2.5, 2.5, 2.5)), "int(add_double3(2.5, 2.5, 2.5))")
var buf string
sprintf(buf, "%.1f", float32(3.5))
assert(0, strcmp(buf, "3.5"), "var buf string;sprintf(buf,\"%.1f\",float32(3.5));strcmp(buf,\"3.5\")")
assert(&ret3, ret3, "ret3")
var fn func() int = ret3
assert(3, fn(), "fn()")
var fn01 = ret3
assert(3, fn01(), "fn01()")
fn02 := ret3
assert(3, fn02(), "fn02()")
fn03 := add2
assert(3, fn03(1, 2), "fn03(1,2)")
assert(3, fnptr(add2, 1, 2), "fnptr(add2, 1,2)")
assert(55, add10_int(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), "add10_int(1,2,3,4,5,6,7,8,9,10)")
assert(55, add10_float(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), "add10_float(1,2,3,4,5,6,7,8,9,10)")
assert(55, add10_double(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), "add10_double(1,2,3,4,5,6,7,8,9,10)")
var buf2 string
sprintf(buf2, "%d %.1f %.1f %.1f %d %d %.1f %d %d %d %d %.1f %d %d %.1f %.1f %.1f %.1f %d", 1, 1.0, 1.0, 1.0, 1, 1, 1.0, 1, 1, 1, 1, 1.0, 1, 1, 1.0, 1.0, 1.0, 1.0, 1)
assert(0, strcmp(buf2, "1 1.0 1.0 1.0 1 1 1.0 1 1 1 1 1.0 1 1 1.0 1.0 1.0 1.0 1"), "strcmp(buf2, \"1 1.0 1.0 1.0 1 1 1.0 1 1 1 1 1.0 1 1 1.0 1.0 1.0 1.0 1\")")
assert(4, many_args1(1, 2, 3, 4, 5, 6, 40, 10), "many_args1(1,2,3,4,5,6,40,10)")
assert(4, many_args2(1, 2, 3, 4, 5, 6, 7, 8, 40, 10), "many_args2(1,2,3,4,5,6,7,8,40,10)")
assert(8, many_args3(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 80, 10), "many_args3(1,2,3,4,5,6,7,8,9,10,11,12,13,14,80,10)")
x4 := Ty4{10, 20, 30, 40}
assert(10, x4.a, "x1.a")
assert(10, struct_test4(x4, 0), "x4:=Ty4{10,20,30,40};struct_test4(x4,0)")
assert(20, struct_test4(x4, 1), "x4:=Ty4{10,20,30,40};struct_test4(x4,1)")
assert(30, struct_test4(x4, 2), "x4:=Ty4{10,20,30,40};struct_test4(x4,2)")
assert(40, struct_test4(x4, 3), "x4:=Ty4{10,20,30,40};struct_test4(x4,3)")
x5 := Ty5{10, 20, 30}
assert(10, struct_test5(x5, 0), "x5:=Ty5{10,20,30};struct_test5(x5,0)")
assert(20, struct_test5(x5, 1), "x5:=Ty5{10,20,30};struct_test5(x5,1)")
assert(30, struct_test5(x5, 2), "x5:=Ty5{10,20,30};struct_test5(x5,2)")
x6 := Ty6{10, 20, 30}
assert(10, struct_test6(x6, 0), "x6:=Ty6{10,20,30};struct_test6(x6,0)")
assert(20, struct_test6(x6, 1), "x6:=Ty6{10,20,30};struct_test6(x6,1)")
assert(30, struct_test6(x6, 2), "x6:=Ty6{10,20,30};struct_test6(x6,2)")
x7 := Ty7{10, 20, 30}
assert(10, struct_test7(x7, 0), "x7:=Ty7{10,20,30};struct_test7(x7,0)")
assert(20, struct_test7(x7, 1), "x7:=Ty7{10,20,30};struct_test7(x7,1)")
assert(30, struct_test7(x7, 2), "x7:=Ty7{10,20,30};struct_test7(x7,2)")
x8 := Ty4{10, 20, 30, 40}
assert(10, structTest14(x8, 0), "x8:=Ty4{10,20,30,40};structTest14(x8,0)")
assert(20, structTest14(x8, 1), "x8:=Ty4{10,20,30,40};structTest14(x8,1)")
assert(30, structTest14(x8, 2), "x8:=Ty4{10,20,30,40};structTest14(x8,2)")
assert(40, structTest14(x8, 3), "x8:=Ty4{10,20,30,40};structTest14(x8,3)")
x9 := Ty5{10, 20, 30}
assert(10, structTest15(x9, 0), "x9:=Ty5{10,20,30};structTest15(x9,0)")
assert(20, structTest15(x9, 1), "x9:=Ty5{10,20,30};structTest15(x9,1)")
assert(30, structTest15(x9, 2), "x9:=Ty5{10,20,30};structTest15(x9,2)")
assert(10, struct_test24().a, "struct_test24().a")
assert(20, struct_test24().b, "struct_test24().b")
assert(30, struct_test24().c, "struct_test24().c")
assert(40, struct_test24().d, "struct_test24().d")
assert(10, struct_test25().a, "struct_test25().a")
assert(20, struct_test25().b, "struct_test25().b")
assert(30, struct_test25().c, "struct_test25().c")
assert(10, struct_test26().a[0], "struct_test26().a[0]")
assert(20, struct_test26().a[1], "struct_test26().a[1]")
assert(30, struct_test26().a[2], "struct_test26().a[2]")
assert(10, struct_test27().a[0], "struct_test27().a[0]")
assert(60, struct_test27().a[5], "struct_test27().a[5]")
assert(100, struct_test27().a[9], "struct_test27().a[9]")
assert(1, struct_test28().a[0], "struct_test28().a[0]")
assert(5, struct_test28().a[4], "struct_test28().a[4]")
assert(10, struct_test28().a[9], "struct_test28().a[9]")
assert(15, struct_test28().a[14], "struct_test28().a[14]")
assert(20, struct_test28().a[19], "struct_test28().a[19]")
assert(10, struct_test34().a, "struct_test34().a")
assert(20, struct_test34().b, "struct_test34().b")
assert(30, struct_test34().c, "struct_test34().c")
assert(40, struct_test34().d, "struct_test34().d")
assert(10, struct_test35().a, "struct_test35().a")
assert(20, struct_test35().b, "struct_test35().b")
assert(30, struct_test35().c, "struct_test35().c")
assert(10, struct_test36().a[0], "struct_test36().a[0]")
assert(20, struct_test36().a[1], "struct_test36().a[1]")
assert(30, struct_test36().a[2], "struct_test36().a[2]")
assert(10, struct_test37().a[0], "struct_test37().a[0]")
assert(60, struct_test37().a[5], "struct_test36().a[5]")
assert(100, struct_test37().a[9], "struct_test36().a[9]")
assert(1, struct_test38().a[0], "struct_test38().a[0]")
assert(5, struct_test38().a[4], "struct_test38().a[4]")
assert(10, struct_test38().a[9], "struct_test38().a[9]")
assert(15, struct_test38().a[14], "struct_test38().a[14]")
assert(20, struct_test38().a[19], "struct_test38().a[19]")
assert(55, add10_identList_int(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), "add10_identList_int(1,2,3,4,5,6,7,8,9,10)")
assert(55, add10_identList_float(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), "add10_identList_float(1,2,3,4,5,6,7,8,9,10)")
assert(55, add10_identList_double(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), "add10_identList_double(1,2,3,4,5,6,7,8,9,10)")
assert(4, many_args_list1(1, 2, 3, 4, 5, 6, 40, 10), "many_args1(1,2,3,4,5,6,40,10)")
assert(4, many_args_list2(1, 2, 3, 4, 5, 6, 7, 8, 40, 10), "many_args2(1,2,3,4,5,6,7,8,40,10)")
assert(8, many_args_list3(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 80, 10), "many_args3(1,2,3,4,5,6,7,8,9,10,11,12,13,14,80,10)")
// var x10, x11, x12 = multi_return()
// assert(6, x10, "x10") // 最後の返り値以外は捨てられる。raxレジスタが最後の返り値で上書きされるため
// assert(0, x11, "x11")
// assert(0, x12, "x12")
assert(0, strcmp(struct_test39().a, "aaa"), "strcmp(struct_test39().a, \"aaa\")")
assert(0, strcmp(struct_test39().b, "bbb"), "strcmp(struct_test39().b, \"bbb\")")
println("OK")
} | testdata/esc/functions.go | 0.578567 | 0.466359 | functions.go | starcoder |
package terraform
import (
"bytes"
htmltemplate "html/template"
"strings"
texttemplate "text/template"
"github.com/Masterminds/sprig/v3"
)
const (
// DefaultPlanTemplate is a default template for terraform plan
DefaultPlanTemplate = `
{{template "plan_title" .}}
{{if .Link}}[CI link]({{.Link}}){{end}}
{{if .HasDestroy}}{{template "deletion_warning" .}}{{end}}
{{template "result" .}}
{{template "updated_resources" .}}
<details><summary>Details (Click me)</summary>
{{wrapCode .CombinedOutput}}
</details>
{{if .ErrorMessages}}
## :warning: Errors
{{range .ErrorMessages}}
* {{. -}}
{{- end}}{{end}}`
// DefaultApplyTemplate is a default template for terraform apply
DefaultApplyTemplate = `
{{template "apply_title" .}}
{{if .Link}}[CI link]({{.Link}}){{end}}
{{template "result" .}}
<details><summary>Details (Click me)</summary>
{{wrapCode .CombinedOutput}}
</details>
{{if .ErrorMessages}}
## :warning: Errors
{{range .ErrorMessages}}
* {{. -}}
{{- end}}{{end}}`
// DefaultPlanParseErrorTemplate is a default template for terraform plan parse error
DefaultPlanParseErrorTemplate = `
{{template "plan_title" .}}
{{if .Link}}[CI link]({{.Link}}){{end}}
It failed to parse the result.
<details><summary>Details (Click me)</summary>
{{wrapCode .CombinedOutput}}
</details>
`
// DefaultApplyParseErrorTemplate is a default template for terraform apply parse error
DefaultApplyParseErrorTemplate = `
## Apply Result{{if .Vars.target}} ({{.Vars.target}}){{end}}
{{if .Link}}[CI link]({{.Link}}){{end}}
It failed to parse the result.
<details><summary>Details (Click me)</summary>
{{wrapCode .CombinedOutput}}
</details>
`
)
// CommonTemplate represents template entities
type CommonTemplate struct {
Result string
ChangedResult string
ChangeOutsideTerraform string
Warning string
Link string
UseRawOutput bool
HasDestroy bool
Vars map[string]string
Templates map[string]string
Stdout string
Stderr string
CombinedOutput string
ExitCode int
ErrorMessages []string
CreatedResources []string
UpdatedResources []string
DeletedResources []string
ReplacedResources []string
}
// Template is a default template for terraform commands
type Template struct {
Template string
CommonTemplate
}
// NewPlanTemplate is PlanTemplate initializer
func NewPlanTemplate(template string) *Template {
if template == "" {
template = DefaultPlanTemplate
}
return &Template{
Template: template,
}
}
// NewApplyTemplate is ApplyTemplate initializer
func NewApplyTemplate(template string) *Template {
if template == "" {
template = DefaultApplyTemplate
}
return &Template{
Template: template,
}
}
func NewPlanParseErrorTemplate(template string) *Template {
if template == "" {
template = DefaultPlanParseErrorTemplate
}
return &Template{
Template: template,
}
}
func NewApplyParseErrorTemplate(template string) *Template {
if template == "" {
template = DefaultApplyParseErrorTemplate
}
return &Template{
Template: template,
}
}
func avoidHTMLEscape(text string) htmltemplate.HTML {
return htmltemplate.HTML(text) //nolint:gosec
}
func wrapCode(text string) interface{} {
if strings.Contains(text, "```") {
return `<pre><code>` + text + `</code></pre>`
}
return htmltemplate.HTML("\n```\n" + text + "\n```\n") //nolint:gosec
}
func generateOutput(kind, template string, data map[string]interface{}, useRawOutput bool) (string, error) {
var b bytes.Buffer
if useRawOutput {
tpl, err := texttemplate.New(kind).Funcs(texttemplate.FuncMap{
"avoidHTMLEscape": avoidHTMLEscape,
"wrapCode": wrapCode,
}).Funcs(sprig.TxtFuncMap()).Parse(template)
if err != nil {
return "", err
}
if err := tpl.Execute(&b, data); err != nil {
return "", err
}
} else {
tpl, err := htmltemplate.New(kind).Funcs(htmltemplate.FuncMap{
"avoidHTMLEscape": avoidHTMLEscape,
"wrapCode": wrapCode,
}).Funcs(sprig.FuncMap()).Parse(template)
if err != nil {
return "", err
}
if err := tpl.Execute(&b, data); err != nil {
return "", err
}
}
return b.String(), nil
}
// Execute binds the execution result of terraform command into template
func (t *Template) Execute() (string, error) {
data := map[string]interface{}{
"Result": t.Result,
"ChangedResult": t.ChangedResult,
"ChangeOutsideTerraform": t.ChangeOutsideTerraform,
"Warning": t.Warning,
"Link": t.Link,
"Vars": t.Vars,
"Stdout": t.Stdout,
"Stderr": t.Stderr,
"CombinedOutput": t.CombinedOutput,
"ExitCode": t.ExitCode,
"ErrorMessages": t.ErrorMessages,
"CreatedResources": t.CreatedResources,
"UpdatedResources": t.UpdatedResources,
"DeletedResources": t.DeletedResources,
"ReplacedResources": t.ReplacedResources,
"HasDestroy": t.HasDestroy,
}
templates := map[string]string{
"plan_title": "## {{if eq .ExitCode 1}}:x: {{end}}Plan Result{{if .Vars.target}} ({{.Vars.target}}){{end}}",
"apply_title": "## :{{if eq .ExitCode 0}}white_check_mark{{else}}x{{end}}: Apply Result{{if .Vars.target}} ({{.Vars.target}}){{end}}",
"result": "{{if .Result}}<pre><code>{{ .Result }}</code></pre>{{end}}",
"updated_resources": `{{if .CreatedResources}}
* Create
{{- range .CreatedResources}}
* {{.}}
{{- end}}{{end}}{{if .UpdatedResources}}
* Update
{{- range .UpdatedResources}}
* {{.}}
{{- end}}{{end}}{{if .DeletedResources}}
* Delete
{{- range .DeletedResources}}
* {{.}}
{{- end}}{{end}}{{if .ReplacedResources}}
* Replace
{{- range .ReplacedResources}}
* {{.}}
{{- end}}{{end}}`,
"deletion_warning": `### :warning: Resource Deletion will happen :warning:
This plan contains resource delete operation. Please check the plan result very carefully!`,
}
for k, v := range t.Templates {
templates[k] = v
}
resp, err := generateOutput("default", addTemplates(t.Template, templates), data, t.UseRawOutput)
if err != nil {
return "", err
}
return resp, nil
}
// SetValue sets template entities to CommonTemplate
func (t *Template) SetValue(ct CommonTemplate) {
t.CommonTemplate = ct
}
func addTemplates(tpl string, templates map[string]string) string {
for k, v := range templates {
tpl += `{{define "` + k + `"}}` + v + "{{end}}"
}
return tpl
} | pkg/terraform/template.go | 0.579043 | 0.403567 | template.go | starcoder |
package vm
func MultFunc(left, right func(Context) (Value, error)) func(Context) (Value, error) {
return func(ctx Context) (Value, error) {
leftValue, err := left(ctx)
if err != nil {
return Null(), err
}
rightValue, err := right(ctx)
if err != nil {
return Null(), err
}
switch rightValue.Type {
case ValueNull:
return Null(), NewArithmeticError("*", leftValue.Type.String(), rightValue.Type.String())
case ValueBool:
return Null(), NewArithmeticError("*", leftValue.Type.String(), rightValue.Type.String())
case ValueString:
return Null(), NewArithmeticError("*", leftValue.Type.String(), rightValue.Type.String())
case ValueInt64:
return multInt(leftValue, rightValue.Int64)
case ValueUint64:
return multUint(leftValue, rightValue.Uint64)
case ValueFloat64:
return multFloat(leftValue, rightValue.Float64)
// case ValueDatetime:
// return multDatetime(leftValue, IntToDatetime(rightValue.Int64))
// case ValueInterval:
// return multInterval(leftValue, IntToInterval(rightValue.Int64))
default:
return Null(), NewArithmeticError("*", leftValue.Type.String(), rightValue.Type.String())
}
}
}
func multInt(left Value, right int64) (Value, error) {
switch left.Type {
case ValueNull:
return Null(), NewArithmeticError("*", left.Type.String(), "int")
case ValueBool:
return Null(), NewArithmeticError("*", left.Type.String(), "int")
case ValueString:
return Null(), NewArithmeticError("*", left.Type.String(), "int")
case ValueInt64:
return IntToValue(left.Int64 * right), nil
case ValueUint64:
if right < 0 {
return IntToValue(int64(left.Uint64) * right), nil
}
return UintToValue(left.Uint64 * uint64(right)), nil
case ValueFloat64:
return FloatToValue(left.Float64 * float64(right)), nil
default:
return Null(), NewArithmeticError("*", left.Type.String(), "int")
}
}
func multUint(left Value, right uint64) (Value, error) {
switch left.Type {
case ValueNull:
return Null(), NewArithmeticError("*", left.Type.String(), "uint")
case ValueBool:
return Null(), NewArithmeticError("*", left.Type.String(), "uint")
case ValueString:
return Null(), NewArithmeticError("*", left.Type.String(), "uint")
case ValueInt64:
if left.Int64 < 0 {
return IntToValue(left.Int64 * int64(right)), nil
}
return UintToValue(uint64(left.Int64) * right), nil
case ValueUint64:
return UintToValue(left.Uint64 * right), nil
case ValueFloat64:
return FloatToValue(left.Float64 * float64(right)), nil
default:
return Null(), NewArithmeticError("*", left.Type.String(), "uint")
}
}
func multFloat(left Value, right float64) (Value, error) {
switch left.Type {
case ValueNull:
return Null(), NewArithmeticError("*", left.Type.String(), "float")
case ValueBool:
return Null(), NewArithmeticError("*", left.Type.String(), "float")
case ValueString:
return Null(), NewArithmeticError("*", left.Type.String(), "float")
case ValueInt64:
return FloatToValue(float64(left.Int64) * right), nil
case ValueUint64:
return FloatToValue(float64(left.Uint64) * right), nil
case ValueFloat64:
return FloatToValue(left.Float64 * right), nil
default:
return Null(), NewArithmeticError("*", left.Type.String(), "float")
}
}
// func multInterval(left Value, right time.Duration) (Value, error) {
// switch left.Type {
// case ValueDatetime:
// t := IntToDatetime(left.Int64)
// return DatetimeToValue(t.Add(-right)), nil
// case ValueInterval:
// t := IntToInterval(left.Int64)
// return IntervalToValue(t -right), nil
// default:
// return Null(), NewArithmeticError("*", left.Type.String(), "datetime")
// }
// } | vm/mul.go | 0.609873 | 0.701851 | mul.go | starcoder |
package telog
import (
"crypto/sha256"
"fmt"
)
type hashPointer struct {
pointer *block
hash string
}
type block struct {
hashPointer hashPointer
data string
}
type Telog struct {
head hashPointer
count int
}
// Init initializes an empty head used for the tamper evident log with SHA-256.
func (t *Telog) Init() {
t.head = hashPointer{}
t.count = 0
}
func (t *Telog) GetNumBlocks() int {
return t.count
}
// hashSha256 returns the hash digest of a block.
func (t *Telog) hashSha256(block block) string {
return fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%v", block))))
}
// AddBlock adds a block with data to the right end of a tamper evident log, where the left end of the log is the first
// data block added and the right end of the log is the last data block added.
func (t *Telog) AddBlock(data string) {
// Create a new block.
newBlock := block{
// Use the old hash pointer of the head to connect the new block to the right-most block
hashPointer: t.head,
data: data,
}
// Hash the new block.
newBlockHash := t.hashSha256(newBlock)
// Connect the head to the new block with a hash pointer.
t.head = hashPointer{
pointer: &newBlock,
hash: newBlockHash,
}
t.count += 1
}
// Check determines if the log has been tampered with, returning true if the log is valid and false if the log was
// tampered with.
func (t *Telog) Check() bool {
currentHashPointer := t.head
emptyHashPointer := hashPointer{}
// Execute as long as there is not a non-empty hash pointer.
for currentHashPointer != emptyHashPointer {
// Access the block pointed to by the hash pointer
currentBlock := *currentHashPointer.pointer
// Rehash the block to check if it was tampered with.
currentBlockHash := t.hashSha256(currentBlock)
if currentBlockHash != currentHashPointer.hash {
return false
}
// Iterate to next pointer
currentHashPointer = currentBlock.hashPointer
}
return true
}
// Attack modifies the block at position idx.
// Position 0 is the genesis block.
func (t *Telog) Attack(idx int) {
// idx starts counting from the genesis block
// reverseIdx starts counting from the head
reverseIdx := t.count - idx
if reverseIdx <= 0 {
fmt.Println("The block to attack does not exist.")
return
}
// Find the pointer to the block that is being attacked
currentHashPointer := t.head
for i := 1; i < reverseIdx; i++{
currentHashPointer = (*currentHashPointer.pointer).hashPointer
}
// Change data in that block to "Attacked"
(*currentHashPointer.pointer).data = "Attacked"
fmt.Println("ATTACK: Block", idx)
} | telog/telog.go | 0.679285 | 0.410756 | telog.go | starcoder |
package main
import "fmt"
import "bufio"
import "os"
import "strings"
/*
Write a program which allows the user to create a set of animals and to get information about those animals. Each animal has a name and can be either a cow, bird, or snake. With each command, the user can either create a new animal of one of the three types, or the user can request information about an animal that he/she has already created. Each animal has a unique name, defined by the user. Note that the user can define animals of a chosen type, but the types of animals are restricted to either cow, bird, or snake. The following table contains the three types of animals and their associated data.
Animal Food eaten Locomtion method Spoken sound
cow grass walk moo
bird worms fly peep
snake mice slither hsss
Your program should present the user with a prompt, “>”, to indicate that the user can type a request. Your program should accept one command at a time from the user, print out a response, and print out a new prompt on a new line. Your program should continue in this loop forever. Every command from the user must be either a “newanimal” command or a “query” command.
Each “newanimal” command must be a single line containing three strings. The first string is “newanimal”. The second string is an arbitrary string which will be the name of the new animal. The third string is the type of the new animal, either “cow”, “bird”, or “snake”. Your program should process each newanimal command by creating the new animal and printing “Created it!” on the screen.
Each “query” command must be a single line containing 3 strings. The first string is “query”. The second string is the name of the animal. The third string is the name of the information requested about the animal, either “eat”, “move”, or “speak”. Your program should process each query command by printing out the requested data.
Define an interface type called Animal which describes the methods of an animal. Specifically, the Animal interface should contain the methods Eat(), Move(), and Speak(), which take no arguments and return no values. The Eat() method should print the animal’s food, the Move() method should print the animal’s locomotion, and the Speak() method should print the animal’s spoken sound. Define three types Cow, Bird, and Snake. For each of these three types, define methods Eat(), Move(), and Speak() so that the types Cow, Bird, and Snake all satisfy the Animal interface. When the user creates an animal, create an object of the appropriate type. Your program should call the appropriate method when the user issues a query command.
*/
var slice []Animal
type Animal interface {
Name() string
Eat()
Move()
Speak()
}
type Cow struct {
name string
food string
locomotion string
sound string
}
func (x Cow) Name() string {
return x.name
}
func (x Cow) Eat() {
fmt.Println(x.food)
}
func (x Cow) Move() {
fmt.Println(x.locomotion)
}
func (x Cow) Speak() {
fmt.Println(x.sound)
}
type Bird struct {
name string
food string
locomotion string
sound string
}
func (x Bird) Name() string {
return x.name
}
func (x Bird) Eat() {
fmt.Println(x.food)
}
func (x Bird) Move() {
fmt.Println(x.locomotion)
}
func (x Bird) Speak() {
fmt.Println(x.sound)
}
type Snake struct {
name string
food string
locomotion string
sound string
}
func (x Snake) Name() string {
return x.name
}
func (x Snake) Eat() {
fmt.Println(x.food)
}
func (x Snake) Move() {
fmt.Println(x.locomotion)
}
func (x Snake) Speak() {
fmt.Println(x.sound)
}
func getNewAnimal(name string, type1 string) Animal {
var a1 Animal
switch type1 {
case "cow":
cow := Cow{name, "grass", "walk", "moo"}
a1 = cow
return a1
case "bird":
bird := Bird{name, "worms", "fly", "peep"}
a1 = bird
return a1
case "snake":
snake := Snake{name, "mice", "slither", "hss"}
a1 = snake
return a1
default:
return nil
}
}
func performAction(name string, info string) {
for _, v := range slice {
if name == v.Name() {
switch info {
case "eat":
v.Eat()
continue
case "move":
v.Move()
continue
case "speak":
v.Speak()
continue
default:
fmt.Println("No such action defined. Use eat, speak or move.")
}
}
}
}
func main() {
inputReader := bufio.NewReader(os.Stdin)
for {
fmt.Printf(">")
input, _ := inputReader.ReadString('\n')
input = strings.ToLower(strings.TrimSuffix(input, "\n"))
command := strings.Split(input, " ")
if command[0] == "newanimal" {
animal := getNewAnimal(command[1], command[2])
fmt.Println(animal)
if animal != nil {
fmt.Println("Created it!")
slice = append(slice, animal)
fmt.Println(slice)
}
} else if command[0] == "query" {
performAction(command[1], command[2])
} else {
fmt.Println("First word needs to be either 'newanimal' or 'query'")
continue
}
}
} | course-2/animals-2/animals.go | 0.555435 | 0.422445 | animals.go | starcoder |
package qunit
//GopherJS Bindings for qunitjs.com
import "github.com/gopherjs/gopherjs/js"
type QUnitAssert struct {
*js.Object
}
type DoneCallbackObject struct {
*js.Object
Failed int `js:"failed"`
Passed int `js:"passed"`
Total int `js:"total"`
Runtime int `js:"runtime"`
}
type LogCallbackObject struct {
*js.Object
result bool `js:"result"`
actual *js.Object `js:"actual"`
expected *js.Object `js:"expected"`
message string `js:"message"`
source string `js:"source"`
}
type ModuleStartCallbackObject struct {
*js.Object
name string `js:"name"`
}
type ModuleDoneCallbackObject struct {
*js.Object
name string `js:"name"`
failed int `js:"failed"`
passed int `js:"passed"`
total int `js:"total"`
}
type TestDoneCallbackObject struct {
*js.Object
name string `js:"name"`
module string `js:"module"`
failed int `js:"failed"`
passed int `js:"passed"`
total int `js:"total"`
duration int `js:"duration"`
}
type TestStartCallbackObject struct {
*js.Object
name string `js:"name"`
module string `js:"module"`
}
func (qa QUnitAssert) DeepEqual(actual interface{}, expected interface{}, message string) bool {
return qa.Call("deepEqual", actual, expected, message).Bool()
}
func (qa QUnitAssert) Equal(actual interface{}, expected interface{}, message string) bool {
return qa.Call("equal", actual, expected, message).Bool()
}
func (qa QUnitAssert) NotDeepEqual(actual interface{}, expected interface{}, message string) bool {
return qa.Call("notDeepEqual", actual, expected, message).Bool()
}
func (qa QUnitAssert) NotEqual(actual interface{}, expected interface{}, message string) bool {
return qa.Call("notEqual", actual, expected, message).Bool()
}
func (qa QUnitAssert) NotPropEqual(actual interface{}, expected interface{}, message string) bool {
return qa.Call("notPropEqual", actual, expected, message).Bool()
}
func (qa QUnitAssert) PropEqual(actual interface{}, expected interface{}, message string) bool {
return qa.Call("propEqual", actual, expected, message).Bool()
}
func (qa QUnitAssert) NotStrictEqual(actual interface{}, expected interface{}, message string) bool {
return qa.Call("notStrictEqual", actual, expected, message).Bool()
}
func (qa QUnitAssert) Ok(state interface{}, message string) bool {
return qa.Call("ok", state, message).Bool()
}
func (qa QUnitAssert) StrictEqual(actual interface{}, expected interface{}, message string) bool {
return qa.Call("strictEqual", actual, expected, message).Bool()
}
func (qa QUnitAssert) ThrowsExpected(block func() interface{}, expected interface{}, message string) *js.Object {
return qa.Call("throwsExpected", block, expected, message)
}
func (qa QUnitAssert) Throws(block func() interface{}, message string) *js.Object {
return qa.Call("throws", block, message)
}
func (qa QUnitAssert) Async() func() {
// Use a closure to wrap around the async javascript object
asyncObj := qa.Call("async")
return func() {
asyncObj.Invoke()
}
}
//start QUnit static methods
func Test(name string, testFn func(QUnitAssert)) {
js.Global.Get("QUnit").Call("test", name, func(e *js.Object) {
testFn(QUnitAssert{Object: e})
})
}
func TestExpected(title string, expected int, testFn func(assert QUnitAssert) interface{}) *js.Object {
t := js.Global.Get("QUnit").Call("test", title, expected, func(e *js.Object) {
testFn(QUnitAssert{Object: e})
})
return t
}
func Ok(state interface{}, message string) *js.Object {
return js.Global.Get("QUnit").Call("ok", state, message)
}
func Start() *js.Object {
return js.Global.Get("QUnit").Call("start")
}
func StartDecrement(decrement int) *js.Object {
return js.Global.Get("QUnit").Call("start", decrement)
}
func Stop() *js.Object {
return js.Global.Get("QUnit").Call("stop")
}
func StopIncrement(increment int) *js.Object {
return js.Global.Get("QUnit").Call("stop", increment)
}
func Begin(callbackFn func() interface{}) *js.Object {
t := js.Global.Get("QUnit").Call("begin", func() {
callbackFn()
})
return t
}
func Done(callbackFn func(details DoneCallbackObject) interface{}) *js.Object {
t := js.Global.Get("QUnit").Call("done", func(e *js.Object) {
callbackFn(DoneCallbackObject{Object: e})
})
return t
}
func Log(callbackFn func(details LogCallbackObject) interface{}) *js.Object {
/*
2do:
t := js.Global.Get("QUnit").Call("log", func(e *js.Object) {
callbackFn(LogCallbackObject{Object: e})
})
*/
t := js.Global.Get("QUnit").Call("log", callbackFn)
return t
}
func ModuleDone(callbackFn func(details ModuleDoneCallbackObject) interface{}) *js.Object {
t := js.Global.Get("QUnit").Call("moduleDone", func(e *js.Object) {
callbackFn(ModuleDoneCallbackObject{Object: e})
})
return t
}
func ModuleStart(callbackFn func(name string) interface{}) *js.Object {
t := js.Global.Get("QUnit").Call("moduleStart", func(e *js.Object) {
callbackFn(e.String())
})
return t
}
func TestDone(callbackFn func(details TestDoneCallbackObject) interface{}) *js.Object {
t := js.Global.Get("QUnit").Call("testDone", func(e *js.Object) {
callbackFn(TestDoneCallbackObject{Object: e})
})
return t
}
func TestStart(callbackFn func(details TestStartCallbackObject) interface{}) *js.Object {
t := js.Global.Get("QUnit").Call("testStart", func(e *js.Object) {
callbackFn(TestStartCallbackObject{Object: e})
})
return t
}
func AsyncTestExpected(name string, expected interface{}, testFn func() interface{}) *js.Object {
t := js.Global.Get("QUnit").Call("asyncTestExpected", name, expected, func() {
testFn()
})
return t
}
func AsyncTest(name string, testFn func() interface{}) *js.Object {
t := js.Global.Get("QUnit").Call("asyncTest", name, func() {
testFn()
})
return t
}
func Expect(amount int) *js.Object {
return js.Global.Get("QUnit").Call("expect", amount)
}
func Equiv(a interface{}, b interface{}) *js.Object {
return js.Global.Get("QUnit").Call("equiv", a, b)
}
func Module(name string) *js.Object {
return js.Global.Get("QUnit").Call("module", name)
}
type Lifecycle interface {
Setup()
Teardown()
}
func ModuleLifecycle(name string, lc Lifecycle) *js.Object {
o := js.Global.Get("Object").New()
if lc.Setup != nil {
o.Set("setup", lc.Setup)
}
if lc.Teardown != nil {
o.Set("teardown", lc.Teardown)
}
return js.Global.Get("QUnit").Call("module", name, o)
}
type Raises struct {
*js.Object
Raises *js.Object `js:"raises"`
}
func Push(result interface{}, actual interface{}, expected interface{}, message string) *js.Object {
return js.Global.Get("QUnit").Call("push", result, actual, expected, message)
}
func Reset() *js.Object {
return js.Global.Get("QUnit").Call("reset")
} | vendor/github.com/rusco/qunit/qunit.go | 0.748904 | 0.456773 | qunit.go | starcoder |
package opencl
// Convolution self-test, performed once at the start of each simulation
import (
"math/rand"
data "github.com/seeder-research/uMagNUS/data"
util "github.com/seeder-research/uMagNUS/util"
)
// Compares FFT-accelerated convolution against brute-force on sparse data.
// This is not really needed but very quickly uncovers newly introduced bugs.
func testConvolution(c *DemagConvolution, PBC [3]int, realKern [3][3]*data.Slice) {
if PBC != [3]int{0, 0, 0} {
// the brute-force method does not work for pbc.
util.Log("skipping convolution self-test for PBC")
return
}
util.Log("//convolution self-test...")
inhost := data.NewSlice(3, c.inputSize)
initConvTestInput(inhost.Vectors())
gpu := NewSlice(3, c.inputSize)
defer gpu.Free()
data.Copy(gpu, inhost)
Msat := NewSlice(1, [3]int{1, 1, 256})
defer Msat.Free()
Memset(Msat, 1)
vol := data.NilSlice(1, c.inputSize)
c.Exec(gpu, gpu, vol, ToMSlice(Msat))
output := gpu.HostCopy()
brute := data.NewSlice(3, c.inputSize)
bruteConv(inhost.Vectors(), brute.Vectors(), realKern)
a, b := output.Host(), brute.Host()
err := float32(0)
for c := range a {
for i := range a[c] {
if fabs(a[c][i]-b[c][i]) > err {
err = fabs(a[c][i] - b[c][i])
}
}
}
if err > CONV_TOLERANCE {
util.Fatal("convolution self-test tolerance: ", err, " FAIL")
}
}
// Maximum tolerable error on demag convolution self-test.
const CONV_TOLERANCE = 1e-6
// Brute-force O(N²) vector convolution on CPU.
// Used to verify GPU FFT convolution.
// Input better be sparse.
// A nil kernel element is interpreted as all 0s.
// Kernel indices are destination index, source index.
// (O0) (K01 K02 K03) (I0)
// (O1) = (K11 K12 K13) * (I1)
// (O2) (K21 K22 K23) (I2)
func bruteConv(in, out [3][][][]float32, kernel [3][3]*data.Slice) {
var kern [3][3][][][]float32
for i := range kern {
for j := range kern[i] {
if kernel[i][j] != nil {
kern[i][j] = kernel[i][j].Scalars()
}
}
}
size := sizeOf(in[0])
ksize := sizeOf(kern[0][0])
// Zero output first
for c := 0; c < 3; c++ {
for iz := 0; iz < size[Z]; iz++ {
for iy := 0; iy < size[Y]; iy++ {
for ix := 0; ix < size[X]; ix++ {
out[c][iz][iy][ix] = 0
}
}
}
}
for sc := 0; sc < 3; sc++ {
for sz := 0; sz < size[Z]; sz++ {
for sy := 0; sy < size[Y]; sy++ {
for sx := 0; sx < size[X]; sx++ {
if in[sc][sz][sy][sx] == 0 {
continue // skip zero source
}
for dc := 0; dc < 3; dc++ { // dest component
if kern[dc][sc] == nil {
continue // skip zero kernel
}
for dz := 0; dz < size[Z]; dz++ {
k := wrap(dz-sz, ksize[Z])
for dy := 0; dy < size[Y]; dy++ {
j := wrap(dy-sy, ksize[Y])
for dx := 0; dx < size[X]; dx++ {
i := wrap(dx-sx, ksize[X])
out[dc][dz][dy][dx] += in[sc][sz][sy][sx] * kern[dc][sc][k][j][i]
}
}
}
}
}
}
}
}
}
// Wraps an index to [0, max] (python-like modulus)
func wrap(number, max int) int {
for number < 0 {
number += max
}
for number >= max {
number -= max
}
return number
}
// generate sparse input data for testing the convolution.
func initConvTestInput(input [3][][][]float32) {
rng := rand.New(rand.NewSource(0)) // reproducible tests
size := sizeOf(input[0])
Nx, Ny, Nz := size[X], size[Y], size[Z]
ixs := [...]int{0, Nx / 5, Nx / 2, Nx - 1}
iys := [...]int{0, Ny / 7, Ny / 2, Ny - 1}
izs := [...]int{0, Nz / 11, Nz / 2, Nz - 1}
for c := range input {
for _, i := range izs {
for _, j := range iys {
for _, k := range ixs {
input[c][i][j][k] = 1 - 2*rng.Float32()
}
}
}
}
}
// Returns the x, y, z size of block
func sizeOf(block [][][]float32) [3]int {
return [3]int{len(block[0][0]), len(block[0]), len(block)}
} | opencl/conv_selftest.go | 0.765155 | 0.504028 | conv_selftest.go | starcoder |
package gg
import (
"image"
"image/color"
"github.com/golang/freetype/truetype"
)
type LineCap int
const (
LineCapRound LineCap = iota
LineCapButt
LineCapSquare
)
type LineJoin int
const (
LineJoinRound LineJoin = iota
LineJoinBevel
)
type FillRule int
const (
FillRuleWinding FillRule = iota
FillRuleEvenOdd
)
type Align int
const (
AlignLeft Align = iota
AlignCenter
AlignRight
)
// GraphicContext describes the interface for the various backends (images, pdf, opengl, ...)
type GraphicContext interface {
// Width returns the width of the context
Width() float64
// Height returns the height of the context
Height() float64
// BeginPath creates a new path
BeginPath()
// MoveTo creates a new subpath that start at the specified point
MoveTo(x, y float64)
// LineTo adds a line to the current subpath
LineTo(x, y float64)
// QuadraticTo adds a quadratic Bézier curve to the current subpath
QuadraticTo(x1, y1, x2, y2 float64)
// ArcTo adds a circular arc to the current sub-path, using
// the given control points and radius.
ArcTo(x1, y1, x2, y2, radius float64)
// Close creates a line from the current point to the last MoveTo
// point (if not the same) and mark the path as closed so the
// first and last lines join nicely.
ClosePath()
// CurrentPoint returns the current point of the current sub path
CurrentPoint() (float64, float64, bool)
// SetStrokeColor sets the current stroke color
SetStrokeColor(r, g, b, a int)
// SetFillColor sets the current fill color
SetFillColor(r, g, b, a int)
// SetFillRule sets the current fill rule
SetFillRule(f FillRule)
// SetFillStyle sets current fill style
SetFillStyle(pattern Pattern)
// SetStrokeStyle sets current stroke style
SetStrokeStyle(pattern Pattern)
// SetStrokeWeight sets the current line width
SetStrokeWeight(lineWidth float64)
// StrokeWeight returns the current line width
StrokeWeight() float64
// SetLineCap sets the current line cap
SetLineCap(cap LineCap)
// SetLineJoin sets the current line join
SetLineJoin(join LineJoin)
// SetLineDash sets the current dash
SetLineDash(dashes ...float64)
// SetLineDashOffset sets the initial offset into
// the dash pattern to use when stroking dashed paths.
SetLineDashOffset(dashOffset float64)
// SetFontSize sets the current font size
SetFontSize(fontSize float64)
// FontSize returns the current font size
FontSize() float64
// SetFont sets the current font
SetFont(f *truetype.Font)
// Identity resets the current transformation matrix to the identity matrix.
// This results in no translating, scaling, rotating, or shearing.
Identity()
// Rotate applies a rotation to the current transformation matrix. angle is in radian.
Rotate(angle float64)
// Translate applies a translation to the current transformation matrix.
Translate(tx, ty float64)
// Scale applies a scale to the current transformation matrix.
Scale(sx, sy float64)
// TransformPoint multiplies the specified point by the current matrix,
// returning a transformed position.
TransformPoint(x, y float64) (float64, float64)
// GetMatrix returns the Transformation Matrix
GetMatrix() Matrix
// SetMatrix sets the current transformation matrix
SetMatrix(m Matrix)
// Push saves the current state of the context for later retrieval. These
// can be nested.
Push()
// Pop restores the last saved context state from the stack
Pop()
// Clear fills the current canvas with a default transparent color
Clear()
// Stroke strokes the paths with the color specified by SetStrokeColor
Stroke()
// Fill fills the paths with the color specified by SetFillColor
Fill()
// FillAndStroke first fills the current path and than strokes it
FillAndStroke()
// SetPixelColor sets the color of the specified pixel using the current color.
SetPixelColor(c color.Color, x, y int)
// DrawPoint draws a point
DrawPoint(x, y float64)
// DrawLine draws a line
DrawLine(x1, y1, x2, y2 float64)
// DrawEllipticalArc draws an elliptical arc
DrawEllipticalArc(x, y, rx, ry, angle1, angle2 float64)
// DrawImageAnchored draws the specified image at the specified anchor point
DrawImageAnchored(im image.Image, x, y int, ax, ay float64)
// DrawStringAnchored draws the specified text at the specified anchor point.
// The anchor point is x - w * ax, y - h * ay, where w, h is the size of the
// text. Use ax=0.5, ay=0.5 to center the text at the specified point.
DrawStringAnchored(s string, x, y, ax, ay float64)
// MeasureString returns the rendered width and height of the specified text
// given the current font face.
MeasureString(s string) (w, h float64)
// Clip updates the clipping region by intersecting the current
// clipping region with the current path as it would be filled by dc.Fill().
// The path is cleared after this operation.
Clip()
// ResetClip clears the clipping region.
ResetClip()
} | context.go | 0.701917 | 0.528533 | context.go | starcoder |
package function
import (
"errors"
"fmt"
"regexp"
"time"
"github.com/dolthub/go-mysql-server/sql"
)
var offsetRegex = regexp.MustCompile(`(?m)^(\+|\-)(\d{2}):(\d{2})$`) // (?m)^\+|\-(\d{2}):(\d{2})$
type ConvertTz struct {
dt sql.Expression
fromTz sql.Expression
toTz sql.Expression
}
var _ sql.FunctionExpression = (*ConvertTz)(nil)
// NewConvertTz returns an implementation of the CONVERT_TZ() function.
func NewConvertTz(dt, fromTz, toTz sql.Expression) sql.Expression {
return &ConvertTz{
dt: dt,
fromTz: fromTz,
toTz: toTz,
}
}
// Resolved implements the sql.Expression interface.
func (c *ConvertTz) Resolved() bool {
return c.dt.Resolved() && c.fromTz.Resolved() && c.toTz.Resolved()
}
// String implements the sql.Expression interface.
func (c *ConvertTz) String() string {
return fmt.Sprintf("CONVERT_TZ(%s, %s, %s)", c.dt, c.fromTz, c.toTz)
}
// Type implements the sql.Expression interface.
func (c *ConvertTz) Type() sql.Type {
return sql.Datetime
}
// IsNullable implements the sql.Expression interface.
func (c *ConvertTz) IsNullable() bool {
return true
}
// Eval implements the sql.Expression interface.
func (c *ConvertTz) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) {
from, err := c.fromTz.Eval(ctx, row)
if err != nil {
return nil, err
}
to, err := c.toTz.Eval(ctx, row)
if err != nil {
return nil, err
}
dt, err := c.dt.Eval(ctx, row)
if err != nil {
return nil, err
}
// If either the date, or the timezones/offsets are not correct types we return NULL.
datetime, err := sql.Datetime.ConvertWithoutRangeCheck(dt)
if err != nil {
return nil, nil
}
fromStr, ok := from.(string)
if !ok {
return nil, nil
}
toStr, ok := to.(string)
if !ok {
return nil, nil
}
converted, success := convertTimeZone(datetime, fromStr, toStr)
if success {
return sql.Datetime.ConvertWithoutRangeCheck(converted)
}
// If we weren't successful converting by timezone try converting via offsets.
converted, success = convertOffsets(datetime, fromStr, toStr)
if !success {
return nil, nil
}
return sql.Datetime.ConvertWithoutRangeCheck(converted)
}
// convertTimeZone returns the conversion of t from timezone fromLocation to toLocation.
func convertTimeZone(datetime time.Time, fromLocation string, toLocation string) (time.Time, bool) {
fLoc, err := time.LoadLocation(fromLocation)
if err != nil {
return time.Time{}, false
}
tLoc, err := time.LoadLocation(toLocation)
if err != nil {
return time.Time{}, false
}
delta := getCopy(datetime, fLoc).Sub(getCopy(datetime, tLoc))
return datetime.Add(delta), true
}
// getCopy recreates the time t in the wanted timezone.
func getCopy(t time.Time, loc *time.Location) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), loc).UTC()
}
// convertOffsets returns the conversion of t to t + (endDuration - startDuration) and a boolean indicating success.
func convertOffsets(t time.Time, startDuration string, endDuration string) (time.Time, bool) {
fromDuration, err := getDeltaAsDuration(startDuration)
if err != nil {
return time.Time{}, false
}
toDuration, err := getDeltaAsDuration(endDuration)
if err != nil {
return time.Time{}, false
}
return t.Add(toDuration - fromDuration), true
}
// getDeltaAsDuration takes in a MySQL offset in the format (ex +01:00) and returns it as a time Duration.
func getDeltaAsDuration(d string) (time.Duration, error) {
var hours string
var mins string
var symbol string
matches := offsetRegex.FindStringSubmatch(d)
if len(matches) == 4 {
symbol = matches[1]
hours = matches[2]
mins = matches[3]
} else {
return -1, errors.New("error: unable to process time")
}
return time.ParseDuration(symbol + hours + "h" + mins + "m")
}
// Children implements the sql.Expression interface.
func (c *ConvertTz) Children() []sql.Expression {
return []sql.Expression{c.dt, c.fromTz, c.toTz}
}
// WithChildren implements the sql.Expression interface.
func (c *ConvertTz) WithChildren(children ...sql.Expression) (sql.Expression, error) {
if len(children) != 3 {
return nil, sql.ErrInvalidChildrenNumber.New(c, len(children), 3)
}
return NewConvertTz(children[0], children[1], children[2]), nil
}
// FunctionName implement the sql.FunctionExpression interface.
func (c *ConvertTz) FunctionName() string {
return "convert_tz"
} | sql/expression/function/convert_tz.go | 0.746139 | 0.454533 | convert_tz.go | starcoder |
package types
import "encoding/binary"
// Encoder stores the information necessary for the encoding functions
type Encoder struct {
data []byte
}
// NewEncoder returns an empty Encoder struct
func NewEncoder() Encoder {
return Encoder{
data: []byte{},
}
}
// GetEncodedData returns the `data` byte slice containing all the previously encoded data
func (encoder *Encoder) GetEncodedData() []byte {
return encoder.data
}
// EncodeU8 takes an `uint8` variable and encodes it into a byte array
func (encoder *Encoder) EncodeU8(value uint8) {
encoder.data = append(encoder.data, value)
}
// EncodeU16 takes an `uint16` variable and encodes it into a byte array
func (encoder *Encoder) EncodeU16(value uint16) {
bytes := make([]byte, 2)
binary.LittleEndian.PutUint16(bytes, value)
encoder.data = append(encoder.data, bytes...)
}
// EncodeU32 takes an `uint32` variable and encodes it into a byte array
func (encoder *Encoder) EncodeU32(value uint32) {
bytes := make([]byte, 4)
binary.LittleEndian.PutUint32(bytes, value)
encoder.data = append(encoder.data, bytes...)
}
// EncodeU64 takes an `uint64` variable and encodes it into a byte array
func (encoder *Encoder) EncodeU64(value uint64) {
bytes := make([]byte, 8)
binary.LittleEndian.PutUint64(bytes, value)
encoder.data = append(encoder.data, bytes...)
}
// EncodeSigned8 takes an `int8` variable and encodes it into a byte array
func (encoder *Encoder) EncodeSigned8(value int8) {
uintValue := uint8(value)
encoder.EncodeU8(uintValue)
}
// EncodeSigned16 takes an `int16` variable and encodes it into a byte array
func (encoder *Encoder) EncodeSigned16(value int16) {
uintValue := uint16(value)
encoder.EncodeU16(uintValue)
}
// EncodeSigned32 takes an `int32` variable and encodes it into a byte array
func (encoder *Encoder) EncodeSigned32(value int32) {
uintValue := uint32(value)
encoder.EncodeU32(uintValue)
}
// EncodeSigned64 takes an `int64` variable and encodes it into a byte array
func (encoder *Encoder) EncodeSigned64(value int64) {
uintValue := uint64(value)
encoder.EncodeU64(uintValue)
}
// EncodeBytes takes a `[]byte` variable and encodes it into a byte array
func (encoder *Encoder) EncodeBytes(value []byte) {
encoder.EncodeU32(uint32(len(value)))
encoder.data = append(encoder.data, value...)
}
// EncodeString takes a `string` variable and encodes it into a byte array
func (encoder *Encoder) EncodeString(value string) {
stringBytes := []byte(value)
encoder.EncodeU32(uint32(len(stringBytes)))
encoder.data = append(encoder.data, stringBytes...)
} | x/sunchain/types/encoder.go | 0.831554 | 0.566798 | encoder.go | starcoder |
package detour
/// Defines polygon filtering and traversal costs for navigation mesh query operations.
/// @ingroup detour
type DtQueryFilter struct {
m_areaCost [DT_MAX_AREAS]float32 ///< Cost per area type. (Used by default implementation.)
m_includeFlags uint16 ///< Flags for polygons that can be visited. (Used by default implementation.)
m_excludeFlags uint16 ///< Flags for polygons that should not be visted. (Used by default implementation.)
}
/// @name Getters and setters for the default implementation data.
///@{
/// Returns the traversal cost of the area.
/// @param[in] i The id of the area.
/// @returns The traversal cost of the area.
func (this *DtQueryFilter) GetAreaCost(i int) float32 { return this.m_areaCost[i] }
/// Sets the traversal cost of the area.
/// @param[in] i The id of the area.
/// @param[in] cost The new cost of traversing the area.
func (this *DtQueryFilter) SetAreaCost(i int, cost float32) { this.m_areaCost[i] = cost }
/// Returns the include flags for the filter.
/// Any polygons that include one or more of these flags will be
/// included in the operation.
func (this *DtQueryFilter) GetIncludeFlags() uint16 { return this.m_includeFlags }
/// Sets the include flags for the filter.
/// @param[in] flags The new flags.
func (this *DtQueryFilter) SetIncludeFlags(flags uint16) { this.m_includeFlags = flags }
/// Returns the exclude flags for the filter.
/// Any polygons that include one ore more of these flags will be
/// excluded from the operation.
func (this *DtQueryFilter) GetExcludeFlags() uint16 { return this.m_excludeFlags }
/// Sets the exclude flags for the filter.
/// @param[in] flags The new flags.
func (this *DtQueryFilter) SetExcludeFlags(flags uint16) { this.m_excludeFlags = flags }
///@}
func DtAllocDtQueryFilter() *DtQueryFilter {
filter := &DtQueryFilter{}
filter.constructor()
return filter
}
func DtFreeDtQueryFilter(filter *DtQueryFilter) {
if filter == nil {
return
}
filter.destructor()
}
/// Provides information about raycast hit
/// filled by dtNavMeshQuery::raycast
/// @ingroup detour
type DtRaycastHit struct {
/// The hit parameter. (FLT_MAX if no wall hit.)
T float32
/// hitNormal The normal of the nearest wall hit. [(x, y, z)]
HitNormal [3]float32
/// The index of the edge on the final polygon where the wall was hit.
HitEdgeIndex int32
/// Pointer to an array of reference ids of the visited polygons. [opt]
Path []DtPolyRef
/// The number of visited polygons. [opt]
PathCount int32
/// The maximum number of polygons the @p path array can hold.
MaxPath int32
/// The cost of the path until hit.
PathCost float32
}
/// Provides custom polygon query behavior.
/// Used by dtNavMeshQuery::queryPolygons.
/// @ingroup detour
type DtPolyQuery interface {
/// Called for each batch of unique polygons touched by the search area in dtNavMeshQuery::queryPolygons.
/// This can be called multiple times for a single query.
Process(tile *DtMeshTile, polys []*DtPoly, refs []DtPolyRef, count int)
}
type dtQueryData struct {
status DtStatus
lastBestNode *DtNode
lastBestNodeCost float32
startRef DtPolyRef
endRef DtPolyRef
startPos [3]float32
endPos [3]float32
filter *DtQueryFilter
options DtFindPathOptions
raycastLimitSqr float32
}
type DtNavMeshQuery struct {
m_nav *DtNavMesh ///< Pointer to navmesh data.
m_query dtQueryData ///< Sliced query state.
m_tinyNodePool *DtNodePool ///< Pointer to small node pool.
m_nodePool *DtNodePool ///< Pointer to node pool.
m_openList *DtNodeQueue ///< Pointer to open list queue.
}
/// Allocates a query object using the Detour allocator.
/// @return An allocated query object, or null on failure.
/// @ingroup detour
func DtAllocNavMeshQuery() *DtNavMeshQuery {
query := &DtNavMeshQuery{}
query.constructor()
return query
}
/// Frees the specified query object using the Detour allocator.
/// @param[in] query A query object allocated using #dtAllocNavMeshQuery
/// @ingroup detour
func DtFreeNavMeshQuery(query *DtNavMeshQuery) {
if query == nil {
return
}
query.destructor()
} | vendor/github.com/fananchong/recastnavigation-go/Detour/DetourNavMeshQuery.go | 0.872958 | 0.570032 | DetourNavMeshQuery.go | starcoder |
package parser
import (
"strconv"
"strings"
"github.com/census-ecosystem/opencensus-experiments/go/iot/protocol"
"github.com/pkg/errors"
)
type TextParser struct {
}
// In this function, it firstly transform the input byte stream into a map of string -> interface{}.
// If it manages so, it would extract the required variable as defined in the protocol.
// Otherwise it would return an un-empty error.
func (parser *TextParser) DecodeMeasurement(input []byte) (protocol.MeasureArgument, error) {
var output protocol.MeasureArgument
// parseResult is only the transition result of parse. It is in the form of map[string]interface{}
// Using the interface{} can make it more general since we might change the protocol in the future.
var parseResult map[string]interface{} = make(map[string]interface{})
ss := string(input)
// First of all, find the outermost layer of bracket.
firstBracketPos := strings.Index(ss, "{")
lastBracketPos := strings.LastIndex(ss, "}")
if firstBracketPos == -1 || lastBracketPos == -1 {
return output, errors.Errorf("Unpaired brackets in the two end of input string")
}
// Then trim the leading and trailing bracket of the string
ss = ss[firstBracketPos+1 : lastBracketPos]
err := parser.helper(ss, parseResult)
// If the error is not empty, return it.
if err != nil {
return output, err
}
var ok bool
output.Name, ok = parseResult["Name"].(string)
if ok == false {
return output, errors.Errorf("Value for Name is not valid string")
}
output.Value, ok = parseResult["Value"].(string)
if ok == false {
return output, errors.Errorf("Value for Measurement is not valid string")
}
output.Tags = make(map[string]string)
// Since we would not assert the type of map[string]interface{} to map[string]string, we need to copy one by one
for k, v := range parseResult["Tags"].(map[string]interface{}) {
output.Tags[k], ok = v.(string)
if ok == false {
//fmt.Print(test)
return output, errors.Errorf("Value for Tags key pair is not valid string")
}
}
return output, nil
}
// The input string of helper function is already trimmed of the leading and trailing bracket.
func (parser *TextParser) helper(ss string, res map[string]interface{}) error {
// Judge whether there are nested brackets
var pos int = strings.Index(ss, "{")
if pos == -1 {
// No nested brackets. We could parse the string through the helper function.
err := parser.parseWithNoBracket(ss, res)
return err
} else {
// Nested Bracket exists in the string. Currently we know the start of nested string, we firstly find its end
count := 1
lastBracket := pos + 1
for ; lastBracket < len(ss); lastBracket = lastBracket + 1 {
if ss[lastBracket] == '}' {
count = count - 1
}
if ss[lastBracket] == '{' {
count = count + 1
}
if count == 0 {
break
}
}
// If the count is not zero after we traverse the whole string, it means that left and right brackets are not paired
if count != 0 {
return errors.Errorf("Nested bracket unvalid")
}
var nestedResult map[string]interface{} = make(map[string]interface{})
// Recursively handle the string without leading and trailing brackets
err := parser.helper(ss[pos+1:lastBracket], nestedResult)
if err != nil {
return nil
} else {
// We would need to find the key of this nestedResult
start := pos - 1
for start >= 0 && ss[start] != '"' {
start = start - 1
}
if start == -1 {
return errors.Errorf("No key found!")
}
end := start - 1
for end >= 0 && ss[end] != '"' {
end = end - 1
}
if end == -1 {
return errors.Errorf("No pair of quatation mark found")
}
key := ss[end+1 : start]
if len(key) == 0 {
return errors.Errorf("Key is empty string")
}
res[key] = nestedResult
// Before 'end', there is no bracket, which means there is no nested brackets. So we call the helper function
if err := parser.parseWithNoBracket(ss[0:end], res); err != nil {
return err
}
if lastBracket+1 == len(ss) {
// The end of string
return nil
} else {
// There are key-value pairs left behind. We should continue to parse the rest of string
if err := parser.helper(ss[lastBracket+1:len(ss)], res); err != nil {
return err
}
}
}
}
return nil
}
// This function parses the string without any nested map as the value
// The input map is the reference to the parse result
func (parser *TextParser) parseWithNoBracket(ss string, res map[string]interface{}) error {
ss = strings.Trim(ss, " ")
ss = strings.Trim(ss, ",")
ss = strings.Trim(ss, " ")
if len(ss) == 0 {
// Remaining characters are all whitespaces
return nil
}
// Key-value pair in the string are separated by comma.
sspairs := strings.Split(ss, ",")
// If there are not key-value pair in the string, directly return a empty map
for _, sspair := range sspairs {
// Key and value in the pair are separated by colons.
kvpair := strings.Split(sspair, ":")
if len(kvpair) != 2 {
return errors.Errorf("More than one colon in the key/value pairs")
}
// before handling the key and value, we need trim all the leading and trailing whitespaces of them
key := strings.Trim(kvpair[0], " ")
value := strings.Trim(kvpair[1], " ")
// Since every key / value has a leading / trailing bracket, its size has to be larger than 2.
if len(key) <= 2 || len(value) <= 2 {
return errors.Errorf("Key or Value is Empty")
}
// Every key / value has a leading / trailing bracket, otherwise it's invalid.
if key[0] != '"' || key[len(key)-1] != '"' {
return errors.Errorf("Key not started or ended with quataion marks")
}
// Character on the both side of value has to form a pair of quataion marks
if value[0] != '"' || value[len(value)-1] != '"' {
return errors.Errorf("Value not started / ended with quatation marks / brackets")
}
key = key[1 : len(key)-1]
value = value[1 : len(value)-1]
res[key] = value
}
return nil
}
func (parser *TextParser) EncodeResponse(myResponse *protocol.Response) ([]byte, error) {
// Format is {"Code" : 200, "Info" : "TMP"}
var res string = "{\"Code\":" + strconv.Itoa(myResponse.Code) + ",\"Info\":\"" + myResponse.Info + "\"}"
return []byte(res), nil
} | go/iot/protocol/parser/textParser.go | 0.617397 | 0.402333 | textParser.go | starcoder |
package solver
import (
"bufio"
"fmt"
"io"
"strconv"
"strings"
)
// ParseCardConstrs parses the given cardinality constraints.
// Will panic if a zero value appears in the literals.
func ParseCardConstrs(constrs []CardConstr) *Problem {
var pb Problem
for _, constr := range constrs {
card := constr.AtLeast
if card <= 0 { // Clause is trivially SAT, ignore
continue
}
if len(constr.Lits) < card { // Clause cannot be satsfied
pb.Status = Unsat
return &pb
}
if len(constr.Lits) == card { // All lits must be true
for i := range constr.Lits {
if constr.Lits[i] == 0 {
panic("literal 0 found in clause")
}
lit := IntToLit(int32(constr.Lits[i]))
v := lit.Var()
if int(v) >= pb.NbVars {
pb.NbVars = int(v) + 1
}
pb.Units = append(pb.Units, lit)
}
} else {
lits := make([]Lit, len(constr.Lits))
for j, val := range constr.Lits {
if val == 0 {
panic("literal 0 found in clause")
}
lits[j] = IntToLit(int32(val))
if v := int(lits[j].Var()); v >= pb.NbVars {
pb.NbVars = v + 1
}
}
pb.Clauses = append(pb.Clauses, NewCardClause(lits, card))
}
}
pb.Model = make([]decLevel, pb.NbVars)
for _, unit := range pb.Units {
v := unit.Var()
if pb.Model[v] == 0 {
if unit.IsPositive() {
pb.Model[v] = 1
} else {
pb.Model[v] = -1
}
} else if pb.Model[v] > 0 != unit.IsPositive() {
pb.Status = Unsat
return &pb
}
}
pb.simplifyCard()
return &pb
}
func (pb *Problem) appendClause(constr PBConstr) {
lits := make([]Lit, len(constr.Lits))
for j, val := range constr.Lits {
lits[j] = IntToLit(int32(val))
}
pb.Clauses = append(pb.Clauses, NewPBClause(lits, constr.Weights, constr.AtLeast))
}
// ParsePBConstrs parses and returns a PB problem from PBConstr values.
func ParsePBConstrs(constrs []PBConstr) *Problem {
var pb Problem
for _, constr := range constrs {
for i := range constr.Lits {
lit := IntToLit(int32(constr.Lits[i]))
v := lit.Var()
if int(v) >= pb.NbVars {
pb.NbVars = int(v) + 1
}
}
card := constr.AtLeast
if card <= 0 { // Clause is trivially SAT, ignore
continue
}
sumW := constr.WeightSum()
if sumW < card { // Clause cannot be satsfied
pb.Status = Unsat
return &pb
}
if sumW == card { // All lits must be true
for i := range constr.Lits {
lit := IntToLit(int32(constr.Lits[i]))
found := false
for _, u := range pb.Units {
if u == lit {
found = true
break
}
}
if !found {
pb.Units = append(pb.Units, lit)
}
}
} else {
pb.appendClause(constr)
}
}
pb.Model = make([]decLevel, pb.NbVars)
for _, unit := range pb.Units {
v := unit.Var()
if pb.Model[v] == 0 {
if unit.IsPositive() {
pb.Model[v] = 1
} else {
pb.Model[v] = -1
}
} else if pb.Model[v] > 0 != unit.IsPositive() {
pb.Status = Unsat
return &pb
}
}
pb.simplifyPB()
return &pb
}
// parsePBOptim parses the "min:" instruction.
func (pb *Problem) parsePBOptim(fields []string, line string) error {
weights, lits, err := pb.parseTerms(fields[1:], line)
if err != nil {
return err
}
pb.minLits = make([]Lit, len(lits))
for i, lit := range lits {
pb.minLits[i] = IntToLit(int32(lit))
}
pb.minWeights = weights
return nil
}
func (pb *Problem) parsePBLine(line string) error {
if line[len(line)-1] != ';' {
return fmt.Errorf("line %q does not end with semicolon", line)
}
fields := strings.Fields(line[:len(line)-1])
if len(fields) == 0 {
return fmt.Errorf("empty line in file")
}
if fields[0] == "min:" { // Optimization constraint
return pb.parsePBOptim(fields, line)
}
return pb.parsePBConstrLine(fields, line)
}
func (pb *Problem) parsePBConstrLine(fields []string, line string) error {
if len(fields) < 3 {
return fmt.Errorf("invalid syntax %q", line)
}
operator := fields[len(fields)-2]
if operator != ">=" && operator != "=" {
return fmt.Errorf("invalid operator %q in %q: expected \">=\" or \"=\"", operator, line)
}
rhs, err := strconv.Atoi(fields[len(fields)-1])
if err != nil {
return fmt.Errorf("invalid value %q in %q: %v", fields[len(fields)-1], line, err)
}
weights, lits, err := pb.parseTerms(fields[:len(fields)-2], line)
if err != nil {
return err
}
var constrs []PBConstr
if operator == ">=" {
constrs = []PBConstr{GtEq(lits, weights, rhs)}
} else {
constrs = Eq(lits, weights, rhs)
}
for _, constr := range constrs {
card := constr.AtLeast
sumW := constr.WeightSum()
if sumW < card { // Clause cannot be satsfied
pb.Status = Unsat
return nil
}
if sumW == card { // All lits must be true
for i := range constr.Lits {
lit := IntToLit(int32(constr.Lits[i]))
pb.Units = append(pb.Units, lit)
}
} else {
lits := make([]Lit, len(constr.Lits))
for j, val := range constr.Lits {
lits[j] = IntToLit(int32(val))
}
pb.Clauses = append(pb.Clauses, NewPBClause(lits, constr.Weights, card))
}
}
return nil
}
func (pb *Problem) parseTerms(terms []string, line string) (weights []int, lits []int, err error) {
weights = make([]int, 0, len(terms)/2)
lits = make([]int, 0, len(terms)/2)
i := 0
for i < len(terms) {
var l string
w, err := strconv.Atoi(terms[i])
if err != nil {
l = terms[i]
if !strings.HasPrefix(l, "x") && !strings.HasPrefix(l, "~x") {
return nil, nil, fmt.Errorf("invalid weight %q in %q: %v", terms[i*2], line, err)
}
// This is a weightless lit, i.e a lit with weight 1.
weights = append(weights, 1)
} else {
weights = append(weights, w)
i++
l = terms[i]
if !strings.HasPrefix(l, "x") && !strings.HasPrefix(l, "~x") || len(l) < 2 {
return nil, nil, fmt.Errorf("invalid variable name %q in %q", l, line)
}
}
var lit int
if l[0] == '~' {
lit, err = strconv.Atoi(l[2:])
lits = append(lits, -lit)
} else {
lit, err = strconv.Atoi(l[1:])
lits = append(lits, lit)
}
if err != nil {
return nil, nil, fmt.Errorf("invalid variable %q in %q: %v", l, line, err)
}
if lit > pb.NbVars {
pb.NbVars = lit
}
i++
}
return weights, lits, nil
}
// ParseOPB parses a file corresponding to the OPB syntax.
// See http://www.cril.univ-artois.fr/PB16/format.pdf for more details.
func ParseOPB(f io.Reader) (*Problem, error) {
scanner := bufio.NewScanner(f)
var pb Problem
for scanner.Scan() {
line := scanner.Text()
if line == "" || line[0] == '*' {
continue
}
if err := pb.parsePBLine(line); err != nil {
return nil, err
}
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("could not parse OPB: %v", err)
}
pb.Model = make([]decLevel, pb.NbVars)
pb.simplifyPB()
return &pb, nil
} | vendor/github.com/crillab/gophersat/solver/parser_pb.go | 0.645455 | 0.419588 | parser_pb.go | starcoder |
package brickcolor
import "image/color"
var (
White = BrickColor{Hex: "#F2F3F3", Number: 1, RGBA: color.RGBA{242, 243, 243, 255}, Name: "White"}
Grey = BrickColor{Hex: "#A1A5A2", Number: 2, RGBA: color.RGBA{161, 165, 162, 255}, Name: "Grey"}
LightYellow = BrickColor{Hex: "#F9E999", Number: 3, RGBA: color.RGBA{249, 233, 153, 255}, Name: "Light yellow"}
BrickYellow = BrickColor{Hex: "#D7C59A", Number: 5, RGBA: color.RGBA{215, 197, 154, 255}, Name: "Brick yellow"}
LightGreenMint = BrickColor{Hex: "#C2DAB8", Number: 6, RGBA: color.RGBA{194, 218, 184, 255}, Name: "Light green (Mint)"}
LightReddishViolet = BrickColor{Hex: "#E8BAC8", Number: 9, RGBA: color.RGBA{232, 186, 200, 255}, Name: "Light reddish violet"}
PastelBlue = BrickColor{Hex: "#80BBDB", Number: 11, RGBA: color.RGBA{128, 187, 219, 255}, Name: "Pastel Blue"}
LightOrangeBrown = BrickColor{Hex: "#CB8442", Number: 12, RGBA: color.RGBA{203, 132, 66, 255}, Name: "Light orange brown"}
Nougat = BrickColor{Hex: "#CC8E69", Number: 18, RGBA: color.RGBA{204, 142, 105, 255}, Name: "Nougat"}
BrightRed = BrickColor{Hex: "#C4281C", Number: 21, RGBA: color.RGBA{196, 40, 28, 255}, Name: "Bright red"}
MedReddishViolet = BrickColor{Hex: "#C470A0", Number: 22, RGBA: color.RGBA{196, 112, 160, 255}, Name: "Med. reddish violet"}
BrightBlue = BrickColor{Hex: "#0D69AC", Number: 23, RGBA: color.RGBA{13, 105, 172, 255}, Name: "Bright blue"}
BrightYellow = BrickColor{Hex: "#F5CD30", Number: 24, RGBA: color.RGBA{245, 205, 48, 255}, Name: "Bright yellow"}
EarthOrange = BrickColor{Hex: "#624732", Number: 25, RGBA: color.RGBA{98, 71, 50, 255}, Name: "Earth orange"}
Black = BrickColor{Hex: "#1B2A35", Number: 26, RGBA: color.RGBA{27, 42, 53, 255}, Name: "Black"}
DarkGrey = BrickColor{Hex: "#6D6E6C", Number: 27, RGBA: color.RGBA{109, 110, 108, 255}, Name: "Dark grey"}
DarkGreen = BrickColor{Hex: "#287F47", Number: 28, RGBA: color.RGBA{40, 127, 71, 255}, Name: "Dark green"}
MediumGreen = BrickColor{Hex: "#A1C48C", Number: 29, RGBA: color.RGBA{161, 196, 140, 255}, Name: "Medium green"}
LigYellowichOrange = BrickColor{Hex: "#F3CF9B", Number: 36, RGBA: color.RGBA{243, 207, 155, 255}, Name: "Lig. Yellowich orange"}
BrightGreen = BrickColor{Hex: "#4B974B", Number: 37, RGBA: color.RGBA{75, 151, 75, 255}, Name: "Bright green"}
DarkOrange = BrickColor{Hex: "#A05F35", Number: 38, RGBA: color.RGBA{160, 95, 53, 255}, Name: "Dark orange"}
LightBluishViolet = BrickColor{Hex: "#C1CADE", Number: 39, RGBA: color.RGBA{193, 202, 222, 255}, Name: "Light bluish violet"}
Transparent = BrickColor{Hex: "#ECECEC", Number: 40, RGBA: color.RGBA{236, 236, 236, 255}, Name: "Transparent"}
TrRed = BrickColor{Hex: "#CD544B", Number: 41, RGBA: color.RGBA{205, 84, 75, 255}, Name: "Tr. Red"}
TrLgBlue = BrickColor{Hex: "#C1DFF0", Number: 42, RGBA: color.RGBA{193, 223, 240, 255}, Name: "Tr. Lg blue"}
TrBlue = BrickColor{Hex: "#7BB6E8", Number: 43, RGBA: color.RGBA{123, 182, 232, 255}, Name: "Tr. Blue"}
TrYellow = BrickColor{Hex: "#F7F18D", Number: 44, RGBA: color.RGBA{247, 241, 141, 255}, Name: "Tr. Yellow"}
LightBlue = BrickColor{Hex: "#B4D2E4", Number: 45, RGBA: color.RGBA{180, 210, 228, 255}, Name: "Light blue"}
TrFluReddishOrange = BrickColor{Hex: "#D9856C", Number: 47, RGBA: color.RGBA{217, 133, 108, 255}, Name: "Tr. Flu. Reddish orange"}
TrGreen = BrickColor{Hex: "#84B68D", Number: 48, RGBA: color.RGBA{132, 182, 141, 255}, Name: "Tr. Green"}
TrFluGreen = BrickColor{Hex: "#F8F184", Number: 49, RGBA: color.RGBA{248, 241, 132, 255}, Name: "Tr. Flu. Green"}
PhosphWhite = BrickColor{Hex: "#ECE8DE", Number: 50, RGBA: color.RGBA{236, 232, 222, 255}, Name: "Phosph. White"}
LightRed = BrickColor{Hex: "#EEC4B6", Number: 100, RGBA: color.RGBA{238, 196, 182, 255}, Name: "Light red"}
MediumRed = BrickColor{Hex: "#DA867A", Number: 101, RGBA: color.RGBA{218, 134, 122, 255}, Name: "Medium red"}
MediumBlue = BrickColor{Hex: "#6E99CA", Number: 102, RGBA: color.RGBA{110, 153, 202, 255}, Name: "Medium blue"}
LightGrey = BrickColor{Hex: "#C7C1B7", Number: 103, RGBA: color.RGBA{199, 193, 183, 255}, Name: "Light grey"}
BrightViolet = BrickColor{Hex: "#6B327C", Number: 104, RGBA: color.RGBA{107, 50, 124, 255}, Name: "Bright violet"}
BrYellowishOrange = BrickColor{Hex: "#E29B40", Number: 105, RGBA: color.RGBA{226, 155, 64, 255}, Name: "Br. yellowish orange"}
BrightOrange = BrickColor{Hex: "#DA8541", Number: 106, RGBA: color.RGBA{218, 133, 65, 255}, Name: "Bright orange"}
BrightBluishGreen = BrickColor{Hex: "#008F9C", Number: 107, RGBA: color.RGBA{0, 143, 156, 255}, Name: "Bright bluish green"}
EarthYellow = BrickColor{Hex: "#685C43", Number: 108, RGBA: color.RGBA{104, 92, 67, 255}, Name: "Earth yellow"}
BrightBluishViolet = BrickColor{Hex: "#435493", Number: 110, RGBA: color.RGBA{67, 84, 147, 255}, Name: "Bright bluish violet"}
TrBrown = BrickColor{Hex: "#BFB7B1", Number: 111, RGBA: color.RGBA{191, 183, 177, 255}, Name: "<NAME>"}
MediumBluishViolet = BrickColor{Hex: "#6874AC", Number: 112, RGBA: color.RGBA{104, 116, 172, 255}, Name: "Medium bluish violet"}
TrMediReddishViolet = BrickColor{Hex: "#E5ADC8", Number: 113, RGBA: color.RGBA{229, 173, 200, 255}, Name: "Tr. Medi. reddish violet"}
MedYellowishGreen = BrickColor{Hex: "#C7D23C", Number: 115, RGBA: color.RGBA{199, 210, 60, 255}, Name: "Med. yellowish green"}
MedBluishGreen = BrickColor{Hex: "#55A5AF", Number: 116, RGBA: color.RGBA{85, 165, 175, 255}, Name: "Med. bluish green"}
LightBluishGreen = BrickColor{Hex: "#B7D7D5", Number: 118, RGBA: color.RGBA{183, 215, 213, 255}, Name: "Light bluish green"}
BrYellowishGreen = BrickColor{Hex: "#A4BD47", Number: 119, RGBA: color.RGBA{164, 189, 71, 255}, Name: "Br. yellowish green"}
LigYellowishGreen = BrickColor{Hex: "#D9E4A7", Number: 120, RGBA: color.RGBA{217, 228, 167, 255}, Name: "Lig. yellowish green"}
MedYellowishOrange = BrickColor{Hex: "#E7AC58", Number: 121, RGBA: color.RGBA{231, 172, 88, 255}, Name: "Med. yellowish orange"}
BrReddishOrange = BrickColor{Hex: "#D36F4C", Number: 123, RGBA: color.RGBA{211, 111, 76, 255}, Name: "Br. reddish orange"}
BrightReddishViolet = BrickColor{Hex: "#923978", Number: 124, RGBA: color.RGBA{146, 57, 120, 255}, Name: "Bright reddish violet"}
LightOrange = BrickColor{Hex: "#EAB892", Number: 125, RGBA: color.RGBA{234, 184, 146, 255}, Name: "Light orange"}
TrBrightBluishViolet = BrickColor{Hex: "#A5A5CB", Number: 126, RGBA: color.RGBA{165, 165, 203, 255}, Name: "Tr. Bright bluish violet"}
Gold = BrickColor{Hex: "#DCBC81", Number: 127, RGBA: color.RGBA{220, 188, 129, 255}, Name: "Gold"}
DarkNougat = BrickColor{Hex: "#AE7A59", Number: 128, RGBA: color.RGBA{174, 122, 89, 255}, Name: "Dark nougat"}
Silver = BrickColor{Hex: "#9CA3A8", Number: 131, RGBA: color.RGBA{156, 163, 168, 255}, Name: "Silver"}
NeonOrange = BrickColor{Hex: "#D5733D", Number: 133, RGBA: color.RGBA{213, 115, 61, 255}, Name: "Neon orange"}
NeonGreen = BrickColor{Hex: "#D8DD56", Number: 134, RGBA: color.RGBA{216, 221, 86, 255}, Name: "Neon green"}
SandBlue = BrickColor{Hex: "#74869D", Number: 135, RGBA: color.RGBA{116, 134, 157, 255}, Name: "Sand blue"}
SandViolet = BrickColor{Hex: "#877C90", Number: 136, RGBA: color.RGBA{135, 124, 144, 255}, Name: "Sand violet"}
MediumOrange = BrickColor{Hex: "#E09864", Number: 137, RGBA: color.RGBA{224, 152, 100, 255}, Name: "Medium orange"}
SandYellow = BrickColor{Hex: "#958A73", Number: 138, RGBA: color.RGBA{149, 138, 115, 255}, Name: "Sand yellow"}
EarthBlue = BrickColor{Hex: "#203A56", Number: 140, RGBA: color.RGBA{32, 58, 86, 255}, Name: "Earth blue"}
EarthGreen = BrickColor{Hex: "#27462D", Number: 141, RGBA: color.RGBA{39, 70, 45, 255}, Name: "Earth green"}
TrFluBlue = BrickColor{Hex: "#CFE2F7", Number: 143, RGBA: color.RGBA{207, 226, 247, 255}, Name: "Tr. Flu. Blue"}
SandBlueMetallic = BrickColor{Hex: "#7988A1", Number: 145, RGBA: color.RGBA{121, 136, 161, 255}, Name: "Sand blue metallic"}
SandVioletMetallic = BrickColor{Hex: "#958EA3", Number: 146, RGBA: color.RGBA{149, 142, 163, 255}, Name: "Sand violet metallic"}
SandYellowMetallic = BrickColor{Hex: "#938767", Number: 147, RGBA: color.RGBA{147, 135, 103, 255}, Name: "Sand yellow metallic"}
DarkGreyMetallic = BrickColor{Hex: "#575857", Number: 148, RGBA: color.RGBA{87, 88, 87, 255}, Name: "Dark grey metallic"}
BlackMetallic = BrickColor{Hex: "#161D32", Number: 149, RGBA: color.RGBA{22, 29, 50, 255}, Name: "Black metallic"}
LightGreyMetallic = BrickColor{Hex: "#ABADAC", Number: 150, RGBA: color.RGBA{171, 173, 172, 255}, Name: "Light grey metallic"}
SandGreen = BrickColor{Hex: "#789082", Number: 151, RGBA: color.RGBA{120, 144, 130, 255}, Name: "Sand green"}
SandRed = BrickColor{Hex: "#957977", Number: 153, RGBA: color.RGBA{149, 121, 119, 255}, Name: "Sand red"}
DarkRed = BrickColor{Hex: "#7B2E2F", Number: 154, RGBA: color.RGBA{123, 46, 47, 255}, Name: "Dark red"}
TrFluYellow = BrickColor{Hex: "#FFF67B", Number: 157, RGBA: color.RGBA{255, 246, 123, 255}, Name: "Tr. Flu. Yellow"}
TrFluRed = BrickColor{Hex: "#E1A4C2", Number: 158, RGBA: color.RGBA{225, 164, 194, 255}, Name: "Tr. Flu. Red"}
GunMetallic = BrickColor{Hex: "#756C62", Number: 168, RGBA: color.RGBA{117, 108, 98, 255}, Name: "Gun metallic"}
RedFlipFlop = BrickColor{Hex: "#97695B", Number: 176, RGBA: color.RGBA{151, 105, 91, 255}, Name: "Red flip/flop"}
YellowFlipFlop = BrickColor{Hex: "#B48455", Number: 178, RGBA: color.RGBA{180, 132, 85, 255}, Name: "Yellow flip/flop"}
SilverFlipFlop = BrickColor{Hex: "#898788", Number: 179, RGBA: color.RGBA{137, 135, 136, 255}, Name: "Silver flip/flop"}
Curry = BrickColor{Hex: "#D7A94B", Number: 180, RGBA: color.RGBA{215, 169, 75, 255}, Name: "Curry"}
FireYellow = BrickColor{Hex: "#F9D62E", Number: 190, RGBA: color.RGBA{249, 214, 46, 255}, Name: "Fire Yellow"}
FlameYellowishOrange = BrickColor{Hex: "#E8AB2D", Number: 191, RGBA: color.RGBA{232, 171, 45, 255}, Name: "Flame yellowish orange"}
ReddishBrown = BrickColor{Hex: "#694028", Number: 192, RGBA: color.RGBA{105, 64, 40, 255}, Name: "Reddish brown"}
FlameReddishOrange = BrickColor{Hex: "#CF6024", Number: 193, RGBA: color.RGBA{207, 96, 36, 255}, Name: "Flame reddish orange"}
MediumStoneGrey = BrickColor{Hex: "#A3A2A5", Number: 194, RGBA: color.RGBA{163, 162, 165, 255}, Name: "Medium stone grey"}
RoyalBlue = BrickColor{Hex: "#4667A4", Number: 195, RGBA: color.RGBA{70, 103, 164, 255}, Name: "Royal blue"}
DarkRoyalBlue = BrickColor{Hex: "#23478B", Number: 196, RGBA: color.RGBA{35, 71, 139, 255}, Name: "Dark Royal blue"}
BrightReddishLilac = BrickColor{Hex: "#8E4285", Number: 198, RGBA: color.RGBA{142, 66, 133, 255}, Name: "Bright reddish lilac"}
DarkStoneGrey = BrickColor{Hex: "#635F62", Number: 199, RGBA: color.RGBA{99, 95, 98, 255}, Name: "Dark stone grey"}
LemonMetalic = BrickColor{Hex: "#828A5D", Number: 200, RGBA: color.RGBA{130, 138, 93, 255}, Name: "Lemon metalic"}
LightStoneGrey = BrickColor{Hex: "#E5E4DF", Number: 208, RGBA: color.RGBA{229, 228, 223, 255}, Name: "Light stone grey"}
DarkCurry = BrickColor{Hex: "#B08E44", Number: 209, RGBA: color.RGBA{176, 142, 68, 255}, Name: "Dark Curry"}
FadedGreen = BrickColor{Hex: "#709578", Number: 210, RGBA: color.RGBA{112, 149, 120, 255}, Name: "Faded green"}
Turquoise = BrickColor{Hex: "#79B5B5", Number: 211, RGBA: color.RGBA{121, 181, 181, 255}, Name: "Turquoise"}
LightRoyalBlue = BrickColor{Hex: "#9FC3E9", Number: 212, RGBA: color.RGBA{159, 195, 233, 255}, Name: "Light Royal blue"}
MediumRoyalBlue = BrickColor{Hex: "#6C81B7", Number: 213, RGBA: color.RGBA{108, 129, 183, 255}, Name: "Medium Royal blue"}
Rust = BrickColor{Hex: "#904C2A", Number: 216, RGBA: color.RGBA{144, 76, 42, 255}, Name: "Rust"}
Brown = BrickColor{Hex: "#7C5C46", Number: 217, RGBA: color.RGBA{124, 92, 70, 255}, Name: "Brown"}
ReddishLilac = BrickColor{Hex: "#96709F", Number: 218, RGBA: color.RGBA{150, 112, 159, 255}, Name: "Reddish lilac"}
Lilac = BrickColor{Hex: "#6B629B", Number: 219, RGBA: color.RGBA{107, 98, 155, 255}, Name: "Lilac"}
LightLilac = BrickColor{Hex: "#A7A9CE", Number: 220, RGBA: color.RGBA{167, 169, 206, 255}, Name: "Light lilac"}
BrightPurple = BrickColor{Hex: "#CD6298", Number: 221, RGBA: color.RGBA{205, 98, 152, 255}, Name: "Bright purple"}
LightPurple = BrickColor{Hex: "#E4ADC8", Number: 222, RGBA: color.RGBA{228, 173, 200, 255}, Name: "Light purple"}
LightPink = BrickColor{Hex: "#DC9095", Number: 223, RGBA: color.RGBA{220, 144, 149, 255}, Name: "Light pink"}
LightBrickYellow = BrickColor{Hex: "#F0D5A0", Number: 224, RGBA: color.RGBA{240, 213, 160, 255}, Name: "Light brick yellow"}
WarmYellowishOrange = BrickColor{Hex: "#EBB87F", Number: 225, RGBA: color.RGBA{235, 184, 127, 255}, Name: "Warm yellowish orange"}
CoolYellow = BrickColor{Hex: "#FDEA8D", Number: 226, RGBA: color.RGBA{253, 234, 141, 255}, Name: "Cool yellow"}
DoveBlue = BrickColor{Hex: "#7DBBDD", Number: 232, RGBA: color.RGBA{125, 187, 221, 255}, Name: "Dove blue"}
MediumLilac = BrickColor{Hex: "#342B75", Number: 268, RGBA: color.RGBA{52, 43, 117, 255}, Name: "Medium lilac"}
SlimeGreen = BrickColor{Hex: "#506D54", Number: 301, RGBA: color.RGBA{80, 109, 84, 255}, Name: "Slime green"}
SmokyGrey = BrickColor{Hex: "#5B5D69", Number: 302, RGBA: color.RGBA{91, 93, 105, 255}, Name: "Smoky grey"}
DarkBlue = BrickColor{Hex: "#0010B0", Number: 303, RGBA: color.RGBA{0, 16, 176, 255}, Name: "Dark blue"}
ParsleyGreen = BrickColor{Hex: "#2C651D", Number: 304, RGBA: color.RGBA{44, 101, 29, 255}, Name: "Parsley green"}
SteelBlue = BrickColor{Hex: "#527CAE", Number: 305, RGBA: color.RGBA{82, 124, 174, 255}, Name: "Steel blue"}
StormBlue = BrickColor{Hex: "#335882", Number: 306, RGBA: color.RGBA{51, 88, 130, 255}, Name: "Storm blue"}
Lapis = BrickColor{Hex: "#102ADC", Number: 307, RGBA: color.RGBA{16, 42, 220, 255}, Name: "Lapis"}
DarkIndigo = BrickColor{Hex: "#3D1585", Number: 308, RGBA: color.RGBA{61, 21, 133, 255}, Name: "Dark indigo"}
SeaGreen = BrickColor{Hex: "#348E40", Number: 309, RGBA: color.RGBA{52, 142, 64, 255}, Name: "Sea green"}
Shamrock = BrickColor{Hex: "#5B9A4C", Number: 310, RGBA: color.RGBA{91, 154, 76, 255}, Name: "Shamrock"}
Fossil = BrickColor{Hex: "#9FA1AC", Number: 311, RGBA: color.RGBA{159, 161, 172, 255}, Name: "Fossil"}
Mulberry = BrickColor{Hex: "#592259", Number: 312, RGBA: color.RGBA{89, 34, 89, 255}, Name: "Mulberry"}
ForestGreen = BrickColor{Hex: "#1F801D", Number: 313, RGBA: color.RGBA{31, 128, 29, 255}, Name: "Forest green"}
CadetBlue = BrickColor{Hex: "#9FADC0", Number: 314, RGBA: color.RGBA{159, 173, 192, 255}, Name: "Cadet blue"}
ElectricBlue = BrickColor{Hex: "#0989CF", Number: 315, RGBA: color.RGBA{9, 137, 207, 255}, Name: "Electric blue"}
Eggplant = BrickColor{Hex: "#7B007B", Number: 316, RGBA: color.RGBA{123, 0, 123, 255}, Name: "Eggplant"}
Moss = BrickColor{Hex: "#7C9C6B", Number: 317, RGBA: color.RGBA{124, 156, 107, 255}, Name: "Moss"}
Artichoke = BrickColor{Hex: "#8AAB85", Number: 318, RGBA: color.RGBA{138, 171, 133, 255}, Name: "Artichoke"}
SageGreen = BrickColor{Hex: "#B9C4B1", Number: 319, RGBA: color.RGBA{185, 196, 177, 255}, Name: "Sage green"}
GhostGrey = BrickColor{Hex: "#CACBD1", Number: 320, RGBA: color.RGBA{202, 203, 209, 255}, Name: "Ghost grey"}
Lilac2 = BrickColor{Hex: "#A75E9B", Number: 321, RGBA: color.RGBA{167, 94, 155, 255}, Name: "Lilac"}
Plum = BrickColor{Hex: "#7B2F7B", Number: 322, RGBA: color.RGBA{123, 47, 123, 255}, Name: "Plum"}
Olivine = BrickColor{Hex: "#94BE81", Number: 323, RGBA: color.RGBA{148, 190, 129, 255}, Name: "Olivine"}
LaurelGreen = BrickColor{Hex: "#A8BD99", Number: 324, RGBA: color.RGBA{168, 189, 153, 255}, Name: "Laurel green"}
QuillGrey = BrickColor{Hex: "#DFDFDE", Number: 325, RGBA: color.RGBA{223, 223, 222, 255}, Name: "Quill grey"}
Crimson = BrickColor{Hex: "#970000", Number: 327, RGBA: color.RGBA{151, 0, 0, 255}, Name: "Crimson"}
Mint = BrickColor{Hex: "#B1E5A6", Number: 328, RGBA: color.RGBA{177, 229, 166, 255}, Name: "Mint"}
BabyBlue = BrickColor{Hex: "#98C2DB", Number: 329, RGBA: color.RGBA{152, 194, 219, 255}, Name: "Baby blue"}
CarnationPink = BrickColor{Hex: "#FF98DC", Number: 330, RGBA: color.RGBA{255, 152, 220, 255}, Name: "Carnation pink"}
Persimmon = BrickColor{Hex: "#FF5959", Number: 331, RGBA: color.RGBA{255, 89, 89, 255}, Name: "Persimmon"}
Maroon = BrickColor{Hex: "#750000", Number: 332, RGBA: color.RGBA{117, 0, 0, 255}, Name: "Maroon"}
Gold2 = BrickColor{Hex: "#EFB838", Number: 333, RGBA: color.RGBA{239, 184, 56, 255}, Name: "Gold"}
DaisyOrange = BrickColor{Hex: "#F8D96D", Number: 334, RGBA: color.RGBA{248, 217, 109, 255}, Name: "Daisy orange"}
Pearl = BrickColor{Hex: "#E7E7EC", Number: 335, RGBA: color.RGBA{231, 231, 236, 255}, Name: "Pearl"}
Fog = BrickColor{Hex: "#C7D4E4", Number: 336, RGBA: color.RGBA{199, 212, 228, 255}, Name: "Fog"}
Salmon = BrickColor{Hex: "#FF9494", Number: 337, RGBA: color.RGBA{255, 148, 148, 255}, Name: "Salmon"}
TerraCotta = BrickColor{Hex: "#BE6862", Number: 338, RGBA: color.RGBA{190, 104, 98, 255}, Name: "Terra Cotta"}
Cocoa = BrickColor{Hex: "#562424", Number: 339, RGBA: color.RGBA{86, 36, 36, 255}, Name: "Cocoa"}
Wheat = BrickColor{Hex: "#F1E7C7", Number: 340, RGBA: color.RGBA{241, 231, 199, 255}, Name: "Wheat"}
Buttermilk = BrickColor{Hex: "#FEF3BB", Number: 341, RGBA: color.RGBA{254, 243, 187, 255}, Name: "Buttermilk"}
Mauve = BrickColor{Hex: "#E0B2D0", Number: 342, RGBA: color.RGBA{224, 178, 208, 255}, Name: "Mauve"}
Sunrise = BrickColor{Hex: "#D490BD", Number: 343, RGBA: color.RGBA{212, 144, 189, 255}, Name: "Sunrise"}
Tawny = BrickColor{Hex: "#965555", Number: 344, RGBA: color.RGBA{150, 85, 85, 255}, Name: "Tawny"}
Rust2 = BrickColor{Hex: "#8F4C2A", Number: 345, RGBA: color.RGBA{143, 76, 42, 255}, Name: "Rust"}
Cashmere = BrickColor{Hex: "#D3BE96", Number: 346, RGBA: color.RGBA{211, 190, 150, 255}, Name: "Cashmere"}
Khaki = BrickColor{Hex: "#E2DCBC", Number: 347, RGBA: color.RGBA{226, 220, 188, 255}, Name: "Khaki"}
LilyWhite = BrickColor{Hex: "#EDEAEA", Number: 348, RGBA: color.RGBA{237, 234, 234, 255}, Name: "Lily white"}
Seashell = BrickColor{Hex: "#E9DADA", Number: 349, RGBA: color.RGBA{233, 218, 218, 255}, Name: "Seashell"}
Burgundy = BrickColor{Hex: "#883E3E", Number: 350, RGBA: color.RGBA{136, 62, 62, 255}, Name: "Burgundy"}
Cork = BrickColor{Hex: "#BC9B5D", Number: 351, RGBA: color.RGBA{188, 155, 93, 255}, Name: "Cork"}
Burlap = BrickColor{Hex: "#C7AC78", Number: 352, RGBA: color.RGBA{199, 172, 120, 255}, Name: "Burlap"}
Beige = BrickColor{Hex: "#CABFA3", Number: 353, RGBA: color.RGBA{202, 191, 163, 255}, Name: "Beige"}
Oyster = BrickColor{Hex: "#BBB3B2", Number: 354, RGBA: color.RGBA{187, 179, 178, 255}, Name: "Oyster"}
PineCone = BrickColor{Hex: "#6C584B", Number: 355, RGBA: color.RGBA{108, 88, 75, 255}, Name: "Pine Cone"}
FawnBrown = BrickColor{Hex: "#A0844F", Number: 356, RGBA: color.RGBA{160, 132, 79, 255}, Name: "Fawn brown"}
HurricaneGrey = BrickColor{Hex: "#958988", Number: 357, RGBA: color.RGBA{149, 137, 136, 255}, Name: "Hurricane grey"}
CloudyGrey = BrickColor{Hex: "#ABA89E", Number: 358, RGBA: color.RGBA{171, 168, 158, 255}, Name: "Cloudy grey"}
Linen = BrickColor{Hex: "#AF9483", Number: 359, RGBA: color.RGBA{175, 148, 131, 255}, Name: "Linen"}
Copper = BrickColor{Hex: "#966766", Number: 360, RGBA: color.RGBA{150, 103, 102, 255}, Name: "Copper"}
DirtBrown = BrickColor{Hex: "#564236", Number: 361, RGBA: color.RGBA{86, 66, 54, 255}, Name: "Dirt brown"}
Bronze = BrickColor{Hex: "#7E683F", Number: 362, RGBA: color.RGBA{126, 104, 63, 255}, Name: "Bronze"}
Flint = BrickColor{Hex: "#69665C", Number: 363, RGBA: color.RGBA{105, 102, 92, 255}, Name: "Flint"}
DarkTaupe = BrickColor{Hex: "#5A4C42", Number: 364, RGBA: color.RGBA{90, 76, 66, 255}, Name: "Dark taupe"}
BurntSienna = BrickColor{Hex: "#6A3909", Number: 365, RGBA: color.RGBA{106, 57, 9, 255}, Name: "Burnt Sienna"}
InstitutionalWhite = BrickColor{Hex: "#F8F8F8", Number: 1001, RGBA: color.RGBA{248, 248, 248, 255}, Name: "Institutional white"}
MidGray = BrickColor{Hex: "#CDCDCD", Number: 1002, RGBA: color.RGBA{205, 205, 205, 255}, Name: "Mid gray"}
ReallyBlack = BrickColor{Hex: "#111111", Number: 1003, RGBA: color.RGBA{17, 17, 17, 255}, Name: "Really black"}
ReallyRed = BrickColor{Hex: "#FF0000", Number: 1004, RGBA: color.RGBA{255, 0, 0, 255}, Name: "Really red"}
DeepOrange = BrickColor{Hex: "#FFB000", Number: 1005, RGBA: color.RGBA{255, 176, 0, 255}, Name: "Deep orange"}
Alder = BrickColor{Hex: "#B480FF", Number: 1006, RGBA: color.RGBA{180, 128, 255, 255}, Name: "Alder"}
DustyRose = BrickColor{Hex: "#A34B4B", Number: 1007, RGBA: color.RGBA{163, 75, 75, 255}, Name: "<NAME>"}
Olive = BrickColor{Hex: "#C1BE42", Number: 1008, RGBA: color.RGBA{193, 190, 66, 255}, Name: "Olive"}
NewYeller = BrickColor{Hex: "#FFFF00", Number: 1009, RGBA: color.RGBA{255, 255, 0, 255}, Name: "<NAME>"}
ReallyBlue = BrickColor{Hex: "#0000FF", Number: 1010, RGBA: color.RGBA{0, 0, 255, 255}, Name: "Really blue"}
NavyBlue = BrickColor{Hex: "#002060", Number: 1011, RGBA: color.RGBA{0, 32, 96, 255}, Name: "Navy blue"}
DeepBlue = BrickColor{Hex: "#2154B9", Number: 1012, RGBA: color.RGBA{33, 84, 185, 255}, Name: "Deep blue"}
Cyan = BrickColor{Hex: "#04AFEC", Number: 1013, RGBA: color.RGBA{4, 175, 236, 255}, Name: "Cyan"}
CGABrown = BrickColor{Hex: "#AA5500", Number: 1014, RGBA: color.RGBA{170, 85, 0, 255}, Name: "CGA brown"}
Magenta = BrickColor{Hex: "#AA00AA", Number: 1015, RGBA: color.RGBA{170, 0, 170, 255}, Name: "Magenta"}
Pink = BrickColor{Hex: "#FF66CC", Number: 1016, RGBA: color.RGBA{255, 102, 204, 255}, Name: "Pink"}
DeepOrange2 = BrickColor{Hex: "#FFAF00", Number: 1017, RGBA: color.RGBA{255, 175, 0, 255}, Name: "Deep orange"}
Teal = BrickColor{Hex: "#12EED4", Number: 1018, RGBA: color.RGBA{18, 238, 212, 255}, Name: "Teal"}
Toothpaste = BrickColor{Hex: "#00FFFF", Number: 1019, RGBA: color.RGBA{0, 255, 255, 255}, Name: "Toothpaste"}
LimeGreen = BrickColor{Hex: "#00FF00", Number: 1020, RGBA: color.RGBA{0, 255, 0, 255}, Name: "Lime green"}
Camo = BrickColor{Hex: "#3A7D15", Number: 1021, RGBA: color.RGBA{58, 125, 21, 255}, Name: "Camo"}
Grime = BrickColor{Hex: "#7F8E64", Number: 1022, RGBA: color.RGBA{127, 142, 100, 255}, Name: "Grime"}
Lavender = BrickColor{Hex: "#8C5B9F", Number: 1023, RGBA: color.RGBA{140, 91, 159, 255}, Name: "Lavender"}
PastelLightBlue = BrickColor{Hex: "#AFDDFF", Number: 1024, RGBA: color.RGBA{175, 221, 255, 255}, Name: "Pastel light blue"}
PastelOrange = BrickColor{Hex: "#FFC9C9", Number: 1025, RGBA: color.RGBA{255, 201, 201, 255}, Name: "Pastel orange"}
PastelViolet = BrickColor{Hex: "#B1A7FF", Number: 1026, RGBA: color.RGBA{177, 167, 255, 255}, Name: "Pastel violet"}
PastelBlueGreen = BrickColor{Hex: "#9FF3E9", Number: 1027, RGBA: color.RGBA{159, 243, 233, 255}, Name: "Pastel blue-green"}
PastelGreen = BrickColor{Hex: "#CCFFCC", Number: 1028, RGBA: color.RGBA{204, 255, 204, 255}, Name: "Pastel green"}
PastelYellow = BrickColor{Hex: "#FFFFCC", Number: 1029, RGBA: color.RGBA{255, 255, 204, 255}, Name: "Pastel yellow"}
PastelBrown = BrickColor{Hex: "#FFCC99", Number: 1030, RGBA: color.RGBA{255, 204, 153, 255}, Name: "Pastel brown"}
RoyalPurple = BrickColor{Hex: "#6225D1", Number: 1031, RGBA: color.RGBA{98, 37, 209, 255}, Name: "Royal purple"}
HotPink = BrickColor{Hex: "#FF00BF", Number: 1032, RGBA: color.RGBA{255, 0, 191, 255}, Name: "<NAME>"}
)
// All available BrickColors on Roblox.
var All = []BrickColor{
White,
Grey,
LightYellow,
BrickYellow,
LightGreenMint,
LightReddishViolet,
PastelBlue,
LightOrangeBrown,
Nougat,
BrightRed,
MedReddishViolet,
BrightBlue,
BrightYellow,
EarthOrange,
Black,
DarkGrey,
DarkGreen,
MediumGreen,
LigYellowichOrange,
BrightGreen,
DarkOrange,
LightBluishViolet,
Transparent,
TrRed,
TrLgBlue,
TrBlue,
TrYellow,
LightBlue,
TrFluReddishOrange,
TrGreen,
TrFluGreen,
PhosphWhite,
LightRed,
MediumRed,
MediumBlue,
LightGrey,
BrightViolet,
BrYellowishOrange,
BrightOrange,
BrightBluishGreen,
EarthYellow,
BrightBluishViolet,
TrBrown,
MediumBluishViolet,
TrMediReddishViolet,
MedYellowishGreen,
MedBluishGreen,
LightBluishGreen,
BrYellowishGreen,
LigYellowishGreen,
MedYellowishOrange,
BrReddishOrange,
BrightReddishViolet,
LightOrange,
TrBrightBluishViolet,
Gold,
DarkNougat,
Silver,
NeonOrange,
NeonGreen,
SandBlue,
SandViolet,
MediumOrange,
SandYellow,
EarthBlue,
EarthGreen,
TrFluBlue,
SandBlueMetallic,
SandVioletMetallic,
SandYellowMetallic,
DarkGreyMetallic,
BlackMetallic,
LightGreyMetallic,
SandGreen,
SandRed,
DarkRed,
TrFluYellow,
TrFluRed,
GunMetallic,
RedFlipFlop,
YellowFlipFlop,
SilverFlipFlop,
Curry,
FireYellow,
FlameYellowishOrange,
ReddishBrown,
FlameReddishOrange,
MediumStoneGrey,
RoyalBlue,
DarkRoyalBlue,
BrightReddishLilac,
DarkStoneGrey,
LemonMetalic,
LightStoneGrey,
DarkCurry,
FadedGreen,
Turquoise,
LightRoyalBlue,
MediumRoyalBlue,
Rust,
Brown,
ReddishLilac,
Lilac,
LightLilac,
BrightPurple,
LightPurple,
LightPink,
LightBrickYellow,
WarmYellowishOrange,
CoolYellow,
DoveBlue,
MediumLilac,
SlimeGreen,
SmokyGrey,
DarkBlue,
ParsleyGreen,
SteelBlue,
StormBlue,
Lapis,
DarkIndigo,
SeaGreen,
Shamrock,
Fossil,
Mulberry,
ForestGreen,
CadetBlue,
ElectricBlue,
Eggplant,
Moss,
Artichoke,
SageGreen,
GhostGrey,
Lilac2,
Plum,
Olivine,
LaurelGreen,
QuillGrey,
Crimson,
Mint,
BabyBlue,
CarnationPink,
Persimmon,
Maroon,
Gold2,
DaisyOrange,
Pearl,
Fog,
Salmon,
TerraCotta,
Cocoa,
Wheat,
Buttermilk,
Mauve,
Sunrise,
Tawny,
Rust2,
Cashmere,
Khaki,
LilyWhite,
Seashell,
Burgundy,
Cork,
Burlap,
Beige,
Oyster,
PineCone,
FawnBrown,
HurricaneGrey,
CloudyGrey,
Linen,
Copper,
DirtBrown,
Bronze,
Flint,
DarkTaupe,
BurntSienna,
InstitutionalWhite,
MidGray,
ReallyBlack,
ReallyRed,
DeepOrange,
Alder,
DustyRose,
Olive,
NewYeller,
ReallyBlue,
NavyBlue,
DeepBlue,
Cyan,
CGABrown,
Magenta,
Pink,
DeepOrange2,
Teal,
Toothpaste,
LimeGreen,
Camo,
Grime,
Lavender,
PastelLightBlue,
PastelOrange,
PastelViolet,
PastelBlueGreen,
PastelGreen,
PastelYellow,
PastelBrown,
RoyalPurple,
HotPink}
var byNumber = map[int]BrickColor{
1: White,
2: Grey,
3: LightYellow,
5: BrickYellow,
6: LightGreenMint,
9: LightReddishViolet,
11: PastelBlue,
12: LightOrangeBrown,
18: Nougat,
21: BrightRed,
22: MedReddishViolet,
23: BrightBlue,
24: BrightYellow,
25: EarthOrange,
26: Black,
27: DarkGrey,
28: DarkGreen,
29: MediumGreen,
36: LigYellowichOrange,
37: BrightGreen,
38: DarkOrange,
39: LightBluishViolet,
40: Transparent,
41: TrRed,
42: TrLgBlue,
43: TrBlue,
44: TrYellow,
45: LightBlue,
47: TrFluReddishOrange,
48: TrGreen,
49: TrFluGreen,
50: PhosphWhite,
100: LightRed,
101: MediumRed,
102: MediumBlue,
103: LightGrey,
104: BrightViolet,
105: BrYellowishOrange,
106: BrightOrange,
107: BrightBluishGreen,
108: EarthYellow,
110: BrightBluishViolet,
111: TrBrown,
112: MediumBluishViolet,
113: TrMediReddishViolet,
115: MedYellowishGreen,
116: MedBluishGreen,
118: LightBluishGreen,
119: BrYellowishGreen,
120: LigYellowishGreen,
121: MedYellowishOrange,
123: BrReddishOrange,
124: BrightReddishViolet,
125: LightOrange,
126: TrBrightBluishViolet,
127: Gold,
128: DarkNougat,
131: Silver,
133: NeonOrange,
134: NeonGreen,
135: SandBlue,
136: SandViolet,
137: MediumOrange,
138: SandYellow,
140: EarthBlue,
141: EarthGreen,
143: TrFluBlue,
145: SandBlueMetallic,
146: SandVioletMetallic,
147: SandYellowMetallic,
148: DarkGreyMetallic,
149: BlackMetallic,
150: LightGreyMetallic,
151: SandGreen,
153: SandRed,
154: DarkRed,
157: TrFluYellow,
158: TrFluRed,
168: GunMetallic,
176: RedFlipFlop,
178: YellowFlipFlop,
179: SilverFlipFlop,
180: Curry,
190: FireYellow,
191: FlameYellowishOrange,
192: ReddishBrown,
193: FlameReddishOrange,
194: MediumStoneGrey,
195: RoyalBlue,
196: DarkRoyalBlue,
198: BrightReddishLilac,
199: DarkStoneGrey,
200: LemonMetalic,
208: LightStoneGrey,
209: DarkCurry,
210: FadedGreen,
211: Turquoise,
212: LightRoyalBlue,
213: MediumRoyalBlue,
216: Rust,
217: Brown,
218: ReddishLilac,
219: Lilac,
220: LightLilac,
221: BrightPurple,
222: LightPurple,
223: LightPink,
224: LightBrickYellow,
225: WarmYellowishOrange,
226: CoolYellow,
232: DoveBlue,
268: MediumLilac,
301: SlimeGreen,
302: SmokyGrey,
303: DarkBlue,
304: ParsleyGreen,
305: SteelBlue,
306: StormBlue,
307: Lapis,
308: DarkIndigo,
309: SeaGreen,
310: Shamrock,
311: Fossil,
312: Mulberry,
313: ForestGreen,
314: CadetBlue,
315: ElectricBlue,
316: Eggplant,
317: Moss,
318: Artichoke,
319: SageGreen,
320: GhostGrey,
321: Lilac2,
322: Plum,
323: Olivine,
324: LaurelGreen,
325: QuillGrey,
327: Crimson,
328: Mint,
329: BabyBlue,
330: CarnationPink,
331: Persimmon,
332: Maroon,
333: Gold2,
334: DaisyOrange,
335: Pearl,
336: Fog,
337: Salmon,
338: TerraCotta,
339: Cocoa,
340: Wheat,
341: Buttermilk,
342: Mauve,
343: Sunrise,
344: Tawny,
345: Rust2,
346: Cashmere,
347: Khaki,
348: LilyWhite,
349: Seashell,
350: Burgundy,
351: Cork,
352: Burlap,
353: Beige,
354: Oyster,
355: PineCone,
356: FawnBrown,
357: HurricaneGrey,
358: CloudyGrey,
359: Linen,
360: Copper,
361: DirtBrown,
362: Bronze,
363: Flint,
364: DarkTaupe,
365: BurntSienna,
1001: InstitutionalWhite,
1002: MidGray,
1003: ReallyBlack,
1004: ReallyRed,
1005: DeepOrange,
1006: Alder,
1007: DustyRose,
1008: Olive,
1009: NewYeller,
1010: ReallyBlue,
1011: NavyBlue,
1012: DeepBlue,
1013: Cyan,
1014: CGABrown,
1015: Magenta,
1016: Pink,
1017: DeepOrange2,
1018: Teal,
1019: Toothpaste,
1020: LimeGreen,
1021: Camo,
1022: Grime,
1023: Lavender,
1024: PastelLightBlue,
1025: PastelOrange,
1026: PastelViolet,
1027: PastelBlueGreen,
1028: PastelGreen,
1029: PastelYellow,
1030: PastelBrown,
1031: RoyalPurple,
1032: HotPink,
} | generated.go | 0.77907 | 0.459501 | generated.go | starcoder |
package main
import (
. "github.com/9d77v/leetcode/pkg/algorithm/math"
. "github.com/9d77v/leetcode/pkg/algorithm/stack"
)
/*
题目:柱状图中最大的矩形
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/largest-rectangle-in-histogram/
*/
/*
方法一:暴力方法
时间复杂度:О(n²)
空间复杂度:О(1)
运行时间:688 ms 内存消耗:4.2 MB
*/
func largestRectangleAreaFunc1(heights []int) (max int) {
n := len(heights)
for i, height := range heights {
j, left, right := 1, i, i
for left-1 > -1 && heights[left-1] >= heights[i] {
j++
left--
}
for right+1 < n && heights[right+1] >= heights[i] {
j++
right++
}
max = Max(max, height*j)
}
return max
}
/*
方法二:单调栈
时间复杂度:О(n)
空间复杂度:О(n)
运行时间:12 ms 内存消耗:5.7 MB
*/
func largestRectangleAreaFunc2(heights []int) (max int) {
n := len(heights)
left, right := make([]int, n), make([]int, n)
//栈存放下标
var stack Stack = NewSliceStack(n)
for i := 0; i < n; i++ {
for !stack.IsEmpty() && heights[stack.Peek().(int)] > heights[i] {
stack.Pop()
}
if stack.IsEmpty() {
left[i] = -1
} else {
left[i] = stack.Peek().(int)
}
stack.Push(i)
}
stack = NewSliceStack(n)
for i := n - 1; i > -1; i-- {
for !stack.IsEmpty() && heights[stack.Peek().(int)] > heights[i] {
stack.Pop()
}
if stack.IsEmpty() {
right[i] = n
} else {
right[i] = stack.Peek().(int)
}
stack.Push(i)
}
for i := 0; i < n; i++ {
max = Max(max, (right[i]-left[i]-1)*heights[i])
}
return
}
/*
方法三:单调栈+常数优化
时间复杂度:О(n)
空间复杂度:О(n)
运行时间:8 ms 内存消耗:5.5 MB
*/
func largestRectangleAreaFunc3(heights []int) (max int) {
heights = append(heights, -1)
stack := make([]int, 0, len(heights))
for i, height := range heights {
for len(stack) > 0 && heights[stack[len(stack)-1]] > height {
topValue := heights[stack[len(stack)-1]]
stack = stack[:len(stack)-1]
right := i - 1
left := 0
if len(stack) > 0 {
left = stack[len(stack)-1] + 1
}
max = Max(max, (right-left+1)*topValue)
}
stack = append(stack, i)
}
return
} | internal/leetcode/84.largest-rectangle-in-histogram/main.go | 0.600891 | 0.403302 | main.go | starcoder |
package canvas
import (
"math"
)
// Rectangle returns a rectangle with width w and height h.
func Rectangle(w, h float64) *Path {
if equal(w, 0.0) || equal(h, 0.0) {
return &Path{}
}
p := &Path{}
p.LineTo(w, 0.0)
p.LineTo(w, h)
p.LineTo(0.0, h)
p.Close()
return p
}
// RoundedRectangle returns a rectangle with width w and height h with rounded corners of radius r. A negative radius will cast the corners inwards (ie. concave).
func RoundedRectangle(w, h, r float64) *Path {
if equal(w, 0.0) || equal(h, 0.0) {
return &Path{}
} else if equal(r, 0.0) {
return Rectangle(w, h)
}
sweep := true
if r < 0.0 {
sweep = false
r = -r
}
r = math.Min(r, w/2.0)
r = math.Min(r, h/2.0)
p := &Path{}
p.MoveTo(0.0, r)
p.ArcTo(r, r, 0.0, false, sweep, r, 0.0)
p.LineTo(w-r, 0.0)
p.ArcTo(r, r, 0.0, false, sweep, w, r)
p.LineTo(w, h-r)
p.ArcTo(r, r, 0.0, false, sweep, w-r, h)
p.LineTo(r, h)
p.ArcTo(r, r, 0.0, false, sweep, 0.0, h-r)
p.Close()
return p
}
// BeveledRectangle returns a rectangle with width w and height h with beveled corners at distance r from the corner.
func BeveledRectangle(w, h, r float64) *Path {
if equal(w, 0.0) || equal(h, 0.0) {
return &Path{}
} else if equal(r, 0.0) {
return Rectangle(w, h)
}
r = math.Abs(r)
r = math.Min(r, w/2.0)
r = math.Min(r, h/2.0)
p := &Path{}
p.MoveTo(0.0, r)
p.LineTo(r, 0.0)
p.LineTo(w-r, 0.0)
p.LineTo(w, r)
p.LineTo(w, h-r)
p.LineTo(w-r, h)
p.LineTo(r, h)
p.LineTo(0.0, h-r)
p.Close()
return p
}
// Circle returns a circle with radius r.
func Circle(r float64) *Path {
return Ellipse(r, r)
}
// Ellipse returns an ellipse with radii rx,ry.
func Ellipse(rx, ry float64) *Path {
if equal(rx, 0.0) || equal(ry, 0.0) {
return &Path{}
}
p := &Path{}
p.MoveTo(rx, 0.0)
p.ArcTo(rx, ry, 0.0, false, true, -rx, 0.0)
p.ArcTo(rx, ry, 0.0, false, true, rx, 0.0)
p.Close()
return p
}
// RegularPolygon returns a regular polygon with radius r and rotation rot in degrees. It uses n vertices/edges, so when n approaches infinity this will return a path that approximates a circle. n must be 3 or more. The up boolean defines whether the first point will point north or not.
func RegularPolygon(n int, r float64, up bool) *Path {
return RegularStarPolygon(n, 1, r, up)
}
// RegularStarPolygon returns a regular star polygon with radius r and rotation rot in degrees. It uses n vertices of density d. This will result in a self-intersection star in counter clockwise direction. If n/2 < d the star will be clockwise and if n and d are not coprime a regular polygon will be obtained, possible with multiple windings. n must be 3 or more and d 2 or more. The up boolean defines whether the first point will point north or not.
func RegularStarPolygon(n, d int, r float64, up bool) *Path {
if n < 3 || d < 1 || n == d*2 || equal(r, 0.0) {
return &Path{}
}
dtheta := 2.0 * math.Pi / float64(n)
theta0 := 0.5 * math.Pi
if !up {
theta0 += dtheta / 2.0
}
p := &Path{}
for i := 0; i == 0 || i%n != 0; i += d {
theta := theta0 + float64(i)*dtheta
sintheta, costheta := math.Sincos(theta)
if i == 0 {
p.MoveTo(r*costheta, r*sintheta)
} else {
p.LineTo(r*costheta, r*sintheta)
}
}
p.Close()
return p
}
// StarPolygon returns a star polygon of n points with alternating radius R and r. The up boolean defines whether the first point (true) or second point (false) will be pointing north.
func StarPolygon(n int, R, r float64, up bool) *Path {
if n < 3 || equal(R, 0.0) || equal(r, 0.0) {
return &Path{}
}
n *= 2
dtheta := 2.0 * math.Pi / float64(n)
theta0 := 0.5 * math.Pi
if !up {
theta0 += dtheta
}
p := &Path{}
for i := 0; i < n; i++ {
theta := theta0 + float64(i)*dtheta
sintheta, costheta := math.Sincos(theta)
if i == 0 {
p.MoveTo(R*costheta, R*sintheta)
} else if i%2 == 0 {
p.LineTo(R*costheta, R*sintheta)
} else {
p.LineTo(r*costheta, r*sintheta)
}
}
p.Close()
return p
} | shapes.go | 0.895624 | 0.630031 | shapes.go | starcoder |
package types
import (
"github.com/lyraproj/puppet-evaluator/eval"
"io"
"strconv"
)
type CallableType struct {
paramsType eval.Type
returnType eval.Type
blockType eval.Type // Callable or Optional[Callable]
}
var Callable_Type eval.ObjectType
func init() {
Callable_Type = newObjectType(`Pcore::CallableType`,
`Pcore::AnyType {
attributes => {
param_types => {
type => Optional[Type[Tuple]],
value => undef
},
block_type => {
type => Optional[Type[Callable]],
value => undef
},
return_type => {
type => Optional[Type],
value => undef
}
}
}`, func(ctx eval.Context, args []eval.Value) eval.Value {
var paramsType eval.Type
var returnType eval.Type
var blockType eval.Type
switch len(args) {
case 0:
case 3:
if pt, ok := args[2].(eval.Type); ok {
blockType = pt
}
fallthrough
case 2:
if pt, ok := args[1].(eval.Type); ok {
returnType = pt
}
fallthrough
case 1:
if pt, ok := args[0].(eval.Type); ok {
paramsType = pt
}
}
return NewCallableType(paramsType, returnType, blockType)
})
}
func DefaultCallableType() *CallableType {
return callableType_DEFAULT
}
func NewCallableType(paramsType eval.Type, returnType eval.Type, blockType eval.Type) *CallableType {
return &CallableType{paramsType, returnType, blockType}
}
func NewCallableType2(args ...eval.Value) *CallableType {
return NewCallableType3(WrapValues(args))
}
func NewCallableType3(args eval.List) *CallableType {
argc := args.Len()
if argc == 0 {
return DefaultCallableType()
}
var (
rt eval.Type
block eval.Type
ok bool
)
if argc == 1 || argc == 2 {
// check for [[params, block], return]
var iv eval.List
if iv, ok = args.At(0).(eval.List); ok {
if argc == 2 {
if rt, ok = args.At(1).(eval.Type); !ok {
panic(NewIllegalArgumentType2(`Callable[]`, 1, `Type`, args.At(1)))
}
}
argc = iv.Len()
args = iv
}
}
last := args.At(argc - 1)
block, ok = last.(*CallableType)
if !ok {
block = nil
var ob *OptionalType
if ob, ok = last.(*OptionalType); ok {
if _, ok = ob.typ.(*CallableType); ok {
block = ob
}
}
}
if ok {
argc--
args = args.Slice(0, argc)
last = args.At(argc)
}
return NewCallableType(tupleFromArgs(true, args), rt, block)
}
func (t *CallableType) BlockType() eval.Type {
if t.blockType == nil {
return nil // Return untyped nil
}
return t.blockType
}
func (t *CallableType) CallableWith(args []eval.Value, block eval.Lambda) bool {
if block != nil {
cb := t.blockType
switch cb.(type) {
case nil:
return false
case *OptionalType:
cb = cb.(*OptionalType).ContainedType()
}
if block.PType() == nil {
return false
}
if !isAssignable(block.PType(), cb) {
return false
}
} else if t.blockType != nil && !isAssignable(t.blockType, anyType_DEFAULT) {
// Required block but non provided
return false
}
if pt, ok := t.paramsType.(*TupleType); ok {
return pt.IsInstance3(args, nil)
}
return true
}
func (t *CallableType) Accept(v eval.Visitor, g eval.Guard) {
v(t)
if t.paramsType != nil {
t.paramsType.Accept(v, g)
}
if t.blockType != nil {
t.blockType.Accept(v, g)
}
if t.returnType != nil {
t.returnType.Accept(v, g)
}
}
func (t *CallableType) BlockName() string {
return `block`
}
func (t *CallableType) CanSerializeAsString() bool {
return canSerializeAsString(t.paramsType) && canSerializeAsString(t.blockType) && canSerializeAsString(t.returnType)
}
func (t *CallableType) SerializationString() string {
return t.String()
}
func (t *CallableType) Default() eval.Type {
return callableType_DEFAULT
}
func (t *CallableType) Equals(o interface{}, g eval.Guard) bool {
_, ok := o.(*CallableType)
return ok
}
func (t *CallableType) Generic() eval.Type {
return callableType_DEFAULT
}
func (t *CallableType) Get(key string) (eval.Value, bool) {
switch key {
case `param_types`:
if t.paramsType == nil {
return eval.UNDEF, true
}
return t.paramsType, true
case `return_type`:
if t.returnType == nil {
return eval.UNDEF, true
}
return t.returnType, true
case `block_type`:
if t.blockType == nil {
return eval.UNDEF, true
}
return t.blockType, true
default:
return nil, false
}
}
func (t *CallableType) IsAssignable(o eval.Type, g eval.Guard) bool {
oc, ok := o.(*CallableType)
if !ok {
return false
}
if t.returnType == nil && t.paramsType == nil && t.blockType == nil {
return true
}
if t.returnType != nil {
or := oc.returnType
if or == nil {
or = anyType_DEFAULT
}
if !isAssignable(t.returnType, or) {
return false
}
}
// NOTE: these tests are made in reverse as it is calling the callable that is constrained
// (it's lower bound), not its upper bound
if oc.paramsType != nil && (t.paramsType == nil || !isAssignable(oc.paramsType, t.paramsType)) {
return false
}
if t.blockType == nil {
if oc.blockType != nil {
return false
}
return true
}
if oc.blockType == nil {
return false
}
return isAssignable(oc.blockType, t.blockType)
}
func (t *CallableType) IsInstance(o eval.Value, g eval.Guard) bool {
if l, ok := o.(eval.Lambda); ok {
return isAssignable(t, l.PType())
}
// TODO: Maybe check Go func using reflection
return false
}
func (t *CallableType) MetaType() eval.ObjectType {
return Callable_Type
}
func (t *CallableType) Name() string {
return `Callable`
}
func (t *CallableType) ParameterNames() []string {
if pt, ok := t.paramsType.(*TupleType); ok {
n := len(pt.types)
r := make([]string, 0, n)
for i := 0; i < n; {
i++
r = append(r, strconv.Itoa(i))
}
return r
}
return []string{}
}
func (t *CallableType) Parameters() (params []eval.Value) {
if *t == *callableType_DEFAULT {
return eval.EMPTY_VALUES
}
if pt, ok := t.paramsType.(*TupleType); ok {
tupleParams := pt.Parameters()
if len(tupleParams) == 0 {
params = make([]eval.Value, 0)
} else {
params = eval.Select1(tupleParams, func(p eval.Value) bool { _, ok := p.(*UnitType); return !ok })
}
} else {
params = make([]eval.Value, 0)
}
if t.blockType != nil {
params = append(params, t.blockType)
}
if t.returnType != nil {
params = []eval.Value{WrapValues(params), t.returnType}
}
return params
}
func (t *CallableType) ParametersType() eval.Type {
if t.paramsType == nil {
return nil // Return untyped nil
}
return t.paramsType
}
func (t *CallableType) Resolve(c eval.Context) eval.Type {
if t.paramsType != nil {
t.paramsType = resolve(c, t.paramsType).(*TupleType)
}
if t.returnType != nil {
t.returnType = resolve(c, t.returnType)
}
if t.blockType != nil {
t.blockType = resolve(c, t.blockType)
}
return t
}
func (t *CallableType) ReturnType() eval.Type {
return t.returnType
}
func (t *CallableType) String() string {
return eval.ToString2(t, NONE)
}
func (t *CallableType) PType() eval.Type {
return &TypeType{t}
}
func (t *CallableType) ToString(b io.Writer, s eval.FormatContext, g eval.RDetect) {
TypeToString(t, b, s, g)
}
var callableType_DEFAULT = &CallableType{paramsType: nil, blockType: nil, returnType: nil} | types/callabletype.go | 0.521959 | 0.455683 | callabletype.go | starcoder |
package stripe
import (
"context"
"github.com/stripe/stripe-go"
"github.com/turbot/steampipe-plugin-sdk/grpc/proto"
"github.com/turbot/steampipe-plugin-sdk/plugin"
"github.com/turbot/steampipe-plugin-sdk/plugin/transform"
)
func tableStripeInvoice(ctx context.Context) *plugin.Table {
return &plugin.Table{
Name: "stripe_invoice",
Description: "Invoices available for purchase or subscription.",
List: &plugin.ListConfig{
Hydrate: listInvoice,
KeyColumns: []*plugin.KeyColumn{
{Name: "collection_method", Require: plugin.Optional},
{Name: "created", Operators: []string{">", ">=", "=", "<", "<="}, Require: plugin.Optional},
{Name: "due_date", Operators: []string{">", ">=", "=", "<", "<="}, Require: plugin.Optional},
{Name: "subscription_id", Require: plugin.Optional},
{Name: "status", Require: plugin.Optional},
},
},
Get: &plugin.GetConfig{
Hydrate: getInvoice,
KeyColumns: plugin.SingleColumn("id"),
},
Columns: []*plugin.Column{
// Top columns
{Name: "id", Type: proto.ColumnType_STRING, Description: "Unique identifier for the invoice."},
{Name: "number", Type: proto.ColumnType_STRING, Description: "A unique, identifying string that appears on emails sent to the customer for this invoice. This starts with the customer’s unique invoice_prefix if it is specified."},
{Name: "amount_due", Type: proto.ColumnType_INT, Transform: transform.FromField("AmountDue"), Description: "Final amount due at this time for this invoice. If the invoice’s total is smaller than the minimum charge amount, for example, or if there is account credit that can be applied to the invoice, the amount_due may be 0. If there is a positive starting_balance for the invoice (the customer owes money), the amount_due will also take that into account. The charge that gets generated for the invoice will be for the amount specified in amount_due."},
{Name: "amount_paid", Type: proto.ColumnType_INT, Transform: transform.FromField("AmountPaid"), Description: "The amount, in cents, that was paid."},
{Name: "amount_remaining", Type: proto.ColumnType_INT, Transform: transform.FromField("AmountRemaining"), Description: "The amount remaining, in cents, that is due."},
{Name: "created", Type: proto.ColumnType_TIMESTAMP, Transform: transform.FromField("Created").Transform(transform.UnixToTimestamp), Description: "Time at which the invoice was created."},
{Name: "status", Type: proto.ColumnType_STRING, Description: "The status of the invoice, one of draft, open, paid, uncollectible, or void."},
// Other columns
{Name: "account_country", Type: proto.ColumnType_STRING, Description: "The country of the business associated with this invoice, most often the business creating the invoice."},
{Name: "account_name", Type: proto.ColumnType_STRING, Description: "The public name of the business associated with this invoice, most often the business creating the invoice."},
{Name: "application_fee_amount", Type: proto.ColumnType_INT, Transform: transform.FromField("ApplicationFeeAmount"), Description: "The fee in cents that will be applied to the invoice and transferred to the application owner’s Stripe account when the invoice is paid."},
{Name: "attempt_count", Type: proto.ColumnType_INT, Transform: transform.FromField("AttemptCount"), Description: "Number of payment attempts made for this invoice, from the perspective of the payment retry schedule. Any payment attempt counts as the first attempt, and subsequently only automatic retries increment the attempt count. In other words, manual payment attempts after the first attempt do not affect the retry schedule."},
{Name: "attempted", Type: proto.ColumnType_BOOL, Description: "Whether an attempt has been made to pay the invoice. An invoice is not attempted until 1 hour after the invoice.created webhook, for example, so you might not want to display that invoice as unpaid to your users."},
{Name: "auto_advance", Type: proto.ColumnType_BOOL, Description: "Controls whether Stripe will perform automatic collection of the invoice. When false, the invoice’s state will not automatically advance without an explicit action."},
{Name: "billing_reason", Type: proto.ColumnType_STRING, Description: "Indicates the reason why the invoice was created. subscription_cycle indicates an invoice created by a subscription advancing into a new period. subscription_create indicates an invoice created due to creating a subscription. subscription_update indicates an invoice created due to updating a subscription. subscription is set for all old invoices to indicate either a change to a subscription or a period advancement. manual is set for all invoices unrelated to a subscription (for example: created via the invoice editor). The upcoming value is reserved for simulated invoices per the upcoming invoice endpoint. subscription_threshold indicates an invoice created due to a billing threshold being reached."},
{Name: "charge", Type: proto.ColumnType_JSON, Description: "ID of the latest charge generated for this invoice, if any."},
{Name: "collection_method", Type: proto.ColumnType_STRING, Description: "Either charge_automatically, or send_invoice. When charging automatically, Stripe will attempt to pay this invoice using the default source attached to the customer. When sending an invoice, Stripe will email this invoice to the customer with payment instructions."},
{Name: "currency", Type: proto.ColumnType_STRING, Description: "Three-letter ISO currency code, in lowercase. Must be a supported currency."},
{Name: "custom_fields", Type: proto.ColumnType_JSON, Description: "Custom fields displayed on the invoice."},
{Name: "customer", Type: proto.ColumnType_JSON, Description: "The ID of the customer who will be billed."},
{Name: "customer_address", Type: proto.ColumnType_JSON, Description: "The customer’s address. Until the invoice is finalized, this field will equal customer.address. Once the invoice is finalized, this field will no longer be updated."},
{Name: "customer_email", Type: proto.ColumnType_STRING, Description: "The customer’s email. Until the invoice is finalized, this field will equal customer.email. Once the invoice is finalized, this field will no longer be updated."},
{Name: "customer_name", Type: proto.ColumnType_STRING, Description: "The customer’s name. Until the invoice is finalized, this field will equal customer.name. Once the invoice is finalized, this field will no longer be updated."},
{Name: "customer_phone", Type: proto.ColumnType_STRING, Description: "The customer’s phone number. Until the invoice is finalized, this field will equal customer.phone. Once the invoice is finalized, this field will no longer be updated."},
{Name: "customer_shipping", Type: proto.ColumnType_JSON, Description: "The customer’s shipping information. Until the invoice is finalized, this field will equal customer.shipping. Once the invoice is finalized, this field will no longer be updated."},
{Name: "customer_tax_exempt", Type: proto.ColumnType_STRING, Description: "The customer’s tax exempt status. Until the invoice is finalized, this field will equal customer.tax_exempt. Once the invoice is finalized, this field will no longer be updated."},
{Name: "customer_tax_ids", Type: proto.ColumnType_JSON, Description: "The customer’s tax IDs. Until the invoice is finalized, this field will contain the same tax IDs as customer.tax_ids. Once the invoice is finalized, this field will no longer be updated."},
{Name: "default_payment_method", Type: proto.ColumnType_STRING, Description: "ID of the default payment method for the invoice. It must belong to the customer associated with the invoice. If not set, defaults to the subscription’s default payment method, if any, or to the default payment method in the customer’s invoice settings."},
{Name: "default_source", Type: proto.ColumnType_STRING, Description: "ID of the default payment source for the invoice. It must belong to the customer associated with the invoice and be in a chargeable state. If not set, defaults to the subscription’s default source, if any, or to the customer’s default source."},
{Name: "default_tax_rates", Type: proto.ColumnType_JSON, Description: "The tax rates applied to this invoice, if any."},
{Name: "description", Type: proto.ColumnType_STRING, Description: "An arbitrary string attached to the object. Often useful for displaying to users. Referenced as ‘memo’ in the Dashboard."},
{Name: "discount", Type: proto.ColumnType_JSON, Description: "Describes the current discount applied to this invoice, if there is one. Not populated if there are multiple discounts."},
{Name: "due_date", Type: proto.ColumnType_TIMESTAMP, Transform: transform.FromField("DueDate").Transform(transform.UnixToTimestamp), Description: "The date on which payment for this invoice is due. This value will be null for invoices where collection_method=charge_automatically."},
{Name: "ending_balance", Type: proto.ColumnType_INT, Transform: transform.FromField("EndingBalance"), Description: "Ending customer balance after the invoice is finalized. Invoices are finalized approximately an hour after successful webhook delivery or when payment collection is attempted for the invoice. If the invoice has not been finalized yet, this will be null."},
{Name: "footer", Type: proto.ColumnType_STRING, Description: "Footer displayed on the invoice."},
{Name: "hosted_invoice_url", Type: proto.ColumnType_STRING, Description: "The URL for the hosted invoice page, which allows customers to view and pay an invoice. If the invoice has not been finalized yet, this will be null."},
{Name: "invoice_pdf", Type: proto.ColumnType_STRING, Description: "The link to download the PDF for the invoice. If the invoice has not been finalized yet, this will be null."},
{Name: "lines", Type: proto.ColumnType_JSON, Description: "The individual line items that make up the invoice. lines is sorted as follows: invoice items in reverse chronological order, followed by the subscription, if any."},
{Name: "livemode", Type: proto.ColumnType_BOOL, Description: "Has the value true if the invoice exists in live mode or the value false if the invoice exists in test mode."},
{Name: "metadata", Type: proto.ColumnType_JSON, Description: "Set of key-value pairs that you can attach to an invoice. This can be useful for storing additional information about the invoice in a structured format."},
{Name: "next_payment_attempt", Type: proto.ColumnType_TIMESTAMP, Transform: transform.FromField("NextPaymentAttempt").Transform(transform.UnixToTimestamp), Description: "The time at which payment will next be attempted. This value will be null for invoices where collection_method=send_invoice."},
{Name: "paid", Type: proto.ColumnType_BOOL, Description: "Whether payment was successfully collected for this invoice. An invoice can be paid (most commonly) with a charge or with credit from the customer’s account balance."},
{Name: "payment_intent", Type: proto.ColumnType_JSON, Description: "The PaymentIntent associated with this invoice. The PaymentIntent is generated when the invoice is finalized, and can then be used to pay the invoice. Note that voiding an invoice will cancel the PaymentIntent."},
{Name: "period_end", Type: proto.ColumnType_TIMESTAMP, Transform: transform.FromField("PeriodEnd").Transform(transform.UnixToTimestamp), Description: "End of the usage period during which invoice items were added to this invoice."},
{Name: "period_start", Type: proto.ColumnType_TIMESTAMP, Transform: transform.FromField("PeriodStart").Transform(transform.UnixToTimestamp), Description: "Start of the usage period during which invoice items were added to this invoice."},
{Name: "post_payment_credit_notes_amount", Type: proto.ColumnType_INT, Transform: transform.FromField("PostPaymentCreditNotesAmount"), Description: "Total amount of all post-payment credit notes issued for this invoice."},
{Name: "pre_payment_credit_notes_amount", Type: proto.ColumnType_INT, Transform: transform.FromField("PrePaymentCreditNotesAmount"), Description: "Total amount of all pre-payment credit notes issued for this invoice."},
{Name: "receipt_number", Type: proto.ColumnType_STRING, Description: "This is the transaction number that appears on email receipts sent for this invoice."},
{Name: "starting_balance", Type: proto.ColumnType_INT, Transform: transform.FromField("StartingBalance"), Description: "Starting customer balance before the invoice is finalized. If the invoice has not been finalized yet, this will be the current customer balance."},
{Name: "statement_descriptor", Type: proto.ColumnType_STRING, Description: "Extra information about an invoice for the customer’s credit card statement."},
{Name: "status_transitions", Type: proto.ColumnType_JSON, Description: "The timestamps at which the invoice status was updated."},
//{Name: "subscription", Type: proto.ColumnType_JSON, Description: "The subscription that this invoice was prepared for, if any."},
{Name: "subscription_id", Type: proto.ColumnType_STRING, Transform: transform.FromField("Subscription.ID"), Description: "ID of the subscription that this invoice was prepared for, if any."},
{Name: "subscription_proration_date", Type: proto.ColumnType_TIMESTAMP, Transform: transform.FromField("SubscriptionProrationDate").Transform(transform.UnixToTimestamp), Description: "Only set for upcoming invoices that preview prorations. The time used to calculate prorations."},
{Name: "subtotal", Type: proto.ColumnType_INT, Transform: transform.FromField("Subtotal"), Description: "Total of all subscriptions, invoice items, and prorations on the invoice before any invoice level discount or tax is applied. Item discounts are already incorporated"},
{Name: "tax", Type: proto.ColumnType_INT, Transform: transform.FromField("Tax"), Description: "The amount of tax on this invoice. This is the sum of all the tax amounts on this invoice."},
{Name: "threshold_reason", Type: proto.ColumnType_JSON, Description: "If billing_reason is set to subscription_threshold this returns more information on which threshold rules triggered the invoice."},
{Name: "total", Type: proto.ColumnType_INT, Transform: transform.FromField("Total"), Description: "Total after discounts and taxes."},
{Name: "total_tax_amounts", Type: proto.ColumnType_JSON, Description: "The aggregate amounts calculated per tax rate for all line items."},
{Name: "transfer_data", Type: proto.ColumnType_JSON, Description: "The account (if any) the payment will be attributed to for tax reporting, and where funds from the payment will be transferred to for the invoice."},
{Name: "webhooks_delivered_at", Type: proto.ColumnType_TIMESTAMP, Transform: transform.FromField("WebhooksDeliveredAt").Transform(transform.UnixToTimestamp), Description: "Invoices are automatically paid or sent 1 hour after webhooks are delivered, or until all webhook delivery attempts have been exhausted. This field tracks the time when webhooks for this invoice were successfully delivered. If the invoice had no webhooks to deliver, this will be set while the invoice is being created."},
},
}
}
func listInvoice(ctx context.Context, d *plugin.QueryData, _ *plugin.HydrateData) (interface{}, error) {
conn, err := connect(ctx, d)
if err != nil {
plugin.Logger(ctx).Error("stripe_invoice.listInvoice", "connection_error", err)
return nil, err
}
params := &stripe.InvoiceListParams{
ListParams: stripe.ListParams{
Context: ctx,
Limit: stripe.Int64(100),
Expand: stripe.StringSlice([]string{"data.default_payment_method", "data.default_source", "data.subscription"}),
},
}
equalQuals := d.KeyColumnQuals
if equalQuals["status"] != nil {
params.Status = stripe.String(equalQuals["status"].GetStringValue())
}
if equalQuals["collection_method"] != nil {
params.CollectionMethod = stripe.String(equalQuals["collection_method"].GetStringValue())
}
if equalQuals["subscription_id"] != nil {
params.Subscription = stripe.String(equalQuals["subscription_id"].GetStringValue())
}
// Comparison values
quals := d.Quals
if quals["created"] != nil {
for _, q := range quals["created"].Quals {
tsSecs := q.Value.GetTimestampValue().GetSeconds()
switch q.Operator {
case ">":
if params.CreatedRange == nil {
params.CreatedRange = &stripe.RangeQueryParams{}
}
params.CreatedRange.GreaterThan = tsSecs
case ">=":
if params.CreatedRange == nil {
params.CreatedRange = &stripe.RangeQueryParams{}
}
params.CreatedRange.GreaterThanOrEqual = tsSecs
case "=":
params.Created = stripe.Int64(tsSecs)
case "<=":
if params.CreatedRange == nil {
params.CreatedRange = &stripe.RangeQueryParams{}
}
params.CreatedRange.LesserThanOrEqual = tsSecs
case "<":
if params.CreatedRange == nil {
params.CreatedRange = &stripe.RangeQueryParams{}
}
params.CreatedRange.LesserThan = tsSecs
}
}
}
if quals["due_date"] != nil {
for _, q := range quals["due_date"].Quals {
tsSecs := q.Value.GetTimestampValue().GetSeconds()
switch q.Operator {
case ">":
if params.DueDateRange == nil {
params.DueDateRange = &stripe.RangeQueryParams{}
}
params.DueDateRange.GreaterThan = tsSecs
case ">=":
if params.DueDateRange == nil {
params.DueDateRange = &stripe.RangeQueryParams{}
}
params.DueDateRange.GreaterThanOrEqual = tsSecs
case "=":
params.DueDate = stripe.Int64(tsSecs)
case "<=":
if params.DueDateRange == nil {
params.DueDateRange = &stripe.RangeQueryParams{}
}
params.DueDateRange.LesserThanOrEqual = tsSecs
case "<":
if params.DueDateRange == nil {
params.DueDateRange = &stripe.RangeQueryParams{}
}
params.DueDateRange.LesserThan = tsSecs
}
}
}
limit := d.QueryContext.Limit
if d.QueryContext.Limit != nil {
if *limit < *params.ListParams.Limit {
params.ListParams.Limit = limit
}
}
var count int64
i := conn.Invoices.List(params)
for i.Next() {
d.StreamListItem(ctx, i.Invoice())
count++
if limit != nil {
if count >= *limit {
break
}
}
}
if err := i.Err(); err != nil {
plugin.Logger(ctx).Error("stripe_invoice.listInvoice", "query_error", err, "params", params, "i", i)
return nil, err
}
return nil, nil
}
func getInvoice(ctx context.Context, d *plugin.QueryData, _ *plugin.HydrateData) (interface{}, error) {
conn, err := connect(ctx, d)
if err != nil {
plugin.Logger(ctx).Error("stripe_invoice.getInvoice", "connection_error", err)
return nil, err
}
quals := d.KeyColumnQuals
id := quals["id"].GetStringValue()
item, err := conn.Invoices.Get(id, &stripe.InvoiceParams{})
if err != nil {
plugin.Logger(ctx).Error("stripe_invoice.getInvoice", "query_error", err, "id", id)
return nil, err
}
return item, nil
} | stripe/table_stripe_invoice.go | 0.634204 | 0.413418 | table_stripe_invoice.go | starcoder |
package gosom
import (
"encoding/csv"
"encoding/json"
"io"
"math"
"math/rand"
"strconv"
"github.com/gonum/floats"
)
// A Matrix holds and extends a two dimensional float slice.
type Matrix struct {
Data [][]float64
Rows int
Columns int
Minimums []float64
Maximums []float64
Minimum float64
Maximum float64
NaNs bool
}
// NewMatrix will create a new Matrix and work out the meta information.
// The function expects the float slice to be consistent in columns.
func NewMatrix(data [][]float64) *Matrix {
m := &Matrix{
Data: data,
Rows: len(data),
Columns: len(data[0]),
}
m.Minimums = make([]float64, m.Columns)
m.Maximums = make([]float64, m.Columns)
for i := 0; i < m.Columns; i++ {
rawColumn := m.Column(i)
clearedColumn := clearNANs(rawColumn)
m.Minimums[i] = floats.Min(clearedColumn)
m.Maximums[i] = floats.Max(clearedColumn)
if floats.HasNaN(rawColumn) {
m.NaNs = true
}
}
m.Minimum = floats.Min(m.Minimums)
m.Maximum = floats.Max(m.Maximums)
return m
}
// Column returns all values in a column.
func (m *Matrix) Column(col int) []float64 {
out := make([]float64, m.Rows)
for i, row := range m.Data {
out[i] = row[col]
}
return out
}
// RandomRow returns a random row from the matrix.
func (m *Matrix) RandomRow() []float64 {
return m.Data[rand.Intn(m.Rows)]
}
// SubMatrix returns a matrix that holds a subset of the current matrix.
func (m *Matrix) SubMatrix(start, length int) *Matrix {
values := make([][]float64, m.Rows)
for i, row := range m.Data {
values[i] = make([]float64, length)
copy(values[i], row[start:start+length])
}
return NewMatrix(values)
}
// LoadMatrixFromCSV reads CSV data and returns a new matrix.
func LoadMatrixFromCSV(source io.Reader) (*Matrix, error) {
reader := csv.NewReader(source)
data, err := reader.ReadAll()
if err != nil {
return nil, err
}
values := make([][]float64, len(data))
for i, row := range data {
values[i] = make([]float64, len(row))
for j, value := range row {
f, err := strconv.ParseFloat(value, 64)
if err != nil {
values[i][j] = math.NaN()
} else {
values[i][j] = f
}
}
}
return NewMatrix(values), nil
}
// LoadMatrixFromJSON read JSON data and returns a new matrix.
func LoadMatrixFromJSON(source io.Reader) (*Matrix, error) {
reader := json.NewDecoder(source)
var data [][]interface{}
err := reader.Decode(&data)
if err != nil {
return nil, err
}
values := make([][]float64, len(data))
for i := 0; i < len(data); i++ {
values[i] = make([]float64, len(data[i]))
for j := 0; j < len(data[i]); j++ {
if f, ok := data[i][j].(float64); ok {
values[i][j] = f
} else {
values[i][j] = math.NaN()
}
}
}
return NewMatrix(values), nil
} | matrix.go | 0.809577 | 0.477311 | matrix.go | starcoder |
package pspec
import (
"fmt"
"github.com/lyraproj/issue/issue"
"github.com/lyraproj/pcore/pcore"
"github.com/lyraproj/pcore/px"
"github.com/lyraproj/pcore/types"
"github.com/lyraproj/puppet-evaluator/evaluator"
"github.com/lyraproj/puppet-evaluator/pdsl"
"github.com/lyraproj/puppet-parser/parser"
)
type (
Input interface {
CreateTests(expected Result) []Executable
}
Node interface {
Description() string
Get(key string) (LazyValue, bool)
CreateTest() Test
collectInputs(context *TestContext, inputs []Input) []Input
}
Result interface {
CreateTest(actual interface{}) Executable
setExample(example *Example)
}
ResultEntry interface {
Match() px.Value
}
node struct {
description string
values map[string]LazyValue
given *Given
}
Example struct {
node
results []Result
}
Examples struct {
node
children []Node
}
Given struct {
inputs []Input
}
ParseResult struct {
// ParseResult needs a location so that it can provide that to the PN parser
location issue.Location
example *Example
expected string
}
EvaluationResult struct {
example *Example
expected px.Value
}
source struct {
code px.Value
epp bool
}
Source struct {
sources []*source
}
NamedSource struct {
source
name string
}
ParserOptions struct {
options px.OrderedMap
}
SettingsInput struct {
settings px.Value
}
ScopeInput struct {
scope px.Value
}
)
func pathContentAndEpp(src interface{}) (path string, content px.Value, epp bool) {
switch src := src.(type) {
case *source:
return ``, src.code, src.epp
case *NamedSource:
return src.name, src.code, src.epp
default:
panic(px.Error(px.Failure, issue.H{`message`: fmt.Sprintf(`Unknown source type %T`, src)}))
}
}
func (e *EvaluationResult) CreateTest(actual interface{}) Executable {
path, source, epp := pathContentAndEpp(actual)
return func(context *TestContext, assertions Assertions) {
o := context.ParserOptions()
if epp {
o = append(o, parser.EppMode)
}
actual, issues := parseAndValidate(path, context.resolveLazyValue(source).String(), false, o...)
failOnError(assertions, issues)
context.DoWithContext(func(c pdsl.EvaluationContext) {
actualResult, evalIssues := evaluate(c, actual)
failOnError(assertions, evalIssues)
assertions.AssertEquals(context.resolveLazyValue(e.expected), actualResult)
})
}
}
func (e *EvaluationResult) setExample(example *Example) {
e.example = example
}
func (n *node) initialize(description string, given *Given) {
n.description = description
n.given = given
n.values = make(map[string]LazyValue, 8)
}
func (n *node) addLetDefs(lazyValueLets []*LazyValueLet) {
for _, ll := range lazyValueLets {
n.values[ll.valueName] = ll.value
}
}
func newExample(description string, given *Given, results []Result) *Example {
e := &Example{results: results}
e.node.initialize(description, given)
return e
}
func newExamples(description string, given *Given, children []Node) *Examples {
e := &Examples{children: children}
e.node.initialize(description, given)
return e
}
func (n *node) collectInputs(context *TestContext, inputs []Input) []Input {
pc := context.parent
if pc != nil {
inputs = pc.node.collectInputs(pc, inputs)
}
g := n.given
if g != nil {
inputs = append(inputs, g.inputs...)
}
return inputs
}
func (e *Example) CreateTest() Test {
test := func(context *TestContext, assertions Assertions) {
tests := make([]Executable, 0, 8)
for _, input := range e.collectInputs(context, make([]Input, 0, 8)) {
for _, result := range e.results {
tests = append(tests, input.CreateTests(result)...)
}
}
for _, test := range tests {
test(context, assertions)
}
}
return &TestExecutable{testNode{e}, test}
}
func (e *Examples) CreateTest() Test {
tests := make([]Test, len(e.children))
for idx, child := range e.children {
tests[idx] = child.CreateTest()
}
return &TestGroup{testNode{e}, tests}
}
func (n *node) Description() string {
return n.description
}
func (n *node) Get(key string) (v LazyValue, ok bool) {
v, ok = n.values[key]
return
}
func (p *ParseResult) CreateTest(actual interface{}) Executable {
path, source, epp := pathContentAndEpp(actual)
expectedPN := ParsePN(p.location, p.expected)
return func(context *TestContext, assertions Assertions) {
o := context.ParserOptions()
if epp {
o = append(o, parser.EppMode)
}
actual, issues := parseAndValidate(path, context.resolveLazyValue(source).String(), false, o...)
failOnError(assertions, issues)
// Automatically strip off blocks that contain one statement
if pr, ok := actual.(*parser.Program); ok {
actual = pr.Body()
}
if be, ok := actual.(*parser.BlockExpression); ok {
s := be.Statements()
if len(s) == 1 {
actual = s[0]
}
}
actualPN := actual.ToPN()
assertions.AssertEquals(expectedPN.String(), actualPN.String())
}
}
func (p *ParseResult) setExample(example *Example) {
p.example = example
}
func (s *SettingsInput) CreateTests(expected Result) []Executable {
// Settings input does not create any tests
return []Executable{func(tc *TestContext, assertions Assertions) {
settings, ok := tc.resolveLazyValue(s.settings).(*types.Hash)
if !ok {
panic(px.Error(ValueNotHash, issue.H{`type`: `Settings`}))
}
settings.EachPair(func(key, value px.Value) {
pcore.Set(key.String(), value)
})
}}
}
func (s *ScopeInput) CreateTests(expected Result) []Executable {
return []Executable{func(tc *TestContext, assertions Assertions) {
scope, ok := tc.resolveLazyValue(s.scope).(*types.Hash)
if !ok {
panic(px.Error(ValueNotHash, issue.H{`type`: `Scope`}))
}
tc.scope = evaluator.NewScope2(scope, false)
}}
}
func (i *Source) CreateTests(expected Result) []Executable {
result := make([]Executable, len(i.sources))
for idx, source := range i.sources {
result[idx] = expected.CreateTest(source)
}
return result
}
func (i *Source) AsInput() Input {
return i
}
func (ns *NamedSource) CreateTests(expected Result) []Executable {
return []Executable{expected.CreateTest(ns)}
}
func (ps *ParserOptions) CreateTests(expected Result) []Executable {
return []Executable{func(tc *TestContext, assertions Assertions) {
if tc.parserOptions == nil {
tc.parserOptions = ps.options
} else {
tc.parserOptions = tc.parserOptions.Merge(ps.options)
}
}}
}
func init() {
px.NewGoConstructor2(`PSpec::Example`,
func(l px.LocalTypes) {
l.Type2(`Given`, types.NewGoRuntimeType(&Given{}))
l.Type2(`Let`, types.NewGoRuntimeType(&LazyValueLet{}))
l.Type2(`SpecResult`, types.NewGoRuntimeType((*Result)(nil)))
},
func(d px.Dispatch) {
d.Param(`String`)
d.RepeatedParam(`Variant[Let,Given,SpecResult]`)
d.Function(func(c px.Context, args []px.Value) px.Value {
lets := make([]*LazyValueLet, 0)
var given *Given
results := make([]Result, 0)
for _, arg := range args[1:] {
if rt, ok := arg.(*types.RuntimeValue); ok {
i := rt.Interface()
switch i.(type) {
case *LazyValueLet:
lets = append(lets, i.(*LazyValueLet))
case *Given:
if given != nil {
}
given = i.(*Given)
case Result:
results = append(results, i.(Result))
}
}
}
example := newExample(args[0].String(), given, results)
example.addLetDefs(lets)
for _, result := range results {
result.setExample(example)
}
return types.WrapRuntime(example)
})
})
px.NewGoConstructor2(`PSpec::Examples`,
func(l px.LocalTypes) {
l.Type2(`Given`, types.NewGoRuntimeType(&Given{}))
l.Type2(`Let`, types.NewGoRuntimeType(&LazyValueLet{}))
l.Type2(`ExampleNode`, types.NewGoRuntimeType((*Node)(nil)))
l.Type(`Nodes`, `Variant[ExampleNode, Array[Nodes]]`)
},
func(d px.Dispatch) {
d.Param(`String`)
d.RepeatedParam(`Variant[Nodes,Let,Given]`)
d.Function(func(c px.Context, args []px.Value) px.Value {
lets := make([]*LazyValueLet, 0)
var given *Given
others := make([]px.Value, 0)
for _, arg := range args[1:] {
if rt, ok := arg.(*types.RuntimeValue); ok {
if l, ok := rt.Interface().(*LazyValueLet); ok {
lets = append(lets, l)
continue
}
if g, ok := rt.Interface().(*Given); ok {
given = g
continue
}
}
others = append(others, arg)
}
ex := newExamples(args[0].String(), given, splatNodes(types.WrapValues(others)))
ex.addLetDefs(lets)
return types.WrapRuntime(ex)
})
})
px.NewGoConstructor(`PSpec::Given`,
func(d px.Dispatch) {
d.RepeatedParam2(types.NewVariantType(types.DefaultStringType(), types.NewGoRuntimeType((*Input)(nil)), types.NewGoRuntimeType((*LazyValue)(nil))))
d.Function(func(c px.Context, args []px.Value) px.Value {
argc := len(args)
inputs := make([]Input, argc)
for idx := 0; idx < argc; idx++ {
arg := args[idx]
switch arg.(type) {
case px.StringValue:
inputs[idx] = &Source{[]*source{{arg, false}}}
default:
v := arg.(*types.RuntimeValue).Interface()
switch v.(type) {
case Input:
inputs[idx] = v.(Input)
default:
inputs[idx] = &Source{[]*source{{arg, false}}}
}
}
}
return types.WrapRuntime(&Given{inputs})
})
})
px.NewGoConstructor(`PSpec::Settings`,
func(d px.Dispatch) {
d.Param(`Any`)
d.Function(func(c px.Context, args []px.Value) px.Value {
return types.WrapRuntime(&SettingsInput{args[0]})
})
})
px.NewGoConstructor(`PSpec::Scope`,
func(d px.Dispatch) {
d.Param(`Hash[Pattern[/\A[a-z_]\w*\z/],Any]`)
d.Function(func(c px.Context, args []px.Value) px.Value {
return types.WrapRuntime(&ScopeInput{args[0]})
})
})
px.NewGoConstructor(`PSpec::Source`,
func(d px.Dispatch) {
d.RepeatedParam2(types.NewVariantType(types.DefaultStringType(), types.NewGoRuntimeType((*LazyValue)(nil))))
d.Function(func(c px.Context, args []px.Value) px.Value {
argc := len(args)
sources := make([]*source, argc)
for idx := 0; idx < argc; idx++ {
sources[idx] = &source{args[idx], false}
}
return types.WrapRuntime(&Source{sources})
})
})
px.NewGoConstructor(`PSpec::Epp_source`,
func(d px.Dispatch) {
d.RepeatedParam2(types.NewVariantType(types.DefaultStringType(), types.NewGoRuntimeType((*LazyValue)(nil))))
d.Function(func(c px.Context, args []px.Value) px.Value {
argc := len(args)
sources := make([]*source, argc)
for idx := 0; idx < argc; idx++ {
sources[idx] = &source{args[idx], true}
}
return types.WrapRuntime(&Source{sources})
})
})
px.NewGoConstructor(`PSpec::Named_source`,
func(d px.Dispatch) {
d.Param(`String`)
d.Param2(types.NewVariantType(types.DefaultStringType(), types.NewGoRuntimeType((*LazyValue)(nil))))
d.Function(func(c px.Context, args []px.Value) px.Value {
return types.WrapRuntime(&NamedSource{source{args[1], false}, args[0].String()})
})
})
px.NewGoConstructor(`PSpec::Unindent`,
func(d px.Dispatch) {
d.Param(`String`)
d.Function(func(c px.Context, args []px.Value) px.Value {
return types.WrapString(issue.Unindent(args[0].String()))
})
})
px.NewGoConstructor(`PSpec::Parser_options`,
func(d px.Dispatch) {
d.Param(`Hash[Pattern[/[a-z_]*/],Data]`)
d.Function(func(c px.Context, args []px.Value) px.Value {
return types.WrapRuntime(&ParserOptions{args[0].(*types.Hash)})
})
})
}
func splatNodes(args px.List) []Node {
nodes := make([]Node, 0)
args.Each(func(arg px.Value) {
if rv, ok := arg.(*types.RuntimeValue); ok {
nodes = append(nodes, rv.Interface().(Node))
} else {
nodes = append(nodes, splatNodes(arg.(*types.Array))...)
}
})
return nodes
} | pspec/example.go | 0.670932 | 0.419767 | example.go | starcoder |
package store
import (
"bufio"
"encoding/binary"
"fmt"
"os"
"sync"
)
// Store is an interface for the byte store.
type Store interface {
// Append persists the given bytes to the store. Returns the number of
// written bytes, the position where the store holds the record and an error.
Append(record []byte) (n uint64, position uint64, err error)
// Read returns the record stored at the given position.
Read(position uint64) ([]byte, error)
// ReadAt reads bytes of b length beginning at the offset.
// It implements io.ReaderAt on the store type.
ReadAt(b []byte, offset int64) (int, error)
// Close persists any buffered data before closing the store.
Close() error
}
// RecordSizeLength defines the number of bytes used to store the record length.
const RecordSizeLength = 8
// MaxRecordLength defines the maximum length of the single record.
const MaxRecordLength = 1 << RecordSizeLength
// ErrMaxRecordLength is returned if the record more the the maximum length.
var ErrMaxRecordLength = fmt.Errorf("the record to long: max length is %d", MaxRecordLength)
// store struct is a simple wrapper around a file to read and write bytes to it.
// This struct implements the Store interface.
type store struct {
mu sync.Mutex // to prevent cincurrent read/write to the file
file *os.File
buf *bufio.Writer
size uint64
}
// New returns a new store that wraps the given file.
func New(file *os.File) (Store, error) {
// File could be not empty, so it is necessary to get its size. It equals
// to 0 if the file is new and empty. The file size is used as the store size.
fileStat, err := os.Stat(file.Name())
if err != nil {
return nil, fmt.Errorf("failed to read the file stat: %w", err)
}
fileSize := uint64(fileStat.Size())
store := &store{
mu: sync.Mutex{},
file: file,
size: fileSize,
buf: bufio.NewWriter(file),
}
return store, nil
}
// Append persists the given bytes to the store. Returns the number of written
// bytes, the position where the store holds the record in the file and an error.
func (s *store) Append(record []byte) (uint64, uint64, error) {
s.mu.Lock()
defer s.mu.Unlock()
if len(record) > MaxRecordLength {
return 0, 0, ErrMaxRecordLength
}
// Remember current position to return at the end.
position := s.size
// fmt.Println(s.buf)
// Write the record length to know the record size on reading.
recordSize := uint64(len(record))
if err := binary.Write(s.buf, binary.BigEndian, recordSize); err != nil {
return 0, 0, fmt.Errorf("failed to write the record size: %w", err)
}
// fmt.Println(s.buf)
// Write to the buffered writer instead of directly to the file to reduce
// the number of system calls and improve performance.
n, err := s.buf.Write(record)
if err != nil {
return 0, 0, fmt.Errorf("failed to write the record: %w", err)
}
// fmt.Println(s.buf)
// Do not forget to add length of the record size.
n += RecordSizeLength
s.size += uint64(n)
return uint64(n), position, nil
}
// Read returns the record stored at the given position.
func (s *store) Read(position uint64) ([]byte, error) {
s.mu.Lock()
defer s.mu.Unlock()
// Flush the buffer to write all records from the buffer to disk before
// reading from the file.
if err := s.buf.Flush(); err != nil {
return nil, fmt.Errorf("failed to flush the buffer: %w", err)
}
// Read the bytes that contain the record size.
recordSize := make([]byte, RecordSizeLength)
if _, err := s.file.ReadAt(recordSize, int64(position)); err != nil {
return nil, fmt.Errorf("failed to read the record size: %w", err)
}
recordPosition := int64(position + RecordSizeLength)
b := make([]byte, binary.BigEndian.Uint64(recordSize))
if _, err := s.file.ReadAt(b, recordPosition); err != nil {
return nil, fmt.Errorf("failed to read the record: %w", err)
}
return b, nil
}
// ReadAt reads bytes of b length from the file beginning at the offset.
func (s *store) ReadAt(b []byte, offset int64) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
// Flush the buffer to write all records from the buffer to disk before
// reading from the file.
if err := s.buf.Flush(); err != nil {
return 0, fmt.Errorf("failed to flush the buffer: %w", err)
}
n, err := s.file.ReadAt(b, offset)
if err != nil {
return 0, fmt.Errorf("failed to read: %w", err)
}
return n, nil
}
// Close persists any buffered data to file before closing the file.
func (s *store) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
// Flush the buffer to write all records from the buffer to disk before
// closing the file.
if err := s.buf.Flush(); err != nil {
return fmt.Errorf("failed to flush the buffer: %w", err)
}
if err := s.file.Close(); err != nil {
return fmt.Errorf("failed to close the file: %w", err)
}
return nil
} | internal/log/store/store.go | 0.73431 | 0.45538 | store.go | starcoder |
package network
import (
"github.com/jrecuero/go-cli/grafo"
)
// Network represents ...
type Network struct {
*grafo.Grafo
}
// AddNode is ...
func (net *Network) AddNode(parent grafo.IVertex, child grafo.IVertex, weight int) error {
if parent == nil {
parent = net.GetRoot()
}
var edge grafo.IEdge = NewWeight(parent, child, weight)
return net.AddEdge(parent, edge)
}
// CostToNode returns how much weight is required to move fromt the network
// anchor to the destination node.
func (net *Network) CostToNode(dest *Node) (int, bool) {
if edge, ok := net.ExistPathTo(nil, dest.Vertex); ok {
if w, bok := edge.Check(); bok {
weight := w.(int) + dest.Content.(*NodeContent).GetWeight()
return weight, true
}
}
return 0, false
}
// pathsFromNodeToNode is ...
func (net *Network) pathsFromNodeToNode(anchor *Node, dest *Node, ids []grafo.Ider) []*grafo.Path {
var paths []*grafo.Path
ids = append(ids, anchor.GetID())
//tools.ToDisplay("%#v\n", ids)
for _, edge := range anchor.Edges {
if found := findIDInArray(edge.GetChild().GetID(), ids); !found {
if edge.GetChild() == NodeToVertex(dest) {
p := grafo.NewPath("")
p.Edges = append(p.Edges, edge)
paths = append(paths, p)
} else {
if childPaths := net.pathsFromNodeToNode(ToNode(edge.GetChild()), dest, ids); childPaths != nil {
for _, childPath := range childPaths {
edgees := []grafo.IEdge{edge}
childPath.Edges = append(edgees, childPath.Edges...)
paths = append(paths, childPath)
}
}
}
}
}
return paths
}
// PathsFromNodeToNode is ...
func (net *Network) PathsFromNodeToNode(anchor *Node, dest *Node) []*grafo.Path {
return net.pathsFromNodeToNode(anchor, dest, nil)
}
// FindLoops is ...
func (net *Network) FindLoops(anchor *Node, ids []grafo.Ider) [][]*Node {
if index := indexOf(anchor.GetID(), ids); index != -1 {
//tools.ToDisplay("Loop at: %#v : %d\n", ids, index)
var nodes []*Node
for _, id := range ids[index:len(ids)] {
nodes = append(nodes, ToNode(net.GetVertices()[id]))
}
return [][]*Node{nodes}
}
ids = append(ids, anchor.GetID())
var loops [][]*Node
for _, edge := range anchor.Edges {
if loop := net.FindLoops(ToNode(edge.GetChild()), ids); loop != nil {
for _, l := range loop {
loops = append(loops, l)
}
}
}
return loops
}
// TotalWeightInPath is ...
func (net *Network) TotalWeightInPath(path *grafo.Path) int {
var weight int
for _, edge := range path.Edges {
if w, ok := edge.Check(); ok {
weight += w.(int)
}
weight += edge.GetChild().GetContent().(*NodeContent).GetWeight()
}
return weight
}
// isBetterPath is ...
func (net *Network) isBetterPath(best *grafo.Path, bestWeight int, path *grafo.Path) (*grafo.Path, int) {
pathWeight := net.TotalWeightInPath(path)
if best == nil || pathWeight < bestWeight {
return path, pathWeight
}
return best, bestWeight
}
// BestPathFromNodeToNode is ...
func (net *Network) BestPathFromNodeToNode(anchor *Node, dest *Node) (*grafo.Path, int) {
var bestPath *grafo.Path
var bestWeight int
paths := net.PathsFromNodeToNode(anchor, dest)
for _, path := range paths {
bestPath, bestWeight = net.isBetterPath(bestPath, bestWeight, path)
}
return bestPath, bestWeight
}
//NewNetwork is ...
func NewNetwork(label string) *Network {
return &Network{
Grafo: grafo.NewGrafo(label),
}
}
// findIDInArray is ...
func findIDInArray(id grafo.Ider, lista []grafo.Ider) bool {
for _, val := range lista {
if val == id {
return true
}
}
return false
}
// indexOf is ...
func indexOf(id grafo.Ider, lista []grafo.Ider) int {
for index, val := range lista {
if val == id {
return index
}
}
return -1
} | grafo/network/network.go | 0.667906 | 0.435841 | network.go | starcoder |
package xnumber
import (
"fmt"
"math"
"strconv"
)
// accuracy
type Accuracy func() float64
// Default accuracy, use 1e-3.
var DefaultAccuracy = NewAccuracy(1e-3)
func NewAccuracy(eps float64) Accuracy {
return func() float64 {
return eps
}
}
func (eps Accuracy) Equal(a, b float64) bool {
return math.Abs(a-b) < eps()
}
func (eps Accuracy) NotEqual(a, b float64) bool {
return !eps.Equal(a, b)
}
func (eps Accuracy) Greater(a, b float64) bool {
return math.Max(a, b) == a && math.Abs(a-b) > eps()
}
func (eps Accuracy) Smaller(a, b float64) bool {
return math.Max(a, b) == b && math.Abs(a-b) > eps()
}
func (eps Accuracy) GreaterOrEqual(a, b float64) bool {
return math.Max(a, b) == a || math.Abs(a-b) < eps()
}
func (eps Accuracy) SmallerOrEqual(a, b float64) bool {
return math.Max(a, b) == b || math.Abs(a-b) < eps()
}
// render
func RenderByte(b float64) string {
if DefaultAccuracy.SmallerOrEqual(b, 0) {
return "0B"
}
if DefaultAccuracy.Smaller(b, 1024) {
return fmt.Sprintf("%dB", int(b))
}
kb := b / 1024.0
if DefaultAccuracy.Smaller(kb, 1024) {
return fmt.Sprintf("%.2fKB", kb)
}
mb := kb / 1024.0
if DefaultAccuracy.Smaller(mb, 1024) {
return fmt.Sprintf("%.2fMB", mb)
}
gb := mb / 1024.0
if DefaultAccuracy.Smaller(gb, 1024) {
return fmt.Sprintf("%.2fGB", gb)
}
tb := gb / 1024.0
return fmt.Sprintf("%.2fTB", tb)
}
func Bool(b bool) int {
if b {
return 1
}
return 0
}
// parse
func ParseInt(s string, base int) (int, error) {
i, e := strconv.ParseInt(s, base, 0)
return int(i), e
}
func ParseInt8(s string, base int) (int8, error) {
i, e := strconv.ParseInt(s, base, 8)
return int8(i), e
}
func ParseInt16(s string, base int) (int16, error) {
i, e := strconv.ParseInt(s, base, 16)
return int16(i), e
}
func ParseInt32(s string, base int) (int32, error) {
i, e := strconv.ParseInt(s, base, 32)
return int32(i), e
}
func ParseInt64(s string, base int) (int64, error) {
i, e := strconv.ParseInt(s, base, 64)
return i, e
}
func ParseUint(s string, base int) (uint, error) {
i, e := strconv.ParseUint(s, base, 0)
return uint(i), e
}
func ParseUint8(s string, base int) (uint8, error) {
i, e := strconv.ParseUint(s, base, 8)
return uint8(i), e
}
func ParseUint16(s string, base int) (uint16, error) {
i, e := strconv.ParseUint(s, base, 16)
return uint16(i), e
}
func ParseUint32(s string, base int) (uint32, error) {
i, e := strconv.ParseUint(s, base, 32)
return uint32(i), e
}
func ParseUint64(s string, base int) (uint64, error) {
i, e := strconv.ParseUint(s, base, 64)
return i, e
}
func ParseFloat32(s string) (float32, error) {
f, e := strconv.ParseFloat(s, 32)
return float32(f), e
}
func ParseFloat64(s string) (float64, error) {
f, e := strconv.ParseFloat(s, 64)
return f, e
}
// atoX
func Atoi(s string) (int, error) {
return ParseInt(s, 10)
}
func Atoi8(s string) (int8, error) {
return ParseInt8(s, 10)
}
func Atoi16(s string) (int16, error) {
return ParseInt16(s, 10)
}
func Atoi32(s string) (int32, error) {
return ParseInt32(s, 10)
}
func Atoi64(s string) (int64, error) {
return ParseInt64(s, 10)
}
func Atou(s string) (uint, error) {
return ParseUint(s, 10)
}
func Atou8(s string) (uint8, error) {
return ParseUint8(s, 10)
}
func Atou16(s string) (uint16, error) {
return ParseUint16(s, 10)
}
func Atou32(s string) (uint32, error) {
return ParseUint32(s, 10)
}
func Atou64(s string) (uint64, error) {
return ParseUint64(s, 10)
}
func Atof32(s string) (float32, error) {
return ParseFloat32(s)
}
func Atof64(s string) (float64, error) {
return ParseFloat64(s)
}
// format
func FormatInt(i int, base int) string {
return strconv.FormatInt(int64(i), base)
}
func FormatInt8(i int8, base int) string {
return strconv.FormatInt(int64(i), base)
}
func FormatInt16(i int16, base int) string {
return strconv.FormatInt(int64(i), base)
}
func FormatInt32(i int32, base int) string {
return strconv.FormatInt(int64(i), base)
}
func FormatInt64(i int64, base int) string {
return strconv.FormatInt(i, base)
}
func FormatUint(i uint, base int) string {
return strconv.FormatUint(uint64(i), base)
}
func FormatUint8(i uint8, base int) string {
return strconv.FormatUint(uint64(i), base)
}
func FormatUint16(i uint16, base int) string {
return strconv.FormatUint(uint64(i), base)
}
func FormatUint32(i uint32, base int) string {
return strconv.FormatUint(uint64(i), base)
}
func FormatUint64(i uint64, base int) string {
return strconv.FormatUint(i, base)
}
func FormatFloat32(f float32, fmt byte, prec int) string {
return strconv.FormatFloat(float64(f), fmt, prec, 32)
}
func FormatFloat64(f float64, fmt byte, prec int) string {
return strconv.FormatFloat(f, fmt, prec, 64)
}
// Xtoa
func Itoa(i int) string {
return FormatInt(i, 10)
}
func I8toa(i int8) string {
return FormatInt8(i, 10)
}
func I16toa(i int16) string {
return FormatInt16(i, 10)
}
func I32toa(i int32) string {
return FormatInt32(i, 10)
}
func I64toa(i int64) string {
return FormatInt64(i, 10)
}
func Utoa(i uint) string {
return FormatUint(i, 10)
}
func U8toa(i uint8) string {
return FormatUint8(i, 10)
}
func U16toa(i uint16) string {
return FormatUint16(i, 10)
}
func U32toa(i uint32) string {
return FormatUint32(i, 10)
}
func U64toa(i uint64) string {
return FormatUint64(i, 10)
}
func F32toa(f float32) string {
return FormatFloat32(f, 'f', -1)
}
func F64toa(f float64) string {
return FormatFloat64(f, 'f', -1)
}
// min max
const (
MinInt8 = int8(-128) // -1 << 7
MinInt16 = int16(-32768) // -1 << 15
MinInt32 = int32(-2147483648) // -1 << 31
MinInt64 = int64(-9223372036854775808) // -1 << 63
MinUint8 = uint8(0) // 0
MinUint16 = uint16(0) // 0
MinUint32 = uint32(0) // 0
MinUint64 = uint64(0) // 0
MaxInt8 = int8(127) // 1<<7 - 1
MaxInt16 = int16(32767) // 1<<15 - 1
MaxInt32 = int32(2147483647) // 1<<31 - 1
MaxInt64 = int64(9223372036854775807) // 1<<63 - 1
MaxUint8 = uint8(255) // 1<<8 - 1
MaxUint16 = uint16(65535) // 1<<16 - 1
MaxUint32 = uint32(4294967295) // 1<<32 - 1
MaxUint64 = uint64(18446744073709551615) // 1<<64 - 1
MaxFloat32 = float32(math.MaxFloat32) // 2**127 * (2**24 - 1) / 2**23
SmallestNonzeroFloat32 = float32(math.SmallestNonzeroFloat32) // 1 / 2**(127 - 1 + 23)
MaxFloat64 = float64(math.MaxFloat64) // 2**1023 * (2**53 - 1) / 2**52
SmallestNonzeroFloat64 = float64(math.SmallestNonzeroFloat64) // 1 / 2**(1023 - 1 + 52)
) | xnumber/xnumber.go | 0.811078 | 0.51818 | xnumber.go | starcoder |
package simulation
import (
"math"
)
type ypFunc func(t, y float64) float64 // dy/dt definition
type ypStepFunc func(t, y, dt float64) float64 // step function for computing dy/dt
// newRKStep takes a function representing an ODE
// and returns a function that performs a single step of the 4th order
// Runge-Kutta method. See https://en.wikipedia.org/wiki/Runge–Kutta_methods
func newRK4Step(yp ypFunc) ypStepFunc {
return func(t, y, dt float64) float64 {
dy1 := dt * yp(t, y)
dy2 := dt * yp(t+dt/2, y+dy1/2)
dy3 := dt * yp(t+dt/2, y+dy2/2)
dy4 := dt * yp(t+dt, y+dy3)
return y + (dy1+2*(dy2+dy3)+dy4)/6
}
}
// SolveStep performs an update towards solving a DE using RK4. Performs approx. 1/dtStep iterations in a step.
func solveStep(t, y, dtStep float64, yPrime ypFunc) (t2, y2 float64) {
ypStep := newRK4Step(yPrime)
for steps := int(1 / dtStep); steps > 1; steps-- {
y = ypStep(t, y, dtStep)
t += dtStep
}
tUp := math.Ceil(t)
dtFinal := float64(tUp) - t // perform last step over remaining dt to finish integer time increment
y = ypStep(t, y, dtFinal)
return tUp, y
}
// ODEProblem is simply a struct to initialise the parts of and ODE IVP
type ODEProblem struct {
YPrime ypFunc // func that returns dy/dt
T0 int // initial integer timestep
Y0 float64 // initial y value for IVP
DtStep float64 // solver step size. Typically 0.1
}
// Step is a closure that initialises t, y and returns a function that allows you to perform a solution
// step in the DE solution. Performs approx. 1/dtStep iterations in a step.
func (de ODEProblem) Step() func() (t2, y2 float64) {
t, y := float64(de.T0), de.Y0
return func() (t2, y2 float64) {
t, y = solveStep(t, y, de.DtStep, de.YPrime)
return t, y
}
}
// StepDeltaY is the same as Step but allows for manipulation of y by providing a deltaY arg. Internal y
// will then be modified: y -> y+deltaY. Useful for modifiying y between steps to model external disturbances (e.g. resource consumption)
func (de ODEProblem) StepDeltaY() func(float64) (t2, y2 float64) {
t, y := float64(de.T0), de.Y0
return func(deltaY float64) (t2, y2 float64) {
t, y = solveStep(t, y+deltaY, de.DtStep, de.YPrime) // adjust y by deltaY
return t, y
}
}
// SolveUntilT solves a DE from T0 (from initialisation) to tFinal
func (de ODEProblem) SolveUntilT(tFinal int) []float64 {
dtPrint := 1 // and to print at whole numbers.
t, y := float64(de.T0), de.Y0
out := make([]float64, 0)
for t1 := de.T0 + dtPrint; t1 <= tFinal; t1 += dtPrint {
t, y = solveStep(t, y, de.DtStep, de.YPrime)
out = append(out, y)
}
return out
} | internal/common/simulation/ode.go | 0.832203 | 0.879613 | ode.go | starcoder |
package iso20022
// Conversion between the currency of a card acceptor and the currency of a card issuer, provided by a dedicated service provider. The currency conversion has to be accepted by the cardholder.
type CurrencyConversion1 struct {
// Identification of the currency conversion operation for the service provider.
CurrencyConversionIdentification *Max35Text `xml:"CcyConvsId,omitempty"`
// Result of a requested currency conversion.
Result *CurrencyConversionResponse1Code `xml:"Rslt"`
// Plain text explaining the result of the currency conversion request.
ResponseReason *Max35Text `xml:"RspnRsn,omitempty"`
// Currency into which the amount is converted (ISO 4217, 3 alphanumeric characters).
TargetCurrency *CurrencyCode `xml:"TrgtCcy"`
// Currency into which the amount is converted (ISO 4217, 3 numeric characters).
TargetCurrencyNumeric *Exact3NumericText `xml:"TrgtCcyNmrc"`
// Maximal number of digits after the decimal separator for target currency.
TargetCurrencyDecimal *Number `xml:"TrgtCcyDcml"`
// Full name of the target currency.
TargetCurrencyName *Max35Text `xml:"TrgtCcyNm,omitempty"`
// Amount converted in the target currency, including additional charges.
ResultingAmount *ImpliedCurrencyAndAmount `xml:"RsltgAmt"`
// Exchange rate, expressed as a percentage, applied to convert the original amount into the resulting amount.
ExchangeRate *PercentageRate `xml:"XchgRate"`
// Exchange rate, expressed as a percentage, applied to convert the resulting amount into the original amount.
InvertedExchangeRate *PercentageRate `xml:"NvrtdXchgRate,omitempty"`
// Date and time at which the exchange rate has been quoted.
QuotationDate *ISODateTime `xml:"QtnDt,omitempty"`
// Validity limit of the exchange rate.
ValidUntil *ISODateTime `xml:"VldUntil,omitempty"`
// Currency from which the amount is converted (ISO 4217, 3 alphanumeric characters).
SourceCurrency *CurrencyCode `xml:"SrcCcy"`
// Currency from which the amount is converted (ISO 4217, 3 numeric characters).
SourceCurrencyNumeric *CurrencyCode `xml:"SrcCcyNmrc,omitempty"`
// Maximal number of digits after the decimal separator for source currency.
SourceCurrencyDecimal *Number `xml:"SrcCcyDcml"`
// Full name of the source currency.
SourceCurrencyName *Max35Text `xml:"SrcCcyNm,omitempty"`
// Original amount in the source currency.
OriginalAmount *ImpliedCurrencyAndAmount `xml:"OrgnlAmt"`
// Commission or additional charges made as part of a currency conversion.
CommissionDetails []*Commission19 `xml:"ComssnDtls,omitempty"`
// Markup made as part of a currency conversion.
MarkUpDetails []*Commission18 `xml:"MrkUpDtls,omitempty"`
// Card scheme declaration (disclaimer) to present to the cardholder.
DeclarationDetails *Max2048Text `xml:"DclrtnDtls,omitempty"`
}
func (c *CurrencyConversion1) SetCurrencyConversionIdentification(value string) {
c.CurrencyConversionIdentification = (*Max35Text)(&value)
}
func (c *CurrencyConversion1) SetResult(value string) {
c.Result = (*CurrencyConversionResponse1Code)(&value)
}
func (c *CurrencyConversion1) SetResponseReason(value string) {
c.ResponseReason = (*Max35Text)(&value)
}
func (c *CurrencyConversion1) SetTargetCurrency(value string) {
c.TargetCurrency = (*CurrencyCode)(&value)
}
func (c *CurrencyConversion1) SetTargetCurrencyNumeric(value string) {
c.TargetCurrencyNumeric = (*Exact3NumericText)(&value)
}
func (c *CurrencyConversion1) SetTargetCurrencyDecimal(value string) {
c.TargetCurrencyDecimal = (*Number)(&value)
}
func (c *CurrencyConversion1) SetTargetCurrencyName(value string) {
c.TargetCurrencyName = (*Max35Text)(&value)
}
func (c *CurrencyConversion1) SetResultingAmount(value, currency string) {
c.ResultingAmount = NewImpliedCurrencyAndAmount(value, currency)
}
func (c *CurrencyConversion1) SetExchangeRate(value string) {
c.ExchangeRate = (*PercentageRate)(&value)
}
func (c *CurrencyConversion1) SetInvertedExchangeRate(value string) {
c.InvertedExchangeRate = (*PercentageRate)(&value)
}
func (c *CurrencyConversion1) SetQuotationDate(value string) {
c.QuotationDate = (*ISODateTime)(&value)
}
func (c *CurrencyConversion1) SetValidUntil(value string) {
c.ValidUntil = (*ISODateTime)(&value)
}
func (c *CurrencyConversion1) SetSourceCurrency(value string) {
c.SourceCurrency = (*CurrencyCode)(&value)
}
func (c *CurrencyConversion1) SetSourceCurrencyNumeric(value string) {
c.SourceCurrencyNumeric = (*CurrencyCode)(&value)
}
func (c *CurrencyConversion1) SetSourceCurrencyDecimal(value string) {
c.SourceCurrencyDecimal = (*Number)(&value)
}
func (c *CurrencyConversion1) SetSourceCurrencyName(value string) {
c.SourceCurrencyName = (*Max35Text)(&value)
}
func (c *CurrencyConversion1) SetOriginalAmount(value, currency string) {
c.OriginalAmount = NewImpliedCurrencyAndAmount(value, currency)
}
func (c *CurrencyConversion1) AddCommissionDetails() *Commission19 {
newValue := new(Commission19)
c.CommissionDetails = append(c.CommissionDetails, newValue)
return newValue
}
func (c *CurrencyConversion1) AddMarkUpDetails() *Commission18 {
newValue := new(Commission18)
c.MarkUpDetails = append(c.MarkUpDetails, newValue)
return newValue
}
func (c *CurrencyConversion1) SetDeclarationDetails(value string) {
c.DeclarationDetails = (*Max2048Text)(&value)
} | CurrencyConversion1.go | 0.831143 | 0.527986 | CurrencyConversion1.go | starcoder |
package core
import (
"image/color"
"math"
"reflect"
)
type Color struct {
R, G, B byte
}
var Black = Color{0, 0, 0}
var BlackRGBA = color.RGBA{0, 0, 0, 255}
func (c Color) RGBA() (r, g, b, a uint32) {
return color.RGBA{c.R, c.G, c.B, 255}.RGBA()
}
func (c Color) ToRGBA() color.RGBA {
return color.RGBA{
c.R,
c.G,
c.B,
255,
}
}
func MixColors(c1 Color, c2 Color, f float64) Color {
return Color{
R: MixBytes(c1.R, c2.R, f),
G: MixBytes(c1.G, c2.G, f),
B: MixBytes(c1.B, c2.B, f),
}
}
func MixColorsRGBA(c1 color.RGBA, c2 color.RGBA, f float64) color.RGBA {
return color.RGBA{
R: MixBytes(c1.R, c2.R, f),
G: MixBytes(c1.G, c2.G, f),
B: MixBytes(c1.B, c2.B, f),
A: 255,
}
}
func min(a, b uint8) uint8 {
if a > b {
return b
}
return a
}
func Darken(c Color, d uint8) Color {
return Color{
R: c.R - min(d, c.R),
G: c.G - min(d, c.G),
B: c.B - min(d, c.B),
}
}
func DarkenRGBA(c color.RGBA, d uint8) color.RGBA {
return color.RGBA{
R: c.R - min(d, c.R),
G: c.G - min(d, c.G),
B: c.B - min(d, c.B),
A: c.A,
}
}
func Lighten(c Color, d uint8) Color {
return Color{
R: c.R + min(d, 255-c.R),
G: c.G + min(d, 255-c.G),
B: c.B + min(d, 255-c.B),
}
}
func LightenRGBA(c color.RGBA, d uint8) color.RGBA {
return color.RGBA{
R: c.R + min(d, 255-c.R),
G: c.G + min(d, 255-c.G),
B: c.B + min(d, 255-c.B),
A: c.A,
}
}
func v(m1, m2, hue float64) float64 {
_, hue = math.Modf(hue)
_, hue = math.Modf(hue + 1)
if hue < 1./6 {
return m1 + (m2-m1)*hue*6
}
if hue < .5 {
return m2
}
if hue < 2./3 {
return m1 + (m2-m1)*(2./3-hue)*6
}
return m1
}
func Hsl2col(hue, sat, lig int) Color {
h := float64(hue) / 360
s := float64(sat) / 100
l := float64(lig) / 100
var rf, gf, bf, m1, m2 float64
if s == 0 {
rf, gf, bf = 1, 1, 1
} else {
if l <= .5 {
m2 = l * (1.0 + s)
} else {
m2 = l + s - (l * s)
}
m1 = 2*l - m2
rf = v(m1, m2, h+1./3)
gf = v(m1, m2, h)
bf = v(m1, m2, h-1./3)
}
return Color{
R: byte(255 * rf),
G: byte(255 * gf),
B: byte(255 * bf),
}
}
func ColorFromData(d interface{}, name string, lightness int) Color {
dv := reflect.ValueOf(d)
hue := int(dv.FieldByName(name + "Hue").Int())
sat := int(dv.FieldByName(name + "Sat").Int())
return Hsl2col(hue, sat, lightness)
} | unicornify/core/color.go | 0.798265 | 0.411466 | color.go | starcoder |
package rfm69
// http://www.hoperf.com/upload/rf/RFM69HCW-V1.1.pdf
const (
// FXOSC is the radio's oscillator frequency in Hertz.
FXOSC = 32000000
// SPIWriteMode is used to encode register addresses for SPI writes.
SPIWriteMode = 1 << 7
)
// Common Configuration Registers
const (
RegFifo = 0x00 // FIFO read/write access
RegOpMode = 0x01 // Operating modes of the transceiver
RegDataModul = 0x02 // Data operation mode and Modulation settings
RegBitrateMsb = 0x03 // Bit Rate setting, Most Significant Bits
RegBitrateLsb = 0x04 // Bit Rate setting, Least Significant Bits
RegFdevMsb = 0x05 // Frequency Deviation setting, Most Significant Bits
RegFdevLsb = 0x06 // Frequency Deviation setting, Least Significant Bits
RegFrfMsb = 0x07 // RF Carrier Frequency, Most Significant Bits
RegFrfMid = 0x08 // RF Carrier Frequency, Intermediate Bits
RegFrfLsb = 0x09 // RF Carrier Frequency, Least Significant Bits
RegOsc1 = 0x0A // RF Oscillators Settings
RegAfcCtrl = 0x0B // AFC control in low modulation index situations
RegListen1 = 0x0D // Listen Mode settings
RegListen2 = 0x0E // Listen Mode Idle duration
RegListen3 = 0x0F // Listen Mode Rx duration
RegVersion = 0x10
)
// Transmitter Registers
const (
RegPaLevel = 0x11 // PA selection and Output Power control
RegPaRamp = 0x12 // Control of the PA ramp time in FSK mode
RegOcp = 0x13 // Over Current Protection control
)
// Receiver Registers
const (
RegLna = 0x18 // LNA settings
RegRxBw = 0x19 // Channel Filter BW Control
RegAfcBw = 0x1A // Channel Filter BW control during the AFC routine
RegOokPeak = 0x1B // OOK demodulator selection and control in peak mode
RegOokAvg = 0x1C // Average threshold control of the OOK demodulator
RegOokFix = 0x1D // Fixed threshold control of the OOK demodulator
RegAfcFei = 0x1E // AFC and FEI control and status
RegAfcMsb = 0x1F // MSB of the frequency correction of the AFC
RegAfcLsb = 0x20 // LSB of the frequency correction of the AFC
RegFeiMsb = 0x21 // MSB of the calculated frequency error
RegFeiLsb = 0x22 // LSB of the calculated frequency error
RegRssiConfig = 0x23 // RSSI-related settings
RegRssiValue = 0x24 // RSSI value in dBm
)
// IRQ and Pin Mapping Registers
const (
RegDioMapping1 = 0x25 // Mapping of pins DIO0 to DIO3
RegDioMapping2 = 0x26 // Mapping of pins DIO4 and DIO5, ClkOut frequency
RegIrqFlags1 = 0x27 // Status register: PLL Lock state, Timeout, RSSI > Threshold...
RegIrqFlags2 = 0x28 // Status register: FIFO handling flags...
RegRssiThresh = 0x29 // RSSI Threshold control
RegRxTimeout1 = 0x2A // Timeout duration between Rx request and RSSI detection
RegRxTimeout2 = 0x2B // Timeout duration between RSSI detection and PayloadReady
)
// Packet Engine Registers
const (
RegPreambleMsb = 0x2C // Preamble length, MSB
RegPreambleLsb = 0x2D // Preamble length, LSB
RegSyncConfig = 0x2E // Sync Word Recognition control
RegSyncValue1 = 0x2F // Sync Word bytes, 1 through 8
RegSyncValue2 = 0x30
RegSyncValue3 = 0x31
RegSyncValue4 = 0x32
RegSyncValue5 = 0x33
RegSyncValue6 = 0x34
RegSyncValue7 = 0x35
RegSyncValue8 = 0x36
RegPacketConfig1 = 0x37 // Packet mode settings
RegPayloadLength = 0x38 // Payload length setting
RegNodeAdrs = 0x39 // Node address
RegBroadcastAdrs = 0x3A // Broadcast address
RegAutoModes = 0x3B // Auto modes settings
RegFifoThresh = 0x3C // Fifo threshold, Tx start condition
RegPacketConfig2 = 0x3D // Packet mode settings
RegAesKey1 = 0x3E // 16 bytes of the cypher key
RegAesKey2 = 0x3F
RegAesKey3 = 0x40
RegAesKey4 = 0x41
RegAesKey5 = 0x42
RegAesKey6 = 0x43
RegAesKey7 = 0x44
RegAesKey8 = 0x45
RegAesKey9 = 0x46
RegAesKey10 = 0x47
RegAesKey11 = 0x48
RegAesKey12 = 0x49
RegAesKey13 = 0x4A
RegAesKey14 = 0x4B
RegAesKey15 = 0x4C
RegAesKey16 = 0x4D
)
// Temperature Sensor Registers
const (
RegTemp1 = 0x4E // Temperature Sensor control
RegTemp2 = 0x4F // Temperature readout
)
// Test Registers
const (
RegTest = 0x50 // Internal test registers
RegTestLna = 0x58 // Sensitivity boost
RegTestPa1 = 0x5A // High Power PA settings
RegTestPa2 = 0x5C // High Power PA settings
RegTestDagc = 0x6F // Fading Margin Improvement
RegTestAfc = 0x71 // AFC offset for low modulation index AFC
)
// Skip RegFifo to avoid burst mode access.
const ConfigurationStart = RegOpMode
// resetConfiguration contains the register values after reset,
// according to data sheet section 6.
var resetConfiguration = []byte{
RegOpMode: 0x04,
RegDataModul: 0x00,
RegBitrateMsb: 0x1A,
RegBitrateLsb: 0x0B,
RegFdevMsb: 0x00,
RegFdevLsb: 0x52,
RegFrfMsb: 0xE4,
RegFrfMid: 0xC0,
RegFrfLsb: 0x00,
RegOsc1: 0x41,
RegAfcCtrl: 0x40, // unused bits; disagrees with data sheet
0xC: 0x02, // reserved
RegListen1: 0x92,
RegListen2: 0xF5,
RegListen3: 0x20,
RegVersion: 0x24,
RegPaLevel: 0x9F,
RegPaRamp: 0x09,
RegOcp: 0x1A,
0x14: 0x40, // reserved
0x15: 0xB0, // reserved
0x16: 0x7B, // reserved
0x17: 0x9B, // reserved
RegLna: 0x08,
RegRxBw: 0x86,
RegAfcBw: 0x8A,
RegOokPeak: 0x40,
RegOokAvg: 0x80,
RegOokFix: 0x06,
RegAfcFei: 0x10,
RegAfcMsb: 0x00,
RegAfcLsb: 0x00,
RegFeiMsb: 0x00,
RegFeiLsb: 0x00,
RegRssiConfig: 0x02,
RegRssiValue: 0xFF,
RegDioMapping1: 0x00,
RegDioMapping2: 0x05,
RegIrqFlags1: 0x80,
RegIrqFlags2: 0x00,
RegRssiThresh: 0xFF,
RegRxTimeout1: 0x00,
RegRxTimeout2: 0x00,
RegPreambleMsb: 0x00,
RegPreambleLsb: 0x03,
RegSyncConfig: 0x98,
RegSyncValue1: 0x00,
RegSyncValue2: 0x00,
RegSyncValue3: 0x00,
RegSyncValue4: 0x00,
RegSyncValue5: 0x00,
RegSyncValue6: 0x00,
RegSyncValue7: 0x00,
RegSyncValue8: 0x00,
RegPacketConfig1: 0x10,
RegPayloadLength: 0x40,
RegNodeAdrs: 0x00,
RegBroadcastAdrs: 0x00,
RegAutoModes: 0x00,
RegFifoThresh: 0x0F,
RegPacketConfig2: 0x02,
RegAesKey1: 0x00,
RegAesKey2: 0x00,
RegAesKey3: 0x00,
RegAesKey4: 0x00,
RegAesKey5: 0x00,
RegAesKey6: 0x00,
RegAesKey7: 0x00,
RegAesKey8: 0x00,
RegAesKey9: 0x00,
RegAesKey10: 0x00,
RegAesKey11: 0x00,
RegAesKey12: 0x00,
RegAesKey13: 0x00,
RegAesKey14: 0x00,
RegAesKey15: 0x00,
RegAesKey16: 0x00,
RegTemp1: 0x01,
RegTemp2: 0x00,
// Omit test registers to avoid undefined behavior.
}
// ResetConfiguration returns a copy of the register values after reset.
func ResetConfiguration() []byte {
return resetConfiguration[:]
}
// defaultConfiguration contains the default (recommended) values,
// according to data sheet section 6.
var defaultConfiguration = []byte{
RegOpMode: 0x04,
RegDataModul: 0x00,
RegBitrateMsb: 0x1A,
RegBitrateLsb: 0x0B,
RegFdevMsb: 0x00,
RegFdevLsb: 0x52,
RegFrfMsb: 0xE4,
RegFrfMid: 0xC0,
RegFrfLsb: 0x00,
RegOsc1: 0x41,
RegAfcCtrl: 0x00,
0x0C: 0x02, // reserved
RegListen1: 0x92,
RegListen2: 0xF5,
RegListen3: 0x20,
RegVersion: 0x24,
RegPaLevel: 0x9F,
RegPaRamp: 0x09,
RegOcp: 0x1A,
0x14: 0x40, // reserved
0x15: 0xB0, // reserved
0x16: 0x7B, // reserved
0x17: 0x9B, // reserved
RegLna: 0x88,
RegRxBw: 0x55,
RegAfcBw: 0x8B,
RegOokPeak: 0x40,
RegOokAvg: 0x80,
RegOokFix: 0x06,
RegAfcFei: 0x10,
RegAfcMsb: 0x00,
RegAfcLsb: 0x00,
RegFeiMsb: 0x00,
RegFeiLsb: 0x00,
RegRssiConfig: 0x02,
RegRssiValue: 0xFF,
RegDioMapping1: 0x00,
RegDioMapping2: 0x07,
RegIrqFlags1: 0x80,
RegIrqFlags2: 0x00,
RegRssiThresh: 0xE4,
RegRxTimeout1: 0x00,
RegRxTimeout2: 0x00,
RegPreambleMsb: 0x00,
RegPreambleLsb: 0x03,
RegSyncConfig: 0x98,
RegSyncValue1: 0x01,
RegSyncValue2: 0x01,
RegSyncValue3: 0x01,
RegSyncValue4: 0x01,
RegSyncValue5: 0x01,
RegSyncValue6: 0x01,
RegSyncValue7: 0x01,
RegSyncValue8: 0x01,
RegPacketConfig1: 0x10,
RegPayloadLength: 0x40,
RegNodeAdrs: 0x00,
RegBroadcastAdrs: 0x00,
RegAutoModes: 0x00,
RegFifoThresh: 0x8F,
RegPacketConfig2: 0x02,
RegAesKey1: 0x00,
RegAesKey2: 0x00,
RegAesKey3: 0x00,
RegAesKey4: 0x00,
RegAesKey5: 0x00,
RegAesKey6: 0x00,
RegAesKey7: 0x00,
RegAesKey8: 0x00,
RegAesKey9: 0x00,
RegAesKey10: 0x00,
RegAesKey11: 0x00,
RegAesKey12: 0x00,
RegAesKey13: 0x00,
RegAesKey14: 0x00,
RegAesKey15: 0x00,
RegAesKey16: 0x00,
RegTemp1: 0x01,
RegTemp2: 0x00,
}
// DefaultConfiguration returns a copy of the default (recommended) values.
func DefaultConfiguration() []byte {
return defaultConfiguration[:]
}
// RegOpMode
const (
SequencerOff = 1 << 7
ListenOn = 1 << 6
ListenAbort = 1 << 5
ModeShift = 2
ModeMask = 7 << 2
SleepMode = 0 << 2
StandbyMode = 1 << 2
FreqSynthMode = 2 << 2
TransmitterMode = 3 << 2
ReceiverMode = 4 << 2
)
// RegDataModul
const (
PacketMode = 0 << 5
ContinuousModeWithBitSync = 2 << 5
ContinuousModeWithoutBitSync = 3 << 5
ModulationTypeMask = 3 << 3
ModulationTypeFSK = 0 << 3
ModulationTypeOOK = 1 << 3
ModulationShapingShift = 0
)
// RegOsc1
const (
RcCalStart = 1 << 7
RcCalDone = 1 << 6
)
// RegAfcCtrl
const (
AfcLowBetaOn = 1 << 5
)
// RegListen1
const (
ListenResolIdleShift = 6
ListenResolRxShift = 4
ListenCriteria = 1 << 3
ListenEndShift = 1
)
// RegPaLevel
// See http://blog.andrehessling.de/2015/02/07/figuring-out-the-power-level-settings-of-hoperfs-rfm69-hwhcw-modules/
const (
Pa0On = 1 << 7
Pa1On = 1 << 6
Pa2On = 1 << 5
OutputPowerShift = 0
)
// RegOcp
const (
OcpOn = 1 << 4
OcpTrimShift = 0
)
// RegLna
const (
LnaZin = 1 << 7
LnaCurrentGainShift = 3
LnaGainSelectShift = 0
)
// RegRxBw
const (
DccFreqShift = 5
DccFreqMask = 7 << 5
RxBwMantShift = 3
RxBwMantMask = 3 << 3
RxBwMant16 = 0 << 3
RxBwMant20 = 1 << 3
RxBwMant24 = 2 << 3
RxBwExpShift = 0
RxBwExpMask = 7 << 0
)
// RegOokPeak
const (
OokThreshTypeShift = 6
OokPeakThreshStepShift = 3
OokPeakThreshDecShift = 0
)
// RegOokAvg
const (
OokAverageThreshFiltShift = 6
)
// RegAfcFei
const (
FeiDone = 1 << 6
FeiStart = 1 << 5
AfcDone = 1 << 4
AfcAutoclearOn = 1 << 3
AfcAutoOn = 1 << 2
AfcClear = 1 << 1
AfcStart = 1 << 0
)
// RegRssiConfig
const (
RssiDone = 1 << 1
RssiStart = 1 << 0
)
// RegDioMapping1
const (
Dio0MappingShift = 6
Dio1MappingShift = 4
Dio2MappingShift = 2
Dio3MappingShift = 0
)
// RegDioMapping2
const (
Dio4MappingShift = 6
Dio5MappingShift = 4
ClkOutShift = 0
)
// RegIrqFlags1
const (
ModeReady = 1 << 7
RxReady = 1 << 6
TxReady = 1 << 5
PllLock = 1 << 4
Rssi = 1 << 3
Timeout = 1 << 2
AutoMode = 1 << 1
SyncAddressMatch = 1 << 0
)
// RegIrqFlags2
const (
FifoFull = 1 << 7
FifoNotEmpty = 1 << 6
FifoLevel = 1 << 5
FifoOverrun = 1 << 4
PacketSent = 1 << 3
PayloadReady = 1 << 2
CrcOk = 1 << 1
)
// RegSyncConfig
const (
SyncOn = 1 << 7
FifoFillCondition = 1 << 6
SyncSizeShift = 3
SyncTolShift = 0
)
// RegPacketConfig1
const (
FixedLength = 0 << 7
VariableLength = 1 << 7
DcFreeShift = 5
CrcOn = 1 << 4
CrcOff = 0 << 4
CrcAutoClearOff = 1 << 3
AddressFilteringShift = 1
)
// RegAutoModes
const (
EnterConditionShift = 5
EnterConditionNone = 0 << 5
EnterConditionFifoNotEmpty = 1 << 5
EnterConditionFifoLevel = 2 << 5
EnterConditionCrcOk = 3 << 5
EnterConditionPayloadReady = 4 << 5
EnterConditionSyncAddress = 5 << 5
EnterConditionPacketSent = 6 << 5
EnterConditionFifoEmpty = 7 << 5
ExitConditionShift = 2
ExitConditionNone = 0 << 2
ExitConditionFifoEmpty = 1 << 2
ExitConditionFifoLevel = 2 << 2
ExitConditionCrcOk = 3 << 2
ExitConditionPayloadReady = 4 << 2
ExitConditionSyncAddress = 5 << 2
ExitConditionPacketSent = 6 << 2
ExitConditionTimeout = 7 << 2
IntermediateModeShift = 0
IntermediateModeSleep = 0 << 0
IntermediateModeStandby = 1 << 0
IntermediateModeRx = 2 << 0
IntermediateModeTx = 3 << 0
)
// RegFifoThresh
const (
TxStartFifoNotEmpty = 1 << 7
TxStartFifoLevel = 0 << 7
FifoThresholdShift = 0
)
// RegPacketConfig2
const (
InterPacketRxDelayShift = 4
RestartRx = 1 << 2
AutoRxRestartOn = 1 << 1
AutoRxRestartOff = 0 << 1
AesOn = 1 << 0
)
// RegTemp1
const (
TempMeasStart = 1 << 3
TempMeasRunning = 1 << 2
) | rfm69.go | 0.500488 | 0.513059 | rfm69.go | starcoder |
package num
import (
"math"
"github.com/cpmech/gosl/chk"
"github.com/cpmech/gosl/fun"
"github.com/cpmech/gosl/io"
"github.com/cpmech/gosl/la"
"github.com/cpmech/gosl/utl"
)
// NlSolver implements a solver to nonlinear systems of equations
// References:
// [1] G.Forsythe, M.Malcolm, C.Moler, Computer methods for mathematical
// computations. M., Mir, 1980, p.180 of the Russian edition
type NlSolver struct {
// constants
cteJac bool // constant Jacobian (Modified Newton's method)
linSearch bool // use linear search
linSchMaxIt int // line search maximum iterations
maxIt int // Newton's method maximum iterations
chkConv bool // check convergence
atol float64 // absolute tolerance
rtol float64 // relative tolerance
ftol float64 // minimum value of fx
fnewt float64 // [derived] Newton's method tolerance
// auxiliary data
neq int // number of equations
scal la.Vector // scaling vector
fx la.Vector // f(x)
mdx la.Vector // - delta x
useDn bool // use dense solver (matrix inversion) instead of Umfpack (sparse)
numJ bool // use numerical Jacobian (with sparse solver)
// callbacks
Ffcn fun.Vv // f(x) function f:vector, x:vector
JfcnSp fun.Tv // J(x)=dfdx Jacobian for sparse solver
JfcnDn fun.Mv // J(x)=dfdx Jacobian for dense solver
// output callback
Out func(x []float64) // output callback function
// data for Umfpack (sparse)
Jtri la.Triplet // triplet
w la.Vector // workspace
lis la.Umfpack // linear solver
lsReady bool // linear solver is lsReady
// data for dense solver (matrix inversion)
J *la.Matrix // dense Jacobian matrix
Ji *la.Matrix // inverse of Jacobian matrix
// data for line-search
φ float64
dφdx la.Vector
x0 la.Vector
// stat data
It int // number of iterations from the last call to Solve
NFeval int // number of calls to Ffcn (function evaluations)
NJeval int // number of calls to Jfcn (Jacobian evaluations)
}
// Init initialises solver
// Input:
// useSp -- Use sparse solver with JfcnSp
// useDn -- Use dense solver (matrix inversion) with JfcnDn
// numJ -- Use numeric Jacobian (sparse version only)
// prms -- control parameters (default values)
// "cteJac" = -1 [false] constant Jacobian (Modified Newton's method)
// "linSearch" = -1 [false] use linear search
// "linSchMaxIt" = 20 linear solver maximum iterations
// "maxIt" = 20 Newton's method maximum iterations
// "chkConv" = -1 [false] check convergence
// "atol" = 1e-8 absolute tolerance
// "rtol" = 1e-8 relative tolerance
// "ftol" = 1e-9 minimum value of fx
func (o *NlSolver) Init(neq int, Ffcn fun.Vv, JfcnSp fun.Tv, JfcnDn fun.Mv, useDn, numJ bool, prms map[string]float64) {
// set default values
o.cteJac = false
o.linSearch = false
o.linSchMaxIt = 20
o.maxIt = 20
o.chkConv = false
atol := 1e-8
rtol := 1e-8
ftol := 1e-9
// read parameters
for k, v := range prms {
switch k {
case "cteJac":
o.cteJac = v > 0
case "linSearch":
o.linSearch = v > 0
case "linSchMaxIt":
o.linSchMaxIt = int(v)
case "maxIt":
o.maxIt = int(v)
case "chkConv":
o.chkConv = v > 0
case "atol":
atol = v
case "rtol":
rtol = v
case "ftol":
ftol = v
default:
chk.Panic("parameter named %q is invalid\n", k)
}
}
// set tolerances
o.SetTols(atol, rtol, ftol, MACHEPS)
// auxiliary data
o.neq = neq
o.scal = la.NewVector(o.neq)
o.fx = la.NewVector(o.neq)
o.mdx = la.NewVector(o.neq)
// callbacks
o.Ffcn, o.JfcnSp, o.JfcnDn = Ffcn, JfcnSp, JfcnDn
// type of linear solver and Jacobian matrix (numerical or analytical: sparse only)
o.useDn, o.numJ = useDn, numJ
// use dense linear solver
if o.useDn {
o.J = la.NewMatrix(o.neq, o.neq)
o.Ji = la.NewMatrix(o.neq, o.neq)
// use sparse linear solver
} else {
o.Jtri.Init(o.neq, o.neq, o.neq*o.neq)
if JfcnSp == nil {
o.numJ = true
}
if o.numJ {
o.w = la.NewVector(o.neq)
}
}
// allocate slices for line search
o.dφdx = la.NewVector(o.neq)
o.x0 = la.NewVector(o.neq)
}
// Free frees memory
func (o *NlSolver) Free() {
if !o.useDn {
o.lis.Free()
}
}
// SetTols set tolerances
func (o *NlSolver) SetTols(Atol, Rtol, Ftol, ϵ float64) {
o.atol, o.rtol, o.ftol = Atol, Rtol, Ftol
o.fnewt = utl.Max(10.0*ϵ/Rtol, utl.Min(0.03, math.Sqrt(Rtol)))
}
// Solve solves non-linear problem f(x) == 0
func (o *NlSolver) Solve(x []float64, silent bool) {
// compute scaling vector
la.VecScaleAbs(o.scal, o.atol, o.rtol, x) // scal = Atol + Rtol*abs(x)
// evaluate function @ x
o.Ffcn(o.fx, x) // fx := f(x)
o.NFeval, o.NJeval = 1, 0
// show message
if !silent {
o.msg("", 0, 0, 0, true, false)
}
// iterations
var Ldx, LdxPrev, Θ float64 // RMS norm of delta x, convergence rate
var fxMax float64
var nfv int
for o.It = 0; o.It < o.maxIt; o.It++ {
// check convergence on f(x)
fxMax = o.fx.Largest(1.0) // den = 1.0
if fxMax < o.ftol {
if !silent {
o.msg("fxMax(ini)", o.It, Ldx, fxMax, false, true)
}
break
}
// show message
if !silent {
o.msg("", o.It, Ldx, fxMax, false, false)
}
// output
if o.Out != nil {
o.Out(x)
}
// evaluate Jacobian @ x
if o.It == 0 || !o.cteJac {
if o.useDn {
o.JfcnDn(o.J, x)
} else {
if o.numJ {
Jacobian(&o.Jtri, o.Ffcn, x, o.fx, o.w)
o.NFeval += o.neq
} else {
o.JfcnSp(&o.Jtri, x)
}
}
o.NJeval++
}
// dense solution
if o.useDn {
// invert matrix
la.MatInv(o.Ji, o.J, false)
// solve linear system (compute mdx) and compute lin-search data
o.φ = 0.0
for i := 0; i < o.neq; i++ {
o.mdx[i], o.dφdx[i] = 0.0, 0.0
for j := 0; j < o.neq; j++ {
o.mdx[i] += o.Ji.Get(i, j) * o.fx[j] // mdx = inv(J) * fx
o.dφdx[i] += o.J.Get(j, i) * o.fx[j] // dφdx = tra(J) * fx
}
o.φ += o.fx[i] * o.fx[i]
}
o.φ *= 0.5
// sparse solution
} else {
// init sparse solver
if !o.lsReady {
symmetric, verbose := false, false
o.lis.Init(&o.Jtri, &la.SpArgs{Symmetric: symmetric, Verbose: verbose, Ordering: "", Scaling: "", Guess: nil, Communicator: nil})
o.lsReady = true
}
// factorisation (must be done for all iterations)
o.lis.Fact()
// solve linear system => compute mdx
o.lis.Solve(o.mdx, o.fx, false) // mdx = inv(J) * fx false => !sumToRoot
// compute lin-search data
if o.linSearch {
o.φ = 0.5 * la.VecDot(o.fx, o.fx)
la.SpTriMatTrVecMul(o.dφdx, &o.Jtri, o.fx) // dφdx := transpose(J) * fx
}
}
// update x
Ldx = 0.0
for i := 0; i < o.neq; i++ {
o.x0[i] = x[i]
x[i] -= o.mdx[i]
Ldx += (o.mdx[i] / o.scal[i]) * (o.mdx[i] / o.scal[i])
}
Ldx = math.Sqrt(Ldx / float64(o.neq))
// calculate fx := f(x) @ update x
o.Ffcn(o.fx, x)
o.NFeval++
// check convergence on f(x) => avoid line-search if converged already
fxMax = o.fx.Largest(1.0) // den = 1.0
if fxMax < o.ftol {
if !silent {
o.msg("fxMax", o.It, Ldx, fxMax, false, true)
}
break
}
// check convergence on Ldx
if Ldx < o.fnewt {
if !silent {
o.msg("Ldx", o.It, Ldx, fxMax, false, true)
}
break
}
// call line-search => update x and fx
if o.linSearch {
nfv = LineSearch(x, o.fx, o.Ffcn, o.mdx, o.x0, o.dφdx, o.φ, o.linSchMaxIt, true)
o.NFeval += nfv
Ldx = 0.0
for i := 0; i < o.neq; i++ {
Ldx += ((x[i] - o.x0[i]) / o.scal[i]) * ((x[i] - o.x0[i]) / o.scal[i])
}
Ldx = math.Sqrt(Ldx / float64(o.neq))
fxMax = o.fx.Largest(1.0) // den = 1.0
if Ldx < o.fnewt {
if !silent {
o.msg("Ldx(linsrch)", o.It, Ldx, fxMax, false, true)
}
break
}
}
// check convergence rate
if o.It > 0 && o.chkConv {
Θ = Ldx / LdxPrev
if Θ > 0.99 {
chk.Panic("solver is diverging with Θ = %g (Ldx=%g, LdxPrev=%g)", Θ, Ldx, LdxPrev)
}
}
LdxPrev = Ldx
}
// output
if o.Out != nil {
o.Out(x)
}
// check convergence
if o.It == o.maxIt {
chk.Panic("cannot converge after %d iterations", o.It)
}
return
}
// CheckJ check Jacobian matrix
// Ouptut: cnd -- condition number (with Frobenius norm)
func (o *NlSolver) CheckJ(x []float64, tol float64, chkJnum, silent bool) (cnd float64) {
// Jacobian matrix
var Jmat *la.Matrix
if o.useDn {
Jmat = la.NewMatrix(o.neq, o.neq)
o.JfcnDn(Jmat, x)
} else {
if o.numJ {
Jacobian(&o.Jtri, o.Ffcn, x, o.fx, o.w)
} else {
o.JfcnSp(&o.Jtri, x)
}
Jmat = o.Jtri.ToDense()
}
// condition number
cnd = la.MatCondNum(Jmat, "F")
if math.IsInf(cnd, 0) || math.IsNaN(cnd) {
chk.Panic("condition number is Inf or NaN: %v", cnd)
}
// numerical Jacobian
if !chkJnum {
return
}
var Jtmp la.Triplet
ws := la.NewVector(o.neq)
o.Ffcn(o.fx, x)
Jtmp.Init(o.neq, o.neq, o.neq*o.neq)
Jacobian(&Jtmp, o.Ffcn, x, o.fx, ws)
Jnum := Jtmp.ToMatrix(nil).ToDense()
for i := 0; i < o.neq; i++ {
for j := 0; j < o.neq; j++ {
chk.PrintAnaNum(io.Sf("J[%d][%d]", i, j), tol, Jmat.Get(i, j), Jnum.Get(i, j), !silent)
}
}
maxdiff := Jmat.MaxDiff(Jnum)
if maxdiff > tol {
chk.Panic("maxdiff = %g\n", maxdiff)
}
return
}
// msg prints information on residuals
func (o *NlSolver) msg(typ string, it int, Ldx, fxMax float64, first, last bool) {
if first {
io.Pf("\n%4s%23s%23s\n", "it", "Ldx", "fxMax")
io.Pf("%4s%23s%23s\n", "", io.Sf("(%7.1e)", o.fnewt), io.Sf("(%7.1e)", o.ftol))
return
}
io.Pf("%4d%23.15e%23.15e\n", it, Ldx, fxMax)
if last {
io.Pf(". . . converged with %s. nit=%d, nFeval=%d, nJeval=%d\n", typ, it, o.NFeval, o.NJeval)
}
} | num/nlsolver.go | 0.622115 | 0.523968 | nlsolver.go | starcoder |
package birnn
import (
"encoding/gob"
"sync"
"github.com/nlpodyssey/spago/ag"
"github.com/nlpodyssey/spago/mat"
"github.com/nlpodyssey/spago/nn"
)
// MergeType is the enumeration-like type used for the set of merging methods
// which a BiRNN model Processor can perform.
type MergeType int
const (
// Concat merging method: the outputs are concatenated together (the default)
Concat MergeType = iota
// Sum merging method: the outputs are added together
Sum
// Prod merging method: the outputs multiplied element-wise together
Prod
// Avg merging method: the average of the outputs is taken
Avg
)
var _ nn.Model[float32] = &Model[float32]{}
// Model contains the serializable parameters.
type Model[T mat.DType] struct {
nn.BaseModel[T]
Positive nn.StandardModel[T] // positive time direction a.k.a. left-to-right
Negative nn.StandardModel[T] // negative time direction a.k.a. right-to-left
MergeMode MergeType
}
func init() {
gob.Register(&Model[float32]{})
gob.Register(&Model[float64]{})
}
// New returns a new model with parameters initialized to zeros.
func New[T mat.DType](positive, negative nn.StandardModel[T], merge MergeType) *Model[T] {
return &Model[T]{
Positive: positive,
Negative: negative,
MergeMode: merge,
}
}
// Forward performs the forward step for each input node and returns the result.
func (m *Model[T]) Forward(xs ...ag.Node[T]) []ag.Node[T] {
var pos []ag.Node[T]
var neg []ag.Node[T]
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
pos = m.Positive.Forward(xs...)
}()
go func() {
defer wg.Done()
neg = m.Negative.Forward(reversed(xs)...)
}()
wg.Wait()
out := make([]ag.Node[T], len(pos))
for i := range out {
out[i] = m.merge(pos[i], neg[len(out)-1-i])
}
return out
}
func reversed[T mat.DType](ns []ag.Node[T]) []ag.Node[T] {
r := make([]ag.Node[T], len(ns))
copy(r, ns)
for i := 0; i < len(r)/2; i++ {
j := len(r) - i - 1
r[i], r[j] = r[j], r[i]
}
return r
}
func (m *Model[T]) merge(a, b ag.Node[T]) ag.Node[T] {
switch m.MergeMode {
case Concat:
return ag.Concat(a, b)
case Sum:
return ag.Add(a, b)
case Prod:
return ag.Prod(a, b)
case Avg:
return ag.ProdScalar(ag.Add(a, b), ag.Constant[T](0.5))
default:
panic("birnn: invalid merge mode")
}
} | nn/birnn/birnn.go | 0.639286 | 0.50116 | birnn.go | starcoder |
package ivg
import (
"image/color"
)
const Magic = "\x89IVG"
var MagicBytes = []byte(Magic)
const (
MidViewBox = 0
MidSuggestedPalette = 1
)
const (
// Min aligns min of ViewBox with min of rect
Min = 0.0
// Mid aligns mid of ViewBox with mid of rect
Mid = 0.5
// Max aligns max of ViewBox with max of rect
Max = 1.0
)
// ViewBox is a Rectangle
type ViewBox struct {
MinX, MinY, MaxX, MaxY float32
}
// Size returns the ViewBox's size in both dimensions. An IconVG graphic is
// scalable; these dimensions do not necessarily map 1:1 to pixels.
func (v ViewBox) Size() (dx, dy float32) {
return v.MaxX - v.MinX, v.MaxY - v.MinY
}
// AspectMeet fits the ViewBox inside the rect maintaining its aspect ratio.
// The ax, ay argument determine the position of the resized viewbox in the
// given rect. For example ax = Mid, ay = Mid will position the resized
// viewbox always in the middle of the rect
func (v ViewBox) AspectMeet(minX, minY, maxX, maxY float32, ax, ay float32) (MinX, MinY, MaxX, MaxY float32) {
rdx, rdy := maxX-minX, maxY-minY
vdx, vdy := v.Size()
vbAR := vdx / vdy
vdx, vdy = rdx, rdy
if vdx/vdy < vbAR {
vdy = vdx / vbAR
} else {
vdx = vdy * vbAR
}
minX += (rdx - vdx) * ax
maxX = minX + vdx
minY += (rdy - vdy) * ay
maxY = minY + vdy
return minX, minY, maxX, maxY
}
// AspectSlice fills the rect maintaining the ViewBox's aspect ratio. The ax,
// ay argument determine the position of the resized viewbox in the given
// rect. For example ax = Mid, ay = Mid will position the resized viewbox
// always in the middle of the rect
func (v ViewBox) AspectSlice(minX, minY, maxX, maxY float32, ax, ay float32) (MinX, MinY, MaxX, MaxY float32) {
rdx, rdy := maxX-minX, maxY-minY
vdx, vdy := v.Size()
vbAR := vdx / vdy
vdx, vdy = rdx, rdy
if vdx/vdy < vbAR {
vdx = vdy * vbAR
} else {
vdy = vdx / vbAR
}
minX += (rdx - vdx) * ax
maxX = minX + vdx
minY += (rdy - vdy) * ay
maxY = minY + vdy
return minX, minY, maxX, maxY
}
// Metadata is an IconVG's metadata.
type Metadata struct {
ViewBox ViewBox
// Palette is a 64 color palette. When encoding, it is the suggested
// palette to place within the IconVG graphic. When decoding, it is either
// the optional palette passed to Decode, or if no optional palette was
// given, the suggested palette within the IconVG graphic.
Palette [64]color.RGBA
}
// DefaultViewBox is the default ViewBox. Its values should not be modified.
var DefaultViewBox = ViewBox{
MinX: -32, MinY: -32,
MaxX: +32, MaxY: +32,
}
// DefaultPalette is the default Palette. Its values should not be modified.
var DefaultPalette = [64]color.RGBA{
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
{0x00, 0x00, 0x00, 0xff},
}
// DefaultMetadata combines the default ViewBox and the default Palette.
var DefaultMetadata = Metadata{
ViewBox: DefaultViewBox,
Palette: DefaultPalette,
}
// Icon is an interface to an icon tha tcan be drawn on a Destination
type Icon interface {
// Name is a unique name of the icon inside your program. e.g. "favicon"
// It is used to differentiate it from other icons in your program.
Name() string
// RenderOn is called to let the icon render itself on
// a Destination with a list of color.RGBA overrides.
RenderOn(dst Destination, col ...color.RGBA) error
} | ivg.go | 0.710929 | 0.450722 | ivg.go | starcoder |
package bmath
import (
"github.com/go-gl/mathgl/mgl32"
"github.com/wieku/danser-go/settings"
)
type Rectangle struct {
MinX, MinY, MaxX, MaxY float64
}
type Camera struct {
screenRect Rectangle
projection mgl32.Mat4
view mgl32.Mat4
projectionView mgl32.Mat4
invProjectionView mgl32.Mat4
viewDirty bool
origin Vector2d
position Vector2d
rotation float64
scale Vector2d
rebuildCache bool
cache []mgl32.Mat4
}
func NewCamera() *Camera {
return &Camera{scale: NewVec2d(1, 1)}
}
func (camera *Camera) SetViewport(width, height int, yDown bool) {
camera.screenRect.MinX = -float64(width) / 2
camera.screenRect.MaxX = float64(width) / 2
if yDown {
camera.screenRect.MinY = float64(height) / 2
camera.screenRect.MaxY = -float64(height) / 2
} else {
camera.screenRect.MinY = -float64(height) / 2
camera.screenRect.MaxY = float64(height) / 2
}
if yDown {
camera.projection = mgl32.Ortho(float32(camera.screenRect.MinX), float32(camera.screenRect.MaxX), float32(camera.screenRect.MinY), float32(camera.screenRect.MaxY), 1, -1)
} else {
camera.projection = mgl32.Ortho(float32(camera.screenRect.MinX), float32(camera.screenRect.MaxX), float32(camera.screenRect.MinY), float32(camera.screenRect.MaxY), -1, 1)
}
camera.rebuildCache = true
camera.viewDirty = true
}
func (camera *Camera) SetOsuViewport(width, height int, scale float64) {
scl := (float64(height) * 900.0 / 1080.0) / 384.0 * scale
if 512.0/384.0 > float64(width)/float64(height) {
scl = (float64(width) * 900.0 / 1080.0) / 512.0 * scale
}
camera.SetViewport(int(settings.Graphics.GetWidth()), int(settings.Graphics.GetHeight()), true)
camera.SetOrigin(NewVec2d(512.0/2, 384.0/2))
camera.SetScale(NewVec2d(scl, scl))
camera.Update()
camera.rebuildCache = true
camera.viewDirty = true
}
func (camera *Camera) SetViewportF(x, y, width, height int) {
camera.screenRect.MinX = float64(x)
camera.screenRect.MaxX = float64(width)
camera.screenRect.MinY = float64(y)
camera.screenRect.MaxY = float64(height)
camera.projection = mgl32.Ortho(float32(camera.screenRect.MinX), float32(camera.screenRect.MaxX), float32(camera.screenRect.MinY), float32(camera.screenRect.MaxY), 1, -1)
camera.rebuildCache = true
camera.viewDirty = true
}
func (camera *Camera) calculateView() {
camera.view = mgl32.Translate3D(camera.position.X32(), camera.position.Y32(), 0).Mul4(mgl32.HomogRotate3DZ(float32(camera.rotation))).Mul4(mgl32.Scale3D(camera.scale.X32(), camera.scale.Y32(), 1)).Mul4(mgl32.Translate3D(camera.origin.X32(), camera.origin.Y32(), 0))
}
func (camera *Camera) SetPosition(pos Vector2d) {
camera.position = pos
camera.viewDirty = true
}
func (camera *Camera) SetOrigin(pos Vector2d) {
camera.origin = pos.Scl(-1)
camera.viewDirty = true
}
func (camera *Camera) SetScale(scale Vector2d) {
camera.scale = scale
camera.viewDirty = true
}
func (camera *Camera) SetRotation(rad float64) {
camera.rotation = rad
camera.viewDirty = true
}
func (camera *Camera) Rotate(rad float64) {
camera.rotation += rad
camera.viewDirty = true
}
func (camera *Camera) Translate(pos Vector2d) {
camera.position = camera.position.Add(pos)
camera.viewDirty = true
}
func (camera *Camera) Scale(scale Vector2d) {
camera.scale = camera.scale.Mult(scale)
camera.viewDirty = true
}
func (camera *Camera) Update() {
if camera.viewDirty {
camera.calculateView()
camera.projectionView = camera.projection.Mul4(camera.view)
camera.invProjectionView = camera.projectionView.Inv()
camera.rebuildCache = true
camera.viewDirty = false
}
}
func (camera *Camera) GenRotated(rotations int, rotOffset float64) []mgl32.Mat4 {
if len(camera.cache) != rotations || camera.rebuildCache {
if len(camera.cache) != rotations {
camera.cache = make([]mgl32.Mat4, rotations)
}
for i := 0; i < rotations; i++ {
camera.cache[i] = camera.projection.Mul4(mgl32.HomogRotate3DZ(float32(i) * float32(rotOffset))).Mul4(camera.view)
}
camera.rebuildCache = false
}
return camera.cache
}
func (camera Camera) GetProjectionView() mgl32.Mat4 {
return camera.projectionView
}
func (camera Camera) Unproject(screenPos Vector2d) Vector2d {
res := camera.invProjectionView.Mul4x1(mgl32.Vec4{float32((screenPos.X + camera.screenRect.MinX) / camera.screenRect.MaxX), -float32((screenPos.Y + camera.screenRect.MaxY) / camera.screenRect.MinY), 0.0, 1.0})
return NewVec2d(float64(res[0]), float64(res[1]))
}
func (camera Camera) GetWorldRect() Rectangle {
res := camera.invProjectionView.Mul4x1(mgl32.Vec4{-1.0, 1.0, 0.0, 1.0})
var rectangle Rectangle
rectangle.MinX = float64(res[0])
rectangle.MinY = float64(res[1])
res = camera.invProjectionView.Mul4x1(mgl32.Vec4{1.0, -1.0, 0.0, 1.0})
rectangle.MaxX = float64(res[0])
rectangle.MaxY = float64(res[1])
if rectangle.MinY > rectangle.MaxY {
a := rectangle.MinY
rectangle.MinY, rectangle.MaxY = rectangle.MaxY, a
}
return rectangle
} | bmath/camera.go | 0.800419 | 0.582194 | camera.go | starcoder |
package effect
import (
"korok.io/korok/math/f32"
"korok.io/korok/gfx"
"korok.io/korok/math"
)
// FireSimulator can simulate the fire effect.
type FountainSimulator struct {
Pool
RateController
LifeController
VisualController
velocity Channel_v2
deltaColor Channel_v4
deltaRot Channel_f32
// Configuration.
Config struct{
Duration, Rate float32
Life Var
Size Var
Color TwoColor
Fading bool
Position [2]Var
Angle Var
Speed Var
Gravity float32
Rotation Var
Additive bool
}
}
func NewFountainSimulator(cap int) *FountainSimulator {
sim := FountainSimulator{Pool: Pool{Cap: cap}}
sim.AddChan(Life, Size)
sim.AddChan(Position, Velocity)
sim.AddChan(Color, ColorDelta)
sim.AddChan(Rotation, RotationDelta)
// config
sim.Config.Duration = math.MaxFloat32
sim.Config.Rate = float32(cap)/3
sim.Config.Life = Var{3, .25}
sim.Config.Color = TwoColor{f32.Vec4{1, 1, 1, 1}, f32.Vec4{1, 1, 1, 1}, false}
sim.Config.Fading = false
sim.Config.Size = Var{8, 2}
sim.Config.Angle = Var{3.14/2, 3.14/3}
sim.Config.Speed = Var{120, 20}
sim.Config.Rotation = Var{0, 1}
sim.Config.Gravity = -120
return &sim
}
func (f *FountainSimulator) Initialize() {
f.Pool.Initialize()
f.Life = f.Field(Life).(Channel_f32)
f.ParticleSize = f.Field(Size).(Channel_f32)
f.Position = f.Field(Position).(Channel_v2)
f.velocity = f.Field(Velocity).(Channel_v2)
f.Color = f.Field(Color).(Channel_v4)
f.deltaColor = f.Field(ColorDelta).(Channel_v4)
f.Rotation = f.Field(Rotation).(Channel_f32)
f.deltaRot = f.Field(RotationDelta).(Channel_f32)
f.RateController.Initialize(f.Config.Duration, f.Config.Rate)
}
func (f *FountainSimulator) Simulate(dt float32) {
// spawn new particle
if new := f.Rate(dt); new > 0 {
f.newParticle(new)
}
n := int32(f.Live)
// update old particle
f.Life.Sub(n, dt)
// position integrate: p' = p + v * t
f.Position.Integrate(n, f.velocity, dt)
// v' = v + g * t
f.velocity.Add(n, 0, f.Config.Gravity*dt)
// spin
f.Rotation.Integrate(n, f.deltaRot, dt)
// Color
f.Color.Integrate(n, f.deltaColor, dt)
// GC
f.GC(&f.Pool)
}
func (f *FountainSimulator) Size() (live, cap int) {
return int(f.Live), f.Cap
}
func (f *FountainSimulator) newParticle(new int) {
if (f.Live + new) > f.Cap {
return
}
start := f.Live
f.Live += new
for i := start; i < f.Live; i++ {
f.Life[i] = f.Config.Life.Random()
f.ParticleSize[i] = f.Config.Size.Random()
startColor := f.Config.Color.Random()
f.Color[i] = startColor
if f.Config.Fading {
invLife := 1/f.Life[i]
f.deltaColor[i] = f32.Vec4{
-startColor[0] * invLife,
-startColor[1] * invLife,
-startColor[2] * invLife,
-startColor[2] * invLife,
}
}
px := f.Config.Position[0].Random()
py := f.Config.Position[1].Random()
f.Position[i] = f32.Vec2{px, py}
a := f.Config.Angle.Random()
s := f.Config.Speed.Random()
f.velocity[i] = f32.Vec2{math.Cos(a)*s, math.Sin(a)*s}
r := f.Config.Rotation.Random()
f.deltaRot[i] = r
}
}
func (f *FountainSimulator) Visualize(buf []gfx.PosTexColorVertex, tex gfx.Tex2D) {
f.VisualController.Visualize(buf, tex, f.Live, f.Config.Additive)
} | effect/sim_fountain.go | 0.714628 | 0.404272 | sim_fountain.go | starcoder |
package model
// ColumnType describes the possible types that a column may take
type ColumnType int
// List of possible ColumnType values
const (
ColumnTypeInvalid ColumnType = iota
ColumnTypeBit
ColumnTypeTinyInt
ColumnTypeSmallInt
ColumnTypeMediumInt
ColumnTypeInt
ColumnTypeInteger
ColumnTypeBigInt
ColumnTypeReal
ColumnTypeDouble
ColumnTypeFloat
ColumnTypeDecimal
ColumnTypeNumeric
ColumnTypeDate
ColumnTypeTime
ColumnTypeTimestamp
ColumnTypeDateTime
ColumnTypeYear
ColumnTypeChar
ColumnTypeVarChar
ColumnTypeBinary
ColumnTypeVarBinary
ColumnTypeTinyBlob
ColumnTypeBlob
ColumnTypeMediumBlob
ColumnTypeLongBlob
ColumnTypeTinyText
ColumnTypeText
ColumnTypeMediumText
ColumnTypeLongText
ColumnTypeEnum
ColumnTypeSet
ColumnTypeBoolean
ColumnTypeBool
ColumnTypeJSON
ColumnTypeGEOMETRY
ColumnTypeMax
)
func (c ColumnType) String() string {
switch c {
case ColumnTypeBit:
return "BIT"
case ColumnTypeTinyInt:
return "TINYINT"
case ColumnTypeSmallInt:
return "SMALLINT"
case ColumnTypeMediumInt:
return "MEDIUMINT"
case ColumnTypeInt:
return "INT"
case ColumnTypeInteger:
return "INTEGER"
case ColumnTypeBigInt:
return "BIGINT"
case ColumnTypeReal:
return "REAL"
case ColumnTypeDouble:
return "DOUBLE"
case ColumnTypeFloat:
return "FLOAT"
case ColumnTypeDecimal:
return "DECIMAL"
case ColumnTypeNumeric:
return "NUMERIC"
case ColumnTypeDate:
return "DATE"
case ColumnTypeTime:
return "TIME"
case ColumnTypeTimestamp:
return "TIMESTAMP"
case ColumnTypeDateTime:
return "DATETIME"
case ColumnTypeYear:
return "YEAR"
case ColumnTypeChar:
return "CHAR"
case ColumnTypeVarChar:
return "VARCHAR"
case ColumnTypeBinary:
return "BINARY"
case ColumnTypeVarBinary:
return "VARBINARY"
case ColumnTypeTinyBlob:
return "TINYBLOB"
case ColumnTypeBlob:
return "BLOB"
case ColumnTypeMediumBlob:
return "MEDIUMBLOB"
case ColumnTypeLongBlob:
return "LONGBLOB"
case ColumnTypeTinyText:
return "TINYTEXT"
case ColumnTypeText:
return "TEXT"
case ColumnTypeMediumText:
return "MEDIUMTEXT"
case ColumnTypeLongText:
return "LONGTEXT"
case ColumnTypeEnum:
return "ENUM"
case ColumnTypeSet:
return "SET"
case ColumnTypeBoolean:
return "BOOLEAN"
case ColumnTypeBool:
return "BOOL"
case ColumnTypeJSON:
return "JSON"
case ColumnTypeGEOMETRY:
return "GEOMETRY"
default:
return "(invalid)"
}
}
// SynonymType returns synonym for a given type.
// If the type does not have a synonym then this method returns the receiver itself
func (c ColumnType) SynonymType() ColumnType {
switch c {
case ColumnTypeBool:
return ColumnTypeTinyInt
case ColumnTypeBoolean:
return ColumnTypeTinyInt
case ColumnTypeInteger:
return ColumnTypeInt
case ColumnTypeNumeric:
return ColumnTypeDecimal
case ColumnTypeReal:
return ColumnTypeDouble
}
return c
} | model/columns_gen.go | 0.705075 | 0.530784 | columns_gen.go | starcoder |
package ast
import (
"bytes"
"fmt"
"github.com/geode-lang/geode/pkg/lexer"
)
// ExpressionComponents are nodes that make up the expression
// component system defined in parseExpression.go
// ExpComponent is a representation of complex compound expressions
// like call()[1]().foo().bar[12] for example. It is meant to be
// simple to link expression nodes on to, as it is a linked list
// type structure
type ExpComponent interface {
fmt.Stringer
Add(ExpComponent)
Ident() string
Next() ExpComponent
ConstructNode(Node) (Node, error)
}
type componentChainNode struct {
next ExpComponent
token lexer.Token
}
func (n *componentChainNode) Add(comp ExpComponent) {
if n.next != nil {
n.next.Add(comp)
} else {
n.next = comp
}
}
func (n *componentChainNode) String() string {
if n.next == nil {
return ""
}
return fmt.Sprintf("%s%s", n.next.Ident(), n.next)
}
func (n *componentChainNode) Next() ExpComponent {
return n.next
}
// =========================== BaseComponent ===========================
// BaseComponent is the base of a component linked list
// it is used as the generalized start of any component list
type BaseComponent struct {
componentChainNode
}
// Ident implements ExpComponent.Ident
func (c *BaseComponent) Ident() string {
return c.String()
}
// ConstructNode returns the ast node for the expression component
func (c *BaseComponent) ConstructNode(prev Node) (Node, error) {
d := c.Next()
var err error
node := prev
for d != nil {
node, err = d.ConstructNode(node)
if err != nil {
return nil, err
}
if node == nil {
return nil, fmt.Errorf("ConstructNode on %T returned nil, but no error", d)
}
d = d.Next()
}
return node, nil
}
// =========================== IdentComponent ===========================
// IdentComponent is a component of an expresison that represents
// an identity access
type IdentComponent struct {
componentChainNode
Value string
}
// Ident implements ExpComponent.Ident
func (c *IdentComponent) Ident() string {
return c.Value
}
// ConstructNode returns the ast node for the expression component
func (c *IdentComponent) ConstructNode(prev Node) (Node, error) {
n := NewIdentNode(c.Value)
n.Token = c.token
return n, nil
}
// =========================== IdentDeclComponent ===========================
// IdentDeclComponent is a component of an expresison that represents
// an identity declaration
type IdentDeclComponent struct {
componentChainNode
Type TypeNode
Name IdentNode
}
// Ident implements ExpComponent.Ident
func (c *IdentDeclComponent) Ident() string {
return fmt.Sprintf("%s %s", c.Type, c.Name)
}
// ConstructNode returns the ast node for the expression component
func (c *IdentDeclComponent) ConstructNode(prev Node) (Node, error) {
n := VariableDefnNode{}
n.NodeType = nodeVariableDecl
n.Token = c.token
n.Typ = c.Type
n.Name = c.Name
return n, nil
}
// =========================== CallComponent ===========================
// CallComponent is an expression component for function calls
type CallComponent struct {
componentChainNode
Args []Node
}
// Ident implements ExpComponent.Ident
func (c *CallComponent) Ident() string {
buf := &bytes.Buffer{}
buf.WriteString("(")
for i, arg := range c.Args {
if arg == nil {
buf.WriteString("_")
} else {
fmt.Fprintf(buf, "%s", arg)
}
if i < len(c.Args)-1 {
buf.WriteString(", ")
}
}
buf.WriteString(")")
return buf.String()
}
// ConstructNode returns the ast node for the expression component
func (c *CallComponent) ConstructNode(prev Node) (Node, error) {
switch prev.(type) {
case StringNode:
n := StringFormatNode{}
n.Token = c.token
n.NodeType = nodeStringFormat
n.Format = prev.(StringNode)
for _, argc := range c.Args {
n.Args = append(n.Args, argc)
}
return n, nil
}
n := FunctionCallNode{}
n.Token = c.token
n.NodeType = nodeFunctionCall
base, ok := prev.(Callable)
if !ok {
return nil, fmt.Errorf("function call requires callable - given %T", prev)
}
n.Name = base
for _, argc := range c.Args {
n.Args = append(n.Args, argc)
}
return n, nil
}
// =========================== NumberComponent ===========================
// NumberComponent is an expression component for numbers
type NumberComponent struct {
componentChainNode
Value string
}
// ConstructNode returns the ast node for the expression component
func (c *NumberComponent) ConstructNode(prev Node) (Node, error) {
n, err := GetNumberNodeFromString(c.Value)
if err != nil {
return nil, err
}
if n == nil {
return nil, fmt.Errorf("unable to get number type from number component's value")
}
return n, nil
}
// Ident implements ExpComponent.Ident
func (c *NumberComponent) Ident() string {
return c.Value
}
// =========================== SubscriptComponent ===========================
// SubscriptComponent is an expression component for numbers
type SubscriptComponent struct {
componentChainNode
Value Node
}
// ConstructNode returns the ast node for the expression component
func (c *SubscriptComponent) ConstructNode(prev Node) (Node, error) {
n := &SubscriptNode{}
n.Token = c.token
n.NodeType = nodeSubscript
var ok bool
n.Source, ok = prev.(Accessable)
if !ok {
return nil, fmt.Errorf("previous node in SubscriptComponent is not accessable: %T", prev)
}
val := c.Value
n.Index, ok = val.(Accessable)
if !ok {
return nil, fmt.Errorf("index node in SubscriptComponent is not accessable: %T, %T", val, c.Value)
}
return n, nil
}
// Ident implements ExpComponent.Ident
func (c *SubscriptComponent) Ident() string {
return "[" + c.Value.String() + "]"
}
// =========================== ArrayComponent ===========================
// ArrayComponent is an expression component for numbers
type ArrayComponent struct {
componentChainNode
Values []Node
}
// Ident implements ExpComponent.Ident
func (c *ArrayComponent) Ident() string {
buf := &bytes.Buffer{}
buf.WriteString("[")
for i, arg := range c.Values {
if arg == nil {
buf.WriteString("_")
} else {
fmt.Fprintf(buf, "%s", arg)
}
if i < len(c.Values)-1 {
buf.WriteString(", ")
}
}
buf.WriteString("]")
return buf.String()
}
// ConstructNode returns the ast node for the expression component
func (c *ArrayComponent) ConstructNode(prev Node) (Node, error) {
n := ArrayNode{}
n.Token = c.token
n.Length = len(c.Values)
n.NodeType = nodeArray
for _, item := range c.Values {
n.Elements = append(n.Elements, item)
}
return n, nil
}
// =========================== DotComponent ===========================
// DotComponent is an expression component for numbers
type DotComponent struct {
componentChainNode
Value string
}
// Ident implements ExpComponent.Ident
func (c *DotComponent) Ident() string {
return fmt.Sprintf(".%s", c.Value)
}
// ConstructNode returns the ast node for the expression component
func (c *DotComponent) ConstructNode(prev Node) (Node, error) {
n := DotReference{}
n.Token = c.token
n.NodeType = nodeDot
base, ok := prev.(Reference)
if !ok {
return nil, fmt.Errorf("dot component requires a reference type on the lhs. instead got %T", prev)
}
n.Base = base
n.Field = NewIdentNode(c.Value)
return n, nil
}
// =========================== StringComponent ===========================
// StringComponent is an expression component for numbers
type StringComponent struct {
componentChainNode
Value string
}
// Ident implements ExpComponent.Ident
func (c *StringComponent) Ident() string {
return fmt.Sprintf(".%s", c.Value)
}
// ConstructNode returns the ast node for the expression component
func (c *StringComponent) ConstructNode(prev Node) (Node, error) {
n := StringNode{}
n.Token = c.token
n.NodeType = nodeString
val := c.Value[1 : len(c.Value)-1]
escaped, _ := UnescapeString(val)
n.Value = escaped
return n, nil
}
// =========================== ParenthesisComponent ===========================
// ParenthesisComponent is an expression component for numbers
type ParenthesisComponent struct {
componentChainNode
Value Node
}
// Ident implements ExpComponent.Ident
func (c *ParenthesisComponent) Ident() string {
return fmt.Sprintf(".%s", c.Value)
}
// ConstructNode returns the ast node for the expression component
func (c *ParenthesisComponent) ConstructNode(prev Node) (Node, error) {
return c.Value, nil
}
// =========================== BooleanComponent ===========================
// BooleanComponent is an expression component for numbers
type BooleanComponent struct {
componentChainNode
Value string
}
// Ident implements ExpComponent.Ident
func (c *BooleanComponent) Ident() string {
return fmt.Sprintf("%s", c.Value)
}
// ConstructNode returns the ast node for the expression component
func (c *BooleanComponent) ConstructNode(prev Node) (Node, error) {
n := BooleanNode{}
n.Token = c.token
n.NodeType = nodeBool
n.Value = c.Value
return n, nil
}
// =========================== CharComponent ===========================
// CharComponent is an expression component for numbers
type CharComponent struct {
componentChainNode
Value string
}
// Ident implements ExpComponent.Ident
func (c *CharComponent) Ident() string {
return fmt.Sprintf("%s", c.Value)
}
// ConstructNode returns the ast node for the expression component
func (c *CharComponent) ConstructNode(prev Node) (Node, error) {
n := CharNode{}
n.Token = c.token
n.NodeType = nodeBool
n.Value = []rune(c.Value)[1]
return n, nil
}
// =========================== TypeInfoComponent ===========================
// TypeInfoComponent is an expression component for numbers
type TypeInfoComponent struct {
componentChainNode
Type TypeNode
}
// Ident implements ExpComponent.Ident
func (c *TypeInfoComponent) Ident() string {
node, _ := c.ConstructNode(nil)
return fmt.Sprintf("%s", node)
}
// ConstructNode returns the ast node for the expression component
func (c *TypeInfoComponent) ConstructNode(prev Node) (Node, error) {
n := TypeInfoNode{}
n.Token = c.token
n.NodeType = nodeTypeInfo
n.T = c.Type
return n, nil
} | pkg/ast/ExpressionComponents.go | 0.717309 | 0.425486 | ExpressionComponents.go | starcoder |
package main
import (
"bufio"
"fmt"
"log"
"math"
"os"
)
type Vec2d struct{ x, y int }
func (v Vec2d) Add(v0 Vec2d) Vec2d {
return Vec2d{
x: v.x + v0.x,
y: v.y + v0.y,
}
}
var directions []Vec2d = []Vec2d{
/*UP*/
Vec2d{0, 1},
/*LEFT*/ Vec2d{-1, 0}, Vec2d{1, 0}, /*RIGHT*/
Vec2d{0, -1},
/*DOWN*/
}
type Block struct {
char byte
location Vec2d
path []Track // Path to connect two blocks
}
type Track struct {
key *Block
distance int
l2c uint32 // Length to connect
}
func checkBlock(block byte, bType string) bool {
switch bType {
case "entrance":
return block == '@' || block == '|' || block == '&' || block == '^'
case "key":
return block >= 'a' && block <= 'z'
case "door":
return block >= 'A' && block <= 'Z'
}
return false
}
func distFrom(bType string, block byte) uint32 {
switch bType {
case "key":
return uint32(1 << (block - 'a'))
case "door":
return uint32(1 << (block - 'A'))
}
return uint32(0)
}
func fetchEntraceLoction(vault [][]byte) Vec2d {
for y, row := range vault {
for x, block := range row {
if block == '@' { return Vec2d{x, y} }
}
}
return Vec2d{-1, -1} // No entrance found
}
func check6sides(vault [][]byte, entrance Vec2d) {
for dy := -1; dy <= 1; dy++ {
for dx := -1; dx <= 1; dx++ {
if dx == 0 && dy == 0 { continue } // Intial entrance location
if vault[entrance.y+dy][entrance.x+dx] != '.' {
log.Fatal("[ERROR]: Unable to send robot inside entrance at: %v\n", entrance.Add(Vec2d{dx, dy}))
}
}
}
}
func main() {
if len(os.Args) < 2 {
log.Fatal(`
[ERROR]: Please provide the input dataset!
**Usage: ./main /path/to/file
`)
}
parsedData := ReadFile(os.Args[1])
vault := make([][]byte, len(parsedData))
for y, row := range parsedData { vault[y] = []byte(row) }
fmt.Println("Length of shortest path that collects all of the keys [in vault steps]:", navigateVault(vault))
E := fetchEntraceLoction(vault)
check6sides(vault, E) // Some verification
vault[E.y-1][E.x-1] = '@'; vault[E.y-1][E.x] = '#'; vault[E.y-1][E.x+1] = '|';
vault[ E.y ][E.x-1] = '#'; vault[ E.y ][E.x] = '#'; vault[ E.y ][E.x+1] = '#';
vault[E.y+1][E.x-1] = '&'; vault[E.y+1][E.x] = '#'; vault[E.y+1][E.x+1] = '^';
fmt.Println("Number of fewest steps necessary to collect all of the keys [in steps]:", navigateVault(vault))
}
func navigateVault(vault [][]byte) int {
var keysCount int = 0
blocks := make(map[byte]*Block)
// Aligning data from the grid
for y, row := range vault {
for x, block := range row {
if checkBlock(block, "key") { keysCount++ }
if checkBlock(block, "entrance") || checkBlock(block, "key") {
blocks[block] = &Block{
char: block,
location: Vec2d{x, y},
}
}
}
}
type Item struct {
location Vec2d
l2c uint32 // Length to connect
distance int
}
// Track and connect blocks through vault-exploration.
for _, block := range blocks {
var openBlocks []Item
openBlocks = append(openBlocks, Item{block.location, 0, 0})
visited := make(map[Vec2d]bool)
visited[block.location] = true
for len(openBlocks) != 0 {
currentBlock := openBlocks[0]
openBlocks = openBlocks[1:]
for _, dirVec := range directions {
nextVec := currentBlock.location.Add(dirVec)
item := vault[nextVec.y][nextVec.x]
var bufferItem Item
if visited[nextVec] { continue }
if item == '.' || checkBlock(item, "entrance") {
bufferItem = Item{
location: nextVec,
l2c: currentBlock.l2c,
distance: currentBlock.distance + 1,
}
openBlocks = append(openBlocks, bufferItem)
visited[nextVec] = true
} else if checkBlock(item, "door") {
bufferItem = Item{
location: nextVec,
l2c: currentBlock.l2c | distFrom("door", item),
distance: currentBlock.distance + 1,
}
openBlocks = append(openBlocks, bufferItem)
visited[nextVec] = true
} else if checkBlock(item, "key") {
bufferItem = Item{
location: nextVec,
l2c: currentBlock.l2c | distFrom("key", item),
distance: currentBlock.distance + 1,
}
openBlocks = append(openBlocks, bufferItem)
visited[nextVec] = true
block.path = append(block.path, Track{
key: blocks[item],
l2c: currentBlock.l2c,
distance: currentBlock.distance + 1,
})
}
}
}
}
var totalKeysCount uint32 = (1 << keysCount) - 1
var locations []*Block
for _, block := range blocks {
if checkBlock(block.char, "entrance") { locations = append(locations, block) }
}
return UnlockDoors(locations, 0, math.MaxInt32, 0, totalKeysCount)
}
func UnlockDoors(locations []*Block, currentDistance, shortestDistance int, UnlockedDoorsCount, totalKeysCount uint32) int {
IsUnlocked := func(doors, keys uint32) bool { return doors&keys == keys }
if IsUnlocked(UnlockedDoorsCount, totalKeysCount) { return currentDistance }
for i, loc := range locations {
for _, unit := range loc.path {
if !IsUnlocked(UnlockedDoorsCount, unit.l2c) { continue }
if IsUnlocked(UnlockedDoorsCount, distFrom("key", unit.key.char)) { continue }
newDistance := currentDistance + unit.distance
if shortestDistance < newDistance { continue }
newLocations := make([]*Block, len(locations))
copy(newLocations, locations)
newLocations[i] = unit.key
newUnlockedDoorsCount := UnlockedDoorsCount | distFrom("key", unit.key.char)
finalDistance := UnlockDoors(newLocations, newDistance, shortestDistance, newUnlockedDoorsCount, totalKeysCount)
if finalDistance < shortestDistance { shortestDistance = finalDistance }
}
}
return shortestDistance
}
func ReadFile(fileName string) []string {
fhand, err := os.Open(fileName)
if err != nil { log.Fatal(err) }
defer fhand.Close()
var data []string
scanner := bufio.NewScanner(fhand)
for scanner.Scan() {
data = append(data, scanner.Text())
}
return data
} | 2019/Day-18/Many-Worlds_Interpretation/main.go | 0.639061 | 0.452657 | main.go | starcoder |
// Package unicode provides a mockable wrapper for unicode.
package unicode
import (
unicode "unicode"
)
var _ Interface = &Impl{}
var _ = unicode.In
type Interface interface {
In(r rune, ranges ...*unicode.RangeTable) bool
Is(rangeTab *unicode.RangeTable, r rune) bool
IsControl(r rune) bool
IsDigit(r rune) bool
IsGraphic(r rune) bool
IsLetter(r rune) bool
IsLower(r rune) bool
IsMark(r rune) bool
IsNumber(r rune) bool
IsOneOf(ranges []*unicode.RangeTable, r rune) bool
IsPrint(r rune) bool
IsPunct(r rune) bool
IsSpace(r rune) bool
IsSymbol(r rune) bool
IsTitle(r rune) bool
IsUpper(r rune) bool
SimpleFold(r rune) rune
To(_case int, r rune) rune
ToLower(r rune) rune
ToTitle(r rune) rune
ToUpper(r rune) rune
}
type Impl struct{}
func (*Impl) In(r rune, ranges ...*unicode.RangeTable) bool {
return unicode.In(r, ranges...)
}
func (*Impl) Is(rangeTab *unicode.RangeTable, r rune) bool {
return unicode.Is(rangeTab, r)
}
func (*Impl) IsControl(r rune) bool {
return unicode.IsControl(r)
}
func (*Impl) IsDigit(r rune) bool {
return unicode.IsDigit(r)
}
func (*Impl) IsGraphic(r rune) bool {
return unicode.IsGraphic(r)
}
func (*Impl) IsLetter(r rune) bool {
return unicode.IsLetter(r)
}
func (*Impl) IsLower(r rune) bool {
return unicode.IsLower(r)
}
func (*Impl) IsMark(r rune) bool {
return unicode.IsMark(r)
}
func (*Impl) IsNumber(r rune) bool {
return unicode.IsNumber(r)
}
func (*Impl) IsOneOf(ranges []*unicode.RangeTable, r rune) bool {
return unicode.IsOneOf(ranges, r)
}
func (*Impl) IsPrint(r rune) bool {
return unicode.IsPrint(r)
}
func (*Impl) IsPunct(r rune) bool {
return unicode.IsPunct(r)
}
func (*Impl) IsSpace(r rune) bool {
return unicode.IsSpace(r)
}
func (*Impl) IsSymbol(r rune) bool {
return unicode.IsSymbol(r)
}
func (*Impl) IsTitle(r rune) bool {
return unicode.IsTitle(r)
}
func (*Impl) IsUpper(r rune) bool {
return unicode.IsUpper(r)
}
func (*Impl) SimpleFold(r rune) rune {
return unicode.SimpleFold(r)
}
func (*Impl) To(_case int, r rune) rune {
return unicode.To(_case, r)
}
func (*Impl) ToLower(r rune) rune {
return unicode.ToLower(r)
}
func (*Impl) ToTitle(r rune) rune {
return unicode.ToTitle(r)
}
func (*Impl) ToUpper(r rune) rune {
return unicode.ToUpper(r)
} | unicode/unicode.go | 0.734405 | 0.420838 | unicode.go | starcoder |
package week
import (
"database/sql/driver"
)
// NullWeek is a nullable Week representation.
type NullWeek struct {
Week Week
Valid bool
}
// NewNullWeek creates a new NullWeek.
func NewNullWeek(week Week, valid bool) NullWeek {
return NullWeek{Week: week, Valid: valid}
}
// NullWeekFrom creates a new NullWeek that will always be valid.
func NullWeekFrom(week Week) NullWeek {
return NewNullWeek(week, true)
}
// NullWeekFromPtr creates a new NullWeek that may be null if week is nil.
func NullWeekFromPtr(week *Week) NullWeek {
if week == nil {
return NullWeek{}
}
return NewNullWeek(*week, true)
}
// MarshalText implements the encoding TextMarshaler interface.
func (n NullWeek) MarshalText() ([]byte, error) {
if !n.Valid {
return []byte{}, nil
}
return n.Week.MarshalText()
}
// UnmarshalText implements the encoding TextUnmarshaler interface.
func (n *NullWeek) UnmarshalText(text []byte) error {
str := string(text)
if str == "" || str == "null" {
n.Week, n.Valid = Week{}, false
return nil
}
err := n.Week.UnmarshalText(text)
n.Valid = err == nil
return err
}
// MarshalJSON implements the json Marshaler interface.
func (n NullWeek) MarshalJSON() ([]byte, error) {
if !n.Valid {
return []byte("null"), nil
}
return n.Week.MarshalJSON()
}
// UnmarshalJSON implements the json Unmarshaler interface.
func (n *NullWeek) UnmarshalJSON(data []byte) error {
str := string(data)
if str == "null" {
n.Week, n.Valid = Week{}, false
return nil
}
err := n.Week.UnmarshalJSON(data)
n.Valid = err == nil
return err
}
// Scan implements the sql Scanner interface.
func (n *NullWeek) Scan(value interface{}) error {
if value == nil {
n.Week, n.Valid = Week{}, false
return nil
}
err := n.Week.Scan(value)
if err != nil {
return err
}
n.Valid = true
return nil
}
// Value implements the driver Valuer interface.
func (n NullWeek) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.Week.Value()
}
// Ptr returns a pointer to this NullWeek's value, or a nil pointer it it is invalid.
func (n NullWeek) Ptr() *Week {
if !n.Valid {
return nil
}
return &n.Week
}
// IsZero returns true for invalid NullWeeks.
func (n NullWeek) IsZero() bool {
return !n.Valid
} | null.go | 0.719384 | 0.479077 | null.go | starcoder |
package isc
import (
"reflect"
)
//ListFilter filter specificated item in a list
func ListFilter[T any](list []T, f func(T) bool) []T {
var dest []T
return ListFilterTo(list, &dest, f)
}
//ListFilterNot Returns a list containing all elements not matching the given predicate.
func ListFilterNot[T any](list []T, predicate func(T) bool) []T {
var n []T
return ListFilterNotTo(list, &n, predicate)
}
//ListFilterIndexed Returns a list containing only elements matching the given predicate.
//Params: predicate - function that takes the index of an element and the element itself and returns the result of predicate evaluation on the element.
func ListFilterIndexed[T any](list []T, predicate func(int, T) bool) []T {
var n []T
return ListFilterIndexedTo(list, &n, predicate)
}
//ListFilterNotIndexed Appends all elements matching the given predicate to the given destination.
//Params: predicate - function that takes the index of an element and the element itself and returns the result of predicate evaluation on the element.
func ListFilterNotIndexed[T any](list []T, f func(int, T) bool) []T {
var n []T
for i, e := range list {
if !f(i, e) {
n = append(n, e)
}
}
return n
}
//ListFilterNotNull Returns a list containing all elements that are not null.
func ListFilterNotNull[T any](list []*T) []*T {
var n []*T
for _, e := range list {
if e != nil {
n = append(n, e)
}
}
return n
}
//ListFilterTo Appends all elements matching the given predicate to the given dest.
func ListFilterTo[T any](list []T, dest *[]T, f func(T) bool) []T {
var n []T
for _, e := range list {
if f(e) {
*dest = append(*dest, e)
n = append(n, e)
}
}
return n
}
//ListFilterNotTo Appends all elements not matching the given predicate to the given destination.
func ListFilterNotTo[T any](list []T, dest *[]T, predicate func(T) bool) []T {
var n []T
for _, e := range list {
if !predicate(e) {
*dest = append(*dest, e)
n = append(n, e)
}
}
return n
}
//ListFilterIndexedTo Appends all elements matching the given predicate to the given destination.
//Params: predicate - function that takes the index of an element and the element itself and returns the result of predicate evaluation on the element.
func ListFilterIndexedTo[T any](list []T, dest *[]T, predicate func(int, T) bool) []T {
var n []T
for i, e := range list {
if predicate(i, e) {
*dest = append(*dest, e)
n = append(n, e)
}
}
return n
}
//ListFilterNotIndexedTo Appends all elements not matching the given predicate to the given destination.
//Params: predicate - function that takes the index of an element and the element itself and returns the result of predicate evaluation on the element.
func ListFilterNotIndexedTo[T any](list []T, dest *[]T, predicate func(int, T) bool) []T {
var n []T
for i, e := range list {
if !predicate(i, e) {
*dest = append(*dest, e)
n = append(n, e)
}
}
return n
}
func ListContains[T any](list []T, item T) bool {
ret := false
for _, e := range list {
if reflect.DeepEqual(e, item) {
ret = true
break
}
}
return ret
}
func ListDistinct[T any](list []T) []T {
return SliceDistinct(list)
}
/// functions for map
func MapFilter[K comparable, V any](m map[K]V, f func(K, V) bool) map[K]V {
n := make(map[K]V)
for k, v := range m {
if f(k, v) {
n[k] = v
}
}
return n
}
func MapFilterNot[K comparable, V any](m map[K]V, f func(K, V) bool) map[K]V {
n := make(map[K]V)
for k, v := range m {
if !f(k, v) {
n[k] = v
}
}
return n
}
func MapFilterKeys[K comparable, V any](m map[K]V, f func(K) bool) map[K]V {
n := make(map[K]V)
for k, v := range m {
if f(k) {
n[k] = v
}
}
return n
}
func MapFilterValues[K comparable, V any](m map[K]V, f func(V) bool) map[K]V {
n := make(map[K]V)
for k, v := range m {
if f(v) {
n[k] = v
}
}
return n
}
func MapFilterTo[K comparable, V any](m map[K]V, dest *map[K]V, f func(K, V) bool) map[K]V {
n := make(map[K]V)
for k, v := range m {
if f(k, v) {
(*dest)[k] = v
n[k] = v
}
}
return n
}
func MapFilterNotTo[K comparable, V any](m map[K]V, dest *map[K]V, f func(K, V) bool) map[K]V {
n := make(map[K]V)
for k, v := range m {
if !f(k, v) {
(*dest)[k] = v
n[k] = v
}
}
return n
}
func MapContains[K comparable, V any](m map[K]V, k K, v V) bool {
ret := false
for t, u := range m {
if t == k && reflect.DeepEqual(u, v) {
ret = true
break
}
}
return ret
}
func MapContainsKey[K comparable, V any](m map[K]V, k K) bool {
ret := false
for t := range m {
if t == k {
ret = true
break
}
}
return ret
}
func MapContainsValue[K comparable, V any](m map[K]V, v V) bool {
ret := false
for _, u := range m {
if reflect.DeepEqual(u, v) {
ret = true
break
}
}
return ret
} | isc/filter.go | 0.695545 | 0.501282 | filter.go | starcoder |
package encryption
import (
"crypto/cipher"
"fmt"
)
type CipherCrypt struct {
Block cipher.Block
}
//Encrypt encrypts src to dst with cipher & iv, if failed return error
//src the original source bytes
//c the defined cipher type,now support CBC,CFB,OFB,ECB
//ivs the iv for CBC,CFB,OFB mode
//dst the encrypted bytes
func (cc *CipherCrypt) Encrypt(src []byte, c Cipher, ivs ...[]byte) (dst []byte, err error) {
block := cc.Block
data := PKCS7Padding(src, block.BlockSize())
if len(data)%block.BlockSize() != 0 {
return nil, fmt.Errorf("Need a multiple of the blocksize ")
}
switch c {
case CBC:
return cbcEncrypt(block, data, ivs...)
case CFB:
return cfbEncrypt(block, data, ivs...)
case OFB:
return ofbCrypt(block, data, ivs...)
default:
return ecbEncrypt(block, data)
}
}
//EncryptToString encrypts src then encodes data returned to string
//encodeType now support String,HEX,Base64
func (cc *CipherCrypt) EncryptToString(encodeType Encode, src []byte, c Cipher, ivs ...[]byte) (dst string, err error) {
data, err := cc.Encrypt(src, c, ivs...)
if err != nil {
return
}
return EncodeToString(data, encodeType)
}
//Decrypt decrypts src to dst with cipher & iv, if failed return error
//src the original encrypted bytes
//c the defined cipher type,now support CBC,CFB,OFB,ECB
//ivs the iv for CBC,CFB,OFB mode
//dst the decrypted bytes
func (cc *CipherCrypt) Decrypt(src []byte, c Cipher, ivs ...[]byte) (dst []byte, err error) {
block := cc.Block
switch c {
case CBC:
dst, err = cbcDecrypt(block, src, ivs...)
case CFB:
dst, err = cfbDecrypt(block, src, ivs...)
case OFB:
dst, err = ofbCrypt(block, src, ivs...)
default:
dst, err = ecbDecrypt(block, src)
}
return UnPaddingPKCS7(dst), err
}
//DecryptToString decrypts src then encodes return data to string
//encodeType now support String,HEX,Base64
func (cc *CipherCrypt) DecryptToString(encodeType Encode, src []byte, c Cipher, ivs ...[]byte) (dst string, err error) {
data, err := cc.Decrypt(src, c, ivs...)
if err != nil {
return
}
return EncodeToString(data, encodeType)
}
//ecbEncrypt encrypts data with ecb mode
func ecbEncrypt(block cipher.Block, src []byte) (dst []byte, err error) {
out := make([]byte, len(src))
dst = out
for len(src) > 0 {
block.Encrypt(dst, src[:block.BlockSize()])
src = src[block.BlockSize():]
dst = dst[block.BlockSize():]
}
return out, nil
}
//ecbDecrypt decrypts data with ecb mode
func ecbDecrypt(block cipher.Block, src []byte) (dst []byte, err error) {
dst = make([]byte, len(src))
out := dst
bs := block.BlockSize()
if len(src)%bs != 0 {
err = fmt.Errorf("crypto/cipher: input not full blocks")
return
}
for len(src) > 0 {
block.Decrypt(out, src[:bs])
src = src[bs:]
out = out[bs:]
}
return
}
//cbcEncrypt encrypts data with cbc mode
func cbcEncrypt(block cipher.Block, src []byte, ivs ...[]byte) (dst []byte, err error) {
var iv []byte
if len(ivs) > 0 {
iv = ivs[0]
}
bm := cipher.NewCBCEncrypter(block, iv)
dst = make([]byte, len(src))
bm.CryptBlocks(dst, src)
return
}
//cbcDecrypt decrypts data with cbc mode
func cbcDecrypt(block cipher.Block, src []byte, ivs ...[]byte) (dst []byte, err error) {
var iv []byte
if len(ivs) > 0 {
iv = ivs[0]
}
bm := cipher.NewCBCDecrypter(block, iv)
dst = make([]byte, len(src))
bm.CryptBlocks(dst, src)
return
}
//cfbEncrypt encrypts data with cfb mode
func cfbEncrypt(block cipher.Block, src []byte, ivs ...[]byte) (dst []byte, err error) {
var iv []byte
if len(ivs) > 0 {
iv = ivs[0]
}
bm := cipher.NewCFBEncrypter(block, iv)
dst = make([]byte, len(src))
bm.XORKeyStream(dst, src)
return
}
//cfbDecrypt decrypts data with cfb mode
func cfbDecrypt(block cipher.Block, src []byte, ivs ...[]byte) (dst []byte, err error) {
var iv []byte
if len(ivs) > 0 {
iv = ivs[0]
}
bm := cipher.NewCFBDecrypter(block, iv)
dst = make([]byte, len(src))
bm.XORKeyStream(dst, src)
return
}
//ofbCrypt encrypts or decrypts data with ofb mode
func ofbCrypt(block cipher.Block, src []byte, ivs ...[]byte) (dst []byte, err error) {
var iv []byte
if len(ivs) > 0 {
iv = ivs[0]
}
bm := cipher.NewOFB(block, iv)
dst = make([]byte, len(src))
bm.XORKeyStream(dst, src)
return
} | pkg/encryption/cipher.go | 0.584864 | 0.403126 | cipher.go | starcoder |
package starwars_characters
var Schema = `
schema {
query: Query
mutation: Mutation
subscription: Subscription
}
type Mutation {
}
type Subscription{
}
"The query type, represents the entry points related to characters in the Starwars universe."
type Query {
hero(episode: Episode = NEWHOPE): Character
search(text: String!): [SearchResult]!
character(id: ID!): Character
droid(id: ID!): Droid
human(id: ID!): Human
}
"The id of a Starship"
scalar Starship
"The episodes in the Star Wars trilogy"
enum Episode {
"Star Wars Episode IV: A New Hope, released in 1977."
NEWHOPE
"Star Wars Episode V: The Empire Strikes Back, released in 1980."
EMPIRE
"Star Wars Episode VI: Return of the Jedi, released in 1983."
JEDI
}
"A character from the Star Wars universe"
interface Character {
"The ID of the character"
id: ID!
"The name of the character"
name: String!
"The friends of the character, or an empty list if they have none"
friends: [Character]
"The friends of the character exposed as a connection with edges"
friendsConnection(first: Int, after: ID): FriendsConnection!
"The movies this character appears in"
appearsIn: [Episode!]!
}
"Units of height"
enum LengthUnit {
"The standard unit around the world"
METER
"Primarily used in the United States"
FOOT
}
"A humanoid creature from the Star Wars universe"
type Human implements Character {
"The ID of the human"
id: ID!
"What this human calls themselves"
name: String!
"Height in the preferred unit, default is meters"
height(unit: LengthUnit = METER): Float!
"mass in kilograms, or null if unknown"
mass: Float
"This human's friends, or an empty list if they have none"
friends: [Character]
"The friends of the human exposed as a connection with edges"
friendsConnection(first: Int, after: ID): FriendsConnection!
"The movies this human appears in"
appearsIn: [Episode!]!
"A list of starships this person has piloted, or an empty list if none"
starships: [Starship]
}
"An autonomous mechanical character in the Star Wars universe"
type Droid implements Character {
"The ID of the droid"
id: ID!
"What others call this droid"
name: String!
"This droid's friends, or an empty list if they have none"
friends: [Character]
"The friends of the droid exposed as a connection with edges"
friendsConnection(first: Int, after: ID): FriendsConnection!
"The movies this droid appears in"
appearsIn: [Episode!]!
"This droid's primary function"
primaryFunction: String
}
"A connection object for a character's friends"
type FriendsConnection {
"The total number of friends"
totalCount: Int!
"The edges for each of the character's friends."
edges: [FriendsEdge]
"A list of the friends, as a convenience when edges are not needed."
friends: [Character]
"Information for paginating this connection"
pageInfo: PageInfo!
}
"An edge object for a character's friends"
type FriendsEdge {
"A cursor used for pagination"
cursor: ID!
"The character represented by this friendship edge"
node: Character
}
"Information for paginating this connection"
type PageInfo {
startCursor: ID
endCursor: ID
hasNextPage: Boolean!
}
union SearchResult = Human | Droid
` | examples/starwars_characters/schema.go | 0.721743 | 0.499695 | schema.go | starcoder |
package ais
import (
"bytes"
"fmt"
"time"
)
// Window is used to create a convolution algorithm that slides down a RecordSet
// and performs analysis on Records that are within the a time window.
type Window struct {
leftMarker, rightMarker time.Time
timeIndex int
width time.Duration
Data map[uint64]*Record
}
// NewWindow returns a *Window with the left marker set to the time in
// the next record read from the RecordSet. The Window width will be set from
// the argument provided and the righ marker will be derived from left and width.
// When creating a Window right after opening a RecordSet then the Window
// will be set to first Record in the set, but that first record will still be
// available to the client's first call to rs.Read(). For any non-nil error
// NewWindow returns nil and the error.
func NewWindow(rs *RecordSet, width time.Duration) (*Window, error) {
win := new(Window)
timeIndex, ok := rs.Headers().Contains("BaseDateTime")
if !ok {
return nil, fmt.Errorf("newwindow: headers does not contain BaseDateTime")
}
win.SetIndex(timeIndex)
rec, err := rs.readFirst()
if err != nil {
return nil, fmt.Errorf("newwindow: %v", err)
}
t, err := time.Parse(TimeLayout, (*rec)[timeIndex])
if err != nil {
return nil, fmt.Errorf("newwindow: %v", err)
}
win.SetLeft(t)
win.SetWidth(width)
win.SetRight(win.Left().Add(win.Width()))
return win, nil
}
// Left returns the left marker.
func (win *Window) Left() time.Time { return win.leftMarker }
// SetLeft defines the left marker for the Window
func (win *Window) SetLeft(marker time.Time) {
win.leftMarker = marker
}
// Right returns the right marker.
func (win *Window) Right() time.Time { return win.rightMarker }
// SetRight defines the right marker of the Window.
func (win *Window) SetRight(marker time.Time) {
win.rightMarker = marker
}
// Width returns the width of the Window.
func (win *Window) Width() time.Duration { return win.width }
// SetWidth provides the block of time coverd by the Window.
func (win *Window) SetWidth(dur time.Duration) {
win.width = dur
}
// SetIndex provides the integer index of the BaseDateTime field the
// Records stored in the Window.
func (win *Window) SetIndex(index int) {
win.timeIndex = index
}
// AddRecord appends a new Record to the data in the Window.
func (win *Window) AddRecord(rec Record) {
if win.Data == nil {
win.Data = make(map[uint64]*Record)
}
h := rec.Hash()
// fmt.Println("hash is: ", h)
win.Data[h] = &rec
}
// InWindow tests if a time is in the Window.
func (win *Window) InWindow(t time.Time) bool {
if win.leftMarker.Equal(t) {
return true
}
return win.leftMarker.Before(t) && t.Before(win.rightMarker)
}
// RecordInWindow returns true if the record is in the Window.
// Errors are possible from parsing the BaseDateTime field of the
// Record.
func (win *Window) RecordInWindow(rec *Record) (bool, error) {
t, err := rec.ParseTime(win.timeIndex)
if err != nil {
return false, fmt.Errorf("recordinwindow: %v", err)
}
return win.InWindow(t), nil
}
// Slide moves the window down by the time provided in the arugment dur.
// Slide also removes any data from the Window that would no longer return
// true from InWindow for the new left and right markers after the Slide.
func (win *Window) Slide(dur time.Duration) {
win.SetLeft(win.leftMarker.Add(dur))
win.SetRight(win.leftMarker.Add(win.Width()))
win.validate()
}
// Len returns the lenght of the slice holding the Records in the Window
func (win *Window) Len() int {
return len(win.Data)
}
// Validate checks the data held by the Window to ensure every Record passes
// the InWindow test.
func (win *Window) validate() error {
for hash, rec := range win.Data {
in, err := win.RecordInWindow(rec)
if err != nil {
return err
}
if !in {
delete(win.Data, hash)
}
}
return nil
}
// String implements the Stringer interface for Window.
func (win *Window) String() string {
var buf bytes.Buffer
for _, rec := range win.Data {
fmt.Fprintln(&buf, rec)
}
return buf.String()
}
// Config provides a pretty print of the Window's configuration
func (win *Window) Config() string {
var buf bytes.Buffer
buf.WriteString(fmt.Sprintf("Window has the following configuration\n"))
buf.WriteString(fmt.Sprintf("\tLeft marker: %s\n", win.Left().Format(TimeLayout)))
buf.WriteString(fmt.Sprintf("\tWindow width: %v\n", win.Width()))
return buf.String()
} | window.go | 0.831074 | 0.449211 | window.go | starcoder |
package main
import (
"fmt"
"math"
"math/cmplx"
"math/rand"
"sort"
"time"
"github.com/ldsec/lattigo/ckks"
)
func randomFloat(min, max float64) float64 {
return min + rand.Float64()*(max-min)
}
func randomComplex(min, max float64) complex128 {
return complex(randomFloat(min, max), randomFloat(min, max))
}
func chebyshevinterpolation() {
// This example will pack random 8192 float64 values in the range [-8, 8]
// and approximate the function 1/(exp(-x) + 1) over the range [-8, 8].
// The result is then parsed and compared to the expected result.
rand.Seed(time.Now().UnixNano())
// Scheme params
params := ckks.DefaultParams[ckks.PN14QP438]
encoder := ckks.NewEncoder(params)
// Keys
kgen := ckks.NewKeyGenerator(params)
var sk *ckks.SecretKey
var pk *ckks.PublicKey
sk, pk = kgen.GenKeyPair()
// Relinearization key
var rlk *ckks.EvaluationKey
rlk = kgen.GenRelinKey(sk)
// Encryptor
encryptor := ckks.NewEncryptorFromPk(params, pk)
// Decryptor
decryptor := ckks.NewDecryptor(params, sk)
// Evaluator
evaluator := ckks.NewEvaluator(params)
slots := uint64(1 << (params.LogN - 1))
// Values to encrypt
values := make([]complex128, slots)
for i := range values {
values[i] = complex(randomFloat(-8, 8), 0)
}
fmt.Printf("HEAAN parameters : logN = %d, logQ = %d, levels = %d, scale= %f, sigma = %f \n",
params.LogN, params.LogQP(), params.MaxLevel()+1, params.Scale, params.Sigma)
fmt.Println()
fmt.Printf("Values : %6f %6f %6f %6f...\n",
round(values[0]), round(values[1]), round(values[2]), round(values[3]))
fmt.Println()
// Plaintext creation and encoding process
plaintext := ckks.NewPlaintext(params, params.MaxLevel(), params.Scale)
encoder.Encode(plaintext, values, slots)
// Encryption process
var ciphertext *ckks.Ciphertext
ciphertext = encryptor.EncryptNew(plaintext)
fmt.Println("Evaluation of the function 1/(exp(-x)+1) in the range [-8, 8] (degree of approximation : 32)")
// Evaluation process
// We ask to approximate f(x) in the range [-8, 8] with a chebyshev polynomial of 33 coefficients (degree 32).
chebyapproximation := ckks.Approximate(f, -8, 8, 33)
// We evaluate the interpolated chebyshev polynomial on the ciphertext
ciphertext = evaluator.EvaluateChebyEco(ciphertext, chebyapproximation, rlk)
fmt.Println("Done... Consumed levels :", params.MaxLevel()-ciphertext.Level())
// Decryption process + Decoding process
valuesTest := encoder.Decode(decryptor.DecryptNew(ciphertext), slots)
// Computation of the reference values
for i := range values {
values[i] = f(values[i])
}
// Printing results and comparison
fmt.Println()
fmt.Printf("ValuesTest : %6f %6f %6f %6f...\n",
round(valuesTest[0]), round(valuesTest[1]), round(valuesTest[2]), round(valuesTest[3]))
fmt.Printf("ValuesWant : %6f %6f %6f %6f...\n",
round(values[0]), round(values[1]), round(values[2]), round(values[3]))
verifyVector(values, valuesTest)
}
func f(x complex128) complex128 {
return 1 / (cmplx.Exp(-x) + 1)
}
func round(x complex128) complex128 {
var factor float64
factor = 100000000
a := math.Round(real(x)*factor) / factor
b := math.Round(imag(x)*factor) / factor
return complex(a, b)
}
func verifyVector(valuesWant, valuesTest []complex128) (err error) {
var deltaReal, deltaImag float64
var minprec, maxprec, meanprec, medianprec complex128
diff := make([]complex128, len(valuesWant))
minprec = complex(0, 0)
maxprec = complex(1, 1)
meanprec = complex(0, 0)
distribReal := make(map[uint64]uint64)
distribImag := make(map[uint64]uint64)
for i := range valuesWant {
// Test the ratio for big values (> 1) and difference for small values (< 1)
deltaReal = math.Abs(real(valuesTest[i]) - real(valuesWant[i]))
deltaImag = math.Abs(imag(valuesTest[i]) - imag(valuesWant[i]))
diff[i] += complex(deltaReal, 0)
diff[i] += complex(0, deltaImag)
meanprec += diff[i]
if real(diff[i]) > real(minprec) {
minprec = complex(real(diff[i]), 0)
}
if imag(diff[i]) > imag(minprec) {
minprec = complex(real(minprec), imag(diff[i]))
}
if real(diff[i]) < real(maxprec) {
maxprec = complex(real(diff[i]), 0)
}
if imag(diff[i]) < imag(maxprec) {
maxprec = complex(real(maxprec), imag(diff[i]))
}
distribReal[uint64(math.Floor(math.Log2(1/real(diff[i]))))]++
distribImag[uint64(math.Floor(math.Log2(1/imag(diff[i]))))]++
}
meanprec /= complex(float64(len(valuesWant)), 0)
medianprec = calcmedian(diff)
fmt.Println()
fmt.Printf("Minimum precision : (%.2f, %.2f) bits \n",
math.Log2(1/real(minprec)), math.Log2(1/imag(minprec)))
fmt.Printf("Maximum precision : (%.2f, %.2f) bits \n",
math.Log2(1/real(maxprec)), math.Log2(1/imag(maxprec)))
fmt.Printf("Mean precision : (%.2f, %.2f) bits \n",
math.Log2(1/real(meanprec)), math.Log2(1/imag(meanprec)))
fmt.Printf("Median precision : (%.2f, %.2f) bits \n",
math.Log2(1/real(medianprec)), math.Log2(1/imag(medianprec)))
fmt.Println()
return nil
}
func calcmedian(values []complex128) (median complex128) {
tmp := make([]float64, len(values))
for i := range values {
tmp[i] = real(values[i])
}
sort.Float64s(tmp)
for i := range values {
values[i] = complex(tmp[i], imag(values[i]))
}
for i := range values {
tmp[i] = imag(values[i])
}
sort.Float64s(tmp)
for i := range values {
values[i] = complex(real(values[i]), tmp[i])
}
index := len(values) / 2
if len(values)&1 == 1 {
return values[index]
}
return (values[index] + values[index+1]) / 2
}
func main() {
chebyshevinterpolation()
} | examples/ckks/examples_ckks.go | 0.681939 | 0.421105 | examples_ckks.go | starcoder |
package grid
// Interface used as a generic
type T interface{}
// Grid is a dwo dimentional array that can be walked
// Left(), Right(), Up(), Down() cell by cell infinitely
type Grid struct {
cells []T
dim int
}
// Make new Grid by providing length of one side, Grid will be dim x dim
// If dim = 3, Grid will be 3 by 3
func NewGrid(dim int) *Grid {
g := Grid{
cells: make([]T, dim*dim),
dim: dim,
}
for i := range g.cells {
g.cells[i] = 0
}
return &g
}
// Make new Grid by providing length of one side, Grid will be dim x dim
// If dim = 3, Grid will be 3 by 3
func New(dim int) *Grid {
return NewGrid(dim)
}
// Public getter to get all cells as a single array,
func (g Grid) Cells() []T {
return g.cells
}
// Get one dimension size
func (g Grid) Dim() int {
return g.dim
}
// Get index of a Row by providing Index of cell
func (g Grid) Row(i int) int {
return int(i / g.dim)
}
// Get index of a column by providing Index of a cell
func (g Grid) Column(i int) int {
return i % g.dim
}
// Get index and a Row and Column by providing Index of a cell
func (g Grid) RowColumn(i int) (int, int) {
return g.Row(i), g.Column(i)
}
// Get value of a cell by providing Index of a cell
func (g Grid) Value(i int) T {
return g.cells[i]
}
// Get Index of a cell by providing row and column index
func (g Grid) Index(r int, c int) int {
return (g.dim * r) + c
}
func (g Grid) isFirstRow(i int) bool {
return g.Row(i) == 0
}
func (g Grid) isLastRow(i int) bool {
return g.Row(i) == (g.dim - 1)
}
func (g Grid) isFirstColumn(i int) bool {
return g.Column(i) == 0
}
func (g Grid) isLastColumn(i int) bool {
return g.Column(i) == (g.dim - 1)
}
// Index of a cell to direction (method name) by providing Index of a cell
func (g Grid) Up(i int) int {
if g.isFirstRow(i) {
return g.Index(g.dim-1, g.Column(i))
}
return g.Index(g.Row(i)-1, g.Column(i))
}
// Index of a cell to direction (method name) by providing Index of a cell
func (g Grid) Down(i int) int {
if g.isLastRow(i) {
return g.Index(0, g.Column(i))
}
return g.Index(g.Row(i)+1, g.Column(i))
}
// Index of a cell to direction (method name) by providing Index of a cell
func (g Grid) Left(i int) int {
if g.isFirstColumn(i) {
return g.Index(g.Row(i), g.dim-1)
}
return g.Index(g.Row(i), g.Column(i)-1)
}
// Index of a cell to direction (method name) by providing Index of a cell
func (g Grid) Right(i int) int {
if g.isLastColumn(i) {
return g.Index(g.Row(i), 0)
}
return g.Index(g.Row(i), g.Column(i)+1)
}
// Set value of a cell where Index is first arg and value second
func (g Grid) Set(i int, v int) {
g.cells[i] = v
} | grid.go | 0.813794 | 0.560132 | grid.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.