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 state
import (
"sync"
"sync/atomic"
)
// State captures the state of a Babble node: Babbling, CatchingUp, Joining,
// Leaving, Suspended, or Shutdown
type State uint32
const (
// Babbling is the state in which a node gossips regularly with other nodes
// as part of the hashgraph consensus algorithm, and responds to other
// requests.
Babbling State = iota
// CatchingUp is the state in which a node attempts to fast-forward to a
// future point in the hashgraph as part of the FastSync protocol.
CatchingUp
// Joining is the state in which a node attempts to join a Babble group by
// submitting a join request.
Joining
// Leaving is the state in which a node attempts to politely leave a Babble
// group by submitting a leave request.
Leaving
// Shutdown is the state in which a node stops responding to external events
// and closes its transport.
Shutdown
// Suspended is the state in which a node passively participates in the
// gossip protocol but does not process any new events or transactions.
Suspended
)
// WGLIMIT is the maximum number of goroutines that can be launched through
// state.GoFunc
const WGLIMIT = 20
// String returns the string representation of a State
func (s State) String() string {
switch s {
case Babbling:
return "Babbling"
case CatchingUp:
return "CatchingUp"
case Joining:
return "Joining"
case Leaving:
return "Leaving"
case Shutdown:
return "Shutdown"
case Suspended:
return "Suspended"
default:
return "Unknown"
}
}
// Manager wraps a State with get and set methods. It is also used to limit the
// number of goroutines launched by the node, and to wait for all of them to
// complete.
type Manager struct {
state State
wg sync.WaitGroup
wgCount int32
}
// GetState returns the current state.
func (b *Manager) GetState() State {
stateAddr := (*uint32)(&b.state)
return State(atomic.LoadUint32(stateAddr))
}
// SetState sets the state.
func (b *Manager) SetState(s State) {
stateAddr := (*uint32)(&b.state)
atomic.StoreUint32(stateAddr, uint32(s))
}
// GoFunc launches a goroutine for a given function, if there are currently
// less than WGLIMIT running. It increments the waitgroup.
func (b *Manager) GoFunc(f func()) {
tempWgCount := atomic.LoadInt32(&b.wgCount)
if tempWgCount < WGLIMIT {
b.wg.Add(1)
atomic.AddInt32(&b.wgCount, 1)
go func() {
defer b.wg.Done()
atomic.AddInt32(&b.wgCount, -1)
f()
}()
}
}
// WaitRoutines waits for all the goroutines in the waitgroup.
func (b *Manager) WaitRoutines() {
b.wg.Wait()
} | src/node/state/state.go | 0.560734 | 0.413536 | state.go | starcoder |
package list
import (
"fmt"
"github.com/flowonyx/functional"
"github.com/flowonyx/functional/errors"
"github.com/flowonyx/functional/option"
)
// Head returns the first item from values.
// If values contains no items, it returns the zero value for the type
// and a IndexOutOfRangeErr.
func Head[T any](values []T) (T, error) {
if len(values) > 0 {
return values[0], nil
}
return *(new(T)), fmt.Errorf("%w: Head([0]%T)", errors.IndexOutOfRangeErr, values)
}
// Tail returns all but the first item from values.
// If values contains no items, it returns the an empty slice.
func Tail[T any](values []T) []T {
if len(values) > 0 {
return values[1:]
}
return make([]T, 0)
}
// Last returns the last item from values.
// If values contains no items, it returns the zero value for the type
// and a IndexOutOfRangeErr.
func Last[T any](values []T) (T, error) {
if len(values) > 0 {
return values[len(values)-1], nil
}
return *(new(T)), fmt.Errorf("%w: Last([0]%T)", errors.IndexOutOfRangeErr, values)
}
// TryHead returns the first item from values as an Option.
// If values contains no items, it returns None.
func TryHead[T any](values []T) option.Option[T] {
if h, err := Head(values); err != nil {
return option.None[T]()
} else {
return option.Some(h)
}
}
// TryLast returns the last item from values as an Option.
// If values contains no items, it returns None.
func TryLast[T any](values []T) option.Option[T] {
if l, err := Last(values); err != nil {
return option.None[T]()
} else {
return option.Some(l)
}
}
// MustHead returns the first item from values.
// If values contains no items, it will panic with an index out of range.
// This should only be used when you are certain there is at least one item in values.
func MustHead[T any](values []T) T {
if len(values) == 0 {
panic("MustHead called with empty slice")
}
return values[0]
}
// MustLast returns the last item from values.
// If values contains no items, it will panic with an index out of range.
// This should only be used when you are certain there is at least one item in values.
func MustLast[T any](values []T) T {
if len(values) == 0 {
panic("MustLast called with empty slice")
}
return values[len(values)-1]
}
// Cons makes a new list with head at the beginning and the items in tail after that.
func Cons[T any](head T, tail []T) []T {
return append([]T{head}, tail...)
}
// ConsPair makes a new list with the first item in the Pair at the beginning
// and the items in the second item in the Pair after that.
func ConsPair[T any](p functional.Pair[T, []T]) []T {
head, tail := functional.FromPair(p)
return append([]T{head}, tail...)
} | list/headTailLast.go | 0.784608 | 0.51312 | headTailLast.go | starcoder |
package winipcfg
import "fmt"
// NDIS_MEDIUM defined in ntddndis.h
// (https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ntddndis/ne-ntddndis-_ndis_medium)
type NdisMedium uint32
const (
NdisMedium802_3 NdisMedium = 0
NdisMedium802_5 NdisMedium = 1
NdisMediumFddi NdisMedium = 2
NdisMediumWan NdisMedium = 3
NdisMediumLocalTalk NdisMedium = 4
NdisMediumDix NdisMedium = 5 // defined for convenience, not a real medium
NdisMediumArcnetRaw NdisMedium = 6
NdisMediumArcnet878_2 NdisMedium = 7
NdisMediumAtm NdisMedium = 8
NdisMediumWirelessWan NdisMedium = 9
NdisMediumIrda NdisMedium = 10
NdisMediumBpc NdisMedium = 11
NdisMediumCoWan NdisMedium = 12
NdisMedium1394 NdisMedium = 13
NdisMediumInfiniBand NdisMedium = 14
NdisMediumTunnel NdisMedium = 15
NdisMediumNative802_11 NdisMedium = 16
NdisMediumLoopback NdisMedium = 17
NdisMediumWiMAX NdisMedium = 18
NdisMediumIP NdisMedium = 19
NdisMediumMax NdisMedium = 20
)
func (nm NdisMedium) String() string {
switch nm {
case NdisMedium802_3:
return "NdisMedium802_3"
case NdisMedium802_5:
return "NdisMedium802_5"
case NdisMediumFddi:
return "NdisMediumFddi"
case NdisMediumWan:
return "NdisMediumWan"
case NdisMediumLocalTalk:
return "NdisMediumLocalTalk"
case NdisMediumDix:
return "NdisMediumDix"
case NdisMediumArcnetRaw:
return "NdisMediumArcnetRaw"
case NdisMediumArcnet878_2:
return "NdisMediumArcnet878_2"
case NdisMediumAtm:
return "NdisMediumAtm"
case NdisMediumWirelessWan:
return "NdisMediumWirelessWan"
case NdisMediumIrda:
return "NdisMediumIrda"
case NdisMediumBpc:
return "NdisMediumBpc"
case NdisMediumCoWan:
return "NdisMediumCoWan"
case NdisMedium1394:
return "NdisMedium1394"
case NdisMediumInfiniBand:
return "NdisMediumInfiniBand"
case NdisMediumTunnel:
return "NdisMediumTunnel"
case NdisMediumNative802_11:
return "NdisMediumNative802_11"
case NdisMediumLoopback:
return "NdisMediumLoopback"
case NdisMediumWiMAX:
return "NdisMediumWiMAX"
case NdisMediumIP:
return "NdisMediumIP"
case NdisMediumMax:
return "NdisMediumMax"
default:
return fmt.Sprintf("NdisMedium_UNKNOWN(%d)", nm)
}
} | vendor/golang.zx2c4.com/winipcfg/ndis_medium.go | 0.648578 | 0.463141 | ndis_medium.go | starcoder |
package main
import (
"math"
"math/rand"
"time"
)
func main() {
p := Perceptron{
input: [][]float64{{0, 0, 1}, {1, 1, 1}, {1, 0, 1}, {0, 1, 0}}, // Input Data
actualOutput: []float64{0, 1, 1, 0}, // Actual Output
epochs: 100000, // Number of Epoch
}
p.initialize()
p.train()
// Make Predictions
print("Expected result is 0\n")
print(p.forwardPass([]float64{0, 1, 0}), "\n")
print(p.forwardPass([]float64{0, 1, 1}), "\n")
print(p.forwardPass([]float64{0, 0, 0}), "\n")
print("Expected result is 1\n")
print(p.forwardPass([]float64{1, 1, 0}), "\n")
print(p.forwardPass([]float64{1, 1, 1}), "\n")
print(p.forwardPass([]float64{1, 0, 0}), "\n")
}
// Perceptron is a type of Neural Network.
type Perceptron struct {
input [][]float64
actualOutput []float64
weights []float64
bias float64
epochs int
}
func (a *Perceptron) initialize() {
rand.Seed(time.Now().UnixNano())
a.bias = 0.0
a.weights = make([]float64, len(a.input[0]))
for i := 0; i < len(a.input[0]); i++ {
a.weights[i] = rand.Float64()
}
}
// sigmoid performs Sigmoid Activation
func (a *Perceptron) sigmoid(x float64) float64 {
return 1.0 / (1.0 + math.Exp(-x))
}
// forwardPass performs Forward Propagation
func (a *Perceptron) forwardPass(x []float64) (sum float64) {
return a.sigmoid(dotProduct(a.weights, x) + a.bias)
}
// gradW calculates the Gradient of Weights
func (a *Perceptron) gradW(x []float64, y float64) []float64 {
pred := a.forwardPass(x)
return scalarMatMul(-(pred-y)*pred*(1-pred), x)
}
// gradB calculates the Gradients of Bias
func (a *Perceptron) gradB(x []float64, y float64) float64 {
pred := a.forwardPass(x)
return -(pred - y) * pred * (1 - pred)
}
// train trains the Perception for n epochs
func (a *Perceptron) train() {
for i := 0; i < a.epochs; i++ {
dw := make([]float64, len(a.input[0]))
db := 0.0
for length, val := range a.input {
dw = vecAdd(dw, a.gradW(val, a.actualOutput[length]))
db += a.gradB(val, a.actualOutput[length])
}
dw = scalarMatMul(2/float64(len(a.actualOutput)), dw)
a.weights = vecAdd(a.weights, dw)
a.bias += db * 2 / float64(len(a.actualOutput))
}
}
// dotProduct returns the product of two vectors of the same size.
func dotProduct(v1, v2 []float64) float64 {
dot := 0.0
for i := 0; i < len(v1); i++ {
dot += v1[i] * v2[i]
}
return dot
}
// vecAdd returns the addition of two vectors of the same size.
func vecAdd(v1, v2 []float64) []float64 {
add := make([]float64, len(v1))
for i := 0; i < len(v1); i++ {
add[i] = v1[i] + v2[i]
}
return add
}
// scalarMatMul returns the product of a vector and a matrix.
func scalarMatMul(s float64, mat []float64) []float64 {
result := make([]float64, len(mat))
for i := 0; i < len(mat); i++ {
result[i] += s * mat[i]
}
return result
} | main.go | 0.663124 | 0.504516 | main.go | starcoder |
package slice
import (
"fmt"
"reflect"
)
var errorType = reflect.TypeOf((*error)(nil)).Elem()
func assertSlice(v reflect.Value) {
if k := v.Kind(); k != reflect.Slice {
panic(fmt.Errorf("%s (%s) is not a slice", v.Type().Name(), k))
}
}
func assertSliceFun(fType reflect.Type) {
if fType.Kind() != reflect.Func {
panic(fmt.Errorf("SliceFuncError: not a function"))
}
if fType.NumIn() != 2 {
panic(fmt.Errorf("SliceFuncError: the second function must take two arguments"))
}
if fType.In(0).Kind() != reflect.Int {
panic(fmt.Errorf("SliceFuncError: the second function must take int value on the first argument"))
}
if fType.In(1).Kind() == reflect.Struct {
panic(fmt.Errorf(
"SliceFuncError: the second function must not take struct value on the second argument, use %q instead",
reflect.PtrTo(fType.In(1)),
))
}
}
const noErrorsInMultiError = "No errors"
// SliceError is an error collection as a single error.
// error[i] might be nil if there is no error.
type SliceError []error
// NewSliceError creates SliceError instance with the given size.
func NewSliceError(size int) SliceError {
return SliceError(make([]error, size))
}
// Error implemnts error.Error()
func (se SliceError) Error() string {
var firstError error
var errorCount int
for _, e := range se {
if e != nil {
if firstError == nil {
firstError = e
}
errorCount++
}
}
switch errorCount {
case 0:
return noErrorsInMultiError
case 1:
return firstError.Error()
}
return fmt.Sprintf("%s (and %d other errors)", firstError.Error(), errorCount)
}
// SplitByLength splits a list into multiple lists. Each lengths of lists must be up to `each`
// You can use the returned value as `[][]T` when you pass `[]T` for list.
func SplitByLength(list interface{}, eachSize int) interface{} {
a := reflect.ValueOf(list)
assertSlice(a)
// create and allocate lists
bucketType := a.Type()
bucketListType := reflect.SliceOf(bucketType)
tailSize := a.Len() % eachSize
bucketListLen := a.Len() / eachSize
if tailSize != 0 {
bucketListLen++
}
bucketList := reflect.MakeSlice(bucketListType, bucketListLen, bucketListLen)
// fill non-tail (must hold eachSize)
for i := 0; i < bucketListLen-1; i++ {
bucket := bucketList.Index(i)
bucket.Set(reflect.MakeSlice(bucketType, eachSize, eachSize))
offset := i * eachSize
for j := 0; j < eachSize; j++ {
bucket.Index(j).Set(a.Index(offset + j))
}
}
// fill tail
if tailSize == 0 {
tailSize = eachSize
}
bucket := bucketList.Index(bucketListLen - 1)
bucket.Set(reflect.MakeSlice(bucketType, tailSize, tailSize))
offset := (bucketListLen - 1) * eachSize
for j := 0; j < tailSize; j++ {
bucket.Index(j).Set(a.Index(offset + j))
}
return bucketList.Interface()
}
// ToInterface converts []*T to []interface{}
func ToInterface(v interface{}) []interface{} {
a := reflect.ValueOf(v)
assertSlice(a)
vv := make([]interface{}, a.Len())
for i := range vv {
vv[i] = a.Index(i).Interface()
}
return vv
}
// ToAddr converts []T to []*T
func ToAddr(v interface{}) interface{} {
a := reflect.ValueOf(v)
assertSlice(a)
list := reflect.MakeSlice(
reflect.SliceOf(reflect.PtrTo(a.Type().Elem())),
a.Len(),
a.Cap(),
)
for i := 0; i < a.Len(); i++ {
list.Index(i).Set(a.Index(i).Addr())
}
return list.Interface()
}
// ToElem converts []*T to []T
func ToElem(v interface{}) interface{} {
a := reflect.ValueOf(v)
assertSlice(a)
list := reflect.MakeSlice(
reflect.SliceOf(a.Type().Elem().Elem()),
a.Len(),
a.Cap(),
)
for i := 0; i < a.Len(); i++ {
list.Index(i).Set(a.Index(i).Elem())
}
return list.Interface()
} | iterator/slice/slice.go | 0.658857 | 0.452838 | slice.go | starcoder |
package genheightmap
import (
"github.com/Flokey82/go_gens/vectors"
"math"
"math/rand"
opensimplex "github.com/ojrac/opensimplex-go"
)
type Terrain interface {
//ApplyGen(f GenFunc)
MinMax() (float64, float64)
}
type GenFunc func(x, y float64) float64
func GenSlope(direction vectors.Vec2) GenFunc {
return func(x, y float64) float64 {
return x*direction.X + y*direction.Y
}
}
func GenCone(slope float64) GenFunc {
return func(x, y float64) float64 {
return math.Pow(x*x+y*y, 0.5) * slope
}
}
func GenVolCone(slope float64) GenFunc {
return func(x, y float64) float64 {
dist := math.Pow(x*x+y*y, 0.5)
if dist < 0.1 {
return -4 * dist * slope
}
return dist * slope
}
}
func GenMountains(maxX, maxY float64, n int, r float64) GenFunc {
rand.Seed(1234)
var mounts [][2]float64
for i := 0; i < n; i++ {
mounts = append(mounts, [2]float64{maxX * (rand.Float64() - 0.5), maxY * (rand.Float64() - 0.5)})
}
return func(x, y float64) float64 {
var val float64
for j := 0; j < n; j++ {
m := mounts[j]
val += math.Pow(math.Exp(-((x-m[0])*(x-m[0])+(y-m[1])*(y-m[1]))/(2*r*r)), 2)
}
return val
}
}
func GenNoise(seed int64, slope float64) GenFunc {
perlin := opensimplex.New(seed)
mult := 15.0
pow := 1.0
return func(x, y float64) float64 {
x *= mult
y *= mult
e := 1 * math.Abs(perlin.Eval2(x, y))
e += 0.5 * math.Abs(perlin.Eval2(x*2, y*2))
e += 0.25 * perlin.Eval2(x*4, y*4)
e /= (1 + 0.5 + 0.25)
return math.Pow(e, pow)
}
}
func CalcMean(nums []float64) float64 {
total := 0.0
for _, v := range nums {
total += v
}
return total / float64(len(nums))
}
func MinMax(hm []float64) (float64, float64) {
if len(hm) == 0 {
return 0, 0
}
min := hm[0]
max := hm[0]
for _, h := range hm {
if h > max {
max = h
}
if h < min {
min = h
}
}
return min, max
}
type Modify func(val float64) float64
func ModNormalize(min, max float64) Modify {
return func(val float64) float64 {
return (val - min) / (max - min)
}
}
func ModPeaky() Modify {
return math.Sqrt
}
func ModSeaLevel(min, max, q float64) Modify {
delta := min + (max-min)*0.1
//delta := quantile(h, q)
return func(val float64) float64 {
return val - delta
}
}
type ModifyWithIndex func(idx int, val float64) float64
type GetNeighbors func(idx int) []int
type GetHeight func(idx int) float64
func ModRelax(n GetNeighbors, h GetHeight) ModifyWithIndex {
return func(idx int, val float64) float64 {
vals := []float64{val}
for _, nb := range n(idx) {
vals = append(vals, h(nb))
}
return CalcMean(vals)
}
} | genheightmap/genheightmap.go | 0.691914 | 0.527621 | genheightmap.go | starcoder |
package yit
import (
"strings"
"gopkg.in/yaml.v3"
)
var (
All = func(node *yaml.Node) bool {
return true
}
None = func(node *yaml.Node) bool {
return false
}
StringValue = Intersect(
WithKind(yaml.ScalarNode),
WithShortTag("!!str"),
)
)
func Intersect(ps ...Predicate) Predicate {
return func(node *yaml.Node) bool {
for _, p := range ps {
if !p(node) {
return false
}
}
return true
}
}
func Union(ps ...Predicate) Predicate {
return func(node *yaml.Node) bool {
for _, p := range ps {
if p(node) {
return true
}
}
return false
}
}
func Negate(p Predicate) Predicate {
return func(node *yaml.Node) bool {
return !p(node)
}
}
func WithStringValue(value string) Predicate {
return Intersect(
StringValue,
func(node *yaml.Node) bool {
return node.Value == value
},
)
}
func WithShortTag(tag string) Predicate {
return func(node *yaml.Node) bool {
return node.ShortTag() == tag
}
}
func WithValue(value string) Predicate {
return func(node *yaml.Node) bool {
return node.Value == value
}
}
func WithKind(kind yaml.Kind) Predicate {
return func(node *yaml.Node) bool {
return node.Kind == kind
}
}
func WithMapKey(key string) Predicate {
return func(node *yaml.Node) bool {
return FromNode(node).MapKeys().AnyMatch(WithValue(key))
}
}
func WithMapValue(value string) Predicate {
return func(node *yaml.Node) bool {
return FromNode(node).MapValues().AnyMatch(WithValue(value))
}
}
func WithMapKeyValue(keyPredicate, valuePredicate Predicate) Predicate {
return Intersect(
WithKind(yaml.MappingNode),
func(node *yaml.Node) bool {
for i := 0; i < len(node.Content); i += 2 {
key := node.Content[i]
value := node.Content[i+1]
if keyPredicate(key) && valuePredicate(value) {
return true
}
}
return false
},
)
}
func WithPrefix(prefix string) Predicate {
return func(node *yaml.Node) bool {
return strings.HasPrefix(node.Value, prefix)
}
}
func WithSuffix(suffix string) Predicate {
return func(node *yaml.Node) bool {
return strings.HasSuffix(node.Value, suffix)
}
} | vendor/github.com/dprotaso/go-yit/predicates.go | 0.570092 | 0.491761 | predicates.go | starcoder |
package binarytransforms
import (
"encoding/binary"
"errors"
"fmt"
"strings"
)
// LittleEndianBinaryToInt64 converts a little endian byte slice to int64.
func LittleEndianBinaryToInt64(inBytes []byte) (outInt64 int64, err error) {
inBytesLength := len(inBytes)
if inBytesLength > 8 || inBytesLength == 0 {
err = fmt.Errorf("LittleEndianBinaryToInt64() received %d bytes but expected 1-8 bytes", inBytesLength)
outInt64 = 0
return
}
// Pad it to get to 8 bytes
if inBytes[inBytesLength-1] >= 0x80 {
if inBytesLength < 8 {
bytesToPad := 8 - inBytesLength
for i := 0; i < bytesToPad; i++ {
inBytes = append(inBytes, 0xff)
}
}
} else {
if inBytesLength < 8 {
bytesToPad := 8 - inBytesLength
for i := 0; i < bytesToPad; i++ {
inBytes = append(inBytes, 0x00)
}
}
}
outInt64 = int64(binary.LittleEndian.Uint64(inBytes))
return
}
// LittleEndianBinaryToUInt64 converts a little endian byte slice to uint64.
func LittleEndianBinaryToUInt64(inBytes []byte) (outUInt64 uint64, err error) {
inBytesLength := len(inBytes)
if inBytesLength > 8 || inBytesLength == 0 {
err = fmt.Errorf("LittleEndianBinaryToUInt64() received %d bytes but expected 1-8 bytes", inBytesLength)
outUInt64 = 0
return
}
// Pad it to get to 8 bytes
if inBytesLength < 8 {
bytesToPad := 8 - inBytesLength
for i := 0; i < bytesToPad; i++ {
inBytes = append(inBytes, 0x00)
}
}
outUInt64 = binary.LittleEndian.Uint64(inBytes)
return
}
// LittleEndianBinaryToUInt16 converts a little endian byte slice to uint16.
func LittleEndianBinaryToUInt16(inBytes []byte) (outUInt16 uint16, err error) {
inBytesLength := len(inBytes)
if inBytesLength != 2 {
err = fmt.Errorf("LittleEndianBinaryToUInt16() received %d bytes but expected 2 bytes", inBytesLength)
outUInt16 = 0
return
}
outUInt16 = binary.LittleEndian.Uint16(inBytes)
return
}
// LittleEndianBinaryToUInt32 converts a little endian byte slice to uint32.
func LittleEndianBinaryToUInt32(inBytes []byte) (outUInt32 uint32, err error) {
inBytesLength := len(inBytes)
if inBytesLength != 4 {
err = fmt.Errorf("LittleEndianBinaryToUInt32() received %d bytes but expected 4 bytes", inBytesLength)
outUInt32 = 0
return
}
outUInt32 = binary.LittleEndian.Uint32(inBytes)
return
}
// UnicodeBytesToASCII converts a byte slice of unicode characters to ASCII
func UnicodeBytesToASCII(unicodeBytes []byte) (asciiString string, err error) {
inBytesLength := len(unicodeBytes)
if inBytesLength == 0 {
err = errors.New("UnicodeBytesToASCII() received no bytes")
asciiString = ""
return
}
unicodeString := string(unicodeBytes)
asciiString = strings.Replace(unicodeString, "\x00", "", -1)
return
} | binarytransforms.go | 0.659076 | 0.44348 | binarytransforms.go | starcoder |
package workshop
import (
"errors"
"log"
"math"
"strconv"
)
func add2Numbers(x, y int) int {
return x + y
}
func printFormattedResponse(name string) string {
return name + " hello there"
}
func wordSwap(word1, word2 string) (string, string) {
return word2, word1
}
func nakedReturn(x, y, z *int) (x1, y1, z1 int) {
*x++
*y++
*z++
x1 = *x * 2
y1 = *y * 3
z1 = *z * 4
return
}
func giveErrorIfEmpty(str string) (string, error) {
if str == "" {
error := errors.New("You must pass a string")
return str, error
}
return str, nil
}
func hypotenuse(x, y float64) float64 {
return math.Sqrt(x*x + y*y)
}
func summation(args ...int) int {
sum := 0
for _, val := range args {
sum += val
}
return sum
}
func format2DecimalPlaces(num float64) string {
str := strconv.FormatFloat(num, 'f', 2, 64)
return str
}
func distanceOfLine(x1, y1, x2, y2 float64) func() string {
var distance float64
return func() string {
distance = math.Sqrt(math.Pow(x2-x1, 2) + math.Pow(y2-y1, 2))
return format2DecimalPlaces(distance)
}
}
func functions() {
adder := add2Numbers(5, 7)
assert(adder == 12)
formatResponse := printFormattedResponse("Jane")
assert(formatResponse == "Jane hello there")
summer := func(numbers []int) int {
sum := 0
for i := 0; i < len(numbers); i++ {
sum += numbers[i]
}
return sum
}
numbers := []int{
1, 2, 3, 4, 5, 6, 7,
}
sumEmUp := summer(numbers)
assert(sumEmUp == 28)
lastName, firstName := wordSwap("marcel", "belmont")
assert(lastName == "belmont" && firstName == "marcel")
x, y, z := 1, 2, 3
x2, y2, z2 := nakedReturn(&x, &y, &z)
assert(x2 == 4 && y2 == 9 && z2 == 16)
_, err := giveErrorIfEmpty("")
assert(err.Error() == "You must pass a string")
str, err := giveErrorIfEmpty("hello")
if err != nil {
log.Fatal(err)
}
assert(str == "hello")
hyp := hypotenuse(3, 4)
assert(hyp == 5)
sum1 := summation(1, 2, 3)
assert(sum1 == 6)
sum2 := summation()
assert(sum2 == 0)
distance := distanceOfLine(3, 4, 5, 6)
assert(distance() == "2.83")
} | functions.go | 0.718199 | 0.412234 | functions.go | starcoder |
package stats
import "time"
// MovingAverage models a series of arbitrary uint64 values placed equidistantly in the time domain.
type MovingAverage struct {
totals []uint64
maxTotals int
sampleInterval time.Duration // TODO: Don't terminologically restrict the moving average to the time domain.
sampleFunc func() uint64
}
// NewMovingAverage constructs a new MovingAverage with given sample count limit, given assumed sample interval
// and given sample function.
func NewMovingAverage(maxSampleCount int, sampleInterval time.Duration, sampleFunc func() uint64) *MovingAverage {
return &MovingAverage{maxTotals: maxSampleCount + 1, sampleInterval: sampleInterval, sampleFunc: sampleFunc}
}
// TakeSample calls the sample function the MovingAverage was constructed with using NewMovingAverage
// and stores the returned value internally, discarding any old values
func (ma *MovingAverage) TakeSample() {
currentTotal := ma.sampleFunc()
if len(ma.totals) >= ma.maxTotals {
ma.totals = append(ma.totals[1:], currentTotal)
} else {
ma.totals = append(ma.totals, currentTotal)
}
}
// AveragePerSecondDelta returns the average per-second change from sample to sample using all available samples.
func (ma *MovingAverage) AveragePerSecondDelta() float64 {
if len(ma.totals) == 0 {
return 0
}
var availableDeltaCount int
var samplesDelta float64
if len(ma.totals) == 1 {
availableDeltaCount = 1
samplesDelta = float64(ma.totals[0])
} else if len(ma.totals) < ma.maxTotals {
availableDeltaCount = len(ma.totals)
samplesDelta = float64(ma.totals[len(ma.totals)-1])
} else {
availableDeltaCount = len(ma.totals) - 1
samplesDelta = float64(ma.totals[len(ma.totals)-1] - ma.totals[0])
}
samplesDeltaDuration := ma.sampleInterval.Seconds() * float64(availableDeltaCount)
changePerSecond := samplesDelta / samplesDeltaDuration
return changePerSecond
}
// TODO: Principally, something like AverageTotal() would be nice to have as well, but isn't needed for trivrost.
// Total returns the most recent value sampled by TakeSample(), or 0 if it has not been called yet.
func (ma *MovingAverage) Total() uint64 {
if ma.totals == nil {
return 0
}
return ma.totals[len(ma.totals)-1]
}
// Reset returns this moving average to its initial state, as if it had just been returned from NewMovingAverage().
func (ma *MovingAverage) Reset() {
ma.totals = nil
} | pkg/stats/moving_average.go | 0.517815 | 0.539954 | moving_average.go | starcoder |
package v1alpha1
import (
v1alpha1 "kubeform.dev/kubeform/apis/aws/v1alpha1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache"
)
// WafregionalRateBasedRuleLister helps list WafregionalRateBasedRules.
type WafregionalRateBasedRuleLister interface {
// List lists all WafregionalRateBasedRules in the indexer.
List(selector labels.Selector) (ret []*v1alpha1.WafregionalRateBasedRule, err error)
// WafregionalRateBasedRules returns an object that can list and get WafregionalRateBasedRules.
WafregionalRateBasedRules(namespace string) WafregionalRateBasedRuleNamespaceLister
WafregionalRateBasedRuleListerExpansion
}
// wafregionalRateBasedRuleLister implements the WafregionalRateBasedRuleLister interface.
type wafregionalRateBasedRuleLister struct {
indexer cache.Indexer
}
// NewWafregionalRateBasedRuleLister returns a new WafregionalRateBasedRuleLister.
func NewWafregionalRateBasedRuleLister(indexer cache.Indexer) WafregionalRateBasedRuleLister {
return &wafregionalRateBasedRuleLister{indexer: indexer}
}
// List lists all WafregionalRateBasedRules in the indexer.
func (s *wafregionalRateBasedRuleLister) List(selector labels.Selector) (ret []*v1alpha1.WafregionalRateBasedRule, err error) {
err = cache.ListAll(s.indexer, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.WafregionalRateBasedRule))
})
return ret, err
}
// WafregionalRateBasedRules returns an object that can list and get WafregionalRateBasedRules.
func (s *wafregionalRateBasedRuleLister) WafregionalRateBasedRules(namespace string) WafregionalRateBasedRuleNamespaceLister {
return wafregionalRateBasedRuleNamespaceLister{indexer: s.indexer, namespace: namespace}
}
// WafregionalRateBasedRuleNamespaceLister helps list and get WafregionalRateBasedRules.
type WafregionalRateBasedRuleNamespaceLister interface {
// List lists all WafregionalRateBasedRules in the indexer for a given namespace.
List(selector labels.Selector) (ret []*v1alpha1.WafregionalRateBasedRule, err error)
// Get retrieves the WafregionalRateBasedRule from the indexer for a given namespace and name.
Get(name string) (*v1alpha1.WafregionalRateBasedRule, error)
WafregionalRateBasedRuleNamespaceListerExpansion
}
// wafregionalRateBasedRuleNamespaceLister implements the WafregionalRateBasedRuleNamespaceLister
// interface.
type wafregionalRateBasedRuleNamespaceLister struct {
indexer cache.Indexer
namespace string
}
// List lists all WafregionalRateBasedRules in the indexer for a given namespace.
func (s wafregionalRateBasedRuleNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.WafregionalRateBasedRule, err error) {
err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {
ret = append(ret, m.(*v1alpha1.WafregionalRateBasedRule))
})
return ret, err
}
// Get retrieves the WafregionalRateBasedRule from the indexer for a given namespace and name.
func (s wafregionalRateBasedRuleNamespaceLister) Get(name string) (*v1alpha1.WafregionalRateBasedRule, error) {
obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name)
if err != nil {
return nil, err
}
if !exists {
return nil, errors.NewNotFound(v1alpha1.Resource("wafregionalratebasedrule"), name)
}
return obj.(*v1alpha1.WafregionalRateBasedRule), nil
} | client/listers/aws/v1alpha1/wafregionalratebasedrule.go | 0.59302 | 0.449634 | wafregionalratebasedrule.go | starcoder |
package testinggo
import (
"aletheiaware.com/cryptogo"
"bytes"
"crypto/rsa"
"encoding/base64"
"github.com/golang/protobuf/proto"
"regexp"
"testing"
)
func AssertNoError(t *testing.T, err error) {
t.Helper()
if err != nil {
t.Fatalf("Expected no error, instead got '%s'", err)
}
}
func AssertError(t *testing.T, expected string, err error) {
t.Helper()
if err == nil {
t.Fatalf("Expected error '%s'", expected)
} else if err.Error() != expected {
t.Fatalf("Expected error '%s', instead got '%s'", expected, err)
}
}
func AssertMatchesError(t *testing.T, expected string, err error) {
t.Helper()
if err == nil {
t.Fatalf("Expected error '%s'", expected)
} else {
match, _ := regexp.MatchString(expected, err.Error())
if !match {
t.Fatalf("Expected error '%s', instead got '%s'", expected, err)
}
}
}
func AssertHashEqual(t *testing.T, expected, actual []byte) {
t.Helper()
if !bytes.Equal(expected, actual) {
t.Fatalf("Wrong hash: expected '%s', instead got '%s'", base64.RawURLEncoding.EncodeToString(expected), base64.RawURLEncoding.EncodeToString(actual))
}
}
func AssertProtobufEqual(t *testing.T, expected, actual proto.Message) {
t.Helper()
es := expected.String()
as := actual.String()
if es != as {
t.Fatalf("Wrong protobuf: expected '%s', instead got '%s'", es, as)
}
}
func AssertPrivateKeyEqual(t *testing.T, expected, actual *rsa.PrivateKey) {
t.Helper()
hash := cryptogo.Hash([]byte("abcdefghijklmnopqrstuvwxyz"))
expectedSignature, err := cryptogo.CreateSignature(cryptogo.SignatureAlgorithm_SHA512WITHRSA_PSS, expected, hash)
AssertNoError(t, err)
AssertNoError(t, cryptogo.VerifySignature(cryptogo.SignatureAlgorithm_SHA512WITHRSA_PSS, &actual.PublicKey, hash, expectedSignature))
actualSignature, err := cryptogo.CreateSignature(cryptogo.SignatureAlgorithm_SHA512WITHRSA_PSS, actual, hash)
AssertNoError(t, err)
AssertNoError(t, cryptogo.VerifySignature(cryptogo.SignatureAlgorithm_SHA512WITHRSA_PSS, &expected.PublicKey, hash, actualSignature))
} | assert.go | 0.59302 | 0.472379 | assert.go | starcoder |
package archive
import (
"gocms/pkg/page"
"sort"
"time"
)
// Record type that allows us to use a common index value for the various kinds of archive lists, be they in a map or a slice.
// Then it is easy to sort the order of the lists.
// Ranging over a map in Go is in a random order by design, and before, I used a mix of index types (int and time.Month).
type Record struct {
Count int // This represents the number of records in the current map
Month time.Month // This is only used when we want to record the related time.Month value
Posts []page.Info // This is only used when we want to record a list of relevant pages
}
// GetYears - get a map of years containing posts with the post count
func GetYears() map[int]Record {
years := make(map[int]Record)
pages := page.GetAllPages()
for _, p := range pages {
if p.Status == page.Published && p.Template == "post" {
year := p.PubDate.Year()
r, present := years[year]
if present {
r.Count++
} else {
r = Record{Count: 1}
}
years[year] = r
}
}
return years
}
// GetMonths - get a map of months containing posts with the post count
func GetMonths(year int) map[int]Record {
months := make(map[int]Record)
pages := page.GetAllPages()
for _, p := range pages {
if p.PubDate.Year() == year && p.Status == page.Published && p.Template == "post" {
month := p.PubDate.Month()
r, present := months[int(month)]
if present {
r.Count++
} else {
r = Record{Count: 1}
}
r.Month = month
months[int(month)] = r
}
}
return months
}
// GetDays - get a map of days containing posts, and the post meta data for a given year, month
func GetDays(year int, month time.Month) map[int]Record {
days := make(map[int]Record)
pages := page.GetAllPages()
for _, p := range pages {
if p.PubDate.Year() == year && p.PubDate.Month() == month && p.Status == page.Published && p.Template == "post" {
day := p.PubDate.Day()
r, present := days[day]
if present {
r.Count++
} else {
r = Record{Count: 1}
}
r.Posts = append(r.Posts, p)
days[day] = r
}
}
return days
}
// GetKeysInOrder returns a sorted slice of map keys, since ranging over a map is done in a random order.
// We need this []int to index into the map in order to render ordered lists.
func GetKeysInOrder(items map[int]Record) []int {
// Make slice to store keys
keys := make([]int, len(items))
// Add the map keys to the slice
i := 0
for k := range items {
keys[i] = k
i++
}
sort.Ints(keys)
return keys
} | pkg/archive/archive.go | 0.599368 | 0.460471 | archive.go | starcoder |
Package gofpdf implements a PDF document generator with high level support for
text, drawing and images.
Features
• Choice of measurement unit, page format and margins
• Page header and footer management
• Automatic page breaks, line breaks, and text justification
• Inclusion of JPEG, PNG, GIF and basic path-only SVG images
• Colors, gradients and alpha channel transparency
• Outline bookmarks
• Internal and external links
• TrueType, Type1 and encoding support
• Page compression
• Lines, Bézier curves, arcs, and ellipses
• Rotation, scaling, skewing, translation, and mirroring
• Clipping
• Document protection
• Layers
gofpdf has no dependencies other than the Go standard library. All tests pass
on Linux, Mac and Windows platforms. Like FPDF version 1.7, from which gofpdf
is derived, this package does not yet support UTF-8 fonts. However, support is
provided to translate UTF-8 runes to code page encodings.
Installation
To install the package on your system, run
go get github.com/jung-kurt/gofpdf
Later, to receive updates, run
go get -u github.com/jung-kurt/gofpdf
Quick Start
The following Go code generates a simple PDF file.
pdf := gofpdf.New("P", "mm", "A4", "")
pdf.AddPage()
pdf.SetFont("Arial", "B", 16)
pdf.Cell(40, 10, "Hello, world")
err := pdf.OutputFileAndClose("hello.pdf")
See the functions in the fpdf_test.go file (shown as examples in this
documentation) for more advanced PDF examples.
Errors
If an error occurs in an Fpdf method, an internal error field is set. After
this occurs, Fpdf method calls typically return without performing any
operations and the error state is retained. This error management scheme
facilitates PDF generation since individual method calls do not need to be
examined for failure; it is generally sufficient to wait until after Output()
is called. For the same reason, if an error occurs in the calling application
during PDF generation, it may be desirable for the application to transfer the
error to the Fpdf instance by calling the SetError() method or the SetErrorf()
method. At any time during the life cycle of the Fpdf instance, the error state
can be determined with a call to Ok() or Err(). The error itself can be
retrieved with a call to Error().
Conversion Notes
This package is a relatively straightforward translation from the original FPDF
library written in PHP (despite the caveat in the introduction to Effective
Go). The API names have been retained even though the Go idiom would suggest
otherwise (for example, pdf.GetX() is used rather than simply pdf.X()). The
similarity of the two libraries makes the original FPDF website a good source
of information. It includes a forum and FAQ.
However, some internal changes have been made. Page content is built up using
buffers (of type bytes.Buffer) rather than repeated string concatenation.
Errors are handled as explained above rather than panicking. Output is
generated through an interface of type io.Writer or io.WriteCloser. A number of
the original PHP methods behave differently based on the type of the arguments
that are passed to them; in these cases additional methods have been exported
to provide similar functionality. Font definition files are produced in JSON
rather than PHP.
Example PDFs
A side effect of running "go test" is the production of a number of example
PDFs. These can be found in the gofpdf/pdf directory after the tests complete.
Please note that these examples run in the context of a test. In order run an
example as a standalone application, you'll need to examine fpdf_test.go for
some helper routines, for example exampleFilename and summary.
Nonstandard Fonts
Nothing special is required to use the standard PDF fonts (courier, helvetica,
times, zapfdingbats) in your documents other than calling SetFont().
In order to use a different TrueType or Type1 font, you will need to generate a
font definition file and, if the font will be embedded into PDFs, a compressed
version of the font file. This is done by calling the MakeFont function or
using the included makefont command line utility. To create the utility, cd
into the makefont subdirectory and run "go build". This will produce a
standalone executable named makefont. Select the appropriate encoding file from
the font subdirectory and run the command as in the following example.
./makefont --embed --enc=../font/cp1252.map --dst=../font ../font/calligra.ttf
In your PDF generation code, call AddFont() to load the font and, as with the
standard fonts, SetFont() to begin using it. Most examples, including the
package example, demonstrate this method. Good sources of free, open-source
fonts include http://www.google.com/fonts/ and http://dejavu-fonts.org/.
Related Packages
The draw2d package (https://github.com/llgcode/draw2d) is a two dimensional
vector graphics library that can generate output in different forms. It uses
gofpdf for its document production mode.
Contributing Changes
gofpdf is a global community effort and you are invited to make it even better.
If you have implemented a new feature or corrected a problem, please consider
contributing your change to the project. Here are guidelines for making
submissions. Your change should
• be compatible with the MIT License
• be properly documented
• include an example in fpdf_test.go if appropriate
• conform to the standards of golint (https://github.com/golang/lint) and
go vet (https://godoc.org/golang.org/x/tools/cmd/vet), that is, `golint .` and
`go vet .` should not generate any warnings
• not diminish test coverage (https://blog.golang.org/cover)
Pull requests (https://help.github.com/articles/using-pull-requests/) work
nicely as a means of contributing your changes.
License
gofpdf is released under the MIT License. It is copyrighted by <NAME> and
the contributors acknowledged below.
Acknowledgments
This package's code and documentation are closely derived from the FPDF library
(http://www.fpdf.org/) created by <NAME>, and a number of font and
image resources are copied directly from it. Drawing support is adapted from
the FPDF geometric figures script by <NAME>. Transparency
support is adapted from the FPDF transparency script by <NAME>.
Support for gradients and clipping is adapted from FPDF scripts by Andreas
Würmser. Support for outline bookmarks is adapted from Olivier Plathey by
<NAME>. Layer support is adapted from Olivier Plathey. Support for
transformations is adapted from the FPDF transformation script by <NAME>
and <NAME>. PDF protection is adapted from the work of Klemen
Vodopivec for the FPDF product. Lawrence Kesteloot provided code to allow an
image's extent to be determined prior to placement. Support for vertical
alignment within a cell was provided by <NAME>. <NAME>
generalized the font and image loading code to use the Reader interface while
maintaining backward compatibility. <NAME> provided code for the
Polygon function. <NAME> provided the Beziergon function and corrected
some naming issues with the internal curve function. <NAME> provided
implementations for dashed line drawing and generalized font loading. <NAME> provided support for multi-segment path drawing with smooth line
joins, line join styles, enhanced fill modes, and has helped greatly with
package presentation and tests. <NAME> has provided valuable assistance
with the code.
Roadmap
• Handle UTF-8 source text natively. Until then, automatic translation of
UTF-8 runes to code page bytes is provided.
• Improve test coverage as reported by the coverage tool.
*/
package gofpdf | doc.go | 0.774669 | 0.739069 | doc.go | starcoder |
package graph
import (
"fmt"
"sync"
"github.com/pkg/errors"
)
const (
rootNodeID = "acb_root"
)
// Node represents a vertex in a Dag.
type Node struct {
Name string
Value *Step
children map[string]*Node
mu sync.Mutex
degree int
}
// NewNode creates a new Node based on the provided name and value.
func NewNode(value *Step) *Node {
return &Node{
Name: value.ID,
Value: value,
children: make(map[string]*Node),
mu: sync.Mutex{},
degree: 0,
}
}
// GetDegree returns the degree of the node.
func (n *Node) GetDegree() int {
n.mu.Lock()
defer n.mu.Unlock()
return n.degree
}
// Dag represents a thread safe directed acyclic graph.
type Dag struct {
Root *Node
Nodes map[string]*Node
mu sync.Mutex
}
// NewDag creates a new Dag with a root vertex.
func NewDag() *Dag {
dag := new(Dag)
dag.Nodes = make(map[string]*Node)
dag.Root = NewNode(&Step{ID: rootNodeID})
return dag
}
// NewDagFromTask creates a new Dag based on the specified Task.
func NewDagFromTask(t *Task) (*Dag, error) {
dag := NewDag()
var prevStep *Step
for _, step := range t.Steps {
if err := step.Validate(); err != nil {
return dag, err
}
if _, err := dag.AddVertex(step); err != nil {
return dag, err
}
// If the step is parallel, add it to the root
if step.ShouldExecuteImmediately() {
if err := dag.AddEdge(rootNodeID, step.ID); err != nil {
return dag, err
}
} else if step.HasNoWhen() {
// If the step has no when, add it to the root or the previous step
if prevStep == nil {
if err := dag.AddEdge(rootNodeID, step.ID); err != nil {
return dag, err
}
} else {
if err := dag.AddEdge(prevStep.ID, step.ID); err != nil {
return dag, err
}
}
} else {
// Otherwise, add edges according to when
for _, dep := range step.When {
if err := dag.AddEdge(dep, step.ID); err != nil {
return dag, err
}
}
}
prevStep = step
}
return dag, nil
}
// AddVertex adds a vertex to the Dag with the specified name and value.
func (d *Dag) AddVertex(value *Step) (*Node, error) {
if value.ID == rootNodeID {
return nil, fmt.Errorf("%v is a reserved ID, it can't be used", rootNodeID)
}
d.mu.Lock()
defer d.mu.Unlock()
if _, ok := d.Nodes[value.ID]; ok {
return nil, fmt.Errorf("%s already exists as a vertex", value.ID)
}
n := NewNode(value)
d.Nodes[value.ID] = n
return n, nil
}
// AddEdge adds an edge between from and to.
func (d *Dag) AddEdge(from string, to string) error {
fromNode, toNode, err := d.validateFromAndTo(from, to)
if err != nil {
return err
}
fromNode.mu.Lock()
fromNode.children[to] = toNode
fromNode.mu.Unlock()
toNode.mu.Lock()
toNode.degree++
toNode.mu.Unlock()
return nil
}
// RemoveEdge removes the edge between from and to.
func (d *Dag) RemoveEdge(from string, to string) error {
fromNode, toNode, err := d.validateFromAndTo(from, to)
if err != nil {
return err
}
fromNode.mu.Lock()
delete(fromNode.children, to)
fromNode.mu.Unlock()
toNode.mu.Lock()
toNode.degree--
toNode.mu.Unlock()
return nil
}
// Children returns the node's children.
func (n *Node) Children() []*Node {
childNodes := make([]*Node, 0, len(n.children))
n.mu.Lock()
defer n.mu.Unlock()
for _, v := range n.children {
childNodes = append(childNodes, v)
}
return childNodes
}
func (d *Dag) validateFromAndTo(from string, to string) (*Node, *Node, error) {
if from == "" {
return nil, nil, errors.New("from cannot be empty")
}
if to == "" {
return nil, nil, errors.New("to cannot be empty")
}
if from == to {
return nil, nil, errors.New("from and to cannot be the same")
}
d.mu.Lock()
defer d.mu.Unlock()
var fromNode *Node
if from == rootNodeID {
fromNode = d.Root
} else {
var ok bool
if fromNode, ok = d.Nodes[from]; !ok {
return nil, nil, fmt.Errorf("%v does not exist as a vertex [from: %v, to: %v]", from, from, to)
}
}
toNode, ok := d.Nodes[to]
if !ok {
return nil, nil, fmt.Errorf("%v does not exist as a vertex [from: %v, to: %v]", to, from, to)
}
return fromNode, toNode, nil
} | graph/dag.go | 0.738575 | 0.435001 | dag.go | starcoder |
package v3
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"strings"
"github.com/golang/protobuf/proto"
equality "github.com/solo-io/protoc-gen-ext/pkg/equality"
)
// ensure the imports are used
var (
_ = errors.New("")
_ = fmt.Print
_ = binary.LittleEndian
_ = bytes.Compare
_ = strings.Compare
_ = equality.Equalizer(nil)
_ = proto.Message(nil)
)
// Equal function
func (m *HealthCheck) Equal(that interface{}) bool {
if that == nil {
return m == nil
}
target, ok := that.(*HealthCheck)
if !ok {
that2, ok := that.(HealthCheck)
if ok {
target = &that2
} else {
return false
}
}
if target == nil {
return m == nil
} else if m == nil {
return false
}
if h, ok := interface{}(m.GetTimeout()).(equality.Equalizer); ok {
if !h.Equal(target.GetTimeout()) {
return false
}
} else {
if !proto.Equal(m.GetTimeout(), target.GetTimeout()) {
return false
}
}
if h, ok := interface{}(m.GetInterval()).(equality.Equalizer); ok {
if !h.Equal(target.GetInterval()) {
return false
}
} else {
if !proto.Equal(m.GetInterval(), target.GetInterval()) {
return false
}
}
if h, ok := interface{}(m.GetInitialJitter()).(equality.Equalizer); ok {
if !h.Equal(target.GetInitialJitter()) {
return false
}
} else {
if !proto.Equal(m.GetInitialJitter(), target.GetInitialJitter()) {
return false
}
}
if h, ok := interface{}(m.GetIntervalJitter()).(equality.Equalizer); ok {
if !h.Equal(target.GetIntervalJitter()) {
return false
}
} else {
if !proto.Equal(m.GetIntervalJitter(), target.GetIntervalJitter()) {
return false
}
}
if m.GetIntervalJitterPercent() != target.GetIntervalJitterPercent() {
return false
}
if h, ok := interface{}(m.GetUnhealthyThreshold()).(equality.Equalizer); ok {
if !h.Equal(target.GetUnhealthyThreshold()) {
return false
}
} else {
if !proto.Equal(m.GetUnhealthyThreshold(), target.GetUnhealthyThreshold()) {
return false
}
}
if h, ok := interface{}(m.GetHealthyThreshold()).(equality.Equalizer); ok {
if !h.Equal(target.GetHealthyThreshold()) {
return false
}
} else {
if !proto.Equal(m.GetHealthyThreshold(), target.GetHealthyThreshold()) {
return false
}
}
if h, ok := interface{}(m.GetAltPort()).(equality.Equalizer); ok {
if !h.Equal(target.GetAltPort()) {
return false
}
} else {
if !proto.Equal(m.GetAltPort(), target.GetAltPort()) {
return false
}
}
if h, ok := interface{}(m.GetReuseConnection()).(equality.Equalizer); ok {
if !h.Equal(target.GetReuseConnection()) {
return false
}
} else {
if !proto.Equal(m.GetReuseConnection(), target.GetReuseConnection()) {
return false
}
}
if h, ok := interface{}(m.GetNoTrafficInterval()).(equality.Equalizer); ok {
if !h.Equal(target.GetNoTrafficInterval()) {
return false
}
} else {
if !proto.Equal(m.GetNoTrafficInterval(), target.GetNoTrafficInterval()) {
return false
}
}
if h, ok := interface{}(m.GetUnhealthyInterval()).(equality.Equalizer); ok {
if !h.Equal(target.GetUnhealthyInterval()) {
return false
}
} else {
if !proto.Equal(m.GetUnhealthyInterval(), target.GetUnhealthyInterval()) {
return false
}
}
if h, ok := interface{}(m.GetUnhealthyEdgeInterval()).(equality.Equalizer); ok {
if !h.Equal(target.GetUnhealthyEdgeInterval()) {
return false
}
} else {
if !proto.Equal(m.GetUnhealthyEdgeInterval(), target.GetUnhealthyEdgeInterval()) {
return false
}
}
if h, ok := interface{}(m.GetHealthyEdgeInterval()).(equality.Equalizer); ok {
if !h.Equal(target.GetHealthyEdgeInterval()) {
return false
}
} else {
if !proto.Equal(m.GetHealthyEdgeInterval(), target.GetHealthyEdgeInterval()) {
return false
}
}
if strings.Compare(m.GetEventLogPath(), target.GetEventLogPath()) != 0 {
return false
}
if h, ok := interface{}(m.GetEventService()).(equality.Equalizer); ok {
if !h.Equal(target.GetEventService()) {
return false
}
} else {
if !proto.Equal(m.GetEventService(), target.GetEventService()) {
return false
}
}
if m.GetAlwaysLogHealthCheckFailures() != target.GetAlwaysLogHealthCheckFailures() {
return false
}
if h, ok := interface{}(m.GetTlsOptions()).(equality.Equalizer); ok {
if !h.Equal(target.GetTlsOptions()) {
return false
}
} else {
if !proto.Equal(m.GetTlsOptions(), target.GetTlsOptions()) {
return false
}
}
if h, ok := interface{}(m.GetTransportSocketMatchCriteria()).(equality.Equalizer); ok {
if !h.Equal(target.GetTransportSocketMatchCriteria()) {
return false
}
} else {
if !proto.Equal(m.GetTransportSocketMatchCriteria(), target.GetTransportSocketMatchCriteria()) {
return false
}
}
switch m.HealthChecker.(type) {
case *HealthCheck_HttpHealthCheck_:
if _, ok := target.HealthChecker.(*HealthCheck_HttpHealthCheck_); !ok {
return false
}
if h, ok := interface{}(m.GetHttpHealthCheck()).(equality.Equalizer); ok {
if !h.Equal(target.GetHttpHealthCheck()) {
return false
}
} else {
if !proto.Equal(m.GetHttpHealthCheck(), target.GetHttpHealthCheck()) {
return false
}
}
case *HealthCheck_TcpHealthCheck_:
if _, ok := target.HealthChecker.(*HealthCheck_TcpHealthCheck_); !ok {
return false
}
if h, ok := interface{}(m.GetTcpHealthCheck()).(equality.Equalizer); ok {
if !h.Equal(target.GetTcpHealthCheck()) {
return false
}
} else {
if !proto.Equal(m.GetTcpHealthCheck(), target.GetTcpHealthCheck()) {
return false
}
}
case *HealthCheck_GrpcHealthCheck_:
if _, ok := target.HealthChecker.(*HealthCheck_GrpcHealthCheck_); !ok {
return false
}
if h, ok := interface{}(m.GetGrpcHealthCheck()).(equality.Equalizer); ok {
if !h.Equal(target.GetGrpcHealthCheck()) {
return false
}
} else {
if !proto.Equal(m.GetGrpcHealthCheck(), target.GetGrpcHealthCheck()) {
return false
}
}
case *HealthCheck_CustomHealthCheck_:
if _, ok := target.HealthChecker.(*HealthCheck_CustomHealthCheck_); !ok {
return false
}
if h, ok := interface{}(m.GetCustomHealthCheck()).(equality.Equalizer); ok {
if !h.Equal(target.GetCustomHealthCheck()) {
return false
}
} else {
if !proto.Equal(m.GetCustomHealthCheck(), target.GetCustomHealthCheck()) {
return false
}
}
default:
// m is nil but target is not nil
if m.HealthChecker != target.HealthChecker {
return false
}
}
return true
}
// Equal function
func (m *HealthCheck_Payload) Equal(that interface{}) bool {
if that == nil {
return m == nil
}
target, ok := that.(*HealthCheck_Payload)
if !ok {
that2, ok := that.(HealthCheck_Payload)
if ok {
target = &that2
} else {
return false
}
}
if target == nil {
return m == nil
} else if m == nil {
return false
}
switch m.Payload.(type) {
case *HealthCheck_Payload_Text:
if _, ok := target.Payload.(*HealthCheck_Payload_Text); !ok {
return false
}
if strings.Compare(m.GetText(), target.GetText()) != 0 {
return false
}
case *HealthCheck_Payload_Binary:
if _, ok := target.Payload.(*HealthCheck_Payload_Binary); !ok {
return false
}
if bytes.Compare(m.GetBinary(), target.GetBinary()) != 0 {
return false
}
default:
// m is nil but target is not nil
if m.Payload != target.Payload {
return false
}
}
return true
}
// Equal function
func (m *HealthCheck_HttpHealthCheck) Equal(that interface{}) bool {
if that == nil {
return m == nil
}
target, ok := that.(*HealthCheck_HttpHealthCheck)
if !ok {
that2, ok := that.(HealthCheck_HttpHealthCheck)
if ok {
target = &that2
} else {
return false
}
}
if target == nil {
return m == nil
} else if m == nil {
return false
}
if strings.Compare(m.GetHost(), target.GetHost()) != 0 {
return false
}
if strings.Compare(m.GetPath(), target.GetPath()) != 0 {
return false
}
if h, ok := interface{}(m.GetSend()).(equality.Equalizer); ok {
if !h.Equal(target.GetSend()) {
return false
}
} else {
if !proto.Equal(m.GetSend(), target.GetSend()) {
return false
}
}
if h, ok := interface{}(m.GetReceive()).(equality.Equalizer); ok {
if !h.Equal(target.GetReceive()) {
return false
}
} else {
if !proto.Equal(m.GetReceive(), target.GetReceive()) {
return false
}
}
if len(m.GetRequestHeadersToAdd()) != len(target.GetRequestHeadersToAdd()) {
return false
}
for idx, v := range m.GetRequestHeadersToAdd() {
if h, ok := interface{}(v).(equality.Equalizer); ok {
if !h.Equal(target.GetRequestHeadersToAdd()[idx]) {
return false
}
} else {
if !proto.Equal(v, target.GetRequestHeadersToAdd()[idx]) {
return false
}
}
}
if len(m.GetRequestHeadersToRemove()) != len(target.GetRequestHeadersToRemove()) {
return false
}
for idx, v := range m.GetRequestHeadersToRemove() {
if strings.Compare(v, target.GetRequestHeadersToRemove()[idx]) != 0 {
return false
}
}
if len(m.GetExpectedStatuses()) != len(target.GetExpectedStatuses()) {
return false
}
for idx, v := range m.GetExpectedStatuses() {
if h, ok := interface{}(v).(equality.Equalizer); ok {
if !h.Equal(target.GetExpectedStatuses()[idx]) {
return false
}
} else {
if !proto.Equal(v, target.GetExpectedStatuses()[idx]) {
return false
}
}
}
if m.GetCodecClientType() != target.GetCodecClientType() {
return false
}
if h, ok := interface{}(m.GetServiceNameMatcher()).(equality.Equalizer); ok {
if !h.Equal(target.GetServiceNameMatcher()) {
return false
}
} else {
if !proto.Equal(m.GetServiceNameMatcher(), target.GetServiceNameMatcher()) {
return false
}
}
if h, ok := interface{}(m.GetResponseAssertions()).(equality.Equalizer); ok {
if !h.Equal(target.GetResponseAssertions()) {
return false
}
} else {
if !proto.Equal(m.GetResponseAssertions(), target.GetResponseAssertions()) {
return false
}
}
return true
}
// Equal function
func (m *HealthCheck_TcpHealthCheck) Equal(that interface{}) bool {
if that == nil {
return m == nil
}
target, ok := that.(*HealthCheck_TcpHealthCheck)
if !ok {
that2, ok := that.(HealthCheck_TcpHealthCheck)
if ok {
target = &that2
} else {
return false
}
}
if target == nil {
return m == nil
} else if m == nil {
return false
}
if h, ok := interface{}(m.GetSend()).(equality.Equalizer); ok {
if !h.Equal(target.GetSend()) {
return false
}
} else {
if !proto.Equal(m.GetSend(), target.GetSend()) {
return false
}
}
if len(m.GetReceive()) != len(target.GetReceive()) {
return false
}
for idx, v := range m.GetReceive() {
if h, ok := interface{}(v).(equality.Equalizer); ok {
if !h.Equal(target.GetReceive()[idx]) {
return false
}
} else {
if !proto.Equal(v, target.GetReceive()[idx]) {
return false
}
}
}
return true
}
// Equal function
func (m *HealthCheck_RedisHealthCheck) Equal(that interface{}) bool {
if that == nil {
return m == nil
}
target, ok := that.(*HealthCheck_RedisHealthCheck)
if !ok {
that2, ok := that.(HealthCheck_RedisHealthCheck)
if ok {
target = &that2
} else {
return false
}
}
if target == nil {
return m == nil
} else if m == nil {
return false
}
if strings.Compare(m.GetKey(), target.GetKey()) != 0 {
return false
}
return true
}
// Equal function
func (m *HealthCheck_GrpcHealthCheck) Equal(that interface{}) bool {
if that == nil {
return m == nil
}
target, ok := that.(*HealthCheck_GrpcHealthCheck)
if !ok {
that2, ok := that.(HealthCheck_GrpcHealthCheck)
if ok {
target = &that2
} else {
return false
}
}
if target == nil {
return m == nil
} else if m == nil {
return false
}
if strings.Compare(m.GetServiceName(), target.GetServiceName()) != 0 {
return false
}
if strings.Compare(m.GetAuthority(), target.GetAuthority()) != 0 {
return false
}
return true
}
// Equal function
func (m *HealthCheck_CustomHealthCheck) Equal(that interface{}) bool {
if that == nil {
return m == nil
}
target, ok := that.(*HealthCheck_CustomHealthCheck)
if !ok {
that2, ok := that.(HealthCheck_CustomHealthCheck)
if ok {
target = &that2
} else {
return false
}
}
if target == nil {
return m == nil
} else if m == nil {
return false
}
if strings.Compare(m.GetName(), target.GetName()) != 0 {
return false
}
switch m.ConfigType.(type) {
case *HealthCheck_CustomHealthCheck_TypedConfig:
if _, ok := target.ConfigType.(*HealthCheck_CustomHealthCheck_TypedConfig); !ok {
return false
}
if h, ok := interface{}(m.GetTypedConfig()).(equality.Equalizer); ok {
if !h.Equal(target.GetTypedConfig()) {
return false
}
} else {
if !proto.Equal(m.GetTypedConfig(), target.GetTypedConfig()) {
return false
}
}
default:
// m is nil but target is not nil
if m.ConfigType != target.ConfigType {
return false
}
}
return true
}
// Equal function
func (m *HealthCheck_TlsOptions) Equal(that interface{}) bool {
if that == nil {
return m == nil
}
target, ok := that.(*HealthCheck_TlsOptions)
if !ok {
that2, ok := that.(HealthCheck_TlsOptions)
if ok {
target = &that2
} else {
return false
}
}
if target == nil {
return m == nil
} else if m == nil {
return false
}
if len(m.GetAlpnProtocols()) != len(target.GetAlpnProtocols()) {
return false
}
for idx, v := range m.GetAlpnProtocols() {
if strings.Compare(v, target.GetAlpnProtocols()[idx]) != 0 {
return false
}
}
return true
} | projects/gloo/pkg/api/external/envoy/config/core/v3/health_check.pb.equal.go | 0.540196 | 0.412648 | health_check.pb.equal.go | starcoder |
package tchart
import (
"fmt"
"image"
"github.com/derailed/tview"
"github.com/gdamore/tcell/v2"
)
const (
// DeltaSame represents no difference.
DeltaSame delta = iota
// DeltaMore represents a higher value.
DeltaMore
// DeltaLess represents a lower value.
DeltaLess
gaugeFmt = "0%dd"
)
type delta int
// Gauge represents a gauge component.
type Gauge struct {
*Component
data Metric
resolution int
deltaOk, deltaS2 delta
}
// NewGauge returns a new gauge.
func NewGauge(id string) *Gauge {
return &Gauge{
Component: NewComponent(id),
}
}
// SetResolution overrides the default number of digits to display.
func (g *Gauge) SetResolution(n int) {
g.resolution = n
}
// IsDial returns true if chart is a dial
func (g *Gauge) IsDial() bool {
return true
}
// Add adds a new metric.
func (g *Gauge) Add(m Metric) {
g.mx.Lock()
defer g.mx.Unlock()
g.deltaOk, g.deltaS2 = computeDelta(g.data.S1, m.S1), computeDelta(g.data.S2, m.S2)
g.data = m
}
type number struct {
ok bool
val int64
str string
delta delta
}
// Draw draws the primitive.
func (g *Gauge) Draw(sc tcell.Screen) {
g.Component.Draw(sc)
g.mx.RLock()
defer g.mx.RUnlock()
rect := g.asRect()
mid := image.Point{X: rect.Min.X + rect.Dx()/2, Y: rect.Min.Y + rect.Dy()/2 - 1}
style := tcell.StyleDefault.Background(g.bgColor)
style = style.Foreground(tcell.ColorYellow)
sc.SetContent(mid.X, mid.Y, '⠔', nil, style)
max := g.data.MaxDigits()
if max < g.resolution {
max = g.resolution
}
var (
fmat = "%" + fmt.Sprintf(gaugeFmt, max)
o = image.Point{X: mid.X, Y: mid.Y - 1}
)
s1C, s2C := g.colorForSeries()
d1, d2 := fmt.Sprintf(fmat, g.data.S1), fmt.Sprintf(fmat, g.data.S2)
o.X -= len(d1) * 3
g.drawNum(sc, o, number{ok: true, val: g.data.S1, delta: g.deltaOk, str: d1}, style.Foreground(s1C).Dim(false))
o.X = mid.X + 1
g.drawNum(sc, o, number{ok: false, val: g.data.S2, delta: g.deltaS2, str: d2}, style.Foreground(s2C).Dim(false))
if rect.Dx() > 0 && rect.Dy() > 0 && g.legend != "" {
legend := g.legend
if g.HasFocus() {
legend = fmt.Sprintf("[%s:%s:]", g.focusFgColor, g.focusBgColor) + g.legend + "[::]"
}
tview.Print(sc, legend, rect.Min.X, o.Y+3, rect.Dx(), tview.AlignCenter, tcell.ColorWhite)
}
}
func (g *Gauge) drawNum(sc tcell.Screen, o image.Point, n number, style tcell.Style) {
c1, _ := g.colorForSeries()
if n.ok {
style = style.Foreground(c1)
printDelta(sc, n.delta, o, style)
}
dm, significant := NewDotMatrix(), n.val == 0
if significant {
style = g.dimmed
}
for i := 0; i < len(n.str); i++ {
if n.str[i] == '0' && !significant {
g.drawDial(sc, dm.Print(int(n.str[i]-48)), o, g.dimmed)
} else {
significant = true
g.drawDial(sc, dm.Print(int(n.str[i]-48)), o, style)
}
o.X += 3
}
if !n.ok {
o.X++
printDelta(sc, n.delta, o, style)
}
}
func (g *Gauge) drawDial(sc tcell.Screen, m Matrix, o image.Point, style tcell.Style) {
for r := 0; r < len(m); r++ {
for c := 0; c < len(m[r]); c++ {
dot := m[r][c]
if dot == dots[0] {
sc.SetContent(o.X+c, o.Y+r, dots[1], nil, g.dimmed)
} else {
sc.SetContent(o.X+c, o.Y+r, dot, nil, style)
}
}
}
}
// ----------------------------------------------------------------------------
// Helpers...
func computeDelta(d1, d2 int64) delta {
if d2 == 0 {
return DeltaSame
}
d := d2 - d1
switch {
case d > 0:
return DeltaMore
case d < 0:
return DeltaLess
default:
return DeltaSame
}
}
func printDelta(sc tcell.Screen, d delta, o image.Point, s tcell.Style) {
s = s.Dim(false)
switch d {
case DeltaLess:
sc.SetContent(o.X-1, o.Y+1, '↓', nil, s)
case DeltaMore:
sc.SetContent(o.X-1, o.Y+1, '↑', nil, s)
}
} | internal/tchart/gauge.go | 0.739046 | 0.412471 | gauge.go | starcoder |
package gl
import (
"strings"
"unsafe"
"github.com/go-gl/mathgl/mgl32"
"github.com/thinkofdeath/gl/v3.2-core/gl"
)
// ShaderType is type of shader to be used, different types run
// at different stages in the pipeline.
type ShaderType uint32
// Valid shader types.
const (
VertexShader ShaderType = gl.VERTEX_SHADER
FragmentShader ShaderType = gl.FRAGMENT_SHADER
GeometryShader ShaderType = gl.GEOMETRY_SHADER
)
// ShaderParameter is a parameter that can set or read from a
// shader.
type ShaderParameter uint32
// Valid shader parameters.
const (
CompileStatus ShaderParameter = gl.COMPILE_STATUS
InfoLogLength ShaderParameter = gl.INFO_LOG_LENGTH
)
// Program is a collection of shaders which will be run on draw
// operations.
type Program uint32
// CreateProgram allocates a new program.
func CreateProgram() Program {
return Program(gl.CreateProgram())
}
// AttachShader attaches the passed shader to the program.
func (p Program) AttachShader(s Shader) {
gl.AttachShader(uint32(p), uint32(s))
}
// Link links the program's shaders.
func (p Program) Link() {
gl.LinkProgram(uint32(p))
}
var (
currentProgram Program
)
// Use sets this shader as the active shader. If this shader is
// already active this does nothing.
func (p Program) Use() {
if p == currentProgram {
return
}
gl.UseProgram(uint32(p))
currentProgram = p
}
// Uniform is a per-a-draw value that can be passed into the
// program.
type Uniform int32
// UniformLocation returns the uniform with the given name in
// the program.
func (p Program) UniformLocation(name string) Uniform {
n := gl.Str(name + "\x00")
return Uniform(gl.GetUniformLocation(uint32(p), n))
}
// Matrix4 sets the value of the uniform to the passed matrix.
func (u Uniform) Matrix4(matrix *mgl32.Mat4) {
gl.UniformMatrix4fv(int32(u), 1, false, (*float32)(unsafe.Pointer(matrix)))
}
// Matrix4 sets the value of the uniform to the passed matrix.
func (u Uniform) Matrix4Multi(matrix []mgl32.Mat4) {
gl.UniformMatrix4fv(int32(u), int32(len(matrix)), false, (*float32)(gl.Ptr(matrix)))
}
// Int sets the value of the uniform to the passed integer.
func (u Uniform) Int(val int) {
gl.Uniform1i(int32(u), int32(val))
}
// Int3 sets the value of the uniform to the passed integers.
func (u Uniform) Int3(x, y, z int) {
gl.Uniform3i(int32(u), int32(x), int32(y), int32(z))
}
// IntV sets the value of the uniform to the passed integer array.
func (u Uniform) IntV(v ...int) {
gl.Uniform1iv(int32(u), int32(len(v)), (*int32)(gl.Ptr(v)))
}
// Float sets the value of the uniform to the passed float.
func (u Uniform) Float(val float32) {
gl.Uniform1f(int32(u), val)
}
// Float2 sets the value of the uniform to the passed floats.
func (u Uniform) Float2(x, y float32) {
gl.Uniform2f(int32(u), x, y)
}
// Float3 sets the value of the uniform to the passed floats.
func (u Uniform) Float3(x, y, z float32) {
gl.Uniform3f(int32(u), x, y, z)
}
// Float3 sets the value of the uniform to the passed floats.
func (u Uniform) Float4(x, y, z, w float32) {
gl.Uniform4f(int32(u), x, y, z, w)
}
func (u Uniform) FloatMutli(a []float32) {
gl.Uniform4fv(int32(u), int32(len(a)), (*float32)(gl.Ptr(a)))
}
func (u Uniform) FloatMutliRaw(a interface{}, l int) {
gl.Uniform4fv(int32(u), int32(l), (*float32)(gl.Ptr(a)))
}
// Attribute is a per-a-vertex value that can be passed into the
// program.
type Attribute int32
// AttributeLocation returns the attribute with the given name in
// the program.
func (p Program) AttributeLocation(name string) Attribute {
n := gl.Str(name + "\x00")
return Attribute(gl.GetAttribLocation(uint32(p), n))
}
// Enable enables the attribute for use in rendering.
func (a Attribute) Enable() {
gl.EnableVertexAttribArray(uint32(a))
}
// Disable disables the attribute for use in rendering.
func (a Attribute) Disable() {
gl.DisableVertexAttribArray(uint32(a))
}
// Pointer is used to specify the format of the data in the buffer. The data will
// be uploaded as floats.
func (a Attribute) Pointer(size int, ty Type, normalized bool, stride, offset int) {
gl.VertexAttribPointer(uint32(a), int32(size), uint32(ty), normalized, int32(stride), uintptr(offset))
}
// PointerInt is used to specify the format of the data in the buffer. The data will
// be uploaded as integers.
func (a Attribute) PointerInt(size int, ty Type, stride, offset int) {
gl.VertexAttribIPointer(uint32(a), int32(size), uint32(ty), int32(stride), uintptr(offset))
}
// Shader is code to be run on the gpu at a specific stage in the
// pipeline.
type Shader uint32
// CreateShader creates a new shader of the specifed type.
func CreateShader(t ShaderType) Shader {
return Shader(gl.CreateShader(uint32(t)))
}
// Source sets the source of the shader.
func (s Shader) Source(src string) {
ss := gl.Str(src + "\x00")
gl.ShaderSource(uint32(s), 1, &ss, nil)
}
// Compile compiles the shader.
func (s Shader) Compile() {
gl.CompileShader(uint32(s))
}
// Parameter returns the integer value of the parameter for
// this shader.
func (s Shader) Parameter(param ShaderParameter) int {
var p int32
gl.GetShaderiv(uint32(s), uint32(param), &p)
return int(p)
}
// InfoLog returns the log from compiling the shader.
func (s Shader) InfoLog() string {
l := s.Parameter(InfoLogLength)
var ptr unsafe.Pointer
var buf []byte
if l > 0 {
buf = make([]byte, l)
ptr = gl.Ptr(buf)
}
gl.GetShaderInfoLog(uint32(s), int32(l), nil, (*uint8)(ptr))
return strings.TrimRight(string(buf), "\x00")
} | render/gl/shader.go | 0.789112 | 0.46873 | shader.go | starcoder |
package object
import (
"bytes"
"hash/fnv"
"strconv"
"strings"
)
// Type is a type of objects.
type Type string
const (
// IntegerType represents a type of integers.
IntegerType Type = "Integer"
// FloatType represents a type of floating point numbers.
FloatType = "Float"
// BooleanType represents a type of booleans.
BooleanType = "Boolean"
// NilType represents a type of nil.
NilType = "Nil"
// ReturnValueType represents a type of return values.
ReturnValueType = "ReturnValue"
// ErrorType represents a type of errors.
ErrorType = "Error"
// FunctionType represents a type of functions.
FunctionType = "Function"
// StringType represents a type of strings.
StringType = "String"
// BuiltinType represents a type of builtin functions.
BuiltinType = "Builtin"
// ArrayType represents a type of arrays.
ArrayType = "Array"
// HashType represents a type of hashes.
HashType = "Hash"
)
// Object represents an object of Monkey language.
type Object interface {
Type() Type
Inspect() string
}
// HashKey represents a key of a hash.
type HashKey struct {
Type Type
Value uint64
}
// Hashable is the interface that is able to become a hash key.
type Hashable interface {
HashKey() HashKey
}
// Integer represents an integer.
type Integer struct {
Value int64
}
// Type returns the type of the Integer.
func (i *Integer) Type() Type {
return IntegerType
}
// Inspect returns a string representation of the Integer.
func (i *Integer) Inspect() string {
return strconv.FormatInt(i.Value, 10)
}
// HashKey returns a hash key object for i.
func (i *Integer) HashKey() HashKey {
return HashKey{
Type: i.Type(),
Value: uint64(i.Value),
}
}
// Float represents an integer.
type Float struct {
Value float64
}
// Type returns the type of f.
func (f *Float) Type() Type {
return FloatType
}
// Inspect returns a string representation of f.
func (f *Float) Inspect() string {
return strconv.FormatFloat(f.Value, 'f', -1, 64)
}
// HashKey returns a hash key object for f.
func (f *Float) HashKey() HashKey {
s := strconv.FormatFloat(f.Value, 'f', -1, 64)
h := fnv.New64a()
h.Write([]byte(s))
return HashKey{
Type: f.Type(),
Value: h.Sum64(),
}
}
// Boolean represents a boolean.
type Boolean struct {
Value bool
}
// Type returns the type of the Boolean.
func (b *Boolean) Type() Type {
return BooleanType
}
// Inspect returns a string representation of the Boolean.
func (b *Boolean) Inspect() string {
return strconv.FormatBool(b.Value)
}
// HashKey returns a hash key object for b.
func (b *Boolean) HashKey() HashKey {
key := HashKey{Type: b.Type()}
if b.Value {
key.Value = 1
}
return key
}
// Nil represents the absence of any value.
type Nil struct{}
// Type returns the type of the Nil.
func (n *Nil) Type() Type {
return NilType
}
// Inspect returns a string representation of the Nil.
func (n *Nil) Inspect() string {
return "nil"
}
// ReturnValue represents a return value.
type ReturnValue struct {
Value Object
}
// Type returns the type of the ReturnValue.
func (rv *ReturnValue) Type() Type {
return ReturnValueType
}
// Inspect returns a string representation of the ReturnValue.
func (rv *ReturnValue) Inspect() string {
return rv.Value.Inspect()
}
// Error represents an error.
type Error struct {
Message string
}
// Type returns the type of the Error.
func (e *Error) Type() Type {
return ErrorType
}
// Inspect returns a string representation of the Error.
func (e *Error) Inspect() string {
return "Error: " + e.Message
}
// Function represents a function.
type Function struct {
Parameters []*ast.Ident
Body *ast.BlockStatement
Env Environment
}
// Type returns the type of the Function.
func (f *Function) Type() Type {
return FunctionType
}
// Inspect returns a string representation of the Function.
func (f *Function) Inspect() string {
var out bytes.Buffer
params := make([]string, 0, len(f.Parameters))
for _, p := range f.Parameters {
params = append(params, p.String())
}
out.WriteString("fn(")
out.WriteString(strings.Join(params, ", "))
out.WriteString(") {\n")
out.WriteString(f.Body.String())
out.WriteString("\n}")
return out.String()
}
// String represents a string.
type String struct {
Value string
}
// Type returns the type of the String.
func (s *String) Type() Type {
return StringType
}
// Inspect returns a string representation of the String.
func (s *String) Inspect() string {
return s.Value
}
// HashKey returns a hash key object for s.
func (s *String) HashKey() HashKey {
h := fnv.New64a()
h.Write([]byte(s.Value))
return HashKey{
Type: s.Type(),
Value: h.Sum64(),
}
}
// BuiltinFunction represents a function signature of builtin functions.
type BuiltinFunction func(args ...Object) Object
// Builtin represents a builtin function.
type Builtin struct {
Fn BuiltinFunction
}
// Type returns the type of the Builtin.
func (b *Builtin) Type() Type {
return BuiltinType
}
// Inspect returns a string representation of the Builtin.
func (b *Builtin) Inspect() string {
return "builtin function"
}
// Array represents an array.
type Array struct {
Elements []Object
}
// Type returns the type of the Array.
func (*Array) Type() Type {
return ArrayType
}
// Inspect returns a string representation of the Array.
func (a *Array) Inspect() string {
if a == nil {
return ""
}
elements := make([]string, 0, len(a.Elements))
for _, e := range a.Elements {
elements = append(elements, e.Inspect())
}
var out bytes.Buffer
out.WriteString("[")
out.WriteString(strings.Join(elements, ", "))
out.WriteString("]")
return out.String()
}
// HashPair represents a key-value pair in a hash.
type HashPair struct {
Key Object
Value Object
}
// Hash represents a hash.
type Hash struct {
Pairs map[HashKey]HashPair
}
// Type returns the type of the Hash.
func (*Hash) Type() Type {
return HashType
}
// Inspect returns a string representation of the Hash.
func (h *Hash) Inspect() string {
if h == nil {
return ""
}
pairs := make([]string, 0, len(h.Pairs))
for _, pair := range h.Pairs {
pairs = append(pairs, pair.Key.Inspect()+": "+pair.Value.Inspect())
}
var out bytes.Buffer
out.WriteString("{")
out.WriteString(strings.Join(pairs, ", "))
out.WriteString("}")
return out.String()
} | object/object.go | 0.855836 | 0.483709 | object.go | starcoder |
package iqfeed
import "time"
// UpdSummaryMsg is the main struct for both update and summary messages.
type UpdSummaryMsg struct {
SevenDayYield float64 // A price field, the value from a Money Market fund over the last seven days.
Ask float64 // The lowest price a market maker or broker is willing to accept for a security.
AskChange float64 // Change in Ask since last offer.
AskMktCenter int // The Market Center that sent the ask information. See Listed Market Codes for possible values.
AskSize int // The share size available for the ask price in a given security.
AskTime time.Time // The time for the last ask.
AvailRegions string // Dash delimited string of available regions.
AvgMaturity float64 // The average number of days until maturity of a Money Market Fund’s assets.
Bid float64 // The highest price a market maker or broker is willing to pay for a security.
BidTick string // Undocumented currently
BidChange float64 // Change in Bid since last offer.
BidMktCenter int // The Market Center that sent the bid information. See Listed Market Codes for possible values.
BidSize int // The share size available for the bid price in a given security
BidTime time.Time // The time of the last bid.
Change float64 // Today's change (Last - Close)
ChangeFrmOpen float64 // Change in last since open
Close float64 // The closing price of the day. For commodities this will be the last TRADE of the session
CloseRng1 float64 // For commodities only. Range value for closing trades that aren’t reported individually.
CloseRng2 float64 // For commodities only. Range value for closing trades that aren’t reported individually.
DaysToExpir string // Number of days to contract expiration
DecPrecision string // Last Precision used
Delay int // The number of minutes a quote is delayed when not authorized for real-time data
ExchangeID string // This is the exchange ID. Convert to decimal and use the Listed Markets lookup to decode this value.
ExtendedTrdLast float64 // Price of the most recent extended trade (last qualified trades + Form T trades).
ExtendedTrdDate time.Time // Date of the extended trade. (MM/DD/CCYY)
ExtendedTrdMktCntr int // Market Center of the most recent extended trade (last qualified trades + Form T trades).
ExtendedTrdSize int // Size of the most recent extended trade (last qualified trades + Form T trades).
ExtendedTrdTime time.Time // Time (including microseconds) of the most recent extended trade (last qualified trades + Form T trades).
ExtendedTrdChange float64 // Extended Trade minus Yesterday's close.
ExtendedTrdDiff float64 // Extended Trade minus Last
FinancialStatusInd string // Denotes if an issuer has failed to submit its regulatory filings on a timely basis, has failed to meet the exchange's continuing listing standards, and/or has filed for bankruptcy. See Financial Status Indicator Codes.
FractionDispCode string // Display formatting code see Price Format Codes.
High float64 // Today's highest trade price
Last float64 // Last trade price from the regular trading session
LastDate time.Time // Date of the last qualified trade. (MM/DD/CCYY).
LastMktCntr int // Market Center of most recent last qualified trade.
LastSize int // Size of the most recent last qualified trade.
LastTime time.Time // Time (including microseconds) of most recent last qualified trade (HH:MM:SS.fff)
LastTrdDate time.Time // Date of last trade
Low float64 // Today's lowest trade price
MktCapitilization float64 // Real-time calculated market cap (Last * Common Shares Outstanding).
MktOpen int // 1 = market open, 0 = market closed NOTE: This field is valid for Futures and Future Options only.
MsgContents string // Possible single character values include: C - Last Qualified Trade. |E - Extended Trade = Form T trade.|O - Other Trade = Any trade not accounted for by C or E.|b - A bid update occurred.|a - An ask update occurred.|o - An Open occurred.|h - A High occurred.|l - A Low occurred.|c - A Close occurred.|s - A Settlement occurred.|v - A volume update occurred.|NOTE: you can get multiple codes in a single message but you will only get one trade identifier per message. NOTE: It is also possible to receive no codes in a message if the fields that updated were not trade or quote related.
MostRecentTrade float64 // Price of the most recent trade (including all non-last-qualified trades).
MostRecntTradeCond string // Conditions that identify the type of trade that occurred.
MostRecntTradeDate time.Time // Date of the most recent trade (MM/DD/CCYY)
MostRecentTradeMktCntr int // Market Center of the most recent trade (including all non-last-qualified trades).
MostRecentTradeSize int // Size of the most recent trade (including all non-last-qualified trades).
MostRecentTradeTime time.Time // Time (including microseconds) of the most recent trade (including all non-last-qualified trades).
NetAssetValue float64 // Mutual Funds only. The market value of a mutual fund share equal to the net asset of a fund divided by the total number of shares outstanding. NOTE: this field is the same as the Bid field for Mutual Funds.
NetAssetValue2 float64 // Undocumented
NumTradesToday int // The number of trades for the current day.
Open float64 // The opening price of the day. For commodities this will be the first TRADE of the session.
OpenInterest int // IEOptions, Futures, FutureOptions, and SSFutures only.
OpenRange1 float64 // For commodities only. Range value for opening trades that aren’t reported individually.
OpenRange2 float64 // For commodities only. Range value for opening trades that aren’t reported individually.
PcntChange float64 // (Change / Close)
PcntOffAvgVol float64 // Current Total Volume divided by Average Volume (from fundamental message).
PrevDayVol int // Previous Day's Volume
PERatio float64 // Real-time calculated PE (Today's Last / Earnings Per Share)
Range float64 // Trading range for the current day (high - low).
RestrictedCode string // Short Sale Restricted flag - "N" for Not restricted or "R" for Restricted.
Settle float64 // Futures or FutureOptions only.
SettleDate time.Time // The date that the Settle is valid for.
Spread float64 // The difference between Bid and Ask prices
Strike float64 // The strike price for the option
Symbol string // The Symbol ID to match with watch request
Tick int // "173"=Up, "175"=Down, "183"=No Change. Only valid for Last qualified trades.
TickID int // Identifier for tick
TotalVol int // Today's cumulative volume in number of shares.
Type string // Valid values are Q or P. The character Q indicates an Update message, and the character P indicates a Summary Message.
Volatility float64 // Real-time calculated volatility (Today's High - Today's Low) / Last
VWAP float64 // Volume Weighted Average Price.
IncrVolume int // Incremental Volume
Reserved1 string // Reserved
ExpirationDate time.Time // Expiration date
RegionalVol int // RegionalVol
Regions string // Undocumented
TradeTime time.Time // TradeTime
}
// UnMarshall sends the data into the usable struct for consumption by the application.
func (u *UpdSummaryMsg) UnMarshall(items []string, fields map[int]string, loc *time.Location) {
//DynFields: map[4:Most Recent Trade Market Center 7:Bid Size 11:High 1:Most Recent Trade 8:Ask 9:Ask Size 12:Low 10:Open 15:Most Recent Trade Conditions 13:Close 14:Message Contents 0:Symbol 2:Most Recent Trade Size 3:Most Recent Trade TimeMS 5:Total Volume 6:Bid]
//Unmarshall: AAPL,95.0200,100,09:35:57.022,26,1325032,95.0200,100,95.0400,400,95.0000,95.3800,94.8600,94.4800,ba,01,
//fmt.Printf("Dyn: %#v\nItems: %#v\n", fields, items)
//time.Sleep(50 * time.Millisecond)
//fmt.Printf("Unmarshall: %#v\n", items)
for k, v := range items {
switch fields[k] {
case "Symbol":
u.Symbol = v
case "Exchange ID":
u.ExchangeID = v
case "Last":
u.Last = GetFloatFromStr(v)
case "Change":
u.Change = GetFloatFromStr(v)
case "Percent Change":
u.PcntChange = GetFloatFromStr(v)
case "Total Volume":
u.TotalVol = GetIntFromStr(v)
case "Incremental Volume":
u.IncrVolume = GetIntFromStr(v)
case "High":
u.High = GetFloatFromStr(v)
case "Low":
u.Low = GetFloatFromStr(v)
case "Bid":
u.Bid = GetFloatFromStr(v)
case "Ask":
u.Ask = GetFloatFromStr(v)
case "Bid Size":
u.BidSize = GetIntFromStr(v)
case "Ask Size":
u.AskSize = GetIntFromStr(v)
case "Tick":
u.Tick = GetIntFromStr(v)
case "Bid Tick":
u.BidTick = v
case "Range":
u.Range = GetFloatFromStr(v)
case "Last Trade Time":
u.LastTrdDate = GetTimeInHMS(v, loc)
case "Open Interest":
u.OpenInterest = GetIntFromStr(v)
case "Open":
u.Open = GetFloatFromStr(v)
case "Close":
u.Close = GetFloatFromStr(v)
case "Spread":
u.Spread = GetFloatFromStr(v)
case "Strike":
u.Strike = GetFloatFromStr(v)
case "Settle":
u.Settle = GetFloatFromStr(v)
case "Delay":
u.Delay = GetIntFromStr(v)
case "Market Center":
u.AskMktCenter = GetIntFromStr(v)
case "Restricted Code":
u.RestrictedCode = v
case "Net Asset Value":
u.NetAssetValue = GetFloatFromStr(v)
case "Average Maturity":
u.AvgMaturity = GetFloatFromStr(v)
case "7 Day Yield":
u.SevenDayYield = GetFloatFromStr(v)
case "Last Trade Date":
u.LastTrdDate = GetDateMMDDCCYY(v, loc)
case "(Reserved)":
u.Reserved1 = v
case "Extended Trading Last":
u.ExtendedTrdLast = GetFloatFromStr(v)
case "Expiration Date":
u.ExpirationDate = GetDateMMDDCCYY(v, loc)
case "Regional Volume":
u.RegionalVol = GetIntFromStr(v)
case "Net Asset Value 2":
u.NetAssetValue2 = GetFloatFromStr(v)
case "Extended Trading Change":
u.ExtendedTrdChange = GetFloatFromStr(v)
case "Extended Trading Difference":
u.ExtendedTrdDiff = GetFloatFromStr(v)
case "Price-Earnings Ratio":
u.PERatio = GetFloatFromStr(v)
case "Percent Off Average Volume":
u.PcntOffAvgVol = GetFloatFromStr(v)
case "Bid Change":
u.BidChange = GetFloatFromStr(v)
case "Ask Change":
u.AskChange = GetFloatFromStr(v)
case "Change From Open":
u.ChangeFrmOpen = GetFloatFromStr(v)
case "Market Open":
u.MktOpen = GetIntFromStr(v)
case "Volatility":
u.Volatility = GetFloatFromStr(v)
case "Market Capitalization":
u.MktCapitilization = GetFloatFromStr(v)
case "Fraction Display Code":
u.FractionDispCode = v
case "Decimal Precision":
u.DecPrecision = v
case "Days to Expiration":
u.DaysToExpir = v
case "Previous Day Volume":
u.PrevDayVol = GetIntFromStr(v)
case "Regions":
u.Regions = v
case "Open Range 1":
u.OpenRange1 = GetFloatFromStr(v)
case "Close Range 1":
u.CloseRng1 = GetFloatFromStr(v)
case "Open Range 2":
u.OpenRange2 = GetFloatFromStr(v)
case "Close Range 2":
u.CloseRng2 = GetFloatFromStr(v)
case "Number of Trades Today":
u.NumTradesToday = GetIntFromStr(v)
case "Bid Time":
u.BidTime = GetTimeInHMS(v, loc)
case "Ask Time":
u.AskTime = GetTimeInHMS(v, loc)
case "VWAP":
u.VWAP = GetFloatFromStr(v)
case "TickID":
u.TickID = GetIntFromStr(v)
case "Financial Status Indicator":
u.FinancialStatusInd = v
case "Settlement Date":
u.SettleDate = GetDateMMDDCCYY(v, loc)
case "Trade Market Center":
u.MostRecentTradeMktCntr = GetIntFromStr(v)
case "Bid Market Center":
u.BidMktCenter = GetIntFromStr(v)
case "Ask Market Center":
u.AskMktCenter = GetIntFromStr(v)
case "Trade Time":
u.TradeTime = GetTimeInHMS(v, loc)
case "Available Regions":
u.AvailRegions = v
case "Type":
u.Type = v
}
}
} | updatesummary.go | 0.592195 | 0.6372 | updatesummary.go | starcoder |
package powerlogger
import (
"go.opentelemetry.io/otel/label"
"go.uber.org/zap"
)
type LabelType int
const (
// INVALID is used for a Value with no value set.
INVALID LabelType = iota
BOOL
INT32
INT64
UINT32
UINT64
FLOAT32
FLOAT64
STRING
ARRAY
)
// Label struct for context information
type Label interface {
OtelLabel() label.KeyValue
ZapLabel() zap.Field
}
func OtelLabels(labels ...Label) []label.KeyValue {
otlabels := []label.KeyValue{}
for _, label := range labels {
otlabels = append(otlabels, label.OtelLabel())
}
return otlabels
}
func ZapLabels(labels ...Label) []zap.Field {
zaplabels := []zap.Field{}
for _, label := range labels {
zaplabels = append(zaplabels, label.ZapLabel())
}
return zaplabels
}
func ParseOtelLabel(label label.KeyValue) Label {
switch LabelType(label.Value.Type()) {
case BOOL:
return Bool(string(label.Key), label.Value.AsBool())
case INT32:
return Int32(string(label.Key), label.Value.AsInt32())
case INT64:
return Int64(string(label.Key), label.Value.AsInt64())
// case UINT32:
// return Uint64(string(label.Key), label.Value.AsInt64())
// case UINT64:
case FLOAT32:
return Float32(string(label.Key), label.Value.AsFloat32())
case FLOAT64:
return Float64(string(label.Key), label.Value.AsFloat64())
case STRING:
return String(string(label.Key), label.Value.AsString())
case ARRAY:
}
return nil
}
type BoolLabel struct {
Type LabelType
Key string
Val bool
}
type IntLabel struct {
Type LabelType
Key string
Val int
}
type Int32Label struct {
Type LabelType
Key string
Val int32
}
type Int64Label struct {
Type LabelType
Key string
Val int64
}
type Float32Label struct {
Type LabelType
Key string
Val float32
}
type Float64Label struct {
Type LabelType
Key string
Val float64
}
type StringLabel struct {
Type LabelType
Key string
Val string
}
// Bool attach Bool label
func Bool(key string, val bool) *BoolLabel {
return &BoolLabel{
Type: BOOL,
Key: key,
Val: val,
}
}
// Int32 attach Int32 label
func Int32(key string, val int32) *Int32Label {
return &Int32Label{
Type: INT32,
Key: key,
Val: val,
}
}
// Int64 attach Int64 label
func Int64(key string, val int64) *Int64Label {
return &Int64Label{
Type: INT64,
Key: key,
Val: val,
}
}
// Float32 attach Float32 label
func Float32(key string, val float32) *Float32Label {
return &Float32Label{
Type: FLOAT32,
Key: key,
Val: val,
}
}
// Float64 attach Float64 label
func Float64(key string, val float64) *Float64Label {
return &Float64Label{
Type: FLOAT64,
Key: key,
Val: val,
}
}
// String attach String label
func String(key string, val string) *StringLabel {
return &StringLabel{
Type: STRING,
Key: key,
Val: val,
}
}
func (bl *BoolLabel) OtelLabel() label.KeyValue {
return label.Bool(bl.Key, bl.Val)
}
func (bl *BoolLabel) ZapLabel() zap.Field {
return zap.Bool(bl.Key, bl.Val)
}
func (il *IntLabel) OtelLabel() label.KeyValue {
return label.Int(il.Key, il.Val)
}
func (il *IntLabel) ZapLabel() zap.Field {
return zap.Int(il.Key, il.Val)
}
func (il32 *Int32Label) OtelLabel() label.KeyValue {
return label.Int32(il32.Key, il32.Val)
}
func (il32 *Int32Label) ZapLabel() zap.Field {
return zap.Int32(il32.Key, il32.Val)
}
func (il64 *Int64Label) OtelLabel() label.KeyValue {
return label.Int64(il64.Key, il64.Val)
}
func (il64 *Int64Label) ZapLabel() zap.Field {
return zap.Int64(il64.Key, il64.Val)
}
func (fl32 *Float32Label) OtelLabel() label.KeyValue {
return label.Float32(fl32.Key, fl32.Val)
}
func (fl32 *Float32Label) ZapLabel() zap.Field {
return zap.Float32(fl32.Key, fl32.Val)
}
func (fl64 *Float64Label) OtelLabel() label.KeyValue {
return label.Float64(fl64.Key, fl64.Val)
}
func (fl64 *Float64Label) ZapLabel() zap.Field {
return zap.Float64(fl64.Key, fl64.Val)
}
func (sl *StringLabel) OtelLabel() label.KeyValue {
return label.String(sl.Key, sl.Val)
}
func (sl *StringLabel) ZapLabel() zap.Field {
return zap.String(sl.Key, sl.Val)
} | labels.go | 0.559049 | 0.42483 | labels.go | starcoder |
package models
import (
i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e "time"
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// SignIn
type SignIn struct {
Entity
// The application name displayed in the Azure Portal. Supports $filter (eq and startsWith operators only).
appDisplayName *string
// The application identifier in Azure Active Directory. Supports $filter (eq operator only).
appId *string
// A list of conditional access policies that are triggered by the corresponding sign-in activity.
appliedConditionalAccessPolicies []AppliedConditionalAccessPolicyable
// Contains a collection of values that represent the conditional access authentication contexts applied to the sign-in.
authenticationContextClassReferences []AuthenticationContextable
// The result of the authentication attempt and additional details on the authentication method.
authenticationDetails []AuthenticationDetailable
// The authentication methods used. Possible values: SMS, Authenticator App, App Verification code, Password, FIDO, PTA, or PHS.
authenticationMethodsUsed []string
// Additional authentication processing details, such as the agent name in case of PTA/PHS or Server/farm name in case of federated authentication.
authenticationProcessingDetails []KeyValueable
// Lists the protocol type or grant type used in the authentication. The possible values are: none, oAuth2, ropc, wsFederation, saml20, deviceCode, unknownFutureValue. For authentications that use protocols other than the possible values listed, the protocol type is listed as none.
authenticationProtocol *ProtocolType
// This holds the highest level of authentication needed through all the sign-in steps, for sign-in to succeed. Supports $filter (eq and startsWith operators only).
authenticationRequirement *string
// Sources of authentication requirement, such as conditional access, per-user MFA, identity protection, and security defaults.
authenticationRequirementPolicies []AuthenticationRequirementPolicyable
// The Autonomous System Number (ASN) of the network used by the actor.
autonomousSystemNumber *int32
// Contains a fully qualified Azure Resource Manager ID of an Azure resource accessed during the sign-in.
azureResourceId *string
// The legacy client used for sign-in activity. For example: Browser, Exchange ActiveSync, Modern clients, IMAP, MAPI, SMTP, or POP. Supports $filter (eq operator only).
clientAppUsed *string
// Describes the credential type that a user client or service principal provided to Azure AD to authenticate itself. You may wish to review clientCredentialType to track and eliminate less secure credential types or to watch for clients and service principals using anomalous credential types. The possible values are: none, clientSecret, clientAssertion, federatedIdentityCredential, managedIdentity, certificate, unknownFutureValue.
clientCredentialType *ClientCredentialType
// The status of the conditional access policy triggered. Possible values: success, failure, notApplied, or unknownFutureValue. Supports $filter (eq operator only).
conditionalAccessStatus *ConditionalAccessStatus
// The identifier that's sent from the client when sign-in is initiated. This is used for troubleshooting the corresponding sign-in activity when calling for support. Supports $filter (eq operator only).
correlationId *string
// The date and time the sign-in was initiated. The Timestamp type is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. Supports $orderby and $filter (eq, le, and ge operators only).
createdDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time
// Describes the type of cross-tenant access used by the actor to access the resource. Possible values are: none, b2bCollaboration, b2bDirectConnect, microsoftSupport, serviceProvider, unknownFutureValue. If the sign in did not cross tenant boundaries, the value is none.
crossTenantAccessType *SignInAccessType
// The device information from where the sign-in occurred. Includes information such as deviceId, OS, and browser. Supports $filter (eq and startsWith operators only) on browser and operatingSystem properties.
deviceDetail DeviceDetailable
// Contains the identifier of an application's federated identity credential, if a federated identity credential was used to sign in.
federatedCredentialId *string
// During a failed sign in, a user may click a button in the Azure portal to mark the failed event for tenant admins. If a user clicked the button to flag the failed sign in, this value is true.
flaggedForReview *bool
// The tenant identifier of the user initiating the sign in. Not applicable in Managed Identity or service principal sign ins.
homeTenantId *string
// For user sign ins, the identifier of the tenant that the user is a member of. Only populated in cases where the home tenant has provided affirmative consent to Azure AD to show the tenant content.
homeTenantName *string
// Indicates the token types that were presented to Azure AD to authenticate the actor in the sign in. The possible values are: none, primaryRefreshToken, saml11, saml20, unknownFutureValue, remoteDesktopToken. NOTE Azure AD may have also used token types not listed in this Enum type to authenticate the actor. Do not infer the lack of a token if it is not one of the types listed. Also, please note that you must use the Prefer: include-unknown-enum-members request header to get the following value(s) in this evolvable enum: remoteDesktopToken.
incomingTokenType *IncomingTokenType
// The IP address of the client from where the sign-in occurred. Supports $filter (eq and startsWith operators only).
ipAddress *string
// The IP address a user used to reach a resource provider, used to determine Conditional Access compliance for some policies. For example, when a user interacts with Exchange Online, the IP address Exchange receives from the user may be recorded here. This value is often null.
ipAddressFromResourceProvider *string
// Indicates whether a user sign in is interactive. In interactive sign in, the user provides an authentication factor to Azure AD. These factors include passwords, responses to MFA challenges, biometric factors, or QR codes that a user provides to Azure AD or an associated app. In non-interactive sign in, the user doesn't provide an authentication factor. Instead, the client app uses a token or code to authenticate or access a resource on behalf of a user. Non-interactive sign ins are commonly used for a client to sign in on a user's behalf in a process transparent to the user.
isInteractive *bool
// Shows whether the sign in event was subject to an Azure AD tenant restriction policy.
isTenantRestricted *bool
// The city, state, and 2 letter country code from where the sign-in occurred. Supports $filter (eq and startsWith operators only) on city, state, and countryOrRegion properties.
location SignInLocationable
// The mfaDetail property
mfaDetail MfaDetailable
// The network location details including the type of network used and its names.
networkLocationDetails []NetworkLocationDetailable
// The request identifier of the first request in the authentication sequence. Supports $filter (eq operator only).
originalRequestId *string
// Contains information about the Azure AD Private Link policy that is associated with the sign in event.
privateLinkDetails PrivateLinkDetailsable
// The request processing time in milliseconds in AD STS.
processingTimeInMilliseconds *int32
// The name of the resource that the user signed in to. Supports $filter (eq operator only).
resourceDisplayName *string
// The identifier of the resource that the user signed in to. Supports $filter (eq operator only).
resourceId *string
// The identifier of the service principal representing the target resource in the sign-in event.
resourceServicePrincipalId *string
// The tenant identifier of the resource referenced in the sign in.
resourceTenantId *string
// The reason behind a specific state of a risky user, sign-in, or a risk event. Possible values: none, adminGeneratedTemporaryPassword, userPerformedSecuredPasswordChange, userPerformedSecuredPasswordReset, adminConfirmedSigninSafe, aiConfirmedSigninSafe, userPassedMFADrivenByRiskBasedPolicy, adminDismissedAllRiskForUser, adminConfirmedSigninCompromised, or unknownFutureValue. The value none means that no action has been performed on the user or sign-in so far. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers are returned hidden.
riskDetail *RiskDetail
// The list of risk event types associated with the sign-in. Possible values: unlikelyTravel, anonymizedIPAddress, maliciousIPAddress, unfamiliarFeatures, malwareInfectedIPAddress, suspiciousIPAddress, leakedCredentials, investigationsThreatIntelligence, generic, or unknownFutureValue. Supports $filter (eq and startsWith operators only).
riskEventTypes_v2 []string
// The aggregated risk level. Possible values: none, low, medium, high, hidden, or unknownFutureValue. The value hidden means the user or sign-in was not enabled for Azure AD Identity Protection. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers are returned hidden.
riskLevelAggregated *RiskLevel
// The risk level during sign-in. Possible values: none, low, medium, high, hidden, or unknownFutureValue. The value hidden means the user or sign-in was not enabled for Azure AD Identity Protection. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers are returned hidden.
riskLevelDuringSignIn *RiskLevel
// The risk state of a risky user, sign-in, or a risk event. Possible values: none, confirmedSafe, remediated, dismissed, atRisk, confirmedCompromised, or unknownFutureValue. Supports $filter (eq operator only).
riskState *RiskState
// The unique identifier of the key credential used by the service principal to authenticate.
servicePrincipalCredentialKeyId *string
// The certificate thumbprint of the certificate used by the service principal to authenticate.
servicePrincipalCredentialThumbprint *string
// The application identifier used for sign-in. This field is populated when you are signing in using an application. Supports $filter (eq and startsWith operators only).
servicePrincipalId *string
// The application name used for sign-in. This field is populated when you are signing in using an application. Supports $filter (eq and startsWith operators only).
servicePrincipalName *string
// Any conditional access session management policies that were applied during the sign-in event.
sessionLifetimePolicies []SessionLifetimePolicyable
// Indicates the category of sign in that the event represents. For user sign ins, the category can be interactiveUser or nonInteractiveUser and corresponds to the value for the isInteractive property on the signin resource. For managed identity sign ins, the category is managedIdentity. For service principal sign ins, the category is servicePrincipal. Possible values are: interactiveUser, nonInteractiveUser, servicePrincipal, managedIdentity, unknownFutureValue. Supports $filter (eq, ne).
signInEventTypes []string
// The identification that the user provided to sign in. It may be the userPrincipalName but it's also populated when a user signs in using other identifiers.
signInIdentifier *string
// The type of sign in identifier. Possible values are: userPrincipalName, phoneNumber, proxyAddress, qrCode, onPremisesUserPrincipalName, unknownFutureValue.
signInIdentifierType *SignInIdentifierType
// The sign-in status. Includes the error code and description of the error (in case of a sign-in failure). Supports $filter (eq operator only) on errorCode property.
status SignInStatusable
// The name of the identity provider. For example, sts.microsoft.com. Supports $filter (eq operator only).
tokenIssuerName *string
// The type of identity provider. The possible values are: AzureAD, ADFederationServices, UnknownFutureValue, AzureADBackupAuth, ADFederationServicesMFAAdapter, NPSExtension. Note that you must use the Prefer: include-unknown-enum-members request header to get the following values in this evolvable enum: AzureADBackupAuth , ADFederationServicesMFAAdapter , NPSExtension.
tokenIssuerType *TokenIssuerType
// A unique base64 encoded request identifier used to track tokens issued by Azure AD as they are redeemed at resource providers.
uniqueTokenIdentifier *string
// The user agent information related to sign-in. Supports $filter (eq and startsWith operators only).
userAgent *string
// The display name of the user. Supports $filter (eq and startsWith operators only).
userDisplayName *string
// The identifier of the user. Supports $filter (eq operator only).
userId *string
// The UPN of the user. Supports $filter (eq and startsWith operators only).
userPrincipalName *string
// Identifies whether the user is a member or guest in the tenant. Possible values are: member, guest, unknownFutureValue.
userType *SignInUserType
}
// NewSignIn instantiates a new signIn and sets the default values.
func NewSignIn()(*SignIn) {
m := &SignIn{
Entity: *NewEntity(),
}
return m
}
// CreateSignInFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateSignInFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewSignIn(), nil
}
// GetAppDisplayName gets the appDisplayName property value. The application name displayed in the Azure Portal. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetAppDisplayName()(*string) {
if m == nil {
return nil
} else {
return m.appDisplayName
}
}
// GetAppId gets the appId property value. The application identifier in Azure Active Directory. Supports $filter (eq operator only).
func (m *SignIn) GetAppId()(*string) {
if m == nil {
return nil
} else {
return m.appId
}
}
// GetAppliedConditionalAccessPolicies gets the appliedConditionalAccessPolicies property value. A list of conditional access policies that are triggered by the corresponding sign-in activity.
func (m *SignIn) GetAppliedConditionalAccessPolicies()([]AppliedConditionalAccessPolicyable) {
if m == nil {
return nil
} else {
return m.appliedConditionalAccessPolicies
}
}
// GetAuthenticationContextClassReferences gets the authenticationContextClassReferences property value. Contains a collection of values that represent the conditional access authentication contexts applied to the sign-in.
func (m *SignIn) GetAuthenticationContextClassReferences()([]AuthenticationContextable) {
if m == nil {
return nil
} else {
return m.authenticationContextClassReferences
}
}
// GetAuthenticationDetails gets the authenticationDetails property value. The result of the authentication attempt and additional details on the authentication method.
func (m *SignIn) GetAuthenticationDetails()([]AuthenticationDetailable) {
if m == nil {
return nil
} else {
return m.authenticationDetails
}
}
// GetAuthenticationMethodsUsed gets the authenticationMethodsUsed property value. The authentication methods used. Possible values: SMS, Authenticator App, App Verification code, Password, FIDO, PTA, or PHS.
func (m *SignIn) GetAuthenticationMethodsUsed()([]string) {
if m == nil {
return nil
} else {
return m.authenticationMethodsUsed
}
}
// GetAuthenticationProcessingDetails gets the authenticationProcessingDetails property value. Additional authentication processing details, such as the agent name in case of PTA/PHS or Server/farm name in case of federated authentication.
func (m *SignIn) GetAuthenticationProcessingDetails()([]KeyValueable) {
if m == nil {
return nil
} else {
return m.authenticationProcessingDetails
}
}
// GetAuthenticationProtocol gets the authenticationProtocol property value. Lists the protocol type or grant type used in the authentication. The possible values are: none, oAuth2, ropc, wsFederation, saml20, deviceCode, unknownFutureValue. For authentications that use protocols other than the possible values listed, the protocol type is listed as none.
func (m *SignIn) GetAuthenticationProtocol()(*ProtocolType) {
if m == nil {
return nil
} else {
return m.authenticationProtocol
}
}
// GetAuthenticationRequirement gets the authenticationRequirement property value. This holds the highest level of authentication needed through all the sign-in steps, for sign-in to succeed. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetAuthenticationRequirement()(*string) {
if m == nil {
return nil
} else {
return m.authenticationRequirement
}
}
// GetAuthenticationRequirementPolicies gets the authenticationRequirementPolicies property value. Sources of authentication requirement, such as conditional access, per-user MFA, identity protection, and security defaults.
func (m *SignIn) GetAuthenticationRequirementPolicies()([]AuthenticationRequirementPolicyable) {
if m == nil {
return nil
} else {
return m.authenticationRequirementPolicies
}
}
// GetAutonomousSystemNumber gets the autonomousSystemNumber property value. The Autonomous System Number (ASN) of the network used by the actor.
func (m *SignIn) GetAutonomousSystemNumber()(*int32) {
if m == nil {
return nil
} else {
return m.autonomousSystemNumber
}
}
// GetAzureResourceId gets the azureResourceId property value. Contains a fully qualified Azure Resource Manager ID of an Azure resource accessed during the sign-in.
func (m *SignIn) GetAzureResourceId()(*string) {
if m == nil {
return nil
} else {
return m.azureResourceId
}
}
// GetClientAppUsed gets the clientAppUsed property value. The legacy client used for sign-in activity. For example: Browser, Exchange ActiveSync, Modern clients, IMAP, MAPI, SMTP, or POP. Supports $filter (eq operator only).
func (m *SignIn) GetClientAppUsed()(*string) {
if m == nil {
return nil
} else {
return m.clientAppUsed
}
}
// GetClientCredentialType gets the clientCredentialType property value. Describes the credential type that a user client or service principal provided to Azure AD to authenticate itself. You may wish to review clientCredentialType to track and eliminate less secure credential types or to watch for clients and service principals using anomalous credential types. The possible values are: none, clientSecret, clientAssertion, federatedIdentityCredential, managedIdentity, certificate, unknownFutureValue.
func (m *SignIn) GetClientCredentialType()(*ClientCredentialType) {
if m == nil {
return nil
} else {
return m.clientCredentialType
}
}
// GetConditionalAccessStatus gets the conditionalAccessStatus property value. The status of the conditional access policy triggered. Possible values: success, failure, notApplied, or unknownFutureValue. Supports $filter (eq operator only).
func (m *SignIn) GetConditionalAccessStatus()(*ConditionalAccessStatus) {
if m == nil {
return nil
} else {
return m.conditionalAccessStatus
}
}
// GetCorrelationId gets the correlationId property value. The identifier that's sent from the client when sign-in is initiated. This is used for troubleshooting the corresponding sign-in activity when calling for support. Supports $filter (eq operator only).
func (m *SignIn) GetCorrelationId()(*string) {
if m == nil {
return nil
} else {
return m.correlationId
}
}
// GetCreatedDateTime gets the createdDateTime property value. The date and time the sign-in was initiated. The Timestamp type is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. Supports $orderby and $filter (eq, le, and ge operators only).
func (m *SignIn) GetCreatedDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {
if m == nil {
return nil
} else {
return m.createdDateTime
}
}
// GetCrossTenantAccessType gets the crossTenantAccessType property value. Describes the type of cross-tenant access used by the actor to access the resource. Possible values are: none, b2bCollaboration, b2bDirectConnect, microsoftSupport, serviceProvider, unknownFutureValue. If the sign in did not cross tenant boundaries, the value is none.
func (m *SignIn) GetCrossTenantAccessType()(*SignInAccessType) {
if m == nil {
return nil
} else {
return m.crossTenantAccessType
}
}
// GetDeviceDetail gets the deviceDetail property value. The device information from where the sign-in occurred. Includes information such as deviceId, OS, and browser. Supports $filter (eq and startsWith operators only) on browser and operatingSystem properties.
func (m *SignIn) GetDeviceDetail()(DeviceDetailable) {
if m == nil {
return nil
} else {
return m.deviceDetail
}
}
// GetFederatedCredentialId gets the federatedCredentialId property value. Contains the identifier of an application's federated identity credential, if a federated identity credential was used to sign in.
func (m *SignIn) GetFederatedCredentialId()(*string) {
if m == nil {
return nil
} else {
return m.federatedCredentialId
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *SignIn) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := m.Entity.GetFieldDeserializers()
res["appDisplayName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetAppDisplayName(val)
}
return nil
}
res["appId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetAppId(val)
}
return nil
}
res["appliedConditionalAccessPolicies"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateAppliedConditionalAccessPolicyFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]AppliedConditionalAccessPolicyable, len(val))
for i, v := range val {
res[i] = v.(AppliedConditionalAccessPolicyable)
}
m.SetAppliedConditionalAccessPolicies(res)
}
return nil
}
res["authenticationContextClassReferences"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateAuthenticationContextFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]AuthenticationContextable, len(val))
for i, v := range val {
res[i] = v.(AuthenticationContextable)
}
m.SetAuthenticationContextClassReferences(res)
}
return nil
}
res["authenticationDetails"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateAuthenticationDetailFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]AuthenticationDetailable, len(val))
for i, v := range val {
res[i] = v.(AuthenticationDetailable)
}
m.SetAuthenticationDetails(res)
}
return nil
}
res["authenticationMethodsUsed"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfPrimitiveValues("string")
if err != nil {
return err
}
if val != nil {
res := make([]string, len(val))
for i, v := range val {
res[i] = *(v.(*string))
}
m.SetAuthenticationMethodsUsed(res)
}
return nil
}
res["authenticationProcessingDetails"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateKeyValueFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]KeyValueable, len(val))
for i, v := range val {
res[i] = v.(KeyValueable)
}
m.SetAuthenticationProcessingDetails(res)
}
return nil
}
res["authenticationProtocol"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseProtocolType)
if err != nil {
return err
}
if val != nil {
m.SetAuthenticationProtocol(val.(*ProtocolType))
}
return nil
}
res["authenticationRequirement"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetAuthenticationRequirement(val)
}
return nil
}
res["authenticationRequirementPolicies"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateAuthenticationRequirementPolicyFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]AuthenticationRequirementPolicyable, len(val))
for i, v := range val {
res[i] = v.(AuthenticationRequirementPolicyable)
}
m.SetAuthenticationRequirementPolicies(res)
}
return nil
}
res["autonomousSystemNumber"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetAutonomousSystemNumber(val)
}
return nil
}
res["azureResourceId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetAzureResourceId(val)
}
return nil
}
res["clientAppUsed"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetClientAppUsed(val)
}
return nil
}
res["clientCredentialType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseClientCredentialType)
if err != nil {
return err
}
if val != nil {
m.SetClientCredentialType(val.(*ClientCredentialType))
}
return nil
}
res["conditionalAccessStatus"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseConditionalAccessStatus)
if err != nil {
return err
}
if val != nil {
m.SetConditionalAccessStatus(val.(*ConditionalAccessStatus))
}
return nil
}
res["correlationId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetCorrelationId(val)
}
return nil
}
res["createdDateTime"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetTimeValue()
if err != nil {
return err
}
if val != nil {
m.SetCreatedDateTime(val)
}
return nil
}
res["crossTenantAccessType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseSignInAccessType)
if err != nil {
return err
}
if val != nil {
m.SetCrossTenantAccessType(val.(*SignInAccessType))
}
return nil
}
res["deviceDetail"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateDeviceDetailFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetDeviceDetail(val.(DeviceDetailable))
}
return nil
}
res["federatedCredentialId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetFederatedCredentialId(val)
}
return nil
}
res["flaggedForReview"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetFlaggedForReview(val)
}
return nil
}
res["homeTenantId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetHomeTenantId(val)
}
return nil
}
res["homeTenantName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetHomeTenantName(val)
}
return nil
}
res["incomingTokenType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseIncomingTokenType)
if err != nil {
return err
}
if val != nil {
m.SetIncomingTokenType(val.(*IncomingTokenType))
}
return nil
}
res["ipAddress"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetIpAddress(val)
}
return nil
}
res["ipAddressFromResourceProvider"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetIpAddressFromResourceProvider(val)
}
return nil
}
res["isInteractive"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetIsInteractive(val)
}
return nil
}
res["isTenantRestricted"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetIsTenantRestricted(val)
}
return nil
}
res["location"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateSignInLocationFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetLocation(val.(SignInLocationable))
}
return nil
}
res["mfaDetail"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateMfaDetailFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetMfaDetail(val.(MfaDetailable))
}
return nil
}
res["networkLocationDetails"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateNetworkLocationDetailFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]NetworkLocationDetailable, len(val))
for i, v := range val {
res[i] = v.(NetworkLocationDetailable)
}
m.SetNetworkLocationDetails(res)
}
return nil
}
res["originalRequestId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetOriginalRequestId(val)
}
return nil
}
res["privateLinkDetails"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreatePrivateLinkDetailsFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetPrivateLinkDetails(val.(PrivateLinkDetailsable))
}
return nil
}
res["processingTimeInMilliseconds"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetProcessingTimeInMilliseconds(val)
}
return nil
}
res["resourceDisplayName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetResourceDisplayName(val)
}
return nil
}
res["resourceId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetResourceId(val)
}
return nil
}
res["resourceServicePrincipalId"] = func (n i878a<PASSWORD>89d26896388a3f487<PASSWORD>27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetResourceServicePrincipalId(val)
}
return nil
}
res["resourceTenantId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetResourceTenantId(val)
}
return nil
}
res["riskDetail"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseRiskDetail)
if err != nil {
return err
}
if val != nil {
m.SetRiskDetail(val.(*RiskDetail))
}
return nil
}
res["riskEventTypes_v2"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfPrimitiveValues("string")
if err != nil {
return err
}
if val != nil {
res := make([]string, len(val))
for i, v := range val {
res[i] = *(v.(*string))
}
m.SetRiskEventTypes_v2(res)
}
return nil
}
res["riskLevelAggregated"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseRiskLevel)
if err != nil {
return err
}
if val != nil {
m.SetRiskLevelAggregated(val.(*RiskLevel))
}
return nil
}
res["riskLevelDuringSignIn"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseRiskLevel)
if err != nil {
return err
}
if val != nil {
m.SetRiskLevelDuringSignIn(val.(*RiskLevel))
}
return nil
}
res["riskState"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseRiskState)
if err != nil {
return err
}
if val != nil {
m.SetRiskState(val.(*RiskState))
}
return nil
}
res["servicePrincipalCredentialKeyId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetServicePrincipalCredentialKeyId(val)
}
return nil
}
res["servicePrincipalCredentialThumbprint"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetServicePrincipalCredentialThumbprint(val)
}
return nil
}
res["servicePrincipalId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetServicePrincipalId(val)
}
return nil
}
res["servicePrincipalName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetServicePrincipalName(val)
}
return nil
}
res["sessionLifetimePolicies"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateSessionLifetimePolicyFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]SessionLifetimePolicyable, len(val))
for i, v := range val {
res[i] = v.(SessionLifetimePolicyable)
}
m.SetSessionLifetimePolicies(res)
}
return nil
}
res["signInEventTypes"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfPrimitiveValues("string")
if err != nil {
return err
}
if val != nil {
res := make([]string, len(val))
for i, v := range val {
res[i] = *(v.(*string))
}
m.SetSignInEventTypes(res)
}
return nil
}
res["signInIdentifier"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetSignInIdentifier(val)
}
return nil
}
res["signInIdentifierType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseSignInIdentifierType)
if err != nil {
return err
}
if val != nil {
m.SetSignInIdentifierType(val.(*SignInIdentifierType))
}
return nil
}
res["status"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetObjectValue(CreateSignInStatusFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
m.SetStatus(val.(SignInStatusable))
}
return nil
}
res["tokenIssuerName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetTokenIssuerName(val)
}
return nil
}
res["tokenIssuerType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseTokenIssuerType)
if err != nil {
return err
}
if val != nil {
m.SetTokenIssuerType(val.(*TokenIssuerType))
}
return nil
}
res["uniqueTokenIdentifier"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetUniqueTokenIdentifier(val)
}
return nil
}
res["userAgent"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetUserAgent(val)
}
return nil
}
res["userDisplayName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetUserDisplayName(val)
}
return nil
}
res["userId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetUserId(val)
}
return nil
}
res["userPrincipalName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetUserPrincipalName(val)
}
return nil
}
res["userType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseSignInUserType)
if err != nil {
return err
}
if val != nil {
m.SetUserType(val.(*SignInUserType))
}
return nil
}
return res
}
// GetFlaggedForReview gets the flaggedForReview property value. During a failed sign in, a user may click a button in the Azure portal to mark the failed event for tenant admins. If a user clicked the button to flag the failed sign in, this value is true.
func (m *SignIn) GetFlaggedForReview()(*bool) {
if m == nil {
return nil
} else {
return m.flaggedForReview
}
}
// GetHomeTenantId gets the homeTenantId property value. The tenant identifier of the user initiating the sign in. Not applicable in Managed Identity or service principal sign ins.
func (m *SignIn) GetHomeTenantId()(*string) {
if m == nil {
return nil
} else {
return m.homeTenantId
}
}
// GetHomeTenantName gets the homeTenantName property value. For user sign ins, the identifier of the tenant that the user is a member of. Only populated in cases where the home tenant has provided affirmative consent to Azure AD to show the tenant content.
func (m *SignIn) GetHomeTenantName()(*string) {
if m == nil {
return nil
} else {
return m.homeTenantName
}
}
// GetIncomingTokenType gets the incomingTokenType property value. Indicates the token types that were presented to Azure AD to authenticate the actor in the sign in. The possible values are: none, primaryRefreshToken, saml11, saml20, unknownFutureValue, remoteDesktopToken. NOTE Azure AD may have also used token types not listed in this Enum type to authenticate the actor. Do not infer the lack of a token if it is not one of the types listed. Also, please note that you must use the Prefer: include-unknown-enum-members request header to get the following value(s) in this evolvable enum: remoteDesktopToken.
func (m *SignIn) GetIncomingTokenType()(*IncomingTokenType) {
if m == nil {
return nil
} else {
return m.incomingTokenType
}
}
// GetIpAddress gets the ipAddress property value. The IP address of the client from where the sign-in occurred. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetIpAddress()(*string) {
if m == nil {
return nil
} else {
return m.ipAddress
}
}
// GetIpAddressFromResourceProvider gets the ipAddressFromResourceProvider property value. The IP address a user used to reach a resource provider, used to determine Conditional Access compliance for some policies. For example, when a user interacts with Exchange Online, the IP address Exchange receives from the user may be recorded here. This value is often null.
func (m *SignIn) GetIpAddressFromResourceProvider()(*string) {
if m == nil {
return nil
} else {
return m.ipAddressFromResourceProvider
}
}
// GetIsInteractive gets the isInteractive property value. Indicates whether a user sign in is interactive. In interactive sign in, the user provides an authentication factor to Azure AD. These factors include passwords, responses to MFA challenges, biometric factors, or QR codes that a user provides to Azure AD or an associated app. In non-interactive sign in, the user doesn't provide an authentication factor. Instead, the client app uses a token or code to authenticate or access a resource on behalf of a user. Non-interactive sign ins are commonly used for a client to sign in on a user's behalf in a process transparent to the user.
func (m *SignIn) GetIsInteractive()(*bool) {
if m == nil {
return nil
} else {
return m.isInteractive
}
}
// GetIsTenantRestricted gets the isTenantRestricted property value. Shows whether the sign in event was subject to an Azure AD tenant restriction policy.
func (m *SignIn) GetIsTenantRestricted()(*bool) {
if m == nil {
return nil
} else {
return m.isTenantRestricted
}
}
// GetLocation gets the location property value. The city, state, and 2 letter country code from where the sign-in occurred. Supports $filter (eq and startsWith operators only) on city, state, and countryOrRegion properties.
func (m *SignIn) GetLocation()(SignInLocationable) {
if m == nil {
return nil
} else {
return m.location
}
}
// GetMfaDetail gets the mfaDetail property value. The mfaDetail property
func (m *SignIn) GetMfaDetail()(MfaDetailable) {
if m == nil {
return nil
} else {
return m.mfaDetail
}
}
// GetNetworkLocationDetails gets the networkLocationDetails property value. The network location details including the type of network used and its names.
func (m *SignIn) GetNetworkLocationDetails()([]NetworkLocationDetailable) {
if m == nil {
return nil
} else {
return m.networkLocationDetails
}
}
// GetOriginalRequestId gets the originalRequestId property value. The request identifier of the first request in the authentication sequence. Supports $filter (eq operator only).
func (m *SignIn) GetOriginalRequestId()(*string) {
if m == nil {
return nil
} else {
return m.originalRequestId
}
}
// GetPrivateLinkDetails gets the privateLinkDetails property value. Contains information about the Azure AD Private Link policy that is associated with the sign in event.
func (m *SignIn) GetPrivateLinkDetails()(PrivateLinkDetailsable) {
if m == nil {
return nil
} else {
return m.privateLinkDetails
}
}
// GetProcessingTimeInMilliseconds gets the processingTimeInMilliseconds property value. The request processing time in milliseconds in AD STS.
func (m *SignIn) GetProcessingTimeInMilliseconds()(*int32) {
if m == nil {
return nil
} else {
return m.processingTimeInMilliseconds
}
}
// GetResourceDisplayName gets the resourceDisplayName property value. The name of the resource that the user signed in to. Supports $filter (eq operator only).
func (m *SignIn) GetResourceDisplayName()(*string) {
if m == nil {
return nil
} else {
return m.resourceDisplayName
}
}
// GetResourceId gets the resourceId property value. The identifier of the resource that the user signed in to. Supports $filter (eq operator only).
func (m *SignIn) GetResourceId()(*string) {
if m == nil {
return nil
} else {
return m.resourceId
}
}
// GetResourceServicePrincipalId gets the resourceServicePrincipalId property value. The identifier of the service principal representing the target resource in the sign-in event.
func (m *SignIn) GetResourceServicePrincipalId()(*string) {
if m == nil {
return nil
} else {
return m.resourceServicePrincipalId
}
}
// GetResourceTenantId gets the resourceTenantId property value. The tenant identifier of the resource referenced in the sign in.
func (m *SignIn) GetResourceTenantId()(*string) {
if m == nil {
return nil
} else {
return m.resourceTenantId
}
}
// GetRiskDetail gets the riskDetail property value. The reason behind a specific state of a risky user, sign-in, or a risk event. Possible values: none, adminGeneratedTemporaryPassword, userPerformedSecuredPasswordChange, userPerformedSecuredPasswordReset, adminConfirmedSigninSafe, aiConfirmedSigninSafe, userPassedMFADrivenByRiskBasedPolicy, adminDismissedAllRiskForUser, adminConfirmedSigninCompromised, or unknownFutureValue. The value none means that no action has been performed on the user or sign-in so far. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers are returned hidden.
func (m *SignIn) GetRiskDetail()(*RiskDetail) {
if m == nil {
return nil
} else {
return m.riskDetail
}
}
// GetRiskEventTypes_v2 gets the riskEventTypes_v2 property value. The list of risk event types associated with the sign-in. Possible values: unlikelyTravel, anonymizedIPAddress, maliciousIPAddress, unfamiliarFeatures, malwareInfectedIPAddress, suspiciousIPAddress, leakedCredentials, investigationsThreatIntelligence, generic, or unknownFutureValue. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetRiskEventTypes_v2()([]string) {
if m == nil {
return nil
} else {
return m.riskEventTypes_v2
}
}
// GetRiskLevelAggregated gets the riskLevelAggregated property value. The aggregated risk level. Possible values: none, low, medium, high, hidden, or unknownFutureValue. The value hidden means the user or sign-in was not enabled for Azure AD Identity Protection. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers are returned hidden.
func (m *SignIn) GetRiskLevelAggregated()(*RiskLevel) {
if m == nil {
return nil
} else {
return m.riskLevelAggregated
}
}
// GetRiskLevelDuringSignIn gets the riskLevelDuringSignIn property value. The risk level during sign-in. Possible values: none, low, medium, high, hidden, or unknownFutureValue. The value hidden means the user or sign-in was not enabled for Azure AD Identity Protection. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers are returned hidden.
func (m *SignIn) GetRiskLevelDuringSignIn()(*RiskLevel) {
if m == nil {
return nil
} else {
return m.riskLevelDuringSignIn
}
}
// GetRiskState gets the riskState property value. The risk state of a risky user, sign-in, or a risk event. Possible values: none, confirmedSafe, remediated, dismissed, atRisk, confirmedCompromised, or unknownFutureValue. Supports $filter (eq operator only).
func (m *SignIn) GetRiskState()(*RiskState) {
if m == nil {
return nil
} else {
return m.riskState
}
}
// GetServicePrincipalCredentialKeyId gets the servicePrincipalCredentialKeyId property value. The unique identifier of the key credential used by the service principal to authenticate.
func (m *SignIn) GetServicePrincipalCredentialKeyId()(*string) {
if m == nil {
return nil
} else {
return m.servicePrincipalCredentialKeyId
}
}
// GetServicePrincipalCredentialThumbprint gets the servicePrincipalCredentialThumbprint property value. The certificate thumbprint of the certificate used by the service principal to authenticate.
func (m *SignIn) GetServicePrincipalCredentialThumbprint()(*string) {
if m == nil {
return nil
} else {
return m.servicePrincipalCredentialThumbprint
}
}
// GetServicePrincipalId gets the servicePrincipalId property value. The application identifier used for sign-in. This field is populated when you are signing in using an application. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetServicePrincipalId()(*string) {
if m == nil {
return nil
} else {
return m.servicePrincipalId
}
}
// GetServicePrincipalName gets the servicePrincipalName property value. The application name used for sign-in. This field is populated when you are signing in using an application. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetServicePrincipalName()(*string) {
if m == nil {
return nil
} else {
return m.servicePrincipalName
}
}
// GetSessionLifetimePolicies gets the sessionLifetimePolicies property value. Any conditional access session management policies that were applied during the sign-in event.
func (m *SignIn) GetSessionLifetimePolicies()([]SessionLifetimePolicyable) {
if m == nil {
return nil
} else {
return m.sessionLifetimePolicies
}
}
// GetSignInEventTypes gets the signInEventTypes property value. Indicates the category of sign in that the event represents. For user sign ins, the category can be interactiveUser or nonInteractiveUser and corresponds to the value for the isInteractive property on the signin resource. For managed identity sign ins, the category is managedIdentity. For service principal sign ins, the category is servicePrincipal. Possible values are: interactiveUser, nonInteractiveUser, servicePrincipal, managedIdentity, unknownFutureValue. Supports $filter (eq, ne).
func (m *SignIn) GetSignInEventTypes()([]string) {
if m == nil {
return nil
} else {
return m.signInEventTypes
}
}
// GetSignInIdentifier gets the signInIdentifier property value. The identification that the user provided to sign in. It may be the userPrincipalName but it's also populated when a user signs in using other identifiers.
func (m *SignIn) GetSignInIdentifier()(*string) {
if m == nil {
return nil
} else {
return m.signInIdentifier
}
}
// GetSignInIdentifierType gets the signInIdentifierType property value. The type of sign in identifier. Possible values are: userPrincipalName, phoneNumber, proxyAddress, qrCode, onPremisesUserPrincipalName, unknownFutureValue.
func (m *SignIn) GetSignInIdentifierType()(*SignInIdentifierType) {
if m == nil {
return nil
} else {
return m.signInIdentifierType
}
}
// GetStatus gets the status property value. The sign-in status. Includes the error code and description of the error (in case of a sign-in failure). Supports $filter (eq operator only) on errorCode property.
func (m *SignIn) GetStatus()(SignInStatusable) {
if m == nil {
return nil
} else {
return m.status
}
}
// GetTokenIssuerName gets the tokenIssuerName property value. The name of the identity provider. For example, sts.microsoft.com. Supports $filter (eq operator only).
func (m *SignIn) GetTokenIssuerName()(*string) {
if m == nil {
return nil
} else {
return m.tokenIssuerName
}
}
// GetTokenIssuerType gets the tokenIssuerType property value. The type of identity provider. The possible values are: AzureAD, ADFederationServices, UnknownFutureValue, AzureADBackupAuth, ADFederationServicesMFAAdapter, NPSExtension. Note that you must use the Prefer: include-unknown-enum-members request header to get the following values in this evolvable enum: AzureADBackupAuth , ADFederationServicesMFAAdapter , NPSExtension.
func (m *SignIn) GetTokenIssuerType()(*TokenIssuerType) {
if m == nil {
return nil
} else {
return m.tokenIssuerType
}
}
// GetUniqueTokenIdentifier gets the uniqueTokenIdentifier property value. A unique base64 encoded request identifier used to track tokens issued by Azure AD as they are redeemed at resource providers.
func (m *SignIn) GetUniqueTokenIdentifier()(*string) {
if m == nil {
return nil
} else {
return m.uniqueTokenIdentifier
}
}
// GetUserAgent gets the userAgent property value. The user agent information related to sign-in. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetUserAgent()(*string) {
if m == nil {
return nil
} else {
return m.userAgent
}
}
// GetUserDisplayName gets the userDisplayName property value. The display name of the user. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetUserDisplayName()(*string) {
if m == nil {
return nil
} else {
return m.userDisplayName
}
}
// GetUserId gets the userId property value. The identifier of the user. Supports $filter (eq operator only).
func (m *SignIn) GetUserId()(*string) {
if m == nil {
return nil
} else {
return m.userId
}
}
// GetUserPrincipalName gets the userPrincipalName property value. The UPN of the user. Supports $filter (eq and startsWith operators only).
func (m *SignIn) GetUserPrincipalName()(*string) {
if m == nil {
return nil
} else {
return m.userPrincipalName
}
}
// GetUserType gets the userType property value. Identifies whether the user is a member or guest in the tenant. Possible values are: member, guest, unknownFutureValue.
func (m *SignIn) GetUserType()(*SignInUserType) {
if m == nil {
return nil
} else {
return m.userType
}
}
// Serialize serializes information the current object
func (m *SignIn) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
err := m.Entity.Serialize(writer)
if err != nil {
return err
}
{
err = writer.WriteStringValue("appDisplayName", m.GetAppDisplayName())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("appId", m.GetAppId())
if err != nil {
return err
}
}
if m.GetAppliedConditionalAccessPolicies() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAppliedConditionalAccessPolicies()))
for i, v := range m.GetAppliedConditionalAccessPolicies() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("appliedConditionalAccessPolicies", cast)
if err != nil {
return err
}
}
if m.GetAuthenticationContextClassReferences() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAuthenticationContextClassReferences()))
for i, v := range m.GetAuthenticationContextClassReferences() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("authenticationContextClassReferences", cast)
if err != nil {
return err
}
}
if m.GetAuthenticationDetails() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAuthenticationDetails()))
for i, v := range m.GetAuthenticationDetails() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("authenticationDetails", cast)
if err != nil {
return err
}
}
if m.GetAuthenticationMethodsUsed() != nil {
err = writer.WriteCollectionOfStringValues("authenticationMethodsUsed", m.GetAuthenticationMethodsUsed())
if err != nil {
return err
}
}
if m.GetAuthenticationProcessingDetails() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAuthenticationProcessingDetails()))
for i, v := range m.GetAuthenticationProcessingDetails() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("authenticationProcessingDetails", cast)
if err != nil {
return err
}
}
if m.GetAuthenticationProtocol() != nil {
cast := (*m.GetAuthenticationProtocol()).String()
err = writer.WriteStringValue("authenticationProtocol", &cast)
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("authenticationRequirement", m.GetAuthenticationRequirement())
if err != nil {
return err
}
}
if m.GetAuthenticationRequirementPolicies() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAuthenticationRequirementPolicies()))
for i, v := range m.GetAuthenticationRequirementPolicies() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("authenticationRequirementPolicies", cast)
if err != nil {
return err
}
}
{
err = writer.WriteInt32Value("autonomousSystemNumber", m.GetAutonomousSystemNumber())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("azureResourceId", m.GetAzureResourceId())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("clientAppUsed", m.GetClientAppUsed())
if err != nil {
return err
}
}
if m.GetClientCredentialType() != nil {
cast := (*m.GetClientCredentialType()).String()
err = writer.WriteStringValue("clientCredentialType", &cast)
if err != nil {
return err
}
}
if m.GetConditionalAccessStatus() != nil {
cast := (*m.GetConditionalAccessStatus()).String()
err = writer.WriteStringValue("conditionalAccessStatus", &cast)
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("correlationId", m.GetCorrelationId())
if err != nil {
return err
}
}
{
err = writer.WriteTimeValue("createdDateTime", m.GetCreatedDateTime())
if err != nil {
return err
}
}
if m.GetCrossTenantAccessType() != nil {
cast := (*m.GetCrossTenantAccessType()).String()
err = writer.WriteStringValue("crossTenantAccessType", &cast)
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("deviceDetail", m.GetDeviceDetail())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("federatedCredentialId", m.GetFederatedCredentialId())
if err != nil {
return err
}
}
{
err = writer.WriteBoolValue("flaggedForReview", m.GetFlaggedForReview())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("homeTenantId", m.GetHomeTenantId())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("homeTenantName", m.GetHomeTenantName())
if err != nil {
return err
}
}
if m.GetIncomingTokenType() != nil {
cast := (*m.GetIncomingTokenType()).String()
err = writer.WriteStringValue("incomingTokenType", &cast)
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("ipAddress", m.GetIpAddress())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("ipAddressFromResourceProvider", m.GetIpAddressFromResourceProvider())
if err != nil {
return err
}
}
{
err = writer.WriteBoolValue("isInteractive", m.GetIsInteractive())
if err != nil {
return err
}
}
{
err = writer.WriteBoolValue("isTenantRestricted", m.GetIsTenantRestricted())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("location", m.GetLocation())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("mfaDetail", m.GetMfaDetail())
if err != nil {
return err
}
}
if m.GetNetworkLocationDetails() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetNetworkLocationDetails()))
for i, v := range m.GetNetworkLocationDetails() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("networkLocationDetails", cast)
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("originalRequestId", m.GetOriginalRequestId())
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("privateLinkDetails", m.GetPrivateLinkDetails())
if err != nil {
return err
}
}
{
err = writer.WriteInt32Value("processingTimeInMilliseconds", m.GetProcessingTimeInMilliseconds())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("resourceDisplayName", m.GetResourceDisplayName())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("resourceId", m.GetResourceId())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("resourceServicePrincipalId", m.GetResourceServicePrincipalId())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("resourceTenantId", m.GetResourceTenantId())
if err != nil {
return err
}
}
if m.GetRiskDetail() != nil {
cast := (*m.GetRiskDetail()).String()
err = writer.WriteStringValue("riskDetail", &cast)
if err != nil {
return err
}
}
if m.GetRiskEventTypes_v2() != nil {
err = writer.WriteCollectionOfStringValues("riskEventTypes_v2", m.GetRiskEventTypes_v2())
if err != nil {
return err
}
}
if m.GetRiskLevelAggregated() != nil {
cast := (*m.GetRiskLevelAggregated()).String()
err = writer.WriteStringValue("riskLevelAggregated", &cast)
if err != nil {
return err
}
}
if m.GetRiskLevelDuringSignIn() != nil {
cast := (*m.GetRiskLevelDuringSignIn()).String()
err = writer.WriteStringValue("riskLevelDuringSignIn", &cast)
if err != nil {
return err
}
}
if m.GetRiskState() != nil {
cast := (*m.GetRiskState()).String()
err = writer.WriteStringValue("riskState", &cast)
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("servicePrincipalCredentialKeyId", m.GetServicePrincipalCredentialKeyId())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("servicePrincipalCredentialThumbprint", m.GetServicePrincipalCredentialThumbprint())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("servicePrincipalId", m.GetServicePrincipalId())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("servicePrincipalName", m.GetServicePrincipalName())
if err != nil {
return err
}
}
if m.GetSessionLifetimePolicies() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSessionLifetimePolicies()))
for i, v := range m.GetSessionLifetimePolicies() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("sessionLifetimePolicies", cast)
if err != nil {
return err
}
}
if m.GetSignInEventTypes() != nil {
err = writer.WriteCollectionOfStringValues("signInEventTypes", m.GetSignInEventTypes())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("signInIdentifier", m.GetSignInIdentifier())
if err != nil {
return err
}
}
if m.GetSignInIdentifierType() != nil {
cast := (*m.GetSignInIdentifierType()).String()
err = writer.WriteStringValue("signInIdentifierType", &cast)
if err != nil {
return err
}
}
{
err = writer.WriteObjectValue("status", m.GetStatus())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("tokenIssuerName", m.GetTokenIssuerName())
if err != nil {
return err
}
}
if m.GetTokenIssuerType() != nil {
cast := (*m.GetTokenIssuerType()).String()
err = writer.WriteStringValue("tokenIssuerType", &cast)
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("uniqueTokenIdentifier", m.GetUniqueTokenIdentifier())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("userAgent", m.GetUserAgent())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("userDisplayName", m.GetUserDisplayName())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("userId", m.GetUserId())
if err != nil {
return err
}
}
{
err = writer.WriteStringValue("userPrincipalName", m.GetUserPrincipalName())
if err != nil {
return err
}
}
if m.GetUserType() != nil {
cast := (*m.GetUserType()).String()
err = writer.WriteStringValue("userType", &cast)
if err != nil {
return err
}
}
return nil
}
// SetAppDisplayName sets the appDisplayName property value. The application name displayed in the Azure Portal. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetAppDisplayName(value *string)() {
if m != nil {
m.appDisplayName = value
}
}
// SetAppId sets the appId property value. The application identifier in Azure Active Directory. Supports $filter (eq operator only).
func (m *SignIn) SetAppId(value *string)() {
if m != nil {
m.appId = value
}
}
// SetAppliedConditionalAccessPolicies sets the appliedConditionalAccessPolicies property value. A list of conditional access policies that are triggered by the corresponding sign-in activity.
func (m *SignIn) SetAppliedConditionalAccessPolicies(value []AppliedConditionalAccessPolicyable)() {
if m != nil {
m.appliedConditionalAccessPolicies = value
}
}
// SetAuthenticationContextClassReferences sets the authenticationContextClassReferences property value. Contains a collection of values that represent the conditional access authentication contexts applied to the sign-in.
func (m *SignIn) SetAuthenticationContextClassReferences(value []AuthenticationContextable)() {
if m != nil {
m.authenticationContextClassReferences = value
}
}
// SetAuthenticationDetails sets the authenticationDetails property value. The result of the authentication attempt and additional details on the authentication method.
func (m *SignIn) SetAuthenticationDetails(value []AuthenticationDetailable)() {
if m != nil {
m.authenticationDetails = value
}
}
// SetAuthenticationMethodsUsed sets the authenticationMethodsUsed property value. The authentication methods used. Possible values: SMS, Authenticator App, App Verification code, Password, FIDO, PTA, or PHS.
func (m *SignIn) SetAuthenticationMethodsUsed(value []string)() {
if m != nil {
m.authenticationMethodsUsed = value
}
}
// SetAuthenticationProcessingDetails sets the authenticationProcessingDetails property value. Additional authentication processing details, such as the agent name in case of PTA/PHS or Server/farm name in case of federated authentication.
func (m *SignIn) SetAuthenticationProcessingDetails(value []KeyValueable)() {
if m != nil {
m.authenticationProcessingDetails = value
}
}
// SetAuthenticationProtocol sets the authenticationProtocol property value. Lists the protocol type or grant type used in the authentication. The possible values are: none, oAuth2, ropc, wsFederation, saml20, deviceCode, unknownFutureValue. For authentications that use protocols other than the possible values listed, the protocol type is listed as none.
func (m *SignIn) SetAuthenticationProtocol(value *ProtocolType)() {
if m != nil {
m.authenticationProtocol = value
}
}
// SetAuthenticationRequirement sets the authenticationRequirement property value. This holds the highest level of authentication needed through all the sign-in steps, for sign-in to succeed. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetAuthenticationRequirement(value *string)() {
if m != nil {
m.authenticationRequirement = value
}
}
// SetAuthenticationRequirementPolicies sets the authenticationRequirementPolicies property value. Sources of authentication requirement, such as conditional access, per-user MFA, identity protection, and security defaults.
func (m *SignIn) SetAuthenticationRequirementPolicies(value []AuthenticationRequirementPolicyable)() {
if m != nil {
m.authenticationRequirementPolicies = value
}
}
// SetAutonomousSystemNumber sets the autonomousSystemNumber property value. The Autonomous System Number (ASN) of the network used by the actor.
func (m *SignIn) SetAutonomousSystemNumber(value *int32)() {
if m != nil {
m.autonomousSystemNumber = value
}
}
// SetAzureResourceId sets the azureResourceId property value. Contains a fully qualified Azure Resource Manager ID of an Azure resource accessed during the sign-in.
func (m *SignIn) SetAzureResourceId(value *string)() {
if m != nil {
m.azureResourceId = value
}
}
// SetClientAppUsed sets the clientAppUsed property value. The legacy client used for sign-in activity. For example: Browser, Exchange ActiveSync, Modern clients, IMAP, MAPI, SMTP, or POP. Supports $filter (eq operator only).
func (m *SignIn) SetClientAppUsed(value *string)() {
if m != nil {
m.clientAppUsed = value
}
}
// SetClientCredentialType sets the clientCredentialType property value. Describes the credential type that a user client or service principal provided to Azure AD to authenticate itself. You may wish to review clientCredentialType to track and eliminate less secure credential types or to watch for clients and service principals using anomalous credential types. The possible values are: none, clientSecret, clientAssertion, federatedIdentityCredential, managedIdentity, certificate, unknownFutureValue.
func (m *SignIn) SetClientCredentialType(value *ClientCredentialType)() {
if m != nil {
m.clientCredentialType = value
}
}
// SetConditionalAccessStatus sets the conditionalAccessStatus property value. The status of the conditional access policy triggered. Possible values: success, failure, notApplied, or unknownFutureValue. Supports $filter (eq operator only).
func (m *SignIn) SetConditionalAccessStatus(value *ConditionalAccessStatus)() {
if m != nil {
m.conditionalAccessStatus = value
}
}
// SetCorrelationId sets the correlationId property value. The identifier that's sent from the client when sign-in is initiated. This is used for troubleshooting the corresponding sign-in activity when calling for support. Supports $filter (eq operator only).
func (m *SignIn) SetCorrelationId(value *string)() {
if m != nil {
m.correlationId = value
}
}
// SetCreatedDateTime sets the createdDateTime property value. The date and time the sign-in was initiated. The Timestamp type is always in UTC time. For example, midnight UTC on Jan 1, 2014 is 2014-01-01T00:00:00Z. Supports $orderby and $filter (eq, le, and ge operators only).
func (m *SignIn) SetCreatedDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() {
if m != nil {
m.createdDateTime = value
}
}
// SetCrossTenantAccessType sets the crossTenantAccessType property value. Describes the type of cross-tenant access used by the actor to access the resource. Possible values are: none, b2bCollaboration, b2bDirectConnect, microsoftSupport, serviceProvider, unknownFutureValue. If the sign in did not cross tenant boundaries, the value is none.
func (m *SignIn) SetCrossTenantAccessType(value *SignInAccessType)() {
if m != nil {
m.crossTenantAccessType = value
}
}
// SetDeviceDetail sets the deviceDetail property value. The device information from where the sign-in occurred. Includes information such as deviceId, OS, and browser. Supports $filter (eq and startsWith operators only) on browser and operatingSystem properties.
func (m *SignIn) SetDeviceDetail(value DeviceDetailable)() {
if m != nil {
m.deviceDetail = value
}
}
// SetFederatedCredentialId sets the federatedCredentialId property value. Contains the identifier of an application's federated identity credential, if a federated identity credential was used to sign in.
func (m *SignIn) SetFederatedCredentialId(value *string)() {
if m != nil {
m.federatedCredentialId = value
}
}
// SetFlaggedForReview sets the flaggedForReview property value. During a failed sign in, a user may click a button in the Azure portal to mark the failed event for tenant admins. If a user clicked the button to flag the failed sign in, this value is true.
func (m *SignIn) SetFlaggedForReview(value *bool)() {
if m != nil {
m.flaggedForReview = value
}
}
// SetHomeTenantId sets the homeTenantId property value. The tenant identifier of the user initiating the sign in. Not applicable in Managed Identity or service principal sign ins.
func (m *SignIn) SetHomeTenantId(value *string)() {
if m != nil {
m.homeTenantId = value
}
}
// SetHomeTenantName sets the homeTenantName property value. For user sign ins, the identifier of the tenant that the user is a member of. Only populated in cases where the home tenant has provided affirmative consent to Azure AD to show the tenant content.
func (m *SignIn) SetHomeTenantName(value *string)() {
if m != nil {
m.homeTenantName = value
}
}
// SetIncomingTokenType sets the incomingTokenType property value. Indicates the token types that were presented to Azure AD to authenticate the actor in the sign in. The possible values are: none, primaryRefreshToken, saml11, saml20, unknownFutureValue, remoteDesktopToken. NOTE Azure AD may have also used token types not listed in this Enum type to authenticate the actor. Do not infer the lack of a token if it is not one of the types listed. Also, please note that you must use the Prefer: include-unknown-enum-members request header to get the following value(s) in this evolvable enum: remoteDesktopToken.
func (m *SignIn) SetIncomingTokenType(value *IncomingTokenType)() {
if m != nil {
m.incomingTokenType = value
}
}
// SetIpAddress sets the ipAddress property value. The IP address of the client from where the sign-in occurred. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetIpAddress(value *string)() {
if m != nil {
m.ipAddress = value
}
}
// SetIpAddressFromResourceProvider sets the ipAddressFromResourceProvider property value. The IP address a user used to reach a resource provider, used to determine Conditional Access compliance for some policies. For example, when a user interacts with Exchange Online, the IP address Exchange receives from the user may be recorded here. This value is often null.
func (m *SignIn) SetIpAddressFromResourceProvider(value *string)() {
if m != nil {
m.ipAddressFromResourceProvider = value
}
}
// SetIsInteractive sets the isInteractive property value. Indicates whether a user sign in is interactive. In interactive sign in, the user provides an authentication factor to Azure AD. These factors include passwords, responses to MFA challenges, biometric factors, or QR codes that a user provides to Azure AD or an associated app. In non-interactive sign in, the user doesn't provide an authentication factor. Instead, the client app uses a token or code to authenticate or access a resource on behalf of a user. Non-interactive sign ins are commonly used for a client to sign in on a user's behalf in a process transparent to the user.
func (m *SignIn) SetIsInteractive(value *bool)() {
if m != nil {
m.isInteractive = value
}
}
// SetIsTenantRestricted sets the isTenantRestricted property value. Shows whether the sign in event was subject to an Azure AD tenant restriction policy.
func (m *SignIn) SetIsTenantRestricted(value *bool)() {
if m != nil {
m.isTenantRestricted = value
}
}
// SetLocation sets the location property value. The city, state, and 2 letter country code from where the sign-in occurred. Supports $filter (eq and startsWith operators only) on city, state, and countryOrRegion properties.
func (m *SignIn) SetLocation(value SignInLocationable)() {
if m != nil {
m.location = value
}
}
// SetMfaDetail sets the mfaDetail property value. The mfaDetail property
func (m *SignIn) SetMfaDetail(value MfaDetailable)() {
if m != nil {
m.mfaDetail = value
}
}
// SetNetworkLocationDetails sets the networkLocationDetails property value. The network location details including the type of network used and its names.
func (m *SignIn) SetNetworkLocationDetails(value []NetworkLocationDetailable)() {
if m != nil {
m.networkLocationDetails = value
}
}
// SetOriginalRequestId sets the originalRequestId property value. The request identifier of the first request in the authentication sequence. Supports $filter (eq operator only).
func (m *SignIn) SetOriginalRequestId(value *string)() {
if m != nil {
m.originalRequestId = value
}
}
// SetPrivateLinkDetails sets the privateLinkDetails property value. Contains information about the Azure AD Private Link policy that is associated with the sign in event.
func (m *SignIn) SetPrivateLinkDetails(value PrivateLinkDetailsable)() {
if m != nil {
m.privateLinkDetails = value
}
}
// SetProcessingTimeInMilliseconds sets the processingTimeInMilliseconds property value. The request processing time in milliseconds in AD STS.
func (m *SignIn) SetProcessingTimeInMilliseconds(value *int32)() {
if m != nil {
m.processingTimeInMilliseconds = value
}
}
// SetResourceDisplayName sets the resourceDisplayName property value. The name of the resource that the user signed in to. Supports $filter (eq operator only).
func (m *SignIn) SetResourceDisplayName(value *string)() {
if m != nil {
m.resourceDisplayName = value
}
}
// SetResourceId sets the resourceId property value. The identifier of the resource that the user signed in to. Supports $filter (eq operator only).
func (m *SignIn) SetResourceId(value *string)() {
if m != nil {
m.resourceId = value
}
}
// SetResourceServicePrincipalId sets the resourceServicePrincipalId property value. The identifier of the service principal representing the target resource in the sign-in event.
func (m *SignIn) SetResourceServicePrincipalId(value *string)() {
if m != nil {
m.resourceServicePrincipalId = value
}
}
// SetResourceTenantId sets the resourceTenantId property value. The tenant identifier of the resource referenced in the sign in.
func (m *SignIn) SetResourceTenantId(value *string)() {
if m != nil {
m.resourceTenantId = value
}
}
// SetRiskDetail sets the riskDetail property value. The reason behind a specific state of a risky user, sign-in, or a risk event. Possible values: none, adminGeneratedTemporaryPassword, userPerformedSecuredPasswordChange, userPerformedSecuredPasswordReset, adminConfirmedSigninSafe, aiConfirmedSigninSafe, userPassedMFADrivenByRiskBasedPolicy, adminDismissedAllRiskForUser, adminConfirmedSigninCompromised, or unknownFutureValue. The value none means that no action has been performed on the user or sign-in so far. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers are returned hidden.
func (m *SignIn) SetRiskDetail(value *RiskDetail)() {
if m != nil {
m.riskDetail = value
}
}
// SetRiskEventTypes_v2 sets the riskEventTypes_v2 property value. The list of risk event types associated with the sign-in. Possible values: unlikelyTravel, anonymizedIPAddress, maliciousIPAddress, unfamiliarFeatures, malwareInfectedIPAddress, suspiciousIPAddress, leakedCredentials, investigationsThreatIntelligence, generic, or unknownFutureValue. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetRiskEventTypes_v2(value []string)() {
if m != nil {
m.riskEventTypes_v2 = value
}
}
// SetRiskLevelAggregated sets the riskLevelAggregated property value. The aggregated risk level. Possible values: none, low, medium, high, hidden, or unknownFutureValue. The value hidden means the user or sign-in was not enabled for Azure AD Identity Protection. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers are returned hidden.
func (m *SignIn) SetRiskLevelAggregated(value *RiskLevel)() {
if m != nil {
m.riskLevelAggregated = value
}
}
// SetRiskLevelDuringSignIn sets the riskLevelDuringSignIn property value. The risk level during sign-in. Possible values: none, low, medium, high, hidden, or unknownFutureValue. The value hidden means the user or sign-in was not enabled for Azure AD Identity Protection. Supports $filter (eq operator only). Note: Details for this property are only available for Azure AD Premium P2 customers. All other customers are returned hidden.
func (m *SignIn) SetRiskLevelDuringSignIn(value *RiskLevel)() {
if m != nil {
m.riskLevelDuringSignIn = value
}
}
// SetRiskState sets the riskState property value. The risk state of a risky user, sign-in, or a risk event. Possible values: none, confirmedSafe, remediated, dismissed, atRisk, confirmedCompromised, or unknownFutureValue. Supports $filter (eq operator only).
func (m *SignIn) SetRiskState(value *RiskState)() {
if m != nil {
m.riskState = value
}
}
// SetServicePrincipalCredentialKeyId sets the servicePrincipalCredentialKeyId property value. The unique identifier of the key credential used by the service principal to authenticate.
func (m *SignIn) SetServicePrincipalCredentialKeyId(value *string)() {
if m != nil {
m.servicePrincipalCredentialKeyId = value
}
}
// SetServicePrincipalCredentialThumbprint sets the servicePrincipalCredentialThumbprint property value. The certificate thumbprint of the certificate used by the service principal to authenticate.
func (m *SignIn) SetServicePrincipalCredentialThumbprint(value *string)() {
if m != nil {
m.servicePrincipalCredentialThumbprint = value
}
}
// SetServicePrincipalId sets the servicePrincipalId property value. The application identifier used for sign-in. This field is populated when you are signing in using an application. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetServicePrincipalId(value *string)() {
if m != nil {
m.servicePrincipalId = value
}
}
// SetServicePrincipalName sets the servicePrincipalName property value. The application name used for sign-in. This field is populated when you are signing in using an application. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetServicePrincipalName(value *string)() {
if m != nil {
m.servicePrincipalName = value
}
}
// SetSessionLifetimePolicies sets the sessionLifetimePolicies property value. Any conditional access session management policies that were applied during the sign-in event.
func (m *SignIn) SetSessionLifetimePolicies(value []SessionLifetimePolicyable)() {
if m != nil {
m.sessionLifetimePolicies = value
}
}
// SetSignInEventTypes sets the signInEventTypes property value. Indicates the category of sign in that the event represents. For user sign ins, the category can be interactiveUser or nonInteractiveUser and corresponds to the value for the isInteractive property on the signin resource. For managed identity sign ins, the category is managedIdentity. For service principal sign ins, the category is servicePrincipal. Possible values are: interactiveUser, nonInteractiveUser, servicePrincipal, managedIdentity, unknownFutureValue. Supports $filter (eq, ne).
func (m *SignIn) SetSignInEventTypes(value []string)() {
if m != nil {
m.signInEventTypes = value
}
}
// SetSignInIdentifier sets the signInIdentifier property value. The identification that the user provided to sign in. It may be the userPrincipalName but it's also populated when a user signs in using other identifiers.
func (m *SignIn) SetSignInIdentifier(value *string)() {
if m != nil {
m.signInIdentifier = value
}
}
// SetSignInIdentifierType sets the signInIdentifierType property value. The type of sign in identifier. Possible values are: userPrincipalName, phoneNumber, proxyAddress, qrCode, onPremisesUserPrincipalName, unknownFutureValue.
func (m *SignIn) SetSignInIdentifierType(value *SignInIdentifierType)() {
if m != nil {
m.signInIdentifierType = value
}
}
// SetStatus sets the status property value. The sign-in status. Includes the error code and description of the error (in case of a sign-in failure). Supports $filter (eq operator only) on errorCode property.
func (m *SignIn) SetStatus(value SignInStatusable)() {
if m != nil {
m.status = value
}
}
// SetTokenIssuerName sets the tokenIssuerName property value. The name of the identity provider. For example, sts.microsoft.com. Supports $filter (eq operator only).
func (m *SignIn) SetTokenIssuerName(value *string)() {
if m != nil {
m.tokenIssuerName = value
}
}
// SetTokenIssuerType sets the tokenIssuerType property value. The type of identity provider. The possible values are: AzureAD, ADFederationServices, UnknownFutureValue, AzureADBackupAuth, ADFederationServicesMFAAdapter, NPSExtension. Note that you must use the Prefer: include-unknown-enum-members request header to get the following values in this evolvable enum: AzureADBackupAuth , ADFederationServicesMFAAdapter , NPSExtension.
func (m *SignIn) SetTokenIssuerType(value *TokenIssuerType)() {
if m != nil {
m.tokenIssuerType = value
}
}
// SetUniqueTokenIdentifier sets the uniqueTokenIdentifier property value. A unique base64 encoded request identifier used to track tokens issued by Azure AD as they are redeemed at resource providers.
func (m *SignIn) SetUniqueTokenIdentifier(value *string)() {
if m != nil {
m.uniqueTokenIdentifier = value
}
}
// SetUserAgent sets the userAgent property value. The user agent information related to sign-in. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetUserAgent(value *string)() {
if m != nil {
m.userAgent = value
}
}
// SetUserDisplayName sets the userDisplayName property value. The display name of the user. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetUserDisplayName(value *string)() {
if m != nil {
m.userDisplayName = value
}
}
// SetUserId sets the userId property value. The identifier of the user. Supports $filter (eq operator only).
func (m *SignIn) SetUserId(value *string)() {
if m != nil {
m.userId = value
}
}
// SetUserPrincipalName sets the userPrincipalName property value. The UPN of the user. Supports $filter (eq and startsWith operators only).
func (m *SignIn) SetUserPrincipalName(value *string)() {
if m != nil {
m.userPrincipalName = value
}
}
// SetUserType sets the userType property value. Identifies whether the user is a member or guest in the tenant. Possible values are: member, guest, unknownFutureValue.
func (m *SignIn) SetUserType(value *SignInUserType)() {
if m != nil {
m.userType = value
}
} | models/sign_in.go | 0.655997 | 0.483405 | sign_in.go | starcoder |
package astar
import (
. "github.com/Jcowwell/go-algorithm-club/Utils"
)
type Node[E comparable] struct {
vertex E // The graph vertex.
cost float32 // The actual cost between the start vertex and this vertex.
estimate float32 // Estimated (heuristic) cost betweent this vertex and the target vertex.
}
func (n Node[E]) init(vertex E, cost, estimate float32) {
n.vertex = vertex
n.cost = cost
n.estimate = estimate
}
func (n Node[E]) hashValue() uintptr {
return Hash(n.vertex)
}
func less[E comparable, n Node[E]](lhs, rhs Node[E]) bool {
return lhs.cost+lhs.estimate < rhs.cost+lhs.estimate
}
func equal[E comparable, n Node[E]](lhs, rhs Node[E]) bool {
return lhs.vertex == rhs.vertex
}
type Edge[E comparable, V Node[E]] struct {
Vertex V // The edge vertex
cost float32 // The edge's cost.
target float32 // The target vertex.
}
type Graph[E comparable, V Node[E], WE Edge[E, Node[E]]] struct {
Vertex V
Edge WE
Edges func(V) []WE // Lists all edges going out from a vertex.
}
type AStar[E comparable, N Node[E], WE Edge[E, Node[E]], G Graph[E, N, WE]] struct {
graph G // The graph to search on.
heuristic func(N, N) float32 // The heuristic cost function that estimates the cost between two vertices.
open func() // Open list of nodes to expand. HashedHeap
closed map[N]string // Set of vertices already expanded.
costs map[N]float32 // Actual vertex cost for vertices we already encountered (refered to as `g` on the literature).
parents map[N]N // Store the previous node for each expanded node to recreate the path.
init func(G, func(N, N) float32) // Initializes `AStar` with a graph and a heuristic cost function.
path func(N) []N // Finds an optimal path between `source` and `target`. - Precondition: both `source` and `target` belong to `graph`.
expand func(N, N)
cost func(N) float32
buildPath func(N, N) []N
cleanup func()
} | A-Star/a_star.go | 0.75985 | 0.529628 | a_star.go | starcoder |
package tart
// Developed by <NAME> and <NAME>, StochRSI is an oscillator that
// measures the level of RSI relative to its high-low range over a set time period.
// StochRsi applies the Stochastics formula to RSI values, rather than price values,
// making it an indicator of an indicator. The result is an oscillator that
// fluctuates between 0 and 1. In their 1994 book, The New Technical Trader, Chande
// and Kroll explain that RSI can oscillate between 80 and 20 for extended periods
// without reaching extreme levels. Notice that 80 and 20 are used for overbought
// and oversold instead of the more traditional 70 and 30. Traders looking to enter
// a stock based on an overbought or oversold reading in RSI might find themselves
// continuously on the sidelines. Chande and Kroll developed StochRSI to increase
// sensitivity and generate more overbought/oversold signals.
// https://school.stockcharts.com/doku.php?id=technical_indicators:stochrsi
// https://www.investopedia.com/terms/s/stochrsi.asp
type StochRsi struct {
n int64
kN int64
dN int64
util int64
rsi *Rsi
stoch *StochFast
sz int64
}
func NewStochRsi(n int64, kN int64, dt MaType, dN int64) *StochRsi {
return &StochRsi{
n: n,
kN: kN,
dN: dN,
util: n + kN + dN - 1,
rsi: NewRsi(n),
stoch: NewStochFast(kN, dt, dN),
sz: 0,
}
}
func (s *StochRsi) Update(v float64) (float64, float64) {
s.sz++
rsi := s.rsi.Update(v)
if s.sz <= s.n {
return 0, 0
}
k, d := s.stoch.Update(rsi, rsi, rsi)
if s.sz < s.util {
return 0, 0
}
return k, d
}
func (s *StochRsi) InitPeriod() int64 {
return s.util - 1
}
func (s *StochRsi) Valid() bool {
return s.sz > s.InitPeriod()
}
// Developed by <NAME> and <NAME>, StochRSI is an oscillator that
// measures the level of RSI relative to its high-low range over a set time period.
// StochRsi applies the Stochastics formula to RSI values, rather than price values,
// making it an indicator of an indicator. The result is an oscillator that
// fluctuates between 0 and 1. In their 1994 book, The New Technical Trader, Chande
// and Kroll explain that RSI can oscillate between 80 and 20 for extended periods
// without reaching extreme levels. Notice that 80 and 20 are used for overbought
// and oversold instead of the more traditional 70 and 30. Traders looking to enter
// a stock based on an overbought or oversold reading in RSI might find themselves
// continuously on the sidelines. Chande and Kroll developed StochRSI to increase
// sensitivity and generate more overbought/oversold signals.
// https://school.stockcharts.com/doku.php?id=technical_indicators:stochrsi
// https://www.investopedia.com/terms/s/stochrsi.asp
func StochRsiArr(in []float64, n, kN int64, dt MaType, dN int64) ([]float64, []float64) {
k := make([]float64, len(in))
d := make([]float64, len(in))
s := NewStochRsi(n, kN, dt, dN)
for i, v := range in {
k[i], d[i] = s.Update(v)
}
return k, d
} | stochrsi.go | 0.69368 | 0.535281 | stochrsi.go | starcoder |
package oteltest
import (
"context"
"fmt"
"strconv"
"strings"
"sync"
"testing"
"go.opentelemetry.io/otel"
)
type ctxKeyType string
// TextMapCarrier provides a testing storage medium to for a
// TextMapPropagator. It records all the operations it performs.
type TextMapCarrier struct {
mtx sync.Mutex
gets []string
sets [][2]string
data map[string]string
}
// NewTextMapCarrier returns a new *TextMapCarrier populated with data.
func NewTextMapCarrier(data map[string]string) *TextMapCarrier {
copied := make(map[string]string, len(data))
for k, v := range data {
copied[k] = v
}
return &TextMapCarrier{data: copied}
}
// Get returns the value associated with the passed key.
func (c *TextMapCarrier) Get(key string) string {
c.mtx.Lock()
defer c.mtx.Unlock()
c.gets = append(c.gets, key)
return c.data[key]
}
// GotKey tests if c.Get has been called for key.
func (c *TextMapCarrier) GotKey(t *testing.T, key string) bool {
c.mtx.Lock()
defer c.mtx.Unlock()
for _, k := range c.gets {
if k == key {
return true
}
}
t.Errorf("TextMapCarrier.Get(%q) has not been called", key)
return false
}
// GotN tests if n calls to c.Get have been made.
func (c *TextMapCarrier) GotN(t *testing.T, n int) bool {
c.mtx.Lock()
defer c.mtx.Unlock()
if len(c.gets) != n {
t.Errorf("TextMapCarrier.Get was called %d times, not %d", len(c.gets), n)
return false
}
return true
}
// Set stores the key-value pair.
func (c *TextMapCarrier) Set(key, value string) {
c.mtx.Lock()
defer c.mtx.Unlock()
c.sets = append(c.sets, [2]string{key, value})
c.data[key] = value
}
// SetKeyValue tests if c.Set has been called for the key-value pair.
func (c *TextMapCarrier) SetKeyValue(t *testing.T, key, value string) bool {
c.mtx.Lock()
defer c.mtx.Unlock()
var vals []string
for _, pair := range c.sets {
if key == pair[0] {
if value == pair[1] {
return true
}
vals = append(vals, pair[1])
}
}
if len(vals) > 0 {
t.Errorf("TextMapCarrier.Set called with %q and %v values, but not %s", key, vals, value)
}
t.Errorf("TextMapCarrier.Set(%q,%q) has not been called", key, value)
return false
}
// SetN tests if n calls to c.Set have been made.
func (c *TextMapCarrier) SetN(t *testing.T, n int) bool {
c.mtx.Lock()
defer c.mtx.Unlock()
if len(c.sets) != n {
t.Errorf("TextMapCarrier.Set was called %d times, not %d", len(c.sets), n)
return false
}
return true
}
// Reset zeros out the internal state recording of c.
func (c *TextMapCarrier) Reset() {
c.mtx.Lock()
defer c.mtx.Unlock()
c.gets = nil
c.sets = nil
c.data = make(map[string]string)
}
type state struct {
Injections uint64
Extractions uint64
}
func newState(encoded string) state {
if encoded == "" {
return state{}
}
split := strings.SplitN(encoded, ",", 2)
injects, _ := strconv.ParseUint(split[0], 10, 64)
extracts, _ := strconv.ParseUint(split[1], 10, 64)
return state{
Injections: injects,
Extractions: extracts,
}
}
func (s state) String() string {
return fmt.Sprintf("%d,%d", s.Injections, s.Extractions)
}
type TextMapPropagator struct {
Name string
ctxKey ctxKeyType
}
func NewTextMapPropagator(name string) *TextMapPropagator {
return &TextMapPropagator{Name: name, ctxKey: ctxKeyType(name)}
}
func (p *TextMapPropagator) stateFromContext(ctx context.Context) state {
if v := ctx.Value(p.ctxKey); v != nil {
if s, ok := v.(state); ok {
return s
}
}
return state{}
}
func (p *TextMapPropagator) stateFromCarrier(carrier otel.TextMapCarrier) state {
return newState(carrier.Get(p.Name))
}
// Inject set cross-cutting concerns for p from the Context into the carrier.
func (p *TextMapPropagator) Inject(ctx context.Context, carrier otel.TextMapCarrier) {
s := p.stateFromContext(ctx)
s.Injections++
carrier.Set(p.Name, s.String())
}
// InjectedN tests if p has made n injections to carrier.
func (p *TextMapPropagator) InjectedN(t *testing.T, carrier *TextMapCarrier, n int) bool {
if actual := p.stateFromCarrier(carrier).Injections; actual != uint64(n) {
t.Errorf("TextMapPropagator{%q} injected %d times, not %d", p.Name, actual, n)
return false
}
return true
}
// Extract reads cross-cutting concerns for p from the carrier into a Context.
func (p *TextMapPropagator) Extract(ctx context.Context, carrier otel.TextMapCarrier) context.Context {
s := p.stateFromCarrier(carrier)
s.Extractions++
return context.WithValue(ctx, p.ctxKey, s)
}
// ExtractedN tests if p has made n extractions from the lineage of ctx.
// nolint (context is not first arg)
func (p *TextMapPropagator) ExtractedN(t *testing.T, ctx context.Context, n int) bool {
if actual := p.stateFromContext(ctx).Extractions; actual != uint64(n) {
t.Errorf("TextMapPropagator{%q} extracted %d time, not %d", p.Name, actual, n)
return false
}
return true
}
// Fields returns p.Name as the key who's value is set with Inject.
func (p *TextMapPropagator) Fields() []string { return []string{p.Name} } | oteltest/text_map_propagator.go | 0.697403 | 0.41052 | text_map_propagator.go | starcoder |
package assocentity
import (
"math"
"github.com/ndabAP/assocentity/v6/internal/iterator"
"github.com/ndabAP/assocentity/v6/tokenize"
)
type direction int
var (
posDir direction = 1
negDir direction = -1
)
// Do returns the entity distances
func Do(tokenizer tokenize.Tokenizer, psd tokenize.PoSDetermer, entities []string) (map[tokenize.Token]float64, error) {
determTok, err := psd.Determ(tokenizer)
if err != nil {
return map[tokenize.Token]float64{}, err
}
entityTokens, err := tokenizer.TokenizeEntities()
if err != nil {
return map[tokenize.Token]float64{}, err
}
var distAccum = make(map[tokenize.Token][]float64)
// Prepare for generic iterator
di := make(iterator.Elements, len(determTok))
for i, v := range determTok {
di[i] = v
}
determTokTraverser := iterator.New(di)
for determTokTraverser.Next() {
determTokIdx := determTokTraverser.CurrPos()
var (
isEntity bool
entityTraverser *iterator.Iterator
)
for entityIdx := range entityTokens {
// Prepare for generic iterator
e := make(iterator.Elements, len(entityTokens[entityIdx]))
for i, v := range entityTokens[entityIdx] {
e[i] = v
}
entityTraverser = iterator.New(e)
for entityTraverser.Next() {
isEntity = determTokTraverser.CurrElem().(tokenize.Token) == entityTraverser.CurrElem().(tokenize.Token)
// Check if first token matches the entity token
if !isEntity {
break
}
// Check for next token
determTokTraverser.Next()
}
if isEntity {
break
}
}
if isEntity {
// Skip about entity positions
determTokTraverser.SetPos(determTokIdx + entityTraverser.Len() - 1)
continue
}
var dist float64
// Reset because mutated
determTokTraverser.SetPos(determTokIdx)
// Iterate positive direction
posTraverser := iterator.New(di)
posTraverser.SetPos(determTokIdx)
for posTraverser.Next() {
posTraverserIdx := posTraverser.CurrPos()
ok, len := isPartOfEntity(posTraverser, entityTokens, posDir)
if ok {
distAccum[determTokTraverser.CurrElem().(tokenize.Token)] = append(distAccum[determTokTraverser.CurrElem().(tokenize.Token)], dist)
// Skip about entity
posTraverser.SetPos(posTraverserIdx + len - 1)
}
dist++
if ok {
continue
}
// Reset because isPartOfEntity is mutating
posTraverser.SetPos(posTraverserIdx)
}
// Iterate negative direction
dist = 0
negTraverser := iterator.New(di)
negTraverser.SetPos(determTokIdx)
for negTraverser.Prev() {
negTraverserIdx := negTraverser.CurrPos()
ok, len := isPartOfEntity(negTraverser, entityTokens, negDir)
if ok {
distAccum[determTokTraverser.CurrElem().(tokenize.Token)] = append(distAccum[determTokTraverser.CurrElem().(tokenize.Token)], dist)
// Skip about entity
negTraverser.SetPos(negTraverserIdx - len + 1)
}
dist++
if ok {
continue
}
// Reset because isPartOfEntity is mutating
negTraverser.SetPos(negTraverserIdx)
}
}
assocEntities := make(map[tokenize.Token]float64)
// Calculate the distances
for elem, dist := range distAccum {
assocEntities[elem] = avg(dist)
}
return assocEntities, nil
}
// Iterates through entity tokens and returns true if found and positions to skip
func isPartOfEntity(determTokTraverser *iterator.Iterator, entityTokens [][]tokenize.Token, dir direction) (bool, int) {
var (
isEntity bool
entityTraverser *iterator.Iterator
)
for entityIdx := range entityTokens {
// Prepare for generic iterator
e := make(iterator.Elements, len(entityTokens[entityIdx]))
for i, v := range entityTokens[entityIdx] {
e[i] = v
}
entityTraverser = iterator.New(e)
if dir == posDir {
// Positive direction
for entityTraverser.Next() {
isEntity = determTokTraverser.CurrElem().(tokenize.Token).Token == entityTraverser.CurrElem().(tokenize.Token).Token
// Check if first token matches the entity token
if !isEntity {
break
}
// Check for next token
determTokTraverser.Next()
}
} else if dir == negDir {
// Negative direction
entityTraverser.SetPos(entityTraverser.Len() - 1)
for entityTraverser.Prev() {
isEntity = determTokTraverser.CurrElem().(tokenize.Token).Token == entityTraverser.CurrElem().(tokenize.Token).Token
// Check if first token matches the entity token
if !isEntity {
break
}
// Check for next token
determTokTraverser.Prev()
}
}
if isEntity {
return isEntity, entityTraverser.Len()
}
}
return isEntity, entityTraverser.Len()
}
// Returns the average of a float slice
func avg(xs []float64) float64 {
total := 0.0
for _, v := range xs {
total += v
}
return round(total / float64(len(xs)))
}
// Rounds to nearest 0.5
func round(x float64) float64 {
return math.Round(x/0.5) * 0.5
} | assocentity.go | 0.753013 | 0.407392 | assocentity.go | starcoder |
package main
import (
"fmt"
"strings"
)
// We often need our programs to perform operations on collections of data,
// like selecting all items that satisfy a given predicate or mapping all items
// to a new collection with a custom function.
// In some languages it’s idiomatic to use generic data structures and
// algorithms. Go does not support generics; in Go it’s common to provide
// collection functions if and when they are specifically needed for your
// program and data types.
// Here are some example collection functions for slices of strings. You can
// use these examples to build your own functions. Note that in some cases it
// may be clearest to just inline the collection-manipulating code directly,
// instead of creating and calling a helper function.
func Index(strs []string, s string) int {
for i, v := range strs {
if v == s {
return i
}
}
return -1
}
func Include(strs []string, s string) bool {
return Index(strs, s) >= 0
}
func Any(strs []string, f func(string) bool) bool {
for _, v := range strs {
if f(v) {
return true
}
}
return false
}
func All(strs []string, f func(string) bool) bool {
for _, v := range strs {
if !f(v) {
return false
}
}
return true
}
func Filter(strs []string, f func(string) bool) []string {
filtered := make([]string, 0)
for _, v := range strs {
if f(v) {
filtered = append(filtered, v)
}
}
return filtered
}
func Map(strs []string, f func(string) string) []string {
mapped := make([]string, len(strs))
for i, v := range strs {
mapped[i] = f(v)
}
return mapped
}
func main() {
strs := []string{"peach", "apple", "pear", "plum"}
fmt.Println(Index(strs, "pear"))
fmt.Println(Include(strs, "grape"))
fmt.Println(Any(strs, func(v string) bool {
return strings.HasPrefix(v, "p")
}))
fmt.Println(All(strs, func(v string) bool {
return strings.HasPrefix(v, "p")
}))
fmt.Println(Filter(strs, func(v string) bool {
return strings.Contains(v, "e")
}))
fmt.Println(Map(strs, strings.ToUpper))
} | 43-collection-functions/main.go | 0.725551 | 0.44083 | main.go | starcoder |
// Package stack implements a singly-linked list with stack behaviors.
package stack
import (
"fmt"
coll "github.com/maguerrido/collection"
)
// node of a Stack.
type node struct {
// value stored in the node.
value interface{}
// next points to the next node.
// If the node is the bottom node, then points to nil.
next *node
}
// clear sets the properties of the node to its zero values.
// Time complexity: O(1).
func (n *node) clear() {
n.value, n.next = nil, nil
}
// Stack represents a singly-linked list.
// The zero value for Stack is an empty Stack ready to use.
type Stack struct {
// top points to the top node in the Stack.
top *node
// len is the current length (number of nodes).
len int
}
// New returns a new Stack ready to use.
// Time complexity: O(1).
func New() *Stack {
return new(Stack)
}
// NewBySlice returns a new Stack with the values stored in the slice keeping its order.
// The last value of the slice will be the top value of the stack.
// Time complexity: O(n), where n is the current length of the slice.
func NewBySlice(values []interface{}) *Stack {
s := New()
for _, v := range values {
s.Push(v)
}
return s
}
// Clone returns a new cloned Stack.
// Time complexity: O(n), where n is the current length of the stack.
func (s *Stack) Clone() *Stack {
return &Stack{cloneRecursive(s.top), s.len}
}
// quickSortRecursive is an auxiliary recursive function of the Stack Clone method.
func cloneRecursive(n *node) *node {
if n == nil {
return nil
}
return &node{n.value, cloneRecursive(n.next)}
}
// Do gets the top value and performs all the procedures, then repeats it with the rest of the values.
// The stack will be empty.
// Time complexity: O(n*p), where n is the current length of the stack and p is the number of procedures.
func (s *Stack) Do(procedures ...func(v interface{})) {
for !s.IsEmpty() {
v := s.Get()
for _, procedure := range procedures {
procedure(v)
}
}
}
// Equals compares this stack with the 'other' stack and returns true if they are equal.
// Time complexity: O(n), where n is the current length of the stack.
func (s *Stack) Equals(other *Stack) bool {
if s.len != other.len {
return false
}
for i, j := s.top, other.top; i != nil; i, j = i.next, j.next {
if i.value != j.value {
return false
}
}
return true
}
// EqualsByComparator compares this stack with the 'other' stack and returns true if they are equal.
// The comparison between values is defined by the parameter 'equals'.
// The function 'equals' must return true if 'v1' equals 'v2'.
// Time complexity: O(n), where n is the current length of the stack.
func (s *Stack) EqualsByComparator(other *Stack, equals func(v1, v2 interface{}) bool) bool {
if s.len != other.len {
return false
}
for i, j := s.top, other.top; i != nil; i, j = i.next, j.next {
if !equals(i.value, j.value) {
return false
}
}
return true
}
// Get returns the top value and removes it from the stack.
// If the stack is empty, then returns nil.
// Time complexity: O(1).
func (s *Stack) Get() interface{} {
if s.IsEmpty() {
return nil
}
n, v := s.top, s.top.value
s.top = n.next
n.clear()
s.len--
return v
}
// GetIf returns all first values that meet the condition defined by the 'condition' parameter. These values will be
//removed from the stack.
// Time complexity: O(n), where n is the current length of the stack.
func (s *Stack) GetIf(condition func(v interface{}) bool) []interface{} {
values := make([]interface{}, 0)
for n := s.top; n != nil; {
if condition(n.value) {
values = append(values, s.Get())
n = s.top
} else {
return values
}
}
return values
}
// IsEmpty returns true if the stack has no values.
// Time complexity: O(1).
func (s *Stack) IsEmpty() bool {
return s.len == 0
}
func (s *Stack) Iterator() coll.Iterator {
return &iterator{
s: s,
prev: nil,
this: nil,
index: -1,
lastCommand: -1,
lastHasNext: false,
}
}
// Len returns the current length of the stack.
// Time complexity: O(1).
func (s *Stack) Len() int {
return s.len
}
// Peek returns the top value.
// If the stack is empty, then returns nil.
// Time complexity: O(1).
func (s *Stack) Peek() interface{} {
if s.IsEmpty() {
return nil
}
return s.top.value
}
// Push inserts the value 'v' at the top of the stack.
// Time complexity: O(1).
func (s *Stack) Push(v interface{}) {
n := &node{value: v, next: s.top}
s.top = n
s.len++
}
// RemoveAll sets the properties of the stack to its zero values.
// Time complexity: O(1).
func (s *Stack) RemoveAll() {
s.top, s.len = nil, 0
}
func (s *Stack) removeNode(prev, n *node) {
if s.top == n {
s.top = n.next
} else {
prev.next = n.next
}
n.clear()
s.len--
}
// Search returns the index (zero based with top equal to current length - 1) of the first match of the value 'v'.
// If the value 'v' does not belong to the stack, then returns -1.
// Time complexity: O(n), where n is the current length of the stack.
func (s *Stack) Search(v interface{}) int {
for n, i := s.top, s.len-1; n != nil; n, i = n.next, i-1 {
if n.value == v {
return i
}
}
return -1
}
// SearchByComparator returns the index (zero based with top equal to current length - 1) of the first match of the
//value 'v'.
// If the value 'v' does not belong to the stack, then returns -1.
// The comparison between values is defined by the parameter 'equals'.
// The function 'equals' must return true if 'v1' equals 'v2'.
// Time complexity: O(n), where n is the current length of the stack.
func (s *Stack) SearchByComparator(v interface{}, equals func(v1, v2 interface{}) bool) int {
for n, i := s.top, s.len-1; n != nil; n, i = n.next, i-1 {
if equals(n.value, v) {
return i
}
}
return -1
}
// Slice returns a new slice with the values stored in the stack from top to bottom.
// The stack retains its original state.
// Time complexity: O(n), where n is the current length of the stack.
func (s *Stack) Slice() []interface{} {
values := make([]interface{}, 0, s.len)
for n := s.top; n != nil; n = n.next {
values = append(values, n.value)
}
return values
}
// String returns a representation of the stack as a string.
// Stack implements the fmt.Stringer interface.
// Time complexity: O(n), where n is the current length of the stack.
func (s *Stack) String() string {
if s.IsEmpty() {
return "[]"
}
str := "["
n := s.top
for ; n.next != nil; n = n.next {
str += fmt.Sprintf("%v ", n.value)
}
return str + fmt.Sprintf("%v]", n.value)
}
type iterator struct {
s *Stack
prev, this *node
index int
lastCommand int
lastHasNext bool
}
const (
iteratorCommandHasNext = 0
iteratorCommandNext = 1
iteratorCommandRemove = 2
)
func (i *iterator) ForEach(action func(v *interface{})) {
if action != nil {
for n := i.s.top; n != nil; n = n.next {
action(&n.value)
}
}
}
func (i *iterator) HasNext() bool {
i.lastCommand = iteratorCommandHasNext
i.lastHasNext = i.index < i.s.len-1
return i.lastHasNext
}
func (i *iterator) Next() (interface{}, error) {
if i.lastCommand != iteratorCommandHasNext {
return nil, fmt.Errorf(coll.ErrorIteratorNext)
} else if !i.lastHasNext {
return nil, fmt.Errorf(coll.ErrorIteratorHasNext)
}
if i.this == nil {
i.this = i.s.top
} else {
i.prev = i.this
i.this = i.this.next
}
i.index++
i.lastCommand = iteratorCommandNext
return i.this.value, nil
}
func (i *iterator) Remove() error {
if !i.lastHasNext {
return fmt.Errorf(coll.ErrorIteratorHasNext)
} else if i.lastCommand != iteratorCommandNext {
return fmt.Errorf(coll.ErrorIteratorRemove)
}
i.s.removeNode(i.prev, i.this)
i.this = i.prev
i.index--
i.lastCommand = iteratorCommandRemove
return nil
} | stack/stack.go | 0.861217 | 0.541712 | stack.go | starcoder |
// Package term provides structures and helper functions to work with
// terminal (state, sizes).
package term
import (
"errors"
"fmt"
"io"
"os"
"os/signal"
"syscall"
)
var (
// ErrInvalidState is returned if the state of the terminal is invalid.
ErrInvalidState = errors.New("Invalid terminal state")
)
// State represents the state of the terminal.
type State struct {
termios Termios
}
// Winsize represents the size of the terminal window.
type Winsize struct {
Height uint16
Width uint16
x uint16
y uint16
}
// StdStreams returns the standard streams (stdin, stdout, stedrr).
func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) {
return os.Stdin, os.Stdout, os.Stderr
}
// GetFdInfo returns the file descriptor for an os.File and indicates whether the file represents a terminal.
func GetFdInfo(in interface{}) (uintptr, bool) {
var inFd uintptr
var isTerminalIn bool
if file, ok := in.(*os.File); ok {
inFd = file.Fd()
isTerminalIn = IsTerminal(inFd)
}
return inFd, isTerminalIn
}
// IsTerminal returns true if the given file descriptor is a terminal.
func IsTerminal(fd uintptr) bool {
var termios Termios
return tcget(fd, &termios) == 0
}
// RestoreTerminal restores the terminal connected to the given file descriptor
// to a previous state.
func RestoreTerminal(fd uintptr, state *State) error {
if state == nil {
return ErrInvalidState
}
if err := tcset(fd, &state.termios); err != 0 {
return err
}
return nil
}
// SaveState saves the state of the terminal connected to the given file descriptor.
func SaveState(fd uintptr) (*State, error) {
var oldState State
if err := tcget(fd, &oldState.termios); err != 0 {
return nil, err
}
return &oldState, nil
}
// DisableEcho applies the specified state to the terminal connected to the file
// descriptor, with echo disabled.
func DisableEcho(fd uintptr, state *State) error {
newState := state.termios
newState.Lflag &^= syscall.ECHO
if err := tcset(fd, &newState); err != 0 {
return err
}
handleInterrupt(fd, state)
return nil
}
// SetRawTerminal puts the terminal connected to the given file descriptor into
// raw mode and returns the previous state. On UNIX, this puts both the input
// and output into raw mode. On Windows, it only puts the input into raw mode.
func SetRawTerminal(fd uintptr) (*State, error) {
oldState, err := MakeRaw(fd)
if err != nil {
return nil, err
}
handleInterrupt(fd, oldState)
return oldState, err
}
// SetRawTerminalOutput puts the output of terminal connected to the given file
// descriptor into raw mode. On UNIX, this does nothing and returns nil for the
// state. On Windows, it disables LF -> CRLF translation.
func SetRawTerminalOutput(fd uintptr) (*State, error) {
return nil, nil
}
func handleInterrupt(fd uintptr, state *State) {
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, os.Interrupt)
go func() {
for range sigchan {
// quit cleanly and the new terminal item is on a new line
fmt.Println()
signal.Stop(sigchan)
close(sigchan)
RestoreTerminal(fd, state)
os.Exit(1)
}
}()
} | vendor/github.com/docker/docker/pkg/term/term.go | 0.572842 | 0.418875 | term.go | starcoder |
package enums
import (
"bytes"
"encoding"
"errors"
github_com_eden_framework_enumeration "gitee.com/eden-framework/enumeration"
)
var InvalidDroneCiType = errors.New("invalid DroneCiType")
func init() {
github_com_eden_framework_enumeration.RegisterEnums("DroneCiType", map[string]string{
"ssh": "which executes shell commands on remote servers using the ssh protocol",
"exec": "which executes pipeline steps directly on the host machine, with zero isolation",
"kubernetes": "which executes pipeline steps as containers inside of Kubernetes pods",
"docker": "which executes each pipeline steps inside isolated Docker containers",
})
}
func ParseDroneCiTypeFromString(s string) (DroneCiType, error) {
switch s {
case "":
return DRONE_CI_TYPE_UNKNOWN, nil
case "ssh":
return DRONE_CI_TYPE__ssh, nil
case "exec":
return DRONE_CI_TYPE__exec, nil
case "kubernetes":
return DRONE_CI_TYPE__kubernetes, nil
case "docker":
return DRONE_CI_TYPE__docker, nil
}
return DRONE_CI_TYPE_UNKNOWN, InvalidDroneCiType
}
func ParseDroneCiTypeFromLabelString(s string) (DroneCiType, error) {
switch s {
case "":
return DRONE_CI_TYPE_UNKNOWN, nil
case "which executes shell commands on remote servers using the ssh protocol":
return DRONE_CI_TYPE__ssh, nil
case "which executes pipeline steps directly on the host machine, with zero isolation":
return DRONE_CI_TYPE__exec, nil
case "which executes pipeline steps as containers inside of Kubernetes pods":
return DRONE_CI_TYPE__kubernetes, nil
case "which executes each pipeline steps inside isolated Docker containers":
return DRONE_CI_TYPE__docker, nil
}
return DRONE_CI_TYPE_UNKNOWN, InvalidDroneCiType
}
func (DroneCiType) EnumType() string {
return "DroneCiType"
}
func (DroneCiType) Enums() map[int][]string {
return map[int][]string{
int(DRONE_CI_TYPE__ssh): {"ssh", "which executes shell commands on remote servers using the ssh protocol"},
int(DRONE_CI_TYPE__exec): {"exec", "which executes pipeline steps directly on the host machine, with zero isolation"},
int(DRONE_CI_TYPE__kubernetes): {"kubernetes", "which executes pipeline steps as containers inside of Kubernetes pods"},
int(DRONE_CI_TYPE__docker): {"docker", "which executes each pipeline steps inside isolated Docker containers"},
}
}
func (v DroneCiType) String() string {
switch v {
case DRONE_CI_TYPE_UNKNOWN:
return ""
case DRONE_CI_TYPE__ssh:
return "ssh"
case DRONE_CI_TYPE__exec:
return "exec"
case DRONE_CI_TYPE__kubernetes:
return "kubernetes"
case DRONE_CI_TYPE__docker:
return "docker"
}
return "UNKNOWN"
}
func (v DroneCiType) Label() string {
switch v {
case DRONE_CI_TYPE_UNKNOWN:
return ""
case DRONE_CI_TYPE__ssh:
return "which executes shell commands on remote servers using the ssh protocol"
case DRONE_CI_TYPE__exec:
return "which executes pipeline steps directly on the host machine, with zero isolation"
case DRONE_CI_TYPE__kubernetes:
return "which executes pipeline steps as containers inside of Kubernetes pods"
case DRONE_CI_TYPE__docker:
return "which executes each pipeline steps inside isolated Docker containers"
}
return "UNKNOWN"
}
var _ interface {
encoding.TextMarshaler
encoding.TextUnmarshaler
} = (*DroneCiType)(nil)
func (v DroneCiType) MarshalText() ([]byte, error) {
str := v.String()
if str == "UNKNOWN" {
return nil, InvalidDroneCiType
}
return []byte(str), nil
}
func (v *DroneCiType) UnmarshalText(data []byte) (err error) {
*v, err = ParseDroneCiTypeFromString(string(bytes.ToUpper(data)))
return
} | internal/project/drone/enums/drone_ci_type__generated.go | 0.670824 | 0.438004 | drone_ci_type__generated.go | starcoder |
package nodeset
import (
"github.com/insolar/insolar/network/consensus/common/cryptkit"
"github.com/insolar/insolar/network/consensus/gcpv2/api/member"
"github.com/insolar/insolar/network/consensus/gcpv2/api/proofs"
"github.com/insolar/insolar/network/consensus/gcpv2/api/transport"
)
type NodeVectorHelper struct {
digestFactory transport.ConsensusDigestFactory
signatureVerifier cryptkit.SignatureVerifier
entryScanner VectorEntryScanner
bitset member.StateBitset
parentBitset member.StateBitset
}
func NewLocalNodeVector(digestFactory transport.ConsensusDigestFactory,
entryScanner VectorEntryScanner) NodeVectorHelper {
p := NodeVectorHelper{digestFactory, nil,
entryScanner, make(member.StateBitset, entryScanner.GetIndexedCount()), nil,
}
entryScanner.ScanIndexed(func(idx int, nodeData VectorEntryData) {
p.bitset[idx] = mapVectorEntryDataToNodesetEntry(nodeData)
})
return p
}
func mapVectorEntryDataToNodesetEntry(nodeData VectorEntryData) member.BitsetEntry {
switch {
case nodeData.IsEmpty():
return member.BeTimeout
case nodeData.TrustLevel.IsNegative():
return member.BeFraud
case nodeData.TrustLevel == member.UnknownTrust:
return member.BeBaselineTrust
case nodeData.TrustLevel < member.TrustByNeighbors:
return member.BeLimitedTrust
default:
return member.BeHighTrust
}
}
func (p *NodeVectorHelper) CreateDerivedVector(signatureVerifier cryptkit.SignatureVerifier) NodeVectorHelper {
return NodeVectorHelper{p.digestFactory, signatureVerifier,
p.entryScanner, nil, p.bitset}
}
func (p *NodeVectorHelper) PrepareDerivedVector(statRow ComparedBitsetRow) {
if p.bitset != nil && p.parentBitset == nil {
panic("illegal state")
}
p.bitset = make(member.StateBitset, len(p.parentBitset))
for idx := range p.parentBitset {
switch statRow.Get(idx) {
case ComparedMissingHere:
p.bitset[idx] = member.BeTimeout // we don't have it
case ComparedDoubtedMissingHere:
p.bitset[idx] = member.BeTimeout // we don't have it
case ComparedSame:
// ok, use as-is
p.bitset[idx] = p.parentBitset[idx]
case ComparedLessTrustedThere:
// ok - exclude for trusted
p.bitset[idx] = member.BeBaselineTrust
case ComparedLessTrustedHere:
// ok - use for both
p.bitset[idx] = member.BeHighTrust
case ComparedMissingThere:
p.bitset[idx] = member.BeTimeout // we have it, but the other's doesn't
default:
panic("unexpected")
}
}
}
func (p *NodeVectorHelper) buildGlobulaAnnouncementHash(trusted bool) proofs.GlobulaAnnouncementHash {
hasEntries := false
agg := p.digestFactory.GetAnnouncementDigester()
p.entryScanner.ScanIndexed(func(idx int, nodeData VectorEntryData) {
b := p.bitset[idx]
if b.IsTimeout() {
return
}
if trusted && !b.IsTrusted() {
return
}
agg.AddNext(nodeData.StateEvidence.GetNodeStateHash())
hasEntries = true
})
if hasEntries {
return agg.FinishSequence().AsDigestHolder()
}
return nil
}
func (p *NodeVectorHelper) buildGlobulaAnnouncementHashes() (proofs.GlobulaAnnouncementHash, proofs.GlobulaAnnouncementHash) {
/*
NB! SequenceDigester requires at least one hash to be added. So to avoid errors, local node MUST always
have trust level set high enough to get bitset[i].IsTrusted() == true
*/
aggTrusted := p.digestFactory.GetAnnouncementDigester()
var aggDoubted cryptkit.SequenceDigester
p.entryScanner.ScanIndexed(
func(idx int, nodeData VectorEntryData) {
b := p.bitset[idx]
if b.IsTimeout() {
return
}
if b.IsTrusted() {
aggTrusted.AddNext(nodeData.StateEvidence.GetNodeStateHash())
if aggDoubted == nil {
return
}
} else if aggDoubted == nil {
aggDoubted = aggTrusted.ForkSequence()
}
aggDoubted.AddNext(nodeData.StateEvidence.GetNodeStateHash())
})
trustedResult := aggTrusted.FinishSequence().AsDigestHolder()
if aggDoubted != nil {
return trustedResult, aggDoubted.FinishSequence().AsDigestHolder()
}
return trustedResult, trustedResult
}
const (
skipEntry = iota
//missingEntry
trustedEntry
doubtedEntry
)
func (p *NodeVectorHelper) stateFilter(idx int, nodeData VectorEntryData) (bool, uint32) {
b := p.bitset[idx]
if b.IsTimeout() {
return false, skipEntry
}
postpone := nodeData.RequestedMode.IsPowerless() || nodeData.RequestedPower == 0
if b.IsTrusted() {
return postpone, trustedEntry
}
return postpone, doubtedEntry
}
func (p *NodeVectorHelper) buildGlobulaStateHash(trusted bool) proofs.GlobulaAnnouncementHash {
hasEntries := false
agg := p.digestFactory.GetSequenceDigester()
p.entryScanner.ScanSortedWithFilter(
func(nodeData VectorEntryData, filter uint32) {
if filter == skipEntry {
return
}
if filter == doubtedEntry && !trusted {
return
}
digest := cryptkit.NewDigest(nodeData.AnnounceSignature, "").AsDigestHolder()
agg.AddNext(digest)
hasEntries = true
}, p.stateFilter)
if hasEntries {
return agg.FinishSequence().AsDigestHolder()
}
return nil
}
func (p *NodeVectorHelper) buildGlobulaStateHashes() (proofs.GlobulaAnnouncementHash, proofs.GlobulaAnnouncementHash) {
/*
NB! SequenceDigester requires at least one hash to be added. So to avoid errors, local node MUST always
have trust level set high enough to get bitset[i].IsTrusted() == true
*/
aggTrusted := p.digestFactory.GetSequenceDigester()
var aggDoubted cryptkit.SequenceDigester
p.entryScanner.ScanSortedWithFilter(
func(nodeData VectorEntryData, filter uint32) {
if filter == skipEntry {
return
}
digest := cryptkit.NewDigest(nodeData.AnnounceSignature, "").AsDigestHolder()
switch filter {
case trustedEntry:
aggTrusted.AddNext(digest)
if aggDoubted == nil {
return
}
case doubtedEntry:
if aggDoubted == nil {
aggDoubted = aggTrusted.ForkSequence()
}
}
aggDoubted.AddNext(digest)
}, p.stateFilter)
trustedResult := aggTrusted.FinishSequence().AsDigestHolder()
if aggDoubted != nil {
return trustedResult, aggDoubted.FinishSequence().AsDigestHolder()
}
return trustedResult, trustedResult
}
func (p *NodeVectorHelper) BuildGlobulaAnnouncementHashes(buildTrusted, buildDoubted bool,
defaultTrusted, defaultDoubted proofs.GlobulaAnnouncementHash) (trustedHash, doubtedHash proofs.GlobulaAnnouncementHash) {
if buildTrusted && buildDoubted {
return p.buildGlobulaAnnouncementHashes()
}
if buildTrusted {
return p.buildGlobulaAnnouncementHash(true), defaultDoubted
}
if buildDoubted {
return defaultTrusted, p.buildGlobulaAnnouncementHash(false)
}
return defaultTrusted, defaultDoubted
}
func (p *NodeVectorHelper) BuildGlobulaStateHashes(buildTrusted, buildDoubted bool,
defaultTrusted, defaultDoubted proofs.GlobulaStateHash) (trustedHash, doubtedHash proofs.GlobulaStateHash) {
if buildTrusted && buildDoubted {
return p.buildGlobulaStateHashes()
}
if buildTrusted {
return p.buildGlobulaStateHash(true), defaultDoubted
}
if buildDoubted {
return defaultTrusted, p.buildGlobulaStateHash(false)
}
return defaultTrusted, defaultDoubted
}
func (p *NodeVectorHelper) VerifyGlobulaStateSignature(localHash proofs.GlobulaStateHash, remoteSignature cryptkit.SignatureHolder) bool {
if p.signatureVerifier == nil {
panic("illegal state - helper must be initialized as a derived one")
}
return localHash != nil && p.signatureVerifier.IsValidDigestSignature(localHash, remoteSignature)
}
func (p *NodeVectorHelper) GetNodeBitset() member.StateBitset {
return p.bitset
} | network/consensus/gcpv2/phasebundle/nodeset/node_vector.go | 0.532668 | 0.418905 | node_vector.go | starcoder |
package sam
import (
"github.com/biogo/hts/sam"
"github.com/guigolab/bamstats/annotation"
"github.com/guigolab/bamstats/utils"
)
type Record struct {
*sam.Record
}
// Export original sam.Record functions
var (
NewTag = sam.NewTag
NewAux = sam.NewAux
)
func NewRecord(r *sam.Record) *Record {
return &Record{r}
}
func (r *Record) IsUniq() bool {
NH, hasNH := r.Tag([]byte("NH"))
if !hasNH {
return false
}
switch v := NH.Value().(type) {
case int8:
return v == 1
case uint8:
return v == 1
case int16:
return v == 1
case uint16:
return v == 1
case uint32:
return v == 1
case int32:
return v == 1
case float32:
return v == 1
}
return false
}
func (r *Record) IsSplit() bool {
for _, op := range r.Cigar {
if op.Type() == sam.CigarSkipped {
return true
}
}
return false
}
func (r *Record) IsPrimary() bool {
return r.Flags&sam.Secondary == 0
}
func (r *Record) IsUnmapped() bool {
return r.Flags&sam.Unmapped == sam.Unmapped
}
func (r *Record) IsPaired() bool {
return r.Flags&sam.Paired == sam.Paired
}
func (r *Record) IsProperlyPaired() bool {
return r.Flags&sam.ProperPair == sam.ProperPair
}
func (r *Record) IsRead1() bool {
return r.Flags&sam.Read1 == sam.Read1
}
func (r *Record) IsRead2() bool {
return r.Flags&sam.Read2 == sam.Read2
}
func (r *Record) HasMateUnmapped() bool {
return r.Flags&sam.MateUnmapped == sam.MateUnmapped
}
func (r *Record) IsFirstOfValidPair() bool {
return r.IsPaired() && r.IsRead1() && r.IsProperlyPaired() && !r.HasMateUnmapped()
}
func (r *Record) IsDuplicate() bool {
return r.Flags&sam.Duplicate == sam.Duplicate
}
func (r *Record) IsQCFail() bool {
return r.Flags&sam.QCFail == sam.QCFail
}
func (r *Record) GetBlocks() []*annotation.Location {
blocks := make([]*annotation.Location, 0, 10)
ref := r.Ref.Name()
start := r.Pos
end := r.Pos
var con sam.Consume
for _, co := range r.Cigar {
coType := co.Type()
if coType == sam.CigarSkipped {
blocks = append(blocks, annotation.NewLocation(ref, start, end))
start = end + co.Len()
end = start
continue
}
con = co.Type().Consumes()
end += co.Len() * con.Reference
if con.Query != 0 {
end = utils.Max(end, start)
}
}
blocks = append(blocks, annotation.NewLocation(ref, start, end))
return blocks
} | sam/record.go | 0.522689 | 0.422862 | record.go | starcoder |
package mathutil
import (
"fmt"
"strconv"
)
type Comparable interface {
Less(Comparable) bool
Sub(Comparable) Comparable
}
type Int64 int64
func (v Int64) Less(other Comparable) bool {
return v < other.(Int64)
}
func (v Int64) Sub(other Comparable) Comparable {
return v - other.(Int64)
}
const defaultPercentBase = 10000
type Percent struct {
numerator int64
denominator int64
}
func NewPercent(x, y int64) Percent {
if y < 0 {
x, y = -x, -y
}
return Percent{numerator: x, denominator: y}
}
func (p Percent) Normalize() int64 {
return p.NormalizeWithBase(defaultPercentBase)
}
func (p Percent) NormalizeWithBase(base int64) int64 {
if p.denominator == 0 {
return 0
}
x1, y1 := p.numerator/p.denominator, p.numerator%p.denominator
x2, y2 := base/p.denominator, base%p.denominator
return x1*x2*p.denominator + (x1*y2 + x2*y1) + (y1*y2)/p.denominator
}
func (p Percent) Less(other Comparable) bool {
p2 := other.(Percent)
x1 := float64(0)
if p.denominator != 0 {
x1 = float64(p.numerator) / float64(p.denominator)
}
x2 := float64(0)
if p2.denominator != 0 {
x2 = float64(p2.numerator) / float64(p2.denominator)
}
return x1 < x2
}
func (p Percent) Sub(other Comparable) Comparable {
p2 := other.(Percent)
x1 := float64(0)
if p.denominator != 0 {
x1 = float64(p.numerator) / float64(p.denominator)
}
x2 := float64(0)
if p2.denominator != 0 {
x2 = float64(p2.numerator) / float64(p2.denominator)
}
x := x1 - x2
return NewPercent(int64(x*defaultPercentBase), defaultPercentBase)
}
func (p Percent) String() string {
value := p.NormalizeWithBase(10000)
abs := value
sign := ""
if abs < 0 {
abs = -value
sign = "-"
}
return fmt.Sprintf("%s%d.%02d%%", sign, abs/100, abs%100)
}
func (p Percent) MarshalJSON() ([]byte, error) {
return []byte(strconv.FormatInt(p.Normalize(), 10)), nil
}
func (p *Percent) UnmarshalJSON(data []byte) error {
i, err := strconv.ParseInt(string(data), 10, 64)
if err != nil {
return err
}
p.numerator = i
p.denominator = defaultPercentBase
return nil
}
// C(m, n)
func Comb(m, n int) int64 {
sum := int64(1)
if m > n*2 {
n = m - n
}
for i := 0; i < n; i++ {
sum *= int64(m - i)
}
for i := 0; i < n; i++ {
sum /= int64(i + 1)
}
return sum
}
// CombSet C(m, n)
func CombSet(m, n int) [][]int {
type node struct {
parent *node
value int
depth int
}
var (
result [][]int
nodes []*node
)
root := new(node)
root.value = -1
nodes = append(nodes, root)
for len(nodes) > 0 {
x := nodes[len(nodes)-1]
nodes = nodes[:len(nodes)-1]
if x.depth == n {
values := make([]int, 0, n)
curr := x
for curr != nil && curr.value >= 0 {
values = append(values, curr.value)
curr = curr.parent
}
result = append(result, values)
continue
}
for value := x.value + 1; value < m+x.depth+1-n; value++ {
newNode := new(node)
newNode.depth = x.depth + 1
newNode.parent = x
newNode.value = value
nodes = append(nodes, newNode)
}
}
return result
}
func MultiCombSet(nums []int, n int) [][]int {
remainSum := 0
for _, x := range nums {
remainSum += x
}
return multiCombSet(nums, 0, n, remainSum)
}
func multiCombSet(nums []int, begin, n, remainSum int) [][]int {
size := len(nums)
if n == 0 {
return [][]int{make([]int, size)}
}
if n > remainSum {
return nil
}
if remainSum == n {
values := make([]int, size)
for i := begin; i < size; i++ {
values[i] = nums[i]
}
return [][]int{values}
}
var result [][]int
for x := 0; x <= nums[begin]; x++ {
if n >= x && begin+1 < size {
tmpResult := multiCombSet(nums, begin+1, n-x, remainSum-nums[begin])
for _, tmp := range tmpResult {
tmp[begin] = x
result = append(result, tmp)
}
}
}
return result
} | math/mathutil/mathutil.go | 0.580828 | 0.455441 | mathutil.go | starcoder |
package schema
import (
"github.com/goccy/go-yaml"
)
// MarshalYAML return custom JSON byte
func (t Table) MarshalYAML() ([]byte, error) {
if len(t.Columns) == 0 {
t.Columns = []*Column{}
}
if len(t.Indexes) == 0 {
t.Indexes = []*Index{}
}
if len(t.Constraints) == 0 {
t.Constraints = []*Constraint{}
}
if len(t.Triggers) == 0 {
t.Triggers = []*Trigger{}
}
referencedTables := []string{}
for _, rt := range t.ReferencedTables {
referencedTables = append(referencedTables, rt.Name)
}
return yaml.Marshal(&struct {
Name string `yaml:"name"`
Type string `yaml:"type"`
Comment string `yaml:"comment"`
Columns []*Column `yaml:"columns"`
Indexes []*Index `yaml:"indexes"`
Constraints []*Constraint `yaml:"constraints"`
Triggers []*Trigger `yaml:"triggers"`
Def string `yaml:"def"`
Labels Labels `yaml:"labels,omitempty"`
ReferencedTables []string `yaml:"referencedTables,omitempty"`
}{
Name: t.Name,
Type: t.Type,
Comment: t.Comment,
Columns: t.Columns,
Indexes: t.Indexes,
Constraints: t.Constraints,
Triggers: t.Triggers,
Def: t.Def,
Labels: t.Labels,
ReferencedTables: referencedTables,
})
}
// MarshalYAML return custom YAML byte
func (c Column) MarshalYAML() ([]byte, error) {
if c.Default.Valid {
return yaml.Marshal(&struct {
Name string `yaml:"name"`
Type string `yaml:"type"`
Nullable bool `yaml:"nullable"`
Default string `yaml:"default"`
ExtraDef string `yaml:"extraDef,omitempty"`
Labels Labels `yaml:"labels,omitempty"`
Comment string `yaml:"comment"`
ParentRelations []*Relation `yaml:"-"`
ChildRelations []*Relation `yaml:"-"`
}{
Name: c.Name,
Type: c.Type,
Nullable: c.Nullable,
Default: c.Default.String,
Comment: c.Comment,
ExtraDef: c.ExtraDef,
Labels: c.Labels,
ParentRelations: c.ParentRelations,
ChildRelations: c.ChildRelations,
})
}
return yaml.Marshal(&struct {
Name string `yaml:"name"`
Type string `yaml:"type"`
Nullable bool `yaml:"nullable"`
Default *string `yaml:"default"`
ExtraDef string `yaml:"extraDef,omitempty"`
Labels Labels `yaml:"labels,omitempty"`
Comment string `yaml:"comment"`
ParentRelations []*Relation `yaml:"-"`
ChildRelations []*Relation `yaml:"-"`
}{
Name: c.Name,
Type: c.Type,
Nullable: c.Nullable,
Default: nil,
ExtraDef: c.ExtraDef,
Labels: c.Labels,
Comment: c.Comment,
ParentRelations: c.ParentRelations,
ChildRelations: c.ChildRelations,
})
}
// MarshalYAML return custom YAML byte
func (r Relation) MarshalYAML() ([]byte, error) {
columns := []string{}
parentColumns := []string{}
for _, c := range r.Columns {
columns = append(columns, c.Name)
}
for _, c := range r.ParentColumns {
parentColumns = append(parentColumns, c.Name)
}
return yaml.Marshal(&struct {
Table string `yaml:"table"`
Columns []string `yaml:"columns"`
ParentTable string `yaml:"parentTable"`
ParentColumns []string `yaml:"parentColumns"`
Def string `yaml:"def"`
Virtual bool `yaml:"virtual"`
}{
Table: r.Table.Name,
Columns: columns,
ParentTable: r.ParentTable.Name,
ParentColumns: parentColumns,
Def: r.Def,
Virtual: r.Virtual,
})
}
// UnMarshalYAML unmarshal JSON to schema.Table
func (t *Table) UnMarshalYAML(data []byte) error {
s := struct {
Name string `yaml:"name"`
Type string `yaml:"type"`
Comment string `yaml:"comment"`
Columns []*Column `yaml:"columns"`
Indexes []*Index `yaml:"indexes"`
Constraints []*Constraint `yaml:"constraints"`
Triggers []*Trigger `yaml:"triggers"`
Def string `yaml:"def"`
Labels Labels `yaml:"labels,omitempty"`
ReferencedTables []string `yaml:"referencedTables,omitempty"`
}{}
err := yaml.Unmarshal(data, &s)
if err != nil {
return err
}
t.Name = s.Name
t.Type = s.Type
t.Comment = s.Comment
t.Columns = s.Columns
t.Indexes = s.Indexes
t.Constraints = s.Constraints
t.Triggers = s.Triggers
t.Def = s.Def
t.Labels = s.Labels
for _, rt := range s.ReferencedTables {
t.ReferencedTables = append(t.ReferencedTables, &Table{
Name: rt,
})
}
return nil
}
// UnmarshalYAML unmarshal YAML to schema.Column
func (c *Column) UnmarshalYAML(data []byte) error {
s := struct {
Name string `yaml:"name"`
Type string `yaml:"type"`
Nullable bool `yaml:"nullable"`
Default *string `yaml:"default"`
Comment string `yaml:"comment"`
ExtraDef string `yaml:"extraDef,omitempty"`
Labels Labels `yaml:"labels,omitempty"`
ParentRelations []*Relation `yaml:"-"`
ChildRelations []*Relation `yaml:"-"`
}{}
err := yaml.Unmarshal(data, &s)
if err != nil {
return err
}
c.Name = s.Name
c.Type = s.Type
c.Nullable = s.Nullable
if s.Default != nil {
c.Default.Valid = true
c.Default.String = *s.Default
} else {
c.Default.Valid = false
c.Default.String = ""
}
c.ExtraDef = s.ExtraDef
c.Labels = s.Labels
c.Comment = s.Comment
return nil
}
// UnmarshalYAML unmarshal YAML to schema.Column
func (r *Relation) UnmarshalYAML(data []byte) error {
s := struct {
Table string `yaml:"table"`
Columns []string `yaml:"columns"`
ParentTable string `yaml:"parentTable"`
ParentColumns []string `yaml:"parentColumns"`
Def string `yaml:"def"`
Virtual bool `yaml:"virtual"`
}{}
err := yaml.Unmarshal(data, &s)
if err != nil {
return err
}
r.Table = &Table{
Name: s.Table,
}
r.Columns = []*Column{}
for _, c := range s.Columns {
r.Columns = append(r.Columns, &Column{
Name: c,
})
}
r.ParentTable = &Table{
Name: s.ParentTable,
}
r.ParentColumns = []*Column{}
for _, c := range s.ParentColumns {
r.ParentColumns = append(r.ParentColumns, &Column{
Name: c,
})
}
r.Def = s.Def
r.Virtual = s.Virtual
return nil
} | schema/yaml.go | 0.500977 | 0.40869 | yaml.go | starcoder |
package sample
import (
"fmt"
"math/rand"
)
type sampleState struct {
rate uint64
seed int64
sampleCount uint64
trueCount uint64
rnd *rand.Rand
}
// A Sampler is a source of sampling decisions.
type Sampler interface {
// Sample returns a sampling decision based on a random number.
Sample() bool
// SampleFrom returns a sampling decision based on probe.
SampleFrom(probe uint64) bool
State
}
// A State is the internal State of a Sampler.
type State interface {
// Reset the internal state of the sampler to the initial values
// This also resets the random number generator to the initial state with the initial seed value
Reset()
// String returns the internal state of the sampler as string
String() string
// Returns the rate
Rate() uint64
// Calls returns how many times the sampler was asked to sample
Calls() uint64
// Count returns how many times the sampler sampled (returned true)
Count() uint64
}
func (state *sampleState) Rate() uint64 {
if state != nil {
return state.rate
}
return 0
}
func (state *sampleState) Calls() uint64 {
if state != nil {
return state.sampleCount
}
return 0
}
func (state *sampleState) Count() uint64 {
if state != nil {
return state.trueCount
}
return 0
}
func (state *sampleState) Reset() {
state.rnd.Seed(state.seed)
state.sampleCount = 0
state.trueCount = 0
}
func (state *sampleState) String() string {
type X *sampleState
x := X(state)
return fmt.Sprintf("%+v", x)
}
// Deviation returns the deviation between the number of time the sampler return true to the mathematically correct count
func Deviation(state State) (deviation float64) {
if state != nil && state.Count() > 0 {
deviation = 1.0 - 1.0/float64(state.Rate())*(float64(state.Calls())/float64(state.Count()))
} else {
deviation = 1.0
}
return
}
// Stats returns statistical values of the Sampler as String
func Stats(state State) string {
if state != nil {
return fmt.Sprintf("Rate: %d, SampleCount: %d, TrueCount: %d, Deviation: %.4f%%", state.Rate(), state.Calls(), state.Count(), Deviation(state)*100.0)
}
return "No state provided"
} | sample.go | 0.78316 | 0.514034 | sample.go | starcoder |
package model
import (
"sort"
)
const (
// DefaultFilterSize represents the default filter search size.
DefaultFilterSize = 100
// FilterSizeLimit represents the largest filter size.
FilterSizeLimit = 1000
// GeoBoundsFilter represents a geobound filter type.
GeoBoundsFilter = "geobounds"
// CategoricalFilter represents a categorical filter type.
CategoricalFilter = "categorical"
// ClusterFilter represents a cluster filter type.
ClusterFilter = "cluster"
// NumericalFilter represents a numerical filter type.
NumericalFilter = "numerical"
// BivariateFilter represents a numerical filter type.
BivariateFilter = "bivariate"
// DatetimeFilter represents a datetime filter type.
DatetimeFilter = "datetime"
// TextFilter represents a text filter type.
TextFilter = "text"
// VectorFilter represents a text filter type.
VectorFilter = "vector"
// RowFilter represents a numerical filter type.
RowFilter = "row"
// IncludeFilter represents an inclusive filter mode.
IncludeFilter = "include"
// ExcludeFilter represents an exclusive filter mode.
ExcludeFilter = "exclude"
)
// StringSliceEqual compares 2 string slices to see if they are equal.
func StringSliceEqual(a, b []string) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
// Bounds defines a bounding box
type Bounds struct {
MinX float64 `json:"minX"`
MaxX float64 `json:"maxX"`
MinY float64 `json:"minY"`
MaxY float64 `json:"maxY"`
}
// NewBounds creates a Bounds struct from an origin point and width and height.
func NewBounds(minX float64, minY float64, width float64, height float64) *Bounds {
return &Bounds{
MinX: minX,
MinY: minY,
MaxX: minX + width,
MaxY: minY + height,
}
}
// FilterObject captures a collection of invertable filters.
type FilterObject struct {
List []*Filter `json:"list"`
Invert bool `json:"invert"`
}
// FilterSet captures a set of filters representing one subset of data.
type FilterSet struct {
FeatureFilters []FilterObject `json:"featureFilters"`
Mode string `json:"mode"`
}
// Filter defines a variable filter.
type Filter struct {
Key string `json:"key"`
Type string `json:"type"`
NestedType string `json:"nestedType"`
Mode string `json:"mode"`
Min *float64 `json:"min"`
Max *float64 `json:"max"`
Bounds *Bounds `json:"bounds"`
Categories []string `json:"categories"`
D3mIndices []string `json:"d3mIndices"`
IsBaselineFilter bool `json:"isBaselineFilter"`
}
// NewNumericalFilter instantiates a numerical filter.
func NewNumericalFilter(key string, mode string, min float64, max float64) *Filter {
return &Filter{
Key: key,
Type: NumericalFilter,
Mode: mode,
Min: &min,
Max: &max,
}
}
// NewVectorFilter instantiates a vector filter.
func NewVectorFilter(key string, nestedType string, mode string, min float64, max float64) *Filter {
return &Filter{
Key: key,
Type: VectorFilter,
NestedType: nestedType,
Mode: mode,
Min: &min,
Max: &max,
}
}
// NewDatetimeFilter instantiates a datetime filter.
func NewDatetimeFilter(key string, mode string, min float64, max float64) *Filter {
return &Filter{
Key: key,
Type: DatetimeFilter,
Mode: mode,
Min: &min,
Max: &max,
}
}
// NewBivariateFilter instantiates a numerical filter.
func NewBivariateFilter(key string, mode string, minX float64, maxX float64, minY float64, maxY float64) *Filter {
return &Filter{
Key: key,
Type: BivariateFilter,
Mode: mode,
Bounds: &Bounds{
MinX: minX,
MaxX: maxX,
MinY: minY,
MaxY: maxY,
},
}
}
// NewGeoBoundsFilter instantiates a geobounds filter.
func NewGeoBoundsFilter(key string, mode string, minX float64, maxX float64, minY float64, maxY float64) *Filter {
return &Filter{
Key: key,
Type: GeoBoundsFilter,
Mode: mode,
Bounds: &Bounds{
MinX: minX,
MaxX: maxX,
MinY: minY,
MaxY: maxY,
},
}
}
// NewCategoricalFilter instantiates a categorical filter.
func NewCategoricalFilter(key string, mode string, categories []string) *Filter {
sort.Strings(categories)
return &Filter{
Key: key,
Type: CategoricalFilter,
Mode: mode,
Categories: categories,
}
}
// NewClusterFilter instantiates a cluster filter.
func NewClusterFilter(key string, mode string, categories []string) *Filter {
sort.Strings(categories)
return &Filter{
Key: key,
Type: ClusterFilter,
Mode: mode,
Categories: categories,
}
}
// NewTextFilter instantiates a text filter.
func NewTextFilter(key string, mode string, categories []string) *Filter {
sort.Strings(categories)
return &Filter{
Key: key,
Type: TextFilter,
Mode: mode,
Categories: categories,
}
}
// NewRowFilter instantiates a row filter.
func NewRowFilter(mode string, d3mIndices []string) *Filter {
return &Filter{
Key: D3MIndexFieldName,
Type: RowFilter,
Mode: mode,
D3mIndices: d3mIndices,
}
}
// IsValid verifies that a filter set is valid.
func (fs *FilterSet) IsValid() bool {
// make sure every filter object is value
for _, fo := range fs.FeatureFilters {
if !fo.IsValid() {
return false
}
}
return true
}
// Clone a FilterSet
func (fs *FilterSet) Clone() *FilterSet {
featureSet := &FilterSet{
Mode: fs.Mode,
FeatureFilters: []FilterObject{},
}
for _, fo := range fs.FeatureFilters {
cloneFilterObject := FilterObject{
Invert: fo.Invert,
List: []*Filter{},
}
for _, f := range fo.List {
c := *f
cloneFilterObject.List = append(cloneFilterObject.List, &c)
}
featureSet.FeatureFilters = append(featureSet.FeatureFilters, cloneFilterObject)
}
return featureSet
}
// IsValid verifies that a filter object is valid.
func (fo FilterObject) IsValid() bool {
// a filter object acts on a single filter, and they are all the same mode
mode := ""
key := ""
for _, f := range fo.List {
if key == "" {
key = f.Key
mode = f.Mode
} else if key != f.Key {
return false
} else if mode != f.Mode {
return false
}
}
return true
}
// GetBaselineFilter returns only filters that form the baseline.
func (fo FilterObject) GetBaselineFilter() []*Filter {
baseline := []*Filter{}
for _, filter := range fo.List {
if filter.IsBaselineFilter {
baseline = append(baseline, filter)
}
}
return baseline
} | model/filter.go | 0.829216 | 0.58053 | filter.go | starcoder |
package api
import (
. "github.com/gocircuit/circuit/gocircuit.org/render"
)
func RenderAnchorPage() string {
figs := A{
"FigHierarchy": RenderFigurePngSvg(
"Virtual anchor hierarchy and its mapping to Go <code>Anchor</code> objects.", "hierarchy", "600px"),
}
return RenderHtml("Navigating and using the anchor hierarchy", Render(anchorBody, figs))
}
const anchorBody = `
<h2>Navigating and using the anchor hierarchy</h2>
<p>As you as obtain a <code>*Client</code> object <a href="api.html">after dialing</a>, you have your hands on
the root anchor. The type <code>*Client</code> implements the <code>Anchor</code> interface.
{{.FigHierarchy}}
<p>Anchors have two sets of methods: Those for navigating the anchor hierarchy and those for manipulating
elements attached to the anchor. We'll examine both types in turn.
<p>In general, it is safe to call all methods of anchor objects concurrently. In other words, you can
use the same anchor object from different goroutines without any synchronization.
<h3>Navigating</h3>
<p>Anchors have two methods pertaining to navigation of the anchor hierarchy:
<pre>
View() map[string]Anchor
Walk(walk []string) Anchor
</pre>
<p>Method <code>View</code> will return the current list of subanchors of this anchor. The result comes in the
form of a map from child names to anchor objects.
<p>Method <code>Walk</code> takes one <code>[]string</code> argument <code>walk</code>,
which is interpreted as a relative path (down the anchor hierarchy) from this anchor to a descendant. <code>Walk</code> traverses
the path and returns the descendant anchor, separated from this one by the path <code>walk</code>.
<p>Note that <code>Walk</code> always succeeds: If a child anchor is missing as <code>Walk</code> traverses down
the hierarchy, the anchor is created automatically. Anchors persist within the circuit cluster as long as they are
being used, otherwise they are garbage-collected.
An anchor is in use if at least one of the following conditions is met:
<ul>
<li>It is being used by a client (in the form of a held <code>Anchor</code> object),
<li>It has an element attached to it (something like a process or a container, for example), or
<li>It has child anchors.
</ul>
<p>In other words, <code>Walk</code> is not only a method for accessing existing anchors but
also a method for creating new ones (should they not already exist).
<p>The only exception to this rule is posed at the root anchor. The root anchor logically corresponds
to the cluster as a whole. The only allowed subanchors of the root anchor are the ones corresponding
to available circuit servers, and these anchors are created and removed automatically by the system.
<p>If <code>Walk</code> is invoked at the root anchor with a path argument, whose first
element is not present in the hierarchy, the invokation will panic to indicate an error. This is not
a critical panic and one can safely recover from it and continue.
<h3>Manipulating elements</h3>
<p>The <code>Anchor</code> interface has a set of <code>Make…</code> methods,
each of which creates a new resource (process, container, etc.) and, if successful, atomically
attaches it to the anchor. (These methods would fail with a non-nil error, if the anchor
already has an element attached to it.)
<pre>
MakeChan(int) (Chan, error)
MakeProc(Cmd) (Proc, error)
MakeDocker(cdocker.Run) (cdocker.Container, error)
MakeNameserver(string) (Nameserver, error)
MakeOnJoin() (Subscription, error)
MakeOnLeave() (Subscription, error)
</pre>
<p>The use of these methods is detailed in the following sections, dedicated to
<a href="api-process.html">processes</a>,
<a href="api-container.html">containers</a>,
<a href="api-channel.html">channels</a>,
<a href="api-name.html">name servers</a> and
<a href="api-subscription.html">subscriptions</a>.
<p>Anchors have two generic methods for manipulating elements as well:
<pre>
Get() interface{}
Scrub()
</pre>
<p>The <code>Get</code> method will return the element currently associated with the
anchor. (This would be an object of type <code>Chan</code>, <code>Proc</code>,
<code>Container</code>, <code>Nameserver</code>, <code>Server</code> or <code>Subscription</code>.)
<p>The <code>Scrub</code> method will terminate the operation of the element
attached to this anchor and will remove the element from the anchor.
<h3>Auxiliary methods</h3>
<p>Anchors have a couple of auxiliary methods to facilitate programming:
<pre>
Addr() string
Path() string
</pre>
<p>The method <code>Addr</code> returns the circuit address of the server that is hosting this anchor.
The returned value would be a string of the form <code>circuit://…</code>.
<p>The method <code>Path</code> will return the file-system notation of the anchor's path.
This would be a string looking like <code>"/X50faec8c2b5f6418/mysql/shard/1"</code>, for instance.
` | gocircuit.org/api/anchor.go | 0.792384 | 0.676844 | anchor.go | starcoder |
package sigma
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
type lexer struct {
input string // we'll store the string being parsed
start int // the position we started scanning
position int // the current position of our scan
width int // we'll be using runes which can be double byte
items chan Item // the channel we'll use to communicate between the lexer and the parser
}
// lex creates a lexer and starts scanning the provided input.
func lex(input string) *lexer {
l := &lexer{
input: input,
items: make(chan Item, 0),
}
go l.scan()
return l
}
// ignore resets the start position to the current scan position effectively
// ignoring any input.
func (l *lexer) ignore() {
l.start = l.position
}
// next advances the lexer state to the next rune.
func (l *lexer) next() (r rune) {
if l.position >= len(l.input) {
l.width = 0
return eof
}
r, l.width = utf8.DecodeRuneInString(l.todo())
l.position += l.width
return r
}
// backup allows us to step back one rune which is helpful when you've crossed
// a boundary from one state to another.
func (l *lexer) backup() {
l.position = l.position - 1
}
// scan will step through the provided text and execute state functions as
// state changes are observed in the provided input.
func (l *lexer) scan() {
// When we begin processing, let's assume we're going to process text.
// One state function will return another until `nil` is returned to signal
// the end of our process.
for fn := lexCondition; fn != nil; {
fn = fn(l)
}
close(l.items)
}
func (l *lexer) unsuppf(format string, args ...interface{}) stateFn {
msg := fmt.Sprintf(format, args...)
l.items <- Item{T: TokUnsupp, Val: msg}
return nil
}
func (l *lexer) errorf(format string, args ...interface{}) stateFn {
msg := fmt.Sprintf(format, args...)
l.items <- Item{T: TokErr, Val: msg}
return nil
}
// emit sends a item over the channel so the parser can collect and manage
// each segment.
func (l *lexer) emit(k Token) {
i := Item{T: k, Val: l.input[l.start:l.position]}
l.items <- i
l.ignore() // reset our scanner now that we've dispatched a segment
}
func (l lexer) collected() string { return l.input[l.start:l.position] }
func (l lexer) todo() string { return l.input[l.position:] }
// stateFn is a function that is specific to a state within the string.
type stateFn func(*lexer) stateFn
// lexCondition scans what is expected to be text.
func lexCondition(l *lexer) stateFn {
for {
if strings.HasPrefix(l.todo(), TokStOne.Literal()) {
return lexOneOf
}
if strings.HasPrefix(l.todo(), TokStAll.Literal()) {
return lexAllOf
}
switch r := l.next(); {
case r == eof:
return lexEOF
case r == TokSepRpar.Rune():
return lexRparWithTokens
case r == TokSepLpar.Rune():
return lexLpar
case r == TokSepPipe.Rune():
return lexPipe
case unicode.IsSpace(r):
return lexAccumulateBeforeWhitespace
}
}
}
func lexStatement(l *lexer) stateFn {
return lexCondition
}
func lexOneOf(l *lexer) stateFn {
l.position += len(TokStOne.Literal())
l.emit(TokStOne)
return lexCondition
}
func lexAllOf(l *lexer) stateFn {
l.position += len(TokStAll.Literal())
l.emit(TokStAll)
return lexCondition
}
func lexAggs(l *lexer) stateFn {
return l.unsuppf("aggregation not supported yet [%s]", l.input)
}
func lexEOF(l *lexer) stateFn {
if l.position > l.start {
l.emit(checkKeyWord(l.collected()))
}
l.emit(TokLitEof)
return nil
}
func lexPipe(l *lexer) stateFn {
l.emit(TokSepPipe)
return lexAggs
}
func lexLpar(l *lexer) stateFn {
l.emit(TokSepLpar)
return lexCondition
}
func lexRparWithTokens(l *lexer) stateFn {
// emit any text we've accumulated.
if l.position > l.start {
l.backup()
// There may be N whitespace chars between token RPAR
// TODO - may be a more concise way to do this, right now loops like this are everywhere
if t := checkKeyWord(l.collected()); t != TokNil {
l.emit(t)
}
for {
switch r := l.next(); {
case r == eof:
return lexEOF
case unicode.IsSpace(r):
l.ignore()
default:
return lexRpar
}
}
}
return lexRpar
}
func lexRpar(l *lexer) stateFn {
l.emit(TokSepRpar)
return lexCondition
}
func lexAccumulateBeforeWhitespace(l *lexer) stateFn {
l.backup()
// emit any text we've accumulated.
if l.position > l.start {
l.emit(checkKeyWord(l.collected()))
}
return lexWhitespace
}
// lexWhitespace scans what is expected to be whitespace.
func lexWhitespace(l *lexer) stateFn {
for {
switch r := l.next(); {
case r == eof:
return lexEOF
case !unicode.IsSpace(r):
l.backup()
return lexCondition
default:
l.ignore()
}
}
}
func checkKeyWord(in string) Token {
if len(in) == 0 {
return TokNil
}
switch strings.ToLower(in) {
case TokKeywordAnd.Literal():
return TokKeywordAnd
case TokKeywordOr.Literal():
return TokKeywordOr
case TokKeywordNot.Literal():
return TokKeywordNot
case "sum", "min", "max", "count", "avg":
return TokKeywordAgg
case TokIdentifierAll.Literal():
return TokIdentifierAll
default:
if strings.Contains(in, "*") {
return TokIdentifierWithWildcard
}
return TokIdentifier
}
} | pkg/sigma/v2/lexer.go | 0.549641 | 0.422683 | lexer.go | starcoder |
package geogoth
import (
"math"
)
// MinDistance searches for the smallest distance
func MinDistance(distarr []float64) float64 {
distance := distarr[0]
for i := range distarr {
if distarr[i] < distance {
distance = distarr[i]
}
}
return distance
}
// NegToPosRad converts brng to positive if it's negative
func NegToPosRad(rad float64) float64 {
if rad > 0 {
return rad
} else {
return 2*math.Pi + rad
}
}
// Bearing Finds the bearing from one lat/lon point to another.
func Bearing(latA, lonA, latB, lonB float64) float64 {
brng := math.Atan2(math.Sin(lonB-lonA)*math.Cos(latB), math.Cos(latA)*math.Sin(latB)-math.Sin(latA)*math.Cos(latB)*math.Cos(lonB-lonA))
return NegToPosRad(brng)
}
// PIPJordanCurveTheorem returns true if point(feature1) is inside of the polygon(feature2)
// returns false if point(feature1) is outside of the polygon(feature2)
// C/C++ algorithm implementation: https://sidvind.com/wiki/Point-in-polygon:_Jordan_Curve_Theorem
func PIPJordanCurveTheorem(py, px float64, pol interface{}) bool {
// pol - feature2.Geom.Coordinates
polygon := (pol).([][][]float64) // Convert interface to [][][]float64
var x1, x2, k float64
crossing := 0
for p := range polygon {
for i := range polygon[p] {
/* This is done to ensure that we get the same result when
the line goes from left to right and right to left */
if polygon[p][i][1] < polygon[p][(i+1)%len(polygon[p])][1] {
x1 = polygon[p][i][1]
x2 = polygon[p][(i+1)%len(polygon[p])][1]
} else {
x1 = polygon[p][(i+1)%len(polygon[p])][1]
x2 = polygon[p][i][1]
}
/* First check if the ray is possible to cross the line */
if px > x1 && px <= x2 && (py < polygon[p][i][0] || py <= polygon[p][(i+1)%len(polygon[p])][0]) {
eps := 0.000001
/* Calculate the equation of the line */
dx := polygon[p][(i+1)%len(polygon[p])][1] - polygon[p][i][1]
dy := polygon[p][(i+1)%len(polygon[p])][0] - polygon[p][i][0]
if math.Abs(dx) < eps {
k = 999999999999999999
} else {
k = dy / dx
}
m := polygon[p][i][0] - k*polygon[p][i][1]
/* Find if the ray crosses the line */
y2 := k*px + m
if py <= y2 {
crossing++
}
}
}
}
// fmt.Println(fmt.Sprintf("The point is crossing %v lines", crossing))
if crossing%2 == 1 {
return true // The Point is instide of the Polygon
} else {
return false // The Point is outside of the Polygon
}
}
// PointInPolygon ...
func PointInPolygon(feature1, feature2 *Feature) bool {
py, px := GetPointCoordinates(feature1) // Coords of Point
pol := feature2.Geom.Coordinates
return PIPJordanCurveTheorem(py, px, pol)
}
// LineLineIntersection returns true if lines intersectd; false if lines do not intersect
// Algorithm from https://ideone.com/PnPJgb
func LineLineIntersection(yA, xA, yB, xB, yC, xC, yD, xD float64) bool {
yCmP, xCmP := yC-yA, xC-xA
yr, xr := yB-yA, xB-xA
ys, xs := yD-yC, xD-xC
cmpXr := xCmP*yr - yCmP*xr
cmpXs := xCmP*ys - yCmP*xs
rXs := xr*ys - yr*xs
if cmpXr == 0 {
// Lines are collinear, and so intersect if they have any overlap
return ((xC-xA < 0) != (xC-xB < 0)) || ((yC-yA < 0) != (yC-yB < 0))
}
if rXs == 0 {
return false // Lines are parallel
}
rXsr := 1 / rXs
t := cmpXs * rXsr
u := cmpXr * rXsr
return (t >= 0) && (t <= 1) && (u >= 0) && (u <= 1)
}
// DistanceLineLine finds distance between two lines
// func DistanceLineLine(feature1, feature2 *Feature) float64 {
func DistanceLineLine(line1Y1, line1X1, line1Y2, line1X2, line2Y1, line2X1, line2Y2, line2X2 float64) float64 {
var distance float64
if LineLineIntersection(line1Y1, line1X1, line1Y2, line1X2, line2Y1, line2X1, line2Y2, line2X2) == true {
distance = 0
} else {
distarr := make([]float64, 0) // Creates slice for distances between Point and edges of LineString
distarr = append(distarr, DistancePointLine(line1Y1, line1X1, line2Y1, line2X1, line2Y2, line2X2))
distarr = append(distarr, DistancePointLine(line1Y2, line1X2, line2Y1, line2X1, line2Y2, line2X2))
distarr = append(distarr, DistancePointLine(line2Y1, line2X1, line1Y1, line1X1, line1Y2, line1X2))
distarr = append(distarr, DistancePointLine(line2Y2, line2X2, line1Y1, line1X1, line1Y2, line1X2))
distance = MinDistance(distarr)
}
return distance
} | geojson/helper.go | 0.841011 | 0.662742 | helper.go | starcoder |
package components
import (
"sync"
"github.com/go-gl/mathgl/mgl32"
)
const (
// TypeVelocity represents a velocity component's type.
TypeVelocity = "velocity"
)
// Velocity represents the velocity of an entity.
type Velocity interface {
Component
// Rotational retrieves the rotational velocity in radians per second.
Rotational() mgl32.Vec3
// Translational retrieves the translational velocity.
Translational() mgl32.Vec3
// SetRotational sets the rotational velocity.
SetRotational(mgl32.Vec3)
// SetTranslational sets the translational velocity.
SetTranslational(mgl32.Vec3)
// Set sets the rotational and translational velocities.
Set(rotational mgl32.Vec3, translational mgl32.Vec3)
}
type velocity struct {
rotational mgl32.Vec3
translational mgl32.Vec3
dataLock sync.RWMutex
}
// NewVelocity creates a new Velocity component.
func NewVelocity() Velocity {
v := velocity{
rotational: mgl32.Vec3{0, 0, 0},
translational: mgl32.Vec3{0, 0, 0},
}
return &v
}
// Type retrieves the type name of this component.
func (v *velocity) Type() string {
return TypeVelocity
}
// Rotational retrieves the rotational velocity in radians per second.
func (v *velocity) Rotational() mgl32.Vec3 {
v.dataLock.RLock()
defer v.dataLock.RUnlock()
return v.rotational
}
// Translational retrieves the translational velocity.
func (v *velocity) Translational() mgl32.Vec3 {
v.dataLock.RLock()
defer v.dataLock.RUnlock()
return v.translational
}
// SetRotational sets the rotational velocity.
func (v *velocity) SetRotational(rotate mgl32.Vec3) {
v.dataLock.Lock()
defer v.dataLock.Unlock()
v.rotational = rotate
}
// SetTranslational sets the translational velocity.
func (v *velocity) SetTranslational(translate mgl32.Vec3) {
v.dataLock.Lock()
defer v.dataLock.Unlock()
v.translational = translate
}
// Set sets the rotational and translational velocities.
func (v *velocity) Set(rotate, translate mgl32.Vec3) {
v.dataLock.Lock()
defer v.dataLock.Unlock()
v.rotational = rotate
v.translational = translate
} | components/velocity.go | 0.847999 | 0.594345 | velocity.go | starcoder |
package main
import (
"encoding/binary"
"math"
)
// Types
const AMF3_TYPE_UNDEFINED = 0x00
const AMF3_TYPE_NULL = 0x01
const AMF3_TYPE_FALSE = 0x02
const AMF3_TYPE_TRUE = 0x03
const AMF3_TYPE_INTEGER = 0x04
const AMF3_TYPE_DOUBLE = 0x05
const AMF3_TYPE_STRING = 0x06
const AMF3_TYPE_XML_DOC = 0x07
const AMF3_TYPE_DATE = 0x08
const AMF3_TYPE_ARRAY = 0x09
const AMF3_TYPE_OBJECT = 0x0A
const AMF3_TYPE_XML = 0x0B
const AMF3_TYPE_BYTE_ARRAY = 0x0C
type AMF3Value struct {
amf_type byte
int_val int32
float_val float64
str_val string
bytes_val []byte
}
func createAMF3Value(amf_type byte) AMF3Value {
return AMF3Value{
amf_type: amf_type,
int_val: 0,
float_val: 0,
str_val: "",
bytes_val: make([]byte, 0),
}
}
func (v *AMF3Value) GetBool() bool {
return v.amf_type == AMF3_TYPE_TRUE
}
/* Encoding */
func amf3encUI29(num uint32) []byte {
var buf []byte
if num < 0x80 {
buf = make([]byte, 1)
buf[0] = byte(num)
} else if num < 0x4000 {
buf = make([]byte, 2)
buf[0] = byte(num & 0x7F)
buf[1] = byte((num >> 7) | 0x80)
} else if num < 0x200000 {
buf = make([]byte, 3)
buf[0] = byte(num & 0x7F)
buf[1] = byte((num >> 7) & 0x7F)
buf[2] = byte((num >> 14) | 0x80)
} else {
buf = make([]byte, 4)
buf[0] = byte(num & 0xFF)
buf[1] = byte((num >> 8) & 0x7F)
buf[2] = byte((num >> 15) | 0x7F)
buf[3] = byte((num >> 22) | 0x7F)
}
return buf
}
func amf3EncodeOne(val AMF3Value) []byte {
var result []byte
result = []byte{val.amf_type}
switch val.amf_type {
case AMF3_TYPE_INTEGER:
result = append(result, amf3EncodeInteger(val.int_val)...)
case AMF3_TYPE_DOUBLE:
result = append(result, amf3EncodeDouble(val.float_val)...)
case AMF3_TYPE_STRING:
result = append(result, amf3EncodeString(val.str_val)...)
case AMF3_TYPE_XML:
result = append(result, amf3EncodeString(val.str_val)...)
case AMF3_TYPE_XML_DOC:
result = append(result, amf3EncodeString(val.str_val)...)
case AMF3_TYPE_DATE:
result = append(result, amf3EncodeDate(val.float_val)...)
case AMF3_TYPE_BYTE_ARRAY:
result = append(result, amf3EncodeByteArray(val.bytes_val)...)
}
return result
}
func amf3EncodeString(str string) []byte {
b := []byte(str)
sLen := amf3encUI29(uint32(len(b)) << 1)
return append(sLen, b...)
}
func amf3EncodeInteger(i int32) []byte {
return amf3encUI29(uint32(i) & 0x3FFFFFFF)
}
func amf3EncodeDouble(d float64) []byte {
b := make([]byte, 8)
i := math.Float64bits(d)
binary.BigEndian.PutUint64(b, i)
return b
}
func amf3EncodeDate(ts float64) []byte {
prefix := amf3encUI29(1)
return append(prefix, amf3EncodeDouble(ts)...)
}
func amf3EncodeByteArray(b []byte) []byte {
sLen := amf3encUI29(uint32(len(b)) << 1)
return append(sLen, b...)
}
/* Decoding */
func (s *AMFDecodingStream) amf3decUI29() uint32 {
var val uint32
var len uint32
var ended bool
var b byte
val = 0
len = 1
ended = false
for !ended {
b = s.Read(1)[0]
len++
val = (val << 7) + uint32(b&0x7F)
if len < 5 || b > 0x7F {
ended = true
}
}
if len == 5 {
val = val | uint32(b)
}
return val
}
func (s *AMFDecodingStream) ReadAMF3() AMF3Value {
amf_type := s.Read(1)[0]
r := createAMF3Value(amf_type)
switch amf_type {
case AMF3_TYPE_INTEGER:
r.int_val = int32(s.amf3decUI29())
case AMF3_TYPE_DOUBLE:
r.float_val = s.ReadNumber()
case AMF3_TYPE_DATE:
r.int_val = int32(s.amf3decUI29())
r.float_val = s.ReadNumber()
case AMF3_TYPE_STRING:
r.str_val = s.ReadAMF3String()
case AMF3_TYPE_XML:
r.str_val = s.ReadAMF3String()
case AMF3_TYPE_XML_DOC:
r.str_val = s.ReadAMF3String()
case AMF3_TYPE_BYTE_ARRAY:
r.bytes_val = s.ReadAMF3ByteArray()
}
return r
}
func (s *AMFDecodingStream) ReadAMF3String() string {
l := s.amf3decUI29()
strBytes := s.Read(int(l))
return string(strBytes)
}
func (s *AMFDecodingStream) ReadAMF3ByteArray() []byte {
l := s.amf3decUI29()
strBytes := s.Read(int(l))
return strBytes
} | amf3.go | 0.509032 | 0.409103 | amf3.go | starcoder |
package fp
func (l BoolArray) Take(n int) BoolArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([]bool, n)
copy(acc, l[0: n])
return acc }
func (l StringArray) Take(n int) StringArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([]string, n)
copy(acc, l[0: n])
return acc }
func (l IntArray) Take(n int) IntArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([]int, n)
copy(acc, l[0: n])
return acc }
func (l Int64Array) Take(n int) Int64Array {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([]int64, n)
copy(acc, l[0: n])
return acc }
func (l ByteArray) Take(n int) ByteArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([]byte, n)
copy(acc, l[0: n])
return acc }
func (l RuneArray) Take(n int) RuneArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([]rune, n)
copy(acc, l[0: n])
return acc }
func (l Float32Array) Take(n int) Float32Array {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([]float32, n)
copy(acc, l[0: n])
return acc }
func (l Float64Array) Take(n int) Float64Array {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([]float64, n)
copy(acc, l[0: n])
return acc }
func (l AnyArray) Take(n int) AnyArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([]Any, n)
copy(acc, l[0: n])
return acc }
func (l Tuple2Array) Take(n int) Tuple2Array {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([]Tuple2, n)
copy(acc, l[0: n])
return acc }
func (l BoolArrayArray) Take(n int) BoolArrayArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([][]bool, n)
copy(acc, l[0: n])
return acc }
func (l StringArrayArray) Take(n int) StringArrayArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([][]string, n)
copy(acc, l[0: n])
return acc }
func (l IntArrayArray) Take(n int) IntArrayArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([][]int, n)
copy(acc, l[0: n])
return acc }
func (l Int64ArrayArray) Take(n int) Int64ArrayArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([][]int64, n)
copy(acc, l[0: n])
return acc }
func (l ByteArrayArray) Take(n int) ByteArrayArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([][]byte, n)
copy(acc, l[0: n])
return acc }
func (l RuneArrayArray) Take(n int) RuneArrayArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([][]rune, n)
copy(acc, l[0: n])
return acc }
func (l Float32ArrayArray) Take(n int) Float32ArrayArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([][]float32, n)
copy(acc, l[0: n])
return acc }
func (l Float64ArrayArray) Take(n int) Float64ArrayArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([][]float64, n)
copy(acc, l[0: n])
return acc }
func (l AnyArrayArray) Take(n int) AnyArrayArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([][]Any, n)
copy(acc, l[0: n])
return acc }
func (l Tuple2ArrayArray) Take(n int) Tuple2ArrayArray {
size := len(l)
Require(n >= 0, "index should be >= 0")
if n >= size { n = size }
acc := make([][]Tuple2, n)
copy(acc, l[0: n])
return acc } | fp/bootstrap_array_take.go | 0.61451 | 0.662633 | bootstrap_array_take.go | starcoder |
package midi
import (
"bytes"
"fmt"
"gitlab.com/gomidi/midi/v2/internal/utils"
)
// Message represents a MIDI message. It can be created from the MIDI bytes of a message, by calling NewMessage.
type Message struct {
// MsgType represents the message type of the MIDI message
MsgType
// Data contains the bytes of the MiDI message
Data []byte
}
// NewMessage returns a new Message from the bytes of the message, by finding the correct type.
// If the type could not be found, the MsgType of the Message is UnknownMsg.
func NewMessage(data []byte) (m Message) {
m.MsgType = GetMsgType(data)
m.Data = data
return
}
// Key returns the MIDI key - a number from 0 to 127 for NoteOnMsg, NoteOffMsg and PolyAfterTouchMsg.
// For other messages, it returns -1.
func (m Message) Key() int8 {
if m.MsgType.IsOneOf(NoteOnMsg, NoteOffMsg, PolyAfterTouchMsg) {
k, _ := utils.ParseTwoUint7(m.Data[1], m.Data[2])
return int8(k)
}
return -1
}
// IsNoteStart checks, if we have a de facto note start, i.e. a NoteOnMsg with velocity > 0
func (m Message) IsNoteStart() bool {
if m.Is(NoteOnMsg) && m.Velocity() > 0 {
return true
}
return false
}
// IsNoteEnd checks, if we have a de facto note end, i.e. a NoteoffMsg or a NoteOnMsg with velocity == 0
func (m Message) IsNoteEnd() bool {
if m.Is(NoteOffMsg) {
return true
}
if m.Is(NoteOnMsg) && m.Velocity() == 0 {
return true
}
return false
}
// String represents the Message as a string that contains the MsgType and its properties.
func (m Message) String() string {
switch {
case m.Is(ChannelMsg):
var bf bytes.Buffer
fmt.Fprintf(&bf, m.MsgType.String())
//fmt.Fprintf(&bf, " channel: %v ", m.Channel())
switch {
case m.Is(NoteOnMsg):
fmt.Fprintf(&bf, " key: %v velocity: %v", m.Key(), m.Velocity())
case m.Is(NoteOffMsg):
fmt.Fprintf(&bf, " key: %v velocity: %v", m.Key(), m.Velocity())
case m.Is(PolyAfterTouchMsg):
fmt.Fprintf(&bf, " key: %v pressure: %v", m.Key(), m.Pressure())
case m.Is(AfterTouchMsg):
fmt.Fprintf(&bf, " pressure: %v", m.Pressure())
case m.Is(ProgramChangeMsg):
fmt.Fprintf(&bf, " program: %v", m.Program())
case m.Is(PitchBendMsg):
rel, abs := m.Pitch()
fmt.Fprintf(&bf, " pitch: %v / %v", rel, abs)
case m.Is(ControlChangeMsg):
fmt.Fprintf(&bf, " controller: %v change: %v", m.Controller(), m.Change())
default:
}
return bf.String()
case m.Is(MetaMsg):
switch {
case m.Is(MetaTempoMsg):
return fmt.Sprintf("%s bpm: %v", m.MsgType.String(), m.BPM())
case m.Is(MetaTimeSigMsg):
num, denom := m.Meter()
return fmt.Sprintf("%s meter: %v/%v", m.MsgType.String(), num, denom)
case m.IsOneOf(MetaLyricMsg, MetaMarkerMsg, MetaCopyrightMsg, MetaTextMsg, MetaCuepointMsg, MetaDeviceMsg, MetaInstrumentMsg, MetaProgramNameMsg, MetaTrackNameMsg):
return fmt.Sprintf("%s text: %q", m.MsgType.String(), m.Text())
default:
return m.MsgType.String()
}
case m.Is(SysExMsg):
// TODO print the length in bytes
return m.MsgType.String()
case m.Is(SysCommonMsg):
switch {
case m.Is(MTCMsg):
return fmt.Sprintf("%s mtc: %v", m.MsgType.String(), m.MTC())
case m.Is(SPPMsg):
return fmt.Sprintf("%s spp: %v", m.MsgType.String(), m.SPP())
case m.Is(SongSelectMsg):
return fmt.Sprintf("%s song: %v", m.MsgType.String(), m.Song())
default:
return m.MsgType.String()
}
case m.Is(RealTimeMsg):
return m.MsgType.String()
default:
return m.MsgType.String()
}
}
// Meter returns the meter of a MetaTimeSigMsg.
// For other messages, it returns 0,0.
func (m Message) Meter() (num, denom uint8) {
num, denom, _, _ = m.TimeSig()
return
}
// metaData strips away the meta byte and the metatype byte and the varlength byte
func (m Message) metaDataWithoutVarlength() []byte {
//fmt.Printf("original data: % X\n", m.Data)
return m.Data[3:]
}
// TimeSig returns the numerator, denominator, clocksPerClick and demiSemiQuaverPerQuarter of a
// MetaTimeSigMsg. For other messages, it returns 0,0,0,0.
func (m Message) TimeSig() (numerator, denominator, clocksPerClick, demiSemiQuaverPerQuarter uint8) {
if !m.Is(MetaTimeSigMsg) {
//fmt.Println("not timesig message")
return 0, 0, 0, 0
}
data := m.metaDataWithoutVarlength()
if len(data) != 4 {
//fmt.Printf("not correct data lenght: % X \n", data)
//err = unexpectedMessageLengthError("TimeSignature expected length 4")
return 0, 0, 0, 0
}
//fmt.Printf("TimeSigData: % X\n", data)
numerator = data[0]
denominator = data[1]
clocksPerClick = data[2]
demiSemiQuaverPerQuarter = data[3]
denominator = bin2decDenom(denominator)
return
}
// BPM returns the tempo in beats per minute of a meta tempo message.
func (m Message) BPM() float64 {
if !m.MsgType.Is(MetaTempoMsg) {
//fmt.Println("not tempo message")
return -1
}
rd := bytes.NewReader(m.metaDataWithoutVarlength())
microsecondsPerCrotchet, err := utils.ReadUint24(rd)
if err != nil {
//fmt.Println("cant read")
return -1
}
return float64(60000000) / float64(microsecondsPerCrotchet)
}
// Pitch returns the relative and absolute pitch of a PitchBendMsg.
// For other messages it returns -1,-1.
func (m Message) Pitch() (relative int16, absolute int16) {
if !m.MsgType.Is(PitchBendMsg) {
return -1, -1
}
rel, abs := utils.ParsePitchWheelVals(m.Data[1], m.Data[2])
return rel, int16(abs)
}
// Text returns the text for MetaLyricMsg, MetaCopyrightMsg, MetaCuepointMsg, MetaDeviceMsg, MetaInstrumentMsg, MetaMarkerMsg, MetaProgramNameMsg, MetaTextMsg and MetaTrackNameMsg.
// For other messages, it returns "".
func (m Message) Text() string {
if !m.IsOneOf(MetaLyricMsg, MetaCopyrightMsg, MetaCuepointMsg, MetaDeviceMsg, MetaInstrumentMsg, MetaMarkerMsg, MetaProgramNameMsg, MetaTextMsg, MetaTrackNameMsg) {
return ""
}
rd := bytes.NewReader(m.Data[2:])
text, _ := utils.ReadText(rd)
return text
}
// Pressure returns the pressure of a PolyAfterTouchMsg or an AfterTouchMsg.
// For other messages, it returns -1.
func (m Message) Pressure() int8 {
t := m.MsgType
if t.Is(PolyAfterTouchMsg) {
_, v := utils.ParseTwoUint7(m.Data[1], m.Data[2])
return int8(v)
}
if t.Is(AfterTouchMsg) {
return int8(utils.ParseUint7(m.Data[1]))
}
return -1
}
// Program returns the program number for a ProgramChangeMsg.
// For other messages, it returns -1.
func (m Message) Program() int8 {
t := m.MsgType
if t.Is(ProgramChangeMsg) {
return int8(utils.ParseUint7(m.Data[1]))
}
return -1
}
// Change returns the MIDI controllchange (a number from 0 to 127) of a ControlChangeMsg.
// For other messages, it returns -1.
func (m Message) Change() int8 {
if m.MsgType.Is(ControlChangeMsg) {
_, v := utils.ParseTwoUint7(m.Data[1], m.Data[2])
return int8(v)
}
return -1
}
// Channel returns the MIDI channel (a number from 0 to 15) of a ChannelMsg.
// For other messages, or an invalid channel number, it returns -1.
func (m Message) Channel() int8 {
if !m.MsgType.Is(ChannelMsg) {
return -1
}
_, ch := utils.ParseStatus(m.Data[0])
return int8(ch)
}
// Velocity returns the MIDI velocity (a number from 0 to 127) of a NoteOnMsg or a NoteOffMsg.
// For other messages, or an invalid velocity number, it returns -1.
func (m Message) Velocity() int8 {
if m.MsgType.IsOneOf(NoteOnMsg, NoteOffMsg) {
_, v := utils.ParseTwoUint7(m.Data[1], m.Data[2])
return int8(v)
}
return -1
}
// Controller returns the MIDI controller number (a number from 0 to 127) of a ControlChangeMsg.
// For other messages, or an invalid controller number, it returns -1.
func (m Message) Controller() int8 {
if m.MsgType.Is(ControlChangeMsg) {
c, _ := utils.ParseTwoUint7(m.Data[1], m.Data[2])
return int8(c)
}
return -1
}
/*
MTC Quarter Frame
These are the MTC (i.e. SMPTE based) equivalent of the F8 Timing Clock messages,
though offer much higher resolution, as they are sent at a rate of 96 to 120 times
a second (depending on the SMPTE frame rate). Each Quarter Frame message provides
partial timecode information, 8 sequential messages being required to fully
describe a timecode instant. The reconstituted timecode refers to when the first
partial was received. The most significant nibble of the data byte indicates the
partial (aka Message Type).
Partial Data byte Usage
1 0000 bcde Frame number LSBs abcde = Frame number (0 to frameRate-1)
2 0001 000a Frame number MSB
3 0010 cdef Seconds LSBs abcdef = Seconds (0-59)
4 0011 00ab Seconds MSBs
5 0100 cdef Minutes LSBs abcdef = Minutes (0-59)
6 0101 00ab Minutes MSBs
7 0110 defg Hours LSBs ab = Frame Rate (00 = 24, 01 = 25, 10 = 30drop, 11 = 30nondrop)
cdefg = Hours (0-23)
8 0111 0abc Frame Rate, and Hours MSB
*/
// MTC represents a MIDI timing code message (quarter frame)
func (m Message) MTC() int8 {
if !m.MsgType.Is(MTCMsg) {
return -1
}
return int8(utils.ParseUint7(m.Data[1]))
}
// Song returns the song number of a MIDI song select system message
func (m Message) Song() int8 {
if !m.MsgType.Is(SongSelectMsg) {
return -1
}
return int8(utils.ParseUint7(m.Data[1]))
}
// SPP returns the song position pointer of a MIDI song position pointer system message
// For other messages it returns -1,-1.
func (m Message) SPP() (spp int16) {
if !m.MsgType.Is(SPPMsg) {
return -1
}
_, abs := utils.ParsePitchWheelVals(m.Data[2], m.Data[1])
return int16(abs)
} | v2/message.go | 0.621541 | 0.416025 | message.go | starcoder |
// This package implements a basic LISP interpretor for embedding in a go program for scripting.
// This file implements data elements.
package golisp
import (
"errors"
"fmt"
"math"
"os"
"sort"
"strings"
"sync/atomic"
"unsafe"
"github.com/SteelSeries/set.v0"
)
const (
NilType = iota
ConsCellType
AlistType
AlistCellType
IntegerType
FloatType
BooleanType
StringType
SymbolType
FunctionType
MacroType
PrimitiveType
BoxedObjectType
FrameType
EnvironmentType
PortType
)
type ConsCell struct {
Car *Data
Cdr *Data
}
type BoxedObject struct {
ObjType string
Obj unsafe.Pointer
}
type Data struct {
Type uint8
Value unsafe.Pointer
}
// Boolean constants
type BooleanBox struct {
B bool
}
var b_true bool = true
var b_false bool = false
var LispTrue *Data = &Data{Type: BooleanType, Value: unsafe.Pointer(&b_true)}
var LispFalse *Data = &Data{Type: BooleanType, Value: unsafe.Pointer(&b_false)}
// Debug support
var EvalDepth int = 0
var DebugSingleStep bool = false
var DebugCurrentFrame *SymbolTableFrame = nil
var DebugEvalInDebugRepl bool = false
var DebugErrorEnv *SymbolTableFrame = nil
var DebugOnError bool = false
var IsInteractive bool = false
var DebugReturnValue *Data = nil
var DebugOnEntry *set.Set = set.New()
func TypeOf(d *Data) uint8 {
if d == nil {
return NilType
} else {
return d.Type
}
}
func TypeName(t uint8) string {
switch t {
case NilType:
return "Nil"
case ConsCellType:
return "List"
case AlistType:
return "Association List"
case AlistCellType:
return "Association List Cell"
case IntegerType:
return "Integer"
case FloatType:
return "Float"
case BooleanType:
return "Boolean"
case StringType:
return "String"
case SymbolType:
return "Symbol"
case FunctionType:
return "Function"
case MacroType:
return "Macro"
case PrimitiveType:
return "Primitive"
case FrameType:
return "Frame"
case BoxedObjectType:
return "Go Object"
case EnvironmentType:
return "Environment"
case PortType:
return "Port"
default:
return "Unknown"
}
}
// Function has heavy traffic, try to keep it fast
func NilP(d *Data) bool {
if d == nil {
return true
}
if d.Type == ConsCellType || d.Type == AlistType || d.Type == AlistCellType {
cell := (*ConsCell)(d.Value)
if cell == nil || (cell.Car == nil && cell.Cdr == nil) {
return true
}
}
return false
}
func NotNilP(d *Data) bool {
return !NilP(d)
}
func PairP(d *Data) bool {
return d == nil || TypeOf(d) == ConsCellType
}
func ListP(d *Data) bool {
return PairP(d) || AlistP(d)
}
func DottedPairP(d *Data) bool {
return d == nil || TypeOf(d) == AlistCellType
}
func AlistP(d *Data) bool {
return d == nil || TypeOf(d) == AlistType
}
func BooleanP(d *Data) bool {
return d != nil && TypeOf(d) == BooleanType
}
func SymbolP(d *Data) bool {
return d != nil && TypeOf(d) == SymbolType
}
func NakedP(d *Data) bool {
return d != nil && TypeOf(d) == SymbolType && strings.HasSuffix(StringValue(d), ":")
}
func StringP(d *Data) bool {
return d != nil && TypeOf(d) == StringType
}
func IntegerP(d *Data) bool {
return d != nil && TypeOf(d) == IntegerType
}
func FloatP(d *Data) bool {
return d != nil && TypeOf(d) == FloatType
}
func NumberP(d *Data) bool {
return IntegerP(d) || FloatP(d)
}
func ObjectP(d *Data) bool {
return d != nil && TypeOf(d) == BoxedObjectType
}
func FunctionOrPrimitiveP(d *Data) bool {
return d != nil && (TypeOf(d) == FunctionType || TypeOf(d) == PrimitiveType)
}
func FunctionP(d *Data) bool {
return d != nil && TypeOf(d) == FunctionType
}
func PrimitiveP(d *Data) bool {
return d != nil && TypeOf(d) == PrimitiveType
}
func MacroP(d *Data) bool {
return d != nil && TypeOf(d) == MacroType
}
func FrameP(d *Data) bool {
return d != nil && TypeOf(d) == FrameType
}
func EnvironmentP(d *Data) bool {
return d != nil && TypeOf(d) == EnvironmentType
}
func PortP(d *Data) bool {
return d != nil && TypeOf(d) == PortType
}
func EmptyCons() *Data {
cell := ConsCell{Car: nil, Cdr: nil}
return &Data{Type: ConsCellType, Value: unsafe.Pointer(&cell)}
}
func Cons(car *Data, cdr *Data) *Data {
cell := ConsCell{Car: car, Cdr: cdr}
return &Data{Type: ConsCellType, Value: unsafe.Pointer(&cell)}
}
func AppendBang(l *Data, value *Data) *Data {
if NilP(l) {
return Cons(value, nil)
}
var c *Data
for c = l; NotNilP(Cdr(c)); c = Cdr(c) {
}
((*ConsCell)(c.Value)).Cdr = Cons(value, nil)
return l
}
func AppendBangList(l *Data, otherList *Data) *Data {
if NilP(l) {
return otherList
}
var c *Data
for c = l; NotNilP(Cdr(c)); c = Cdr(c) {
}
((*ConsCell)(c.Value)).Cdr = otherList
return l
}
func Append(l *Data, value *Data) *Data {
if NilP(l) {
return Cons(value, nil)
}
var newList = Copy(l)
var c *Data
for c = newList; NotNilP(Cdr(c)); c = Cdr(c) {
}
((*ConsCell)(c.Value)).Cdr = Cons(value, nil)
return newList
}
func AppendList(l *Data, otherList *Data) *Data {
if NilP(l) {
return otherList
}
var newList = Copy(l)
var c *Data
for c = newList; NotNilP(Cdr(c)); c = Cdr(c) {
}
((*ConsCell)(c.Value)).Cdr = otherList
return newList
}
func RemoveFromListBang(l *Data, item *Data) (result *Data) {
var prev *Data
result = l
for cell := l; NotNilP(cell); cell = Cdr(cell) {
if IsEqual(item, Car(cell)) {
if NilP(prev) {
return Cdr(cell)
}
((*ConsCell)(prev.Value)).Cdr = Cdr(cell)
return
}
prev = cell
}
return
}
func Acons(car *Data, cdr *Data, alist *Data) *Data {
pair, _ := Assoc(car, alist)
if NilP(pair) {
p := ConsCell{Car: car, Cdr: cdr}
cell := Data{Type: AlistCellType, Value: unsafe.Pointer(&p)}
conscell := ConsCell{Car: &cell, Cdr: alist}
return &Data{Type: AlistType, Value: unsafe.Pointer(&conscell)}
} else {
((*ConsCell)(pair.Value)).Cdr = cdr
return alist
}
}
func Alist(d *Data) *Data {
if NilP(d) {
return nil
}
if PairP(d) {
headPair := Car(d)
return Acons(Car(headPair), Cdr(headPair), Alist(Cdr(d)))
}
return d
}
func InternalMakeList(c ...*Data) *Data {
return ArrayToList(c)
}
func FrameWithValue(m *FrameMap) *Data {
return &Data{Type: FrameType, Value: unsafe.Pointer(m)}
}
// func EmptyFrame() *Data {
// return &Data{Type: FrameType, Frame: &make(FrameMap)}
// }
func IntegerWithValue(n int64) *Data {
return &Data{Type: IntegerType, Value: unsafe.Pointer(&n)}
}
func FloatWithValue(n float32) *Data {
return &Data{Type: FloatType, Value: unsafe.Pointer(&n)}
}
func BooleanWithValue(b bool) *Data {
if b {
return LispTrue
} else {
return LispFalse
}
}
func StringWithValue(s string) *Data {
return &Data{Type: StringType, Value: unsafe.Pointer(&s)}
}
func SetStringValue(d *Data, s string) *Data {
if StringP(d) {
d.Value = unsafe.Pointer(&s)
return d
} else {
return nil
}
}
func SymbolWithName(s string) *Data {
return &Data{Type: SymbolType, Value: unsafe.Pointer(&s)}
}
func NakedSymbolWithName(s string) *Data {
return Intern(fmt.Sprintf("%s:", s))
}
func NakedSymbolFrom(d *Data) *Data {
return NakedSymbolWithName(StringValue(d))
}
func FunctionWithNameParamsBodyAndParent(name string, params *Data, body *Data, parentEnv *SymbolTableFrame) *Data {
return &Data{Type: FunctionType, Value: unsafe.Pointer(MakeFunction(name, params, body, parentEnv))}
}
func MacroWithNameParamsBodyAndParent(name string, params *Data, body *Data, parentEnv *SymbolTableFrame) *Data {
return &Data{Type: MacroType, Value: unsafe.Pointer(MakeMacro(name, params, body, parentEnv))}
}
func PrimitiveWithNameAndFunc(name string, f *PrimitiveFunction) *Data {
return &Data{Type: PrimitiveType, Value: unsafe.Pointer(f)}
}
func ObjectWithTypeAndValue(typeName string, o unsafe.Pointer) *Data {
bo := BoxedObject{ObjType: typeName, Obj: o}
return &Data{Type: BoxedObjectType, Value: unsafe.Pointer(&bo)}
}
func EnvironmentWithValue(e *SymbolTableFrame) *Data {
return &Data{Type: EnvironmentType, Value: unsafe.Pointer(e)}
}
func PortWithValue(e *os.File) *Data {
return &Data{Type: PortType, Value: unsafe.Pointer(e)}
}
func ConsValue(d *Data) *ConsCell {
if d == nil {
return nil
}
if PairP(d) || AlistP(d) || DottedPairP(d) {
return (*ConsCell)(d.Value)
}
return nil
}
// Function has heavy traffic, try to keep it fast
func Car(d *Data) *Data {
if d == nil {
return nil
}
if d.Type == ConsCellType || d.Type == AlistType || d.Type == AlistCellType {
cell := (*ConsCell)(d.Value)
if cell != nil {
return cell.Car
}
}
return nil
}
// Function has heavy traffic, try to keep it fast
func Cdr(d *Data) *Data {
if d == nil {
return nil
}
if d.Type == ConsCellType || d.Type == AlistType || d.Type == AlistCellType {
cell := (*ConsCell)(d.Value)
if cell != nil {
return cell.Cdr
}
}
return nil
}
func IntegerValue(d *Data) int64 {
if d == nil {
return 0
}
if IntegerP(d) {
return *((*int64)(d.Value))
}
if FloatP(d) {
return int64(*((*float32)(d.Value)))
}
return 0
}
func FloatValue(d *Data) float32 {
if d == nil {
return 0
}
if FloatP(d) {
return *((*float32)(d.Value))
}
if IntegerP(d) {
return float32(*((*int64)(d.Value)))
}
return 0
}
func StringValue(d *Data) string {
if d == nil {
return ""
}
if StringP(d) || SymbolP(d) {
return *((*string)(d.Value))
}
return ""
}
func BooleanValue(d *Data) bool {
if NilP(d) {
return false
}
if BooleanP(d) {
return *((*bool)(d.Value))
}
return true
}
func FrameValue(d *Data) *FrameMap {
if d == nil {
return nil
}
if FrameP(d) {
return (*FrameMap)(d.Value)
}
return nil
}
func FunctionValue(d *Data) *Function {
if d == nil {
return nil
}
if d.Type == FunctionType {
return (*Function)(d.Value)
}
return nil
}
func MacroValue(d *Data) *Macro {
if d == nil {
return nil
}
if d.Type == MacroType {
return (*Macro)(d.Value)
}
return nil
}
func PrimitiveValue(d *Data) *PrimitiveFunction {
if d == nil {
return nil
}
if d.Type == PrimitiveType {
return (*PrimitiveFunction)(d.Value)
}
return nil
}
func ObjectType(d *Data) (oType string) {
if d == nil {
return
}
if ObjectP(d) {
return (*((*BoxedObject)(d.Value))).ObjType
}
return
}
func ObjectValue(d *Data) (p unsafe.Pointer) {
if d == nil {
return
}
if ObjectP(d) {
return (*((*BoxedObject)(d.Value))).Obj
}
return
}
func BoxedObjectValue(d *Data) *BoxedObject {
if d == nil {
return nil
}
if ObjectP(d) {
return (*BoxedObject)(d.Value)
}
return nil
}
func EnvironmentValue(d *Data) *SymbolTableFrame {
if d == nil {
return nil
}
if EnvironmentP(d) {
return (*SymbolTableFrame)(d.Value)
}
return nil
}
func PortValue(d *Data) *os.File {
if d == nil {
return nil
}
if PortP(d) {
return (*os.File)(d.Value)
}
return nil
}
// Function has heavy traffic, try to keep it fast, at least for the list/bytearray cases
func Length(d *Data) int {
if d == nil {
return 0
}
if d.Type == ConsCellType || d.Type == AlistType {
l := 0
for c := d; NotNilP(c); c = Cdr(c) {
l += 1
}
return l
}
if d.Type == BoxedObjectType && ((*BoxedObject)(d.Value)).ObjType == "[]byte" {
dBytes := *(*[]byte)(((*BoxedObject)(d.Value)).Obj)
return len(dBytes)
}
if FrameP(d) {
frame := FrameValue(d)
frame.Mutex.RLock()
length := len(frame.Data)
frame.Mutex.RUnlock()
return length
}
return 0
}
func Reverse(d *Data) (result *Data) {
if d == nil {
return nil
}
if !ListP(d) {
return d
}
var l *Data = nil
for c := d; NotNilP(c); c = Cdr(c) {
l = Cons(Car(c), l)
}
return l
}
func Flatten(d *Data) (result *Data, err error) {
if d == nil {
return nil, nil
}
if !ListP(d) {
return d, nil
}
var l []*Data = make([]*Data, 0, 10)
for c := d; NotNilP(c); c = Cdr(c) {
if ListP(Car(c)) {
for i := Car(c); i != nil; i = Cdr(i) {
l = append(l, Car(i))
}
} else {
l = append(l, Car(c))
}
}
return ArrayToList(l), nil
}
func RecursiveFlatten(d *Data) (result *Data, err error) {
if d == nil {
return nil, nil
}
if !ListP(d) {
return d, nil
}
var l []*Data = make([]*Data, 0, 10)
var elem *Data
for c := d; NotNilP(c); c = Cdr(c) {
if ListP(Car(c)) {
elem, err = RecursiveFlatten(Car(c))
if err != nil {
return
}
for i := elem; i != nil; i = Cdr(i) {
l = append(l, Car(i))
}
} else {
l = append(l, Car(c))
}
}
return ArrayToList(l), nil
}
func QuoteIt(value *Data) (result *Data) {
if value == nil {
return InternalMakeList(Intern("quote"), Cons(nil, nil))
} else {
return InternalMakeList(Intern("quote"), value)
}
}
func QuoteAll(d *Data) (result *Data) {
var l []*Data = make([]*Data, 0, 10)
if d == nil {
l = append(l, QuoteIt(nil))
} else {
for c := d; c != nil; c = Cdr(c) {
l = append(l, QuoteIt(Car(c)))
}
}
return ArrayToList(l)
}
func Assoc(key *Data, alist *Data) (result *Data, err error) {
for c := alist; NotNilP(c); c = Cdr(c) {
pair := Car(c)
if !DottedPairP(pair) && !PairP(pair) {
err = errors.New("An alist MUST be made of pairs.")
return
}
if IsEqual(Car(pair), key) {
result = pair
return
}
}
return
}
func Dissoc(key *Data, alist *Data) (result *Data, err error) {
var newList *Data = nil
for c := alist; NotNilP(c); c = Cdr(c) {
pair := Car(c)
if !DottedPairP(pair) && !PairP(pair) {
err = errors.New("An alist MUST be made of pairs.")
return
}
if !IsEqual(Car(pair), key) {
newList = Acons(Car(pair), Cdr(pair), newList)
}
}
return newList, nil
}
func Copy(d *Data) *Data {
if d == nil {
return d
}
switch d.Type {
case AlistType:
{
alist := Acons(Copy(Caar(d)), Copy(Cdar(d)), nil)
for c := Cdr(d); NotNilP(c); c = Cdr(c) {
alist = Acons(Copy(Caar(c)), Copy(Cdar(c)), alist)
}
return alist
}
case ConsCellType:
{
if NilP(d) {
return d
}
return Cons(Copy(Car(d)), Copy(Cdr(d)))
}
case FrameType:
{
m := FrameMap{}
m.Data = make(FrameMapData)
frame := FrameValue(d)
frame.Mutex.RLock()
for k, v := range frame.Data {
m.Data[k] = Copy(v)
}
frame.Mutex.RUnlock()
return FrameWithValue(&m)
}
case BoxedObjectType:
{
if ObjectType(d) == "[]byte" {
bytes := (*[]byte)(ObjectValue(d))
copy := append([]byte{}, *bytes...)
return ObjectWithTypeAndValue("[]byte", unsafe.Pointer(©))
}
}
}
return d
}
func IsEqual(d *Data, o *Data) bool {
if d == o && !FloatP(d) {
return true
}
if NilP(d) && NilP(o) {
return true
}
if d == nil || o == nil {
return false
}
if AlistP(d) {
if !AlistP(o) && !ListP(o) {
return false
}
} else if DottedPairP(d) {
if !PairP(o) && !DottedPairP(o) {
return false
}
} else if TypeOf(o) != TypeOf(d) {
return false
}
if AlistP(d) {
if Length(d) != Length(o) {
return false
}
for c := d; NotNilP(c); c = Cdr(c) {
otherPair, err := Assoc(Caar(c), o)
if err != nil || NilP(otherPair) || !IsEqual(Cdar(c), Cdr(otherPair)) {
return false
}
}
return true
}
if DottedPairP(d) {
return IsEqual(Car(d), Car(o)) && IsEqual(Cdr(d), Cdr(o))
}
if ListP(d) {
if Length(d) != Length(o) {
return false
}
for a1, a2 := d, o; NotNilP(a1); a1, a2 = Cdr(a1), Cdr(a2) {
if !IsEqual(Car(a1), Car(a2)) {
return false
}
}
return true
}
if FrameP(d) {
frameD := FrameValue(d)
frameO := FrameValue(o)
frameD.Mutex.RLock()
frameO.Mutex.RLock()
if len(frameD.Data) != len(frameO.Data) {
frameO.Mutex.RUnlock()
frameD.Mutex.RUnlock()
return false
}
for k, v := range frameD.Data {
if !IsEqual(v, frameO.Data[k]) {
frameO.Mutex.RUnlock()
frameD.Mutex.RUnlock()
return false
}
}
frameO.Mutex.RUnlock()
frameD.Mutex.RUnlock()
return true
}
// special case for byte arrays
if ObjectP(d) && ObjectType(d) == "[]byte" && ObjectType(o) == "[]byte" {
dBytes := *(*[]byte)(ObjectValue(d))
oBytes := *(*[]byte)(ObjectValue(o))
if len(dBytes) != len(oBytes) {
return false
} else {
for i := 0; i < len(dBytes); i++ {
if dBytes[i] != oBytes[i] {
return false
}
}
}
return true
}
switch TypeOf(d) {
case IntegerType:
return IntegerValue(d) == IntegerValue(o)
case FloatType:
return FloatValue(d) == FloatValue(o)
case BooleanType:
return BooleanValue(d) == BooleanValue(o)
case StringType, SymbolType: // check symbols not generated using intern (aka: gensym and gensym-naked)
return StringValue(d) == StringValue(o)
case FunctionType:
return FunctionValue(d) == FunctionValue(o)
case MacroType:
return MacroValue(d) == MacroValue(o)
case PrimitiveType:
return PrimitiveValue(d) == PrimitiveValue(o)
case BoxedObjectType:
return (ObjectType(d) == ObjectType(o)) && (ObjectValue(d) == ObjectValue(o))
}
return *d == *o
}
func escapeQuotes(str string) string {
buffer := make([]rune, 0, 10)
for _, ch := range str {
if rune(ch) == '"' {
buffer = append(buffer, '\\')
}
buffer = append(buffer, rune(ch))
}
return string(buffer)
}
func String(d *Data) string {
if d == nil {
return "()"
}
switch d.Type {
case ConsCellType:
{
if NilP(d) {
return "()"
}
var c *Data = d
contents := make([]string, 0, Length(d))
for NotNilP(c) && PairP(c) {
contents = append(contents, String(Car(c)))
c = Cdr(c)
}
if NilP(c) {
if SymbolP(Car(d)) && StringValue(Car(d)) == "quote" {
if len(contents) == 1 {
return fmt.Sprintf("'()")
} else {
return fmt.Sprintf("'%s", contents[1])
}
} else {
return fmt.Sprintf("(%s)", strings.Join(contents, " "))
}
} else {
return fmt.Sprintf("(%s . %s)", strings.Join(contents, " "), String(c))
}
}
case AlistType:
{
if NilP(d) {
return "()"
}
contents := make([]string, 0, Length(d))
for c := d; NotNilP(c); c = Cdr(c) {
contents = append(contents, String(Car(c)))
}
return fmt.Sprintf("(%s)", strings.Join(contents, " "))
}
case AlistCellType:
return fmt.Sprintf("(%s . %s)", String(Car(d)), String(Cdr(d)))
case IntegerType:
return fmt.Sprintf("%d", IntegerValue(d))
case FloatType:
{
v := FloatValue(d)
if math.IsInf(float64(v), 0) {
sign := "+"
if math.Signbit(float64(v)) {
sign = "-"
}
return fmt.Sprintf("%sinf", sign)
}
if math.IsNaN(float64(v)) {
return "nan"
}
raw := fmt.Sprintf("%g", FloatValue(d))
if strings.ContainsRune(raw, '.') {
return raw
}
return fmt.Sprintf("%s.0", raw)
}
case BooleanType:
if BooleanValue(d) {
return "#t"
} else {
return "#f"
}
case StringType:
return fmt.Sprintf(`"%s"`, escapeQuotes(StringValue(d)))
case SymbolType:
return StringValue(d)
case FunctionType:
return fmt.Sprintf("<function: %s>", FunctionValue(d).Name)
case MacroType:
return fmt.Sprintf("<macro: %s>", MacroValue(d).Name)
case PrimitiveType:
return fmt.Sprintf("<prim: %s>", PrimitiveValue(d).Name)
case BoxedObjectType:
if ObjectType(d) == "[]byte" {
bytes := (*[]byte)(ObjectValue(d))
contents := make([]string, 0, len(*bytes))
for _, b := range *bytes {
contents = append(contents, fmt.Sprintf("%d", b))
}
return fmt.Sprintf("[%s]", strings.Join(contents, " "))
} else {
return fmt.Sprintf("<opaque Go object of type %s : 0x%x>", ObjectType(d), (*uint64)(ObjectValue(d)))
}
case FrameType:
frame := FrameValue(d)
frame.Mutex.RLock()
keys := make([]string, 0, len(frame.Data))
for key, _ := range frame.Data {
keys = append(keys, key)
}
sort.Strings(keys)
pairs := make([]string, 0, len(frame.Data))
for _, key := range keys {
val := frame.Data[key]
var valString string = String(val)
pairs = append(pairs, fmt.Sprintf("%s %s", key, valString))
}
frame.Mutex.RUnlock()
return fmt.Sprintf("{%s}", strings.Join(pairs, " "))
case EnvironmentType:
return fmt.Sprintf("<environment: %s>", EnvironmentValue(d).Name)
case PortType:
return fmt.Sprintf("<port: %s>", PortValue(d).Name())
}
return ""
}
func PrintString(d *Data) string {
if StringP(d) {
return StringValue(d)
} else {
return String(d)
}
}
func postProcessShortcuts(d *Data) *Data {
symbolObj := Car(d)
if !SymbolP(symbolObj) {
return d
}
pseudoFunction := StringValue(symbolObj)
switch {
// channel shortcuts
case strings.HasPrefix(pseudoFunction, "<-"):
return AppendBangList(InternalMakeList(Intern("channel-read"), Intern(strings.TrimPrefix(pseudoFunction, "<-"))), Cdr(d))
case strings.HasSuffix(pseudoFunction, "<-"):
return AppendBangList(InternalMakeList(Intern("channel-write"), Intern(strings.TrimSuffix(pseudoFunction, "<-"))), Cdr(d))
// frame shortcuts
case strings.HasSuffix(pseudoFunction, ":"):
return AppendBangList(InternalMakeList(Intern("get-slot"), Cadr(d), Car(d)), Cddr(d))
case strings.HasSuffix(pseudoFunction, ":!"):
return AppendBangList(InternalMakeList(Intern("set-slot!"), Cadr(d), Intern(strings.TrimSuffix(pseudoFunction, "!")), Caddr(d)), Cdddr(d))
case strings.HasSuffix(pseudoFunction, ":?"):
return AppendBangList(InternalMakeList(Intern("has-slot?"), Cadr(d), Intern(strings.TrimSuffix(pseudoFunction, "?"))), Cddr(d))
case strings.HasSuffix(pseudoFunction, ":>"):
return AppendBangList(InternalMakeList(Intern("send"), Cadr(d), Intern(strings.TrimSuffix(pseudoFunction, ">"))), Cddr(d))
case strings.HasSuffix(pseudoFunction, ":^"):
return AppendBangList(InternalMakeList(Intern("send-super"), Intern(strings.TrimSuffix(pseudoFunction, "^"))), Cdr(d))
default:
return d
}
}
func printDashes(indent int) {
for i := indent; i > 0; i -= 1 {
fmt.Print("-")
}
}
func logEval(d *Data, env *SymbolTableFrame) {
if LispTrace && !DebugEvalInDebugRepl {
depth := env.Depth()
fmt.Printf("%3d: ", depth)
printDashes(depth)
fmt.Printf("> %s\n", String(d))
EvalDepth += 1
}
}
func logResult(result *Data, env *SymbolTableFrame) {
if LispTrace && !DebugEvalInDebugRepl {
depth := env.Depth()
fmt.Printf("%3d: <", depth)
printDashes(depth)
fmt.Printf(" %s\n", String(result))
}
}
func evalHelper(d *Data, env *SymbolTableFrame, needFunction bool) (result *Data, err error) {
if IsInteractive && !DebugEvalInDebugRepl {
env.CurrentCode.PushFront(fmt.Sprintf("Eval %s", String(d)))
}
logEval(d, env)
if DebugSingleStep {
DebugSingleStep = false
DebugRepl(env)
}
if DebugCurrentFrame != nil && env == DebugCurrentFrame.Previous {
DebugCurrentFrame = nil
DebugRepl(env)
}
if d != nil {
switch d.Type {
case ConsCellType:
{
d = postProcessShortcuts(d)
// catch empty cons cell
if NilP(d) {
return EmptyCons(), nil
}
var function *Data
function, err = evalHelper(Car(d), env, true)
if err != nil {
return
}
if NilP(function) {
err = errors.New(fmt.Sprintf("Nil when function or macro expected for %s.", String(Car(d))))
return
}
if !DebugSingleStep && TypeOf(function) == FunctionType && DebugOnEntry.Has(FunctionValue(function).Name) {
DebugRepl(env)
}
args := Cdr(d)
result, err = Apply(function, args, env)
if err != nil {
err = fmt.Errorf("\nEvaling %s. %w", String(d), err)
return
} else if DebugReturnValue != nil {
result = DebugReturnValue
DebugReturnValue = nil
}
}
case SymbolType:
if NakedP(d) {
result = d
} else {
result = env.ValueOfWithFunctionSlotCheck(d, needFunction)
}
default:
result = d
}
}
logResult(result, env)
if IsInteractive && !DebugEvalInDebugRepl && env.CurrentCode.Len() > 0 {
env.CurrentCode.Remove(env.CurrentCode.Front())
}
return result, nil
}
func Eval(d *Data, env *SymbolTableFrame) (result *Data, err error) {
return evalHelper(d, env, false)
}
func formatApply(function *Data, args *Data) string {
var fname string
if NilP(function) {
return "Trying to apply nil!"
}
switch function.Type {
case FunctionType:
fname = FunctionValue(function).Name
case MacroType:
fname = MacroValue(function).Name
case PrimitiveType:
fname = PrimitiveValue(function).Name
default:
return fmt.Sprintf("%s when function or macro expected for %s.", TypeName(TypeOf(function)), String(function))
}
return fmt.Sprintf("Apply %s to %s", fname, String(args))
}
func Apply(function *Data, args *Data, env *SymbolTableFrame) (result *Data, err error) {
if NilP(function) {
err = errors.New("Nil when function expected.")
return
}
switch function.Type {
case FunctionType:
if atomic.LoadInt32(&FunctionValue(function).SlotFunction) == 1 && env.HasFrame() {
result, err = FunctionValue(function).ApplyWithFrame(args, env, env.Frame)
} else {
result, err = FunctionValue(function).Apply(args, env)
}
case MacroType:
result, err = MacroValue(function).Apply(args, env)
case PrimitiveType:
result, err = PrimitiveValue(function).Apply(args, env)
default:
err = errors.New(fmt.Sprintf("%s when function or macro expected for %s.", TypeName(TypeOf(function)), String(function)))
return
}
return
}
func ApplyWithoutEval(function *Data, args *Data, env *SymbolTableFrame) (result *Data, err error) {
if function == nil {
err = errors.New("Nil when function or macro expected.")
return
}
switch function.Type {
case FunctionType:
if atomic.LoadInt32(&FunctionValue(function).SlotFunction) == 1 && env.HasFrame() {
result, err = FunctionValue(function).ApplyWithoutEvalWithFrame(args, env, env.Frame)
} else {
result, err = FunctionValue(function).ApplyWithoutEval(args, env)
}
// result, err = FunctionValue(function).ApplyWithoutEval(args, env)
case MacroType:
result, err = MacroValue(function).ApplyWithoutEval(args, env)
case PrimitiveType:
result, err = PrimitiveValue(function).ApplyWithoutEval(args, env)
default:
err = errors.New(fmt.Sprintf("%s when function or macro expected for %s.", TypeName(TypeOf(function)), String(function)))
return
}
return
} | data.go | 0.721449 | 0.45417 | data.go | starcoder |
package byteorder
import "math"
var _ = (LittleEndian)(nil)
// LE is an Alias for LittleEndian.
type LE = LittleEndian
// LittleEndian defines little-endian serialization.
type LittleEndian []byte
// ReadUint16 reads the first 2 bytes. An optimized unsafe read on a little endian machine may look like this:
// b := *(*uint16)(unsafe.Pointer(uintptr(unsafe.Pointer(*(**uint16)(unsafe.Pointer(&f.Bytes))))+uintptr(f.Pos)))
// f.Pos+=2
// Warning: such unsafe code relies on UB (undefined behavior) for unaligned access but x86 allows that with a
// speed penalty (when crossing cache lines). Panics when len(b) < 2.
func (b LittleEndian) ReadUint16() uint16 {
_ = b[1] // bounds check hint to compiler; see golang.org/issue/14808
return uint16(b[0]) | uint16(b[1])<<8
}
// WriteUint16 writes an unsigned 16 bit integer. Panics when len(b) < 2.
func (b LittleEndian) WriteUint16(v uint16) {
_ = b[1] // bounds check hint to compiler; see golang.org/issue/14808
b[0] = byte(v)
b[1] = byte(v >> 8) //nolint:gomnd
}
// ReadUint24 reads the first 3 bytes. Panics when len(b) < 3.
func (b LittleEndian) ReadUint24() uint32 {
_ = b[2] // bounds check hint to compiler; see golang.org/issue/14808
return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16
}
// WriteUint24 writes the first 3 bytes. Panics when len(b) < 3.
func (b LittleEndian) WriteUint24(v uint32) {
_ = b[2] // early bounds check to guarantee safety of writes below
b[0] = byte(v)
b[1] = byte(v >> 8) //nolint:gomnd
b[2] = byte(v >> 16) //nolint:gomnd
}
// ReadUint32 reads the first 4 bytes. An optimized unsafe read may look like this:
// b := *(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(*(**uint32)(unsafe.Pointer(&f.Bytes))))+uintptr(f.Pos)))
// f.Pos+=4
// Warning: such unsafe code relies on UB (undefined behavior) for unaligned access but x86 allows that with a
// speed penalty (when crossing cache lines). Panics when len(b) < 4.
func (b LittleEndian) ReadUint32() uint32 {
_ = b[3] // bounds check hint to compiler; see golang.org/issue/14808
return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
}
// WriteUint32 writes the first 4 bytes. Panics when len(b) < 4.
func (b LittleEndian) WriteUint32(v uint32) {
_ = b[3] // bounds check hint to compiler; see golang.org/issue/14808
b[0] = byte(v)
b[1] = byte(v >> 8) //nolint:gomnd
b[2] = byte(v >> 16) //nolint:gomnd
b[3] = byte(v >> 24) //nolint:gomnd
}
// ReadUint40 reads the first 5 bytes. Panics when len(b) < 5.
func (b LittleEndian) ReadUint40() uint64 {
_ = b[4] // bounds check hint to compiler; see golang.org/issue/14808
return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32
}
// WriteUint40 writes the first 5 bytes. Panics when len(b) < 5.
func (b LittleEndian) WriteUint40(v uint64) {
_ = b[4] // bounds check hint to compiler; see golang.org/issue/14808
b[0] = byte(v)
b[1] = byte(v >> 8) //nolint:gomnd
b[2] = byte(v >> 16) //nolint:gomnd
b[3] = byte(v >> 24) //nolint:gomnd
b[4] = byte(v >> 32) //nolint:gomnd
}
// ReadUint48 reads the first 6 bytes. Panics when len(b) < 6.
func (b LittleEndian) ReadUint48() uint64 {
_ = b[5] // bounds check hint to compiler; see golang.org/issue/14808
return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |
uint64(b[4])<<32 | uint64(b[5])<<40
}
// WriteUint48 writes the first 6 bytes. Panics when len(b) < 6.
func (b LittleEndian) WriteUint48(v uint64) {
_ = b[5] // bounds check hint to compiler; see golang.org/issue/14808
b[0] = byte(v)
b[1] = byte(v >> 8) //nolint:gomnd
b[2] = byte(v >> 16) //nolint:gomnd
b[3] = byte(v >> 24) //nolint:gomnd
b[4] = byte(v >> 32) //nolint:gomnd
b[5] = byte(v >> 40) //nolint:gomnd
}
// ReadUint56 reads the first 7 bytes. Panics when len(b) < 7.
func (b LittleEndian) ReadUint56() uint64 {
_ = b[6] // bounds check hint to compiler; see golang.org/issue/14808
return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |
uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48
}
// WriteUint56 writes the first 7 bytes. Panics when len(b) < 7.
func (b LittleEndian) WriteUint56(v uint64) {
_ = b[6] // bounds check hint to compiler; see golang.org/issue/14808
b[0] = byte(v)
b[1] = byte(v >> 8) //nolint:gomnd
b[2] = byte(v >> 16) //nolint:gomnd
b[3] = byte(v >> 24) //nolint:gomnd
b[4] = byte(v >> 32) //nolint:gomnd
b[5] = byte(v >> 40) //nolint:gomnd
b[6] = byte(v >> 48) //nolint:gomnd
}
// ReadUint64 reads the first 8 bytes. Panics when len(b) < 8.
func (b LittleEndian) ReadUint64() uint64 {
_ = b[7] // bounds check hint to compiler; see golang.org/issue/14808
return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |
uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
}
// WriteUint64 writes the first 8 bytes. Panics when len(b) < 8.
func (b LittleEndian) WriteUint64(v uint64) {
_ = b[7] // bounds check hint to compiler; see golang.org/issue/14808
b[0] = byte(v)
b[1] = byte(v >> 8) //nolint:gomnd
b[2] = byte(v >> 16) //nolint:gomnd
b[3] = byte(v >> 24) //nolint:gomnd
b[4] = byte(v >> 32) //nolint:gomnd
b[5] = byte(v >> 40) //nolint:gomnd
b[6] = byte(v >> 48) //nolint:gomnd
b[7] = byte(v >> 56) //nolint:gomnd
}
// ReadFloat64 reads 8 bytes and interprets them as a float64 IEEE 754 4 byte bit sequence.
// Panics when len(b) < 8.
func (b LittleEndian) ReadFloat64() float64 {
bits := b.ReadUint64()
return math.Float64frombits(bits)
}
// WriteFloat64 writes a float64 IEEE 754 8 byte bit sequence.
// Panics when len(b) < 8.
func (b LittleEndian) WriteFloat64(v float64) {
bits := math.Float64bits(v)
b.WriteUint64(bits)
}
// ReadFloat32 reads 4 bytes and interprets them as a float32 IEEE 754 4 byte bit sequence.
// Panics when len(b) < 4.
func (b LittleEndian) ReadFloat32() float32 {
bits := b.ReadUint32()
return math.Float32frombits(bits)
}
// WriteFloat32 writes a float32 IEEE 754 4 byte bit sequence.
// Panics when len(b) < 4.
func (b LittleEndian) WriteFloat32(v float32) {
bits := math.Float32bits(v)
b.WriteUint32(bits)
} | littleendian.go | 0.554229 | 0.48871 | littleendian.go | starcoder |
// Package planner contains a query planner for Rego queries.
package planner
import (
"fmt"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/internal/ir"
)
type planiter func() error
// Planner implements a query planner for Rego queries.
type Planner struct {
strings []ir.StringConst
blocks []ir.Block
curr *ir.Block
vars map[ast.Var]ir.Local
queries []ast.Body
ltarget ir.Local
lcurr ir.Local
}
// New returns a new Planner object.
func New() *Planner {
return &Planner{
lcurr: ir.Input + 1,
vars: map[ast.Var]ir.Local{
ast.InputRootDocument.Value.(ast.Var): ir.Input,
},
}
}
// WithQueries sets the query set to generate a plan for.
func (p *Planner) WithQueries(queries []ast.Body) *Planner {
p.queries = queries
return p
}
// Plan returns a IR plan for the policy query.
func (p *Planner) Plan() (*ir.Policy, error) {
for _, q := range p.queries {
p.blocks = append(p.blocks, ir.Block{})
p.curr = &p.blocks[len(p.blocks)-1]
if err := p.planQuery(q, 0); err != nil {
return nil, err
}
p.appendStmt(ir.ReturnStmt{
Code: ir.Defined,
})
}
p.blocks = append(p.blocks, ir.Block{
Stmts: []ir.Stmt{
ir.ReturnStmt{
Code: ir.Undefined,
},
},
})
policy := ir.Policy{
Static: ir.Static{
Strings: p.strings,
},
Plan: ir.Plan{
Blocks: p.blocks,
},
}
return &policy, nil
}
func (p *Planner) planQuery(q ast.Body, index int) error {
if index >= len(q) {
return nil
}
return p.planExpr(q[index], func() error {
return p.planQuery(q, index+1)
})
}
// TODO(tsandall): improve errors to include locaiton information.
func (p *Planner) planExpr(e *ast.Expr, iter planiter) error {
if e.Negated {
return fmt.Errorf("not keyword not implemented")
}
if len(e.With) > 0 {
return fmt.Errorf("with keyword not implemented")
}
if e.IsCall() {
return p.planExprCall(e, iter)
}
return p.planExprTerm(e, iter)
}
func (p *Planner) planExprTerm(e *ast.Expr, iter planiter) error {
return p.planTerm(e.Terms.(*ast.Term), iter)
}
func (p *Planner) planExprCall(e *ast.Expr, iter planiter) error {
switch e.Operator().String() {
case ast.Equality.Name:
return p.planExprEquality(e, iter)
default:
return fmt.Errorf("%v operator not implemented", e.Operator())
}
}
func (p *Planner) planExprEquality(e *ast.Expr, iter planiter) error {
return p.planTerm(e.Operand(0), func() error {
a := p.ltarget
return p.planTerm(e.Operand(1), func() error {
b := p.ltarget
p.appendStmt(ir.EqualStmt{
A: a,
B: b,
})
return iter()
})
})
}
func (p *Planner) planTerm(t *ast.Term, iter planiter) error {
switch v := t.Value.(type) {
case ast.Number:
return p.planNumber(v, iter)
case ast.String:
return p.planString(v, iter)
case ast.Var:
return p.planVar(v, iter)
case ast.Ref:
return p.planRef(v, iter)
default:
return fmt.Errorf("%v term not implemented", ast.TypeName(v))
}
}
func (p *Planner) planNumber(num ast.Number, iter planiter) error {
i, ok := num.Int()
if !ok {
return fmt.Errorf("float values not implemented")
}
i64 := int64(i)
target := p.newLocal()
p.appendStmt(ir.MakeNumberIntStmt{
Value: i64,
Target: target,
})
p.ltarget = target
return iter()
}
func (p *Planner) planString(str ast.String, iter planiter) error {
index := p.appendStringConst(string(str))
target := p.newLocal()
p.appendStmt(ir.MakeStringStmt{
Index: index,
Target: target,
})
p.ltarget = target
return iter()
}
func (p *Planner) planVar(v ast.Var, iter planiter) error {
if _, ok := p.vars[v]; !ok {
p.vars[v] = p.newLocal()
}
p.ltarget = p.vars[v]
return iter()
}
func (p *Planner) planRef(ref ast.Ref, iter planiter) error {
if !ref[0].Equal(ast.InputRootDocument) {
return fmt.Errorf("%v root document not implemented", ref[0])
}
p.ltarget = p.vars[ast.InputRootDocument.Value.(ast.Var)]
return p.planRefRec(ref, 1, iter)
}
func (p *Planner) planRefRec(ref ast.Ref, index int, iter planiter) error {
if len(ref) == index {
return iter()
}
switch v := ref[index].Value.(type) {
case ast.Null, ast.Boolean, ast.Number, ast.String:
source := p.ltarget
return p.planTerm(ref[index], func() error {
key := p.ltarget
target := p.newLocal()
p.appendStmt(ir.DotStmt{
Source: source,
Key: key,
Target: target,
})
p.ltarget = target
return p.planRefRec(ref, index+1, iter)
})
case ast.Var:
if _, ok := p.vars[v]; !ok {
return p.planLoop(ref, index, iter)
}
p.ltarget = p.vars[v]
return p.planRefRec(ref, index+1, iter)
default:
return fmt.Errorf("%v reference operand not implemented", ast.TypeName(ref[index].Value))
}
}
func (p *Planner) planLoop(ref ast.Ref, index int, iter planiter) error {
source := p.ltarget
return p.planVar(ref[index].Value.(ast.Var), func() error {
key := p.ltarget
cond := p.newLocal()
value := p.newLocal()
p.appendStmt(ir.MakeBooleanStmt{
Value: false,
Target: cond,
})
loop := ir.LoopStmt{
Source: source,
Key: key,
Value: value,
Cond: cond,
}
prev := p.curr
p.curr = &loop.Block
p.ltarget = value
if err := iter(); err != nil {
return err
}
p.appendStmt(ir.AssignStmt{
Value: ir.BooleanConst{
Value: true,
},
Target: cond,
})
p.curr = prev
p.appendStmt(loop)
truth := p.newLocal()
p.appendStmt(ir.MakeBooleanStmt{
Value: true,
Target: truth,
})
p.appendStmt(ir.EqualStmt{
A: cond,
B: truth,
})
return nil
})
}
func (p *Planner) appendStmt(s ir.Stmt) {
p.curr.Stmts = append(p.curr.Stmts, s)
}
func (p *Planner) appendStringConst(s string) int {
index := len(p.strings)
p.strings = append(p.strings, ir.StringConst{
Value: s,
})
return index
}
func (p *Planner) newLocal() ir.Local {
x := p.lcurr
p.lcurr++
return x
} | internal/planner/planner.go | 0.627837 | 0.474814 | planner.go | starcoder |
package Labyrinth
import "github.com/golang/The-Lagorinth/Point"
import "math/rand"
//Global variables used in the project.
//This way it is easy to modify objects in the fly.
var Wall string = "0"
var Pass string = " "
var Treasure string = "$"
var Trap string = "*"
var Monster string = "i"
var CharSymbol string = "c"
var ExitPosition string = "E"
var StartPosition string = "S"
var Projectile string = "o"
var pointMap = map[Point.Point]bool{}
var chanceToBeTreasure int = 25
var chanceToBeTrap int = 10
var chanceToBeNpc int = 15
type Labyrinth struct {
Width, Height int
Labyrinth [40][40]string
}
//CreateLabyrinth call Prim function which handles the creation pf the labyrinth.
//It sets the rand seed.
//It also expands the labyrinth by calling createTreasuresAndTraps function.
//That function determines the location of chests, traps and enemies.
func (lab *Labyrinth) CreateLabyrinth(seed int64) {
rand.Seed(seed)
lab.Prim()
lab.createTreasuresAndTraps()
}
//Prim is the algorithm used to generate the maze.
//refer to package description for more details on Prim's algorithm.
func (lab *Labyrinth) Prim() {
frontier := make([]Point.Point, 0, 40)
var start Point.Point = Point.Point{rand.Intn(lab.Width-1) + 1, rand.Intn(lab.Width-1) + 1, nil}
lab.Labyrinth[start.X][start.Y] = StartPosition
lab.neighbours(&start, &frontier)
for {
randomPoint := rand.Intn(len(frontier))
current := frontier[randomPoint]
frontier = append(frontier[:randomPoint], frontier[randomPoint+1:]...)
opposite := current.Opposite()
last := opposite
if lab.Labyrinth[opposite.X][opposite.Y] == Wall {
lab.Labyrinth[current.X][current.Y] = Pass
if opposite.X != 0 && opposite.X != lab.Width-1 && opposite.Y != 0 && opposite.Y != lab.Height-1 {
lab.Labyrinth[opposite.X][opposite.Y] = Pass
}
lab.neighbours(&opposite, &frontier)
}
if len(frontier) == 0 {
lab.Labyrinth[last.X][last.Y] = "E"
break
}
}
}
//neighbours takes 2 arguments.
//A slice which is passed on to addNeighbour.
//And a point. Function determines all of the point's neighbours and passes their coordinates to addNeighbour.
//Point is passed on to addNeighbour as well to be used as a parent point for its neighbours.
func (lab *Labyrinth) neighbours(point *Point.Point, frontier *[]Point.Point) {
lab.addNeighbour(point.X+1, point.Y, point, frontier)
lab.addNeighbour(point.X-1, point.Y, point, frontier)
lab.addNeighbour(point.X, point.Y+1, point, frontier)
lab.addNeighbour(point.X, point.Y-1, point, frontier)
}
//addNeighbour add a point to frontier slice if the point is not has not been added already.
//Function takes 4 arguments.
//2 coordinates for the point to be added to frontier slice.
//A parent point.
//And the slice itself.
func (lab *Labyrinth) addNeighbour(x int, y int, parent *Point.Point, frontier *[]Point.Point) {
if !pointMap[Point.Point{x, y, parent}] {
if (x > 0 && x < lab.Width-1) && (y > 0 && y < lab.Height-1) {
pointToBeAdd := Point.Point{x, y, parent}
*frontier = append(*frontier, pointToBeAdd)
pointMap[pointToBeAdd] = true
}
}
}
//countWalls counts how many of the neighbours of a point, in the labyrinth, are walls and returns that count.
//Function takes 2 arguments, the coordinates of the point.
func (lab *Labyrinth) countWalls(x int, y int) int {
var wallCount int = 0
if lab.Labyrinth[x+1][y] == Wall {
wallCount++
}
if lab.Labyrinth[x-1][y] == Wall {
wallCount++
}
if lab.Labyrinth[x][y+1] == Wall {
wallCount++
}
if lab.Labyrinth[x][y-1] == Wall {
wallCount++
}
return wallCount
}
//isDeadEnd returns true if a point in the labyrinth has 3 neighbours that are walls
//Function takes 2 arguments, the coordinates of the point.
func (lab *Labyrinth) isDeadEnd(x int, y int) bool {
return lab.countWalls(x, y) == 3
}
//isTreasure return true if a random value is lower than chanceToBeTreasure global variable.
//Function is used for the placement of treasures in the labyrinth.
func (lab *Labyrinth) isTreasure() bool {
return rand.Intn(100) < chanceToBeTreasure
}
//placeNpc places a monster symbol in the labyrinth if a random value is lower than chanceToBeNpc global variable.
//It takes 2 arguments, the coordinates of the point where the symbol will be places.
func (lab *Labyrinth) placeNpc(x int, y int) {
if rand.Intn(100) < chanceToBeNpc {
lab.Labyrinth[x][y] = Monster
}
}
//createTreasuresAndTraps handles the placement of treasures, traps and monsters in the labyrinth.
func (lab *Labyrinth) createTreasuresAndTraps() {
for i := 1; i < lab.Width-1; i++ {
for j := 1; j < lab.Height-1; j++ {
if lab.Labyrinth[i][j] == Pass {
if lab.isDeadEnd(i, j) {
if lab.isTreasure() {
lab.Labyrinth[i][j] = Treasure
} else {
lab.placeNpc(i, j)
}
}
if lab.isCrossRoad(i, j) {
if lab.isTrap() {
lab.Labyrinth[i][j] = Trap
} else {
lab.placeNpc(i, j)
}
}
}
}
}
}
//IsInBondaries determines of the arguments are within the labyrinth.
//Will return false if the arguments are negative or greater than the dimensions of the labyrinth.
func (lab *Labyrinth) IsInBondaries(x int, y int) bool {
return x > -1 && x < lab.Width && y > -1 && y < lab.Height
}
//isCrossRoad returns true if 1 or less of the neighbours of point are walls.
func (lab *Labyrinth) isCrossRoad(x int, y int) bool {
return lab.countWalls(x, y) < 2
}
//isTrap returns true if a random value is lower than the chanceToBeTrap global variable.
func (lab *Labyrinth) isTrap() bool {
return rand.Intn(100) < chanceToBeTrap
} | Labyrinth/labyrinth.go | 0.575111 | 0.495911 | labyrinth.go | starcoder |
package sheetfile
import (
"github.com/fourstring/sheetfs/master/config"
"github.com/fourstring/sheetfs/master/datanode_alloc"
"github.com/fourstring/sheetfs/master/filemgr/file_errors"
"gorm.io/gorm"
"sync"
)
/*
SheetFile
Represents a file containing a sheet.
Every SheetFile is made of lots of Cell. Almost every Cell has
config.MaxBytesPerCell bytes of storage to store its data, and there
is a special one called MetaCell, whose size will be config.BytesPerChunk.
Applications should consider to make use of MetaCell to store data related
to whole sheet. MetaCell can be accessed by (config.SheetMetaCellRow, config.SheetMetaCellCol).
Composed of Cells, SheetFile provides a row/col-oriented API to applications.
Cells is the index of such an API. So Cells must be persistent, so as Chunks storing those
Cells. And as a logical collection of Cells and Chunks, SheetFile should be used as
a helper to persist Cells and Chunks. However, SheetFile itself has not to be kept permanently.
All of its data can be resumed by scanning Cells loaded from database.
Chunks and Cells are maintained in pointers. Sometimes those data will be returned to the
outside world, which implies we can't rely SheetFile.mu on accessing those pointers goroutine-safely.
So all pointers returned will point to a copy, or snapshot of a Chunk or Cell. In other words,
they are a 'goroutine-safe view' of Chunks/Cells at some point.
*/
type SheetFile struct {
mu sync.RWMutex
// All Chunks containing all Cells of the SheetFile.
// Maps ChunkID to *Chunk.
Chunks map[uint64]*Chunk
// All Cells in the sheet.
// Maps CellID to *Cell.
Cells map[int64]*Cell
// Keeps track of latest Chunk whose remaining space is capable of storing a new Cell.
LastAvailableChunk *Chunk
filename string
alloc *datanode_alloc.DataNodeAllocator
}
/*
CreateSheetFile
Create a SheetFile, corresponding sqlite table to store Cells of the SheetFile, MetaCell
and chunk used to store it.
Theoretically, it's not required to flush the metadata of a new file to disk immediately.
However, we make use of sqlite as some kind of alternative to general BTree. So we create
the table here as a workaround.
@para
db: a gorm connection. It should not be a transaction.(See CreateCellTableIfNotExists)
filename: filename of new SheetFile
@return
*SheetFile: pointer of new SheetFile if success, or nil.
error:
some error happens while creating cell table.
*errors.NoDataNodeError: This function must allocate a Chunk for MetaCell, if there
are no DataNodes for storing this cell, returns NoDateNodeError.
*/
func CreateSheetFile(db *gorm.DB, alloc *datanode_alloc.DataNodeAllocator, filename string) (*SheetFile, *Cell, *Chunk, error) {
f := &SheetFile{
Chunks: map[uint64]*Chunk{},
Cells: map[int64]*Cell{},
LastAvailableChunk: nil,
filename: filename,
alloc: alloc,
}
err := f.persistentStructure(db)
if err != nil {
return nil, nil, nil, err
}
dataNode, err := alloc.AllocateNode()
if err != nil {
return nil, nil, nil, err
}
// Create Chunk and MetaCell
chunk := &Chunk{DataNode: dataNode, Version: 0}
chunk.Persistent(db)
metaCell := NewCell(config.SheetMetaCellID, 0, config.BytesPerChunk, chunk.ID, filename)
chunk.Cells = []*Cell{metaCell}
// Add MetaCell and Chunk to new file
f.Chunks[chunk.ID] = chunk
f.Cells[metaCell.CellID] = metaCell
return f, metaCell, chunk, nil
}
/*
LoadSheetFile
Load a SheetFile from database. As mentioned above, SheetFile has not to be persisted.
In fact, this function loads all Cells of given filename from database. Afterwards,
this function scans over those cells, adding them to SheetFile.Cells, and their Chunk to
SheetFile.Chunks. Besides, this function also set SheetFile.LastAvailableChunk to the
first Chunk whose isAvailable() is true.
This method should only be used to load checkpoints in sqlite. (See GetSheetCellsAll)
@para
db: a gorm connection. It can be a transaction.
filename: The validity of filename won't be checked. Caller should guarantee that
a valid filename is passed in.
@return
*SheetFile: pointer of loaded SheetFile.
*/
func LoadSheetFile(db *gorm.DB, alloc *datanode_alloc.DataNodeAllocator, filename string) *SheetFile {
cells := GetSheetCellsAll(db, filename)
file := &SheetFile{
Chunks: map[uint64]*Chunk{},
Cells: map[int64]*Cell{},
filename: filename,
alloc: alloc,
}
for _, cell := range cells {
// SheetName is ignored by gorm, not persist to sqlite
// However it's necessary to persist cell later
cell.SheetName = filename
file.Cells[cell.CellID] = cell
_, ok := file.Chunks[cell.ChunkID]
// config.MaxCellsPerChunk cells will be stored in the same Chunk at most.
// So Chunk of a Cell may have been added to file.Chunks.
// To avoid expensive database operations, we first check whether cell.ChunkID
// has been loaded or not.
if !ok {
dataChunk := loadChunkForFile(db, filename, cell.ChunkID)
file.Chunks[cell.ChunkID] = dataChunk
// SheetFile.WriteCellChunk guarantees that it always fulfill currently
// available Chunk before allocating a new one. So the first Chunk whose
// isAvailable() should be the LastAvailableChunk.
if file.LastAvailableChunk == nil && dataChunk.isAvailable(config.MaxBytesPerCell) {
file.LastAvailableChunk = dataChunk
}
}
}
return file
}
/*
GetAllChunks
Returns the Snapshot of all Chunks.
@return
[]*Chunk: slice of pointers pointing to snapshots of s.Chunks.
*/
func (s *SheetFile) GetAllChunks() []*Chunk {
s.mu.RLock()
defer s.mu.RUnlock()
chunks := make([]*Chunk, len(s.Chunks))
i := 0
for _, c := range s.Chunks {
chunks[i] = c.Snapshot()
i++
}
return chunks
}
/*
GetCellChunk
Lookup Cell located at (row, col) and its Chunk.
@para
row: row number of Cell
col: column number of Cell
@return
*Cell, *Chunk: corresponding snapshots if no error
error:
*errors.CellNotFoundError if row, col passed in is invalid.
*/
func (s *SheetFile) GetCellChunk(row, col uint32) (*Cell, *Chunk, error) {
s.mu.RLock()
defer s.mu.RUnlock()
// Compute CellID by row, col and lookup cell by CellID.
cell := s.Cells[GetCellID(row, col)]
if cell == nil {
return nil, nil, file_errors.NewCellNotFoundError(row, col)
}
return cell.Snapshot(), s.Chunks[cell.ChunkID].Snapshot(), nil
}
/*
getCellOffset
Compute the offset of a cell which will be added to an available Chunk.
Every Chunk has config.MaxCellsPerChunk slots, each slot occupies
config.MaxBytesPerCell bytes, for storing a single Cell.
So the offset is the 0-indexed index of the new Cell in the Chunk times
config.MaxBytesPerCell.
*/
func (s *SheetFile) getCellOffset(chunk *Chunk) uint64 {
return (uint64(len(chunk.Cells))) * config.MaxBytesPerCell
}
/*
addCellToLastAvailable
Add a new cell with given maximum size located at (row,col) to s.LastAvailableChunk.
@para
row: row number
col: column number
size: maximum size of new Cell
@return
*Cell: pointer of new Cell
*/
func (s *SheetFile) addCellToLastAvailable(row, col uint32, size uint64) *Cell {
cell := NewCell(GetCellID(row, col), s.getCellOffset(s.LastAvailableChunk),
size, s.LastAvailableChunk.ID, s.filename)
s.Cells[cell.CellID] = cell
// Add new cell to cells of chunk
s.LastAvailableChunk.Cells = append(s.LastAvailableChunk.Cells, cell)
// Increase Version of LastAvailableChunk because new Cell is added.
s.LastAvailableChunk.Version += 1
return cell
}
/*
WriteCellChunk
Performs necessary metadata mutations to handle an operation of writing data to a Cell.
@para
row, col: row number, column number of Cell to write
tx: a gorm connection, can be a transaction
@return
*Cell, *Chunk: snapshots of the Cell and its Chunk to be written.
error:
*errors.NoDataNodeError if there is no DataNode registered.
*/
func (s *SheetFile) WriteCellChunk(row, col uint32, tx *gorm.DB) (*Cell, *Chunk, error) {
s.mu.Lock()
defer s.mu.Unlock()
cell := s.Cells[GetCellID(row, col)]
// Lookup an existing Cell by CellID first
if cell != nil {
// For existing Cell, just increase its Chunk version
dataChunk := s.Chunks[cell.ChunkID]
dataChunk.Version += 1
return cell.Snapshot(), dataChunk.Snapshot(), nil
} else {
// Generally, the size of the new Cell is config.MaxBytesPerCell. However, for
// the MetaCell defined by (config.SheetMetaCellRow,config.SheetMetaCellCol),
// a whole chunk should be granted to store metadata of a sheet.
newCellSize := config.MaxBytesPerCell
if row == config.SheetMetaCellRow && col == config.SheetMetaCellCol {
newCellSize = config.BytesPerChunk
}
// For a new Cell, tries to add it to s.LastAvailableChunk
if s.LastAvailableChunk != nil && s.LastAvailableChunk.isAvailable(newCellSize) {
// There is a empty slot for the new Cell, add it to s.LastAvailableChunk
cell = s.addCellToLastAvailable(row, col, newCellSize)
return cell.Snapshot(), s.LastAvailableChunk.Snapshot(), nil
} else {
// s.LastAvailableChunk has been fulfilled, allocate a new Chunk, and
// makes it s.LastAvailableChunk.
datanode, err := s.alloc.AllocateNode()
if err != nil {
// If there is no DataNode, *errors.NoDataNodeError will be returned.
return nil, nil, err
}
newChunk := &Chunk{
DataNode: datanode,
Version: 0,
Cells: []*Cell{},
}
// newChunk.ID is allocated by sqlite(autoIncrement). So it's required to persist
// newChunk here to get newChunk.ID.
newChunk.Persistent(tx)
// Add the newChunk to Chunks collection of s.
s.Chunks[newChunk.ID] = newChunk
// Let newChunk to be s.LastAvailableChunk
s.LastAvailableChunk = newChunk
// Re-use logic of addCellToLastAvailable
cell = s.addCellToLastAvailable(row, col, newCellSize)
return cell.Snapshot(), newChunk.Snapshot(), nil
}
}
}
/*
Persistent
Flush the Cell and Chunk data stored in a SheetFile to sqlite.
@para
db: a gorm connection. It's supposed to be a transaction.
@return
error: always nil currently. But potentially errors may be introduced
in the future.
*/
func (s *SheetFile) Persistent(tx *gorm.DB) error {
err := tx.Transaction(s.persistentData)
if err != nil {
return err
}
return nil
}
/*
persistentStructure
Creates the table required to store Cells of a SheetFile.
This method should only be called once when a SheetFile is created.
@para
db: a gorm connection. Creating a table in a sqlite transaction is
not allowed, so it can't be a transaction.
@return
error: errors during creation of the Cell table.
*/
func (s *SheetFile) persistentStructure(db *gorm.DB) error {
err := CreateCellTableIfNotExists(db, s.filename)
if err != nil {
return err
}
return nil
}
/*
persistentData
Flush the Cell and Chunk data stored in a SheetFile to sqlite.
@para
db: a gorm connection. It is supposed to be a transaction.
@return
error: always nil currently. But potentially errors may be introduced
in the future.
*/
func (s *SheetFile) persistentData(tx *gorm.DB) error {
if len(s.Cells) == 0 {
return nil
}
for _, cell := range s.Cells {
cell.Persistent(tx)
}
for _, dataChunk := range s.Chunks {
dataChunk.Persistent(tx)
}
return nil
} | master/sheetfile/sheetfile.go | 0.520253 | 0.496582 | sheetfile.go | starcoder |
package text
// line_scanner.go contains code that finds lines within text.
import (
"strings"
"text/scanner"
"github.com/mum4k/termdash/internal/runewidth"
)
// wrapNeeded returns true if wrapping is needed for the rune at the horizontal
// position on the canvas.
func wrapNeeded(r rune, cvsPosX, cvsWidth int, opts *options) bool {
if r == '\n' {
// Don't wrap for newline characters as they aren't printed on the
// canvas, i.e. they take no horizontal space.
return false
}
rw := runewidth.RuneWidth(r)
return cvsPosX > cvsWidth-rw && opts.wrapAtRunes
}
// findLines finds the starting positions of all lines in the text when the
// text is drawn on a canvas of the provided width with the specified options.
func findLines(text string, cvsWidth int, opts *options) []int {
if cvsWidth <= 0 || text == "" {
return nil
}
ls := newLineScanner(text, cvsWidth, opts)
for state := scanStart; state != nil; state = state(ls) {
}
return ls.lines
}
// lineScanner tracks the progress of scanning the input text when finding
// lines. Lines are identified when newline characters are encountered in the
// input text or when the canvas width and configuration requires line
// wrapping.
type lineScanner struct {
// scanner lexes the input text.
scanner *scanner.Scanner
// cvsWidth is the width of the canvas the text will be drawn on.
cvsWidth int
// cvsPosX tracks the horizontal position of the current character on the
// canvas.
cvsPosX int
// opts are the widget options.
opts *options
// lines are the starting points of the identified lines.
lines []int
}
// newLineScanner returns a new line scanner of the provided text.
func newLineScanner(text string, cvsWidth int, opts *options) *lineScanner {
var s scanner.Scanner
s.Init(strings.NewReader(text))
s.Whitespace = 0 // Don't ignore any whitespace.
s.Mode = scanner.ScanIdents
s.IsIdentRune = func(ch rune, i int) bool {
return i == 0 && ch == '\n'
}
return &lineScanner{
scanner: &s,
cvsWidth: cvsWidth,
opts: opts,
}
}
// scannerState is a state in the FSM that scans the input text and identifies
// newlines.
type scannerState func(*lineScanner) scannerState
// scanStart records the starting location of the current line.
func scanStart(ls *lineScanner) scannerState {
switch tok := ls.scanner.Peek(); {
case tok == scanner.EOF:
return nil
default:
ls.lines = append(ls.lines, ls.scanner.Position.Offset)
return scanLine
}
}
// scanLine scans a line until it finds its end.
func scanLine(ls *lineScanner) scannerState {
for {
switch tok := ls.scanner.Scan(); {
case tok == scanner.EOF:
return nil
case tok == scanner.Ident:
return scanLineBreak
case wrapNeeded(tok, ls.cvsPosX, ls.cvsWidth, ls.opts):
return scanLineWrap
default:
// Move horizontally within the line for each scanned character.
ls.cvsPosX += runewidth.RuneWidth(tok)
}
}
}
// scanLineBreak processes a newline character in the input text.
func scanLineBreak(ls *lineScanner) scannerState {
// Newline characters aren't printed, the following character starts the line.
if ls.scanner.Peek() != scanner.EOF {
ls.cvsPosX = 0
ls.lines = append(ls.lines, ls.scanner.Position.Offset+1)
}
return scanLine
}
// scanLineWrap processes a line wrap due to canvas width.
func scanLineWrap(ls *lineScanner) scannerState {
// The character on which we wrapped will be printed and is the start of
// new line.
ls.cvsPosX = runewidth.StringWidth(ls.scanner.TokenText())
ls.lines = append(ls.lines, ls.scanner.Position.Offset)
return scanLine
} | vendor/github.com/mum4k/termdash/widgets/text/line_scanner.go | 0.641198 | 0.425665 | line_scanner.go | starcoder |
package bdd
import (
"fmt"
"time"
"github.com/onsi/gomega/format"
)
// IsSameTimeAs succeeds if actual is the same time or later
// than the passed-in time.
var IsSameTimeAs = &matcher{
minArgs: 1,
maxArgs: 1,
name: "IsSameTimeAs",
apply: func(actual interface{}, expected []interface{}) Result {
t1, ok := actual.(time.Time)
if !ok {
err := fmt.Errorf("expected a time.Time, got: \n %s", format.Object(actual, 1))
return Result{Error: err}
}
t2, ok := expected[0].(time.Time)
if !ok {
err := fmt.Errorf("expected a time.Time, got: \n %s", format.Object(expected[0], 1))
return Result{Error: err}
}
var r Result
if t1.Equal(t2) {
r.Success = true
} else {
r.FailureMessage = timeMismatch(t1, " to be same time as ", t2)
r.NegatedFailureMessage = timeMismatch(t1, " not to be same time as ", t2)
}
return r
},
}
// IsBefore succeeds if actual is earlier than the passed-in time.
var IsBefore = &matcher{
minArgs: 1,
maxArgs: 1,
name: "IsBefore",
apply: func(actual interface{}, expected []interface{}) Result {
before, ok := actual.(time.Time)
if !ok {
err := fmt.Errorf("expected a time.Time, got: \n %s", format.Object(actual, 1))
return Result{Error: err}
}
after, ok := expected[0].(time.Time)
if !ok {
err := fmt.Errorf("expected a time.Time, got: \n %s", format.Object(expected[0], 1))
return Result{Error: err}
}
var r Result
if before.Before(after) {
r.Success = true
} else {
r.FailureMessage = timeMismatch(before, " to be before ", after)
r.NegatedFailureMessage = timeMismatch(before, " not to be before ", after)
}
return r
},
}
// IsAfter succeeds if actual is later than the passed-in time.
var IsAfter = &matcher{
minArgs: 1,
maxArgs: 1,
name: "IsAfter",
apply: func(actual interface{}, expected []interface{}) Result {
after, ok := actual.(time.Time)
if !ok {
err := fmt.Errorf("expected a time.Time, got: \n %s", format.Object(actual, 1))
return Result{Error: err}
}
before, ok := expected[0].(time.Time)
if !ok {
err := fmt.Errorf("expected a time.Time, got: \n %s", format.Object(expected[0], 1))
return Result{Error: err}
}
var r Result
if after.After(before) {
r.Success = true
} else {
r.FailureMessage = timeMismatch(after, " to be after ", before)
r.NegatedFailureMessage = timeMismatch(after, " not to be after ", before)
}
return r
},
}
// IsOnOrBefore succeeds if actual is the same time or earlier
// than the passed-in time.
var IsOnOrBefore = &matcher{
minArgs: 1,
maxArgs: 1,
name: "IsOnOrBefore",
apply: func(actual interface{}, expected []interface{}) Result {
before, ok := actual.(time.Time)
if !ok {
err := fmt.Errorf("expected a time.Time, got: \n %s", format.Object(actual, 1))
return Result{Error: err}
}
after, ok := expected[0].(time.Time)
if !ok {
err := fmt.Errorf("expected a time.Time, got: \n %s", format.Object(expected[0], 1))
return Result{Error: err}
}
var r Result
if before.Before(after) || before.Equal(after) {
r.Success = true
} else {
r.FailureMessage = timeMismatch(before, " to be before or same time as ", after)
r.NegatedFailureMessage = timeMismatch(before, " to be after ", after)
}
return r
},
}
// IsOnOrAfter succeeds if actual is the same time or later
// than the passed-in time.
var IsOnOrAfter = &matcher{
minArgs: 1,
maxArgs: 1,
name: "IsOnOrAfter",
apply: func(actual interface{}, expected []interface{}) Result {
after, ok := actual.(time.Time)
if !ok {
err := fmt.Errorf("expected a time.Time, got: \n %s", format.Object(actual, 1))
return Result{Error: err}
}
before, ok := expected[0].(time.Time)
if !ok {
err := fmt.Errorf("expected a time.Time, got: \n %s", format.Object(expected[0], 1))
return Result{Error: err}
}
var r Result
if after.After(before) || after.Equal(before) {
r.Success = true
} else {
r.FailureMessage = timeMismatch(after, " to be after or same time as ", before)
r.NegatedFailureMessage = timeMismatch(after, " to be before ", before)
}
return r
},
}
func timeMismatch(t1 time.Time, message string, t2 time.Time) string {
strT1, strT2 := formatTime(t1), formatTime(t2)
return fmt.Sprintf("Expected\n%s\n%s\n%s", strT1, message, strT2)
}
func formatTime(t time.Time) string {
return format.Indent + t.String()
} | matcher_time.go | 0.551815 | 0.541045 | matcher_time.go | starcoder |
Package rollout defines a protocol for automating the gradual rollout of changes
throughout a VitessCluster by splitting rolling update logic into
composable pieces: deciding what changes to make, deciding when and in what
order to apply changes, and then actually applying the changes.
Controllers like VitessShard decide what to change (e.g. new Pod image or args)
based on user input, but rather than applying changes immediately, they merely
annotate objects as having changes pending.
A RolloutPolicy then determines which changes to apply next, based on the user's
configuration, and annotates the objects that are next in line to be updated.
Finally, the Reconciler automatically applies any pending changes that have been
"released" by the RolloutPolicy.
This decomposition makes each piece easier to write correctly, makes the overall
process easier to reason about abstractly, and enables code reuse across
distributed components while maintaining loose coupling to allow composition in
new and unexpected ways without changing the code.
*/
package rollout
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
// AnnotationPrefix is the prefix for annotation keys that are used for
// coordinating drains through this package.
AnnotationPrefix = "rollout.planetscale.com"
// ScheduledAnnotation is the annotation whose presence indicates that the
// object's controller would like to apply pending changes to the object.
ScheduledAnnotation = AnnotationPrefix + "/" + "scheduled"
// ReleasedAnnotation is the annotation whose presence indicates that the
// object's controller may now apply any pending changes to the object.
ReleasedAnnotation = AnnotationPrefix + "/" + "released"
// CascadeAnnotation is the annotation whose presence indicates that the
// object's controller should now release any scheduled changes to its children.
// The controller will remove the annotation when all children are updated.
CascadeAnnotation = AnnotationPrefix + "/" + "cascade"
)
// Scheduled returns whether the object has pending changes.
func Scheduled(obj metav1.Object) bool {
ann := obj.GetAnnotations()
// We only care that the annotation key is present.
// An empty annotation value still indicates changes are pending.
_, present := ann[ScheduledAnnotation]
return present
}
// Released returns whether it's ok to apply changes to the object.
func Released(obj metav1.Object) bool {
ann := obj.GetAnnotations()
// We only care that the annotation key is present.
// An empty annotation value still triggers a drain.
_, present := ann[ReleasedAnnotation]
return present
}
// Cascading returns whether scheduled changes are being applied to an object's children.
func Cascading(obj metav1.Object) bool {
ann := obj.GetAnnotations()
// We only care that the annotation key is present.
// An empty annotation value still indicates that cascading
// changes will be propagated to the object's children.
_, present := ann[CascadeAnnotation]
return present
}
/*
Schedule annotates an object as having pending updates.
If updates are already scheduled, the message will be updated.
Note that this only mutates the provided, in-memory object to add the
annotation; the caller is responsible for sending the updated object to
the server.
'message' is an optional, human-readable description of the pending changes.
*/
func Schedule(obj metav1.Object, message string) {
ann := obj.GetAnnotations()
if ann == nil {
ann = make(map[string]string, 1)
}
ann[ScheduledAnnotation] = message
obj.SetAnnotations(ann)
}
/*
Unschedule removes the "pending" annotation added by Schedule,
as well as the "released" annotation added by Release.
If the object does not have either annotation, this has no effect.
Note that this only mutates the provided, in-memory object to add the
annotation; the caller is responsible for sending the updated object to
the server.
*/
func Unschedule(obj metav1.Object) {
ann := obj.GetAnnotations()
delete(ann, ScheduledAnnotation)
delete(ann, ReleasedAnnotation)
obj.SetAnnotations(ann)
}
/*
Release annotates an object as being ready to have changes applied.
If the object has already been marked as released, this has no effect.
Note that this only mutates the provided, in-memory object to add the
annotation; the caller is responsible for sending the updated object to
the server.
*/
func Release(obj metav1.Object) {
ann := obj.GetAnnotations()
if _, present := ann[ReleasedAnnotation]; present {
// The object has already been released.
return
}
if ann == nil {
ann = make(map[string]string, 1)
}
ann[ReleasedAnnotation] = ""
obj.SetAnnotations(ann)
}
/*
Unrelease removes the "released" annotation added by Release.
If the object does not have the annotation, this has no effect.
Note that this only mutates the provided, in-memory object to add the
annotation; the caller is responsible for sending the updated object to
the server.
*/
func Unrelease(obj metav1.Object) {
ann := obj.GetAnnotations()
delete(ann, ReleasedAnnotation)
obj.SetAnnotations(ann)
}
/*
Cascade annotates an object to tell its controller to release
any scheduled changes to its children.
If the object has already been marked as cascading, this has no effect.
Note that this only mutates the provided, in-memory object to add the
annotation; the caller is responsible for sending the updated object to
the server.
*/
func Cascade(obj metav1.Object) {
ann := obj.GetAnnotations()
if _, present := ann[CascadeAnnotation]; present {
// The object has already been marked as cascading.
return
}
if ann == nil {
ann = make(map[string]string, 1)
}
ann[CascadeAnnotation] = ""
obj.SetAnnotations(ann)
}
/*
Uncascade removes the "cascade" annotation added by Cascade.
If the object does not have the annotation, this has no effect.
Note that this only mutates the provided, in-memory object to add the
annotation; the caller is responsible for sending the updated object to
the server.
*/
func Uncascade(obj metav1.Object) {
ann := obj.GetAnnotations()
delete(ann, CascadeAnnotation)
obj.SetAnnotations(ann)
} | pkg/operator/rollout/rollout.go | 0.823825 | 0.403449 | rollout.go | starcoder |
The Shunting Yard algorithm is stack based.
For the conversion there are two strings the input and the output.
The stack is used to hold the operators not yet added to the output queue eg. +, -, ×
The algorithm then does something depending on what operator is read in eg. "3 + 4" --> "3 4 +"
For the full algorithm in detail follow https://en.wikipedia.org/wiki/Shunting-yard_algorithm#The_algorithm_in_detail
*/
package shunt
// IntToPost converts an infix regular expression to a postfix regular expression
// and returns the resulting string to be later sent to a post fix stack evaluator
func IntToPost(infix string) string {
// Map to store all the special characters and their precedences
// Found regex operator precedence here https://stackoverflow.com/questions/36870168/operator-precedence-in-regular-expressions
specials := map[rune]int{
'*': 10,
'.': 9,
'+': 8,
'?': 7,
'|': 6,
}
// Array of runes to hold the postfix regular expression
// and the stack for the infix operators
pofix, stack := []rune{}, []rune{}
// Loop over infix, throw the index of the char with the blank identifier as it's unneeded
// r is the rune at the index
for _, r := range infix {
switch {
// If the token is a closing bracket, push it onto the operator stack
case r == '(':
stack = append(stack, r)
// If the token is a right bracket, pop the closing bracket from the stack
// If the token on top of the operator stack is not a closing bracket pop it onto the output queue
case r == ')':
for stack[len(stack)-1] != '(' {
pofix = append(pofix, stack[len(stack)-1])
stack = stack[:len(stack)-1] // Everything on the stack up to the closing bracket (the last character)
}
stack = stack[:len(stack)-1] // Pop the closing bracket off the stack
// If the rune is a special character
// '> 0' is used because accessing a key not contained in a map returns 0
case specials[r] > 0:
for len(stack) > 0 && specials[r] <= specials[stack[len(stack)-1]] {
// Pop operators from the operator stack onto the output queue
pofix = append(pofix, stack[len(stack)-1])
stack = stack[:len(stack)-1]
}
stack = append(stack, r)
// If the rune is not a bracket or a special character
default:
pofix = append(pofix, r)
}
}
for len(stack) > 0 {
// Pop element off of stack and onto the output queue
pofix = append(pofix, stack[len(stack)-1])
stack = stack[:len(stack)-1]
}
return string(pofix)
} | shunt/shunt.go | 0.738575 | 0.723334 | shunt.go | starcoder |
package drawing
// NewLineStroker creates a new line stroker.
func NewLineStroker(c LineCap, j LineJoin, flattener Flattener) *LineStroker {
l := new(LineStroker)
l.Flattener = flattener
l.HalfLineWidth = 0.5
l.Cap = c
l.Join = j
return l
}
// LineStroker draws the stroke portion of a line.
type LineStroker struct {
Flattener Flattener
HalfLineWidth float64
Cap LineCap
Join LineJoin
vertices []float64
rewind []float64
x, y, nx, ny float64
}
// MoveTo implements the path builder interface.
func (l *LineStroker) MoveTo(x, y float64) {
l.x, l.y = x, y
}
// LineTo implements the path builder interface.
func (l *LineStroker) LineTo(x, y float64) {
l.line(l.x, l.y, x, y)
}
// LineJoin implements the path builder interface.
func (l *LineStroker) LineJoin() {}
func (l *LineStroker) line(x1, y1, x2, y2 float64) {
dx := (x2 - x1)
dy := (y2 - y1)
if d := vectorDistance(dx, dy); d != 0 {
nx := dy * l.HalfLineWidth / d
ny := -(dx * l.HalfLineWidth / d)
l.appendVertex(x1+nx, y1+ny, x2+nx, y2+ny, x1-nx, y1-ny, x2-nx, y2-ny)
l.x, l.y, l.nx, l.ny = x2, y2, nx, ny
}
}
// Close implements the path builder interface.
func (l *LineStroker) Close() {
if len(l.vertices) > 1 {
l.appendVertex(l.vertices[0], l.vertices[1], l.rewind[0], l.rewind[1])
}
}
// End implements the path builder interface.
func (l *LineStroker) End() {
if len(l.vertices) > 1 {
l.Flattener.MoveTo(l.vertices[0], l.vertices[1])
for i, j := 2, 3; j < len(l.vertices); i, j = i+2, j+2 {
l.Flattener.LineTo(l.vertices[i], l.vertices[j])
}
}
for i, j := len(l.rewind)-2, len(l.rewind)-1; j > 0; i, j = i-2, j-2 {
l.Flattener.LineTo(l.rewind[i], l.rewind[j])
}
if len(l.vertices) > 1 {
l.Flattener.LineTo(l.vertices[0], l.vertices[1])
}
l.Flattener.End()
// reinit vertices
l.vertices = l.vertices[0:0]
l.rewind = l.rewind[0:0]
l.x, l.y, l.nx, l.ny = 0, 0, 0, 0
}
func (l *LineStroker) appendVertex(vertices ...float64) {
s := len(vertices) / 2
l.vertices = append(l.vertices, vertices[:s]...)
l.rewind = append(l.rewind, vertices[s:]...)
} | drawing/stroker.go | 0.765111 | 0.407098 | stroker.go | starcoder |
package plaid
import (
"encoding/json"
)
// HistoricalBalance An object representing a balance held by an account in the past
type HistoricalBalance struct {
// The date of the calculated historical balance, in an [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (YYYY-MM-DD)
Date string `json:"date"`
// The total amount of funds in the account, calculated from the `current` balance in the `balance` object by subtracting inflows and adding back outflows according to the posted date of each transaction. If the account has any pending transactions, historical balance amounts on or after the date of the earliest pending transaction may differ if retrieved in subsequent Asset Reports as a result of those pending transactions posting.
Current float32 `json:"current"`
// The ISO-4217 currency code of the balance. Always `null` if `unofficial_currency_code` is non-`null`.
IsoCurrencyCode NullableString `json:"iso_currency_code"`
// The unofficial currency code associated with the balance. Always `null` if `iso_currency_code` is non-`null`. See the [currency code schema](https://plaid.com/docs/api/accounts#currency-code-schema) for a full listing of supported `iso_currency_code`s.
UnofficialCurrencyCode NullableString `json:"unofficial_currency_code"`
AdditionalProperties map[string]interface{}
}
type _HistoricalBalance HistoricalBalance
// NewHistoricalBalance instantiates a new HistoricalBalance 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 NewHistoricalBalance(date string, current float32, isoCurrencyCode NullableString, unofficialCurrencyCode NullableString) *HistoricalBalance {
this := HistoricalBalance{}
this.Date = date
this.Current = current
this.IsoCurrencyCode = isoCurrencyCode
this.UnofficialCurrencyCode = unofficialCurrencyCode
return &this
}
// NewHistoricalBalanceWithDefaults instantiates a new HistoricalBalance 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 NewHistoricalBalanceWithDefaults() *HistoricalBalance {
this := HistoricalBalance{}
return &this
}
// GetDate returns the Date field value
func (o *HistoricalBalance) GetDate() string {
if o == nil {
var ret string
return ret
}
return o.Date
}
// GetDateOk returns a tuple with the Date field value
// and a boolean to check if the value has been set.
func (o *HistoricalBalance) GetDateOk() (*string, bool) {
if o == nil {
return nil, false
}
return &o.Date, true
}
// SetDate sets field value
func (o *HistoricalBalance) SetDate(v string) {
o.Date = v
}
// GetCurrent returns the Current field value
func (o *HistoricalBalance) GetCurrent() float32 {
if o == nil {
var ret float32
return ret
}
return o.Current
}
// GetCurrentOk returns a tuple with the Current field value
// and a boolean to check if the value has been set.
func (o *HistoricalBalance) GetCurrentOk() (*float32, bool) {
if o == nil {
return nil, false
}
return &o.Current, true
}
// SetCurrent sets field value
func (o *HistoricalBalance) SetCurrent(v float32) {
o.Current = v
}
// GetIsoCurrencyCode returns the IsoCurrencyCode field value
// If the value is explicit nil, the zero value for string will be returned
func (o *HistoricalBalance) GetIsoCurrencyCode() string {
if o == nil || o.IsoCurrencyCode.Get() == nil {
var ret string
return ret
}
return *o.IsoCurrencyCode.Get()
}
// GetIsoCurrencyCodeOk returns a tuple with the IsoCurrencyCode field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *HistoricalBalance) GetIsoCurrencyCodeOk() (*string, bool) {
if o == nil {
return nil, false
}
return o.IsoCurrencyCode.Get(), o.IsoCurrencyCode.IsSet()
}
// SetIsoCurrencyCode sets field value
func (o *HistoricalBalance) SetIsoCurrencyCode(v string) {
o.IsoCurrencyCode.Set(&v)
}
// GetUnofficialCurrencyCode returns the UnofficialCurrencyCode field value
// If the value is explicit nil, the zero value for string will be returned
func (o *HistoricalBalance) GetUnofficialCurrencyCode() string {
if o == nil || o.UnofficialCurrencyCode.Get() == nil {
var ret string
return ret
}
return *o.UnofficialCurrencyCode.Get()
}
// GetUnofficialCurrencyCodeOk returns a tuple with the UnofficialCurrencyCode field value
// and a boolean to check if the value has been set.
// NOTE: If the value is an explicit nil, `nil, true` will be returned
func (o *HistoricalBalance) GetUnofficialCurrencyCodeOk() (*string, bool) {
if o == nil {
return nil, false
}
return o.UnofficialCurrencyCode.Get(), o.UnofficialCurrencyCode.IsSet()
}
// SetUnofficialCurrencyCode sets field value
func (o *HistoricalBalance) SetUnofficialCurrencyCode(v string) {
o.UnofficialCurrencyCode.Set(&v)
}
func (o HistoricalBalance) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if true {
toSerialize["date"] = o.Date
}
if true {
toSerialize["current"] = o.Current
}
if true {
toSerialize["iso_currency_code"] = o.IsoCurrencyCode.Get()
}
if true {
toSerialize["unofficial_currency_code"] = o.UnofficialCurrencyCode.Get()
}
for key, value := range o.AdditionalProperties {
toSerialize[key] = value
}
return json.Marshal(toSerialize)
}
func (o *HistoricalBalance) UnmarshalJSON(bytes []byte) (err error) {
varHistoricalBalance := _HistoricalBalance{}
if err = json.Unmarshal(bytes, &varHistoricalBalance); err == nil {
*o = HistoricalBalance(varHistoricalBalance)
}
additionalProperties := make(map[string]interface{})
if err = json.Unmarshal(bytes, &additionalProperties); err == nil {
delete(additionalProperties, "date")
delete(additionalProperties, "current")
delete(additionalProperties, "iso_currency_code")
delete(additionalProperties, "unofficial_currency_code")
o.AdditionalProperties = additionalProperties
}
return err
}
type NullableHistoricalBalance struct {
value *HistoricalBalance
isSet bool
}
func (v NullableHistoricalBalance) Get() *HistoricalBalance {
return v.value
}
func (v *NullableHistoricalBalance) Set(val *HistoricalBalance) {
v.value = val
v.isSet = true
}
func (v NullableHistoricalBalance) IsSet() bool {
return v.isSet
}
func (v *NullableHistoricalBalance) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableHistoricalBalance(val *HistoricalBalance) *NullableHistoricalBalance {
return &NullableHistoricalBalance{value: val, isSet: true}
}
func (v NullableHistoricalBalance) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableHistoricalBalance) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | plaid/model_historical_balance.go | 0.855881 | 0.586641 | model_historical_balance.go | starcoder |
package input
import (
"github.com/Jeffail/benthos/v3/internal/docs"
"github.com/Jeffail/benthos/v3/lib/input/reader"
"github.com/Jeffail/benthos/v3/lib/log"
"github.com/Jeffail/benthos/v3/lib/message/batch"
"github.com/Jeffail/benthos/v3/lib/metrics"
"github.com/Jeffail/benthos/v3/lib/types"
"github.com/Jeffail/benthos/v3/lib/util/kafka/sasl"
"github.com/Jeffail/benthos/v3/lib/util/tls"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeKafkaBalanced] = TypeSpec{
constructor: fromBatchAwareConstructor(newKafkaBalancedHasBatchProcessor),
Status: docs.StatusDeprecated,
Summary: `
Connects to Kafka brokers and consumes topics by automatically sharing
partitions across other consumers of the same consumer group.`,
Description: `
Offsets are managed within Kafka as per the consumer group (set via config), and
partitions are automatically balanced across any members of the consumer group.
Partitions consumed by this input can be processed in parallel allowing it to
utilise <= N pipeline processing threads and parallel outputs where N is the
number of partitions allocated to this consumer.
The ` + "`batching`" + ` fields allow you to configure a
[batching policy](/docs/configuration/batching#batch-policy) which will be
applied per partition. Any other batching mechanism will stall with this input
due its sequential transaction model.
## Alternatives
The functionality of this input is now covered by the general ` + "[`kafka` input](/docs/components/inputs/kafka)" + `.
### Metadata
This input adds the following metadata fields to each message:
` + "``` text" + `
- kafka_key
- kafka_topic
- kafka_partition
- kafka_offset
- kafka_lag
- kafka_timestamp_unix
- All existing message headers (version 0.11+)
` + "```" + `
The field ` + "`kafka_lag`" + ` is the calculated difference between the high
water mark offset of the partition at the time of ingestion and the current
message offset.
You can access these metadata fields using
[function interpolation](/docs/configuration/interpolation#metadata).`,
FieldSpecs: docs.FieldSpecs{
docs.FieldDeprecated("max_batch_count"),
docs.FieldCommon("addresses", "A list of broker addresses to connect to. If an item of the list contains commas it will be expanded into multiple addresses.", []string{"localhost:9092"}, []string{"localhost:9041,localhost:9042"}, []string{"localhost:9041", "localhost:9042"}).Array(),
tls.FieldSpec(),
sasl.FieldSpec(),
docs.FieldCommon("topics", "A list of topics to consume from. If an item of the list contains commas it will be expanded into multiple topics.").Array(),
docs.FieldCommon("client_id", "An identifier for the client connection."),
docs.FieldAdvanced("rack_id", "A rack identifier for this client."),
docs.FieldCommon("consumer_group", "An identifier for the consumer group of the connection."),
docs.FieldAdvanced("start_from_oldest", "If an offset is not found for a topic partition, determines whether to consume from the oldest available offset, otherwise messages are consumed from the latest offset."),
docs.FieldAdvanced("commit_period", "The period of time between each commit of the current partition offsets. Offsets are always committed during shutdown."),
docs.FieldAdvanced("max_processing_period", "A maximum estimate for the time taken to process a message, this is used for tuning consumer group synchronization."),
docs.FieldAdvanced("group", "Tuning parameters for consumer group synchronization.").WithChildren(
docs.FieldAdvanced("session_timeout", "A period after which a consumer of the group is kicked after no heartbeats."),
docs.FieldAdvanced("heartbeat_interval", "A period in which heartbeats should be sent out."),
docs.FieldAdvanced("rebalance_timeout", "A period after which rebalancing is abandoned if unresolved."),
),
docs.FieldAdvanced("fetch_buffer_cap", "The maximum number of unprocessed messages to fetch at a given time."),
docs.FieldAdvanced("target_version", "The version of the Kafka protocol to use."),
batch.FieldSpec(),
},
Categories: []Category{
CategoryServices,
},
}
}
//------------------------------------------------------------------------------
// NewKafkaBalanced creates a new KafkaBalanced input type.
func NewKafkaBalanced(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) {
// TODO: V4 Remove this.
if conf.KafkaBalanced.MaxBatchCount > 1 {
log.Warnf("Field '%v.max_batch_count' is deprecated, use '%v.batching.count' instead.\n", conf.Type, conf.Type)
conf.KafkaBalanced.Batching.Count = conf.KafkaBalanced.MaxBatchCount
}
k, err := reader.NewKafkaCG(conf.KafkaBalanced, mgr, log, stats)
if err != nil {
return nil, err
}
preserved := reader.NewAsyncPreserver(k)
return NewAsyncReader("kafka_balanced", true, preserved, log, stats)
}
// Deprecated: This is a hack for until the batch processor is removed.
// TODO: V4 Remove this.
func newKafkaBalancedHasBatchProcessor(
hasBatchProc bool,
conf Config,
mgr types.Manager,
log log.Modular,
stats metrics.Type,
) (Type, error) {
if !hasBatchProc {
return NewKafkaBalanced(conf, mgr, log, stats)
}
log.Warnln("Detected presence of a 'batch' processor, kafka_balanced input falling back to single threaded mode. To fix this use the 'batching' fields instead.")
k, err := reader.NewKafkaBalanced(conf.KafkaBalanced, mgr, log, stats)
if err != nil {
return nil, err
}
return NewReader("kafka_balanced", reader.NewPreserver(k), log, stats)
}
//------------------------------------------------------------------------------ | lib/input/kafka_balanced.go | 0.70416 | 0.785843 | kafka_balanced.go | starcoder |
package grids
import (
"math"
"github.com/shomali11/go-interview/algorithms/astar"
)
// GridNode grid node
type GridNode struct {
X int
Y int
Cost float64
IsObstacle bool
world *GridWorld
}
// EstimateDistanceToGoal get distance to the goal
func (n *GridNode) EstimateDistanceToGoal(goal astar.Node) float64 {
return distance(n, goal.(*GridNode))
}
// ActualDistanceToNeighbor get distance to a neighbor
func (n *GridNode) ActualDistanceToNeighbor(node astar.Node) float64 {
if isDiagonal(n, node.(*GridNode)) {
return math.Sqrt2 * n.Cost
}
return n.Cost
}
// GetNeighbors get neighbors
func (n *GridNode) GetNeighbors() []astar.Node {
nodes := make([]astar.Node, 0)
for i := -1; i <= 1; i++ {
for j := -1; j <= 1; j++ {
// If Same Object ...
if i == 0 && j == 0 {
// Skip ...
continue
}
if !n.world.IsValid(n.X+i, n.Y+j) {
continue
}
node := n.world.Get(n.X+i, n.Y+j)
if node.IsObstacle {
continue
}
if n.isBehindObstacles(node) {
continue
}
nodes = append(nodes, node)
}
}
return nodes
}
func (n *GridNode) isBehindObstacles(node *GridNode) bool {
dx := node.X - n.X
dy := node.Y - n.Y
i := node.X
j := node.Y
if dx == 1 && dy == 1 { // Lower Right
if n.world.IsValid(i, j-1) && n.world.IsValid(i-1, j) {
right := n.world.Get(i, j-1)
bottom := n.world.Get(i-1, j)
if right.IsObstacle && bottom.IsObstacle {
return true
}
}
} else if dx == -1 && dy == -1 { // Upper Left
if n.world.IsValid(i+1, j) && n.world.IsValid(i, j+1) {
top := n.world.Get(i+1, j)
left := n.world.Get(i, j+1)
if top.IsObstacle && left.IsObstacle {
return true
}
}
} else if dx == 1 && dy == -1 { // Upper Right
if n.world.IsValid(i-1, j) && n.world.IsValid(i, j+1) {
top := n.world.Get(i-1, j)
right := n.world.Get(i, j+1)
if top.IsObstacle && right.IsObstacle {
return true
}
}
} else if dx == -1 && dy == 1 { // Lower Left
if n.world.IsValid(i, j-1) && n.world.IsValid(i+1, j) {
left := n.world.Get(i, j-1)
bottom := n.world.Get(i+1, j)
if left.IsObstacle && bottom.IsObstacle {
return true
}
}
}
return false
}
func isDiagonal(n *GridNode, node *GridNode) bool {
dx := node.X - n.X
dy := node.Y - n.Y
if dx == 1 && dy == 1 { // Lower Right
return true
} else if dx == -1 && dy == -1 { // Upper Left
return true
} else if dx == 1 && dy == -1 { // Upper Right
return true
} else if dx == -1 && dy == 1 { // Lower Left
return true
}
return false
}
func distance(current *GridNode, other *GridNode) float64 {
currentX := float64(current.X)
currentY := float64(current.Y)
otherX := float64(other.X)
otherY := float64(other.Y)
return math.Sqrt(math.Pow(currentX-otherX, 2) + math.Pow(currentY-otherY, 2))
} | algorithms/astar/grids/grid_node.go | 0.782288 | 0.592667 | grid_node.go | starcoder |
package symbol_table
import (
"github.com/midnight-vivian/go-data-structures/algorithms/searching/binary"
"github.com/midnight-vivian/go-data-structures/utils"
)
var _ SymbolTableSuper = (*STTwoArrays)(nil)
type STTwoArrays struct {
keys []utils.Comparabler
values []interface{}
n int
}
func NewSTTwoArrays() *STTwoArrays {
return &STTwoArrays{
keys: make([]utils.Comparabler, 0),
values: make([]interface{}, 0),
}
}
func (stta *STTwoArrays) Get(key utils.Comparabler) interface{} {
index := stta.Rank(key)
if index < stta.n && stta.keys[index] == key {
return stta.values[index]
}
return nil
}
func (stta *STTwoArrays) Put(key utils.Comparabler, value interface{}) {
if value == nil {
return
}
index := stta.Rank(key)
if index < stta.n && stta.keys[index] == key {
stta.values[index] = value
return
}
stta.keys = append(append(stta.keys[:index], key), stta.keys[index:]...)
stta.values = append(append(stta.values[:index], value), stta.values[index:]...)
stta.n++
}
func (stta *STTwoArrays) Delete(key utils.Comparabler) {
index := stta.Rank(key)
if index < stta.n && stta.keys[index] == key {
stta.keys = append(stta.keys[:index], stta.keys[index+1:]...)
stta.values = append(stta.values[:index], stta.values[index+1:]...)
stta.n--
}
}
func (stta *STTwoArrays) Size() int {
return stta.n
}
func (stta *STTwoArrays) Empty() bool {
return stta.n == 0
}
func (stta *STTwoArrays) Contains(key utils.Comparabler) bool {
if stta.Get(key) != nil {
return true
}
return false
}
func (stta *STTwoArrays) Max() utils.Comparabler {
if stta.Empty() {
return nil
}
return stta.keys[stta.n-1]
}
func (stta *STTwoArrays) Min() utils.Comparabler {
if stta.Empty() {
return nil
}
return stta.keys[0]
}
func (stta *STTwoArrays) DeleteMax() {
if stta.n != 0 {
stta.keys = stta.keys[:stta.n-1]
stta.values = stta.values[:stta.n-1]
stta.n--
}
}
func (stta *STTwoArrays) DeleteMin() {
if stta.n != 0 {
stta.keys = stta.keys[1:]
stta.values = stta.values[1:]
stta.n--
}
}
func (stta *STTwoArrays) Floor(key utils.Comparabler) utils.Comparabler {
index := stta.Rank(key)
if index < stta.n && stta.keys[index] == key {
return stta.keys[index]
}
if index == 0 {
return nil
}
return stta.keys[index-1]
}
func (stta *STTwoArrays) Ceiling(key utils.Comparabler) utils.Comparabler {
index := stta.Rank(key)
if index == stta.n {
return nil
}
return stta.keys[index]
}
func (stta *STTwoArrays) Rank(key utils.Comparabler) int {
if stta.Empty() {
return 0
}
return binary.Search(stta.keys, key)
}
func (stta *STTwoArrays) Select(k int) utils.Comparabler {
if k < stta.n {
return stta.keys[k]
}
return nil
} | data-structures/symbol-table/st_two_arrays.go | 0.58059 | 0.42316 | st_two_arrays.go | starcoder |
// Package list provides utilities for handling lists of dynamically-typed elements
package list
import (
"fmt"
"reflect"
)
// List is an interface to a list of dynamically-typed elements
type List interface {
// Count returns the number if items in the list
Count() int
// Get returns the element at the index i
Get(i int) interface{}
// Set assigns the element at the index i with v
Set(i int, v interface{})
// Append adds a single item, list, or slice of items to this List
Append(v interface{})
// Copy copies the elements at [dst..dst+count) to [src..src+count)
Copy(dst, src, count int)
// CopyFrom copies the elements [src..src+count) from the list l to the
// elements [dst..dst+count) in this list
CopyFrom(l List, dst, src, count int)
// Reduces the size of the list to count elements
Resize(count int)
// ElementType returns the type of the elements of the list
ElementType() reflect.Type
}
// Wrap returns a List that wraps a slice pointer
func Wrap(s interface{}) List {
ptr := reflect.ValueOf(s)
if ptr.Kind() != reflect.Ptr || ptr.Elem().Kind() != reflect.Slice {
panic(fmt.Errorf("Wrap() must be called with a pointer to slice. Got: %T", s))
}
return list{ptr.Elem()}
}
// New returns a new list of element type elem for n items
func New(elem reflect.Type, count int) List {
slice := reflect.SliceOf(elem)
return list{reflect.MakeSlice(slice, count, count)}
}
// Copy makes a shallow copy of the list
func Copy(l List) List {
out := New(l.ElementType(), l.Count())
out.CopyFrom(l, 0, 0, l.Count())
return out
}
type list struct{ v reflect.Value }
func (l list) Count() int {
return l.v.Len()
}
func (l list) Get(i int) interface{} {
return l.v.Index(i).Interface()
}
func (l list) Set(i int, v interface{}) {
l.v.Index(i).Set(reflect.ValueOf(v))
}
func (l list) Append(v interface{}) {
switch v := v.(type) {
case list:
l.v.Set(reflect.AppendSlice(l.v, reflect.Value(v.v)))
case List:
// v implements `List`, but isn't a `list`. Need to do a piece-wise copy
items := make([]reflect.Value, v.Count())
for i := range items {
items[i] = reflect.ValueOf(v.Get(i))
}
l.v.Set(reflect.Append(l.v, items...))
default:
r := reflect.ValueOf(v)
if r.Type() == l.v.Type() {
l.v.Set(reflect.AppendSlice(l.v, r))
return
}
l.v.Set(reflect.Append(l.v, reflect.ValueOf(v)))
}
}
func (l list) Copy(dst, src, count int) {
reflect.Copy(
l.v.Slice(dst, dst+count),
l.v.Slice(src, src+count),
)
}
func (l list) CopyFrom(o List, dst, src, count int) {
if o, ok := o.(list); ok {
reflect.Copy(
l.v.Slice(dst, dst+count),
o.v.Slice(src, src+count),
)
}
// v implements `List`, but isn't a `list`. Need to do a piece-wise copy
items := make([]reflect.Value, count)
for i := range items {
l.Set(dst+i, o.Get(src+i))
}
}
func (l list) Resize(count int) {
new := reflect.MakeSlice(l.v.Type(), count, count)
reflect.Copy(new, l.v)
l.v.Set(new)
}
func (l list) ElementType() reflect.Type {
return l.v.Type().Elem()
} | third_party/tint/tools/src/list/list.go | 0.696475 | 0.430985 | list.go | starcoder |
package trie
import (
"fmt"
)
const (
EOLCharacter rune = '\n'
)
// Error related to trie data structure and related operation
type Error struct {
message string
}
func (e *Error) Error() string {
return e.message
}
func newError(message string) *Error {
return &Error{
message: message,
}
}
// Node of a trie
type Node interface {
// InsertRune value of edge from this node
InsertRune(data rune) Node
// IsLeaf determines if this node
IsLeaf() bool
// MatchRune determines if a rune matches one of the edge.
MatchedRune(data rune) (isEnd bool, isMatched bool)
// NextNode return the nodes that is reference by the edge named 'ch'
NextNode(ch rune) Node
// Runes returns the edges connected to this node
Runes() []rune
}
// Populate operation to populate a Trie
func Populate(trie Node, str string) {
var node Node
for index, ch := range str {
if index == 0 {
node = trie.InsertRune(ch)
} else {
node = node.InsertRune(ch)
}
}
}
// VerifyWord against a pre-populated trie
func VerifyWord(trie Node, word string) error {
var isEnd, isMatched bool
var err error
var node Node = trie
for _, ch := range word {
isEnd, isMatched = node.MatchedRune(ch)
if !isMatched {
return newError(fmt.Sprintf("Trie search error. Unable to match criteria: %v", word))
}
node = node.NextNode(ch)
}
if !isEnd {
err = newError(fmt.Sprintf("Trie search error. Unable to match criteria: %v", word))
} else {
err = nil
}
return err
}
// DeleteWord from a trie
func DeleteWord(trie Node, word string) error {
var todelete map[rune]Node = make(map[rune]Node)
var err error
var isEnd, isMatched bool
var node Node = trie
for _, ch := range word {
todelete[ch] = node
isEnd, isMatched = node.MatchedRune(ch)
if !isMatched {
return newError(fmt.Sprintf("Trie search error. Unable to delete word: %v", word))
}
node = node.NextNode(ch)
}
if !isEnd {
err = newError(fmt.Sprintf("Trie search error. Unable to delete word: %v", word))
} else {
for k, _ := range todelete {
delete(todelete, k)
}
err = nil
}
return err
} | internal/trie/trie.go | 0.621081 | 0.42316 | trie.go | starcoder |
package util
import (
"fmt"
"strconv"
"strings"
"time"
)
func SplitFindContains(str, target, sep string, match bool) bool {
ss := strings.Split(str, sep)
isContain := false
for _, s := range ss {
if strings.Contains(target, s) {
isContain = true
break
}
}
return isContain && match
}
func SplitFindEquals(str, target, sep string, match bool) bool {
ss := strings.Split(str, sep)
isEqual := false
for _, s := range ss {
if target == s {
isEqual = true
break
}
}
return isEqual && match
}
func SplitFindTimeInterval(timeStr string, targetTime time.Time, match bool) (bool, error) {
isContain := false
timeStrs := strings.Split(timeStr, "-")
if len(timeStrs) != 2 {
return match, fmt.Errorf("fail to parse the time condition `%s`", timeStr)
}
startTimeStrs := strings.Split(timeStrs[0], ":")
// time can be "00:00" or "00:00:00"
if len(startTimeStrs) < 2 {
return match, fmt.Errorf("fail to parse the start time `%s`", timeStrs[0])
}
endTimeStrs := strings.Split(timeStrs[1], ":")
if len(endTimeStrs) < 2 {
return match, fmt.Errorf("fail to parse the start time `%s`", timeStrs[1])
}
startTimeHour, err := strconv.Atoi(startTimeStrs[0])
if err != nil {
return match, fmt.Errorf("fail to parse the start time hour `%s`", startTimeStrs[0])
}
startTimeMinute, err := strconv.Atoi(startTimeStrs[1])
if err != nil {
return match, fmt.Errorf("fail to parse the start time minute `%s`", startTimeStrs[1])
}
startTimeSecond := 0
if len(startTimeStrs) > 2 {
startTimeSecond, err = strconv.Atoi(startTimeStrs[2])
if err != nil {
return match, fmt.Errorf("fail to parse the start time second `%s`", startTimeStrs[2])
}
}
if startTimeHour < 0 || startTimeHour >= 24 ||
startTimeMinute < 0 || startTimeMinute >= 60 ||
startTimeSecond < 0 || startTimeSecond >= 60 {
return match, fmt.Errorf("fail to parse the start time, hour:[0,23], minute:[0,59], second:[0,59]")
}
endTimeHour, err := strconv.Atoi(endTimeStrs[0])
if err != nil {
return match, fmt.Errorf("fail to parse the end time hour `%s`", endTimeStrs[0])
}
endTimeMinute, err := strconv.Atoi(endTimeStrs[1])
if err != nil {
return match, fmt.Errorf("fail to parse the end time minute `%s`", endTimeStrs[1])
}
endTimeSecond := 0
if len(endTimeStrs) > 2 {
endTimeSecond, err = strconv.Atoi(endTimeStrs[2])
if err != nil {
return match, fmt.Errorf("fail to parse the end time second `%s`", endTimeStrs[2])
}
}
if endTimeHour < 0 || endTimeHour >= 24 ||
endTimeMinute < 0 || endTimeMinute >= 60 ||
endTimeSecond < 0 || endTimeSecond >= 60 {
return match, fmt.Errorf("fail to parse the end time, hour:[0,23], minute:[0,59], second:[0,59]")
}
var startTime, endTime time.Time
if targetTime.Hour() >= startTimeHour {
startTime = time.Date(targetTime.Year(), targetTime.Month(), targetTime.Day(), startTimeHour, startTimeMinute, startTimeSecond, 0, targetTime.Location())
endTime = time.Date(targetTime.Year(), targetTime.Month(), targetTime.Day(), endTimeHour, endTimeMinute, endTimeSecond, 0, targetTime.Location())
if startTimeHour > endTimeHour {
// 23:00T to 01:00T+1
endTime = endTime.AddDate(0, 0, 1)
}
} else { // target time hour < start time hour, maybe in T-1 cycle
startTime = time.Date(targetTime.Year(), targetTime.Month(), targetTime.Day(), startTimeHour, startTimeMinute, startTimeSecond, 0, targetTime.Location())
endTime = time.Date(targetTime.Year(), targetTime.Month(), targetTime.Day(), endTimeHour, endTimeMinute, endTimeSecond, 0, targetTime.Location())
if startTimeHour > endTimeHour {
// 23:00T-1 to 01:00T
startTime = startTime.AddDate(0, 0, -1)
}
}
if targetTime.After(startTime) && targetTime.Before(endTime) {
isContain = true
}
return isContain && match, nil
} | pkg/util/util.go | 0.640973 | 0.476458 | util.go | starcoder |
package regen
import (
"fmt"
)
// CharClass represents a regular expression character class as a list of ranges.
// The runes contained in the class can be accessed by index.
type tCharClass struct {
Ranges []tCharClassRange
TotalSize int32
}
// CharClassRange represents a single range of characters in a character class.
type tCharClassRange struct {
Start rune
Size int32
}
// NewCharClass creates a character class with a single range.
func newCharClass(start rune, end rune) *tCharClass {
charRange := newCharClassRange(start, end)
return &tCharClass{
Ranges: []tCharClassRange{charRange},
TotalSize: charRange.Size,
}
}
/*
ParseCharClass parses a character class as represented by syntax.Parse into a slice of CharClassRange structs.
Char classes are encoded as pairs of runes representing ranges:
[0-9] = 09, [a0] = aa00 (2 1-len ranges).
e.g.
"[a0-9]" -> "aa09" -> a, 0-9
"[^a-z]" -> "…" -> 0-(a-1), (z+1)-(max rune)
*/
func parseCharClass(runes []rune) *tCharClass {
var totalSize int32
numRanges := len(runes) / 2
ranges := make([]tCharClassRange, numRanges, numRanges)
for i := 0; i < numRanges; i++ {
start := runes[i*2]
end := runes[i*2+1]
// indicates a negative class
if start == 0 {
// doesn't make sense to generate null bytes, so all ranges must start at
// no less than 1.
start = 1
}
r := newCharClassRange(start, end)
ranges[i] = r
totalSize += r.Size
}
return &tCharClass{ranges, totalSize}
}
// GetRuneAt gets a rune from CharClass as a contiguous array of runes.
func (class *tCharClass) GetRuneAt(i int32) rune {
for _, r := range class.Ranges {
if i < r.Size {
return r.Start + rune(i)
}
i -= r.Size
}
panic("index out of bounds")
}
func (class *tCharClass) String() string {
return fmt.Sprintf("%s", class.Ranges)
}
func newCharClassRange(start rune, end rune) tCharClassRange {
if start < 1 {
panic("char class range cannot contain runes less than 1")
}
size := end - start + 1
if size < 1 {
panic("char class range size must be at least 1")
}
return tCharClassRange{
Start: start,
Size: size,
}
}
func (r tCharClassRange) String() string {
if r.Size == 1 {
return fmt.Sprintf("%s:1", runesToString(r.Start))
}
return fmt.Sprintf("%s-%s:%d", runesToString(r.Start), runesToString(r.Start+rune(r.Size-1)), r.Size)
} | char_class.go | 0.761804 | 0.47658 | char_class.go | starcoder |
package influxdb
import (
"bytes"
"fmt"
"strings"
"github.com/influxdata/influxql"
log "github.com/sirupsen/logrus"
)
// ExprReturn represents the type returned by the expr.
type ExprReturn int
const (
// Unknown type.
Unknown ExprReturn = 0
// Scalar type.
Scalar ExprReturn = 1
// SeriesSet type.
SeriesSet ExprReturn = 2
)
// BinaryOperationType represents the operation type
type BinaryOperationType int
const (
// UnknownBinary type.
UnknownBinary BinaryOperationType = 0
// ScalarToScalar Operation.
ScalarToScalar BinaryOperationType = 1
// ScalarToSeries and series type.
ScalarToSeries BinaryOperationType = 2
// SeriesToScalar and series type.
SeriesToScalar BinaryOperationType = 3
// SeriesToSeries type.
SeriesToSeries BinaryOperationType = 4
)
type binaryOperationType struct {
}
// parseExpr Parse native Influx Queries expression
func (p *InfluxParser) parseExpr(getExpr influxql.Expr, level int, selectors []string, where [][]*WhereCond) (string, ExprReturn, error) {
exprType := Unknown
mc2 := ""
// Return the function name or variable name, if available.
switch expr := getExpr.(type) {
case *influxql.Call:
call, exprTypeCall, err := p.parseCall(expr, selectors, where)
if err != nil {
return "", Unknown, err
}
exprType = exprTypeCall
mc2 += call
case *influxql.BinaryExpr:
leftString, leftType, leftError := p.parseExpr(expr.LHS, level+1, selectors, where)
if leftError != nil {
return "", Unknown, leftError
}
rightString, rightType, rightError := p.parseExpr(expr.RHS, level+1, selectors, where)
if rightError != nil {
return "", Unknown, rightError
}
mc2 += leftString + fmt.Sprintf(" 'left-%d' STORE\n", level)
mc2 += rightString + fmt.Sprintf(" 'right-%d' STORE\n", level)
binaryType := getBinaryOperationType(leftType, rightType)
opMc2, opErr := p.parseMathOperation(binaryType, expr.Op, level)
if opErr != nil {
return "", Unknown, rightError
}
mc2 += opMc2
if leftType == Scalar && rightType == Scalar {
exprType = Scalar
} else {
exprType = SeriesSet
}
case *influxql.ParenExpr:
return p.parseExpr(expr.Expr, level+1, selectors, where)
case *influxql.VarRef:
p.HasWildCard = false
fetch, exprTypeCall, err := p.parseFetch(expr.Val, expr.Type, selectors, where)
if err != nil {
return "", Unknown, err
}
exprType = exprTypeCall
mc2 += fetch
case *influxql.IntegerLiteral:
return fmt.Sprintf(" %d ", expr.Val), Scalar, nil
default:
log.Warnf("Parse expr %s : %T", expr.String(), expr)
}
return mc2, exprType, nil
}
// Check a Binary Operation to get it's type
func getBinaryOperationType(leftType, rightType ExprReturn) BinaryOperationType {
if leftType == Scalar && rightType == Scalar {
return ScalarToScalar
}
if leftType == Scalar && rightType == SeriesSet {
return ScalarToSeries
}
if leftType == SeriesSet && rightType == Scalar {
return SeriesToScalar
}
if leftType == SeriesSet && rightType == SeriesSet {
return SeriesToSeries
}
return UnknownBinary
}
// Parse Influx Operator
// https://docs.influxdata.com/influxdb/v1.7/query_language/math_operators/
func (p *InfluxParser) parseMathOperation(binaryOperation BinaryOperationType, op influxql.Token, level int) (string, error) {
switch op {
case influxql.ADD:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d + \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d $left-%d TODOUBLE mapper.add 0 0 0 ] MAP\n", level, level), nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d $right-%d TODOUBLE mapper.add 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return fmt.Sprintf("[ $left-%d $right-%d NULL op.add ] APPLY NONEMPTY\n", level, level), nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.SUB:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d - \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ [ $right-%d -1.0 mapper.mul 0 0 0 ] MAP $left-%d TODOUBLE mapper.add 0 0 0 ] MAP\n", level, level), nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d $right-%d TODOUBLE -1 * mapper.add 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return fmt.Sprintf("[ $left-%d ", level) + "'%2B.tosub' RENAME " + fmt.Sprintf("$right-%d ", level) + " NULL op.sub ] APPLY NONEMPTY\n", nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.MUL:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d * \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d $left-%d TODOUBLE mapper.mul 0 0 0 ] MAP\n", level, level), nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d $right-%d TODOUBLE mapper.mul 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return fmt.Sprintf("[ $left-%d $right-%d NULL op.mul ] APPLY NONEMPTY\n", level, level), nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.DIV:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d + \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d ", level) + " <% DROP " + fmt.Sprintf("$left-%d", level) + " TODOUBLE / %> LMAP\n", nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d 1 $right-%d TODOUBLE / mapper.mul 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return fmt.Sprintf("[ $left-%d ", level) + "'%2B.todiv' RENAME " + fmt.Sprintf("$right-%d ", level) + " NULL op.div ] APPLY NONEMPTY\n", nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.MOD:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d ", level, level) + "% \n", nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d $left-%d mapper.mod 0 0 0 ] MAP\n", level, level), nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d $right-%d mapper.mod 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return "", fmt.Errorf("Modulo is currently not supported between two GTS sets") // FIXME
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.BITWISE_AND:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d & \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d NONEMPTY mapper.tolong 0 0 0 ] MAP ", level) + " <% DROP " + fmt.Sprintf("$left-%d", level) + " TOLONG & %> LMAP\n", nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d NONEMPTY mapper.tolong 0 0 0 ] MAP ", level) + " <% DROP " + fmt.Sprintf("$right-%d", level) + " TOLONG & %> LMAP\n", nil
case SeriesToSeries:
mc2 := fmt.Sprintf("[ $right-%d NONEMPTY mapper.tolong 0 0 0 ] MAP NULL PARTITION 'leftKeys' STORE\n", level)
mc2 += fmt.Sprintf("[ $left-%d NONEMPTY mapper.tolong 0 0 0 ] MAP NULL PARTITION \n", level)
mc2 += getBitwiseApply("&")
return mc2, nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.BITWISE_OR:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d | \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d NONEMPTY mapper.tolong 0 0 0 ] MAP", level) + " <% DROP " + fmt.Sprintf("$left-%d", level) + " TOLONG | %> LMAP\n", nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d NONEMPTY mapper.tolong 0 0 0 ] MAP ", level) + " <% DROP " + fmt.Sprintf("$right-%d", level) + " TOLONG | %> LMAP\n", nil
case SeriesToSeries:
mc2 := fmt.Sprintf("[ $right-%d NONEMPTY mapper.tolong 0 0 0 ] MAP NULL PARTITION 'leftKeys' STORE\n", level)
mc2 += fmt.Sprintf("[ $left-%d NONEMPTY mapper.tolong 0 0 0 ] MAP NULL PARTITION \n", level)
mc2 += getBitwiseApply("|")
return mc2, nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.BITWISE_XOR:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d ^ \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d NONEMPTY mapper.tolong 0 0 0 ] MAP ", level) + " <% DROP " + fmt.Sprintf("$left-%d", level) + " TOLONG ^ %> LMAP\n", nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d NONEMPTY mapper.tolong 0 0 0 ] MAP ", level) + " <% DROP " + fmt.Sprintf("$right-%d", level) + " TOLONG ^ %> LMAP\n", nil
case SeriesToSeries:
mc2 := fmt.Sprintf("[ $right-%d NONEMPTY mapper.tolong 0 0 0 ] MAP NULL PARTITION 'leftKeys' STORE\n", level)
mc2 += fmt.Sprintf("[ $left-%d NONEMPTY mapper.tolong 0 0 0 ] MAP NULL PARTITION \n", level)
mc2 += getBitwiseApply("^")
return mc2, nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.AND:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d AND \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d $left-%d TOBOOLEAN mapper.and 0 0 0 ] MAP\n", level, level), nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d $right-%d TOBOOLEAN mapper.and 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return fmt.Sprintf("[ $right-%d $left-%d NULL op.and ] APPLY NONEMPTY\n", level, level), nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.OR:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d OR \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d $left-%d TOBOOLEAN mapper.or 0 0 0 ] MAP\n", level, level), nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d $right-%d TOBOOLEAN mapper.or 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return fmt.Sprintf("[ $right-%d $left-%d NULL op.or ] APPLY NONEMPTY\n", level, level), nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.EQ:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d == \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d $left-%d mapper.eq 0 0 0 ] MAP\n", level, level), nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d $right-%d mapper.eq 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return fmt.Sprintf("[ $right-%d $left-%d NULL op.eq ] APPLY NONEMPTY\n", level, level), nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.NEQ:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d ! \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d $left-%d TOBOOLEAN mapper.ne 0 0 0 ] MAP\n", level, level), nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d $right-%d TOBOOLEAN mapper.ne 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return fmt.Sprintf("[ $right-%d $left-%d NULL op.ne ] APPLY NONEMPTY\n", level, level), nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.LT:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d < \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d $left-%d TOBOOLEAN mapper.lt 0 0 0 ] MAP\n", level, level), nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d $right-%d TOBOOLEAN mapper.lt 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return fmt.Sprintf("[ $right-%d $left-%d NULL op.lt ] APPLY NONEMPTY\n", level, level), nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.LTE:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d <= \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d $left-%d TOBOOLEAN mapper.le 0 0 0 ] MAP\n", level, level), nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d $right-%d TOBOOLEAN mapper.le 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return fmt.Sprintf("[ $right-%d $left-%d NULL op.le ] APPLY NONEMPTY\n", level, level), nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.GT:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d > \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d $left-%d TOBOOLEAN mapper.gt 0 0 0 ] MAP\n", level, level), nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d $right-%d TOBOOLEAN mapper.gt 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return fmt.Sprintf("[ $right-%d $left-%d NULL op.gt ] APPLY NONEMPTY\n", level, level), nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
case influxql.GTE:
switch binaryOperation {
case ScalarToScalar:
return fmt.Sprintf("$left-%d $right-%d >= \n", level, level), nil
case ScalarToSeries:
return fmt.Sprintf("[ $right-%d $left-%d TOBOOLEAN mapper.ge 0 0 0 ] MAP\n", level, level), nil
case SeriesToScalar:
return fmt.Sprintf("[ $left-%d $right-%d TOBOOLEAN mapper.ge 0 0 0 ] MAP\n", level, level), nil
case SeriesToSeries:
return fmt.Sprintf("[ $right-%d $left-%d NULL op.ge ] APPLY NONEMPTY\n", level, level), nil
default:
return "", fmt.Errorf("Unvalid operation types")
}
default:
log.Warnf("parseMathOperation %s %T", op.String(), op)
return "", fmt.Errorf("Unsupported %s operator", op.String())
}
}
func getBitwiseApply(operator string) string {
mc2 :=
`
[] SWAP <%
'seriesSet' STORE
'key' STORE
$leftKeys $key GET
<%
DUP ISNULL
%>
<%
DROP []
%>
IFT
'secondSet' STORE
$seriesSet
$secondSet
APPEND
<% DUP SIZE 1 > %>
<%
0 REMOVE
DUP
CLONEEMPTY DUP NAME 'cName' STORE
DUP LABELS 'cLabels' STORE
ATTRIBUTES 'cAttributes' STORE
SWAP
<%
`
mc2 += operator
mc2 += `
%>
FOREACH
$cName RENAME
$cLabels RELABEL
$cAttributes SETATTRIBUTES
+
%>
<%
DROP CONTINUE
%>
IFTE
%>
FOREACH
`
return mc2
}
// Generate WarpScript Fetch
func (p *InfluxParser) parseFetch(name string, fetchType influxql.DataType, selectors []string, where [][]*WhereCond) (string, ExprReturn, error) {
fetchString := "FETCH"
switch fetchType {
case influxql.Float:
fetchString = "FETCHDOUBLE"
case influxql.Integer:
fetchString = "FETCHLONG"
case influxql.String:
fetchString = "FETCHSTRING"
case influxql.Boolean:
fetchString = "FETCHBOOLEAN"
}
valueName := name
if name == "*" {
valueName = ".*"
}
mc2 := ""
classname := fmt.Sprintf("~(%s)", strings.Join(p.Classnames, "|"))
hasFilter := false
selectFields := make([]string, 0)
var computeTags bytes.Buffer
for i, wheres := range where {
if len(wheres) > 0 {
computeTags.WriteString(" $set \n")
filterTags := make([]string, 0)
for _, whereCond := range wheres {
if whereCond.isTag {
op := ""
value := whereCond.value.Val
if strings.HasPrefix(whereCond.value.Val, "'") {
value = strings.Trim(whereCond.value.Val, "'")
} else if strings.HasPrefix(whereCond.value.Val, "\"") {
value = strings.Trim(whereCond.value.Val, "\"")
}
if whereCond.op == influxql.REGEX || whereCond.op == influxql.EQREGEX {
op = "~"
} else if whereCond.op == influxql.NEQ {
op = "~"
value = fmt.Sprintf("(?!%s).*?", whereCond.value)
} else if whereCond.op == influxql.NEQREGEX {
op = "~"
value = fmt.Sprintf("(?!%s)?", whereCond.value)
}
filterTags = append(filterTags, fmt.Sprintf(" '%s' '%s%s' ", whereCond.key, op, value))
}
}
computeTags.WriteString(fmt.Sprintf("[ SWAP [] { %s } filter.bylabels ] FILTER \n", strings.Join(filterTags, " ")))
for _, whereCond := range wheres {
if !whereCond.isTag {
hasFilter = true
selectFields = append(selectFields, whereCond.key)
value := whereCond.value.Val
if whereCond.value.Type == influxql.String || whereCond.value.Type == influxql.Unknown {
if !strings.HasPrefix(value, "'") && !strings.HasPrefix(value, "\"") {
value = "'" + value + "'"
}
}
computeTags.WriteString(fmt.Sprintf(" [ SWAP [] '%s' filter.byclass ] FILTER \n", classname+p.Separator+whereCond.key))
switch whereCond.op {
case influxql.SUB:
computeTags.WriteString(fmt.Sprintf("[ SWAP %s TODOUBLE -1 * mapper.add 0 0 0 ] MAP\n", value))
case influxql.DIV:
computeTags.WriteString(fmt.Sprintf("[ SWAP 1 %s TODOUBLE / mapper.mul 0 0 0 ] MAP\n", value))
case influxql.BITWISE_AND, influxql.BITWISE_OR, influxql.BITWISE_XOR:
return "", Unknown, fmt.Errorf("Bitwise %s is currently only supported between numbers (int and float)", whereCond.op.String()) // FIXME)
default:
computeTags.WriteString(fmt.Sprintf(" [ SWAP %s mapper.%s 0 0 0 ] MAP \n", value, getWarpScriptOpString(whereCond.op)))
}
}
}
computeTags.WriteString(" [ SWAP true mapper.replace 0 0 0 ] MAP \n")
computeTags.WriteString("[ SWAP NULL reducer.and ] REDUCE \n")
}
if i > 1 {
computeTags.WriteString("APPEND")
}
}
separator := "\\."
if p.Separator != "." {
separator = p.Separator
}
if hasFilter {
classname = classname + fmt.Sprintf(separator+"(%s|%s)", valueName, strings.Join(selectFields, "|"))
} else {
classname = classname + separator + "(" + valueName + ")"
}
fetchSelector := fmt.Sprintf("'%s{}'", classname)
if len(selectors) > 0 {
fetchSelector = " "
for _, selector := range selectors {
fetchSelector += fmt.Sprintf("'%s{%s}' ", classname, selector)
}
}
mc2 += fmt.Sprintf("{ 'token' '%s' 'selectors' [ %s ] 'end' $end 'timespan' $interval } %s\n", p.Token, fetchSelector, fetchString)
mc2 += "<% DROP DUP NAME 'name' STORE { '.app' NULL '.InfluxDBName' $name '"
mc2 += p.Separator
mc2 += "' <% DUP '' == %> <% DROP 1 ->LIST %> <% SPLIT %> IFTE\n"
mc2 += " 0 GET } RELABEL %> LMAP \n"
if p.HasSubQuery {
mc2 += "<% " + fmt.Sprintf(" 'subqueries-%d' ", p.SubQueryLevel) + " DEFINED %> <% " + fmt.Sprintf("$subqueries-%d ", p.SubQueryLevel)
mc2 += " <% DROP DUP ATTRIBUTES RELABEL [ [ $start $end ] ] CLIP %> LMAP APPEND %> IFT FLATTEN \n"
}
if hasFilter {
filter := `
'set' STORE
$set
NULL
PARTITION
'partitionSet' STORE
`
filter += computeTags.String()
filter += `
//APPEND
[]
SWAP
NULL
PARTITION
<%
[ SWAP [] reducer.or.exclude-nulls ] REDUCE
'mask' STORE
$partitionSet SWAP GET
<%
DROP
DUP NAME 'namePSeries' STORE
'pSeries' STORE
[
$mask
$pSeries 1 ->LIST
[]
op.mask
] APPLY
0 GET $namePSeries RENAME
%>
LMAP
APPEND
%>
FOREACH
NONEMPTY
`
separator := "\\."
if p.Separator != "." {
separator = p.Separator
}
filter += fmt.Sprintf("[ SWAP [] '%s' filter.byclass ] FILTER ", fmt.Sprintf("~(%s)", strings.Join(p.Classnames, "|"))+separator+"("+name+")")
mc2 += filter
}
return mc2, SeriesSet, nil
}
// getWarpScriptOpString: Convert an Influx Operation to a single value WarpScript mapper
func getWarpScriptOpString(op influxql.Token) string {
switch op {
case influxql.ADD:
return "add"
case influxql.MUL:
return "mul"
case influxql.DIV:
return "mul"
case influxql.MOD:
return "mod"
case influxql.EQ, influxql.EQREGEX:
return "eq"
case influxql.NEQREGEX, influxql.NEQ:
return "ne"
case influxql.LT:
return "lt"
case influxql.LTE:
return "le"
case influxql.GT:
return "gt"
case influxql.GTE:
return "ge"
default:
return ""
}
}
// getParameterErrorString: Parameters generic error handling
func (p *InfluxParser) getParameterErrorString(lenArgs int, expArgsLen int, expected int, name string) string {
if expArgsLen == expected {
return fmt.Sprintf("invalid number of arguments for %s, expected %d, got %d", name, expected, lenArgs)
}
return fmt.Sprintf("invalid number of arguments for %s, expected at least %d but no more than %d, got %d", name, expected, expArgsLen, lenArgs)
}
// Parse function call
func (p *InfluxParser) parseCall(expr *influxql.Call, selectors []string, where [][]*WhereCond) (string, ExprReturn, error) {
isTop := false
mc2 := ""
args := make([]string, 0)
switch expr.Name {
// Parse an Aggregation method
case "bottom", "count", "distinct", "first", "integral", "last", "max", "mean", "median", "min", "mode", "percentile", "sample", "spread", "stddev", "sum", "top":
expArgsLen := 1
expected := 1
switch expr.Name {
case "distinct":
if len(expr.Args) > 1 {
errorString := "distinct function can only have one argument"
return "", Unknown, fmt.Errorf(errorString)
}
case "bottom", "top":
expArgsLen = len(expr.Args) + 1
expected = 2
isTop = true
case "percentile", "sample":
expArgsLen = 2
expected = 2
case "integral":
expArgsLen = 2
}
if len(expr.Args) > expArgsLen {
errorString := p.getParameterErrorString(len(expr.Args), expArgsLen, expected, expr.Name)
return "", Unknown, fmt.Errorf(errorString)
}
for i, arg := range expr.Args {
if i == 0 {
fetch, _, err := p.parseArgumentFetch(expr.Name, arg, selectors, where)
if err != nil {
return "", Unknown, err
}
mc2 += fetch
} else if i > 0 {
compArgs := ""
var err error
compArgs, args, err = p.parseComplementaryArgument(expr.Name, arg, args, true, selectors, where, isTop)
if err != nil {
return "", Unknown, err
}
mc2 += compArgs
}
}
if p.HasGroupBy {
p.GroupByTags = append(p.GroupByTags, "'.InfluxDBName'")
mc2 += p.startPartition()
}
// Parse method WarpScript
curFun, err := p.parseAggregationName(expr.Name, args)
if err != nil {
return "", Unknown, err
}
mc2 += curFun
if len(p.GroupByTags) > 0 {
mc2 += `
+
%>
FOREACH
FLATTEN
`
}
case "atan2":
if len(expr.Args) != 2 {
return "", Unknown, fmt.Errorf(invalidNumberOfArgs(expr.Name, 2, len(args)+1))
}
for _, arg := range expr.Args {
compArgs := ""
var err error
compArgs, args, err = p.parseComplementaryArgument(expr.Name, arg, args, false, selectors, where, isTop)
if err != nil {
return "", Unknown, err
}
mc2 += compArgs
}
// atan2 expects 2 arguments on the stack
if p.HasGroupBy {
p.GroupByTags = append(p.GroupByTags, "'.InfluxDBName'")
mc2 += `
<% DROP { '.atan2' 'py' } RELABEL %> LMAP
SWAP
<% DROP { '.atan2' 'px' } RELABEL %> LMAP APPEND
`
mc2 += p.startPartition()
mc2 += `
'set' STORE
[ $set [] { '.atan2' 'py' } filter.bylabels ] FILTER
[ $set [] { '.atan2' 'px' } filter.bylabels ] FILTER
`
}
// Parse method WarpScript
curFun, err := p.parseTransformationsName(expr.Name, args)
if err != nil {
return "", Unknown, err
}
mc2 += curFun
if len(p.GroupByTags) > 0 {
mc2 += `
+
%>
FOREACH
FLATTEN
`
}
case "histogram":
errorString := "undefined function histogram()"
return errorString, Unknown, fmt.Errorf(errorString)
case "abs", "acos", "asin", "atan", "ceil", "cos", "cumulative_sum", "derivative", "difference", "elapsed", "exp", "floor",
"ln", "log", "log2", "log10", "moving_average", "non_negative_derivative", "non_negative_difference", "pow", "round", "sin", "sqrt", "tan":
expArgsLen := 1
expected := 1
switch expr.Name {
case "derivative", "elapsed", "non_negative_derivative":
expArgsLen = 2
case "log", "moving_average", "pow":
expArgsLen = 2
expected = 2
}
if len(expr.Args) > expArgsLen {
errorString := p.getParameterErrorString(len(expr.Args), expArgsLen, expected, expr.Name)
return errorString, Unknown, fmt.Errorf(errorString)
}
for _, arg := range expr.Args {
compArgs := ""
var err error
compArgs, args, err = p.parseComplementaryArgument(expr.Name, arg, args, false, selectors, where, isTop)
if err != nil {
return "", Unknown, err
}
mc2 += compArgs
}
if p.HasGroupBy {
p.GroupByTags = append(p.GroupByTags, "'.InfluxDBName'")
mc2 += p.startPartition()
}
// Parse method WarpScript
curFun, err := p.parseTransformationsName(expr.Name, args)
if err != nil {
return "", Unknown, err
}
mc2 += curFun
if len(p.GroupByTags) > 0 {
mc2 += `
+
%>
FOREACH
FLATTEN
`
}
default:
return "", Unknown, fmt.Errorf("Unimplemented method: %s()", expr.Name)
}
return mc2, SeriesSet, nil
}
// parseArgumentFetch: parse Fetch based on influx Expression argument
func (p *InfluxParser) parseArgumentFetch(name string, arg influxql.Expr, selectors []string, where [][]*WhereCond) (string, ExprReturn, error) {
mc2 := ""
exprType := Unknown
// Argument have to be the selected field
switch argExpr := arg.(type) {
case *influxql.Wildcard:
p.HasWildCard = true
fetch, fetchType, err := p.parseFetch(".*", influxql.Unknown, selectors, where)
if err != nil {
return "", Unknown, err
}
mc2 += fetch
p.HasGroupBy = true
mc2 += p.renameAndSetInfluxStarLabels()
p.GroupByTags = append(p.GroupByTags, "'.INFLUXQL_COLUMN_NAME'")
exprType = fetchType
case *influxql.VarRef:
p.HasWildCard = false
fetch, fetchType, err := p.parseFetch(argExpr.Val, argExpr.Type, selectors, where)
if err != nil {
return "", Unknown, err
}
mc2 += fetch
exprType = fetchType
default:
return "", Unknown, fmt.Errorf("expected field argument in %s()", name)
}
return mc2, exprType, nil
}
// parseComplementaryArgument Parse a secondary argument
func (p *InfluxParser) parseComplementaryArgument(name string, arg influxql.Expr, args []string, aggregation bool, selectors []string, where [][]*WhereCond, isTop bool) (string, []string, error) {
mc2 := ""
// Store complementary method argument
switch argExpr := arg.(type) {
case *influxql.BinaryExpr:
log.Warnf("parseComplementaryArgument - *influxql.BinaryExpr arg %s", influxql.BinaryExprName(argExpr))
case *influxql.ParenExpr:
log.Warnf("parseComplementaryArgument - *influxql.ParenExpr arg %s", influxql.Field{Expr: argExpr.Expr})
case *influxql.Call:
call, _, err := p.parseCall(argExpr, selectors, where)
if err != nil {
return "", args, err
}
mc2 += call
case *influxql.Wildcard:
p.HasWildCard = true
fetch, _, err := p.parseFetch(".*", influxql.Unknown, selectors, where)
if err != nil {
return "", args, err
}
mc2 += fetch
p.HasGroupBy = true
mc2 += p.renameAndSetInfluxStarLabels()
p.GroupByTags = append(p.GroupByTags, "'.INFLUXQL_COLUMN_NAME'")
case *influxql.VarRef:
if isTop {
args = append(args, fmt.Sprintf("%s", argExpr.Val))
} else if !aggregation {
p.HasWildCard = false
fetch, _, err := p.parseFetch(argExpr.Val, argExpr.Type, selectors, where)
if err != nil {
return "", args, err
}
mc2 += fetch
}
case *influxql.DurationLiteral:
args = append(args, fmt.Sprintf("%d", argExpr.Val.Nanoseconds()/1000))
case *influxql.StringLiteral:
args = append(args, fmt.Sprintf("'%s'", argExpr.Val))
case *influxql.BooleanLiteral, *influxql.UnsignedLiteral, *influxql.IntegerLiteral, *influxql.NumberLiteral:
args = append(args, fmt.Sprintf("%s", argExpr.String()))
default:
log.Warnf("parseComplementaryArgument - Default %s %T", argExpr, argExpr)
}
return mc2, args, nil
} | proto/influxdb/internalExprParser.go | 0.607081 | 0.433202 | internalExprParser.go | starcoder |
package queryme
// A Field is the name of a field.
type Field string
// A Value is any constant used in queries.
type Value interface{}
// A SortOrder is an ordering over a field.
type SortOrder struct {
Field Field
Ascending bool
}
// A Predicate is an expression that can is evaluated as either true or false.
type Predicate interface {
// Accept implements the visitor pattern for predicates.
Accept(visitor PredicateVisitor)
}
// PredicateVisitor is an object which can visit any kind of predicate.
type PredicateVisitor interface {
// VisitNot is called to visit a negation predicate.
VisitNot(operand Predicate)
// VisitAnd is called to visit a conjunction predicate.
VisitAnd(operands []Predicate)
// VisitOr is called to visit a disjunction predicate.
VisitOr(operands []Predicate)
// VisitEq is called to visit an equality predicate.
VisitEq(field Field, operands []Value)
// VisitLt is called to visit a stricly less than comparison predicate.
VisitLt(field Field, operand Value)
// VisitLe is called to visit a less or equal comparison predicate.
VisitLe(field Field, operand Value)
// VisitLe is called to visit a stricly greater comparison predicate.
VisitGt(field Field, operand Value)
// VisitLe is called to visit a greater or equal comparison predicate.
VisitGe(field Field, operand Value)
// VisitLe is called to visit a full-text search predicate.
VisitFts(field Field, query string)
}
// Not is a negation predicate.
type Not struct {
Operand Predicate
}
func (p Not) Accept(visitor PredicateVisitor) {
visitor.VisitNot(p.Operand)
}
// And is a conjunction predicate.
type And []Predicate
func (p And) Accept(visitor PredicateVisitor) {
visitor.VisitAnd(p)
}
// Or is a disjunction predicate.
type Or []Predicate
func (p Or) Accept(visitor PredicateVisitor) {
visitor.VisitOr(p)
}
// Eq is an equality predicate.
type Eq struct {
Field Field
Operands []Value
}
func (p Eq) Accept(visitor PredicateVisitor) {
visitor.VisitEq(p.Field, p.Operands)
}
// Lt is a strictly less comparison predicate.
type Lt struct {
Field Field
Operand Value
}
func (p Lt) Accept(visitor PredicateVisitor) {
visitor.VisitLt(p.Field, p.Operand)
}
// Le is a less or equal comparison predicate.
type Le struct {
Field Field
Operand Value
}
func (p Le) Accept(visitor PredicateVisitor) {
visitor.VisitLe(p.Field, p.Operand)
}
// Gt is a stricly greater comparison predicate.
type Gt struct {
Field Field
Operand Value
}
func (p Gt) Accept(visitor PredicateVisitor) {
visitor.VisitGt(p.Field, p.Operand)
}
// Ge is a greater or equal comparison predicate.
type Ge struct {
Field Field
Operand Value
}
func (p Ge) Accept(visitor PredicateVisitor) {
visitor.VisitGe(p.Field, p.Operand)
}
// Ge is a full-text search comparison predicate.
type Fts struct {
Field Field
Query string
}
func (p Fts) Accept(visitor PredicateVisitor) {
visitor.VisitFts(p.Field, p.Query)
}
type fieldsAccumulator struct {
Index map[Field]struct{}
Slice []Field
}
func (acc *fieldsAccumulator) saveField(field Field) {
if _, ok := acc.Index[field]; !ok {
acc.Index[field] = struct{}{}
acc.Slice = append(acc.Slice, field)
}
}
func (acc *fieldsAccumulator) VisitNot(operand Predicate) {
operand.Accept(acc)
}
func (acc *fieldsAccumulator) VisitAnd(operands []Predicate) {
for _, p := range operands {
p.Accept(acc)
}
}
func (acc *fieldsAccumulator) VisitOr(operands []Predicate) {
for _, p := range operands {
p.Accept(acc)
}
}
func (acc *fieldsAccumulator) VisitEq(field Field, operands []Value) {
acc.saveField(field)
}
func (acc *fieldsAccumulator) VisitLt(field Field, operand Value) {
acc.saveField(field)
}
func (acc *fieldsAccumulator) VisitLe(field Field, operand Value) {
acc.saveField(field)
}
func (acc *fieldsAccumulator) VisitGt(field Field, operand Value) {
acc.saveField(field)
}
func (acc *fieldsAccumulator) VisitGe(field Field, operand Value) {
acc.saveField(field)
}
func (acc *fieldsAccumulator) VisitFts(field Field, query string) {
acc.saveField(field)
}
// Fields returns all fields referenced in the predicate.
func Fields(predicate Predicate) []Field {
var acc fieldsAccumulator
acc.Index = make(map[Field]struct{})
acc.Slice = make([]Field, 0, 4)
predicate.Accept(&acc)
return acc.Slice
} | go/expressions.go | 0.798423 | 0.485234 | expressions.go | starcoder |
package sentences
import (
"strings"
)
/*
AnnotateTokens is an interface used for the sentence tokenizer to add properties to
any given token during tokenization.
*/
type AnnotateTokens interface {
Annotate([]*Token) []*Token
}
/*
TypeBasedAnnotation performs the first pass of annotation, which makes decisions
based purely based on the word type of each word:
* '?', '!', and '.' are marked as sentence breaks.
* sequences of two or more periods are marked as ellipsis.
* any word ending in '.' that's a known abbreviation is marked as an abbreviation.
* any other word ending in '.' is marked as a sentence break.
Return these annotations as a tuple of three sets:
* sentbreak_toks: The indices of all sentence breaks.
* abbrev_toks: The indices of all abbreviations.
* ellipsis_toks: The indices of all ellipsis marks.
*/
type TypeBasedAnnotation struct {
*Storage
PunctStrings
TokenExistential
}
// NewTypeBasedAnnotation creates an instance of the TypeBasedAnnotation struct
func NewTypeBasedAnnotation(s *Storage, p PunctStrings, e TokenExistential) *TypeBasedAnnotation {
return &TypeBasedAnnotation{
Storage: s,
PunctStrings: p,
TokenExistential: e,
}
}
// NewAnnotations is the default AnnotateTokens struct that the tokenizer uses
func NewAnnotations(s *Storage, p PunctStrings, word WordTokenizer) []AnnotateTokens {
return []AnnotateTokens{
&TypeBasedAnnotation{s, p, word},
&TokenBasedAnnotation{s, p, word, &DefaultTokenGrouper{}, &OrthoContext{
s, p, word, word,
}},
}
}
// Annotate iterates over all tokens and applies the type annotation on them
func (a *TypeBasedAnnotation) Annotate(tokens []*Token) []*Token {
for _, augTok := range tokens {
a.typeAnnotation(augTok)
}
return tokens
}
func (a *TypeBasedAnnotation) typeAnnotation(token *Token) {
chars := []rune(token.Tok)
if a.HasSentEndChars(token) {
token.SentBreak = true
} else if a.HasPeriodFinal(token) && !strings.HasSuffix(token.Tok, "..") {
tokNoPeriod := strings.ToLower(token.Tok[:len(chars)-1])
tokNoPeriodHypen := strings.Split(tokNoPeriod, "-")
tokLastHyphEl := string(tokNoPeriodHypen[len(tokNoPeriodHypen)-1])
if a.IsAbbr(tokNoPeriod, tokLastHyphEl) {
token.Abbr = true
} else {
token.SentBreak = true
}
}
}
/*
TokenBasedAnnotation performs a token-based classification (section 4) over the given
tokens, making use of the orthographic heuristic (4.1.1), collocation
heuristic (4.1.2) and frequent sentence starter heuristic (4.1.3).
*/
type TokenBasedAnnotation struct {
*Storage
PunctStrings
TokenParser
TokenGrouper
Ortho
}
// Annotate iterates groups tokens in pairs of two and then iterates over them to apply token annotation
func (a *TokenBasedAnnotation) Annotate(tokens []*Token) []*Token {
for _, tokPair := range a.TokenGrouper.Group(tokens) {
a.tokenAnnotation(tokPair[0], tokPair[1])
}
return tokens
}
func (a *TokenBasedAnnotation) tokenAnnotation(tokOne, tokTwo *Token) {
if tokTwo == nil {
return
}
if !a.TokenParser.HasPeriodFinal(tokOne) {
return
}
typ := a.TokenParser.TypeNoPeriod(tokOne)
nextTyp := a.TokenParser.TypeNoSentPeriod(tokTwo)
tokIsInitial := a.TokenParser.IsInitial(tokOne)
/*
[4.1.2. Collocation Heuristic] If there's a
collocation between the word before and after the
period, then label tok as an abbreviation and NOT
a sentence break. Note that collocations with
frequent sentence starters as their second word are
excluded in training.
*/
collocation := strings.Join([]string{typ, nextTyp}, ",")
if a.Collocations[collocation] != 0 {
tokOne.SentBreak = false
tokOne.Abbr = true
return
}
/*
[4.2. Token-Based Reclassification of Abbreviations] If
the token is an abbreviation or an ellipsis, then decide
whether we should *also* classify it as a sentbreak.
*/
if (tokOne.Abbr || a.TokenParser.IsEllipsis(tokOne)) && !tokIsInitial {
/*
[4.1.1. Orthographic Heuristic] Check if there's
orthogrpahic evidence about whether the next word
starts a sentence or not.
*/
isSentStarter := a.Ortho.Heuristic(tokTwo)
if isSentStarter == 1 {
tokOne.SentBreak = true
return
}
/*
[4.1.3. Frequent Sentence Starter Heruistic] If the
next word is capitalized, and is a member of the
frequent-sentence-starters list, then label tok as a
sentence break.
*/
if a.TokenParser.FirstUpper(tokTwo) && a.SentStarters[nextTyp] != 0 {
tokOne.SentBreak = true
return
}
}
/*
Sometimes there are two consecutive tokens with a lone "."
which probably means it is part of a spaced ellipsis ". . ."
so set those tokens and not sentence breaks
*/
if tokOne.Tok == "." && tokTwo.Tok == "." {
tokOne.SentBreak = false
tokTwo.SentBreak = false
return
}
/*
[4.3. Token-Based Detection of Initials and Ordinals]
Check if any initials or ordinals tokens that are marked
as sentbreaks should be reclassified as abbreviations.
*/
if tokIsInitial || typ == "##number##" {
isSentStarter := a.Ortho.Heuristic(tokTwo)
if isSentStarter == 0 {
tokOne.SentBreak = false
tokOne.Abbr = true
return
}
/*
Special heuristic for initials: if orthogrpahic
heuristc is unknown, and next word is always
capitalized, then mark as abbrev (eg: <NAME>).
*/
if isSentStarter == -1 &&
tokIsInitial &&
a.TokenParser.FirstUpper(tokTwo) &&
a.OrthoContext[nextTyp]&orthoLc == 0 {
tokOne.SentBreak = false
tokOne.Abbr = true
return
}
}
} | vendor/gopkg.in/neurosnap/sentences.v1/annotate.go | 0.656988 | 0.500793 | annotate.go | starcoder |
package ng
import (
"math/big"
)
func Gop_istmp(a interface{}) bool {
return false
}
// -----------------------------------------------------------------------------
type UntypedBigint *big.Int
type UntypedBigrat *big.Rat
type UntypedBigfloat *big.Float
type UntypedBigint_Default = Bigint
type UntypedBigrat_Default = Bigrat
type UntypedBigfloat_Default = Bigfloat
func UntypedBigint_Init__0(x int) UntypedBigint {
panic(makeCompilerHappy)
}
func UntypedBigrat_Init__0(x int) UntypedBigrat {
panic(makeCompilerHappy)
}
func UntypedBigrat_Init__1(x UntypedBigint) UntypedBigrat {
panic(makeCompilerHappy)
}
const (
makeCompilerHappy = "make compiler happy"
)
// -----------------------------------------------------------------------------
// type bigint
// A Bigint represents a signed multi-precision integer.
// The zero value for a Bigint represents nil.
type Bigint struct {
*big.Int
}
func tmpint(a, b Bigint) Bigint {
if Gop_istmp(a) {
return a
} else if Gop_istmp(b) {
return b
}
return Bigint{new(big.Int)}
}
func tmpint1(a Bigint) Bigint {
if Gop_istmp(a) {
return a
}
return Bigint{new(big.Int)}
}
// IsNil returns a bigint object is nil or not
func (a Bigint) IsNil() bool {
return a.Int == nil
}
// Gop_Add: func (a bigint) + (b bigint) bigint
func (a Bigint) Gop_Add(b Bigint) Bigint {
return Bigint{tmpint(a, b).Add(a.Int, b.Int)}
}
// Gop_Sub: func (a bigint) - (b bigint) bigint
func (a Bigint) Gop_Sub(b Bigint) Bigint {
return Bigint{tmpint(a, b).Sub(a.Int, b.Int)}
}
// Gop_Mul: func (a bigint) * (b bigint) bigint
func (a Bigint) Gop_Mul(b Bigint) Bigint {
return Bigint{tmpint(a, b).Mul(a.Int, b.Int)}
}
// Gop_Quo: func (a bigint) / (b bigint) bigint {
func (a Bigint) Gop_Quo(b Bigint) Bigint {
return Bigint{tmpint(a, b).Quo(a.Int, b.Int)}
}
// Gop_Rem: func (a bigint) % (b bigint) bigint
func (a Bigint) Gop_Rem(b Bigint) Bigint {
return Bigint{tmpint(a, b).Rem(a.Int, b.Int)}
}
// Gop_Or: func (a bigint) | (b bigint) bigint
func (a Bigint) Gop_Or(b Bigint) Bigint {
return Bigint{tmpint(a, b).Or(a.Int, b.Int)}
}
// Gop_Xor: func (a bigint) ^ (b bigint) bigint
func (a Bigint) Gop_Xor(b Bigint) Bigint {
return Bigint{tmpint(a, b).Xor(a.Int, b.Int)}
}
// Gop_And: func (a bigint) & (b bigint) bigint
func (a Bigint) Gop_And(b Bigint) Bigint {
return Bigint{tmpint(a, b).And(a.Int, b.Int)}
}
// Gop_AndNot: func (a bigint) &^ (b bigint) bigint
func (a Bigint) Gop_AndNot(b Bigint) Bigint {
return Bigint{tmpint(a, b).AndNot(a.Int, b.Int)}
}
// Gop_Lsh: func (a bigint) << (n untyped_uint) bigint
func (a Bigint) Gop_Lsh(n Gop_ninteger) Bigint {
return Bigint{tmpint1(a).Lsh(a.Int, uint(n))}
}
// Gop_Rsh: func (a bigint) >> (n untyped_uint) bigint
func (a Bigint) Gop_Rsh(n Gop_ninteger) Bigint {
return Bigint{tmpint1(a).Rsh(a.Int, uint(n))}
}
// Gop_LT: func (a bigint) < (b bigint) bool
func (a Bigint) Gop_LT(b Bigint) bool {
return a.Cmp(b.Int) < 0
}
// Gop_LE: func (a bigint) <= (b bigint) bool
func (a Bigint) Gop_LE(b Bigint) bool {
return a.Cmp(b.Int) <= 0
}
// Gop_GT: func (a bigint) > (b bigint) bool
func (a Bigint) Gop_GT(b Bigint) bool {
return a.Cmp(b.Int) > 0
}
// Gop_GE: func (a bigint) >= (b bigint) bool
func (a Bigint) Gop_GE(b Bigint) bool {
return a.Cmp(b.Int) >= 0
}
// Gop_EQ: func (a bigint) == (b bigint) bool
func (a Bigint) Gop_EQ(b Bigint) bool {
return a.Cmp(b.Int) == 0
}
// Gop_NE: func (a bigint) != (b bigint) bool
func (a Bigint) Gop_NE(b Bigint) bool {
return a.Cmp(b.Int) != 0
}
// Gop_Neg: func -(a bigint) bigint
func (a Bigint) Gop_Neg() Bigint {
return Bigint{tmpint1(a).Neg(a.Int)}
}
// Gop_Dup: func +(a bigint) bigint
func (a Bigint) Gop_Dup() Bigint {
return Bigint{new(big.Int).Set(a.Int)}
}
// Gop_Not: func ^(a bigint) bigint
func (a Bigint) Gop_Not() Bigint {
return Bigint{tmpint1(a).Not(a.Int)}
}
// Gop_Inc: func ++(b bigint)
func (a Bigint) Gop_Inc() {
a.Int.Add(a.Int, big1)
}
// Gop_Dec: func --(b bigint)
func (a Bigint) Gop_Dec() {
a.Int.Sub(a.Int, big1)
}
// Gop_AddAssign: func (a bigint) += (b bigint)
func (a Bigint) Gop_AddAssign(b Bigint) {
a.Int.Add(a.Int, b.Int)
}
// Gop_SubAssign: func (a bigint) -= (b bigint)
func (a Bigint) Gop_SubAssign(b Bigint) {
a.Int.Sub(a.Int, b.Int)
}
// Gop_MulAssign: func (a bigint) *= (b bigint)
func (a Bigint) Gop_MulAssign(b Bigint) {
a.Int.Mul(a.Int, b.Int)
}
// Gop_QuoAssign: func (a bigint) /= (b bigint) {
func (a Bigint) Gop_QuoAssign(b Bigint) {
a.Int.Quo(a.Int, b.Int)
}
// Gop_RemAssign: func (a bigint) %= (b bigint)
func (a Bigint) Gop_RemAssign(b Bigint) {
a.Int.Rem(a.Int, b.Int)
}
// Gop_OrAssign: func (a bigint) |= (b bigint)
func (a Bigint) Gop_OrAssign(b Bigint) {
a.Int.Or(a.Int, b.Int)
}
// Gop_XorAssign: func (a bigint) ^= (b bigint)
func (a Bigint) Gop_XorAssign(b Bigint) {
a.Int.Xor(a.Int, b.Int)
}
// Gop_AndAssign: func (a bigint) &= (b bigint)
func (a Bigint) Gop_AndAssign(b Bigint) {
a.Int.And(a.Int, b.Int)
}
// Gop_AndNotAssign: func (a bigint) &^= (b bigint)
func (a Bigint) Gop_AndNotAssign(b Bigint) {
a.Int.AndNot(a.Int, b.Int)
}
// Gop_LshAssign: func (a bigint) <<= (n untyped_uint)
func (a Bigint) Gop_LshAssign(n Gop_ninteger) {
a.Int.Lsh(a.Int, uint(n))
}
// Gop_RshAssign: func (a bigint) >>= (n untyped_uint)
func (a Bigint) Gop_RshAssign(n Gop_ninteger) {
a.Int.Rsh(a.Int, uint(n))
}
// -----------------------------------------------------------------------------
// Gop_Rcast: func int64(x bigint) int64
func (a Bigint) Gop_Rcast__0() int64 {
return a.Int64()
}
// Gop_Rcast: func int64(x bigint) (int64, bool)
func (a Bigint) Gop_Rcast__1() (int64, bool) {
return a.Int64(), a.IsInt64()
}
// Gop_Rcast: func uint64(x bigint) uint64
func (a Bigint) Gop_Rcast__2() uint64 {
return a.Uint64()
}
// Gop_Rcast: func uint64(x bigint) (uint64, bool)
func (a Bigint) Gop_Rcast__3() (uint64, bool) {
return a.Uint64(), a.IsUint64()
}
// Bigint_Cast: func bigint(x untyped_int) bigint
func Bigint_Cast__0(x int) Bigint {
return Bigint{big.NewInt(int64(x))}
}
// Bigint_Cast: func bigint(x untyped_bigint) bigint
func Bigint_Cast__1(x UntypedBigint) Bigint {
return Bigint{x}
}
// Bigint_Cast: func bigint(x int64) bigint
func Bigint_Cast__2(x int64) Bigint {
return Bigint{big.NewInt(x)}
}
// Bigint_Cast: func bigint(x uint64) bigint
func Bigint_Cast__3(x uint64) Bigint {
return Bigint{new(big.Int).SetUint64(x)}
}
// Bigint_Cast: func bigint(x uint) bigint
func Bigint_Cast__4(x uint) Bigint {
return Bigint{new(big.Int).SetUint64(uint64(x))}
}
// Bigint_Cast: func bigint(x *big.Int) bigint
func Bigint_Cast__5(x *big.Int) Bigint {
return Bigint{x}
}
// Bigint_Cast: func bigint(x *big.Rat) bigint
func Bigint_Cast__6(x *big.Rat) Bigint {
if x.IsInt() {
return Bigint{x.Num()}
}
ret, _ := new(big.Float).SetRat(x).Int(nil)
return Bigint{ret}
}
// Bigint_Cast: func bigint() bigint
func Bigint_Cast__7() Bigint {
return Bigint{new(big.Int)}
}
// Bigint_Init: func bigint.init(x int) bigint
func Bigint_Init__0(x int) Bigint {
return Bigint{big.NewInt(int64(x))}
}
// Bigint_Init: func bigint.init(x untyped_bigint) bigint
func Bigint_Init__1(x UntypedBigint) Bigint {
return Bigint{x}
}
// Bigint_Init: func bigint.init(x *big.Int) bigint
func Bigint_Init__2(x *big.Int) Bigint {
return Bigint{x}
}
// -----------------------------------------------------------------------------
// type bigrat
// A Bigrat represents a quotient a/b of arbitrary precision.
// The zero value for a Bigrat represents nil.
type Bigrat struct {
*big.Rat
}
func tmprat(a, b Bigrat) Bigrat {
if Gop_istmp(a) {
return a
} else if Gop_istmp(b) {
return b
}
return Bigrat{new(big.Rat)}
}
func tmprat1(a Bigrat) Bigrat {
if Gop_istmp(a) {
return a
}
return Bigrat{new(big.Rat)}
}
// IsNil returns a bigrat object is nil or not
func (a Bigrat) IsNil() bool {
return a.Rat == nil
}
// Gop_Assign: func (a bigrat) = (b bigrat)
func (a Bigrat) Gop_Assign(b Bigrat) {
if Gop_istmp(b) {
*a.Rat = *b.Rat
} else {
a.Rat.Set(b.Rat)
}
}
// Gop_Add: func (a bigrat) + (b bigrat) bigrat
func (a Bigrat) Gop_Add(b Bigrat) Bigrat {
return Bigrat{tmprat(a, b).Add(a.Rat, b.Rat)}
}
// Gop_Sub: func (a bigrat) - (b bigrat) bigrat
func (a Bigrat) Gop_Sub(b Bigrat) Bigrat {
return Bigrat{tmprat(a, b).Sub(a.Rat, b.Rat)}
}
// Gop_Mul: func (a bigrat) * (b bigrat) bigrat
func (a Bigrat) Gop_Mul(b Bigrat) Bigrat {
return Bigrat{tmprat(a, b).Mul(a.Rat, b.Rat)}
}
// Gop_Quo: func (a bigrat) / (b bigrat) bigrat
func (a Bigrat) Gop_Quo(b Bigrat) Bigrat {
return Bigrat{tmprat(a, b).Quo(a.Rat, b.Rat)}
}
// Gop_LT: func (a bigrat) < (b bigrat) bool
func (a Bigrat) Gop_LT(b Bigrat) bool {
return a.Cmp(b.Rat) < 0
}
// Gop_LE: func (a bigrat) <= (b bigrat) bool
func (a Bigrat) Gop_LE(b Bigrat) bool {
return a.Cmp(b.Rat) <= 0
}
// Gop_GT: func (a bigrat) > (b bigrat) bool
func (a Bigrat) Gop_GT(b Bigrat) bool {
return a.Cmp(b.Rat) > 0
}
// Gop_GE: func (a bigrat) >= (b bigrat) bool
func (a Bigrat) Gop_GE(b Bigrat) bool {
return a.Cmp(b.Rat) >= 0
}
// Gop_EQ: func (a bigrat) == (b bigrat) bool
func (a Bigrat) Gop_EQ(b Bigrat) bool {
return a.Cmp(b.Rat) == 0
}
// Gop_NE: func (a bigrat) != (b bigrat) bool
func (a Bigrat) Gop_NE(b Bigrat) bool {
return a.Cmp(b.Rat) != 0
}
// Gop_Neg: func -(a bigrat) bigrat
func (a Bigrat) Gop_Neg() Bigrat {
return Bigrat{tmprat1(a).Neg(a.Rat)}
}
// Gop_Dup: func +(a bigrat) bigrat
func (a Bigrat) Gop_Dup() Bigrat {
return Bigrat{new(big.Rat).Set(a.Rat)}
}
// Gop_Inv: func /(a bigrat) bigrat
func (a Bigrat) Gop_Inv() Bigrat {
return Bigrat{tmprat1(a).Inv(a.Rat)}
}
// Gop_Add: func (a bigrat) += (b bigrat)
func (a Bigrat) Gop_AddAssign(b Bigrat) {
a.Rat.Add(a.Rat, b.Rat)
}
// Gop_Sub: func (a bigrat) -= (b bigrat)
func (a Bigrat) Gop_SubAssign(b Bigrat) {
a.Rat.Sub(a.Rat, b.Rat)
}
// Gop_Mul: func (a bigrat) *= (b bigrat)
func (a Bigrat) Gop_MulAssign(b Bigrat) {
a.Rat.Mul(a.Rat, b.Rat)
}
// Gop_Quo: func (a bigrat) /= (b bigrat)
func (a Bigrat) Gop_QuoAssign(b Bigrat) {
a.Rat.Quo(a.Rat, b.Rat)
}
// -----------------------------------------------------------------------------
// Bigrat_Cast: func bigrat(x untyped_int) bigrat
func Bigrat_Cast__0(x int) Bigrat {
return Bigrat{big.NewRat(int64(x), 1)}
}
// Bigrat_Cast: func bigrat(a untyped_bigint) bigrat
func Bigrat_Cast__1(a UntypedBigint) Bigrat {
return Bigrat{new(big.Rat).SetInt(a)}
}
// Bigrat_Cast: func bigrat(a *big.Int) bigrat
func Bigrat_Cast__2(a *big.Int) Bigrat {
return Bigrat{new(big.Rat).SetInt(a)}
}
// Bigrat_Cast: func bigrat(a bigint) bigrat
func Bigrat_Cast__3(a Bigint) Bigrat {
return Bigrat{new(big.Rat).SetInt(a.Int)}
}
// Bigrat_Cast: func bigrat(a *big.Rat) bigrat
func Bigrat_Cast__4(a *big.Rat) Bigrat {
return Bigrat{a}
}
// Bigrat_Cast: func bigrat() bigrat
func Bigrat_Cast__5() Bigrat {
return Bigrat{new(big.Rat)}
}
// Bigrat_Cast: func bigrat(a, b int64) bigrat
func Bigrat_Cast__6(a, b int64) Bigrat {
return Bigrat{big.NewRat(a, b)}
}
// Bigrat_Init: func bigrat.init(x untyped_int) bigrat
func Bigrat_Init__0(x int) Bigrat {
return Bigrat{big.NewRat(int64(x), 1)}
}
// Bigrat_Init: func bigrat.init(x untyped_bigint) bigrat
func Bigrat_Init__1(x UntypedBigint) Bigrat {
return Bigrat{new(big.Rat).SetInt(x)}
}
// Bigrat_Init: func bigrat.init(x *big.Rat) bigrat
func Bigrat_Init__2(x *big.Rat) Bigrat {
return Bigrat{x}
}
// -----------------------------------------------------------------------------
// type bigfloat
// A Bigfloat represents a multi-precision floating point number.
// The zero value for a Float represents nil.
type Bigfloat struct {
*big.Float
}
// ----------------------------------------------------------------------------- | builtin/ng/big.go | 0.67822 | 0.468183 | big.go | starcoder |
package sprite
const Font_JR_A = `
XXXX
X X
X X
XXXXX
X X
X X
XX XX`
const Font_JR_B = `
XXXX
X X
X X
XXXXX
X X
X X
XXXXXX`
const Font_JR_C = `
XXX X
X XX
X
X
X
X X
XXXX`
const Font_JR_D = `
XXXXX
X X
X X
X X
X X
X X
XXXXXX`
const Font_JR_E = `
XXXXXXX
X X
X
XXX
X
X X
XXXXXXX`
const Font_JR_F = `
XXXXXXX
X X
X
XXX
X
X
XXX`
const Font_JR_G = `
XXX X
X XX
X
X
X XXX
X X
XXXXX`
const Font_JR_H = `
XXX XXX
X X
X X
XXXXX
X X
X X
XXX XXX`
const Font_JR_I = `
XXXX
X
X
X
X
X
XXXX`
const Font_JR_J = `
XXXXXXX
X X
X
X
XX X
X X
XXX`
const Font_JR_K = `
XXX XX
X X
X X
XXXX
X X
X X
XXX XX`
const Font_JR_L = `
XXX
X
X
X
X
X X
XXXXXXX`
const Font_JR_M = `
XX XX
XX XX
X X X
X X
X X
X X
XXX XXX`
const Font_JR_N = `
XX XXX
XX X
XX X
X X X
X XX
X XX
XXX XX`
const Font_JR_O = `
XXX
X X
X X
X X
X X
X X
XXX`
const Font_JR_P = `
XXXXX
X X
X X
XXXX
X
X
XXX`
const Font_JR_Q = `
XXX
X X
X X
X X
X X X
X X
XXX X`
const Font_JR_R = `
XXXXX
X X
X X
XXXX
X X
X X
XXX XXX`
const Font_JR_S = `
XXXX X
X XX
X
XXXXX
X
XX X
X XXXX`
const Font_JR_T = `
XXXXXXX
X X X
X
X
X
X
XXX`
const Font_JR_U = `
XXX XXX
X X
X X
X X
X X
X X
XXX`
const Font_JR_V = `
XXX XXX
X X
X X
X X
X X
XX
XX`
const Font_JR_W = `
XX XX
X X
X X
X X
X X X
XX XX
XX XX`
const Font_JR_X = `
XX XX
X X
X X
X
X X
X X
XX XX`
const Font_JR_Y = `
XXX XXX
X X
X X
XXX
X
X
XXX`
const Font_JR_Z = `
XXXXXXX
X X
X
XXX
X
X X
XXXXXXX`
const Font_JR_a = `
XXXX
X
XXXXX
X X
XXXX X`
const Font_JR_b = `
XX
X
XXXXX
X X
X X
X X
XXXXXX`
const Font_JR_c = `
XXXXX
X X
X
X
XXXXX`
const Font_JR_d = `
XX
X
XXXXX
X X
X X
X X
XXXXXX`
const Font_JR_e = `
XXXXX
X X
XXXXXXX
X
XXXXX`
const Font_JR_f = `
XXX
X X
XXX
X
X
X
XXX`
const Font_JR_g = `
XXXXXX
X X
X X
XXXXXX
X
XXXXXX`
const Font_JR_h = `
XX
X
XXXX
X X
X X
X X
XX XX`
const Font_JR_i = `
X
XXX
X
X
X
XXXX`
const Font_JR_j = `
X
XXXX
X X
X
X
X
XXX`
const Font_JR_k = `
XX
X X
X X
XXX
X X
X X
XX XX`
const Font_JR_l = `
XX
X
X
X
X
X
XX`
const Font_JR_m = `
XXX X
X X X
X X X
X X X
XX XX`
const Font_JR_n = `
XXXXX
X X
X X
X X
XX XX`
const Font_JR_o = `
XXXX
X X
X X
X X
XXXXX`
const Font_JR_p = `
XXXXXX
X X
X X
XXXXX
X
XX`
const Font_JR_q = `
XXXXXX
X X
X X
XXXXX
X
XX`
const Font_JR_r = `
XX XXX
XX X
X
X
XXX`
const Font_JR_s = `
XXXXX
X
XXXXX
X
XXXXX`
const Font_JR_t = `
X
XXXX
X
X
X
XX`
const Font_JR_u = `
XX XX
X X
X X
X X
XXX`
const Font_JR_v = `
XX XX
X X
X X
X X
XX`
const Font_JR_w = `
XX XX
X X X
X X X
X X X
XX X`
const Font_JR_x = `
XX XX
X X
X
X X
XX XX`
const Font_JR_y = `
XX XX
X X
X X
XXXX
X
XXXX`
const Font_JR_z = `
XXXXXXX
X XX
XXX
XX X
XXXXXXX`
const Font_JR_0 = `
XXX
X X
X X X
X X X
X X X
X X
XXX`
const Font_JR_1 = `
X
XX
X X
X
X
X
XXXXX`
const Font_JR_2 = `
XXXXX
X X
X
X
XXX
XX
XXXXXXX`
const Font_JR_3 = `
XXXXXXX
X X
X
XX
X
X X
XXXXX`
const Font_JR_4 = `
XX
X X
X X
X X
XXXXXXX
X
X`
const Font_JR_5 = `
XXXXXXX
X X
X
XXXXXX
X
X X
XXXXX`
const Font_JR_6 = `
XXXXX
X X
X
XXXXXX
X X
X X
XXXXX`
const Font_JR_7 = `
XXXXXXX
X X
X
X
X
X
X`
const Font_JR_8 = `
XXXXX
X X
X X
XXXXX
X X
X X
XXXXX`
const Font_JR_9 = `
XXXXX
X X
X X
XXXXXX
X
X X
XXXXX`
const Font_JR_period = `
XX
XX`
const Font_JR_comma = `
XX
XX
X`
const Font_JR_semicolon = `
XX
XX
XX
XX
X`
const Font_JR_colon = `
XX
XX
XX
XX`
const Font_JR_minus = `
XXXXX`
const Font_JR_plus = `
X
X
XXXXX
X
X`
const Font_JR_times = `
X
X X X
XXX
XXX
X X X
X`
const Font_JR_slash = `
X
X
X
X
X
X`
const Font_JR_percent = `
XX X
XX X
X
X
X XX
X XX`
const Font_JR_lt = `
X
X
X
X
X`
const Font_JR_gt = `
X
X
X
X
X`
const Font_JR_exclamation = `
XX
XX
X
X
XX
XX`
const Font_JR_question = `
XXXX
X XX
XX
XXX
XX
XX`
const Font_JR_down = `
X X
X X
X`
const Font_JR_up = `
X
X X
X X`
const Font_JR_l_bracket = `
XXX
X
X
X
X
X
XXX`
const Font_JR_r_bracket = `
XXX
X
X
X
X
X
XXX`
const Font_JR_l_paren = `
X
X
X
X
X
X
X`
const Font_JR_r_paren = `
X
X
X
X
X
X
X`
const Font_JR_l_brace = `
XX
X
X
X
X
X
XX`
const Font_JR_r_brace = `
XX
X
X
X
X
X
XX`
const Font_JR_sharp = `
X X
XXXXXX
X X
XXXXXX
X X`
const Font_JR_amp = `
XX
X X
X X
XXX
X X X
X X
XXXX X`
const Font_JR_equals = `
XXXXX
XXXXX`
const Font_JR_double_quot = `
XX XX
XX XX
X X`
const Font_JR_quot = `
XX
XX
X`
const Font_JR_at = `
XXX
X X
X XXX X
X X X X
X XXX
X
XXXX`
const Font_JR_pipe = `
X
X
X
X
X
X
X
X`
const Font_JR_b_slash = `
X
X
X
X
X
X`
const Font_JR_eszett = `
XX
X X
X X
X XX
X X
X X X
X XX
X`
const Font_JR_star = `
X X
XXX
X X
XXX
X X`
const Font_JR_underscore = `
XXXXXXXX`
const Font_JR_tilde = `
XXX X
X XXX`
const Font_JR_dollars = `
X
XXXXX
X X
XXXXX
X X
XXXXX
X`
// NewJRFont provides a font based upon <NAME>'s RPG Tileset
func NewJRFont() *Font {
m := map[rune]string{
'A': Font_JR_A,
'B': Font_JR_B,
'C': Font_JR_C,
'D': Font_JR_D,
'E': Font_JR_E,
'F': Font_JR_F,
'G': Font_JR_G,
'H': Font_JR_H,
'I': Font_JR_I,
'J': Font_JR_J,
'K': Font_JR_K,
'L': Font_JR_L,
'M': Font_JR_M,
'N': Font_JR_N,
'O': Font_JR_O,
'P': Font_JR_P,
'Q': Font_JR_Q,
'R': Font_JR_R,
'S': Font_JR_S,
'T': Font_JR_T,
'U': Font_JR_U,
'V': Font_JR_V,
'W': Font_JR_W,
'X': Font_JR_X,
'Y': Font_JR_Y,
'Z': Font_JR_Z,
'a': Font_JR_a,
'b': Font_JR_b,
'c': Font_JR_c,
'd': Font_JR_d,
'e': Font_JR_e,
'f': Font_JR_f,
'g': Font_JR_g,
'h': Font_JR_h,
'i': Font_JR_i,
'j': Font_JR_j,
'k': Font_JR_k,
'l': Font_JR_l,
'm': Font_JR_m,
'n': Font_JR_n,
'o': Font_JR_o,
'p': Font_JR_p,
'q': Font_JR_q,
'r': Font_JR_r,
's': Font_JR_s,
't': Font_JR_t,
'u': Font_JR_u,
'v': Font_JR_v,
'w': Font_JR_w,
'x': Font_JR_x,
'y': Font_JR_y,
'z': Font_JR_z,
'0': Font_JR_0,
'1': Font_JR_1,
'2': Font_JR_2,
'3': Font_JR_3,
'4': Font_JR_4,
'5': Font_JR_5,
'6': Font_JR_6,
'7': Font_JR_7,
'8': Font_JR_8,
'9': Font_JR_9,
'.': Font_JR_period,
',': Font_JR_comma,
';': Font_JR_semicolon,
':': Font_JR_colon,
'-': Font_JR_minus,
'+': Font_JR_plus,
'*': Font_JR_times,
'/': Font_JR_slash,
'%': Font_JR_percent,
'<': Font_JR_lt,
'>': Font_JR_gt,
'!': Font_JR_exclamation,
'?': Font_JR_question,
'∨': Font_JR_down, // unicode U+2228
'^': Font_JR_up,
'[': Font_JR_l_bracket,
']': Font_JR_r_bracket,
'(': Font_JR_l_paren,
')': Font_JR_r_paren,
'{': Font_JR_l_brace,
'}': Font_JR_r_brace,
'#': Font_JR_sharp,
'&': Font_JR_amp,
'=': Font_JR_equals,
'"': Font_JR_double_quot,
'\'': Font_JR_quot,
'@': Font_JR_at,
'|': Font_JR_pipe,
'\\': Font_JR_b_slash,
'ß': Font_JR_eszett,
'☆': Font_JR_star,
'_': Font_JR_underscore,
'~': Font_JR_tilde,
'$': Font_JR_dollars,
}
return NewFont(m, 8, 9)
} | font_jr.go | 0.512937 | 0.454654 | font_jr.go | starcoder |
package apicalypse
import (
"github.com/Henry-Sarabia/blank"
"github.com/pkg/errors"
"strconv"
"strings"
)
var (
// ErrMissingInput occurs when a function is called without input parameters (e.g. nil slice)
ErrMissingInput = errors.New("missing input parameters")
// ErrBlankArgument occurs when a function is called with a blank argument that should not be blank.
ErrBlankArgument = errors.New("a provided argument is blank or empty")
// ErrNegativeInput occurs when a function is called with a negative number that should not be negative.
ErrNegativeInput = errors.New("input cannot be a negative number")
)
// Option is a functional option type used to set the filters for an API query.
// Option is the first-order function returned by the available functional options
// (e.g. Fields or Limit). For the full list of supported filters and their expected
// syntax, please visit: https://apicalypse.io/syntax/
type Option func(map[string]string) error
// ComposeOptions composes multiple functional options into a single Option.
// This is primarily used to create a single functional option that can be used
// repeatedly across multiple queries.
func ComposeOptions(opts ...Option) Option {
return func(filters map[string]string) error {
for _, f := range opts {
if err := f(filters); err != nil {
return errors.Wrap(err, "cannot compose functional options")
}
}
return nil
}
}
// Fields is a functional option for setting the included fields in the results from a query.
func Fields(fields ...string) Option {
return func(filters map[string]string) error {
if len(fields) <= 0 {
return ErrMissingInput
}
for _, f := range fields {
if blank.Is(f) {
return ErrBlankArgument
}
}
f := strings.Join(fields, ",")
f = blank.Remove(f)
filters["fields"] = f
return nil
}
}
// Exclude is a functional option for setting the excluded fields in the results from a query.
func Exclude(fields ...string) Option {
return func(filters map[string]string) error {
if len(fields) <= 0 {
return ErrMissingInput
}
for _, f := range fields {
if blank.Is(f) {
return ErrBlankArgument
}
}
f := strings.Join(fields, ",")
f = blank.Remove(f)
filters["exclude"] = f
return nil
}
}
// Where is a functional option for setting a custom data filter similar to SQL.
// If multiple filters are provided, they are AND'd together.
// For the full list of filters and more information, visit: https://apicalypse.io/syntax/
func Where(custom ...string) Option {
return func(filters map[string]string) error {
if len(custom) <= 0 {
return ErrMissingInput
}
for _, c := range custom {
if blank.Is(c) {
return ErrBlankArgument
}
}
if f, ok := filters["where"]; ok {
custom = append(custom, f)
}
j := strings.Join(custom, " & ")
filters["where"] = j
return nil
}
}
// Limit is a functional option for setting the number of items to return from a query.
// This usually has a maximum limit.
func Limit(n int) Option {
return func(filters map[string]string) error {
if n < 0 {
return ErrNegativeInput
}
filters["limit"] = strconv.Itoa(n)
return nil
}
}
// Offset is a functional option for setting the index to start returning results from a query.
func Offset(n int) Option {
return func(filters map[string]string) error {
if n < 0 {
return ErrNegativeInput
}
filters["offset"] = strconv.Itoa(n)
return nil
}
}
// Sort is a functional option for sorting the results of a query by a certain field's
// values and the use of "asc" or "desc" to sort by ascending or descending order.
func Sort(field, order string) Option {
return func(filters map[string]string) error {
if blank.Is(field) || blank.Is(order) {
return ErrBlankArgument
}
filters["sort"] = field + " " + order
return nil
}
}
// Search is a functional option for searching for a value in a particular column of data.
// If the column is omitted, search will be performed on the default column.
func Search(column, term string) Option {
return func(filters map[string]string) error {
if blank.Is(term) {
return ErrBlankArgument
}
if !blank.Is(column) {
column = column + " "
}
filters["search"] = column + `"` + term + `"`
return nil
}
} | option.go | 0.681833 | 0.434341 | option.go | starcoder |
package tgmock
import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/nnqq/td/bin"
)
// TestingT is simplified *testing.T interface.
type TestingT interface {
require.TestingT
assert.TestingT
Helper()
Cleanup(cb func())
}
// Mock is a mock for tg.Invoker with testify/require support.
type Mock struct {
calls []Handler
assert assertions
}
// Option configures Mock.
type Option interface {
apply(t TestingT, m *Mock)
}
type assertions interface {
Truef(value bool, msg string, args ...interface{})
Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{})
}
type assertAssertions struct {
assert *assert.Assertions
}
func (a assertAssertions) Equal(expected, actual interface{}, msgAndArgs ...interface{}) {
a.assert.Equal(expected, actual, msgAndArgs...)
}
func (a assertAssertions) Truef(value bool, msg string, args ...interface{}) {
a.assert.Truef(value, msg, args...)
}
type optionFunc func(t TestingT, m *Mock)
func (o optionFunc) apply(t TestingT, m *Mock) { o(t, m) }
// WithRequire configures mock to use "require" assertions.
func WithRequire() Option {
return optionFunc(func(t TestingT, m *Mock) {
m.assert = require.New(t)
})
}
// NewRequire creates new Mock with "require" assertions.
func NewRequire(t TestingT) *Mock {
return New(t, WithRequire())
}
// New creates new Mock.
func New(t TestingT, options ...Option) *Mock {
m := &Mock{
assert: &assertAssertions{
assert: assert.New(t),
},
}
for _, o := range options {
o.apply(t, m)
}
t.Cleanup(func() {
m.assert.Truef(
m.AllWereMet(),
"not all expected calls happen (expected yet %d)",
len(m.calls),
)
})
return m
}
// AllWereMet returns true if all expected calls happened.
func (i *Mock) AllWereMet() bool {
return len(i.calls) == 0
}
func (i *Mock) add(h Handler) *Mock {
i.calls = append(i.calls, h)
return i
}
func (i *Mock) pop() (Handler, bool) {
if len(i.calls) < 1 {
return nil, false
}
h := i.calls[0]
// Delete from SliceTricks.
copy(i.calls, i.calls[1:])
i.calls[len(i.calls)-1] = nil
i.calls = i.calls[:len(i.calls)-1]
return h, true
}
// Handler returns HandlerFunc of Mock.
func (i *Mock) Handler() HandlerFunc {
return func(id int64, body bin.Encoder) (bin.Encoder, error) {
h, ok := i.pop()
i.assert.Truef(ok, "unexpected call")
return h.Handle(id, body)
}
} | tgmock/mock.go | 0.706393 | 0.437824 | mock.go | starcoder |
package client
import (
"encoding/binary"
"errors"
"fmt"
"io"
)
// Variable size structure prefix-header byte lengths
const (
CertificateLengthBytes = 3
PreCertificateLengthBytes = 3
ExtensionsLengthBytes = 2
)
// Reads a variable length array of bytes from |r|. |numLenBytes| specifies the
// number of (BigEndian) prefix-bytes which contain the length of the actual
// array data bytes that follow.
// Allocates an array to hold the contents and returns a slice view into it if
// the read was successful, or an error otherwise.
func readVarBytes(r io.Reader, numLenBytes int) ([]byte, error) {
var l uint64
switch {
case numLenBytes > 8:
return nil, fmt.Errorf("numLenBytes too large (%d)", numLenBytes)
case numLenBytes == 0:
return nil, errors.New("numLenBytes should be > 0")
}
// Read the length header bytes
for i := 0; i < numLenBytes; i++ {
l <<= 8
var t uint8
if err := binary.Read(r, binary.BigEndian, &t); err != nil {
return nil, err
}
l |= uint64(t)
}
data := make([]byte, l)
n, err := r.Read(data)
if err != nil {
return nil, err
}
if n != int(l) {
return nil, fmt.Errorf("short read: expected %d but got %d", l, n)
}
return data, nil
}
// Parses the byte-stream representation of a TimestampedEntry from |r| and populates
// the struct |t| with the data.
// See RFC section 3.4 for details on the format.
// Returns a non-nil error if there was a problem.
func ReadTimestampedEntryInto(r io.Reader, t *TimestampedEntry) error {
var err error
if err = binary.Read(r, binary.BigEndian, &t.Timestamp); err != nil {
return err
}
if err = binary.Read(r, binary.BigEndian, &t.EntryType); err != nil {
return err
}
switch t.EntryType {
case X509LogEntryType:
if t.X509Entry, err = readVarBytes(r, CertificateLengthBytes); err != nil {
return err
}
case PrecertLogEntryType:
if err := binary.Read(r, binary.BigEndian, &t.PrecertEntry.IssuerKeyHash); err != nil {
return err
}
if t.PrecertEntry.TBSCertificate, err = readVarBytes(r, PreCertificateLengthBytes); err != nil {
return err
}
default:
return fmt.Errorf("unknown EntryType: %d", t.EntryType)
}
t.Extensions, err = readVarBytes(r, ExtensionsLengthBytes)
return nil
}
// Parses the byte-stream representation of a MerkleTreeLeaf and returns a
// pointer to a new MerkleTreeLeaf structure containing the parsed data.
// See RFC section 3.4 for details on the format.
// Returns a pointer to a new MerkleTreeLeaf or non-nil error if there was a problem
func ReadMerkleTreeLeaf(r io.Reader) (*MerkleTreeLeaf, error) {
var m MerkleTreeLeaf
if err := binary.Read(r, binary.BigEndian, &m.Version); err != nil {
return nil, err
}
if m.Version != V1 {
return nil, fmt.Errorf("unknown Version %d", m.Version)
}
if err := binary.Read(r, binary.BigEndian, &m.LeafType); err != nil {
return nil, err
}
if m.LeafType != TimestampedEntryLeafType {
return nil, fmt.Errorf("unknown LeafType %d", m.LeafType)
}
if err := ReadTimestampedEntryInto(r, &m.TimestampedEntry); err != nil {
return nil, err
}
return &m, nil
} | go/client/serialization.go | 0.744378 | 0.406332 | serialization.go | starcoder |
package sources
import (
"fmt"
"github.com/ericr/solanalyzer/parser"
)
const (
// ExpressionUnknown represents an unknown expression.
ExpressionUnknown = iota
// ExpressionPrimary represents a primary expression.
ExpressionPrimary
// ExpressionNew represents a 'new' expression.
ExpressionNew
// ExpressionUnaryOperation represents a unary operation expression.
ExpressionUnaryOperation
// ExpressionParentheses represents a sub-expression in parentheses.
ExpressionParentheses
// ExpressionMemberAccess represents a member access expression.
ExpressionMemberAccess
// ExpressionBinaryOperation represents a binary operation expression.
ExpressionBinaryOperation
// ExpressionFunctionCall represents a function call expression.
ExpressionFunctionCall
// ExpressionIndexAccess represents an index access expression.
ExpressionIndexAccess
// ExpressionTernary represents a ternary expression.
ExpressionTernary
)
// Expression represents an expression in Solidity.
type Expression struct {
Tokens
SubType int
Operation string
MemberName string
TypeName *TypeName
Primary *PrimaryExpression
FunctionCallArgs *FunctionCallArguments
SubExpression *Expression
LeftExpression *Expression
RightExpression *Expression
IndexExpression *Expression
TernaryIf *Expression
TernaryThen *Expression
TernaryElse *Expression
}
// NewExpression returns a new instance of Expression.
func NewExpression() *Expression {
return &Expression{}
}
// Visit is called by a visitor.
func (e *Expression) Visit(ctx *parser.ExpressionContext) {
e.Start = ctx.GetStart()
e.Stop = ctx.GetStop()
switch ctx.GetChildCount() {
case 1:
primaryExpr := NewPrimaryExpression()
primaryExpr.Visit(ctx.PrimaryExpression().(*parser.PrimaryExpressionContext))
e.SubType = ExpressionPrimary
e.Primary = primaryExpr
case 2:
switch getText(ctx.GetChild(0)) {
case "new":
typeName := NewTypeName()
typeName.Visit(ctx.TypeName().(*parser.TypeNameContext))
e.SubType = ExpressionNew
e.TypeName = typeName
case "++", "--", "+", "-", "after", "delete", "!", "~":
expr := NewExpression()
expr.Visit(ctx.Expression(0).(*parser.ExpressionContext))
e.SubType = ExpressionUnaryOperation
e.Operation = getText(ctx.GetChild(0))
e.SubExpression = expr
default:
switch getText(ctx.GetChild(1)) {
case "++", "--":
expr := NewExpression()
expr.Visit(ctx.Expression(0).(*parser.ExpressionContext))
e.SubType = ExpressionUnaryOperation
e.Operation = getText(ctx.GetChild(1))
e.SubExpression = expr
default:
panic("Unknown expression(2)")
}
}
case 3:
if getText(ctx.GetChild(0)) == "(" && getText(ctx.GetChild(2)) == ")" {
expr := NewExpression()
expr.Visit(ctx.Expression(0).(*parser.ExpressionContext))
e.SubType = ExpressionParentheses
e.SubExpression = expr
return
}
switch getText(ctx.GetChild(1)) {
case ".":
expr := NewExpression()
expr.Visit(ctx.Expression(0).(*parser.ExpressionContext))
e.SubType = ExpressionMemberAccess
e.MemberName = getText(ctx.GetChild(2))
e.SubExpression = expr
case "**", "*", "/", "%", "+", "-", "<<", ">>", "&", "^", "|", "<", ">",
"<=", ">=", "==", "!=", "&&", "||", "=", "|=", "^=", "&=", "<<=", ">>=",
"+=", "-=", "*=", "/=", "%=":
leftExpr := NewExpression()
leftExpr.Visit(ctx.Expression(0).(*parser.ExpressionContext))
rightExpr := NewExpression()
rightExpr.Visit(ctx.Expression(1).(*parser.ExpressionContext))
e.SubType = ExpressionBinaryOperation
e.Operation = getText(ctx.GetChild(1))
e.LeftExpression = leftExpr
e.RightExpression = rightExpr
default:
panic("Unknown expression(3)")
}
case 4:
switch {
case getText(ctx.GetChild(1)) == "(" && getText(ctx.GetChild(3)) == ")":
expr := NewExpression()
expr.Visit(ctx.Expression(0).(*parser.ExpressionContext))
funCallArgs := NewFunctionCallArguments()
funCallArgs.Visit(ctx.FunctionCallArguments().(*parser.FunctionCallArgumentsContext))
e.SubType = ExpressionFunctionCall
e.SubExpression = expr
e.FunctionCallArgs = funCallArgs
case getText(ctx.GetChild(1)) == "[" && getText(ctx.GetChild(3)) == "]":
subExpr := NewExpression()
subExpr.Visit(ctx.Expression(0).(*parser.ExpressionContext))
if ctx.Expression(1) != nil {
indexExpr := NewExpression()
indexExpr.Visit(ctx.Expression(1).(*parser.ExpressionContext))
e.IndexExpression = indexExpr
}
e.SubType = ExpressionIndexAccess
e.SubExpression = subExpr
default:
panic("Unknown expression(4)")
}
case 5:
ifExpr := NewExpression()
ifExpr.Visit(ctx.Expression(0).(*parser.ExpressionContext))
thenExpr := NewExpression()
thenExpr.Visit(ctx.Expression(1).(*parser.ExpressionContext))
elseExpr := NewExpression()
elseExpr.Visit(ctx.Expression(2).(*parser.ExpressionContext))
e.SubType = ExpressionTernary
e.TernaryIf = ifExpr
e.TernaryThen = thenExpr
e.TernaryElse = elseExpr
}
}
func (e *Expression) String() string {
switch e.SubType {
case ExpressionPrimary:
return e.Primary.String()
case ExpressionNew:
return fmt.Sprintf("new %s", e.TypeName)
case ExpressionUnaryOperation:
return fmt.Sprintf("%s %s", e.Operation, e.SubExpression)
case ExpressionParentheses:
return fmt.Sprintf("(%s)", e.SubExpression)
case ExpressionMemberAccess:
return fmt.Sprintf("%s.%s", e.SubExpression, e.MemberName)
case ExpressionBinaryOperation:
return fmt.Sprintf("%s %s %s", e.LeftExpression, e.Operation, e.RightExpression)
case ExpressionFunctionCall:
return fmt.Sprintf("%s(%s)", e.SubExpression, e.FunctionCallArgs)
case ExpressionIndexAccess:
return fmt.Sprintf("%s[%s]", e.SubExpression, e.IndexExpression)
case ExpressionTernary:
return fmt.Sprintf("%s ? %s : %s", e.TernaryIf, e.TernaryThen, e.TernaryElse)
}
return "<unknown>"
} | sources/expression.go | 0.618435 | 0.439627 | expression.go | starcoder |
package models
import (
i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e "time"
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
)
// AssignmentReviewSettings
type AssignmentReviewSettings struct {
// The default decision to apply if the request is not reviewed within the period specified in durationInDays. The possible values are: acceptAccessRecommendation, keepAccess, removeAccess, and unknownFutureValue.
accessReviewTimeoutBehavior *AccessReviewTimeoutBehavior
// Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
additionalData map[string]interface{}
// The number of days within which reviewers should provide input.
durationInDays *int32
// Specifies whether to display recommendations to the reviewer. The default value is true
isAccessRecommendationEnabled *bool
// Specifies whether the reviewer must provide justification for the approval. The default value is true.
isApprovalJustificationRequired *bool
// If true, access reviews are required for assignments from this policy.
isEnabled *bool
// The interval for recurrence, such as monthly or quarterly.
recurrenceType *string
// If the reviewerType is Reviewers, this collection specifies the users who will be reviewers, either by ID or as members of a group, using a collection of singleUser and groupMembers.
reviewers []UserSetable
// Who should be asked to do the review, either Self or Reviewers.
reviewerType *string
// When the first review should start.
startDateTime *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time
}
// NewAssignmentReviewSettings instantiates a new assignmentReviewSettings and sets the default values.
func NewAssignmentReviewSettings()(*AssignmentReviewSettings) {
m := &AssignmentReviewSettings{
}
m.SetAdditionalData(make(map[string]interface{}));
return m
}
// CreateAssignmentReviewSettingsFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateAssignmentReviewSettingsFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewAssignmentReviewSettings(), nil
}
// GetAccessReviewTimeoutBehavior gets the accessReviewTimeoutBehavior property value. The default decision to apply if the request is not reviewed within the period specified in durationInDays. The possible values are: acceptAccessRecommendation, keepAccess, removeAccess, and unknownFutureValue.
func (m *AssignmentReviewSettings) GetAccessReviewTimeoutBehavior()(*AccessReviewTimeoutBehavior) {
if m == nil {
return nil
} else {
return m.accessReviewTimeoutBehavior
}
}
// GetAdditionalData gets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
func (m *AssignmentReviewSettings) GetAdditionalData()(map[string]interface{}) {
if m == nil {
return nil
} else {
return m.additionalData
}
}
// GetDurationInDays gets the durationInDays property value. The number of days within which reviewers should provide input.
func (m *AssignmentReviewSettings) GetDurationInDays()(*int32) {
if m == nil {
return nil
} else {
return m.durationInDays
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *AssignmentReviewSettings) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error))
res["accessReviewTimeoutBehavior"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetEnumValue(ParseAccessReviewTimeoutBehavior)
if err != nil {
return err
}
if val != nil {
m.SetAccessReviewTimeoutBehavior(val.(*AccessReviewTimeoutBehavior))
}
return nil
}
res["durationInDays"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetInt32Value()
if err != nil {
return err
}
if val != nil {
m.SetDurationInDays(val)
}
return nil
}
res["isAccessRecommendationEnabled"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetIsAccessRecommendationEnabled(val)
}
return nil
}
res["isApprovalJustificationRequired"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetIsApprovalJustificationRequired(val)
}
return nil
}
res["isEnabled"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetBoolValue()
if err != nil {
return err
}
if val != nil {
m.SetIsEnabled(val)
}
return nil
}
res["recurrenceType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetRecurrenceType(val)
}
return nil
}
res["reviewers"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateUserSetFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]UserSetable, len(val))
for i, v := range val {
res[i] = v.(UserSetable)
}
m.SetReviewers(res)
}
return nil
}
res["reviewerType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetStringValue()
if err != nil {
return err
}
if val != nil {
m.SetReviewerType(val)
}
return nil
}
res["startDateTime"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetTimeValue()
if err != nil {
return err
}
if val != nil {
m.SetStartDateTime(val)
}
return nil
}
return res
}
// GetIsAccessRecommendationEnabled gets the isAccessRecommendationEnabled property value. Specifies whether to display recommendations to the reviewer. The default value is true
func (m *AssignmentReviewSettings) GetIsAccessRecommendationEnabled()(*bool) {
if m == nil {
return nil
} else {
return m.isAccessRecommendationEnabled
}
}
// GetIsApprovalJustificationRequired gets the isApprovalJustificationRequired property value. Specifies whether the reviewer must provide justification for the approval. The default value is true.
func (m *AssignmentReviewSettings) GetIsApprovalJustificationRequired()(*bool) {
if m == nil {
return nil
} else {
return m.isApprovalJustificationRequired
}
}
// GetIsEnabled gets the isEnabled property value. If true, access reviews are required for assignments from this policy.
func (m *AssignmentReviewSettings) GetIsEnabled()(*bool) {
if m == nil {
return nil
} else {
return m.isEnabled
}
}
// GetRecurrenceType gets the recurrenceType property value. The interval for recurrence, such as monthly or quarterly.
func (m *AssignmentReviewSettings) GetRecurrenceType()(*string) {
if m == nil {
return nil
} else {
return m.recurrenceType
}
}
// GetReviewers gets the reviewers property value. If the reviewerType is Reviewers, this collection specifies the users who will be reviewers, either by ID or as members of a group, using a collection of singleUser and groupMembers.
func (m *AssignmentReviewSettings) GetReviewers()([]UserSetable) {
if m == nil {
return nil
} else {
return m.reviewers
}
}
// GetReviewerType gets the reviewerType property value. Who should be asked to do the review, either Self or Reviewers.
func (m *AssignmentReviewSettings) GetReviewerType()(*string) {
if m == nil {
return nil
} else {
return m.reviewerType
}
}
// GetStartDateTime gets the startDateTime property value. When the first review should start.
func (m *AssignmentReviewSettings) GetStartDateTime()(*i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time) {
if m == nil {
return nil
} else {
return m.startDateTime
}
}
// Serialize serializes information the current object
func (m *AssignmentReviewSettings) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
if m.GetAccessReviewTimeoutBehavior() != nil {
cast := (*m.GetAccessReviewTimeoutBehavior()).String()
err := writer.WriteStringValue("accessReviewTimeoutBehavior", &cast)
if err != nil {
return err
}
}
{
err := writer.WriteInt32Value("durationInDays", m.GetDurationInDays())
if err != nil {
return err
}
}
{
err := writer.WriteBoolValue("isAccessRecommendationEnabled", m.GetIsAccessRecommendationEnabled())
if err != nil {
return err
}
}
{
err := writer.WriteBoolValue("isApprovalJustificationRequired", m.GetIsApprovalJustificationRequired())
if err != nil {
return err
}
}
{
err := writer.WriteBoolValue("isEnabled", m.GetIsEnabled())
if err != nil {
return err
}
}
{
err := writer.WriteStringValue("recurrenceType", m.GetRecurrenceType())
if err != nil {
return err
}
}
if m.GetReviewers() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetReviewers()))
for i, v := range m.GetReviewers() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err := writer.WriteCollectionOfObjectValues("reviewers", cast)
if err != nil {
return err
}
}
{
err := writer.WriteStringValue("reviewerType", m.GetReviewerType())
if err != nil {
return err
}
}
{
err := writer.WriteTimeValue("startDateTime", m.GetStartDateTime())
if err != nil {
return err
}
}
{
err := writer.WriteAdditionalData(m.GetAdditionalData())
if err != nil {
return err
}
}
return nil
}
// SetAccessReviewTimeoutBehavior sets the accessReviewTimeoutBehavior property value. The default decision to apply if the request is not reviewed within the period specified in durationInDays. The possible values are: acceptAccessRecommendation, keepAccess, removeAccess, and unknownFutureValue.
func (m *AssignmentReviewSettings) SetAccessReviewTimeoutBehavior(value *AccessReviewTimeoutBehavior)() {
if m != nil {
m.accessReviewTimeoutBehavior = value
}
}
// SetAdditionalData sets the additionalData property value. Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well.
func (m *AssignmentReviewSettings) SetAdditionalData(value map[string]interface{})() {
if m != nil {
m.additionalData = value
}
}
// SetDurationInDays sets the durationInDays property value. The number of days within which reviewers should provide input.
func (m *AssignmentReviewSettings) SetDurationInDays(value *int32)() {
if m != nil {
m.durationInDays = value
}
}
// SetIsAccessRecommendationEnabled sets the isAccessRecommendationEnabled property value. Specifies whether to display recommendations to the reviewer. The default value is true
func (m *AssignmentReviewSettings) SetIsAccessRecommendationEnabled(value *bool)() {
if m != nil {
m.isAccessRecommendationEnabled = value
}
}
// SetIsApprovalJustificationRequired sets the isApprovalJustificationRequired property value. Specifies whether the reviewer must provide justification for the approval. The default value is true.
func (m *AssignmentReviewSettings) SetIsApprovalJustificationRequired(value *bool)() {
if m != nil {
m.isApprovalJustificationRequired = value
}
}
// SetIsEnabled sets the isEnabled property value. If true, access reviews are required for assignments from this policy.
func (m *AssignmentReviewSettings) SetIsEnabled(value *bool)() {
if m != nil {
m.isEnabled = value
}
}
// SetRecurrenceType sets the recurrenceType property value. The interval for recurrence, such as monthly or quarterly.
func (m *AssignmentReviewSettings) SetRecurrenceType(value *string)() {
if m != nil {
m.recurrenceType = value
}
}
// SetReviewers sets the reviewers property value. If the reviewerType is Reviewers, this collection specifies the users who will be reviewers, either by ID or as members of a group, using a collection of singleUser and groupMembers.
func (m *AssignmentReviewSettings) SetReviewers(value []UserSetable)() {
if m != nil {
m.reviewers = value
}
}
// SetReviewerType sets the reviewerType property value. Who should be asked to do the review, either Self or Reviewers.
func (m *AssignmentReviewSettings) SetReviewerType(value *string)() {
if m != nil {
m.reviewerType = value
}
}
// SetStartDateTime sets the startDateTime property value. When the first review should start.
func (m *AssignmentReviewSettings) SetStartDateTime(value *i336074805fc853987abe6f7fe3ad97a6a6f3077a16391fec744f671a015fbd7e.Time)() {
if m != nil {
m.startDateTime = value
}
} | models/assignment_review_settings.go | 0.616936 | 0.436442 | assignment_review_settings.go | starcoder |
package handler
var (
badgeUnknown = `<svg xmlns="http://www.w3.org/2000/svg" width="115" height="20">
<title>Djinn CI: unknown</title>
<rect width="100" height="20" fill="#383e51"/>
<rect x="53" width="60" height="20" fill="#6a7393"/>
<rect width="100" height="20" fill="url(#a)"/>
<g fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">
<text x="25" y="14">Djinn CI</text>
<text x="83" y="14">unknown</text>
</g>
</svg>`
badgeQueued = `<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20">
<title>Djinn CI: queued</title>
<rect width="100" height="20" fill="#383e51"/>
<rect x="53" width="54" height="20" fill="#272b39"/>
<rect width="100" height="20" fill="url(#a)"/>
<g fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">
<text x="25" y="14">Djinn CI</text>
<text x="78" y="14">queued</text>
</g>
</svg>`
badgeRunning = `<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20">
<title>Djinn CI: running</title>
<rect width="100" height="20" fill="#383e51"/>
<rect x="53" width="54" height="20" fill="#61a0ea"/>
<rect width="100" height="20" fill="url(#a)"/>
<g fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">
<text x="25" y="14">Djinn CI</text>
<text x="78" y="14">running</text>
</g>
</svg>`
badgePassed = `<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20">
<title>Djinn CI: passed</title>
<rect width="100" height="20" fill="#383e51"/>
<rect x="53" width="54" height="20" fill="#269326"/>
<rect width="100" height="20" fill="url(#a)"/>
<g fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">
<text x="25" y="14">Djinn CI</text>
<text x="78" y="14">passed</text>
</g>
</svg>`
badgePassedWithFailures = `<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20">
<title>Djinn CI: passed</title>
<rect width="100" height="20" fill="#383e51"/>
<rect x="53" width="54" height="20" fill="#ff7400"/>
<rect width="100" height="20" fill="url(#a)"/>
<g fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">
<text x="25" y="14">Djinn CI</text>
<text x="78" y="14">passed</text>
</g>
</svg>`
badgeFailed = `<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20">
<title>Djinn CI: failed</title>
<rect width="100" height="20" fill="#383e51"/>
<rect x="53" width="54" height="20" fill="#c64242"/>
<rect width="100" height="20" fill="url(#a)"/>
<g fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">
<text x="25" y="14">Djinn CI</text>
<text x="78" y="14">failed</text>
</g>
</svg>`
badgeKilled = `<svg xmlns="http://www.w3.org/2000/svg" width="105" height="20">
<title>Djinn CI: killed</title>
<rect width="100" height="20" fill="#383e51"/>
<rect x="53" width="54" height="20" fill="#c64242"/>
<rect width="100" height="20" fill="url(#a)"/>
<g fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">
<text x="25" y="14">Djinn CI</text>
<text x="78" y="14">killed</text>
</g>
</svg>`
badgeTimedOut = `<svg xmlns="http://www.w3.org/2000/svg" width="115" height="20">
<title>Djinn CI: timed out</title>
<rect width="100" height="20" fill="#383e51"/>
<rect x="53" width="63" height="20" fill="#6a7393"/>
<rect width="100" height="20" fill="url(#a)"/>
<g fill="#fff" text-anchor="middle" font-family="sans-serif" font-size="11">
<text x="25" y="14">Djinn CI</text>
<text x="83" y="14">timed out</text>
</g>
</svg>`
) | namespace/handler/badge.go | 0.621885 | 0.408218 | badge.go | starcoder |
package circuit
import (
// "os"
"log"
"regexp"
"strings"
"io/ioutil"
gc "github.com/rthornton128/goncurses"
"github.com/furryfaust/textelectronics/components"
)
var (
IO_CHECK = map[int]map[string]int {
0: map[string]int {
"com_x": -1, "com_y": 0, "type_x": 1, "type_y": 0, "x": 2, "y": 0,
},
1: map[string]int {
"com_x": 1, "com_y": 0, "type_x": -1, "type_y": 0, "x": -2, "y": 0,
},
2: map[string]int {
"com_x": 0, "com_y": -1, "type_x": 0, "type_y": 1, "x": 0, "y": 2,
},
3: map[string]int {
"com_x": 0, "com_y": 1, "type_x": 0, "type_y": -1, "x": 0, "y": -2,
},
}
)
type Circuit struct {
Components []components.Component
circuit [][]string
options Options
}
func NewCircuit(o Options) *Circuit {
circuit := &Circuit {}
circuit.options = o
circuit.Components = make([]components.Component, 0)
return circuit
}
func (c *Circuit) Run() {
c.prepare(c.options.Path)
c.parse()
c.assemble()
c.display()
}
func (c *Circuit) prepare(path string) {
dat, _ := ioutil.ReadFile(path)
lines := strings.Split(string(dat), "\n")
width := getLongestInSlice(lines) + 1
c.circuit = [][]string {}
c.circuit = append(c.circuit, make([]string, width))
for _, line := range lines {
chars := append([]string { " " }, strings.Split(line, "")...)
chars = append(chars, make([]string, width - len(line) + 1)...)
chars = append(chars, " ")
c.circuit = append(c.circuit, chars)
}
c.circuit = append(c.circuit, make([]string, width))
}
func getLongestInSlice(slice []string) (longest int) {
for _, s := range slice {
if len(s) > longest {
longest = len(s)
}
}
return
}
func (c *Circuit) parse() {
circuit := c.circuit
values := c.options.Values
for y := 0; y != len(circuit[0]); y++ {
for x := 0; x != len(circuit); x++ {
for _, rec := range c.options.Recognizers {
if found, id := c.recognizeComponent(x, y, rec.Blueprint()); found && id != "" {
com := rec.NewComponent(id, x, y, values)
c.Components = append(c.Components, com)
}
}
}
}
}
func (c *Circuit) recognizeComponent(x int, y int, blueprint [][]string) (found bool, id string) {
circuit := c.circuit
for i := 0; i != len(blueprint); i++ {
for j := 0; j != len(blueprint[i]); j++ {
if len(circuit) < x + i || len(circuit[i]) < y + j {
continue
}
if blueprint[i][j] == "" {
continue
}
if blueprint[i][j] == "." {
id = circuit[x + i][y + j]
continue
}
if circuit[x + i][y + j] != blueprint[i][j] {
found, id = false, ""
return
}
}
}
found = true
return
}
func (c *Circuit) getComponentById(id string) components.Component {
for _, com := range c.Components {
if com.Id() == id {
return com
}
}
return nil
}
func (c *Circuit) getComponentByLocation(x int, y int) components.Component {
for _, com := range c.Components {
cX, cY, cWidth, cHeight := com.Space()
if x >= cX && x <= cX + cWidth && y >= cY && y <= cY + cHeight {
return com
}
}
return nil
}
func contains(str string, slice []string) bool {
for _, s := range slice {
if s == str {
return true
}
}
return false
}
func (c *Circuit) recognizeIOType(x int, y int) (t string, id string, nx int, ny int, direction int) {
if x > 0 && len(c.circuit) - 1 > x && y < len(c.circuit[0]) && y > 0 {
for i := 0; i != 4; i++ {
mappings := IO_CHECK[i];
com := c.getComponentByLocation(x + mappings["com_x"], y + mappings["com_y"])
if com == nil {
continue
}
t = c.circuit[x + mappings["type_x"]][y + mappings["type_y"]]
if contains(t, com.OutputStreams()) || contains(t, com.InputStreams()) {
id, nx, ny, direction = com.Id(), x + mappings["x"], y + mappings["y"], i
return
}
t = ""
}
}
return
}
func (c *Circuit) assemble() {
for y := 0; y != len(c.circuit[0]); y++ {
for x := 0; x != len(c.circuit); x++ {
if c.circuit[x][y] != "%" {
continue
}
mio, mid, cX, cY, direction := c.recognizeIOType(x, y)
mcom := c.getComponentById(mid);
if !(mcom != nil && contains(mio, mcom.OutputStreams())) {
continue
}
c.connect(mcom, mio, cX, cY, direction)
}
}
}
func (c *Circuit) connect(mcom components.Component, mio string, x int, y int, direction int) {
var char string
switch direction {
case 0:
x++
if len(c.circuit) <= x {
break
}
char = c.circuit[x][y]
if match, _ := regexp.MatchString("[|a-zA-Z]", char); match {
c.connect(mcom, mio, x, y, direction)
}
if char == "%" {
fio, fid, _, _, _ := c.recognizeIOType(x, y)
if fid != "" {
fcom := c.getComponentById(fid)
fcom.Connect(mcom.Output(mio), fio)
}
}
if char == "+" {
c.connect(mcom, mio, x, y, 2)
c.connect(mcom, mio, x, y, 3)
c.connect(mcom, mio, x, y, direction)
}
if char == "-" && c.circuit[x + 1][y] == "|" {
c.connect(mcom, mio, x, y, direction)
}
case 1:
x--
if x < 0 {
break
}
char = c.circuit[x][y]
if match, _ := regexp.MatchString("[|a-zA-Z]", char); match {
c.connect(mcom, mio, x, y, direction)
}
if char == "%" {
fio, fid, _, _, _ := c.recognizeIOType(x, y)
if fid != "" {
fcom := c.getComponentById(fid)
fcom.Connect(mcom.Output(mio), fio)
}
}
if char == "+" {
c.connect(mcom, mio, x, y, 2)
c.connect(mcom, mio, x, y, 3)
c.connect(mcom, mio, x, y, direction)
}
if char == "-" && c.circuit[x - 1][y] == "|" {
c.connect(mcom, mio, x, y, direction)
}
case 2:
y++
if len(c.circuit[0]) <= y {
break
}
char = c.circuit[x][y]
if match, _ := regexp.MatchString("[-a-zA-Z]", char); match {
c.connect(mcom, mio, x, y, direction)
}
if char == "%" {
fio, fid, _, _, _ := c.recognizeIOType(x, y)
if fid != "" {
fcom := c.getComponentById(fid)
fcom.Connect(mcom.Output(mio), fio)
}
}
if char == "+" {
c.connect(mcom, mio, x, y, 0)
c.connect(mcom, mio, x, y, 1)
c.connect(mcom, mio, x, y, direction)
}
if char == "|" && c.circuit[x][y + 1] == "-" {
c.connect(mcom, mio, x, y, direction)
}
case 3:
y--
if y < 0 {
break
}
char = c.circuit[x][y]
if match, _ := regexp.MatchString("[-a-zA-Z]", char); match {
c.connect(mcom, mio, x, y, direction)
}
if char == "%" {
fio, fid, _, _, _ := c.recognizeIOType(x, y)
if fid != "" {
fcom := c.getComponentById(fid)
fcom.Connect(mcom.Output(mio), fio)
}
}
if char == "+" {
c.connect(mcom, mio, x, y, 0)
c.connect(mcom, mio, x, y, 1)
c.connect(mcom, mio, x, y, direction)
}
if char == "|" && c.circuit[x][y - 1] == "-" {
c.connect(mcom, mio, x, y, direction)
}
}
}
func (c *Circuit) display() {
stdscr, err := gc.Init()
if err != nil {
log.Println(err)
}
defer gc.End()
rows, cols := stdscr.MaxYX()
height, width := len(c.circuit) + 1, len(c.circuit[0]) + 1
y, x := (rows - height) / 2, (cols - width) / 2
var win *gc.Window
win, err = gc.NewWindow(height, width, y, x)
if err != nil {
log.Println(err)
}
defer win.Delete()
win.Timeout(500)
for i := 0; i != height - 1; i++ {
for j := 0; j != width - 1; j++ {
if c.circuit[i][j] == "" {
continue
}
char := gc.Char([]rune(c.circuit[i][j])[0])
win.MoveAddChar(i, j, char)
}
}
main:
for {
for _, com := range c.Components {
com.Update()
}
for _, com := range c.Components {
cx, cy, _, _ := com.Space()
for coord, out := range com.Visual() {
char := gc.Char([]rune(*out)[0])
win.MoveAddChar(cx + coord.X, cy + coord.Y, char)
}
}
win.NoutRefresh()
gc.Update()
switch win.GetChar() {
case 'q':
break main
}
}
} | circuit/circuit.go | 0.656328 | 0.449332 | circuit.go | starcoder |
package dither
import (
"image"
"image/color"
)
type Settings struct {
Filter [][]float32
}
type Dither struct {
Type string
Settings
}
func (dither Dither) Color(input image.Image, errorMultiplier float32) image.Image {
bounds := input.Bounds()
img := image.NewRGBA(bounds)
for x := bounds.Min.X; x < bounds.Dx(); x++ {
for y := bounds.Min.Y; y < bounds.Dy(); y++ {
pixel := input.At(x, y)
img.Set(x, y, pixel)
}
}
dx, dy := img.Bounds().Dx(), img.Bounds().Dy()
// Prepopulate multidimensional slices
redErrors := make([][]float32, dx)
greenErrors := make([][]float32, dx)
blueErrors := make([][]float32, dx)
for x := 0; x < dx; x++ {
redErrors[x] = make([]float32, dy)
greenErrors[x] = make([]float32, dy)
blueErrors[x] = make([]float32, dy)
for y := 0; y < dy; y++ {
redErrors[x][y] = 0
greenErrors[x][y] = 0
blueErrors[x][y] = 0
}
}
var qrr, qrg, qrb float32
for x := 0; x < dx; x++ {
for y := 0; y < dy; y++ {
r32, g32, b32, a := img.At(x, y).RGBA()
r, g, b := float32(uint8(r32)), float32(uint8(g32)), float32(uint8(b32))
r -= redErrors[x][y] * errorMultiplier
g -= greenErrors[x][y] * errorMultiplier
b -= blueErrors[x][y] * errorMultiplier
// Diffuse the error of each calculation to the neighboring pixels
if r < 128 {
qrr = -r
r = 0
} else {
qrr = 255 - r
r = 255
}
if g < 128 {
qrg = -g
g = 0
} else {
qrg = 255 - g
g = 255
}
if b < 128 {
qrb = -b
b = 0
} else {
qrb = 255 - b
b = 255
}
img.Set(x, y, color.RGBA{uint8(r), uint8(g), uint8(b), uint8(a)})
// Diffuse error in two dimension
ydim := len(dither.Filter) - 1
xdim := len(dither.Filter[0]) / 2
for xx := 0; xx < ydim+1; xx++ {
for yy := -xdim; yy <= xdim-1; yy++ {
if y+yy < 0 || dy <= y+yy || x+xx < 0 || dx <= x+xx {
continue
}
// Adds the error of the previous pixel to the current pixel
redErrors[x+xx][y+yy] += qrr * dither.Filter[xx][yy+ydim]
greenErrors[x+xx][y+yy] += qrg * dither.Filter[xx][yy+ydim]
blueErrors[x+xx][y+yy] += qrb * dither.Filter[xx][yy+ydim]
}
}
}
}
return img
} | dither_color.go | 0.510252 | 0.42919 | dither_color.go | starcoder |
package builtin
import "github.com/kode4food/ale/data"
// Add returns the sum of the provided numbers
var Add = data.Applicative(func(args ...data.Value) data.Value {
if len(args) > 0 {
var res = args[0].(data.Number)
for _, n := range args[1:] {
res = res.Add(n.(data.Number))
}
return res
}
return data.Integer(0)
})
// Sub will subtract one number from the previous, in turn
var Sub = data.Applicative(func(args ...data.Value) data.Value {
if len(args) > 1 {
var res = args[0].(data.Number)
var rest = args[1:]
for _, n := range rest {
res = res.Sub(n.(data.Number))
}
return res
}
return data.Integer(-1).Mul(args[0].(data.Number))
}, 1, data.OrMore)
// Mul will generate the product of all the provided numbers
var Mul = data.Applicative(func(args ...data.Value) data.Value {
var res data.Number = data.Integer(1)
for _, n := range args {
res = res.Mul(n.(data.Number))
}
return res
})
// Div will divide one number by the next, in turn
var Div = data.Applicative(func(args ...data.Value) data.Value {
var res = args[0].(data.Number)
for _, n := range args[1:] {
res = res.Div(n.(data.Number))
}
return res
}, 1, data.OrMore)
// Mod will produce the remainder of dividing one number by the next, in turn
var Mod = data.Applicative(func(args ...data.Value) data.Value {
var res = args[0].(data.Number)
for _, n := range args[1:] {
res = res.Mod(n.(data.Number))
}
return res
}, 1, data.OrMore)
// Eq returns whether the provided numbers are equal
var Eq = data.Applicative(func(args ...data.Value) data.Value {
var res = args[0].(data.Number)
for _, n := range args[1:] {
if res.Cmp(n.(data.Number)) != data.EqualTo {
return data.False
}
}
return data.True
}, 1, data.OrMore)
// Neq returns true if any of the numbers is not equal to the others
var Neq = data.Applicative(func(args ...data.Value) data.Value {
if Eq.Call(args...) == data.True {
return data.False
}
return data.True
}, 1, data.OrMore)
// Gt returns true if each number is greater than the previous
var Gt = data.Applicative(func(args ...data.Value) data.Value {
var l = args[0].(data.Number)
for _, v := range args[1:] {
r := v.(data.Number)
if l.Cmp(r) != data.GreaterThan {
return data.False
}
l = r
}
return data.True
}, 1, data.OrMore)
// Gte returns true if each number is greater than or equal to the previous
var Gte = data.Applicative(func(args ...data.Value) data.Value {
var l = args[0].(data.Number)
for _, v := range args[1:] {
r := v.(data.Number)
cmp := l.Cmp(r)
if !(cmp == data.GreaterThan || cmp == data.EqualTo) {
return data.False
}
l = r
}
return data.True
}, 1, data.OrMore)
// Lt returns true if each number is less than the previous
var Lt = data.Applicative(func(args ...data.Value) data.Value {
var l = args[0].(data.Number)
for _, v := range args[1:] {
r := v.(data.Number)
if l.Cmp(r) != data.LessThan {
return data.False
}
l = r
}
return data.True
}, 1, data.OrMore)
// Lte returns true if each number is less than or equal to the previous
var Lte = data.Applicative(func(args ...data.Value) data.Value {
var l = args[0].(data.Number)
for _, v := range args[1:] {
r := v.(data.Number)
cmp := l.Cmp(r)
if !(cmp == data.LessThan || cmp == data.EqualTo) {
return data.False
}
l = r
}
return data.True
}, 1, data.OrMore)
// IsNumber returns true if the provided value is a number
var IsNumber = data.Applicative(func(args ...data.Value) data.Value {
_, ok := args[0].(data.Number)
return data.Bool(ok)
}, 1)
// IsPosInf returns true if the provided number represents positive infinity
var IsPosInf = data.Applicative(func(args ...data.Value) data.Value {
if num, ok := args[0].(data.Number); ok {
return data.Bool(num.IsPosInf())
}
return data.False
}, 1)
// IsNegInf returns true if the provided number represents negative infinity
var IsNegInf = data.Applicative(func(args ...data.Value) data.Value {
if num, ok := args[0].(data.Number); ok {
return data.Bool(num.IsNegInf())
}
return data.False
}, 1)
// IsNaN returns true if the provided value is not a number
var IsNaN = data.Applicative(func(args ...data.Value) data.Value {
if num, ok := args[0].(data.Number); ok {
return data.Bool(num.IsNaN())
}
return data.False
}, 1) | core/internal/builtin/numeric.go | 0.702632 | 0.596786 | numeric.go | starcoder |
package orbit
import (
"math"
"github.com/dayaftereh/discover/server/mathf"
)
func OrbitFromParams(params *OrbitParameter) *Orbit {
params = extendParams(params)
rP := perifocalPosition(
*params.AngularMomentum,
*params.Eccentricity,
*params.TrueAnomaly,
*params.MU,
)
vP := perifocalVelocity(
*params.AngularMomentum,
*params.Eccentricity,
*params.TrueAnomaly,
*params.MU,
)
q := transformMatrix(
*params.ArgumentOfPeriapsis,
*params.Inclination,
*params.RightAscension,
)
r := q.MultiplyVec(rP)
v := q.MultiplyVec(vP)
return NewOrbit(r, v, *params.MU, *params.CentralBodyRadius)
}
func perifocalPosition(angularMomentum float64, eccentricity float64, trueAnomaly float64, mu float64) *mathf.Vec3 {
h := angularMomentum
e := eccentricity
theta := mathf.ToRadians(trueAnomaly)
return mathf.NewVec3(
math.Cos(theta), math.Sin(theta), 0.0,
).Multiply(
(math.Pow(h, 2.0) / mu) *
(1.0 / (1.0 + (e * math.Cos(theta)))))
}
func perifocalVelocity(angularMomentum float64, eccentricity float64, trueAnomaly float64, mu float64) *mathf.Vec3 {
h := angularMomentum
e := eccentricity
theta := mathf.ToRadians(trueAnomaly)
return mathf.NewVec3(
-math.Sin(theta), e+math.Cos(theta), 0.0,
).Multiply(mu / h)
}
func transformMatrix(argumentOfPeriapsis float64, inclination float64, rightAscension float64) *mathf.Mat3 {
w := mathf.ToRadians(argumentOfPeriapsis)
i := mathf.ToRadians(inclination)
omega := mathf.ToRadians(rightAscension)
sinOmega := math.Sin(omega)
cosOmega := math.Cos(omega)
sinI := math.Sin(i)
cosI := math.Cos(i)
sinW := math.Sin(w)
cosW := math.Cos(w)
return mathf.NewMat3(
-sinOmega*cosI*sinW+(cosOmega*cosW),
-sinOmega*cosI*cosW-(cosOmega*sinW),
sinOmega*sinI,
cosOmega*cosI*sinW+(sinOmega*cosW),
cosOmega*cosI*cosW-(sinOmega*sinW),
-cosOmega*sinI,
sinI*sinW,
sinI*cosW,
cosI,
)
}
func angularMomentumFromSemilatusRectum(semilatusRectum float64, mu float64) float64 {
return math.Sqrt(semilatusRectum * mu)
}
func semilatusRectumFromSemimajorAxisAndEccentricity(semimajorAxis float64, eccentricity float64) float64 {
return semimajorAxis * (1.0 - (math.Pow(eccentricity, 2.0)))
}
func semimajorAxisFromSemilatusRectumAndEccentricity(semilatusRectum float64, eccentricity float64) float64 {
return semilatusRectum / (1.0 - math.Pow(eccentricity, 2.0))
}
func semimajorAxisFromApogeeAndPerigee(apogee float64, perigee float64, centralBodyRadius float64) float64 {
return ((centralBodyRadius * 2.0) + apogee + perigee) / 2.0
}
func eccentricityFromSemimajorAxisAndPerigee(semimajorAxis float64, perigee float64, centralBodyRadius float64) float64 {
return (semimajorAxis / (centralBodyRadius + perigee)) - 1.0
} | server/mathf/orbit/parameter.go | 0.883374 | 0.494507 | parameter.go | starcoder |
package unityai
// Reference to navigation polygon.
type NavMeshPolyRef uint64
// Reference to navigation mesh tile.
type NavMeshTileRef uint64
const (
kPolyRefSaltBits NavMeshPolyRef = 16 // Number of salt bits in the poly/tile ID.
kPolyRefTileBits NavMeshPolyRef = 28 // Number of tile bits in the poly/tile ID.
kPolyRefPolyBits NavMeshPolyRef = 16 // Number of poly bits in the poly/tile ID.
kPolyRefTypeBits NavMeshPolyRef = 4 // Number of type bits in the poly/tile ID.
kPolyRefSaltMask NavMeshPolyRef = 1<<kPolyRefSaltBits - 1
kPolyRefTileMask NavMeshPolyRef = 1<<kPolyRefTileBits - 1
kPolyRefPolyMask NavMeshPolyRef = 1<<kPolyRefPolyBits - 1
kPolyRefTypeMask NavMeshPolyRef = 1<<kPolyRefTypeBits - 1
)
type NavMeshStatus uint32
// High level status.
const (
kNavMeshFailure NavMeshStatus = 1 << 31 // Operation failed.
kNavMeshSuccess NavMeshStatus = 1 << 30 // Operation succeed.
kNavMeshInProgress NavMeshStatus = 1 << 29 // Operation still in progress.
kNavMeshStatusDetailMask NavMeshStatus = 0x0ffffff
kNavMeshWrongMagic NavMeshStatus = 1 << 0 // Input data is not recognized.
kNavMeshWrongVersion NavMeshStatus = 1 << 1 // Input data is in wrong version.
kNavMeshOutOfMemory NavMeshStatus = 1 << 2 // Operation ran out of memory.
kNavMeshInvalidParam NavMeshStatus = 1 << 3 // An input parameter was invalid.
kNavMeshBufferTooSmall NavMeshStatus = 1 << 4 // Result buffer for the query was too small to store all results.
kNavMeshOutOfNodes NavMeshStatus = 1 << 5 // Query ran out of nodes during search.
kNavMeshPartialResult NavMeshStatus = 1 << 6 // Query did not reach the end location, returning best guess.
)
// Returns true of status is success.
func NavMeshStatusSucceed(status NavMeshStatus) bool {
return (status & kNavMeshSuccess) != 0
}
// Returns true of status is failure.
func NavMeshStatusFailed(status NavMeshStatus) bool {
return (status & kNavMeshFailure) != 0
}
// Returns true of status is in progress.
func NavMeshStatusInProgress(status NavMeshStatus) bool {
return (status & kNavMeshInProgress) != 0
}
// Returns true if specific detail is set.
func NavMeshStatusDetail(status NavMeshStatus, detail NavMeshStatus) bool {
return (status & detail) != 0
} | nav_mesh_types.go | 0.640411 | 0.429968 | nav_mesh_types.go | starcoder |
package model
import (
"fmt"
"github.com/mailru/easyjson/jlexer"
"strings"
"time"
)
// OANDA docs - http://developer.oanda.com/rest-live-v20/pricing-ep/
// A PriceBucket represents a price available for an amount of liquidity
type PriceBucket struct {
// The Price offered by the PriceBucket
Price PriceValue `json:"price"`
// The amount of liquidity offered by the PriceBucket
Liquidity int64 `json:"liquidity"`
}
// The specification of an Account-specific Price.
type ClientPrice struct {
// The string “PRICE”. Used to identify the a Price object when found in a stream.
Type string `json:"type"`
// The Price’s Instrument.
Instrument InstrumentName `json:"instrument"`
// The date/time when the Price was created
Time DateTime `json:"time"`
// Flag indicating if the Price is tradeable or not
Tradeable bool `json:"tradeable"`
// The list of prices and liquidity available on the Instrument’s bid side.
// It is possible for this list to be empty if there is no bid liquidity
// currently available for the Instrument in the Account.
Bids []PriceBucket `json:"bids"`
// The list of prices and liquidity available on the Instrument’s ask side.
// It is possible for this list to be empty if there is no ask liquidity
// currently available for the Instrument in the Account.
Asks []PriceBucket `json:"asks"`
// The closeout bid Price. This Price is used when a bid is required to
// closeout a Position (margin closeout or manual) yet there is no bid
// liquidity. The closeout bid is never used to open a new position.
CloseoutBid PriceValue `json:"closeoutBid"`
// The closeout ask Price. This Price is used when a ask is required to
// closeout a Position (margin closeout or manual) yet there is no ask
// liquidity. The closeout ask is never used to open a new position.
CloseoutAsk PriceValue `json:"closeoutAsk"`
}
// QuoteHomeConversionFactors represents the factors that can be used used to convert
// quantities of a Price’s Instrument’s quote currency into the Account’s home currency.
type QuoteHomeConversionFactors struct {
// The factor used to convert a positive amount of the Price’s Instrument’s
// quote currency into a positive amount of the Account’s home currency.
// Conversion is performed by multiplying the quote units by the conversion
// factor.
PositiveUnits DecimalNumber `json:"positiveUnits"`
// The factor used to convert a negative amount of the Price’s Instrument’s
// quote currency into a negative amount of the Account’s home currency.
// Conversion is performed by multiplying the quote units by the conversion
// factor.
NegativeUnits DecimalNumber `json:"negativeUnits"`
}
// A PricingHeartbeat object is injected into the Pricing stream to ensure that the
// HTTP connection remains active.
type PricingHeartbeat struct {
// The string “HEARTBEAT”
Type string `json:"type"`
// The date/time when the PricingHeartbeat was created.
Time DateTime `json:"time"`
}
// An instrument name, a granularity, and a price component to get candlestick data for.
// A string containing the following, all delimited by “:” characters:
// 1) InstrumentName
// 2) CandlestickGranularity
// 3) PricingComponent
// e.g. EUR_USD:S10:BM
type CandleSpecification string
func NewCandleSpecification(
instrument InstrumentName,
granularity CandlestickGranularity,
price PricingComponent,
) CandleSpecification {
return CandleSpecification(fmt.Sprintf("%s:%s:%s", instrument, granularity, price))
}
func (c CandleSpecification) Parse() (InstrumentName, string, PricingComponent) {
var (
s = string(c)
instrument InstrumentName
granularity string
component PricingComponent
)
i := 0
for ; i < len(s); i++ {
if s[i] == ':' {
instrument = InstrumentName(strings.TrimSpace(s[0:i]))
s = s[i+1:]
i = 0
break
}
}
for ; i < len(c); i++ {
if c[i] == ':' {
granularity = strings.TrimSpace(s[0:i])
component = PricingComponent(strings.TrimSpace(s[i+1:]))
break
}
}
return instrument, granularity, component
}
// HomeConversions represents the factors to use to convert quantities
// of a given currency into the Account’s home currency. The conversion factor depends
// on the scenario the conversion is required for.
type HomeConversions struct {
// The currency to be converted into the home currency.
Currency Currency `json:"currency"`
// The factor used to convert any gains for an Account in the specified
// currency into the Account’s home currency. This would include positive
// realized P/L and positive financing amounts. Conversion is performed by
// multiplying the positive P/L by the conversion factor.
AccountGain DecimalNumber `json:"accountGain"`
// The factor used to convert any losses for an Account in the specified
// currency into the Account’s home currency. This would include negative
// realized P/L and negative financing amounts. Conversion is performed by
// multiplying the positive P/L by the conversion factor.
AccountLoss DecimalNumber `json:"accountLoss"`
// The factor used to convert a Position or Trade Value in the specified
// currency into the Account’s home currency. Conversion is performed by
// multiplying the Position or Trade Value by the conversion factor.
PositionValue DecimalNumber `json:"positionValue"`
}
//easyjson:skip
type StreamClientPrice struct {
instrument [32]byte
Instrument []byte
Time time.Time
bids [8]StreamPriceBucket
Bids []StreamPriceBucket
asks [8]StreamPriceBucket
Asks []StreamPriceBucket
CloseoutBid float64
CloseoutAsk float64
Tradeable bool
IsHeartbeat bool
}
//easyjson:skip
type StreamPriceBucket struct {
// The Price offered by the PriceBucket
Price float64
// The amount of liquidity offered by the PriceBucket
Liquidity int64
}
func (out *StreamPriceBucket) UnmarshalEasyJSON(in *jlexer.Lexer) {
isTopLevel := in.IsStart()
if in.IsNull() {
if isTopLevel {
in.Consumed()
}
in.Skip()
return
}
in.Delim('{')
for !in.IsDelim('}') {
key := in.UnsafeFieldName(false)
in.WantColon()
if in.IsNull() {
in.Skip()
in.WantComma()
continue
}
switch key {
case "price":
out.Price = (PriceValue)(in.UnsafeString()).AsFloat64(0)
case "liquidity":
out.Liquidity = in.Int64()
default:
in.SkipRecursive()
}
in.WantComma()
}
in.Delim('}')
if isTopLevel {
in.Consumed()
}
}
func (out *StreamClientPrice) UnmarshalJSON(b []byte) {
in := &jlexer.Lexer{Data: b}
isTopLevel := in.IsStart()
if in.IsNull() {
if isTopLevel {
in.Consumed()
}
in.Skip()
return
}
in.Delim('{')
for !in.IsDelim('}') {
key := in.UnsafeFieldName(false)
in.WantColon()
if in.IsNull() {
in.Skip()
in.WantComma()
continue
}
switch key {
case "type":
s := string(in.String())
out.IsHeartbeat = s == "HEARTBEAT"
//out.Type = string(in.String())
case "instrument":
s := in.UnsafeString()
if len(s) > len(out.instrument) {
s = s[0:len(out.Instrument)]
}
out.Instrument = out.instrument[0:len(s)]
copy(out.Instrument, s)
case "time":
out.Time, _ = (DateTime)(in.UnsafeString()).Parse()
case "tradeable":
out.Tradeable = bool(in.Bool())
case "bids":
if in.IsNull() {
in.Skip()
out.Bids = nil
} else {
in.Delim('[')
out.Bids = out.bids[:0]
for !in.IsDelim(']') {
var v1 StreamPriceBucket
(v1).UnmarshalEasyJSON(in)
if len(out.Bids)+1 == cap(out.bids) {
bids := make([]StreamPriceBucket, len(out.Bids), len(out.Bids)+1)
copy(bids, out.Bids)
out.Bids = bids
}
out.Bids = append(out.Bids, v1)
in.WantComma()
}
in.Delim(']')
}
case "asks":
if in.IsNull() {
in.Skip()
out.Asks = nil
} else {
in.Delim('[')
out.Asks = out.asks[:0]
for !in.IsDelim(']') {
var v2 StreamPriceBucket
(v2).UnmarshalEasyJSON(in)
if len(out.Asks)+1 == cap(out.asks) {
asks := make([]StreamPriceBucket, len(out.Asks), len(out.Asks)+1)
copy(asks, out.Asks)
out.Asks = asks
}
out.Asks = append(out.Asks, v2)
in.WantComma()
}
in.Delim(']')
}
case "closeoutBid":
out.CloseoutBid = (PriceValue)(in.UnsafeString()).AsFloat64(0)
case "closeoutAsk":
out.CloseoutAsk = (PriceValue)(in.UnsafeString()).AsFloat64(0)
default:
in.SkipRecursive()
}
in.WantComma()
}
in.Delim('}')
if isTopLevel {
in.Consumed()
}
} | model/pricing.go | 0.572484 | 0.422088 | pricing.go | starcoder |
package engine
import (
"github.com/divVerent/aaaaxy/internal/level"
m "github.com/divVerent/aaaaxy/internal/math"
)
const (
// GameWidth is the width of the displayed game area.
GameWidth = 640
// GameHeight is the height of the displayed game area.
GameHeight = 360
// GameTPS is the game ticks per second.
GameTPS = 60
// sweepStep is the distance between visibility traces in pixels. Lower means worse performance.
sweepStep = 4
// numSweepTraces is the number of sweep operations we need.
numSweepTraces = 2 * (GameWidth + GameHeight) / sweepStep
// expandSize is the amount of pixels to expand the visible area by.
expandSize = 7
// blurSize is the amount of pixels to blur the visible area by.
blurSize = 5
// expandTiles is the number of tiles beyond tiles hit by a trace that may need to be displayed.
// As map design may need to take this into account, try to keep it at 1.
expandTiles = (expandSize + blurSize + sweepStep + level.TileSize - 1) / level.TileSize
// MinEntitySize is the smallest allowed entity size.
MinEntitySize = 8
// frameBlurSize is how much the previous frame is to be blurred.
frameBlurSize = 1
// frameDarkenAlpha is how much the previous frame is to be darkened relatively.
frameDarkenAlpha = 0.99
// frameDarkenAlpha is how much the previous frame is to be darkened absolutely.
frameDarkenAmount = 1.0 / 255.0
// How much to scroll towards focus point each frame.
scrollPerFrame = 0.1
// Minimum distance from screen edge when scrolling.
scrollMinDistance = 2 * level.TileSize
// Fully "fade in" in one second.
pixelsPerSpawnFrame = (GameWidth / 2) / 60
// borderWindowWidth is the maximum amount of pixels loaded outside the screen.
// Must be at least the largest entity width plus two tiles to cover for misalignment.
borderWindowWidth = 1264 + 2*level.TileSize
// borderWindowHeight is the maximum amount of pixels loaded outside the screen.
// Must be at least the largest entity height plus two tiles to cover for misalignment.
borderWindowHeight = 6480 + 2*level.TileSize
// tileWindowWidth is the maximum known width in tiles.
tileWindowWidth = (GameWidth+2*borderWindowWidth+level.TileSize-2)/level.TileSize + 1
// tileWindowHeight is the maximum known width in tiles.
tileWindowHeight = (GameHeight+2*borderWindowHeight+level.TileSize-2)/level.TileSize + 1
)
//expandStep is a single expansion step.
type expandStep struct {
from, from2, from3, to m.Delta
}
var (
// expandSteps is the list of steps to walk from each marked tile to expand.
expandSteps = []expandStep{
// First expansion tile.
{m.Delta{}, m.Delta{}, m.Delta{}, m.Delta{DX: 1, DY: 0}},
{m.Delta{}, m.Delta{}, m.Delta{}, m.Delta{DX: 0, DY: -1}},
{m.Delta{}, m.Delta{}, m.Delta{}, m.Delta{DX: -1, DY: 0}},
{m.Delta{}, m.Delta{}, m.Delta{}, m.Delta{DX: 0, DY: 1}},
{m.Delta{DX: 1, DY: 0}, m.Delta{DX: 0, DY: -1}, m.Delta{}, m.Delta{DX: 1, DY: -1}},
{m.Delta{DX: -1, DY: 0}, m.Delta{DX: 0, DY: -1}, m.Delta{}, m.Delta{DX: -1, DY: -1}},
{m.Delta{DX: -1, DY: 0}, m.Delta{DX: 0, DY: 1}, m.Delta{}, m.Delta{DX: -1, DY: 1}},
{m.Delta{DX: 1, DY: 0}, m.Delta{DX: 0, DY: 1}, m.Delta{}, m.Delta{DX: 1, DY: 1}},
}
) | internal/engine/constants.go | 0.524638 | 0.555556 | constants.go | starcoder |
package reflector
import (
"reflect"
"time"
"github.com/graphql-go/graphql"
)
var defaultTypeMap TypeMap
func init() {
defaultTypeMap = buildDefaultTypeMap()
}
// GetValueFromResolveParams gets the value of p, translating a graphql construct
// to a golang `reflect.Value`
func GetValueFromResolveParams(p graphql.ResolveParams) reflect.Value {
reflected := reflect.ValueOf(p.Source)
fieldName := p.Info.FieldName
value := findFieldByTag(reflect.Indirect(reflected), "json", GqlName(fieldName))
return value
}
func trivialResolver(p graphql.ResolveParams) (interface{}, error) {
value := GetValueFromResolveParams(p)
return value.Interface(), nil
}
func findFieldByTag(v reflect.Value, tagName string, fieldName GqlName) reflect.Value {
t := v.Type()
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
tag := GetFieldFirstTag(f, tagName)
if tag == string(fieldName) {
return v.Field(i)
}
}
return reflect.Value{}
}
// Format time as string in RFC3339
func timeResolver(p graphql.ResolveParams) (interface{}, error) {
value := GetValueFromResolveParams(p)
t := value.Interface().(time.Time)
return t.UTC().Format(time.RFC3339), nil
}
func buildDefaultTypeMap() TypeMap {
return TypeMap{
reflect.TypeOf(""): {
Output: graphql.String,
Resolver: trivialResolver,
},
reflect.TypeOf(int(5)): {
Output: graphql.Int,
Resolver: trivialResolver,
},
reflect.TypeOf(int8(5)): {
Output: graphql.Int,
Resolver: trivialResolver,
},
reflect.TypeOf(int16(5)): {
Output: graphql.Int,
Resolver: trivialResolver,
},
reflect.TypeOf(int32(5)): {
Output: graphql.Int,
Resolver: trivialResolver,
},
reflect.TypeOf(int64(5)): {
Output: graphql.Int,
Resolver: trivialResolver,
},
reflect.TypeOf(uint(5)): {
Output: graphql.Int,
Resolver: trivialResolver,
},
reflect.TypeOf(uint8(5)): {
Output: graphql.Int,
Resolver: trivialResolver,
},
reflect.TypeOf(uint16(5)): {
Output: graphql.Int,
Resolver: trivialResolver,
},
reflect.TypeOf(uint32(5)): {
Output: graphql.Int,
Resolver: trivialResolver,
},
reflect.TypeOf(uint64(5)): {
Output: graphql.Int,
Resolver: trivialResolver,
},
reflect.TypeOf(byte(5)): {
Output: graphql.Int,
Resolver: trivialResolver,
},
reflect.TypeOf(rune(5)): {
Output: graphql.Int,
Resolver: trivialResolver,
},
reflect.TypeOf(float32(5)): {
Output: graphql.Float,
Resolver: trivialResolver,
},
reflect.TypeOf(float64(5)): {
Output: graphql.Float,
Resolver: trivialResolver,
},
reflect.TypeOf(true): {
Output: graphql.Boolean,
Resolver: trivialResolver,
},
reflect.TypeOf(complex(float32(5), 5)): { // complex64
Output: graphql.String, // String repr is good enough for now
Resolver: trivialResolver, // example: (1+1i) (1real and 1img)
},
reflect.TypeOf(complex(float64(5), 5)): { // complex128
Output: graphql.String,
Resolver: trivialResolver,
},
reflect.TypeOf(time.Now()): {
Output: graphql.String,
Resolver: timeResolver,
},
}
}
// GetDefaultTypeMap returns a default type map, including all the native types
func GetDefaultTypeMap() TypeMap {
return defaultTypeMap
} | reflector/gql_reflector_builtin_types.go | 0.590307 | 0.44059 | gql_reflector_builtin_types.go | starcoder |
package data
import (
"fmt"
rt "git.townsourced.com/townsourced/gorethink"
"git.townsourced.com/townsourced/gorethink/types"
)
/*
LocationUnit defines units of measure for location based queries
*/
const (
LocationUnitMeter = "m"
LocationUnitKilometer = "km"
LocationUnitMile = "mi"
LocationUnitNauticalMile = "nm"
LocationUnitFoot = "ft"
)
// LatLng is a Latitude and Longitude grouping
type LatLng types.Point
// NewLatLng returns a new LatLng type for use with locations
func NewLatLng(latitude, longitude float64) (LatLng, error) {
ll := LatLng(types.Point{})
if longitude < -180 || longitude > 180 {
return ll, fmt.Errorf("Invalid longitude %f", longitude)
}
ll.Lon = longitude
if latitude < -90 || latitude > 90 {
return ll, fmt.Errorf("Invalid latitude %f", latitude)
}
ll.Lat = latitude
return ll, nil
}
func validateUnit(unit string) {
if unit != LocationUnitFoot && unit != LocationUnitKilometer && unit != LocationUnitMeter &&
unit != LocationUnitMile && unit != LocationUnitNauticalMile {
panic(fmt.Sprintf("Invalid location query unit %s", unit))
}
}
// LocationSearcher is an interface for searching based on location
type LocationSearcher interface {
query(t *table, index string, limit int) rt.Term
}
// DistanceSearch is a location search based on distance from a single point
type DistanceSearch struct {
point types.Point
latitude float64
longitude float64
unit string
maxDistance float64
}
// NewDistanceSearch creates a new distance search type
func NewDistanceSearch(latLng LatLng, maxDistance float64, unit string) *DistanceSearch {
validateUnit(unit)
return &DistanceSearch{
point: types.Point(latLng),
unit: unit,
maxDistance: maxDistance,
}
}
func (d *DistanceSearch) query(t *table, index string, limit int) rt.Term {
return t.GetNearest(d.point, rt.GetNearestOpts{
Index: index,
Unit: d.unit,
MaxResults: limit,
MaxDist: d.maxDistance,
}).Map(func(val rt.Term) rt.Term {
return val.Field("doc")
})
}
// AreaSearch is a location search for everything withing a rectangle area
type AreaSearch struct {
nw LatLng
ne LatLng
sw LatLng
se LatLng
}
// NewAreaSearch returns a new area search query
func NewAreaSearch(northBounds, southBounds, eastBounds, westBounds float64) (*AreaSearch, error) {
if northBounds == southBounds {
return nil, fmt.Errorf("North and South latitudes cannot be equal")
}
if eastBounds == westBounds {
return nil, fmt.Errorf("East and West longitudes cannot be equal")
}
if northBounds < southBounds {
southBounds, northBounds = northBounds, southBounds
}
if eastBounds < westBounds {
westBounds, eastBounds = eastBounds, westBounds
}
nw, err := NewLatLng(northBounds, westBounds)
if err != nil {
return nil, err
}
ne, err := NewLatLng(northBounds, eastBounds)
if err != nil {
return nil, err
}
sw, err := NewLatLng(southBounds, westBounds)
if err != nil {
return nil, err
}
se, err := NewLatLng(southBounds, eastBounds)
if err != nil {
return nil, err
}
//check for wraparound
if northBounds == 90 && southBounds == -90 {
return nil, fmt.Errorf("North and South latitudes cannot be equal")
}
if eastBounds == 180 && westBounds == -180 {
return nil, fmt.Errorf("East and West longitudes cannot be equal")
}
return &AreaSearch{
nw: nw,
ne: ne,
sw: sw,
se: se,
}, nil
}
func (a *AreaSearch) query(t *table, index string, limit int) rt.Term {
return t.GetIntersecting(rt.Polygon(types.Point(a.nw),
types.Point(a.ne),
types.Point(a.se),
types.Point(a.sw)), rt.GetIntersectingOpts{
Index: index,
})
} | data/location.go | 0.796055 | 0.417034 | location.go | starcoder |
package interpolator
import (
"math"
"github.com/urandom/drawgl"
"github.com/urandom/drawgl/operation/transform/matrix"
)
type kernel struct {
// Support is the kernel support and must be >= 0. At(t) is assumed to be
// zero when t >= Support.
Support float64
// At is the kernel function. It will only be called with t in the
// range [0, Support).
At func(t float64) float64
halfWidth, kernelArgScale [2]float64
weights [2][]float64
}
func newKernel(
src *drawgl.FloatImage,
m matrix.Matrix3,
) kernel {
i := kernel{}
xscale := abs(m[0][0])
if s := abs(m[0][1]); xscale < s {
xscale = s
}
yscale := abs(m[1][0])
if s := abs(m[1][1]); yscale < s {
yscale = s
}
i.halfWidth[0], i.halfWidth[1] = i.Support, i.Support
i.kernelArgScale[0], i.kernelArgScale[1] = 1.0, 1.0
if xscale > 1 {
i.halfWidth[0] *= xscale
i.kernelArgScale[0] = 1 / xscale
}
if yscale > 1 {
i.halfWidth[1] *= yscale
i.kernelArgScale[1] = 1 / yscale
}
i.weights[0] = make([]float64, 1+2*int(math.Ceil(i.halfWidth[0])))
i.weights[1] = make([]float64, 1+2*int(math.Ceil(i.halfWidth[1])))
return i
}
// Copy from golang.org/x/image/draw
// Copyright (c) 2009 The Go Authors. All rights reserved.
func (i kernel) Get(src *drawgl.FloatImage, fx, fy float64) drawgl.FloatColor {
b := src.Bounds()
totalWeights := [2]float64{}
fx -= 0.5
ix := int(math.Floor(fx - i.halfWidth[0]))
if ix < b.Min.X {
ix = b.Min.X
}
jx := int(math.Ceil(fx + i.halfWidth[1]))
if jx > b.Max.X {
jx = b.Max.X
}
for kx := ix; kx < jx; kx++ {
w := 0.0
if t := abs((fx - float64(kx)) * i.kernelArgScale[0]); t < i.Support {
w = i.At(t)
}
i.weights[0][kx-ix] = w
totalWeights[0] += w
}
for x := range i.weights[0][:jx-ix] {
i.weights[0][x] /= totalWeights[0]
}
fy -= 0.5
iy := int(math.Floor(fy - i.halfWidth[1]))
if iy < b.Min.Y {
iy = b.Min.Y
}
jy := int(math.Ceil(fy + i.halfWidth[1]))
if jy > b.Max.Y {
jy = b.Max.Y
}
for ky := iy; ky < jy; ky++ {
w := 0.0
if t := abs((fy - float64(ky)) * i.kernelArgScale[1]); t < i.Support {
w = i.At(t)
}
i.weights[1][ky-iy] = w
totalWeights[1] += w
}
for y := range i.weights[1][:jy-iy] {
i.weights[1][y] /= totalWeights[1]
}
var pr, pg, pb, pa drawgl.ColorValue
for ky := iy; ky < jy; ky++ {
if yw := i.weights[1][ky-iy]; yw != 0 {
for kx := ix; kx < jx; kx++ {
if xw := drawgl.ColorValue(i.weights[0][kx-ix] * yw); xw != 0 {
pi := (ky-b.Min.Y)*src.Stride + (kx-b.Min.X)*4
pr += src.Pix[pi+0] * xw
pg += src.Pix[pi+1] * xw
pb += src.Pix[pi+2] * xw
pa += src.Pix[pi+3] * xw
}
}
}
}
if pr > pa {
pr = pa
}
if pg > pa {
pg = pa
}
if pb > pa {
pb = pa
}
return drawgl.FloatColor{R: pr, G: pg, B: pb, A: pa}
}
func abs(x float64) float64 {
if x < 0 {
return -x
}
return x
} | interpolator/kernel.go | 0.648132 | 0.490419 | kernel.go | starcoder |
package common
import (
"github.com/OpenWhiteBox/primitives/matrix"
"github.com/OpenWhiteBox/primitives/random"
)
type Surface int
const (
Inside Surface = iota
Outside
)
type MaskType int
const (
RandomMask MaskType = iota
IdentityMask
)
type KeyGenerationOpts interface{}
// IndependentMasks generates the input and output masks independently of each other.
type IndependentMasks struct {
Input, Output MaskType
}
// SameMasks puts the exact same mask on the input and output of the white-box.
type SameMasks MaskType
// MatchingMasks implies a randomly generated input mask and the inverse mask on the output.
type MatchingMasks struct{}
// GenerateMasks generates input and output encodings for a white-box AES construction.
func GenerateMasks(rs *random.Source, opts KeyGenerationOpts, inputMask, outputMask *matrix.Matrix) {
switch opts.(type) {
case IndependentMasks:
*inputMask = generateMask(rs, opts.(IndependentMasks).Input, Inside)
*outputMask = generateMask(rs, opts.(IndependentMasks).Output, Outside)
case SameMasks:
mask := generateMask(rs, MaskType(opts.(SameMasks)), Inside)
*inputMask, *outputMask = mask, mask
case MatchingMasks:
mask := generateMask(rs, RandomMask, Inside)
*inputMask = mask
*outputMask, _ = mask.Invert()
default:
panic("Unrecognized key generation options!")
}
}
func generateMask(rs *random.Source, maskType MaskType, surface Surface) matrix.Matrix {
if maskType == RandomMask {
label := make([]byte, 16)
if surface == Inside {
copy(label[:], []byte("MASK Inside"))
return rs.Matrix(label, 128)
} else {
copy(label[:], []byte("MASK Outside"))
return rs.Matrix(label, 128)
}
} else { // Identity mask.
return matrix.GenerateIdentity(128)
}
}
// Generate byte/word mixing bijections.
// TODO: Ensure that blocks are full-rank.
func MixingBijection(rs *random.Source, size, round, position int) matrix.Matrix {
label := make([]byte, 16)
label[0], label[1], label[2], label[3], label[4] = 'M', 'B', byte(size), byte(round), byte(position)
return rs.Matrix(label, size)
}
type BlockMatrix struct {
Linear matrix.Matrix
Constant [16]byte
Position int
}
func (bm BlockMatrix) Get(i byte) (out [16]byte) {
r := make([]byte, 16)
r[bm.Position] = i
res := bm.Linear.Mul(matrix.Row(r))
copy(out[:], res)
for i, c := range bm.Constant {
out[i] ^= c
}
return
} | constructions/common/keygen_primitives.go | 0.637595 | 0.538073 | keygen_primitives.go | starcoder |
package spritesheet
import (
"errors"
"image"
"image/draw"
)
const (
DefaultImgsPerRow = 5
)
var (
ErrNoImages = errors.New("no images passed to the encoder")
ErrBadDimensions = errors.New("width and/or height of images passed is zero")
)
// NewAlpha returns new image.Alpha
func NewAlpha(r image.Rectangle) draw.Image {
return image.NewAlpha(r)
}
// NewAlpha returns new image.Alpha16
func NewAlpha16(r image.Rectangle) draw.Image {
return image.NewAlpha16(r)
}
// NewCMYK returns new image.CMYK
func NewCMYK(r image.Rectangle) draw.Image {
return image.NewCMYK(r)
}
// NewGrey returns new image.Grey
func NewGray(r image.Rectangle) draw.Image {
return image.NewGray(r)
}
// NewGray16 returns new image.Gray16
func NewGray16(r image.Rectangle) draw.Image {
return image.NewGray16(r)
}
// NewNRGBA returns new image.NRGBA
func NewNRGBA(r image.Rectangle) draw.Image {
return image.NewNRGBA(r)
}
// NewNRGBA64 returns new image.NRGBA64
func NewNRGBA64(r image.Rectangle) draw.Image {
return image.NewNRGBA64(r)
}
// NewRGBA returns new image.NRGBA64
func NewRGBA(r image.Rectangle) draw.Image {
return image.NewRGBA(r)
}
// NewRGBA64 returns new image.NewRGBA64
func NewRGBA64(r image.Rectangle) draw.Image {
return image.NewRGBA64(r)
}
// EncodeOpts provides the encoder the parameters it needs to create a sprite sheet
type EncodeOpts struct {
New func(r image.Rectangle) draw.Image // what format you want the new image to be, defaults to RGBA
ImgsPerRow int
}
// Encode takes a slice of images and based on the encode options will turn
// the images into a single sprite sheet.
// If the images are not all the same size, encode will take the max height
// and max width of any image and use that as its dimensions. For best look,
// all images should be the same size.
func Encode(images []image.Image, opts *EncodeOpts) (image.Image, error) {
images = removeNilImages(images)
if len(images) == 0 {
return nil, ErrNoImages
}
if opts == nil {
opts = &EncodeOpts{}
}
var (
imgsPerRow = imgsPerRow(opts.ImgsPerRow, len(images))
mw, mh = maxDimensions(images)
width, height = sheetDimensions(imgsPerRow, len(images), mw, mh)
)
if width == 0 || height == 0 {
return nil, ErrBadDimensions
}
var (
row, column int
sheet = newSheet(width, height, opts.New)
)
for i := range images {
var (
x, y = column * mw, row * mh // where we are at
bounds = images[i].Bounds() // current img bounds
subImage = image.Rect(x, y, x+bounds.Max.X, y+bounds.Max.Y) // sub rectagle
)
draw.Draw(sheet, subImage, images[i], bounds.Min, draw.Over)
column++
if column > imgsPerRow-1 {
row++
column = 0
}
}
return sheet, nil
}
// remove any nil interfaces
func removeNilImages(in []image.Image) (out []image.Image) {
out = make([]image.Image, 0, len(in))
for i := range in {
if in[i] != nil {
out = append(out, in[i])
}
}
return
}
func imgsPerRow(imgsPerRow, numOfImgs int) int {
if imgsPerRow == 0 {
imgsPerRow = DefaultImgsPerRow
}
if numOfImgs < imgsPerRow {
imgsPerRow = numOfImgs
}
return imgsPerRow
}
// sheetDimensions returns the dimensions of a new sprite sheet based on the number of images,
// images desired per row, and the max width and height of any of the images.
func sheetDimensions(imgsPerRow, numOfImgs, width, height int) (w int, h int) {
if width == 0 || imgsPerRow == 0 {
return // avoid div by 0
}
w = imgsPerRow * width
rows := numOfImgs / imgsPerRow
if numOfImgs%imgsPerRow != 0 {
rows++
}
h = height * rows
return
}
// newSheet creates a new sprite sheet ready to be "drawed" on based on desired widthXheight
// Defaults to using image.RGBA if no new function is provided.
func newSheet(width, height int, n func(rect image.Rectangle) draw.Image) draw.Image {
want := image.Rect(0, 0, width, height)
if n == nil { // default
return image.NewRGBA(want)
}
return n(want)
}
// maxDimensions goes through a slice of images and returns the max width and height
func maxDimensions(images []image.Image) (w, h int) {
if len(images) == 0 {
return
}
for i := range images {
if images[i] == nil {
continue
}
var (
size = images[i].Bounds().Size()
x, y = size.X, size.Y
)
if x > w {
w = x
}
if y > h {
h = y
}
}
return
} | encode.go | 0.763307 | 0.535159 | encode.go | starcoder |
package tracer
import (
"image"
"math"
"math/rand"
)
type Camera struct {
Eye, Direction, Up Vector
right Vector //vector pointing right
phi, theta float64 //latitude and longitude of look direction
imagePlaneWidth, imagePlaneHeight float64 //width and height of the view plane
distance float64 //camera distance from view plane
imagePlane *imagePlane
moveSpeed, lookSpeed float64
}
//Represents the upper and left border of the image plane
type imagePlane struct {
TopLeft Vector
UpperEdge, LeftEdge Vector
}
type CameraMoveDirection int
func NewCamera(eye, direction, up Vector, dImagePlane, imagePlaneWidth, imagePlaneHeight float64, moveSpeed, lookSpeed float64) *Camera {
direction = direction.Normalize()
phi, theta := directionToAngles(direction)
c := &Camera{
Eye: eye, Direction: direction, Up: up.Normalize(),
distance: dImagePlane, imagePlaneWidth: imagePlaneWidth, imagePlaneHeight: imagePlaneHeight,
moveSpeed: moveSpeed, lookSpeed: lookSpeed,
phi: phi, theta: theta,
}
c.updateImagePlane()
return c
}
func (c *Camera) GenerateRays(pixelDimensions, area image.Rectangle, aaFactor float64) []*RayInfo {
maxX, maxY := pixelDimensions.Dx(), pixelDimensions.Dy()
topLeft, upper, left := c.imagePlane.TopLeft, c.imagePlane.UpperEdge, c.imagePlane.LeftEdge
rayInfos := make([]*RayInfo, area.Dx()*area.Dy())
i := 0
for x := area.Min.X; x < area.Max.X; x++ {
for y := area.Min.Y; y < area.Max.Y; y++ {
vx := (float64(x) + 0.5 + rand.Float64()*aaFactor - aaFactor/2) / float64(maxX)
vy := (float64(y) + 0.5 + rand.Float64()*aaFactor - aaFactor/2) / float64(maxY)
p := topLeft.Add(upper.Multiply(vx)).Add(left.Multiply(vy))
direction := p.Subtract(c.Eye).Normalize()
rayInfo := &RayInfo{
Ray: Ray{Origin: c.Eye, Direction: direction},
X: x, Y: y,
}
rayInfos[i] = rayInfo
i++
}
}
return rayInfos
}
//x = strafe, y = forward/backward, z = up/down
func (c *Camera) Move(direction Vector) {
strafe := c.right.Multiply(direction.X * c.moveSpeed)
forward := c.Direction.Multiply(direction.Y * c.moveSpeed)
up := c.Up.Multiply(direction.Z * c.moveSpeed)
c.Eye = c.Eye.Add(strafe).Add(forward).Add(up)
c.updateImagePlane()
}
func (c *Camera) Rotate(deltaPhi, deltaTheta float64) {
c.phi += deltaPhi * c.lookSpeed
c.theta += deltaTheta * c.lookSpeed
if c.theta < 0 {
c.theta = 0
} else if c.theta > math.Pi {
c.theta = math.Pi
}
//calculate new direction vector
c.Direction = anglesToDirection(c.phi, c.theta)
c.updateImagePlane()
}
func anglesToDirection(phi, theta float64) Vector {
return NewVector(
math.Cos(phi)*math.Sin(theta),
math.Sin(phi)*math.Sin(theta),
math.Cos(theta),
)
}
func directionToAngles(direction Vector) (phi, theta float64) {
phi = math.Atan2(direction.Y, direction.X)
theta = math.Acos(direction.Z)
return phi, theta
}
func (c *Camera) updateImagePlane() {
center := c.Eye.Add(c.Direction.Multiply(c.distance))
left := c.Direction.Cross(Vector{0, 0, 1})
c.right = left.Multiply(-1)
c.Up = left.Cross(c.Direction)
c.imagePlane = &imagePlane{
TopLeft: center.Add(left.Multiply(c.imagePlaneWidth / 2)).Add(c.Up.Multiply(c.imagePlaneHeight / 2)),
UpperEdge: left.Multiply(-c.imagePlaneWidth),
LeftEdge: c.Up.Multiply(-c.imagePlaneHeight),
}
} | tracer/camera.go | 0.889084 | 0.850717 | camera.go | starcoder |
package structschema
import (
"context"
"fmt"
"reflect"
"strings"
"github.com/housecanary/gq/ast"
"github.com/housecanary/gq/schema"
)
func areTypesEqual(a, b ast.Type) bool {
if reflect.TypeOf(a) != reflect.TypeOf(b) {
return false
}
switch t := a.(type) {
case *ast.SimpleType:
return t.Name == (b.(*ast.SimpleType)).Name
case *ast.ListType:
return areTypesEqual(t.Of, (b.(*ast.ListType)).Of)
case *ast.NotNilType:
return areTypesEqual(t.Of, (b.(*ast.ListType)).Of)
}
panic("Unknown type")
}
func (m *fieldMeta) validateType(b *Builder, returnType reflect.Type) error {
schemaReturnType, err := b.goTypeToSchemaType(returnType)
if err != nil {
return err
}
expectedType := stripNotNil(m.GqlField.Type)
if !areTypesEqual(schemaReturnType, expectedType) {
return fmt.Errorf("Returned type of field %s is not compatible with schema type (got: %v, expected: %v)", m.Name, schemaReturnType.Signature(), expectedType.Signature())
}
return nil
}
func stripNotNil(typ ast.Type) ast.Type {
switch t := typ.(type) {
case *ast.NotNilType:
return stripNotNil(t.ContainedType())
case *ast.ListType:
return &ast.ListType{Of: stripNotNil(t.ContainedType())}
default:
return typ
}
}
func (m *fieldMeta) buildFieldResolver(b *Builder, structTyp reflect.Type, name string) error {
typeName := structTyp.Name()
pointerType := reflect.PtrTo(structTyp)
field, ok := structTyp.FieldByName(name)
if !ok {
return fmt.Errorf("Struct %s does not have field %s", structTyp.Name(), name)
}
index := field.Index
if err := m.validateType(b, field.Type); err != nil {
return fmt.Errorf("Error creating field resolver for %s:%s - %v", typeName, name, err)
}
isListType := field.Type.Kind() == reflect.Slice || field.Type.Kind() == reflect.Array
m.Resolver = schema.ContextResolver(func(ctx context.Context, v interface{}) (interface{}, error) {
rv := reflect.ValueOf(v)
if rv.Type() == pointerType {
rv = rv.Elem()
}
if rv.Type() != structTyp {
return nil, fmt.Errorf("%v(%T) was not of type %v", v, v, structTyp)
}
fv := rv.FieldByIndex(index)
kind := fv.Kind()
if fv.CanAddr() && kind != reflect.Ptr && !isListType {
fv = fv.Addr()
}
if isListType {
return toList(fv), nil
}
return fixNil(fv), nil
})
return nil
}
func (m *fieldMeta) buildMethodResolver(b *Builder, structTyp reflect.Type, name string) error {
typeName := structTyp.Name()
pointerType := reflect.PtrTo(structTyp)
var method *reflect.Method
for i := 0; i < pointerType.NumMethod(); i++ {
m := pointerType.Method(i)
if strings.EqualFold(m.Name, "resolve"+name) {
method = &m
}
}
if method == nil {
return fmt.Errorf("Cannot find a resolver method for field %s on struct %s: Expected a method of the form Resolve[Field Name]", name, structTyp.Name())
}
mTyp := method.Type
methodName := method.Name
argStart := 1 // Start at 1, the first param is the receiver
var argResolvers []argResolver
var needsResolverContext bool
for i := argStart; i < mTyp.NumIn(); i++ {
argType := mTyp.In(i)
if argType == resolverContextType {
argStart++
needsResolverContext = true
argResolvers = append(argResolvers, func(ctx context.Context) (reflect.Value, error) {
rc := ctx.(schema.ResolverContext)
return reflect.ValueOf(rc), nil
})
} else if argType == contextType {
argStart++
argResolvers = append(argResolvers, func(ctx context.Context) (reflect.Value, error) {
return reflect.ValueOf(ctx), nil
})
} else {
argSig := argType.String()
if argProvider, ok := b.argProviders[argSig]; ok {
argStart++
argResolvers = append(argResolvers, func(ctx context.Context) (reflect.Value, error) {
argVal := argProvider(ctx)
return reflect.ValueOf(argVal), nil
})
} else {
break
}
}
}
numNamedArgs := mTyp.NumIn() - argStart
if numNamedArgs != len(m.GqlField.ArgumentsDefinition) {
if !(numNamedArgs == 0 && needsResolverContext) { // We'll allow a mismatched arg signature if the resolver func takes a ResolverContext arg and no graphql named args
return fmt.Errorf("In type %s, field %s defines %v arguments, but method %s receives %v", typeName, name, len(m.GqlField.ArgumentsDefinition), methodName, numNamedArgs)
}
}
namedArgIndex := 0
for i := argStart; i < mTyp.NumIn(); i++ {
argTyp := mTyp.In(i)
_, err := b.goTypeToSchemaType(argTyp)
if err != nil {
return fmt.Errorf("Error resolving argument %d of resolver method for %s:%s: %v", i+1, typeName, name, err)
}
argDef := m.GqlField.ArgumentsDefinition[namedArgIndex]
argName := argDef.Name
argHasPointerType := argTyp.Kind() == reflect.Ptr
argResolvers = append(argResolvers, func(ctx context.Context) (reflect.Value, error) {
rc := ctx.(schema.ResolverContext)
v, err := rc.GetArgumentValue(argName)
if err != nil {
return reflect.ValueOf(nil), fmt.Errorf("Error resolving argument %s: %v", argName, err)
}
if v == nil {
return reflect.Zero(argTyp), nil
}
rv := reflect.ValueOf(v)
// If arg doesn't have a pointer type, need to indirect
if !argHasPointerType {
rv = reflect.Indirect(rv)
}
return rv, nil
})
namedArgIndex++
}
rh, err := m.makeResultHandler(b, mTyp, typeName, name)
if err != nil {
return fmt.Errorf("Error creating result handler on resolver method for %s:%s: %v", typeName, name, err)
}
receiverTyp := mTyp.In(0)
if len(argResolvers) == 0 {
// No args to resolve. Use a simple resolver
m.Resolver = schema.ContextResolver(func(ctx context.Context, v interface{}) (interface{}, error) {
receiver := coerceReceiver(reflect.ValueOf(v), receiverTyp)
fun := method.Func
args := []reflect.Value{receiver}
return rh(ctx, fun.Call(args)...)
})
} else if needsResolverContext || numNamedArgs > 0 {
m.Resolver = schema.FullResolver(func(ctx schema.ResolverContext, v interface{}) (interface{}, error) {
fun := method.Func
args := make([]reflect.Value, len(argResolvers)+1) // +1 to reserve space for receiver
receiver := coerceReceiver(reflect.ValueOf(v), receiverTyp)
args[0] = receiver
for i, ar := range argResolvers {
if a, err := ar(ctx); err == nil {
args[i+1] = a
} else {
return nil, err
}
}
return rh(ctx, fun.Call(args)...)
})
} else {
m.Resolver = schema.ContextResolver(func(ctx context.Context, v interface{}) (interface{}, error) {
fun := method.Func
receiver := coerceReceiver(reflect.ValueOf(v), receiverTyp)
args := make([]reflect.Value, len(argResolvers)+1) // +1 to reserve space for receiver
args[0] = receiver
for i, ar := range argResolvers {
if a, err := ar(ctx); err == nil {
args[i+1] = a
} else {
return nil, err
}
}
return rh(ctx, fun.Call(args)...)
})
}
return nil
}
func coerceReceiver(receiver reflect.Value, expected reflect.Type) reflect.Value {
rTyp := receiver.Type()
if rTyp != expected {
if expected.Kind() == reflect.Ptr && rTyp == expected.Elem() {
if receiver.CanAddr() {
receiver = receiver.Addr()
} else {
t := reflect.New(rTyp)
t.Elem().Set(receiver)
receiver = t
}
} else if rTyp.Kind() == reflect.Ptr && rTyp.Elem() == expected {
receiver = receiver.Elem()
} else {
panic(fmt.Errorf("Value not coercible to receiver: %v", receiver))
}
}
return receiver
}
func (m *fieldMeta) makeResultHandler(b *Builder, typ reflect.Type, typeName, fieldName string) (resultHandler, error) {
switch typ.NumOut() {
case 1:
out := typ.Out(0)
if out.Kind() == reflect.Chan {
if err := m.validateType(b, out.Elem()); err != nil {
return nil, err
}
return buildAsyncResultHandler(out.Elem(), typeName, fieldName), nil
} else if out.Kind() == reflect.Func {
asyncResultHandler, err := m.makeResultHandler(b, out, typeName, fieldName)
if err != nil {
return nil, err
}
return buildAsyncFuncResultHandler(asyncResultHandler, typeName, fieldName), nil
} else {
if err := m.validateType(b, out); err != nil {
return nil, err
}
return buildSimpleResultHandler(out), nil
}
case 2:
out := typ.Out(0)
if out.Kind() == reflect.Chan && typ.Out(1).Kind() == reflect.Chan {
if err := m.validateType(b, out.Elem()); err != nil {
return nil, err
}
return buildAsyncErrorResultHandler(out.Elem(), typeName, fieldName), nil
} else if typ.Out(1).AssignableTo(errorType) {
if err := m.validateType(b, out); err != nil {
return nil, err
}
return buildErrorResultHandler(out), nil
}
}
return nil, fmt.Errorf("Expected method return value to be one of (<value>) | (chan <value>) | (<value>, error) | (<-chan <value>, <-chan error) | (func () <value>) | (func () (<value>, error))")
}
type argResolver func(context.Context) (reflect.Value, error)
type funcAsyncValue struct {
f reflect.Value
asyncResultHandler resultHandler
ctx context.Context
}
func (v *funcAsyncValue) Await(ctx context.Context) (interface{}, error) {
return v.asyncResultHandler(v.ctx, v.f.Call(nil)...)
}
type chanAsyncValue struct {
typeName string
fieldName string
c reflect.Value
wrap func(reflect.Value) interface{}
}
func (v *chanAsyncValue) Await(ctx context.Context) (interface{}, error) {
rv, ok := v.c.Recv()
if !ok {
return nil, fmt.Errorf("Channel receive failed, closed prematurely")
}
if v.wrap != nil {
return v.wrap(rv), nil
}
return fixNil(rv), nil
}
type chanErrorAsyncValue struct {
typeName string
fieldName string
c reflect.Value
e reflect.Value
wrap func(reflect.Value) interface{}
}
func (v *chanErrorAsyncValue) Await(ctx context.Context) (interface{}, error) {
chosen, rv, ok := reflect.Select([]reflect.SelectCase{
reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: v.c,
},
reflect.SelectCase{
Dir: reflect.SelectRecv,
Chan: v.e,
},
})
switch chosen {
case 0:
if !ok {
errValue, errOk := v.e.Recv()
if !errOk {
return nil, fmt.Errorf("Channel receive failed: result closed and err closed")
}
return nil, fixNilE(errValue)
}
if v.wrap != nil {
return v.wrap(rv), nil
}
return fixNil(rv), nil
case 1:
if !ok {
resultValue, resultOk := v.e.Recv()
if !resultOk {
return nil, fmt.Errorf("Channel receive failed: err closed and result closed")
}
return fixNil(resultValue), nil
}
return nil, fixNilE(rv)
}
// Unreachable code
panic("Invalid selection")
}
type resultHandler func(ctx context.Context, result ...reflect.Value) (interface{}, error)
func fixNil(v reflect.Value) interface{} {
switch v.Kind() {
case reflect.Chan:
fallthrough
case reflect.Func:
fallthrough
case reflect.Interface:
fallthrough
case reflect.Map:
fallthrough
case reflect.Ptr:
fallthrough
case reflect.Slice:
if v.IsNil() {
return nil
}
}
return v.Interface()
}
func fixNilE(v reflect.Value) error {
switch v.Kind() {
case reflect.Chan:
fallthrough
case reflect.Func:
fallthrough
case reflect.Interface:
fallthrough
case reflect.Map:
fallthrough
case reflect.Ptr:
fallthrough
case reflect.Slice:
if v.IsNil() {
return nil
}
}
return v.Interface().(error)
}
type reflectListValue struct {
reflect.Value
}
func (v reflectListValue) ForEachElement(cb schema.ListValueCallback) {
for i := 0; i < v.Len(); i++ {
item := v.Index(i)
if item.Kind() == reflect.Ptr && item.IsNil() {
cb(nil)
} else {
cb(item.Interface())
}
}
}
func toList(v reflect.Value) schema.ListValue {
if v.IsNil() {
return nil
}
return reflectListValue{v}
}
func buildSimpleResultHandler(resultTyp reflect.Type) resultHandler {
if resultTyp.Kind() == reflect.Slice || resultTyp.Kind() == reflect.Array {
return func(ctx context.Context, result ...reflect.Value) (interface{}, error) {
rv := result[0]
return toList(rv), nil
}
}
return func(ctx context.Context, result ...reflect.Value) (interface{}, error) {
return fixNil(result[0]), nil
}
}
func buildErrorResultHandler(resultTyp reflect.Type) resultHandler {
if resultTyp.Kind() == reflect.Slice || resultTyp.Kind() == reflect.Array {
return func(ctx context.Context, result ...reflect.Value) (interface{}, error) {
return toList(result[0]), fixNilE(result[1])
}
}
return func(ctx context.Context, result ...reflect.Value) (interface{}, error) {
return fixNil(result[0]), fixNilE(result[1])
}
}
func buildAsyncResultHandler(resultTyp reflect.Type, typeName, fieldName string) resultHandler {
var wrap func(v reflect.Value) interface{}
if resultTyp.Kind() == reflect.Slice || resultTyp.Kind() == reflect.Array {
wrap = func(v reflect.Value) interface{} {
return toList(v)
}
}
return func(ctx context.Context, result ...reflect.Value) (interface{}, error) {
return &chanAsyncValue{typeName, fieldName, result[0], wrap}, nil
}
}
func buildAsyncErrorResultHandler(resultTyp reflect.Type, typeName, fieldName string) resultHandler {
var wrap func(v reflect.Value) interface{}
if resultTyp.Kind() == reflect.Slice || resultTyp.Kind() == reflect.Array {
wrap = func(v reflect.Value) interface{} {
return toList(v)
}
}
return func(ctx context.Context, result ...reflect.Value) (interface{}, error) {
return &chanErrorAsyncValue{typeName, fieldName, result[0], result[1], wrap}, nil
}
}
func buildAsyncFuncResultHandler(asyncResultHandler resultHandler, typeName, fieldName string) resultHandler {
return func(ctx context.Context, result ...reflect.Value) (interface{}, error) {
return &funcAsyncValue{result[0], asyncResultHandler, ctx}, nil
}
} | schema/structschema/resolver.go | 0.623492 | 0.464476 | resolver.go | starcoder |
package store
import (
"errors"
pb "github.com/yemingfeng/sdb/pkg/protobuf"
"math"
)
var idEmptyError = errors.New("id is empty")
var keyEmptyError = errors.New("key is empty")
// Collection is an abstraction of data structure, dataType = List/Set/SortedSet
// A Collection corresponds to a row containing
// Each row row takes rowKey as a unique value, rowKey = {dataType} + {key} + {id} is combined to form a unique value
// Each row contains N indices
// Each index uses indexKey as a unique value, indexKey = {dataType} + {key} + idx_{indexName} + {indexValue} + {id}
// Take ListCollection as an example, the key of the List is [l1], assuming that the Collection has 4 rows of Row, and each row of Row has the index of value and score
// Then each row of Row is as follows:
// { {key: l1}, {id: 1.1}, {value: aaa}, {score: 1.1}, indexes: [ {name: "value", value: aaa}, {name: "score", value: 1.1} ] }
// { {key: l1}, {id: 2.2}, {value: bbb}, {score: 2.2}, indexes: [ {name: "value", value: bbb}, {name: "score", value: 2.2} ] }
// { {key: l1}, {id: 3.3}, {value: ccc}, {score: 3.3}, indexes: [ {name: "value", value: ccc}, {name: "score", value: 3.3} ] }
// { {key: l1}, {id: 4.4}, {value: aaa}, {score: 4.4}, indexes: [ {name: "value", value: aaa}, {name: "score", value: 4.4} ] }
// Take the Row with id = 1.1 as an example, rowKey = 1/l1/1.1, valueIndexKey = 1/l1/idx_value/aaa/1.1, scoreIndexKey = 1/l1/idx_score/1.1/1.1 The written data is:
// rowKey: 1/l1/1.1 -> { {key: l1}, {id: 1.1}, {value: aaa}, {score: 1.1}, indexes: [ {name: "value", value: aaa}, {name: "score", value: 1.1} ] }
// valueIndexKey: 1/l1/idx_value/aaa/1.1, -> 1/l1/1.1
// scoreIndexKey: 1/l1/idx_score/1.1/1.1 -> 1/l1/1.1
type Collection struct {
dataType pb.DataType
}
// NewCollection create collection
func NewCollection(dataType pb.DataType) *Collection {
return &Collection{dataType: dataType}
}
// DelRowById delete row by id
func (collection *Collection) DelRowById(key []byte, id []byte, batch Batch) error {
existRow, err := collection.GetRowByIdWithBatch(key, id, batch)
if err != nil {
return err
}
return collection.DelRow(existRow, batch)
}
// DelRow delete row
func (collection *Collection) DelRow(row *Row, batch Batch) error {
if row == nil {
return nil
}
key := row.Key
id := row.Id
// delete exist indexes
for i := range row.Indexes {
index := row.Indexes[i]
err := batch.Del(indexKey(collection.dataType, key, index.Name, index.Value, id))
if err != nil {
return err
}
}
// delete row
return batch.Del(rowKey(collection.dataType, key, id))
}
// UpsertRow update or insert
func (collection *Collection) UpsertRow(row *Row, batch Batch) error {
if len(row.Key) == 0 {
return keyEmptyError
}
if len(row.Id) == 0 {
return idEmptyError
}
existRow, err := collection.GetRowByIdWithBatch(row.Key, row.Id, batch)
if err != nil {
return err
}
if existRow != nil {
err := collection.DelRow(existRow, batch)
if err != nil {
return err
}
}
rowKey := rowKey(collection.dataType, row.Key, row.Id)
for i := range row.Indexes {
index := row.Indexes[i]
err := batch.Set(indexKey(collection.dataType, row.Key, index.Name, index.Value, row.Id), rowKey)
if err != nil {
return err
}
}
rawRow, err := marshal(row)
if err != nil {
return err
}
return batch.Set(rowKey, rawRow)
}
// DelAll del all by key
func (collection *Collection) DelAll(key []byte, batch Batch) error {
return batch.Iterate(&PrefixIteratorOption{Prefix: rowKeyPrefix(collection.dataType, key), Offset: 0, Limit: math.MaxUint32},
func(rowKey []byte, rawRow []byte) error {
row, err := unmarshal(rawRow)
if err != nil {
return err
}
return collection.DelRow(row, batch)
})
}
// GetRowByIdWithBatch get row by id
func (collection *Collection) GetRowByIdWithBatch(key []byte, id []byte, batch Batch) (*Row, error) {
value, err := batch.Get(rowKey(collection.dataType, key, id))
if err != nil {
return nil, err
}
return unmarshal(value)
}
// GetRowById get row by id
func (collection *Collection) GetRowById(key []byte, id []byte) (*Row, error) {
batch := NewBatch()
defer batch.Close()
value, err := batch.Get(rowKey(collection.dataType, key, id))
if err != nil {
return nil, err
}
return unmarshal(value)
}
// ExistRowById check row exist
func (collection *Collection) ExistRowById(key []byte, id []byte) (bool, error) {
row, err := collection.GetRowById(key, id)
if err != nil {
return false, err
}
return row != nil, nil
}
// Count dataType + key
func (collection *Collection) Count(key []byte) (uint32, error) {
batch := NewBatch()
defer batch.Close()
count := uint32(0)
if err := batch.Iterate(&PrefixIteratorOption{Prefix: rowKeyPrefix(collection.dataType, key), Offset: 0, Limit: math.MaxUint32},
func(_ []byte, _ []byte) error {
count++
return nil
}); err != nil {
return 0, err
}
return count, nil
}
// Page dataType + key
func (collection *Collection) Page(key []byte, offset int32, limit uint32) ([]*Row, error) {
batch := NewBatch()
defer batch.Close()
rows := make([]*Row, 0)
if err := batch.Iterate(&PrefixIteratorOption{Prefix: rowKeyPrefix(collection.dataType, key), Offset: offset, Limit: limit},
func(_ []byte, rawRow []byte) error {
row, err := unmarshal(rawRow)
if err != nil {
return err
}
rows = append(rows, row)
return nil
}); err != nil {
return nil, err
}
return rows, nil
}
// PageWithBatch dataType + key
func (collection *Collection) PageWithBatch(key []byte, offset int32, limit uint32, batch Batch) ([]*Row, error) {
rows := make([]*Row, 0)
if err := batch.Iterate(&PrefixIteratorOption{Prefix: rowKeyPrefix(collection.dataType, key), Offset: offset, Limit: limit},
func(_ []byte, rawRow []byte) error {
row, err := unmarshal(rawRow)
if err != nil {
return err
}
rows = append(rows, row)
return nil
}); err != nil {
return nil, err
}
return rows, nil
}
// IndexPage page by index name
func (collection *Collection) IndexPage(key []byte, indexName []byte, offset int32, limit uint32) ([]*Row, error) {
batch := NewBatch()
defer batch.Close()
rows := make([]*Row, 0)
if err := batch.Iterate(&PrefixIteratorOption{Prefix: indexKeyPrefix(collection.dataType, key, indexName), Offset: offset, Limit: limit},
func(indexKey []byte, rowKey []byte) error {
rowRaw, err := batch.Get(rowKey)
if err != nil {
return err
}
row, err := unmarshal(rowRaw)
if err != nil {
return err
}
rows = append(rows, row)
return nil
}); err != nil {
return nil, err
}
return rows, nil
}
// IndexValuePage page by index value
func (collection *Collection) IndexValuePage(key []byte, indexName []byte, indexValue []byte, offset int32, limit uint32) ([]*Row, error) {
batch := NewBatch()
defer batch.Close()
rows := make([]*Row, 0)
if err := batch.Iterate(&PrefixIteratorOption{Prefix: indexKeyValuePrefix(collection.dataType, key, indexName, indexValue), Offset: offset, Limit: limit},
func(indexKey []byte, rowKey []byte) error {
rowRaw, err := batch.Get(rowKey)
if err != nil {
return err
}
row, err := unmarshal(rowRaw)
if err != nil {
return err
}
rows = append(rows, row)
return nil
}); err != nil {
return nil, err
}
return rows, nil
} | internal/store/collection.go | 0.684264 | 0.703607 | collection.go | starcoder |
package grid
import (
"upsilon_cities_go/lib/cities/map/pattern"
"upsilon_cities_go/lib/cities/node"
"upsilon_cities_go/lib/cities/nodetype"
)
//CompoundedGrid allow to acces to a grid overlay. accessor will provide data based on base + delta grid. Expect delta grid to be initialized with 0 ;)
type CompoundedGrid struct {
Base *Grid
Delta *Grid
}
//IsFilledP tell whether one can work on this location or not.
func (cg CompoundedGrid) IsFilledP(x int, y int, change nodetype.ChangeType) bool {
return cg.IsFilled(node.NP(x, y), change)
}
//IsFilled tell whether one can work on this location or not.
func (cg CompoundedGrid) IsFilled(location node.Point, change nodetype.ChangeType) bool {
n := cg.Base.Get(location)
return cg.NIsFilled(*n, change)
}
//IsDeltaFilled tell whether one can work on this location or not (in this delta).
func (cg CompoundedGrid) IsDeltaFilled(location node.Point, change nodetype.ChangeType) bool {
n := cg.Delta.Get(location)
return cg.NIsFilled(*n, change)
}
//NIsFilled tell whether one can work on this location or not.
func (cg CompoundedGrid) NIsFilled(n node.Node, change nodetype.ChangeType) bool {
switch change {
case nodetype.Any:
return n.Type != nodetype.None || n.Ground != cg.Base.Base || n.Landscape != nodetype.NoLandscape || n.IsStructure || n.IsRoad
case nodetype.Type:
return n.Type != nodetype.None
case nodetype.Ground:
return n.Ground != cg.Base.Base
case nodetype.Landscape:
return n.Landscape != nodetype.NoLandscape
case nodetype.Structure:
return n.IsStructure
case nodetype.Road:
return n.IsRoad
default:
return n.Type == nodetype.Filled
}
}
//Get will seek out a node.
func (cg CompoundedGrid) Get(location node.Point) node.Node {
n := cg.Delta.Get(location)
if n.Type == nodetype.None {
return *cg.Base.Get(location)
}
return *n
}
//GetP will seek out a node.
func (cg CompoundedGrid) GetP(x int, y int) node.Node {
n := *cg.Delta.GetP(x, y)
if !cg.NIsFilled(n, nodetype.Any) {
return *cg.Base.GetP(x, y)
}
return n
}
//SetPNT set NodeType value in delta, if there is nothing in delta.
func (cg *CompoundedGrid) SetPNT(x int, y int, typ nodetype.NodeType) {
n := cg.Delta.Get(node.NP(x, y))
if n != nil && n.Type == nodetype.None {
nn := *n
nn.Type = typ
cg.Set(nn, nodetype.Type)
}
}
//SetPGT set NodeType value in delta, if there is nothing in delta.
func (cg *CompoundedGrid) SetPGT(x int, y int, typ nodetype.GroundType) {
n := cg.Delta.Get(node.NP(x, y))
if n != nil && n.Type == nodetype.None {
nn := *n
nn.Ground = typ
cg.Set(nn, nodetype.Ground)
}
}
//SetPLT set LandscapeType value in delta, if there is nothing in delta.
func (cg *CompoundedGrid) SetPLT(x int, y int, typ nodetype.LandscapeType) {
n := cg.Delta.Get(node.NP(x, y))
if n != nil && n.Type == nodetype.None {
nn := *n
nn.Landscape = typ
cg.Set(nn, nodetype.Landscape)
}
}
//SetPRoad set Road value in delta, if there is nothing in delta.
func (cg *CompoundedGrid) SetPRoad(x int, y int, road bool) {
n := cg.Delta.Get(node.NP(x, y))
if n != nil && n.Type == nodetype.None {
nn := *n
nn.IsRoad = road
cg.Set(nn, nodetype.Road)
}
}
//SetPCity set LandscapeType value in delta, if there is nothing in delta.
func (cg *CompoundedGrid) SetPCity(x int, y int, cty bool) {
n := cg.Delta.Get(node.NP(x, y))
if n != nil && n.Type == nodetype.None {
nn := *n
nn.IsStructure = cty
cg.Set(nn, nodetype.Structure)
}
}
//Set set value in delta, if there is nothing in delta.
func (cg *CompoundedGrid) Set(n node.Node, change nodetype.ChangeType) {
if !cg.IsDeltaFilled(n.Location, change) {
nd := cg.Delta.Get(n.Location)
nd.Update(&n)
nd.Type = nodetype.Filled
}
}
//SetForce set value in delta.
func (cg *CompoundedGrid) SetForce(n node.Node) {
nd := cg.Delta.Get(n.Location)
nd.Update(&n)
nd.Type = nodetype.Filled
}
//Update set value in delta.
func (cg *CompoundedGrid) Update(n node.Node) {
nd := cg.Delta.Get(n.Location)
nd.Update(&n)
nd.Type = nodetype.Filled
}
//Compact base + delta
func (cg *CompoundedGrid) Compact() *Grid {
for idx, n := range cg.Delta.Nodes {
if n.Type == nodetype.Filled {
cg.Base.Nodes[idx].Update(&n)
}
}
for k, v := range cg.Delta.Cities {
cg.Base.Cities[k] = v
}
for k, v := range cg.Delta.LocationToCity {
cg.Base.LocationToCity[k] = v
}
cg.Delta = Create(cg.Base.Size, cg.Base.Base)
return cg.Base
}
//SelectPattern will select corresponding nodes in a grid based on pattern & location
func (cg *CompoundedGrid) SelectPattern(loc node.Point, pattern pattern.Pattern) []node.Node {
res := make([]node.Node, 0, len(pattern))
for _, v := range pattern.Apply(loc, cg.Base.Size) {
res = append(res, cg.Get(v))
}
return res
}
//SelectPatternMapBorders will select corresponding nodes in a grid based on pattern & location
func (cg *CompoundedGrid) SelectPatternMapBorders(loc node.Point, pattern pattern.Pattern) []node.Node {
res := make([]node.Node, 0, len(pattern))
for _, v := range pattern.ApplyBorders(loc, cg.Base.Size) {
res = append(res, cg.Get(v))
}
return res
}
//SelectMapBorders will retrieve nodes for map borders.
func (cg *CompoundedGrid) SelectMapBorders() []node.Node {
res := make([]node.Node, 0, cg.Base.Size*4)
for idx := 0; idx < cg.Base.Size; idx++ {
res = append(res, cg.Get(node.NP(idx, 0)))
res = append(res, cg.Get(node.NP(idx, cg.Base.Size-1)))
}
for idy := 0; idy < cg.Base.Size; idy++ {
res = append(res, cg.Get(node.NP(0, idy)))
res = append(res, cg.Get(node.NP(cg.Base.Size-1, idy)))
}
return res
}
//AccessibilityGrid generate an accessiblity grid from the compacted version of the grid. (wont alter current Base)
func (cg *CompoundedGrid) AccessibilityGrid() (res AccessibilityGridStruct) {
g := Create(cg.Base.Size, nodetype.Plain)
for idx, n := range cg.Base.Nodes {
g.Nodes[idx] = n
}
for idx, n := range cg.Delta.Nodes {
if n.Type != nodetype.None {
g.Nodes[idx] = n
}
}
return g.DefaultAccessibilityGrid()
} | lib/cities/map/grid/compounded_grid.go | 0.712632 | 0.407216 | compounded_grid.go | starcoder |
package aoc
import (
"bufio"
"io"
"regexp"
"strconv"
)
type Point struct {
X int
Y int
}
type Line struct {
First Point
Second Point
}
var (
linePattern *regexp.Regexp
)
func min(first int, second int) int {
if first < second {
return first
}
return second
}
func max(first int, second int) int {
if first > second {
return first
}
return second
}
func FindHorizontalOverlap(first Line, second Line) []Point {
if first.First.Y == second.First.Y {
// we have some overlap
leftX := max(first.First.X, second.First.X)
rightX := min(first.Second.X, second.Second.X)
if leftX <= rightX {
ret := make([]Point, rightX-leftX+1)
for i := 0; i < (rightX - leftX + 1); i++ {
ret[i] = Point{
X: leftX + i,
Y: first.First.Y,
}
}
return ret
}
}
return []Point{}
}
func FindVerticalOverlap(first Line, second Line) []Point {
if first.First.X == second.First.X {
// we have some overlap
leftY := max(first.First.Y, second.First.Y)
rightY := min(first.Second.Y, second.Second.Y)
if leftY <= rightY {
ret := make([]Point, rightY-leftY+1)
for i := 0; i < (rightY - leftY + 1); i++ {
ret[i] = Point{
X: first.First.X,
Y: leftY + i,
}
}
return ret
}
}
return []Point{}
}
func extractPoint(x string, y string) (Point, error) {
realX, err := strconv.Atoi(x)
if err != nil {
return Point{}, err
}
realY, err := strconv.Atoi(y)
if err != nil {
return Point{}, err
}
return Point{
X: realX,
Y: realY,
}, nil
}
func ReadLines(input io.Reader, pred func(Line) bool) ([]Line, error) {
ret := []Line{}
scanner := bufio.NewScanner(input)
for scanner.Scan() {
subs := linePattern.FindStringSubmatch(scanner.Text())
// fmt.Printf("subs = %v", subs)
first, err := extractPoint(subs[1], subs[2])
if err != nil {
return nil, err
}
second, err := extractPoint(subs[3], subs[4])
if err != nil {
return nil, err
}
line := Line{
First: first,
Second: second,
}
if pred(line) {
ret = append(ret, line)
}
}
return ret, nil
}
func init() {
var err error
linePattern, err = regexp.Compile(`^([0-9]+),([0-9]+) -> ([0-9]+),([0-9]+)$`)
if err != nil {
panic(err)
}
} | internal/aoc/vents.go | 0.571288 | 0.433262 | vents.go | starcoder |
// Package termstat provides a stats implementation which periodically logs the
// statistics to the given writer. It is meant to be used for testing and
// debugging at the terminal in lieu of an actual collector writing to an
// external tool like graphite or datadog. It provides stub implementations for
// some functionality.
package termstat
import (
"fmt"
"io"
"math/rand"
"strings"
"sync"
"time"
)
// Collector collects stats and prints them to the terminal
type Collector struct {
lock sync.Mutex
indexes map[string]int
names []string
stats []int64
changed bool
out io.Writer
}
// NewCollector initializes and returns a new TermStat.
func NewCollector(out io.Writer) *Collector {
ts := &Collector{
indexes: make(map[string]int),
out: out,
}
go func() {
tick := time.NewTicker(time.Second * 2)
for ; ; <-tick.C {
ts.write()
}
}()
return ts
}
// Count adds value to the named stat at the specified rate.
func (t *Collector) Count(name string, value int64, rate float64, tags ...string) {
t.lock.Lock()
t.changed = true
defer t.lock.Unlock()
idx, ok := t.indexes[name]
if !ok {
idx = len(t.stats)
t.stats = append(t.stats, 0)
t.names = append(t.names, name)
t.indexes[name] = idx
}
if rate < 1 {
if rand.Float64() > rate {
return
}
}
t.stats[idx] += value
}
func (t *Collector) write() {
sb := strings.Builder{}
t.lock.Lock()
if !t.changed {
t.lock.Unlock()
return
}
for i := 0; i < len(t.stats); i++ {
_, _ = sb.WriteString(fmt.Sprintf("%s: %d ", t.names[i], t.stats[i]))
}
t.changed = false
fmt.Fprintf(t.out, "\r"+sb.String())
t.lock.Unlock()
}
// Gauge does nothing.
func (t *Collector) Gauge(name string, value float64, rate float64, tags ...string) {}
// Histogram does nothing.
func (t *Collector) Histogram(name string, value float64, rate float64, tags ...string) {}
// Set does nothing.
func (t *Collector) Set(name string, value string, rate float64, tags ...string) {}
// Timing does nothing.
func (t *Collector) Timing(name string, value time.Duration, rate float64, tags ...string) {} | termstat/termstat.go | 0.668339 | 0.623406 | termstat.go | starcoder |
package openapi
import (
"encoding/json"
)
// VulnerabilityScoreSet struct for VulnerabilityScoreSet
type VulnerabilityScoreSet struct {
BaseScore *float64 `json:"BaseScore,omitempty"`
TemporalScore *float64 `json:"TemporalScore,omitempty"`
EnvironmentalScore *float64 `json:"EnvironmentalScore,omitempty"`
Vector *string `json:"Vector,omitempty"`
ProductID *[]string `json:"ProductID,omitempty"`
}
// NewVulnerabilityScoreSet instantiates a new VulnerabilityScoreSet 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 NewVulnerabilityScoreSet() *VulnerabilityScoreSet {
this := VulnerabilityScoreSet{}
return &this
}
// NewVulnerabilityScoreSetWithDefaults instantiates a new VulnerabilityScoreSet 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 NewVulnerabilityScoreSetWithDefaults() *VulnerabilityScoreSet {
this := VulnerabilityScoreSet{}
return &this
}
// GetBaseScore returns the BaseScore field value if set, zero value otherwise.
func (o *VulnerabilityScoreSet) GetBaseScore() float64 {
if o == nil || o.BaseScore == nil {
var ret float64
return ret
}
return *o.BaseScore
}
// GetBaseScoreOk returns a tuple with the BaseScore field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *VulnerabilityScoreSet) GetBaseScoreOk() (*float64, bool) {
if o == nil || o.BaseScore == nil {
return nil, false
}
return o.BaseScore, true
}
// HasBaseScore returns a boolean if a field has been set.
func (o *VulnerabilityScoreSet) HasBaseScore() bool {
if o != nil && o.BaseScore != nil {
return true
}
return false
}
// SetBaseScore gets a reference to the given float64 and assigns it to the BaseScore field.
func (o *VulnerabilityScoreSet) SetBaseScore(v float64) {
o.BaseScore = &v
}
// GetTemporalScore returns the TemporalScore field value if set, zero value otherwise.
func (o *VulnerabilityScoreSet) GetTemporalScore() float64 {
if o == nil || o.TemporalScore == nil {
var ret float64
return ret
}
return *o.TemporalScore
}
// GetTemporalScoreOk returns a tuple with the TemporalScore field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *VulnerabilityScoreSet) GetTemporalScoreOk() (*float64, bool) {
if o == nil || o.TemporalScore == nil {
return nil, false
}
return o.TemporalScore, true
}
// HasTemporalScore returns a boolean if a field has been set.
func (o *VulnerabilityScoreSet) HasTemporalScore() bool {
if o != nil && o.TemporalScore != nil {
return true
}
return false
}
// SetTemporalScore gets a reference to the given float64 and assigns it to the TemporalScore field.
func (o *VulnerabilityScoreSet) SetTemporalScore(v float64) {
o.TemporalScore = &v
}
// GetEnvironmentalScore returns the EnvironmentalScore field value if set, zero value otherwise.
func (o *VulnerabilityScoreSet) GetEnvironmentalScore() float64 {
if o == nil || o.EnvironmentalScore == nil {
var ret float64
return ret
}
return *o.EnvironmentalScore
}
// GetEnvironmentalScoreOk returns a tuple with the EnvironmentalScore field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *VulnerabilityScoreSet) GetEnvironmentalScoreOk() (*float64, bool) {
if o == nil || o.EnvironmentalScore == nil {
return nil, false
}
return o.EnvironmentalScore, true
}
// HasEnvironmentalScore returns a boolean if a field has been set.
func (o *VulnerabilityScoreSet) HasEnvironmentalScore() bool {
if o != nil && o.EnvironmentalScore != nil {
return true
}
return false
}
// SetEnvironmentalScore gets a reference to the given float64 and assigns it to the EnvironmentalScore field.
func (o *VulnerabilityScoreSet) SetEnvironmentalScore(v float64) {
o.EnvironmentalScore = &v
}
// GetVector returns the Vector field value if set, zero value otherwise.
func (o *VulnerabilityScoreSet) GetVector() string {
if o == nil || o.Vector == nil {
var ret string
return ret
}
return *o.Vector
}
// GetVectorOk returns a tuple with the Vector field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *VulnerabilityScoreSet) GetVectorOk() (*string, bool) {
if o == nil || o.Vector == nil {
return nil, false
}
return o.Vector, true
}
// HasVector returns a boolean if a field has been set.
func (o *VulnerabilityScoreSet) HasVector() bool {
if o != nil && o.Vector != nil {
return true
}
return false
}
// SetVector gets a reference to the given string and assigns it to the Vector field.
func (o *VulnerabilityScoreSet) SetVector(v string) {
o.Vector = &v
}
// GetProductID returns the ProductID field value if set, zero value otherwise.
func (o *VulnerabilityScoreSet) GetProductID() []string {
if o == nil || o.ProductID == nil {
var ret []string
return ret
}
return *o.ProductID
}
// GetProductIDOk returns a tuple with the ProductID field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *VulnerabilityScoreSet) GetProductIDOk() (*[]string, bool) {
if o == nil || o.ProductID == nil {
return nil, false
}
return o.ProductID, true
}
// HasProductID returns a boolean if a field has been set.
func (o *VulnerabilityScoreSet) HasProductID() bool {
if o != nil && o.ProductID != nil {
return true
}
return false
}
// SetProductID gets a reference to the given []string and assigns it to the ProductID field.
func (o *VulnerabilityScoreSet) SetProductID(v []string) {
o.ProductID = &v
}
func (o VulnerabilityScoreSet) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.BaseScore != nil {
toSerialize["BaseScore"] = o.BaseScore
}
if o.TemporalScore != nil {
toSerialize["TemporalScore"] = o.TemporalScore
}
if o.EnvironmentalScore != nil {
toSerialize["EnvironmentalScore"] = o.EnvironmentalScore
}
if o.Vector != nil {
toSerialize["Vector"] = o.Vector
}
if o.ProductID != nil {
toSerialize["ProductID"] = o.ProductID
}
return json.Marshal(toSerialize)
}
type NullableVulnerabilityScoreSet struct {
value *VulnerabilityScoreSet
isSet bool
}
func (v NullableVulnerabilityScoreSet) Get() *VulnerabilityScoreSet {
return v.value
}
func (v *NullableVulnerabilityScoreSet) Set(val *VulnerabilityScoreSet) {
v.value = val
v.isSet = true
}
func (v NullableVulnerabilityScoreSet) IsSet() bool {
return v.isSet
}
func (v *NullableVulnerabilityScoreSet) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableVulnerabilityScoreSet(val *VulnerabilityScoreSet) *NullableVulnerabilityScoreSet {
return &NullableVulnerabilityScoreSet{value: val, isSet: true}
}
func (v NullableVulnerabilityScoreSet) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableVulnerabilityScoreSet) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
} | openapi/model_vulnerability_score_set.go | 0.763219 | 0.438244 | model_vulnerability_score_set.go | starcoder |
package donutmaze
import (
"github.com/bogosj/advent-of-code/fileinput"
"github.com/bogosj/advent-of-code/intmath"
)
const (
space = '.'
wall = '#'
)
// Maze represents a donut maze on Pluto.
type Maze struct {
m [][]rune
warps []intmath.Point
visited map[int]map[intmath.Point]bool
IsRecursive bool
}
// New creates a new maze from a provided text file.
func New(p string) *Maze {
m := Maze{}
m.m = input(p)
m.findWarpPoints()
m.visited = map[int]map[intmath.Point]bool{}
return &m
}
func (m *Maze) String() (ret string) {
for _, row := range m.m {
for _, c := range row {
ret += string(c)
}
ret += "\n"
}
return
}
type pointDist struct {
p intmath.Point
dist, depth int
}
// ShortestPath performs a BFS across the maze using warp points and returns the shortest path in steps.
func (m *Maze) ShortestPath() int {
points := []pointDist{pointDist{p: m.startPoint()}}
for len(points) > 0 {
point := points[0]
points = points[1:]
if _, ok := m.visited[point.depth]; !ok {
m.visited[point.depth] = map[intmath.Point]bool{}
}
if _, ok := m.visited[point.depth][point.p]; ok {
continue
}
m.visited[point.depth][point.p] = true
if point.p == m.endPoint() {
if m.IsRecursive {
if point.depth == 0 {
return point.dist
}
} else {
return point.dist
}
}
if m.isWarpPoint(point.p) {
if m.IsRecursive && point.depth == 0 && m.isOuterWarpPoint(point.p) {
// Recursive map exterior warp points are dead ends.
continue
} else {
np := pointDist{
p: m.warpPointOtherEnd(point.p),
dist: point.dist + 1,
depth: point.depth + 1,
}
if m.isOuterWarpPoint(point.p) {
np.depth = point.depth - 1
}
points = append(points, np)
}
}
for _, n := range point.p.Neighbors() {
if m.m[n.Y][n.X] == space {
points = append(points, pointDist{p: n, dist: point.dist + 1, depth: point.depth})
}
}
}
return -1
}
func (m *Maze) isLetter(p intmath.Point) bool {
return m.m[p.Y][p.X] >= 'A' && m.m[p.Y][p.X] <= 'Z'
}
func (m *Maze) isWarpPoint(p intmath.Point) bool {
if p == m.startPoint() || p == m.endPoint() {
return false
}
for _, w := range m.warps {
if w == p {
return true
}
}
return false
}
func (m *Maze) isOuterWarpPoint(p intmath.Point) bool {
if p.Y == 2 || p.Y == len(m.m)-3 {
return true
}
if p.X == 2 || p.X == len(m.m[0])-3 {
return true
}
return false
}
func (m *Maze) warpPointsByName(n string) (ret []intmath.Point) {
for _, w := range m.warps {
if m.warpPointName(w) == n {
ret = append(ret, w)
}
}
return
}
func (m *Maze) warpPointOtherEnd(p intmath.Point) intmath.Point {
n := m.warpPointName(p)
for _, op := range m.warpPointsByName(n) {
if op != p {
return op
}
}
return intmath.Point{}
}
func (m *Maze) startPoint() (ret intmath.Point) {
w := m.warpPointsByName("AA")
return w[0]
}
func (m *Maze) endPoint() (ret intmath.Point) {
w := m.warpPointsByName("ZZ")
return w[0]
}
func (m *Maze) warpPointName(p intmath.Point) string {
var ret []rune
for _, p1 := range p.Neighbors() {
if m.isLetter(p1) {
ret = append(ret, m.m[p1.Y][p1.X])
for _, p2 := range p1.Neighbors() {
if m.isLetter(p2) {
ret = append(ret, m.m[p2.Y][p2.X])
}
}
}
}
if ret[0] < ret[1] {
return string(ret[0]) + string(ret[1])
}
return string(ret[1]) + string(ret[0])
}
func (m *Maze) findWarpPoints() {
for y := range m.m {
for x := range m.m[y] {
if m.m[y][x] == space {
p := intmath.Point{X: x, Y: y}
for _, n := range p.Neighbors() {
if m.isLetter(n) {
m.warps = append(m.warps, p)
}
}
}
}
}
}
func input(p string) (ret [][]rune) {
lines := fileinput.ReadLinesRaw(p)
for _, line := range lines {
row := []rune{}
for _, r := range line {
row = append(row, r)
}
ret = append(ret, row)
}
return
} | 2019/day20/donutmaze/donutmaze.go | 0.730001 | 0.401541 | donutmaze.go | starcoder |
package model
import (
"github.com/sudachen/go-ml/fu"
"reflect"
)
/*
Classification metrics factory
*/
type Classification struct {
Accuracy float64 // accuracy goal
Error float64 // error goal
Confidence float32 // threshold for binary classification
}
/*
Names is the list of calculating metrics
*/
func (m Classification) Names() []string {
return []string{
IterationCol,
SubsetCol,
ErrorCol,
LossCol,
AccuracyCol,
SensitivityCol,
PrecisionCol,
F1ScoreCol,
CorrectCol,
TotalCol,
}
}
/*
New metrics updater for the given iteration and subset
*/
func (m Classification) New(iteration int, subset string) MetricsUpdater {
return &cfupdater{
Classification: m,
iteration: iteration,
subset: subset,
lIncorrect: map[int]float64{},
rIncorrect: map[int]float64{},
cCorrect: map[int]float64{},
}
}
type cfupdater struct {
Classification
iteration int
subset string
correct float64
loss float64
lIncorrect map[int]float64
rIncorrect map[int]float64
cCorrect map[int]float64
count float64
}
func (m *cfupdater) Update(result, label reflect.Value, loss float64) {
l := fu.Cell{label}.Int()
y := 0
if result.Type() == fu.TensorType {
v := result.Interface().(fu.Tensor)
y = v.HotOne()
} else {
if m.Confidence > 0 {
x := fu.Cell{result}.Real()
if x > m.Confidence {
y = 1
}
} else {
y = fu.Cell{result}.Int()
}
}
if l == y {
m.correct++
m.cCorrect[y] = m.cCorrect[y] + 1
} else {
m.lIncorrect[l] = m.lIncorrect[l] + 1
m.rIncorrect[y] = m.rIncorrect[y] + 1
}
m.loss += loss
m.count++
}
func (m *cfupdater) Complete() (fu.Struct, bool) {
if m.count > 0 {
acc := m.correct / m.count
cno := float64(len(m.cCorrect))
var sensitivity, precision, cerr float64
for i, v := range m.cCorrect {
sensitivity += v / (v + m.lIncorrect[i]) // false negative
precision += v / (v + m.rIncorrect[i]) // false positive
cerr += (m.rIncorrect[i] + m.lIncorrect[i]) / m.count
}
sensitivity /= cno
precision /= cno
cerr /= cno
f1 := 2 * precision * sensitivity / (precision + sensitivity)
columns := []reflect.Value{
reflect.ValueOf(m.iteration),
reflect.ValueOf(m.subset),
reflect.ValueOf(cerr),
reflect.ValueOf(m.loss / m.count),
reflect.ValueOf(acc),
reflect.ValueOf(sensitivity),
reflect.ValueOf(precision),
reflect.ValueOf(f1),
reflect.ValueOf(int(m.correct)),
reflect.ValueOf(int(m.count)),
}
goal := false
if m.Accuracy > 0 {
goal = goal || acc > m.Accuracy
}
if m.Error > 0 {
goal = goal || cerr < m.Error
}
return fu.Struct{Names: m.Names(), Columns: columns}, goal
}
return fu.
NaStruct(m.Names(), fu.Float64).
Set(IterationCol, fu.IntZero).
Set(SubsetCol, fu.EmptyString),
false
} | model/classificaction.go | 0.627152 | 0.423875 | classificaction.go | starcoder |
package inmemory
import (
"errors"
"reflect"
"github.com/hellofresh/goengine/metadata"
)
var ErrUnsupportedType = errors.New("the value is not a scalar type")
func asScalar(value interface{}) (interface{}, error) {
switch value.(type) {
case int,
int8,
int16,
int32,
int64,
uint,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
string,
bool,
complex64,
complex128:
return value, nil
}
switch reflect.TypeOf(value).Kind() {
case reflect.Int:
var v int
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Int8:
var v int8
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Int16:
var v int16
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Int32:
var v int32
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Int64:
var v int64
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Uint:
var v uint
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Uint8:
var v uint8
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Uint16:
var v uint16
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Uint32:
var v uint32
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Uint64:
var v uint64
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Float32:
var v float32
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Float64:
var v float64
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.String:
var v string
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Bool:
var v bool
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Complex64:
var v complex64
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
case reflect.Complex128:
var v complex128
return reflect.ValueOf(value).Convert(reflect.TypeOf(v)).Interface(), nil
}
return nil, ErrUnsupportedType
}
func isSupportedOperator(value interface{}, operator metadata.Operator) bool {
switch operator {
case metadata.Equals,
metadata.NotEquals:
switch value.(type) {
case int,
int8,
int16,
int32,
int64,
uint,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
string,
bool,
complex64,
complex128:
return true
}
case metadata.GreaterThan,
metadata.GreaterThanEquals,
metadata.LowerThan,
metadata.LowerThanEquals:
switch value.(type) {
case int,
int8,
int16,
int32,
int64,
uint,
uint8,
uint16,
uint32,
uint64,
float32,
float64,
string:
return true
}
}
return false
}
func (c *metadataConstraint) compareValue(lValue interface{}) (bool, error) {
switch rVal := c.value.(type) {
case int:
if lVal, valid := lValue.(int); valid {
return compareInt(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case int8:
if lVal, valid := lValue.(int8); valid {
return compareInt8(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case int16:
if lVal, valid := lValue.(int16); valid {
return compareInt16(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case int32:
if lVal, valid := lValue.(int32); valid {
return compareInt32(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case int64:
if lVal, valid := lValue.(int64); valid {
return compareInt64(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case uint:
if lVal, valid := lValue.(uint); valid {
return compareUint(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case uint8:
if lVal, valid := lValue.(uint8); valid {
return compareUint8(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case uint16:
if lVal, valid := lValue.(uint16); valid {
return compareUint16(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case uint32:
if lVal, valid := lValue.(uint32); valid {
return compareUint32(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case uint64:
if lVal, valid := lValue.(uint64); valid {
return compareUint64(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case float32:
if lVal, valid := lValue.(float32); valid {
return compareFloat32(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case float64:
if lVal, valid := lValue.(float64); valid {
return compareFloat64(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case string:
if lVal, valid := lValue.(string); valid {
return compareString(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case bool:
if lVal, valid := lValue.(bool); valid {
return compareBool(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case complex64:
if lVal, valid := lValue.(complex64); valid {
return compareComplex64(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
case complex128:
if lVal, valid := lValue.(complex128); valid {
return compareComplex128(rVal, c.operator, lVal)
}
return false, ErrTypeMismatch
}
return false, ErrUnsupportedType
}
func compareInt(rValue int, operator metadata.Operator, lValue int) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareInt8(rValue int8, operator metadata.Operator, lValue int8) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareInt16(rValue int16, operator metadata.Operator, lValue int16) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareInt32(rValue int32, operator metadata.Operator, lValue int32) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareInt64(rValue int64, operator metadata.Operator, lValue int64) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareUint(rValue uint, operator metadata.Operator, lValue uint) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareUint8(rValue uint8, operator metadata.Operator, lValue uint8) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareUint16(rValue uint16, operator metadata.Operator, lValue uint16) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareUint32(rValue uint32, operator metadata.Operator, lValue uint32) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareUint64(rValue uint64, operator metadata.Operator, lValue uint64) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareFloat32(rValue float32, operator metadata.Operator, lValue float32) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareFloat64(rValue float64, operator metadata.Operator, lValue float64) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareString(rValue string, operator metadata.Operator, lValue string) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
case metadata.GreaterThan:
return rValue > lValue, nil
case metadata.GreaterThanEquals:
return rValue >= lValue, nil
case metadata.LowerThan:
return rValue < lValue, nil
case metadata.LowerThanEquals:
return rValue <= lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareBool(rValue bool, operator metadata.Operator, lValue bool) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareComplex64(rValue complex64, operator metadata.Operator, lValue complex64) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
}
return false, ErrUnsupportedOperator
}
func compareComplex128(rValue complex128, operator metadata.Operator, lValue complex128) (bool, error) {
switch operator {
case metadata.Equals:
return rValue == lValue, nil
case metadata.NotEquals:
return rValue != lValue, nil
}
return false, ErrUnsupportedOperator
} | driver/inmemory/matcher_gen.go | 0.604749 | 0.450903 | matcher_gen.go | starcoder |
package ed
import (
"unicode/utf8"
// "fmt"
)
func min(a, b int) int {
if a < b {
return a
}
return b
}
/*
String calculates the edit-distance between two strings. Input strings must be UTF-8 encoded.
The time complexity is O(mn) where m and n are lengths of a and b, and space complexity is O(n).
*/
func String(a, b string) int {
f := make([]int, utf8.RuneCountInString(b)+1)
for j := range f {
f[j] = j
}
for _, ca := range a {
j := 1
fj1 := f[0] // fj1 is the value of f[j - 1] in last iteration
f[0]++
for _, cb := range b {
mn := min(f[j]+1, f[j-1]+1) // delete & insert
if cb != ca {
mn = min(mn, fj1+1) // change
} else {
mn = min(mn, fj1) // matched
}
fj1, f[j] = f[j], mn // save f[j] to fj1(j is about to increase), update f[j] to mn
j++
}
}
return f[len(f)-1]
}
// Constants of operations
const (
opDEL byte = iota
opINS
opCHANGE
opMATCH
)
/*
String calculates the edit-distance and longest-common-string between two strings. Input strings must be UTF-8 encoded.
The time and space complexity are all O(mn) where m and n are lengths of a and b.
NOTE if detailed matching information is not necessary, call String instead because it needs much less memories.
*/
func StringFull(a, b string) (dist int, lcs string) {
la, lb := utf8.RuneCountInString(a), utf8.RuneCountInString(b)
f := make([]int, lb+1)
ops := make([]byte, la*lb)
for j := range f {
f[j] = j
}
p := 0 // the index to ops
for _, ca := range a {
j := 1
fj1 := f[0] // fj1 is the value of f[j - 1] in last iteration
f[0]++
for _, cb := range b {
mn, op := f[j]+1, opDEL
if f[j-1]+1 < mn {
mn, op = f[j-1]+1, opINS
}
if cb != ca {
if fj1+1 < mn {
mn, op = fj1+1, opCHANGE
}
} else {
mn, op = fj1, opMATCH
}
fj1, f[j], ops[p] = f[j], mn, op // save f[j] to fj1(j is about to increase), update f[j] to mn
p++
j++
}
}
// Calculate longest-common-string
lcsi := make([]int, 0, la)
for i, j := la, lb; i > 0 || j > 0; {
var op byte
switch {
case i == 0:
op = opINS
case j == 0:
op = opDEL
default:
op = ops[(i-1)*lb+j-1]
}
switch op {
case opINS:
j--
case opDEL:
i--
case opCHANGE, opMATCH:
i--
j--
if op == opMATCH {
lcsi = append(lcsi, i)
}
}
}
if i, l := 0, len(lcsi)-1; l > 0 {
for _, ca := range a {
if i == lcsi[l] {
lcs = lcs + string(ca)
l--
if l < 0 {
break
}
}
i++
}
}
return f[len(f)-1], lcs
}
// Ternary returns vT if cond equals true, or vF otherwise.
func Ternary(cond bool, vT, vF int) int {
if cond {
return vT
}
return vF
}
// ConstCost returns a const-function whose return value is the specified cost. This is useful for EditDistanceF and EditDistanceFFull if the del/ins cost is constant to positions.
func ConstCost(cost int) func(int) int {
return func(int) int {
return cost
}
}
/*
Base is a helper type which defines LenA, LenB, CostOfDel and CostOfIns methods.
*/
type Base struct {
LA, LB, Cost int
}
// Interface.LenA
func (b *Base) LenA() int {
return b.LA
}
// Interface.LenB
func (b *Base) LenB() int {
return b.LB
}
// Interface.CostOfDel
func (b *Base) CostOfDel(iA int) int {
return b.Cost
}
// Interface.CostOfIns
func (b *Base) CostOfIns(iB int) int {
return b.Cost
}
/*
Interface defines a pair of lists and the cost for each operation.
*/
type Interface interface {
// LenA returns the lenght of the source list
LenA() int
// LenB returns the lenght of the destination list
LenB() int
// CostOfChange returns the change cost from an item in the source list at iA to an item in the destination list at iB
CostOfChange(iA, iB int) int
// CostOfDel returns the cost of deleting an item in the source list at iA
CostOfDel(iA int) int
// CostOfIns returns the cost of inserting an item in the destination list at iB
CostOfIns(iB int) int
}
/*
EditDistance returns the edit-distance defined by Interface.
The time complexity is O(mn) where m and n are lengths of a and b, and space complexity is O(n).
*/
func EditDistance(in Interface) int {
la, lb := in.LenA(), in.LenB()
f := make([]int, lb+1)
for j := 1; j <= lb; j++ {
f[j] = f[j-1] + in.CostOfIns(j-1)
}
for i := 0; i < la; i++ {
fj1 := f[0] // fj1 is the value of f[j - 1] in last iteration
f[0] += in.CostOfDel(i)
for j := 1; j <= lb; j++ {
mn := min(f[j]+in.CostOfDel(i), f[j-1]+in.CostOfIns(j-1)) // delete & insert
mn = min(mn, fj1+in.CostOfChange(i, j-1)) // change/matched
fj1, f[j] = f[j], mn // save f[j] to fj1(j is about to increase), update f[j] to mn
}
}
return f[lb]
}
func matchingFromOps(la, lb int, ops []byte) (matA, matB []int) {
matA, matB = make([]int, la), make([]int, lb)
for i, j := la, lb; i > 0 || j > 0; {
var op byte
switch {
case i == 0:
op = opINS
case j == 0:
op = opDEL
default:
op = ops[(i-1)*lb+j-1]
}
switch op {
case opINS:
j--
matB[j] = -1
case opDEL:
i--
matA[i] = -1
case opCHANGE:
i--
j--
matA[i], matB[j] = j, i
}
}
return matA, matB
}
/*
EditDistanceFull returns the edit-distance and corresponding match indexes defined by Interface.
Each element in matA and matB is the index in the other list, if it is equal to or greater than zero; or -1 meaning a deleting or inserting in matA or matB, respectively.
The time and space complexity are all O(mn) where m and n are lengths of a and b.
NOTE if detailed matching information is not necessary, call EditDistance instead because it needs much less memories.
*/
func EditDistanceFull(in Interface) (dist int, matA, matB []int) {
la, lb := in.LenA(), in.LenB()
f := make([]int, lb+1)
ops := make([]byte, la*lb)
for j := 1; j <= lb; j++ {
f[j] = f[j-1] + in.CostOfIns(j-1)
}
// Matching with dynamic programming
p := 0
for i := 0; i < la; i++ {
fj1 := f[0] // fj1 is the value of f[j - 1] in last iteration
f[0] += in.CostOfDel(i)
for j := 1; j <= lb; j++ {
mn, op := f[j]+in.CostOfDel(i), opDEL // delete
if v := f[j-1] + in.CostOfIns(j-1); v < mn {
// insert
mn, op = v, opINS
}
// change/matched
if v := fj1 + in.CostOfChange(i, j-1); v < mn {
// insert
mn, op = v, opCHANGE
}
fj1, f[j], ops[p] = f[j], mn, op // save f[j] to fj1(j is about to increase), update f[j] to mn
p++
}
}
// Reversely find the match info
matA, matB = matchingFromOps(la, lb, ops)
return f[lb], matA, matB
}
/*
EditDistanceFunc returns the edit-distance defined by parameters and functions.
The time complexity is O(mn) where m and n are lengths of a and b, and space complexity is O(n).
*/
func EditDistanceF(lenA, lenB int, costOfChange func(iA, iB int) int, costOfDel func(iA int) int, costOfIns func(iB int) int) int {
la, lb := lenA, lenB
f := make([]int, lb+1)
for j := 1; j <= lb; j++ {
f[j] = f[j-1] + costOfIns(j-1)
}
for i := 0; i < la; i++ {
fj1 := f[0] // fj1 is the value of f[j - 1] in last iteration
f[0] += costOfDel(i)
for j := 1; j <= lb; j++ {
mn := min(f[j]+costOfDel(i), f[j-1]+costOfIns(j-1)) // delete & insert
mn = min(mn, fj1+costOfChange(i, j-1)) // change/matched
fj1, f[j] = f[j], mn // save f[j] to fj1(j is about to increase), update f[j] to mn
}
}
return f[lb]
}
/*
EditDistanceFFull returns the edit-distance and corresponding match indexes defined by parameters and functions.
Each element in matA and matB is the index in the other list, if it is equal to or greater than zero; or -1 meaning a deleting or inserting in matA or matB, respectively.
The time and space complexity are all O(mn) where m and n are lengths of a and b.
NOTE if detailed matching information is not necessary, call EditDistance instead because it needs much less memories.
*/
func EditDistanceFFull(lenA, lenB int, costOfChange func(iA, iB int) int, costOfDel func(iA int) int, costOfIns func(iB int) int) (dist int, matA, matB []int) {
la, lb := lenA, lenB
f := make([]int, lb+1)
ops := make([]byte, la*lb)
for j := 1; j <= lb; j++ {
f[j] = f[j-1] + costOfIns(j-1)
}
// Matching with dynamic programming
p := 0
for i := 0; i < la; i++ {
fj1 := f[0] // fj1 is the value of f[j - 1] in last iteration
f[0] += costOfDel(i)
for j := 1; j <= lb; j++ {
mn, op := f[j]+costOfDel(i), opDEL // delete
if v := f[j-1] + costOfIns(j-1); v < mn {
// insert
mn, op = v, opINS
}
// change/matched
if v := fj1 + costOfChange(i, j-1); v < mn {
// insert
mn, op = v, opCHANGE
}
fj1, f[j], ops[p] = f[j], mn, op // save f[j] to fj1(j is about to increase), update f[j] to mn
p++
}
}
// Reversely find the match info
matA, matB = matchingFromOps(la, lb, ops)
return f[lb], matA, matB
} | ed/ed.go | 0.650911 | 0.480174 | ed.go | starcoder |
package catalog
import (
"github.com/iand/growth/plot"
)
type Entry struct {
Depth int
plot.Grammar
plot.Plotter
}
var Entries = map[string]Entry{
"big-h": {
Depth: 10,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 90,
Step: 200,
StepDelta: 0.65,
LineWidth: 9,
LineWidthDelta: 0.65,
},
Grammar: plot.Grammar{
Seed: "[F]--F",
Rules: map[rune]string{
'F': "|[+F][-F]",
},
},
},
"bent-big-h": {
Depth: 10,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 80,
Step: 200,
StepDelta: 0.65,
LineWidth: 9,
LineWidthDelta: 0.65,
},
Grammar: plot.Grammar{
Seed: "[F]--F",
Rules: map[rune]string{
'F': "|[+F][-F]",
},
},
},
"two-ys": {
Depth: 10,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 45,
Step: 200,
StepDelta: 0.65,
LineWidth: 9,
LineWidthDelta: 0.65,
},
Grammar: plot.Grammar{
Seed: "[F]----F",
Rules: map[rune]string{
'F': "|[+F][-F]",
},
},
},
"twig": {
Depth: 10,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 20,
Step: 200,
StepDelta: 0.65,
LineWidth: 9,
LineWidthDelta: 0.65,
},
Grammar: plot.Grammar{
Seed: "F",
Rules: map[rune]string{
'F': "|[-F][+F]",
},
},
},
"weed-1": {
Depth: 6,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 25,
Step: 200,
StepDelta: 0.45,
LineWidth: 9,
LineWidthDelta: 0.45,
},
Grammar: plot.Grammar{
Seed: "F",
Rules: map[rune]string{
'F': "F[-F]F[+F]F",
},
},
},
"weed-2": {
Depth: 6,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 25,
Step: 200,
StepDelta: 0.45,
LineWidth: 9,
LineWidthDelta: 0.45,
},
Grammar: plot.Grammar{
Seed: "F",
Rules: map[rune]string{
'F': "|[-F]|[+F]F",
},
},
},
"weed-3": {
Depth: 4,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 20,
Step: 200,
StepDelta: 0.45,
LineWidth: 9,
LineWidthDelta: 0.45,
},
Grammar: plot.Grammar{
Seed: "F",
Rules: map[rune]string{
'F': "|[-F]|[+F][-F]F",
},
},
},
"bush-1": {
Depth: 5,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 25,
Step: 200,
StepDelta: 0.45,
LineWidth: 9,
LineWidthDelta: 0.45,
},
Grammar: plot.Grammar{
Seed: "F",
Rules: map[rune]string{
'F': "FF+[+F-F-F]-[-F+F+F]",
},
},
},
"bush-2": {
Depth: 8,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 20,
Step: 200,
StepDelta: 0.45,
LineWidth: 9,
LineWidthDelta: 0.45,
},
Grammar: plot.Grammar{
Seed: "F",
Rules: map[rune]string{
'F': "|[+F]|[-F]+F",
},
},
},
"tree-1": {
Depth: 6,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 20,
Step: 200,
StepDelta: 0.50,
LineWidth: 9,
LineWidthDelta: 0.5,
},
Grammar: plot.Grammar{
Seed: "F",
Rules: map[rune]string{
'F': "|[---F][+++F]|[--F][++F]|F",
},
},
},
"tree-2": {
Depth: 5,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 8,
Step: 200,
StepDelta: 0.5,
LineWidth: 9,
LineWidthDelta: 0.5,
},
Grammar: plot.Grammar{
Seed: "F",
Rules: map[rune]string{
'F': "|[+++++F][-------F]-|[++++F][------F]-|[+++F][-----F]-|F",
},
},
},
"tree-3": {
Depth: 9,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 20,
Step: 200,
StepDelta: 0.65,
LineWidth: 9,
LineWidthDelta: 0.65,
},
Grammar: plot.Grammar{
Seed: "F",
Rules: map[rune]string{
'F': "|[--F][+F]-F",
},
},
},
"carpet": {
Depth: 5,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 90,
Step: 200,
StepDelta: 0.5,
LineWidth: 9,
LineWidthDelta: 0.5,
},
Grammar: plot.Grammar{
Seed: "F-F-F-F",
Rules: map[rune]string{
'F': "F[F]-F+F[--F]+F-F",
},
},
},
"sierpinksi-square": {
Depth: 5,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 90,
Step: 200,
StepDelta: 0.5,
LineWidth: 2,
LineWidthDelta: 0.8,
},
Grammar: plot.Grammar{
Seed: "F-F-F-F",
Rules: map[rune]string{
'F': "FF[-F-F-F]F",
},
},
},
"rug": {
Depth: 5,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 90,
Step: 200,
StepDelta: 0.5,
LineWidth: 2,
LineWidthDelta: 0.8,
},
Grammar: plot.Grammar{
Seed: "F-F-F-F",
Rules: map[rune]string{
'F': "F[-F-F]FF",
},
},
},
"koch-island": {
Depth: 5,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 60,
Step: 200,
StepDelta: 0.5,
LineWidth: 2,
LineWidthDelta: 0.8,
},
Grammar: plot.Grammar{
Seed: "F++F++F",
Rules: map[rune]string{
'F': "F-F++F-F",
},
},
},
"quadric-koch-island": {
Depth: 4,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 90,
Step: 200,
StepDelta: 0.35,
LineWidth: 1,
LineWidthDelta: 0.9,
},
Grammar: plot.Grammar{
Seed: "F-F-F-F",
Rules: map[rune]string{
'F': "F-F+F+FF-F-F+F",
},
},
},
"square-spikes": {
Depth: 5,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 5,
Step: 200,
StepDelta: 0.5,
LineWidth: 1,
LineWidthDelta: 0.9,
},
Grammar: plot.Grammar{
Seed: "F------------------F------------------F------------------F",
Rules: map[rune]string{
'F': "F-----------------F++++++++++++++++++++++++++++++++++F-----------------F",
},
},
},
"sierpinksi-gasket": {
Depth: 8,
Plotter: plot.Plotter{
InitialAngle: -30,
AngleDelta: 60,
Step: 200,
StepDelta: 0.65,
LineWidth: 1,
LineWidthDelta: 0.9,
},
Grammar: plot.Grammar{
Seed: "F--F--F",
Rules: map[rune]string{
'F': "F--F--F--GG",
'G': "GG",
},
},
},
"sierpinksi-maze": {
Depth: 8,
Plotter: plot.Plotter{
InitialAngle: -30,
AngleDelta: 60,
Step: 200,
StepDelta: 0.65,
LineWidth: 1,
LineWidthDelta: 0.9,
},
Grammar: plot.Grammar{
Seed: "F",
Rules: map[rune]string{
'F': "[GF][+G---F][G+G+F]",
'G': "GG",
},
},
},
"sierpinksi-arrowhead": {
Depth: 8,
Plotter: plot.Plotter{
InitialAngle: -30,
AngleDelta: 60,
Step: 200,
StepDelta: 0.65,
LineWidth: 1,
LineWidthDelta: 0.9,
},
Grammar: plot.Grammar{
Seed: "F",
Rules: map[rune]string{
'F': "[-G+++F][-G+F][GG--F]",
'G': "GG",
},
},
},
"penrose-snowflake": {
Depth: 4,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 18,
Step: 200,
StepDelta: 0.5,
LineWidth: 1,
LineWidthDelta: 0.9,
},
Grammar: plot.Grammar{
Seed: "F----F----F----F----F",
Rules: map[rune]string{
'F': "F----F----F----------F++F----F",
},
},
},
"penrose-tile": {
Depth: 6,
Plotter: plot.Plotter{
InitialAngle: 0,
AngleDelta: 36,
Step: 200,
StepDelta: 0.65,
LineWidth: 1,
LineWidthDelta: 0.9,
},
Grammar: plot.Grammar{
Seed: "[X]++[X]++[X]++[X]++[X]",
Rules: map[rune]string{
'W': "YF++ZF----XF[-YF----WF]++",
'X': "+YF--ZF[---WF--XF]+",
'Y': "-WF++XF[+++YF++ZF]-",
'Z': "--YF++++WF[+ZF++++XF]--XF",
'F': "",
},
},
},
"dragon-curve": {
Depth: 11,
Plotter: plot.Plotter{
InitialAngle: 90,
AngleDelta: 45,
Step: 200,
StepDelta: 0.75,
LineWidth: 1,
LineWidthDelta: 1,
},
Grammar: plot.Grammar{
Seed: "F",
Rules: map[rune]string{
'F': "[+F][+G--G----F]",
'G': "-G++G-",
},
},
},
} | catalog/catalog.go | 0.571647 | 0.598899 | catalog.go | starcoder |
package stats
// Data represents a collection of float64 values. In which
// operations are done
type Data []float64
// Get items in slice
func (d Data) Get(i int) float64 { return d[i] }
// Len return length of slice
func (d *Data) Len() int { return len(*d) }
// Mean Computes the of the data set
func (d *Data) Mean() (float64, error) { return Mean(*d) }
// Sum returns the sum of all the values of data
func (d *Data) Sum() (float64, error) { return Sum(*d) }
// Median returns the mid item in the data when sorted
func (d *Data) Median() (float64, error) { return Median(*d) }
// Mode returns the mode of the data
func (d *Data) Mode() ([]float64, error) { return Mode(*d) }
// Max returns the maximux values in data
func (d *Data) Max() (float64, error) { return Max(*d) }
// Min return the minimum item in data
func (d *Data) Min() (float64, error) { return Min(*d) }
// Variance computes the Population Variance of data
func (d *Data) Variance() (float64, error) { return Variance(*d) }
// PopulationVariance return the Population Variance of data
func (d *Data) PopulationVariance() (float64, error) {
return d.Variance()
}
// SampleVariance returns sample Variance of data
func (d *Data) SampleVariance() (float64, error) {
return SampleVariance(*d)
}
// StandardDeviation computes the Population StandardDeviation
func (d *Data) StandardDeviation() (float64, error) {
return StandardDeviation(*d)
}
// PopulationStandardDeviation computes the Population StandardDeviation
func (d *Data) PopulationStandardDeviation() (float64, error) {
return PopulationStandardDeviation(*d)
}
// SampleStandardDeviation computes the sample StandardDeviation
func (d *Data) SampleStandardDeviation() (float64, error) {
return SampleStandardDeviation(*d)
}
// Zscore computes the number of StandardDeviation from the mean using Population
func (d *Data) Zscore(x float64) (float64, error) {
return Zscore(*d, x)
}
// SampleZscore computes the number of StandardDeviation from the mean using sample
func (d *Data) SampleZscore(x float64) (float64, error) {
return SampleZscore(*d, x)
}
// Range return the data range
func (d *Data) Range() (float64, error) { return Range(*d) }
// SampleStandardError computes sample StandardError
func (d *Data) SampleStandardError() (float64, error) { return SampleStandardError(*d) } | stats/data.go | 0.938216 | 0.908982 | data.go | starcoder |
package poly
import (
"fmt"
"math"
)
// A polynom-like object. Can handle multiplication, integration, sum, etc.
type Poly struct {
// The coefficients of the polynom object. The first coefficient corresponds to the 0th element, and this then continues
// Null Polynoms have a nil coefficient
Coefficients []float64
}
// A method for getting the Degre of a polynom
// Null Polynoms will have a -1 degree while constant polynoms will have a degre of zero.
// Overall, Polynoms have a their coefficients of len = self.Degre() + 1
func (self *Poly) Degre() int {
if self == nil {
return -1
}
for {
if self.Coefficients == nil {
return -1 // instead of the more mathematically correct -inf
} else if len(self.Coefficients) == 0 {
return -1
}
if self.Coefficients[len(self.Coefficients)-1] != 0.0 {
break
}
self.Coefficients = self.Coefficients[:len(self.Coefficients)-1]
}
return len(self.Coefficients) - 1
}
// allows for a composition between two Polynomials. If we were to do
// R := P.Composite(Q), then
// R.Call(x) == P.Call(Q.Call(x))
func (self *Poly) Composite(other *Poly) *Poly {
var sD, oD int
sD = self.Degre()
oD = other.Degre()
if sD < 0 {
return &Poly{}
} else if oD < 0 {
return &Poly{Coefficients: []float64{self.Call(0.)}}
} else if sD == 0 {
return &Poly{Coefficients: self.Coefficients[:]}
} else if oD == 0 {
return &Poly{Coefficients: []float64{self.Call(other.Call(0.))}}
// other is constant
}
// we now try to do it normally
var result, P *Poly
// handling the constant part fitst
result = &Poly{Coefficients: []float64{self.Coefficients[0]}}
P = other
// now for the part actually afffected by the composition
for i := 1; i < len(self.Coefficients); i++ {
result = result.Add(P.Scalar_prod(self.Coefficients[i]))
P = P.Mult(other)
}
return result
}
// Returns the area under the Polynom's curve in the [a, b] segment.
func (self *Poly) Integrate(a, b float64) float64 {
if b < a {
return -self.Integrate(b, a)
}
if self.Degre() < 0 {
return 0
}
sum := 0.
for i := 0; i < len(self.Coefficients); i++ {
j := float64(i)
sum += self.Coefficients[i] / (j + 1) * (math.Pow(b, j+1) - math.Pow(a, j+1))
}
return sum
}
// Creates a Primitive of the Polynom self.
// The primitive is itself a Polynom object
// The integration constant is set to 0 (the 0th Coefficient is null)
func (self *Poly) GetPrimitive() *Poly {
if self.Degre() < 0 {
return &Poly{Coefficients: []float64{}}
}
coeffs := make([]float64, self.Degre()+2)
for i := 0; i < len(coeffs)-1; i++ {
j := float64(i)
coeffs[i+1] = self.Coefficients[i] / (j + 1)
}
return &Poly{Coefficients: coeffs}
}
// Creates a derivative polynom of self.
// Please do remember that taking the primitive of this derived polynom will not get you your original longer
func (self *Poly) GetDeriv() *Poly {
if self.Degre() < 0 { // we have a null polynom
return &Poly{Coefficients: []float64{}}
}
coeffs := make([]float64, self.Degre())
for i := 0; i < len(coeffs); i++ {
j := float64(i)
coeffs[i] = self.Coefficients[i+1] * (j + 1)
}
return &Poly{Coefficients: coeffs}
}
// Derives the polynom and gives the result at x
func (self *Poly) Derive(x float64) float64 {
var sum = 0.
for i := 1; i < self.Degre()+1; i++ {
j := float64(i)
sum += self.Coefficients[i] * j * math.Pow(x, j-1)
}
return sum
}
func (self *Poly) String() string {
var t string
t = "P[X] = "
if self.Degre() < 0 {
t += "0"
return t
}
var n = len(self.Coefficients)
for i := 0; i < n; i++ {
if self.Coefficients[i] != 0. {
if i == 0 {
t += fmt.Sprintf("%f", self.Coefficients[i])
} else if i == 1 {
t += fmt.Sprintf("%f . X", self.Coefficients[i])
} else {
t += fmt.Sprintf("%f . X^%d", self.Coefficients[i], i)
}
if i < n-1 {
t += " + "
}
}
}
return t
}
func (self *Poly) Disp() {
fmt.Println(self.String())
} | polynom.go | 0.701509 | 0.564819 | polynom.go | starcoder |
package matsa
import (
"math"
"math/rand"
"time"
"sort"
"errors"
)
func (list List_f64) Sum() float64 {
if list.Length() == 0 {
return 0
}
var sum float64
// Add em up
for _, n := range list {
sum += n
}
return sum
}
func (list List_f64) Mean() float64 {
l := list.Length()
if l == 0 {
return 0
}
sum := list.Sum()
return sum / float64(l)
}
func (list List_f64) GeometricMean() float64 {
l := list.Length()
if l == 0 {
return 0
}
// Get the product of all the numbers
var p float64
for _, n := range list {
if p == 0 {
p = n
} else {
p *= n
}
}
// Calculate the geometric mean
return math.Pow(p, 1/float64(l))
}
func (list List_f64) HarmonicMean() float64 {
l := list.Length()
if l == 0 {
return 0
}
// Get the sum of all the numbers reciprocals and return an
// error for values that cannot be included in harmonic mean
var p float64
for _, n := range list {
if n < 0 {
return 0
} else if n == 0 {
return 0
}
p += (1 / n)
}
return float64(l) / p
}
func (list List_f64) Median() float64 {
// Start by sorting a copy of the slice
c := sortedCopy(list)
var median float64
// No math is needed if there are no numbers
// For even numbers we add the two middle numbers
// and divide by two using the mean function above
// For odd numbers we just use the middle number
l := len(c)
if l == 0 {
return 0
} else if l%2 == 0 {
median = c[l/2-1 : l/2+1].Mean()
} else {
median = float64(c[l/2])
}
return median
}
func (list List_f64) Mode() List_f64 {
// Return the input if there's only one number
l := list.Length()
if l == 1 {
return list
} else if l == 0 {
return nil
}
c := sortedCopyDif(list)
// Traverse sorted array,
// tracking the longest repeating sequence
mode := make(List_f64, 5)
cnt, maxCnt := 1, 1
for i := 1; i < l; i++ {
switch {
case c[i] == c[i-1]:
cnt++
case cnt == maxCnt && maxCnt != 1:
mode = append(mode, c[i-1])
cnt = 1
case cnt > maxCnt:
mode = append(mode[:0], c[i-1])
maxCnt, cnt = cnt, 1
}
}
switch {
case cnt == maxCnt:
mode = append(mode, c[l-1])
case cnt > maxCnt:
mode = append(mode[:0], c[l-1])
maxCnt = cnt
}
// Since length must be greater than 1,
// check for slices of distinct values
if maxCnt == 1 {
return []float64{}
}
return mode
}
func (list List_f64) StandardDeviation() float64 {
if list.Length() == 0 {
return 0
}
// Get the population variance
vp := list.Variance()
// Return the population standard deviation
return math.Pow(vp, 0.5)
}
func (list List_f64) Variance() float64 {
l := list.Length()
if l == 0 {
return 0
}
// Sum the square of the mean subtracted from each number
m := list.Mean()
var variance float64
for _, n := range list {
variance += (float64(n) - m) * (float64(n) - m)
}
vrnce := variance / float64(l)
return vrnce
}
func (list List_f64) Percentile(percent float64) float64 {
if list.Length() == 0 {
return 0
}
var percentile float64
// Start by sorting a copy of the slice
c := sortedCopy(list)
// Multiple percent by length of input
index := (percent / 100) * float64(len(c))
// Check if the index is a whole number
if index == float64(int64(index)) {
// Convert float to int
i := float64ToInt(index)
// Find the average of the index and following values
percentile = List_f64{c[i-1], c[i]}.Mean()
} else {
// Convert float to int
i := float64ToInt(index)
// Find the value at the index
percentile = c[i-1]
}
return percentile
}
func (list List_f64) Quartile() List_f64 {
il := list.Length()
if il == 0 {
return List_f64{0,0,0}
}
// Start by sorting a copy of the slice
cpy := sortedCopy(list)
// Find the cutoff places depeding on if
// the input slice length is even or odd
var c1 int
var c2 int
if il%2 == 0 {
c1 = il / 2
c2 = il / 2
} else {
c1 = (il - 1) / 2
c2 = c1 + 1
}
// Find the Medians with the cutoff points
Q1 := cpy[:c1].Median()
Q2 := cpy.Median()
Q3 := cpy[c2:].Median()
return List_f64{Q1, Q2, Q3}
}
// InterQuartileRange finds the range between Q1 and Q3
func (list List_f64) InterQuartileRange() float64 {
if list.Length() == 0 {
return 0
}
qs := list.Quartile()
iqr := qs[2] - qs[0]
return iqr
}
// Trimean finds the average of the median and the midhinge
func (list List_f64) Trimean() float64 {
if list.Length() == 0 {
return 0
}
q := list.Quartile()
return (q[0] + (q[1] * 2) + q[2]) / 4
}
func (list List_f64) Correlation(list2 List_f64) float64 {
l1 := list.Length()
l2 := list2.Length()
if l1 == 0 || l2 == 0 {
return 0
}
if l1 != l2 {
return 0
}
sdev1 := list.StandardDeviation()
sdev2 := list2.StandardDeviation()
if sdev1 == 0 || sdev2 == 0 {
return 0
}
covp := list.Covariance(list2)
return covp / (sdev1 * sdev2)
}
func (list List_f64) Pearson(list2 List_f64) float64 {
return list.Correlation(list2)
}
func (list List_f64) Covariance(list2 List_f64) float64 {
l1 := list.Length()
l2 := list2.Length()
if l1 == 0 || l2 == 0 {
return 0
}
if l1 != l2 {
return 0
}
m1 := list.Mean()
m2 := list2.Mean()
// Calculate sum of squares
var ss float64
for i := 0; i < l1; i++ {
delta1 := (list[i] - m1)
delta2 := (list2[i] - m2)
ss += (delta1*delta2 - ss) / float64(i+1)
}
return ss * float64(l1) / float64(l1-1)
}
//utility functions
func Round(input float64, places int) (rounded float64, err error) {
// If the float is not a number
if math.IsNaN(input) {
return 0.0, errors.New("Not a number")
}
// Find out the actual sign and correct the input for later
sign := 1.0
if input < 0 {
sign = -1
input *= -1
}
// Use the places arg to get the amount of precision wanted
precision := math.Pow(10, float64(places))
// Find the decimal place we are looking to round
digit := input * precision
// Get the actual decimal number as a fraction to be compared
_, decimal := math.Modf(digit)
// If the decimal is less than .5 we round down otherwise up
if decimal >= 0.5 {
rounded = math.Ceil(digit)
} else {
rounded = math.Floor(digit)
}
// Finally we do the math to actually create a rounded number
return rounded / precision * sign, nil
}
func GenRandomFloat() float64 {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
return (float64(rand.Intn(100)) + r.Float64())
}
// sortedCopy returns a sorted copy of List_f64
func sortedCopy(list List_f64) List_f64 {
cpy := list.Copy()
sort.Float64s(cpy)
return cpy
}
// sortedCopyDif returns a sorted copy of List_f64
// only if the original data isn't sorted.
// Only use this if returned slice won't be manipulated!
func sortedCopyDif(list List_f64) List_f64 {
if sort.Float64sAreSorted(list) {
return list
}
cpy := list.Copy()
sort.Float64s(cpy)
return cpy
}
// float64ToInt rounds a float64 to an int
func float64ToInt(input float64) int {
r, _ := Round(input, 0)
return int(r)
} | statistics.go | 0.845496 | 0.586404 | statistics.go | starcoder |
package database
import (
"time"
"gorm.io/gorm"
)
type (
Diff struct {
Target
ExpectedState string
ActualState string
ScanID time.Time
Comment string
}
DiffAB struct {
Target
StateA string
StateB string
ScanA time.Time
ScanB time.Time
}
)
func CurrentState(db *gorm.DB) (state []ActualState, err error) {
state = make([]ActualState, 0)
err = currentState(db).Scan(&state).Error
if err != nil {
return nil, err
}
return state, nil
}
func DiffExpected(db *gorm.DB) (diff []Diff, err error) {
diff = make([]Diff, 0)
err = db.Table("expected_states a").Select("address, port, protocol, a.state expected_state, b.state actual_state, scan_id, comment").Joins("FULL JOIN (?) b USING (address, port, protocol) WHERE a.state IS DISTINCT FROM b.state", currentState(db)).Scan(&diff).Error
if err != nil {
return nil, err
}
return diff, nil
}
func DiffOne(db *gorm.DB, id time.Time) (diff []DiffAB, err error) {
diff = make([]DiffAB, 0)
state := db.Model(&ActualState{}).Where(&ActualState{ScanID: id})
err = db.Table("(?) a", state).Select("address, port, protocol, a.state state_a, b.state state_b, a.scan_id scan_a, b.scan_id scan_b").Joins("LEFT JOIN (?) b USING (address, port, protocol) WHERE a.state IS DISTINCT FROM b.state", currentState(db)).Scan(&diff).Error
if err != nil {
return nil, err
}
return diff, nil
}
func DiffTwo(db *gorm.DB, id1, id2 time.Time) (diff []DiffAB, err error) {
diff = make([]DiffAB, 0)
state1 := db.Model(&ActualState{}).Where(&ActualState{ScanID: id1})
state2 := db.Model(&ActualState{}).Where(&ActualState{ScanID: id2})
err = db.Table("(?) a", state1).Select("address, port, protocol, a.state state_a, b.state state_b, a.scan_id scan_a, b.scan_id scan_b").Joins("FULL JOIN (?) b USING (address, port, protocol) WHERE a.state IS DISTINCT FROM b.state", state2).Scan(&diff).Error
if err != nil {
return nil, err
}
return diff, nil
}
func Expected(db *gorm.DB) (state []ExpectedState, err error) {
state = make([]ExpectedState, 0)
err = db.Find(&state).Error
if err != nil {
return nil, err
}
return state, nil
}
func Prune(db *gorm.DB, keep time.Time) error {
current := db.Model(&ActualState{}).Select("MAX(scan_id)").Group("address, port, protocol")
err := db.Delete(&Scan{}, "id NOT IN (?) AND id < ?", current, keep).Error
if err != nil {
return err
}
err = db.Delete(&ActualState{}, "ROW(address, port, protocol, scan_id) NOT IN (?) AND scan_id < ?", current.Select("address, port, protocol, MAX(scan_id)"), keep).Error
if err != nil {
return err
}
return nil
}
func Scans(db *gorm.DB) (scans []Scan, err error) {
scans = make([]Scan, 0)
err = db.Find(&scans).Error
if err != nil {
return nil, err
}
return scans, nil
}
func StateAt(db *gorm.DB, id time.Time) (state []ActualState, err error) {
state = make([]ActualState, 0)
err = db.Where(&ActualState{ScanID: id}).Find(&state, id).Error
if err != nil {
return nil, err
}
return state, nil
}
func currentState(db *gorm.DB) *gorm.DB {
latestScans := db.Model(&ActualState{}).Select("address addr, port p, protocol proto, MAX(scan_id) max_scan_id").Group("addr, p, proto")
return db.Model(&ActualState{}).Joins("JOIN (?) latest_scans ON address = addr AND port = p AND protocol = proto AND scan_id = max_scan_id", latestScans)
} | scanalyzer/internal/database/query.go | 0.558327 | 0.402099 | query.go | starcoder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.