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 proto import ( "math" "reflect" ) func MarshalBool(b *Buffer, fieldIndex uint64, value bool) error { if !value { return nil } b.EncodeVarint(makeWireTag(fieldIndex, WireVarint)) if value { b.buf = append(b.buf, 1) } else { b.buf = append(b.buf, 0) } return nil } func MarshalInt32(b *Buffer, fieldIndex uint64, value int32) error { switch { case value > 0: b.EncodeVarint(makeWireTag(fieldIndex, WireVarint)) b.EncodeVarint(uint64(value)) case value < 0: b.EncodeVarint(makeWireTag(fieldIndex, WireZigzag32)) b.EncodeVarint(Zigzag32(uint64(value))) } return nil } func MarshalUInt32(b *Buffer, fieldIndex uint64, value uint32) error { if value == 0 { return nil } b.EncodeVarint(makeWireTag(fieldIndex, WireVarint)) b.EncodeVarint(uint64(value)) return nil } func MarshalInt64(b *Buffer, fieldIndex uint64, value int64) error { switch { case value > 0: b.EncodeVarint(makeWireTag(fieldIndex, WireVarint)) b.EncodeVarint(uint64(value)) case value < 0: b.EncodeVarint(makeWireTag(fieldIndex, WireZigzag64)) b.EncodeVarint(Zigzag64(uint64(value))) } return nil } func MarshalUInt64(b *Buffer, fieldIndex uint64, value uint64) error { if value == 0 { return nil } b.EncodeVarint(makeWireTag(fieldIndex, WireVarint)) b.EncodeVarint(value) return nil } func MarshalFloat32(b *Buffer, fieldIndex uint64, value float32) error { if value == 0 { return nil } b.EncodeVarint(makeWireTag(fieldIndex, WireFixed32)) b.EncodeFixed32(uint64(math.Float32bits(value))) return nil } func MarshalFloat64(b *Buffer, fieldIndex uint64, value float64) error { if value == 0 { return nil } b.EncodeVarint(makeWireTag(fieldIndex, WireFixed64)) b.EncodeFixed64(uint64(math.Float64bits(value))) return nil } func MarshalString(b *Buffer, fieldIndex uint64, value string) error { if value == "" { return nil } b.EncodeVarint(makeWireTag(fieldIndex, WireBytes)) b.EncodeStringBytes(value) return nil } func MarshalStruct(b *Buffer, fieldIndex uint64, msg Struct) error { structValue := reflect.ValueOf(msg) // *MyType被Message包裹后,判断不为nil if structValue.IsNil() { return nil } size := msg.Size() if size == 0 { return nil } b.EncodeVarint(makeWireTag(fieldIndex, WireBytes)) b.EncodeVarint(uint64(size)) return msg.Marshal(b) }
vendor/github.com/davyxu/protoplus/proto/field_marshal.go
0.551815
0.455622
field_marshal.go
starcoder
package render import ( "image" "image/color" "math" ) type Image16Bit struct { imageData *image.RGBA } func NewImage16Bit(x int, y int, width int, height int) *Image16Bit { return &Image16Bit{ imageData: image.NewRGBA(image.Rect(x, y, x+width, y+height)), } } func ConvertPixelsToImage16Bit(sourcePixels [][]uint16) *Image16Bit { width := len(sourcePixels[0]) height := len(sourcePixels) imageData := image.NewRGBA(image.Rect(0, 0, width, height)) for y := 0; y < height; y++ { for x := 0; x < width; x++ { c := convert16BitColor(sourcePixels[y][x]) imageData.SetRGBA(x, y, c) } } return &Image16Bit{ imageData: imageData, } } func (image16bit *Image16Bit) GetWidth() int { return image16bit.imageData.Bounds().Dx() } func (image16bit *Image16Bit) GetHeight() int { return image16bit.imageData.Bounds().Dy() } func (image16bit *Image16Bit) Clear() { minPoint := image16bit.imageData.Bounds().Min maxPoint := image16bit.imageData.Bounds().Max for y := minPoint.Y; y < maxPoint.Y; y++ { for x := minPoint.X; x < maxPoint.X; x++ { image16bit.imageData.SetRGBA(x, y, color.RGBA{0, 0, 0, 0}) } } } func (image16bit *Image16Bit) WriteSubImage( destOrigin image.Point, sourceImage *Image16Bit, sourceBounds image.Rectangle, ) { subImageWidth := sourceBounds.Dx() subImageHeight := sourceBounds.Dy() for offsetY := 0; offsetY < subImageHeight; offsetY++ { for offsetX := 0; offsetX < subImageWidth; offsetX++ { sourceColor := sourceImage.imageData.RGBAAt(sourceBounds.Min.X+offsetX, sourceBounds.Min.Y+offsetY) // Skip writing transparent pixels if sourceColor.A > 0 { image16bit.imageData.SetRGBA(destOrigin.X+offsetX, destOrigin.Y+offsetY, sourceColor) } } } } // Multiply pixels by a brightness factor // Less than 1.0 will darken it func (image16bit *Image16Bit) WriteSubImageUniformBrightness( destOrigin image.Point, sourceImage *Image16Bit, sourceBounds image.Rectangle, factor float64, ) { subImageWidth := sourceBounds.Dx() subImageHeight := sourceBounds.Dy() for offsetY := 0; offsetY < subImageHeight; offsetY++ { for offsetX := 0; offsetX < subImageWidth; offsetX++ { sourceColor := sourceImage.imageData.RGBAAt(sourceBounds.Min.X+offsetX, sourceBounds.Min.Y+offsetY) newR := int(math.Floor(float64(sourceColor.R) * factor)) newG := int(math.Floor(float64(sourceColor.G) * factor)) newB := int(math.Floor(float64(sourceColor.B) * factor)) modifiedSourceColor := color.RGBA{uint8(newR), uint8(newG), uint8(newB), sourceColor.A} // Skip writing transparent pixels if modifiedSourceColor.A > 0 { image16bit.imageData.SetRGBA(destOrigin.X+offsetX, destOrigin.Y+offsetY, modifiedSourceColor) } } } } func (image16bit *Image16Bit) WriteSubImageVariableBrightness( destOrigin image.Point, sourceImage *Image16Bit, sourceBounds image.Rectangle, rgbFactor [3]float64, ) { subImageWidth := sourceBounds.Dx() subImageHeight := sourceBounds.Dy() for offsetY := 0; offsetY < subImageHeight; offsetY++ { for offsetX := 0; offsetX < subImageWidth; offsetX++ { sourceColor := sourceImage.imageData.RGBAAt(sourceBounds.Min.X+offsetX, sourceBounds.Min.Y+offsetY) newR := int(math.Floor(float64(sourceColor.R) * rgbFactor[0])) newG := int(math.Floor(float64(sourceColor.G) * rgbFactor[1])) newB := int(math.Floor(float64(sourceColor.B) * rgbFactor[2])) modifiedSourceColor := color.RGBA{uint8(newR), uint8(newG), uint8(newB), sourceColor.A} // Skip writing transparent pixels if modifiedSourceColor.A > 0 { image16bit.imageData.SetRGBA(destOrigin.X+offsetX, destOrigin.Y+offsetY, modifiedSourceColor) } } } } func (image16bit *Image16Bit) FillPixels( destOrigin image.Point, sourceBounds image.Rectangle, fillColor color.RGBA, ) { subImageWidth := sourceBounds.Dx() subImageHeight := sourceBounds.Dy() for offsetY := 0; offsetY < subImageHeight; offsetY++ { for offsetX := 0; offsetX < subImageWidth; offsetX++ { image16bit.imageData.SetRGBA(destOrigin.X+offsetX, destOrigin.Y+offsetY, fillColor) } } } func (image16bit *Image16Bit) ApplyMask( destOrigin image.Point, sourceImage *Image16Bit, sourceBounds image.Rectangle, ) { subImageWidth := sourceBounds.Dx() subImageHeight := sourceBounds.Dy() for offsetY := 0; offsetY < subImageHeight; offsetY++ { for offsetX := 0; offsetX < subImageWidth; offsetX++ { destOriginalColor := image16bit.imageData.RGBAAt(destOrigin.X+offsetX, destOrigin.Y+offsetY) sourceColor := sourceImage.imageData.RGBAAt(sourceBounds.Min.X+offsetX, sourceBounds.Min.Y+offsetY) // Set destination pixel to transparent if the mask pixel is transparent (pixel value is 0) destModifiedColor := color.RGBA{destOriginalColor.R, destOriginalColor.G, destOriginalColor.B, sourceColor.A} image16bit.imageData.SetRGBA(destOrigin.X+offsetX, destOrigin.Y+offsetY, destModifiedColor) } } } // OpenGL renderer uses a 1d array to render pixels to screen func (image16bit *Image16Bit) GetPixelsForRendering() []uint16 { bounds := image16bit.imageData.Bounds() width := bounds.Dx() height := bounds.Dy() pixelData1D := make([]uint16, width*height) for y := 0; y < height; y++ { for x := 0; x < width; x++ { index := (y * width) + x pixelData1D[index] = convertRGBAToA1B5G5R5(image16bit.imageData.RGBAAt(x, y)) } } return pixelData1D } // Original pixel is 16 bits in the A1B5G5R5 format // Extract RGBA values func convert16BitColor(pixel uint16) color.RGBA { // r, g, b only has values in range 0 - 32 // scale to 0 - 256 pixelR := (pixel % 32) * 8 pixelG := ((pixel >> 5) % 32) * 8 pixelB := ((pixel >> 10) % 32) * 8 if pixel > 0 { return color.RGBA{uint8(pixelR), uint8(pixelG), uint8(pixelB), uint8(255)} } else { return color.RGBA{0, 0, 0, 0} } } func convertRGBAToA1B5G5R5(pixelColor color.RGBA) uint16 { // Convert color to A1R5G5B5 format for OpenGL rendering newR := uint16(math.Round(float64(pixelColor.R) / 8.0)) newG := uint16(math.Round(float64(pixelColor.G) / 8.0)) newB := uint16(math.Round(float64(pixelColor.B) / 8.0)) if newR >= 32 { newR = 31 } if newG >= 32 { newG = 31 } if newB >= 32 { newB = 31 } newA := uint16(math.Floor(float64(pixelColor.A) / 255.0)) return (newA << 15) | (newB << 10) | (newG << 5) | newR }
render/image16bit.go
0.792946
0.457258
image16bit.go
starcoder
package draw import ( "github.com/faiface/pixel" "github.com/faiface/pixel/imdraw" "image/color" ) type vector = pixel.Vec func v(x, y float64) vector { return pixel.V(x, y) } // Board draws a tic-tac-toe board of squares where // length is length of sides of squares, // thickness is thickness of lines on board // and lineColor is color of lines on board func Board(imd *imdraw.IMDraw, length, thickness float64, lineColor color.Color) { imd.Color = lineColor Square(imd, length, 0, 0, thickness) Square(imd, length, 0, length, thickness) Square(imd, length, 0, 2*length, thickness) Square(imd, length, length, 0, thickness) Square(imd, length, length, length, thickness) Square(imd, length, length, 2*length, thickness) Square(imd, length, 2*length, 0, thickness) Square(imd, length, 2*length, length, thickness) Square(imd, length, 2*length, 2*length, thickness) } // Square draws an individual square where // length is the length of sides of square, // thickness is the thickness of border of square, // and x,y are the position of bottom left corner of square func Square(imd *imdraw.IMDraw, length, x, y, thickness float64) { imd.Push(v(x, y)) imd.Push(v(x, y+length)) imd.Push(v(x+length, y)) imd.Push(v(x+length, y+length)) imd.Rectangle(thickness) } // O draws an O (circle) mark where // c is center position of the circle // radius is the length from center of circle to its border, // thickness is the thickness of border of circle, // and color is the color of the circle func O(imd *imdraw.IMDraw, c vector, radius, thickness float64, color color.Color) { imd.Color = color imd.Push(c) imd.Circle(radius, thickness) } // X draws an X (cross) mark where // c is center position of the cross // length is the length of each diagonal in the cross, // thickness is the thickness of the cross, // and color is the color of the cross func X(imd *imdraw.IMDraw, c vector, length, thickness float64, color color.Color) { imd.Color = color l := length / 2 imd.Push(v(c.X-l, c.Y-l), v(c.X+l, c.Y+l)) imd.Line(thickness) imd.Push(v(c.X+l, c.Y-l), v(c.X-l, c.Y+l)) imd.Line(thickness) } // Line draws a line across marked squares (to show victory) where // c1 is center position of the square at one end of the line // c2 is center position of the square at other end of the line // o1 is potental offset with which to extend the line at one end // o2 is potental offset with which to extend the line at other end // thickness is the thickness of the line, // and color is the color of the line func Line(imd *imdraw.IMDraw, c1, c2, o1, o2 vector, thickness float64, color color.Color) { imd.Color = color if c1.X == c2.X { imd.Push(c1.Add(v(0, o1.Y)), c2.Add(v(0, o2.Y))) } else if c1.Y == c2.Y { imd.Push(c1.Add(v(o1.X, 0)), c2.Add(v(o2.X, 0))) } else { imd.Push(c1.Add(o1), c2.Add(o2)) } imd.Line(thickness) }
draw/draw.go
0.697506
0.488039
draw.go
starcoder
package vector import ( "fmt" "github.com/liyue201/gostl/utils/iterator" ) // Options holds the Vector's options type Options struct { capacity int } // Option is a function type used to set Options type Option func(option *Options) // WithCapacity is used to set the capacity of a Vector func WithCapacity(capacity int) Option { return func(option *Options) { option.capacity = capacity } } // Vector is a linear data structure, the internal is a slice type Vector struct { data []interface{} } // New creates a new Vector func New(opts ...Option) *Vector { option := Options{} for _, opt := range opts { opt(&option) } return &Vector{ data: make([]interface{}, 0, option.capacity), } } // NewFromVector news a Vector from other Vector func NewFromVector(other *Vector) *Vector { v := &Vector{data: make([]interface{}, other.Size(), other.Capacity())} for i := range other.data { v.data[i] = other.data[i] } return v } // Size returns the size of the vector func (v *Vector) Size() int { return len(v.data) } // Capacity returns the capacity of the vector func (v *Vector) Capacity() int { return cap(v.data) } // Empty returns true if the vector is empty, otherwise returns false func (v *Vector) Empty() bool { if len(v.data) == 0 { return true } return false } // PushBack pushes val to the back of the vector func (v *Vector) PushBack(val interface{}) { v.data = append(v.data, val) } // SetAt sets the value val to the vector at position pos func (v *Vector) SetAt(pos int, val interface{}) { if pos < 0 || pos >= v.Size() { return } v.data[pos] = val } // InsertAt inserts the value val to the vector at position pos func (v *Vector) InsertAt(pos int, val interface{}) { if pos < 0 || pos > v.Size() { return } v.data = append(v.data, val) for i := len(v.data) - 1; i > pos; i-- { v.data[i] = v.data[i-1] } v.data[pos] = val } // EraseAt erases the value at position pos func (v *Vector) EraseAt(pos int) { v.EraseIndexRange(pos, pos+1) } // EraseIndexRange erases values at range[first, last) func (v *Vector) EraseIndexRange(first, last int) { if first > last { return } if first < 0 || last > v.Size() { return } left := v.data[:first] right := v.data[last:] v.data = append(left, right...) } // At returns the value at position pos, returns nil if pos is out off range . func (v *Vector) At(pos int) interface{} { if pos < 0 || pos >= v.Size() { return nil } return v.data[pos] } //Front returns the first value in the vector, returns nil if the vector is empty. func (v *Vector) Front() interface{} { return v.At(0) } //Back returns the last value in the vector, returns nil if the vector is empty. func (v *Vector) Back() interface{} { return v.At(v.Size() - 1) } //PopBack returns the last value of the vector and erase it, returns nil if the vector is empty. func (v *Vector) PopBack() interface{} { if v.Empty() { return nil } val := v.Back() v.data = v.data[:len(v.data)-1] return val } //Reserve makes a new space for the vector with passed capacity func (v *Vector) Reserve(capacity int) { if cap(v.data) >= capacity { return } data := make([]interface{}, v.Size(), capacity) for i := 0; i < len(v.data); i++ { data[i] = v.data[i] } v.data = data } // ShrinkToFit shrinks the capacity of the vector to the fit size func (v *Vector) ShrinkToFit() { if len(v.data) == cap(v.data) { return } len := v.Size() data := make([]interface{}, len, len) for i := 0; i < len; i++ { data[i] = v.data[i] } v.data = data } // Clear clears all data in the vector func (v *Vector) Clear() { v.data = v.data[:0] } // Data returns internal data of the vector func (v *Vector) Data() []interface{} { return v.data } // Begin returns the first iterator of the vector func (v *Vector) Begin() *VectorIterator { return v.First() } // End returns the end iterator of the vector func (v *Vector) End() *VectorIterator { return v.IterAt(v.Size()) } // First returns the first iterator of the vector func (v *Vector) First() *VectorIterator { return v.IterAt(0) } // Last returns the last iterator of the vector func (v *Vector) Last() *VectorIterator { return v.IterAt(v.Size() - 1) } // IterAt returns the iterator at position of the vector func (v *Vector) IterAt(pos int) *VectorIterator { return &VectorIterator{vec: v, position: pos} } // Insert inserts a value val to the vector at the position of the iterator iter point to func (v *Vector) Insert(iter iterator.ConstIterator, val interface{}) *VectorIterator { index := iter.(*VectorIterator).position v.InsertAt(index, val) return &VectorIterator{vec: v, position: index} } // Erase erases the element of the iterator iter point to func (v *Vector) Erase(iter iterator.ConstIterator) *VectorIterator { index := iter.(*VectorIterator).position v.EraseAt(index) return &VectorIterator{vec: v, position: index} } // EraseRange erases all elements in the range[first, last) func (v *Vector) EraseRange(first, last iterator.ConstIterator) *VectorIterator { from := first.(*VectorIterator).position to := last.(*VectorIterator).position v.EraseIndexRange(from, to) return &VectorIterator{vec: v, position: from} } // Resize resizes the size of the vector to the passed size func (v *Vector) Resize(size int) { if size >= v.Size() { return } v.data = v.data[:size] } // String returns a string representation of the vector func (v *Vector) String() string { return fmt.Sprintf("%v", v.data) }
ds/vector/vector.go
0.835316
0.538194
vector.go
starcoder
package codec import ( "time" "github.com/juju/errors" "github.com/pingcap/tidb/mysql" "github.com/pingcap/tidb/util/types" ) const ( nilFlag byte = 0 bytesFlag byte = 1 compactBytesFlag byte = 2 intFlag byte = 3 uintFlag byte = 4 floatFlag byte = 5 decimalFlag byte = 6 durationFlag byte = 7 maxFlag byte = 250 ) func encode(b []byte, vals []types.Datum, comparable bool) ([]byte, error) { for _, val := range vals { switch val.Kind() { case types.KindInt64: b = append(b, intFlag) b = EncodeInt(b, val.GetInt64()) case types.KindUint64: b = append(b, uintFlag) b = EncodeUint(b, val.GetUint64()) case types.KindFloat32, types.KindFloat64: b = append(b, floatFlag) b = EncodeFloat(b, val.GetFloat64()) case types.KindString, types.KindBytes: b = encodeBytes(b, val.GetBytes(), comparable) case types.KindMysqlTime: b = encodeBytes(b, []byte(val.GetMysqlTime().String()), comparable) case types.KindMysqlDuration: // duration may have negative value, so we cannot use String to encode directly. b = append(b, durationFlag) b = EncodeInt(b, int64(val.GetMysqlDuration().Duration)) case types.KindMysqlDecimal: b = append(b, decimalFlag) b = EncodeDecimal(b, val.GetMysqlDecimal()) case types.KindMysqlHex: b = append(b, intFlag) b = EncodeInt(b, int64(val.GetMysqlHex().ToNumber())) case types.KindMysqlBit: b = append(b, uintFlag) b = EncodeUint(b, uint64(val.GetMysqlBit().ToNumber())) case types.KindMysqlEnum: b = append(b, uintFlag) b = EncodeUint(b, uint64(val.GetMysqlEnum().ToNumber())) case types.KindMysqlSet: b = append(b, uintFlag) b = EncodeUint(b, uint64(val.GetMysqlSet().ToNumber())) case types.KindNull: b = append(b, nilFlag) case types.KindMinNotNull: b = append(b, bytesFlag) case types.KindMaxValue: b = append(b, maxFlag) default: return nil, errors.Errorf("unsupport encode type %d", val.Kind()) } } return b, nil } func encodeBytes(b []byte, v []byte, comparable bool) []byte { if comparable { b = append(b, bytesFlag) b = EncodeBytes(b, v) } else { b = append(b, compactBytesFlag) b = EncodeCompactBytes(b, v) } return b } // EncodeKey appends the encoded values to byte slice b, returns the appended // slice. It guarantees the encoded value is in ascending order for comparison. func EncodeKey(b []byte, v ...types.Datum) ([]byte, error) { return encode(b, v, true) } // EncodeValue appends the encoded values to byte slice b, returning the appended // slice. It does not guarantee the order for comparison. func EncodeValue(b []byte, v ...types.Datum) ([]byte, error) { return encode(b, v, false) } // Decode decodes values from a byte slice generated with EncodeKey or EncodeValue // before. func Decode(b []byte) ([]types.Datum, error) { if len(b) < 1 { return nil, errors.New("invalid encoded key") } var ( err error values = make([]types.Datum, 0, 1) ) for len(b) > 0 { var d types.Datum b, d, err = DecodeOne(b) if err != nil { return nil, errors.Trace(err) } values = append(values, d) } return values, nil } // DecodeOne decodes on datum from a byte slice generated with EncodeKey or EncodeValue. func DecodeOne(b []byte) (remain []byte, d types.Datum, err error) { if len(b) < 1 { return nil, d, errors.New("invalid encoded key") } flag := b[0] b = b[1:] switch flag { case intFlag: var v int64 b, v, err = DecodeInt(b) d.SetInt64(v) case uintFlag: var v uint64 b, v, err = DecodeUint(b) d.SetUint64(v) case floatFlag: var v float64 b, v, err = DecodeFloat(b) d.SetFloat64(v) case bytesFlag: var v []byte b, v, err = DecodeBytes(b) d.SetBytes(v) case compactBytesFlag: var v []byte b, v, err = DecodeCompactBytes(b) d.SetBytes(v) case decimalFlag: var v mysql.Decimal b, v, err = DecodeDecimal(b) d.SetValue(v) case durationFlag: var r int64 b, r, err = DecodeInt(b) if err == nil { // use max fsp, let outer to do round manually. v := mysql.Duration{Duration: time.Duration(r), Fsp: mysql.MaxFsp} d.SetValue(v) } case nilFlag: default: return b, d, errors.Errorf("invalid encoded key flag %v", flag) } if err != nil { return b, d, errors.Trace(err) } return b, d, nil }
util/codec/codec.go
0.555676
0.426799
codec.go
starcoder
package graphql import ( "reflect" "strconv" "time" ) type Result reflect.Value func (q Result) Q(a interface{}) Result { v := reflect.Value(q) for v.Kind() == reflect.Interface { v = v.Elem() } if v.Kind() == reflect.Map { return Result(v.MapIndex(reflect.ValueOf(a))) } else if v.Kind() == reflect.Slice { return Result(v.Index(int(reflect.ValueOf(a).Int()))) } return Result{} } func (q Result) V(a interface{}) (r reflect.Value) { v := reflect.Value(q) for v.Kind() == reflect.Interface { v = v.Elem() } if v.Kind() == reflect.Map { r = v.MapIndex(reflect.ValueOf(a)) } else if v.Kind() == reflect.Slice { r = v.Index(int(reflect.ValueOf(a).Int())) } for r.Kind() == reflect.Interface { r = r.Elem() } return } func (q Result) List() []Result { v := (reflect.Value)(q) for v.Kind() == reflect.Interface { v = v.Elem() } if v.Kind() == reflect.Slice { r := make([]Result, v.Len(), v.Len()) for i := range r { r[i] = Result(v.Index(i)) } return r } panic("is not list") } func (q Result) Chan() chan Result { v := (reflect.Value)(q) for v.Kind() == reflect.Interface { v = v.Elem() } if v.Kind() == reflect.Slice { c := make(chan Result) go func() { defer close(c) for i := 0; i < v.Len(); i++ { c <- Result(v.Index(i)) } }() return c } panic("is not list") } func (q Result) String(a interface{}) string { v := q.V(a) if !v.IsValid() { return "" } return v.String() } func (q Result) Float32(a interface{}) float32 { v := q.V(a) if !v.IsValid() { return 0 } switch v.Kind() { case reflect.String: f, err := strconv.ParseFloat(v.String(), 32) if err != nil { panic(err.Error()) } return float32(f) case reflect.Float64, reflect.Float32: return float32(v.Float()) default: return float32(v.Int()) } } func (q Result) Float64(a interface{}) float64 { v := q.V(a) if !v.IsValid() { return 0 } switch v.Kind() { case reflect.String: f, err := strconv.ParseFloat(v.String(), 32) if err != nil { panic(err.Error()) } return f case reflect.Float64, reflect.Float32: return v.Float() default: return float64(v.Int()) } } func (q Result) Int(a interface{}) int { v := q.V(a) if !v.IsValid() { return 0 } switch v.Kind() { case reflect.String: i, err := strconv.ParseInt(v.String(), 10, 32) if err != nil { panic(err.Error()) } return int(i) case reflect.Float32, reflect.Float64: return int(v.Float()) } return int(v.Int()) } func (q Result) Time(a interface{}) time.Time { v := q.V(a) if !v.IsValid() { return time.Time{} } if v.Kind() == reflect.String { t, err := time.Parse(time.RFC3339, v.String()) if err != nil { panic(err.Error()) } return t } panic("not string") } func (q Result) Fill(a interface{}) { av := reflect.ValueOf(a).Elem() // a is a ptr to struct at := av.Type() for i := 0; i < at.NumField(); i++ { f := av.Field(i) ft := at.Field(i) switch f.Kind() { case reflect.String: f.Set(reflect.ValueOf(q.String(ft.Name))) case reflect.Float32: f.Set(reflect.ValueOf(q.Float32(ft.Name))) case reflect.Float64: f.Set(reflect.ValueOf(q.Float64(ft.Name))) case reflect.Int, reflect.Int32, reflect.Int64: f.Set(reflect.ValueOf(q.Int(ft.Name))) default: if f.Type() == reflect.TypeOf(time.Time{}) { f.Set(reflect.ValueOf(q.Time(ft.Name))) } else { panic("unsupported type of filed " + ft.Name) } } } }
result.go
0.522202
0.407746
result.go
starcoder
package sketchy import "math" // Generates a Chaikin curve given a set of control points, // a cutoff ratio, and the number of steps to use in the // calculation. func Chaikin(c Curve, q float64, n int) Curve { points := []Point{} // Start with control points points = append(points, c.Points...) left := q / 2 right := 1 - (q / 2) for i := 0; i < n; i++ { newPoints := []Point{} for j := 0; j < len(points)-1; j++ { p1 := points[j] p2 := points[j+1] q := Point{ X: right*p1.X + left*p2.X, Y: right*p1.Y + left*p2.Y, } r := Point{ X: left*p1.X + right*p2.X, Y: left*p1.Y + right*p2.Y, } newPoints = append(newPoints, q, r) } if c.Closed { p1 := points[len(points)-1] p2 := points[0] q := Point{ X: right*p1.X + left*p2.X, Y: right*p1.Y + left*p2.Y, } r := Point{ X: left*p1.X + right*p2.X, Y: left*p1.Y + right*p2.Y, } newPoints = append(newPoints, q, r) } points = []Point{} points = append(points, newPoints...) } return Curve{Points: points, Closed: c.Closed} } // Core parametrers for a 2D Lissajous curve type Lissajous struct { Nx int Ny int Px float64 Py float64 } // Generates a Lissajous curve given parameters, a number of points // to use (i.e. resolution), and an offset and scale (typically to convert // to screen coordinates) func GenLissajous(l Lissajous, n int, offset Point, s float64) Curve { curve := Curve{} maxPhase := Tau / float64(Gcd(l.Nx, l.Ny)) dt := maxPhase / float64(n) for t := 0.0; t < maxPhase; t += dt { xPos := s*math.Sin(float64(l.Nx)*t+l.Px) + offset.X yPos := s*math.Sin(float64(l.Ny)*t+l.Py) + offset.Y point := Point{X: xPos, Y: yPos} curve.Points = append(curve.Points, point) } return curve } // Calculates Padua points for a certain class of Lissajous curves, // where Nx = Ny +/- 1. The correspond to intersection points and // some of the outside points on the curve // See https://en.wikipedia.org/wiki/Padua_points for more details. func PaduaPoints(n int) []Point { points := []Point{} for i := 0; i <= n; i++ { delta := 0 if n%2 == 1 && i%2 == 1 { delta = 1 } for j := 1; j < (n/2)+2+delta; j++ { x := math.Cos(float64(i) * Pi / float64(n)) var y float64 if i%2 == 1 { y = math.Cos(float64(2*j-2) * Pi / float64(n+1)) } else { y = math.Cos(float64(2*j-1) * Pi / float64(n+1)) } points = append(points, Point{X: x, Y: y}) } } return points }
curves.go
0.846101
0.562837
curves.go
starcoder
package reflecthelper import ( "net" "net/url" "reflect" "time" ) // List of reflect.Type used in this package var ( TypeRuneSlice = reflect.TypeOf([]rune{}) TypeByteSlice = reflect.TypeOf([]byte{}) TypeTimePtr = reflect.TypeOf(new(time.Time)) TypeTime = reflect.TypeOf(time.Time{}) TypeDurationPtr = reflect.TypeOf(new(time.Duration)) TypeDuration = reflect.TypeOf(time.Duration(0)) TypeURLPtr = reflect.TypeOf(new(url.URL)) TypeURL = reflect.TypeOf(url.URL{}) TypeIPPtr = reflect.TypeOf(new(net.IP)) TypeIP = reflect.TypeOf(net.IP{}) ) // IsTypeValueElemable checks if the type of the reflect.Value can call Elem. func IsTypeValueElemable(val reflect.Value) bool { return IsKindTypeElemable(GetKind(val)) } // IsTypeElemable checks wether the typ of reflect.Type can call Elem method. func IsTypeElemable(typ reflect.Type) (res bool) { if typ == nil { return } res = IsKindTypeElemable(typ.Kind()) return } // GetType is a wrapper for val.Type() to safely extract type if it is valid. func GetType(val reflect.Value) (typ reflect.Type) { if !val.IsValid() { return } typ = val.Type() return } // GetElemType returns the elem type of a val of reflect.Value. func GetElemType(val reflect.Value) (typ reflect.Type) { if !val.IsValid() { return } typ = val.Type() if IsTypeValueElemable(val) { typ = typ.Elem() } return } // GetElemTypeOfType returns the elem type of the input of reflect.Type. func GetElemTypeOfType(input reflect.Type) (typ reflect.Type) { typ = input if typ == nil { return } if IsTypeElemable(typ) { typ = typ.Elem() } return } // GetChildElemType returns the child elems' (root child) type of the val of reflect.Value. func GetChildElemType(val reflect.Value) (typ reflect.Type) { if !val.IsValid() { return } typ = val.Type() for IsTypeElemable(typ) { typ = typ.Elem() } return } // GetChildElemTypeOfType returns the child elems' (root child) type of the input of reflect.Type. func GetChildElemTypeOfType(input reflect.Type) (typ reflect.Type) { typ = input if typ == nil { return } for IsTypeElemable(typ) { typ = typ.Elem() } return } // GetChildElemPtrType returns the child elems' (root child) ptr type of the val of reflect.Value. func GetChildElemPtrType(val reflect.Value) (typ reflect.Type) { if !val.IsValid() { return } typ = val.Type() res := typ.Kind() for res == reflect.Ptr { typ = typ.Elem() res = typ.Kind() } return } // GetChildElemPtrTypeOfType returns the child elems' (root child) ptr type of the input of reflect.Type. func GetChildElemPtrTypeOfType(input reflect.Type) (typ reflect.Type) { typ = input if typ == nil { return } res := typ.Kind() for res == reflect.Ptr { typ = typ.Elem() res = typ.Kind() } return } // GetChildElemValueType returns the child elem's (root child) type of the val reflect.Value and it only works on ptr kind. func GetChildElemValueType(val reflect.Value) (typ reflect.Type) { typ = GetChildElemPtrType(UnwrapInterfaceValue(val)) return } // IsTypeValueDuration checks whether the type of val reflect.Value is time.Duration or *time.Duration. func IsTypeValueDuration(val reflect.Value) bool { typeVal := GetType(val) return typeVal == TypeDuration || typeVal == TypeDurationPtr } // IsTypeValueTime checks whether the type of val reflect.Value is time.Time or *time.Time. func IsTypeValueTime(val reflect.Value) bool { typeVal := GetType(val) return typeVal == TypeTime || typeVal == TypeTimePtr } // IsTypeValueURL checks whether the type of val reflect.Value is url.URL or *url.URL. func IsTypeValueURL(val reflect.Value) bool { typeVal := GetType(val) return typeVal == TypeURL || typeVal == TypeURLPtr } // IsTypeValueIP checks whether the type of val reflect.Value is net.IP or *net.IP. func IsTypeValueIP(val reflect.Value) bool { typeVal := GetType(val) return typeVal == TypeIP || typeVal == TypeIPPtr }
vendor/github.com/fairyhunter13/reflecthelper/v4/type.go
0.613584
0.467028
type.go
starcoder
package smd // EPThruster defines a EPThruster interface. type EPThruster interface { // Returns the minimum power and voltage requirements for this EPThruster. Min() (voltage, power uint) // Returns the max power and voltage requirements for this EPThruster. Max() (voltage, power uint) // Returns the thrust in Newtons and isp consumed in seconds. Thrust(voltage, power uint) (thrust, isp float64) } /* Available EPThrusters */ // PPS1350 is the Snecma EPThruster used on SMART-1. type PPS1350 struct{} // Min implements the EPThruster interface. func (t *PPS1350) Min() (voltage, power uint) { return t.Max() } // Max implements the EPThruster interface. func (t *PPS1350) Max() (voltage, power uint) { return 350, 2500 } // Thrust implements the EPThruster interface. func (t *PPS1350) Thrust(voltage, power uint) (thrust, isp float64) { if voltage == 350 && power == 2500 { return 89e-3, 1650 } panic("unsupported voltage or power provided") } // PPS5000 is the latest Snecma EPThruster. type PPS5000 struct{} // Min implements the EPThruster interface. func (t *PPS5000) Min() (voltage, power uint) { return t.Max() } // Max implements the EPThruster interface. func (t *PPS5000) Max() (voltage, power uint) { return 350, 2500 // From 1350, not the actual values! } // Thrust implements the EPThruster interface. func (t *PPS5000) Thrust(voltage, power uint) (thrust, isp float64) { if voltage == 350 && power == 2500 { return 310e-3, 1800 } panic("unsupported voltage or power provided") } // BHT1500 is a Busek 1500 EPThruster. // Below is the high thrust mode type BHT1500 struct{} // Min implements the EPThruster interface. func (t *BHT1500) Min() (voltage, power uint) { return t.Max() } // Max implements the EPThruster interface. func (t *BHT1500) Max() (voltage, power uint) { return 1, 2700 // Didn't find the voltage } // Thrust implements the EPThruster interface. func (t *BHT1500) Thrust(voltage, power uint) (thrust, isp float64) { return 179e-3, 1865 } // BHT8000 is a Busek 1500 EPThruster. // Below is the high thrust mode type BHT8000 struct{} // Min implements the EPThruster interface. func (t *BHT8000) Min() (voltage, power uint) { return t.Max() } // Max implements the EPThruster interface. func (t *BHT8000) Max() (voltage, power uint) { return 400, 8e3 // From datasheet } // Thrust implements the EPThruster interface. func (t *BHT8000) Thrust(voltage, power uint) (thrust, isp float64) { return 449e-3, 2210 } // VX200 is a VASIMR 200 kW EPThruster. // Data from http://www.adastrarocket.com/Jared_IEPC11-154.pdf type VX200 struct{} // Min implements the EPThruster interface. func (t *VX200) Min() (voltage, power uint) { return t.Max() } // Max implements the EPThruster interface. func (t *VX200) Max() (voltage, power uint) { return 1, 200e3 // Incorrect voltage } // Thrust implements the EPThruster interface. func (t *VX200) Thrust(voltage, power uint) (thrust, isp float64) { return 5.8, 4900 } // HERMeS is based on the NASA & Rocketdyne 12.5kW demo type HERMeS struct{} // Min implements the EPThruster interface. func (t *HERMeS) Min() (voltage, power uint) { return t.Max() } // Max implements the EPThruster interface. func (t *HERMeS) Max() (voltage, power uint) { return 800, 12500 } // Thrust implements the EPThruster interface. func (t *HERMeS) Thrust(voltage, power uint) (thrust, isp float64) { if voltage == 800 && power == 12500 { return 0.680, 2960 } panic("unsupported voltage or power provided") } // GenericEP is a generic EP EPThruster. type GenericEP struct { thrust float64 isp float64 } // Min implements the EPThruster interface. func (t *GenericEP) Min() (voltage, power uint) { return 0, 0 } // Max implements the EPThruster interface. func (t *GenericEP) Max() (voltage, power uint) { return 0, 0 } // Thrust implements the EPThruster interface. func (t *GenericEP) Thrust(voltage, power uint) (thrust, isp float64) { return t.thrust, t.isp } // NewGenericEP returns a generic electric prop EPThruster. func NewGenericEP(thrust, isp float64) *GenericEP { return &GenericEP{thrust, isp} }
thrusters.go
0.885737
0.45048
thrusters.go
starcoder
package blockchain import ( "crypto/sha256" "errors" "math" "math/big" "personal/GoBlockchain/utils" ) //ErrFailedBlock is returned in case block fails to enter the blockchain var ErrFailedBlock = errors.New("Failed to incorporate block into blockchain") /*ProofOfWork defines the work that has to be done in order for a new block to enter the blockchain. It contains a Block pointer that refer to the new block we want to add to the blockchain, also it has a target big integer. target is used as the upper bound of the work that is needed to be done, more on that in the Run() method. */ type ProofOfWork struct { block *Block target *big.Int } /*NewProofOfWork returns a new proof of work for that block, here we specify the upper bound of the work. In the first 2 lines we create a number where the (256-b.TargetBits) digit is 1 and before that all digits are zero so: 00001XXXXXXXXX. This target will be used as a upper bound for the work. eg: If the work is to find a number (hash) that starts with at least 3 zeros, then target is: 001XXXXX...X and we need a number that is LESS than target. */ func NewProofOfWork(b *Block) *ProofOfWork { target := big.NewInt(1) target.Lsh(target, uint(256-b.TargetBits)) return &ProofOfWork{ block: b, target: target, } } /*newHeaders is used to create a new new header based on: - Hash of previous block - Data of block - Timestamp - Target bits (set the difficulty) - current nonce The header will be used for next iteration of work */ func (pow *ProofOfWork) newHeaders(nonce uint) []byte { return utils.ConcatByteSlices( pow.block.PreviousBlockHash, pow.block.Data, utils.UintToByteSlice(uint64(pow.block.Timestamp)), utils.UintToByteSlice(uint64(pow.block.TargetBits)), utils.UintToByteSlice(uint64(nonce)), ) } /*DoWork is the function that does the work needed to add the block into the blockchain, We start with a nonce = 0 and we prepare a header to be used in the new hash function. In order for this function to be correct it must be less than the target. Each time the hash fails to meet the requirement stated previous the nonce is increased and the hash is tried again. */ func (pow *ProofOfWork) DoWork() (uint, []byte, error) { var currentHash big.Int var maxNonce uint = math.MaxInt64 var hash [32]byte var nonce uint for nonce = 0; nonce < maxNonce; nonce++ { headers := pow.newHeaders(nonce) hash = sha256.Sum256(headers) currentHash.SetBytes(hash[:]) //currentHash < target if currentHash.Cmp(pow.target) == -1 { return nonce, hash[:], nil } } return 0, []byte{}, ErrFailedBlock }
blockchain/proof.go
0.532182
0.431884
proof.go
starcoder
package activation import ( "math/rand" "sync" "github.com/dowlandaiello/eve/common" ) // ParameterInitializationOption is an initialization option used to modify a // parameter's behavior. type ParameterInitializationOption = func(param Parameter) Parameter // LockedParameter is a data type used to synchronize a parameter. type LockedParameter struct { P Parameter // the parameter Mutex sync.Mutex // the lock } // Parameter is a data type used to hold arguments for an operation. type Parameter struct { // an integer parameter I int // a byte parameter B []byte // an abstract parameter A interface{} `graphql:"-"` } /* BEGIN EXPORTED METHODS */ // NewErrorParameter initializes a new abstract parameter with the given error. func NewErrorParameter(err error) Parameter { return Parameter{ A: err, // Set the abstract value of the param to an error } // Return the parameter } // RandomParameter initializes a new random parameter with the given // initialization options. func RandomParameter(opts ...ParameterInitializationOption) Parameter { var param Parameter // Declare a buffer to store the parameter r := rand.Intn(3) // Get a random number // Check the param should be abstract if r == 0 { param = randomAbstract() // Generate a param with a random abstract value } else if r == 1 { param = randomBytes() // Generate a random parameter with a random byte slice value } else { param = randomInt() // Generate a random parameter with a random int value } // Iterate through the provided options for _, opt := range opts { param = opt(param) // Apply the option } return param // Return the final parameter } // Copy copies the value of a given parameter into the parameter. func (p *Parameter) Copy(param Parameter) { // Set each each of the parameter's values to that of the other param p.I = param.I p.A = param.A } // Add adds two parameters. Leaves both parameters untouched. func (p *Parameter) Add(param *Parameter) Parameter { return add(*p, *param) // Add the two parameters } // Sub subtracts the receiving parameter from the inputted parameter. Leaves // both parameters untouched. func (p *Parameter) Sub(param *Parameter) Parameter { return sub(*p, *param) // Add the two parameters } // Mul multiplies two parameters. Leaves both parameters untouched. func (p *Parameter) Mul(param *Parameter) Parameter { return mul(*p, *param) // Add the two parameters } // Div divides two parameters. Leaves both parameters untouched. func (p *Parameter) Div(param *Parameter) Parameter { return div(*p, *param) // Add the two parameters } // IsError checks if the parameter is an error. func (p *Parameter) IsError() bool { _, ok := p.A.(error) // Check whether or not the abstract value can be cast to an error return ok // Return whether or not the cast was successful } // IsIdentity checks if the parameter is requesting the identity. func (p *Parameter) IsIdentity() bool { // Check the parameter isn't an error if !p.IsError() { return false // Return false } return p.A.(error) == ErrIdentityUnknown // Return whether the error is the identity unknown error } // IsZero checks if the parameter has any zero-value fields. func (p *Parameter) IsZero() bool { return p.I == 0 && len(p.B) == 0 && p.A == nil // Return whether or not the parameter has any nil fields } // IsNil checks if the parameter has any nil fields. func (p *Parameter) IsNil() bool { return p.A == nil // Return whether or not each field is null } // Equals checks whether or not two parameters are equivalent. func (p *Parameter) Equals(param *Parameter) bool { return p.I == param.I || p.A == param.A // Return whether or not these parameters are equivalent } // LessThan checks whether or not one parameter is less than another parameter. func (p *Parameter) LessThan(param *Parameter) bool { return p.I < param.I // Return the result } // GreaterThan checks whether or not one parameter is greater than another parameter. func (p *Parameter) GreaterThan(param *Parameter) bool { return p.I > param.I // Return the result } /* END EXPORTED METHODS */ /* BEGIN INTERNAL METHODS */ // randomAbstract generates a new parameter with a random abstract value. func randomAbstract() Parameter { return Parameter{ A: RandomComputation(), // Set the abstract value to be a computation } // Return the abstract parameter } // randomInt generates a new parameter with a random int value. func randomInt() Parameter { return Parameter{ I: rand.Intn(common.GlobalEntropy), // Generate a random int, set the param's i value to the int } // Return the parameter } // randomBytes generates a new parameter with a random byte value. func randomBytes() Parameter { buffer := make([]byte, 4) // Initialize a buffer to read the random byte into rand.Read(buffer) // Read a random byte into the buffer return Parameter{ B: buffer, // Set the parameter's bytes } // Return the parameter } // add adds two parameters. Leaves the abstract parameter untouched. func add(x, y Parameter) Parameter { x.I += y.I // Add the i8s of both parameters // Check y has some byte slice contents if len(y.B) > 0 { var nBytes []byte // Get a buffer to store the new byte slice in // Iterate through the bytes in b for i, b := range y.B { // Check that the second slice is larger that the receiving param if i >= len(x.B) { nBytes = append(nBytes, b) // Append the byte to the new byte slice continue // Continue } nBytes = append(nBytes, x.B[i]+b) // Perform the addition operation, add the result ot the new byte slice } } return x // Return the final parmaeter } // sub subtracts two parameters. Leaves the abstract parameter untouched. func sub(x, y Parameter) Parameter { x.I -= y.I // Subtract the two parameters // Check y has some byte slice contents if len(y.B) > 0 { var nBytes []byte // Get a buffer to store the new byte slice in // Iterate through the bytes in b for i, b := range y.B { // Check that the second slice is larger that the receiving param if i >= len(x.B) { nBytes = append(nBytes, -b) // Append the negative form of the byte to the new byte slice (0 - n = -n) continue // Continue } nBytes = append(nBytes, x.B[i]-b) // Perform the addition operation, add the result ot the new byte slice } } return x // Return the final parameter } // mul multiplies two parameters. Leaves the abstract parameter untouched. func mul(x, y Parameter) Parameter { x.I *= y.I // Multiply the two parameters // Check y has some byte slice contents if len(y.B) > 0 { var nBytes []byte // Get a buffer to store the new byte slice in // Iterate through the bytes in b for i, b := range y.B { // Check that the second slice is larger that the receiving param if i >= len(x.B) { break // All further entries will be zero } nBytes = append(nBytes, x.B[i]*b) // Perform the multiplication operation, add the result ot the new byte slice } } return x // Return the final parameter } // div divides two parameters. Leaves the abstract parameter untouched. func div(x, y Parameter) Parameter { // Check the second param is zero if y.I == 0 { return Parameter{} // Return a zero-val parameter } x.I /= y.I // Divide the two parameters // Check y has some byte slice contents if len(y.B) > 0 { var nBytes []byte // Get a buffer to store the new byte slice in // Iterate through the bytes in b for i, b := range y.B { // Check that the second slice is larger that the receiving param if i >= len(x.B) { break // All further entries will be zero } nBytes = append(nBytes, x.B[i]/b) // Perform the division operation, add the result ot the new byte slice } } return x // Return the final parameter } /* END INTERNAL METHODS */
activation/parameter.go
0.844281
0.58166
parameter.go
starcoder
package game import ( "fmt" "math/rand" ) // BoardElement represents single object on the game board type BoardElement int // BoardElement can be one of the following colors const ( None BoardElement = 0 Red BoardElement = 1 Green BoardElement = 2 Yellow BoardElement = 3 Blue BoardElement = 4 Magenta BoardElement = 5 Cyan BoardElement = 6 White BoardElement = 7 ) // BlockType represents one of the three blocks available in the game type BlockType int // BlockType can be one of the following values const ( A BlockType = 0 B BlockType = 1 C BlockType = 2 ) // ErrorGameReason represents numeric reason passed with the GameError struct type ErrorGameReason int // ErrorGameReasons const ( GameOver ErrorGameReason = 1 IncorrectBlock ErrorGameReason = 2 IncorrectPosition ErrorGameReason = 3 ) // ErrorGame struct implements Error interface and is used to communicate // about errors in the game type ErrorGame struct { Reason ErrorGameReason Message string } func (e *ErrorGame) Error() string { return e.Message } // Game struct contains 10x10 game board and three 5x5 blocks of shapes type Game struct { Board [][]BoardElement BlockA [][]BoardElement BlockB [][]BoardElement BlockC [][]BoardElement Score int GameOver bool randomGenerator *rand.Rand } // New Game is used to initialize Game struct: 10x10 board and three randomly // assigned blocks func New() Game { var g Game // randomSource := rand.NewSource(time.Now().UnixNano()) randomSource := rand.NewSource(1) g.randomGenerator = rand.New(randomSource) g.Board = createContainer(10) g.assignRandomBlocks() return g } // Move is used to select one of available blocks and place it on x,y position. // In case the placement is not possible or block does not exist error is returned. func (g *Game) Move(block BlockType, x int, y int) error { if g.GameOver { return &ErrorGame{GameOver, "Cannot continue playing game in a game over state"} } var selectedBlock [][]BoardElement switch block { case A: selectedBlock = g.BlockA case B: selectedBlock = g.BlockB case C: selectedBlock = g.BlockC default: g.GameOver = true return &ErrorGame{IncorrectBlock, fmt.Sprintf("Incorrect block type specified (%d)", block)} } if isBlockEmpty(selectedBlock) { g.GameOver = true return &ErrorGame{IncorrectBlock, "Selected block is empty"} } error := g.placeBlock(x, y, selectedBlock) if error != nil { g.GameOver = true return error } emptyBlock := createContainer(5) switch block { case A: g.BlockA = emptyBlock case B: g.BlockB = emptyBlock case C: g.BlockC = emptyBlock } if isBlockEmpty(g.BlockA) && isBlockEmpty(g.BlockB) && isBlockEmpty(g.BlockC) { g.assignRandomBlocks() } if g.isGameOver() { g.GameOver = true return &ErrorGame{GameOver, "No other move is possible. Game over."} } return nil } func (g *Game) assignRandomBlocks() { g.BlockA = g.randomShape() g.BlockB = g.randomShape() g.BlockC = g.randomShape() } // placeBlock places provided block on the board at x and y position being 0,0 block's position. // In case the placement is not possible error is returned. func (g *Game) placeBlock(x int, y int, block [][]BoardElement) error { if x < 0 || y < 0 { return &ErrorGame{IncorrectPosition, fmt.Sprintf("%d,%d is below 0,0", x, y)} } newBoard := make([][]BoardElement, len(g.Board)) for i := range g.Board { newBoard[i] = make([]BoardElement, len(g.Board[i])) copy(newBoard[i], g.Board[i]) } placementScore := 0 for boardX := x; boardX < x+len(block); boardX++ { for boardY := y; boardY < y+len(block); boardY++ { blockX := boardX - x blockY := boardY - y if boardX >= len(newBoard) || boardY >= len(newBoard) { if block[blockX][blockY] != None { return &ErrorGame{IncorrectPosition, fmt.Sprintf("%d,%d is out of board and block at %d,%d is not empty (%d)", boardX, boardY, blockX, blockY, block[blockX][blockY])} } continue } if newBoard[boardX][boardY] == None { newBoard[boardX][boardY] = block[blockX][blockY] if block[blockX][blockY] != None { placementScore++ } } else if block[blockX][blockY] != None { return &ErrorGame{IncorrectPosition, fmt.Sprintf("board at %d,%d is not empty (%d) and block at %d,%d is also not empty (%d)", boardX, boardY, newBoard[boardX][boardY], blockX, blockY, block[blockX][blockY])} } } } fullLanesScore := checkAndRemoveFullLanes(newBoard) g.Board = newBoard g.Score += placementScore + fullLanesScore return nil } func (g *Game) isMovePossible(block [][]BoardElement, x int, y int) bool { for boardX := x; boardX < x+len(block); boardX++ { for boardY := y; boardY < y+len(block); boardY++ { blockX := boardX - x blockY := boardY - y if boardX >= len(g.Board) || boardY >= len(g.Board) { if block[blockX][blockY] != None { return false } continue } if g.Board[boardX][boardY] != None && block[blockX][blockY] != None { return false } } } return true } // checkAndRemoveFullLanes firstly counts all full rows and columns // and then removes them from the board, replacing with None value func checkAndRemoveFullLanes(board [][]BoardElement) int { fullRows := make([]bool, len(board)) fullCols := make([]bool, len(board)) for i := 0; i < len(board); i++ { fullRows[i] = true fullCols[i] = true } score := 0 // check all full rows and columns before removing anything for x := 0; x < len(board); x++ { for y := 0; y < len(board); y++ { if fullRows[x] { fullRows[x] = board[x][y] != None } if fullCols[y] { fullCols[y] = board[x][y] != None } } } // remove rows for x := 0; x < len(fullRows); x++ { if !fullRows[x] { continue } score += len(fullCols) for y := 0; y < len(fullCols); y++ { board[x][y] = None } } // remove columns for y := 0; y < len(fullCols); y++ { if !fullCols[y] { continue } score += len(fullRows) for x := 0; x < len(fullRows); x++ { board[x][y] = None } } return score } func (g *Game) isGameOver() bool { movePossible := false if !isBlockEmpty(g.BlockA) && g.isMovePossibleAnywhere(g.BlockA) { movePossible = true } if !isBlockEmpty(g.BlockB) && g.isMovePossibleAnywhere(g.BlockB) { movePossible = true } if !isBlockEmpty(g.BlockC) && g.isMovePossibleAnywhere(g.BlockC) { movePossible = true } return !movePossible } func (g *Game) isMovePossibleAnywhere(block [][]BoardElement) bool { for x := 0; x < len(g.Board); x++ { for y := 0; y < len(g.Board[x]); y++ { if g.Board[x][y] != None { continue } if g.isMovePossible(block, x, y) { return true } } } return false } // randomShape returns random shape from BlockShape method func (g *Game) randomShape() [][]BoardElement { return blockShape(g.randomGenerator.Intn(19)) } // blockShape returns one of 19 shapes available in the game func blockShape(number int) [][]BoardElement { switch number { case 0: return [][]BoardElement{ {Red, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 1: return [][]BoardElement{ {Green, Green, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 2: return [][]BoardElement{ {Green, None, None, None, None}, {Green, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 3: return [][]BoardElement{ {Yellow, Yellow, Yellow, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 4: return [][]BoardElement{ {Yellow, None, None, None, None}, {Yellow, None, None, None, None}, {Yellow, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 5: return [][]BoardElement{ {Blue, Blue, Blue, Blue, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 6: return [][]BoardElement{ {Blue, None, None, None, None}, {Blue, None, None, None, None}, {Blue, None, None, None, None}, {Blue, None, None, None, None}, {None, None, None, None, None}} case 7: return [][]BoardElement{ {Magenta, Magenta, Magenta, Magenta, Magenta}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 8: return [][]BoardElement{ {Magenta, None, None, None, None}, {Magenta, None, None, None, None}, {Magenta, None, None, None, None}, {Magenta, None, None, None, None}, {Magenta, None, None, None, None}} case 9: return [][]BoardElement{ {Cyan, Cyan, None, None, None}, {Cyan, Cyan, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 10: return [][]BoardElement{ {White, White, White, None, None}, {White, White, White, None, None}, {White, White, White, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 11: return [][]BoardElement{ {Cyan, Cyan, Cyan, None, None}, {Cyan, None, None, None, None}, {Cyan, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 12: return [][]BoardElement{ {Cyan, Cyan, Cyan, None, None}, {None, None, Cyan, None, None}, {None, None, Cyan, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 13: return [][]BoardElement{ {None, None, Cyan, None, None}, {None, None, Cyan, None, None}, {Cyan, Cyan, Cyan, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 14: return [][]BoardElement{ {Cyan, None, None, None, None}, {Cyan, None, None, None, None}, {Cyan, Cyan, Cyan, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 15: return [][]BoardElement{ {White, White, None, None, None}, {White, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 16: return [][]BoardElement{ {White, White, None, None, None}, {None, White, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 17: return [][]BoardElement{ {None, White, None, None, None}, {White, White, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} case 18: return [][]BoardElement{ {White, None, None, None, None}, {White, White, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} default: return [][]BoardElement{ {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}, {None, None, None, None, None}} } } // createContainer returns square two diemnsional slice of size x size func createContainer(size int) [][]BoardElement { board := make([][]BoardElement, size) for i := 0; i < size; i++ { board[i] = make([]BoardElement, size) } return board } // isBlockEmpty checks if all fields of the block are None func isBlockEmpty(block [][]BoardElement) bool { for x := 0; x < len(block); x++ { for y := 0; y < len(block); y++ { if block[x][y] != None { return false } } } return true }
game/game.go
0.65368
0.449695
game.go
starcoder
package ast import ( "math" ) // Kind constants. const ( KindNull byte = 0 KindInt64 byte = 1 KindUint64 byte = 2 KindFloat32 byte = 3 KindFloat64 byte = 4 KindString byte = 5 KindBytes byte = 6 KindMysqlBit byte = 7 KindMysqlDecimal byte = 8 KindMysqlDuration byte = 9 KindMysqlEnum byte = 10 KindMysqlHex byte = 11 KindMysqlSet byte = 12 KindMysqlTime byte = 13 KindRow byte = 14 KindInterface byte = 15 KindMinNotNull byte = 16 KindMaxValue byte = 17 KindRaw byte = 18 ) // Datum is a data box holds different kind of data. // It has better performance and is easier to use than `interface{}`. type Datum struct { k byte // datum kind. collation uint8 // collation can hold uint8 values. decimal uint16 // decimal can hold uint16 values. length uint32 // length can hold uint32 values. i int64 // i can hold int64 uint64 float64 values. b []byte // b can hold string or []byte values. x interface{} // x hold all other types. } // Kind gets the kind of the datum. func (d *Datum) Kind() byte { return d.k } // Collation gets the collation of the datum. func (d *Datum) Collation() byte { return d.collation } // SetCollation sets the collation of the datum. func (d *Datum) SetCollation(collation byte) { d.collation = collation } // Frac gets the frac of the datum. func (d *Datum) Frac() int { return int(d.decimal) } // SetFrac sets the frac of the datum. func (d *Datum) SetFrac(frac int) { d.decimal = uint16(frac) } // Length gets the length of the datum. func (d *Datum) Length() int { return int(d.length) } // SetLength sets the length of the datum func (d *Datum) SetLength(l int) { d.length = uint32(l) } // IsNull checks if datum is null. func (d *Datum) IsNull() bool { return d.k == KindNull } // GetInt64 gets int64 value. func (d *Datum) GetInt64() int64 { return d.i } // SetInt64 sets int64 value. func (d *Datum) SetInt64(i int64) { d.k = KindInt64 d.i = i } // GetUint64 gets uint64 value. func (d *Datum) GetUint64() uint64 { return uint64(d.i) } // SetUint64 sets uint64 value. func (d *Datum) SetUint64(i uint64) { d.k = KindUint64 d.i = int64(i) } // GetFloat64 gets float64 value. func (d *Datum) GetFloat64() float64 { return math.Float64frombits(uint64(d.i)) } // SetFloat64 sets float64 value. func (d *Datum) SetFloat64(f float64) { d.k = KindFloat64 d.i = int64(math.Float64bits(f)) } // GetFloat32 gets float32 value. func (d *Datum) GetFloat32() float32 { return float32(math.Float64frombits(uint64(d.i))) } // SetFloat32 sets float32 value. func (d *Datum) SetFloat32(f float32) { d.k = KindFloat32 d.i = int64(math.Float64bits(float64(f))) } // GetString gets string value. func (d *Datum) GetString() string { return String(d.b) } // SetString sets string value. func (d *Datum) SetString(s string) { d.k = KindString sink(s) d.b = Slice(s) } // sink prevents s from being allocated on the stack. var sink = func(s string) { } // GetBytes gets bytes value. func (d *Datum) GetBytes() []byte { return d.b } // SetBytes sets bytes value to datum. func (d *Datum) SetBytes(b []byte) { d.k = KindBytes d.b = b } // SetBytesAsString sets bytes value to datum as string type. func (d *Datum) SetBytesAsString(b []byte) { d.k = KindString d.b = b } // GetInterface gets interface value. func (d *Datum) GetInterface() interface{} { return d.x } // SetInterface sets interface to datum. func (d *Datum) SetInterface(x interface{}) { d.k = KindInterface d.x = x } // GetRow gets row value. func (d *Datum) GetRow() []Datum { return d.x.([]Datum) } // SetRow sets row value. func (d *Datum) SetRow(ds []Datum) { d.k = KindRow d.x = ds } // SetNull sets datum to nil. func (d *Datum) SetNull() { d.k = KindNull d.x = nil } // SetRaw sets raw value. func (d *Datum) SetRaw(b []byte) { d.k = KindRaw d.b = b } // GetRaw gets raw value. func (d *Datum) GetRaw() []byte { return d.b } // GetValue gets the value of the datum of any kind. func (d *Datum) GetValue() interface{} { switch d.k { case KindInt64: return d.GetInt64() case KindUint64: return d.GetUint64() case KindFloat32: return d.GetFloat32() case KindFloat64: return d.GetFloat64() case KindString: return d.GetString() case KindBytes: return d.GetBytes() default: return d.GetInterface() } } // SetValue sets any kind of value. func (d *Datum) SetValue(val interface{}) { switch x := val.(type) { case nil: d.SetNull() case bool: if x { d.SetInt64(1) } else { d.SetInt64(0) } case int: d.SetInt64(int64(x)) case int64: d.SetInt64(x) case uint64: d.SetUint64(x) case float32: d.SetFloat32(x) case float64: d.SetFloat64(x) case string: d.SetString(x) case []byte: d.SetBytes(x) case []Datum: d.SetRow(x) case []interface{}: ds := MakeDatums(x...) d.SetRow(ds) default: d.SetInterface(x) } } // NewDatum creates a new Datum from an interface{}. func NewDatum(in interface{}) (d Datum) { switch x := in.(type) { case []interface{}: d.SetValue(MakeDatums(x...)) default: d.SetValue(in) } return d } // NewIntDatum creates a new Datum from an int64 value. func NewIntDatum(i int64) (d Datum) { d.SetInt64(i) return d } // NewUintDatum creates a new Datum from an uint64 value. func NewUintDatum(i uint64) (d Datum) { d.SetUint64(i) return d } // NewBytesDatum creates a new Datum from a byte slice. func NewBytesDatum(b []byte) (d Datum) { d.SetBytes(b) return d } // NewStringDatum creates a new Datum from a string. func NewStringDatum(s string) (d Datum) { d.SetString(s) return d } // NewFloat64Datum creates a new Datum from a float64 value. func NewFloat64Datum(f float64) (d Datum) { d.SetFloat64(f) return d } // NewFloat32Datum creates a new Datum from a float32 value. func NewFloat32Datum(f float32) (d Datum) { d.SetFloat32(f) return d } // NewRawDatum create a new Datum that is not decoded. func NewRawDatum(b []byte) (d Datum) { d.k = KindRaw d.b = b return d } // MakeDatums creates datum slice from interfaces. func MakeDatums(args ...interface{}) []Datum { datums := make([]Datum, len(args)) for i, v := range args { datums[i] = NewDatum(v) } return datums }
ast/datum.go
0.697506
0.424651
datum.go
starcoder
package scheduler import ( "math" "time" "github.com/hashicorp/nomad/nomad/structs" ) const ( // skipScoreThreshold is a threshold used in the limit iterator to skip nodes // that have a score lower than this. -1 is the lowest possible score for a // node with penalties (based on job anti affinity and node rescheduling penalties skipScoreThreshold = 0.0 // maxSkip limits the number of nodes that can be skipped in the limit iterator maxSkip = 3 ) // Stack is a chained collection of iterators. The stack is used to // make placement decisions. Different schedulers may customize the // stack they use to vary the way placements are made. type Stack interface { // SetNodes is used to set the base set of potential nodes SetNodes([]*structs.Node) // SetTaskGroup is used to set the job for selection SetJob(job *structs.Job) // Select is used to select a node for the task group Select(tg *structs.TaskGroup, options *SelectOptions) *RankedNode } type SelectOptions struct { PenaltyNodeIDs map[string]struct{} PreferredNodes []*structs.Node } // GenericStack is the Stack used for the Generic scheduler. It is // designed to make better placement decisions at the cost of performance. type GenericStack struct { batch bool ctx Context source *StaticIterator wrappedChecks *FeasibilityWrapper quota FeasibleIterator jobConstraint *ConstraintChecker taskGroupDrivers *DriverChecker taskGroupConstraint *ConstraintChecker taskGroupDevices *DeviceChecker distinctHostsConstraint *DistinctHostsIterator distinctPropertyConstraint *DistinctPropertyIterator binPack *BinPackIterator jobAntiAff *JobAntiAffinityIterator nodeReschedulingPenalty *NodeReschedulingPenaltyIterator limit *LimitIterator maxScore *MaxScoreIterator nodeAffinity *NodeAffinityIterator spread *SpreadIterator scoreNorm *ScoreNormalizationIterator } // NewGenericStack constructs a stack used for selecting service placements func NewGenericStack(batch bool, ctx Context) *GenericStack { // Create a new stack s := &GenericStack{ batch: batch, ctx: ctx, } // Create the source iterator. We randomize the order we visit nodes // to reduce collisions between schedulers and to do a basic load // balancing across eligible nodes. s.source = NewRandomIterator(ctx, nil) // Create the quota iterator to determine if placements would result in the // quota attached to the namespace of the job to go over. s.quota = NewQuotaIterator(ctx, s.source) // Attach the job constraints. The job is filled in later. s.jobConstraint = NewConstraintChecker(ctx, nil) // Filter on task group drivers first as they are faster s.taskGroupDrivers = NewDriverChecker(ctx, nil) // Filter on task group constraints second s.taskGroupConstraint = NewConstraintChecker(ctx, nil) // Filter on task group devices s.taskGroupDevices = NewDeviceChecker(ctx) // Create the feasibility wrapper which wraps all feasibility checks in // which feasibility checking can be skipped if the computed node class has // previously been marked as eligible or ineligible. Generally this will be // checks that only needs to examine the single node to determine feasibility. jobs := []FeasibilityChecker{s.jobConstraint} tgs := []FeasibilityChecker{s.taskGroupDrivers, s.taskGroupConstraint, s.taskGroupDevices} s.wrappedChecks = NewFeasibilityWrapper(ctx, s.quota, jobs, tgs) // Filter on distinct host constraints. s.distinctHostsConstraint = NewDistinctHostsIterator(ctx, s.wrappedChecks) // Filter on distinct property constraints. s.distinctPropertyConstraint = NewDistinctPropertyIterator(ctx, s.distinctHostsConstraint) // Upgrade from feasible to rank iterator rankSource := NewFeasibleRankIterator(ctx, s.distinctPropertyConstraint) // Apply the bin packing, this depends on the resources needed // by a particular task group. s.binPack = NewBinPackIterator(ctx, rankSource, false, 0) // Apply the job anti-affinity iterator. This is to avoid placing // multiple allocations on the same node for this job. s.jobAntiAff = NewJobAntiAffinityIterator(ctx, s.binPack, "") s.nodeReschedulingPenalty = NewNodeReschedulingPenaltyIterator(ctx, s.jobAntiAff) s.nodeAffinity = NewNodeAffinityIterator(ctx, s.nodeReschedulingPenalty) s.spread = NewSpreadIterator(ctx, s.nodeAffinity) s.scoreNorm = NewScoreNormalizationIterator(ctx, s.spread) // Apply a limit function. This is to avoid scanning *every* possible node. s.limit = NewLimitIterator(ctx, s.scoreNorm, 2, skipScoreThreshold, maxSkip) // Select the node with the maximum score for placement s.maxScore = NewMaxScoreIterator(ctx, s.limit) return s } func (s *GenericStack) SetNodes(baseNodes []*structs.Node) { // Shuffle base nodes shuffleNodes(baseNodes) // Update the set of base nodes s.source.SetNodes(baseNodes) // Apply a limit function. This is to avoid scanning *every* possible node. // For batch jobs we only need to evaluate 2 options and depend on the // power of two choices. For services jobs we need to visit "enough". // Using a log of the total number of nodes is a good restriction, with // at least 2 as the floor limit := 2 if n := len(baseNodes); !s.batch && n > 0 { logLimit := int(math.Ceil(math.Log2(float64(n)))) if logLimit > limit { limit = logLimit } } s.limit.SetLimit(limit) } func (s *GenericStack) SetJob(job *structs.Job) { s.jobConstraint.SetConstraints(job.Constraints) s.distinctHostsConstraint.SetJob(job) s.distinctPropertyConstraint.SetJob(job) s.binPack.SetPriority(job.Priority) s.jobAntiAff.SetJob(job) s.nodeAffinity.SetJob(job) s.spread.SetJob(job) s.ctx.Eligibility().SetJob(job) if contextual, ok := s.quota.(ContextualIterator); ok { contextual.SetJob(job) } } func (s *GenericStack) Select(tg *structs.TaskGroup, options *SelectOptions) *RankedNode { // This block handles trying to select from preferred nodes if options specify them // It also sets back the set of nodes to the original nodes if options != nil && len(options.PreferredNodes) > 0 { originalNodes := s.source.nodes s.source.SetNodes(options.PreferredNodes) optionsNew := *options optionsNew.PreferredNodes = nil if option := s.Select(tg, &optionsNew); option != nil { s.source.SetNodes(originalNodes) return option } s.source.SetNodes(originalNodes) return s.Select(tg, &optionsNew) } // Reset the max selector and context s.maxScore.Reset() s.ctx.Reset() start := time.Now() // Get the task groups constraints. tgConstr := taskGroupConstraints(tg) // Update the parameters of iterators s.taskGroupDrivers.SetDrivers(tgConstr.drivers) s.taskGroupConstraint.SetConstraints(tgConstr.constraints) s.taskGroupDevices.SetTaskGroup(tg) s.distinctHostsConstraint.SetTaskGroup(tg) s.distinctPropertyConstraint.SetTaskGroup(tg) s.wrappedChecks.SetTaskGroup(tg.Name) s.binPack.SetTaskGroup(tg) s.jobAntiAff.SetTaskGroup(tg) if options != nil { s.nodeReschedulingPenalty.SetPenaltyNodes(options.PenaltyNodeIDs) } s.nodeAffinity.SetTaskGroup(tg) s.spread.SetTaskGroup(tg) if s.nodeAffinity.hasAffinities() || s.spread.hasSpreads() { s.limit.SetLimit(math.MaxInt32) } if contextual, ok := s.quota.(ContextualIterator); ok { contextual.SetTaskGroup(tg) } // Find the node with the max score option := s.maxScore.Next() // Store the compute time s.ctx.Metrics().AllocationTime = time.Since(start) return option } // SystemStack is the Stack used for the System scheduler. It is designed to // attempt to make placements on all nodes. type SystemStack struct { ctx Context source *StaticIterator wrappedChecks *FeasibilityWrapper quota FeasibleIterator jobConstraint *ConstraintChecker taskGroupDrivers *DriverChecker taskGroupConstraint *ConstraintChecker taskGroupDevices *DeviceChecker distinctPropertyConstraint *DistinctPropertyIterator binPack *BinPackIterator scoreNorm *ScoreNormalizationIterator } // NewSystemStack constructs a stack used for selecting service placements func NewSystemStack(ctx Context) *SystemStack { // Create a new stack s := &SystemStack{ctx: ctx} // Create the source iterator. We visit nodes in a linear order because we // have to evaluate on all nodes. s.source = NewStaticIterator(ctx, nil) // Create the quota iterator to determine if placements would result in the // quota attached to the namespace of the job to go over. s.quota = NewQuotaIterator(ctx, s.source) // Attach the job constraints. The job is filled in later. s.jobConstraint = NewConstraintChecker(ctx, nil) // Filter on task group drivers first as they are faster s.taskGroupDrivers = NewDriverChecker(ctx, nil) // Filter on task group constraints second s.taskGroupConstraint = NewConstraintChecker(ctx, nil) // Filter on task group devices s.taskGroupDevices = NewDeviceChecker(ctx) // Create the feasibility wrapper which wraps all feasibility checks in // which feasibility checking can be skipped if the computed node class has // previously been marked as eligible or ineligible. Generally this will be // checks that only needs to examine the single node to determine feasibility. jobs := []FeasibilityChecker{s.jobConstraint} tgs := []FeasibilityChecker{s.taskGroupDrivers, s.taskGroupConstraint, s.taskGroupDevices} s.wrappedChecks = NewFeasibilityWrapper(ctx, s.quota, jobs, tgs) // Filter on distinct property constraints. s.distinctPropertyConstraint = NewDistinctPropertyIterator(ctx, s.wrappedChecks) // Upgrade from feasible to rank iterator rankSource := NewFeasibleRankIterator(ctx, s.distinctPropertyConstraint) // Apply the bin packing, this depends on the resources needed // by a particular task group. Enable eviction as system jobs are high // priority. _, schedConfig, _ := s.ctx.State().SchedulerConfig() enablePreemption := true if schedConfig != nil { enablePreemption = schedConfig.PreemptionConfig.SystemSchedulerEnabled } s.binPack = NewBinPackIterator(ctx, rankSource, enablePreemption, 0) // Apply score normalization s.scoreNorm = NewScoreNormalizationIterator(ctx, s.binPack) return s } func (s *SystemStack) SetNodes(baseNodes []*structs.Node) { // Update the set of base nodes s.source.SetNodes(baseNodes) } func (s *SystemStack) SetJob(job *structs.Job) { s.jobConstraint.SetConstraints(job.Constraints) s.distinctPropertyConstraint.SetJob(job) s.binPack.SetPriority(job.Priority) s.ctx.Eligibility().SetJob(job) if contextual, ok := s.quota.(ContextualIterator); ok { contextual.SetJob(job) } } func (s *SystemStack) Select(tg *structs.TaskGroup, options *SelectOptions) *RankedNode { // Reset the binpack selector and context s.scoreNorm.Reset() s.ctx.Reset() start := time.Now() // Get the task groups constraints. tgConstr := taskGroupConstraints(tg) // Update the parameters of iterators s.taskGroupDrivers.SetDrivers(tgConstr.drivers) s.taskGroupConstraint.SetConstraints(tgConstr.constraints) s.taskGroupDevices.SetTaskGroup(tg) s.wrappedChecks.SetTaskGroup(tg.Name) s.distinctPropertyConstraint.SetTaskGroup(tg) s.binPack.SetTaskGroup(tg) if contextual, ok := s.quota.(ContextualIterator); ok { contextual.SetTaskGroup(tg) } // Get the next option that satisfies the constraints. option := s.scoreNorm.Next() // Store the compute time s.ctx.Metrics().AllocationTime = time.Since(start) return option }
vendor/github.com/hashicorp/nomad/scheduler/stack.go
0.75037
0.420243
stack.go
starcoder
package chaakoo // Pane represents a TMUX pane in a 2D grid type Pane struct { Name string // Name of the pane XStart int // First index in the horizontal direction XEnd int // Last index in the horizontal direction YStart int // First index in the vertical direction YEnd int // Last index in the vertical direction Visited bool // If this node was visited while traversal Left []*Pane // Collection of the panes to the left of the current pane Bottom []*Pane // Collection of the panes to the bottom of the current pane priorLeftIndex int // used while dfs priorBottomIndex int // used while dfs } // Height returns the height of the pane func (p *Pane) Height() int { return p.YEnd - p.YStart + 1 } // Width returns the width of the pane func (p *Pane) Width() int { return p.XEnd - p.XStart + 1 } // AddLeftPane appends left pane to the current pane func (p *Pane) AddLeftPane(leftPane *Pane) { p.Left = append(p.Left, leftPane) } // AddBottomPane appends a bottom pane to the current pane func (p *Pane) AddBottomPane(bottomPane *Pane) { p.Bottom = append(p.Bottom, bottomPane) } func (p *Pane) reset() { p.priorLeftIndex = len(p.Left) - 1 p.priorBottomIndex = len(p.Bottom) - 1 } // AsGrid returns the 2D string array representation of the Pane func (p *Pane) AsGrid() [][]string { p.reset() var grid = make([][]string, p.Height()) for i := range grid { grid[i] = make([]string, p.Width()) for j := range grid[i] { grid[i][j] = p.Name } } for { var leftPane, bottomPane *Pane if p.priorLeftIndex > -1 { leftPane = p.Left[p.priorLeftIndex] } if p.priorBottomIndex > -1 { bottomPane = p.Bottom[p.priorBottomIndex] } if leftPane == nil && bottomPane == nil { return grid } else if leftPane != nil && bottomPane == nil { p.priorLeftIndex-- leftGrid := leftPane.AsGrid() fill(p, leftPane, grid, leftGrid) } else if leftPane == nil && bottomPane != nil { p.priorBottomIndex-- bottomGrid := bottomPane.AsGrid() fill(p, bottomPane, grid, bottomGrid) } else if leftPane.Height() > bottomPane.Height() { p.priorLeftIndex-- leftGrid := leftPane.AsGrid() fill(p, leftPane, grid, leftGrid) } else { p.priorBottomIndex-- bottomGrid := bottomPane.AsGrid() fill(p, bottomPane, grid, bottomGrid) } } } func fill(parent *Pane, child *Pane, parentGrid [][]string, childGrid [][]string) { for i, I := child.YStart-parent.YStart, 0; i <= child.YEnd-parent.YStart; i, I = i+1, I+1 { for j, J := child.XStart-parent.XStart, 0; j <= child.XEnd-parent.XStart; j, J = j+1, J+1 { parentGrid[i][j] = childGrid[I][J] } } }
pane.go
0.762954
0.568595
pane.go
starcoder
package schemas import ( "fmt" "html" "math" "sort" "strconv" "strings" ) type psqlFormatter struct{} func NewPSQLFormatter() SchemaFormatter { return psqlFormatter{} } func (f psqlFormatter) Format(schemaDescription SchemaDescription) string { docs := []string{} sortTables(schemaDescription.Tables) for _, table := range schemaDescription.Tables { docs = append(docs, f.formatTable(schemaDescription, table)...) } sortViews(schemaDescription.Views) for _, view := range schemaDescription.Views { docs = append(docs, f.formatView(schemaDescription, view)...) } types := map[string][]string{} for _, enum := range schemaDescription.Enums { types[enum.Name] = enum.Labels } if len(types) > 0 { docs = append(docs, f.formatTypes(schemaDescription, types)...) } return strings.Join(docs, "\n") } func (f psqlFormatter) formatTable(schemaDescription SchemaDescription, table TableDescription) []string { centerString := func(s string, n int) string { x := float64(n - len(s)) i := int(math.Floor(x / 2)) if i <= 0 { i = 1 } j := int(math.Ceil(x / 2)) if j <= 0 { j = 1 } return strings.Repeat(" ", i) + s + strings.Repeat(" ", j) } formatColumns := func(headers []string, rows [][]string) []string { sizes := make([]int, len(headers)) headerValues := make([]string, len(headers)) sepValues := make([]string, len(headers)) for i, header := range headers { sizes[i] = len(header) for _, row := range rows { if n := len(row[i]); n > sizes[i] { sizes[i] = n } } headerValues[i] = centerString(headers[i], sizes[i]+2) sepValues[i] = strings.Repeat("-", sizes[i]+2) } docs := make([]string, 0, len(rows)+2) docs = append(docs, strings.Join(headerValues, "|")) docs = append(docs, strings.Join(sepValues, "+")) for _, row := range rows { rowValues := make([]string, 0, len(headers)) for i := range headers { if i == len(headers)-1 { rowValues = append(rowValues, row[i]) } else { rowValues = append(rowValues, fmt.Sprintf("%-"+strconv.Itoa(sizes[i])+"s", row[i])) } } docs = append(docs, " "+strings.Join(rowValues, " | ")) } return docs } docs := []string{} docs = append(docs, fmt.Sprintf("# Table \"public.%s\"", table.Name)) docs = append(docs, "```") headers := []string{"Column", "Type", "Collation", "Nullable", "Default"} rows := [][]string{} sortColumns(table.Columns) for _, column := range table.Columns { nullConstraint := "not null" if column.IsNullable { nullConstraint = "" } defaultValue := column.Default if column.IsGenerated == "ALWAYS" { defaultValue = "generated always as (" + column.GenerationExpression + ") stored" } rows = append(rows, []string{ column.Name, column.TypeName, "", nullConstraint, defaultValue, }) } docs = append(docs, formatColumns(headers, rows)...) if len(table.Indexes) > 0 { docs = append(docs, "Indexes:") sortIndexes(table.Indexes) for _, index := range table.Indexes { if index.IsPrimaryKey { def := strings.TrimSpace(strings.Split(index.IndexDefinition, "USING")[1]) docs = append(docs, fmt.Sprintf(" %q PRIMARY KEY, %s", index.Name, def)) } } for _, index := range table.Indexes { if !index.IsPrimaryKey { uq := "" if index.IsUnique { c := "" if index.ConstraintType == "u" { c = " CONSTRAINT" } uq = " UNIQUE" + c + "," } deferrable := "" if index.IsDeferrable { deferrable = " DEFERRABLE" } def := strings.TrimSpace(strings.Split(index.IndexDefinition, "USING")[1]) if index.IsExclusion { def = "EXCLUDE USING " + def } docs = append(docs, fmt.Sprintf(" %q%s %s%s", index.Name, uq, def, deferrable)) } } } numCheckConstraints := 0 numForeignKeyConstraints := 0 for _, constraint := range table.Constraints { switch constraint.ConstraintType { case "c": numCheckConstraints++ case "f": numForeignKeyConstraints++ } } if numCheckConstraints > 0 { docs = append(docs, "Check constraints:") for _, constraint := range table.Constraints { if constraint.ConstraintType == "c" { docs = append(docs, fmt.Sprintf(" %q %s", constraint.Name, constraint.ConstraintDefinition)) } } } if numForeignKeyConstraints > 0 { docs = append(docs, "Foreign-key constraints:") for _, constraint := range table.Constraints { if constraint.ConstraintType == "f" { docs = append(docs, fmt.Sprintf(" %q %s", constraint.Name, constraint.ConstraintDefinition)) } } } type tableAndConstraint struct { TableDescription ConstraintDescription } tableAndConstraints := []tableAndConstraint{} for _, otherTable := range schemaDescription.Tables { for _, constraint := range otherTable.Constraints { if constraint.RefTableName == table.Name { tableAndConstraints = append(tableAndConstraints, tableAndConstraint{otherTable, constraint}) } } } sort.Slice(tableAndConstraints, func(i, j int) bool { return tableAndConstraints[i].ConstraintDescription.Name < tableAndConstraints[j].ConstraintDescription.Name }) if len(tableAndConstraints) > 0 { docs = append(docs, "Referenced by:") for _, tableAndConstraint := range tableAndConstraints { docs = append(docs, fmt.Sprintf(" TABLE %q CONSTRAINT %q %s", tableAndConstraint.TableDescription.Name, tableAndConstraint.ConstraintDescription.Name, tableAndConstraint.ConstraintDescription.ConstraintDefinition)) } } if len(table.Triggers) > 0 { docs = append(docs, "Triggers:") for _, trigger := range table.Triggers { def := strings.TrimSpace(strings.SplitN(trigger.Definition, trigger.Name, 2)[1]) docs = append(docs, fmt.Sprintf(" %s %s", trigger.Name, def)) } } docs = append(docs, "\n```\n") if table.Comment != "" { docs = append(docs, html.EscapeString(table.Comment)+"\n") } sortColumnsByName(table.Columns) for _, column := range table.Columns { if column.Comment != "" { docs = append(docs, fmt.Sprintf("**%s**: %s\n", column.Name, html.EscapeString(column.Comment))) } } return docs } func (f psqlFormatter) formatView(_ SchemaDescription, view ViewDescription) []string { docs := []string{} docs = append(docs, fmt.Sprintf("# View \"public.%s\"\n", view.Name)) docs = append(docs, fmt.Sprintf("## View query:\n\n```sql\n%s\n```\n", view.Definition)) return docs } func (f psqlFormatter) formatTypes(_ SchemaDescription, types map[string][]string) []string { typeNames := make([]string, 0, len(types)) for typeName := range types { typeNames = append(typeNames, typeName) } sort.Strings(typeNames) docs := make([]string, 0, len(typeNames)*4) for _, name := range typeNames { docs = append(docs, fmt.Sprintf("# Type %s", name)) docs = append(docs, "") docs = append(docs, "- "+strings.Join(types[name], "\n- ")) docs = append(docs, "") } return docs } func sortTables(tables []TableDescription) { sort.Slice(tables, func(i, j int) bool { return tables[i].Name < tables[j].Name }) } func sortViews(views []ViewDescription) { sort.Slice(views, func(i, j int) bool { return views[i].Name < views[j].Name }) } func sortColumns(columns []ColumnDescription) { sort.Slice(columns, func(i, j int) bool { return columns[i].Index < columns[j].Index }) } func sortColumnsByName(columns []ColumnDescription) { sort.Slice(columns, func(i, j int) bool { return columns[i].Name < columns[j].Name }) } func sortIndexes(indexes []IndexDescription) { sort.Slice(indexes, func(i, j int) bool { if indexes[i].IsUnique && !indexes[j].IsUnique { return true } if !indexes[i].IsUnique && indexes[j].IsUnique { return false } return indexes[i].Name < indexes[j].Name }) }
internal/database/migration/schemas/formatter_psql.go
0.506591
0.54958
formatter_psql.go
starcoder
package google import ( "errors" "fmt" "strings" ) /** Used to store a row of data */ type SheetData struct { //Store the values in the row Values [][]interface{} //[row][col] //Store the Headers Headers []string //Store a map from the Headers to location headersLoc map[string]int //Store a list of original row numbers RowNumb []int } //Create a new sheet data func NewSheetData(values [][]interface{}) (*SheetData, error) { //We need at least a header row if len(values) == 0 { return nil, errors.New("header row missing from sheet") } //Get the size headerSize := len(values[0]) //Build the needed header info data := &SheetData{ Headers: make([]string, headerSize), headersLoc: make(map[string]int, 0), RowNumb: make([]int, len(values)-1), //No need for the header Values: values[1:], //Remove the header row from the data } //Now store each of the Headers location for easy look up for loc, name := range values[0] { //Convert the name to a string nameString := fmt.Sprint(name) //Save the info data.headersLoc[SanitizeHeader(nameString)] = loc data.Headers[loc] = nameString } //Now just set the values for the row location for i := 0; i < len(data.RowNumb); i++ { data.RowNumb[i] = i + 2 //C style index plus the missing header row } return data, nil } //March over each header and look for value func (sheet *SheetData) findHeaderContaining(header string) int { for ind, value := range sheet.Headers { if strings.Contains(strings.ToLower(value), header) { return ind } } return -1 } //Create a new sheet data func (sheet *SheetData) FilterSheet(header string, value string) *SheetData { //See if we have the header headerCol := sheet.findHeaderContaining(header) //If it is there, return nil if headerCol < 0 { return nil } //Now create a new data sheet newSheet := &SheetData{ Headers: sheet.Headers, //Headers are the same headersLoc: sheet.headersLoc, //Headers are the same RowNumb: make([]int, 0), //No need for the header Values: make([][]interface{}, 0), } //Clean up the value value = strings.TrimSpace(value) //Now check to see if each row has the data for r, rowData := range sheet.Values { //Make sure we have enough data to check if len(rowData) > headerCol { //If they are equal if strings.EqualFold(value, strings.TrimSpace(fmt.Sprint(rowData[headerCol]))) { //Add the data newSheet.Values = append(newSheet.Values, rowData) newSheet.RowNumb = append(newSheet.RowNumb, sheet.RowNumb[r]) } } } //Return the new sheet return newSheet } //Create a new sheet data func (sheet *SheetData) GetColumn(col int) []interface{} { //We need to transpose the data colData := make([]interface{}, 0) //March over each row for r := range sheet.Values { //If it has the column add it if len(sheet.Values[r]) > col+1 { colData = append(colData, sheet.Values[r][col]) } } return colData } //Create a new sheet data func (sheet *SheetData) GetRow(row int) *SheetDataRow { //Look up the row number indexNumber := -1 //Now search over the rows for the row index, for index, rowTest := range sheet.RowNumb { if rowTest == row { indexNumber = index } } //If it avaiable return if indexNumber < 0 { return nil } //Extract the row info dataRow := &SheetDataRow{ Values: sheet.Values[indexNumber], Headers: sheet.Headers, headersLoc: sheet.headersLoc, RowNumber: row, } //If we have fewer values then header size if len(dataRow.Values) < len(dataRow.Headers) { //Make a new array array := make([]interface{}, len(dataRow.Headers)-len(dataRow.Values)) dataRow.Values = append(dataRow.Values, array...) } //Return the new sheet return dataRow } //Create a new sheet data func (sheet *SheetData) GetEmptyDataRow() *SheetDataRow { //Get the size. number of headers size := len(sheet.Headers) //Extract the row info dataRow := &SheetDataRow{ Values: make([]interface{}, size), Headers: sheet.Headers, headersLoc: sheet.headersLoc, RowNumber: -1, } //Return the new sheet return dataRow } //Create a new sheet data func (sheet *SheetData) PrintToScreen() { //March over each header fmt.Print("row,") for _, header := range sheet.Headers { fmt.Print(header) fmt.Print(",") } fmt.Println() //Now print each row for r, rowData := range sheet.Values { //Now print the row number fmt.Print(sheet.RowNumb[r]) fmt.Print(",") //Now each data for _, data := range rowData { fmt.Print(data) fmt.Print(",") } fmt.Println() } } //Create a new sheet data func (sheet *SheetData) NumberRows() int { return len(sheet.Values) } /** Count the number of entries for this column */ func (sheet *SheetData) CountEntries(index int) int { //Start with a count count := 0 //March over each row for _, rowData := range sheet.Values { //If the row as data in the index if index < len(rowData) { //If there is data if rowData[index] != nil && len(fmt.Sprint(rowData[index])) > 0 { count++ } } } return count }
google/SheetData.go
0.546254
0.522385
SheetData.go
starcoder
package types const ( BipolarSigmoid = "bipolar-sigmoid" MultilayerPerceptron = "mlp" ) var activationFuncs = []string{BipolarSigmoid} var nets = []string{MultilayerPerceptron} // ActivationFuncs returns the list of supported neuron activation functions func ActivationFuncs() []string { return activationFuncs } // Nets returns the list of supported network types func Nets() []string { return nets } // PagedRes is a wrapper for a paged response where next can be provided as offset for the subsequent request and last // can be used to determine when there is nothing left to read type PagedRes struct { Last bool `json:"last"` Next int `json:"next"` Results interface{} `json:"results"` } // SimpleRes is used for errors and those cases where the response code would be sufficient but a JSON response helps // consistency and user friendliness type SimpleRes struct { Result string `json:"result"` // Possible values are "error" and "ok" Msg string `json:"message"` } // NewOkRes is a shortcut for building a SimpleRes for a successful result func NewOkRes(msg string) *SimpleRes { return &SimpleRes{Result: "ok", Msg: msg} } // NewErrorRes is a shortcut for building a SimpleRes for a failed result func NewErrorRes(msg string) *SimpleRes { return &SimpleRes{Result: "error", Msg: msg} } // BriefNet is a lightweight and standardized representation for neural network parameters type BriefNet struct { Accuracy float32 `json:"accuracy" example:"0.9"` // Fraction of patterns that were predicted correctly during testing ActivationFunc string `json:"activationFunc"` // Function used to calculate the output of a neuron based on its inputs Averages map[string]float32 `json:"averages"` // Averages of each value in the patterns that were used for training Deviations map[string]float32 `json:"deviations"` // Standard deviation of each value in the patterns that were used for training ErrMargin float32 `json:"errMargin"` // Maximum difference between the expected and produced result to still be considered correct during testing HLayers int `json:"hLayers"` // Number of hidden layers ID string `json:"id"` Inputs []string `json:"inputs"` LearningRate float32 `json:"learningRate"` // How much new inputs altered the network during training Outputs []string `json:"outputs"` Type string `json:"type"` } // TrainRequest as its name implies, is used to ask the training service to create or update a net type TrainRequest struct { ErrMargin float32 `json:"errMargin"` // Maximum difference between the expected and produced result to still be considered correct during testing Inputs []string `json:"inputs"` // Which of the series values should be treated as inputs Outputs []string `json:"outputs"` // Which of the series values should be treated as outputs Required int `json:"required"` // Number of points from the series that should be used to train and test SeriesID string `json:"seriesID"` } // BriefSeries is a lightweight representation of a time series type BriefSeries struct { Name string `json:"name"` Count int `json:"count"` } // CategorizedPoint is similar to pointstores.Point but has its values divided into inputs and outputs (this separation // isn't important when it comes to storing it but allows producers to state their intentions so that, when enough // points are available, a training request can be automatically generated) type CategorizedPoint struct { Inputs map[string]float32 `json:"inputs"` Outputs map[string]float32 `json:"outputs"` TimeStamp int64 `json:"timestamp"` } // HasChanged checks that at least one input and one output is different from the given point. As we're going to be // using these to train a neural network it's important that we don't effectively just train it to recognize one value // very well or that the inputs have 0 influence on the outputs func (cp *CategorizedPoint) HasChanged(other CategorizedPoint) bool { inDiff := false for label, value := range cp.Inputs { if other.Inputs[label] != value { inDiff = true break } } outDiff := false for label, value := range cp.Outputs { if other.Outputs[label] != value { outDiff = true break } } return inDiff && outDiff } // MetricsUpdate bundles snapshots of a set of values that share some relation that could be used to predict each // other in a system. This relation doesn't need to be understood (otherwise implement a specific tool for it) but it // should be there for everything to work type MetricsUpdate struct { SeriesID string `json:"seriesID"` ErrMargin float32 `json:"errMargin"` // How much the predicted value of the net can differ from the actual but still be considered acceptable Labels map[string]string `json:"labels"` Points []CategorizedPoint `json:"points"` Stage string `json:"stage"` // Valid stages are test or production }
api/types/types.go
0.865366
0.53959
types.go
starcoder
Cams */ //----------------------------------------------------------------------------- package sdf import ( "fmt" "math" ) //----------------------------------------------------------------------------- // Flat Flank Cams type FlatFlankCamSDF2 struct { distance float64 // center to center circle distance base_radius float64 // radius of base circle nose_radius float64 // radius of nose circle a V2 // lower point on flank line u V2 // normalised line vector for flank l float64 // length of flank line bb Box2 // bounding box } // FlatFlankCam2D creates a 2D cam profile. // The profile is made from a base circle, a smaller nose circle and flat flanks. // The base circle is centered on the origin. // The nose circle is located on the positive y axis. func FlatFlankCam2D( distance float64, // circle to circle center distance base_radius float64, // radius of base circle nose_radius float64, // radius of nose circle ) SDF2 { s := FlatFlankCamSDF2{} s.distance = distance s.base_radius = base_radius s.nose_radius = nose_radius // work out the flank line sin := (base_radius - nose_radius) / distance cos := math.Sqrt(1 - sin*sin) // first point on line s.a = V2{cos, sin}.MulScalar(base_radius) // second point on line b := V2{cos, sin}.MulScalar(nose_radius).Add(V2{0, distance}) // line information u := b.Sub(s.a) s.u = u.Normalize() s.l = u.Length() // work out the bounding box s.bb = Box2{V2{-base_radius, -base_radius}, V2{base_radius, distance + nose_radius}} return &s } // Evaluate returns the minimum distance to the cam. func (s *FlatFlankCamSDF2) Evaluate(p V2) float64 { // we have symmetry about the y-axis p = V2{Abs(p.X), p.Y} // vector to first point of flank line v := p.Sub(s.a) // work out the t-parameter of the projection onto the flank line t := v.Dot(s.u) var d float64 if t < 0 { // the nearest point is on the major circle d = p.Length() - s.base_radius } else if t <= s.l { // the nearest point is on the flank line d = v.Dot(V2{s.u.Y, -s.u.X}) } else { // the nearest point is on the minor circle d = p.Sub(V2{0, s.distance}).Length() - s.nose_radius } return d } // BoundingBox returns the bounding box for the cam. func (s *FlatFlankCamSDF2) BoundingBox() Box2 { return s.bb } // MakeFlatFlankCam makes a flat flank cam profile from design parameters. func MakeFlatFlankCam( lift float64, // follower lift distance from base circle duration float64, // angle over which the follower lifts from the base circle max_diameter float64, // maximum diameter of cam rotation ) (SDF2, error) { if max_diameter <= 0 { return nil, fmt.Errorf("max_diameter <= 0") } if lift <= 0 { return nil, fmt.Errorf("lift <= 0") } if duration <= 0 || duration >= PI { return nil, fmt.Errorf("invalid duration") } base_radius := (max_diameter / 2.0) - lift if base_radius <= 0 { return nil, fmt.Errorf("base_radius <= 0") } delta := duration / 2.0 c := math.Cos(delta) nose_radius := base_radius - (lift*c)/(1-c) if nose_radius <= 0 { return nil, fmt.Errorf("nose_radius <= 0") } distance := base_radius + lift - nose_radius return FlatFlankCam2D(distance, base_radius, nose_radius), nil } //----------------------------------------------------------------------------- // Three Arc Cams type ThreeArcCamSDF2 struct { distance float64 // center to center circle distance base_radius float64 // radius of base circle nose_radius float64 // radius of nose circle flank_radius float64 // radius of flank circle flank_center V2 // center of flank circle (+ve x-axis flank arc) theta_base float64 // base/flank intersection angle wrt flank center theta_nose float64 // nose/flank intersection angle wrt flank center bb Box2 // bounding box } // ThreeArcCam2D creates a 2D cam profile. // The profile is made from a base circle, a smaller nose circle and circular flank arcs. // The base circle is centered on the origin. // The nose circle is located on the positive y axis. // The flank arcs are tangential to the base and nose circles. func ThreeArcCam2D( distance float64, // circle to circle center distance base_radius float64, // radius of base circle nose_radius float64, // radius of nose circle flank_radius float64, // radius of flank arc ) SDF2 { // check for the minimum size flank radius if flank_radius < (base_radius+distance+nose_radius)/2.0 { panic("flank_radius too small") } s := ThreeArcCamSDF2{} s.distance = distance s.base_radius = base_radius s.nose_radius = nose_radius s.flank_radius = flank_radius // work out the center for the flank radius // the flank arc center must lie on the intersection // of two circles about the base/nose circles r0 := flank_radius - base_radius r1 := flank_radius - nose_radius y := ((r0 * r0) - (r1 * r1) + (distance * distance)) / (2.0 * distance) x := -math.Sqrt((r0 * r0) - (y * y)) // < 0 result, +ve x-axis flank arc s.flank_center = V2{x, y} // work out theta for the intersection of flank arc and base radius p := V2{0, 0}.Sub(s.flank_center) s.theta_base = math.Atan2(p.Y, p.X) // work out theta for the intersection of flank arc and nose radius p = V2{0, distance}.Sub(s.flank_center) s.theta_nose = math.Atan2(p.Y, p.X) // work out the bounding box // TODO fix this - it's wrong if the flank radius is small s.bb = Box2{V2{-base_radius, -base_radius}, V2{base_radius, distance + nose_radius}} return &s } // Evaluate returns the minimum distance to the cam. func (s *ThreeArcCamSDF2) Evaluate(p V2) float64 { // we have symmetry about the y-axis p0 := V2{Abs(p.X), p.Y} // work out the theta angle wrt the flank center v := p0.Sub(s.flank_center) t := math.Atan2(v.Y, v.X) // work out the minimum distance var d float64 if t < s.theta_base { // the closest point is on the base radius d = p0.Length() - s.base_radius } else if t > s.theta_nose { // the closest point is on the nose radius d = p0.Sub(V2{0, s.distance}).Length() - s.nose_radius } else { // the closest point is on the flank radius d = v.Length() - s.flank_radius } return d } // BoundingBox returns the bounding box for the cam. func (s *ThreeArcCamSDF2) BoundingBox() Box2 { return s.bb } // MakeThreeArcCam makes a three arc cam profile from design parameters. func MakeThreeArcCam( lift float64, // follower lift distance from base circle duration float64, // angle over which the follower lifts from the base circle max_diameter float64, // maximum diameter of cam rotation k float64, // tunable, bigger k = rounder nose, E.g. 1.05 ) (SDF2, error) { if max_diameter <= 0 { return nil, fmt.Errorf("max_diameter <= 0") } if lift <= 0 { return nil, fmt.Errorf("lift <= 0") } if duration <= 0 { return nil, fmt.Errorf("invalid duration") } if k <= 1.0 { return nil, fmt.Errorf("invalid k") } base_radius := (max_diameter / 2.0) - lift if base_radius <= 0 { return nil, fmt.Errorf("base_radius <= 0") } // Given the duration we know where the flank arc intersects the base circle. theta := (PI - duration) / 2.0 p0 := V2{math.Cos(theta), math.Sin(theta)}.MulScalar(base_radius) // This gives us a line back to the flank arc center l0 := NewLine2_PV(p0, p0.Negate()) //The flank arc intersects the y axis above the lift height. p1 := V2{0, k * (base_radius + lift)} // The perpendicular bisector of p0 and p1 passes through the flank arc center. p_mid := p1.Add(p0).MulScalar(0.5) u := p1.Sub(p0) l1 := NewLine2_PV(p_mid, V2{u.Y, -u.X}) // Intersect to find the flank arc center. flank_radius, _, err := l0.Intersect(l1) if err != nil { return nil, err } flank_center := l0.Position(flank_radius) // The nose circle is tangential to the flank arcs and the lift line. j := base_radius + lift f := flank_radius cx := flank_center.X cy := flank_center.Y nose_radius := ((cx * cx) + (cy * cy) - (f * f) + (j * j) - (2 * cy * j)) / (2 * (j - f - cy)) // distance between base and nose circles distance := base_radius + lift - nose_radius return ThreeArcCam2D(distance, base_radius, nose_radius, flank_radius), nil } //----------------------------------------------------------------------------- // MakeGenevaCAM makes 2D profiles for the driver/driven wheels of a geneva cam. func MakeGenevaCam( num_sectors int, // number of sectors in the driven wheel center_distance float64, // center to center distance of driver/driven wheels driver_radius float64, // radius of lock portion of driver wheel driven_radius float64, // radius of driven wheel pin_radius float64, // radius of driver pin clearance float64, // pin/slot and wheel/wheel clearance ) (SDF2, SDF2, error) { if num_sectors < 2 { return nil, nil, fmt.Errorf("invalid number of sectors, must be > 2") } if center_distance <= 0 || driven_radius <= 0 || driver_radius <= 0 || pin_radius <= 0 { return nil, nil, fmt.Errorf("invalid dimensions, must be > 0") } if clearance < 0 { return nil, nil, fmt.Errorf("invalid clearance, must be >= 0") } if center_distance > driven_radius+driver_radius { return nil, nil, fmt.Errorf("center distance is too large") } // work out the pin offset from the center of the driver wheel theta := TAU / (2.0 * float64(num_sectors)) d := center_distance r := driven_radius pin_offset := math.Sqrt((d * d) + (r * r) - (2 * d * r * math.Cos(theta))) // driven wheel s_driven := Circle2D(driven_radius - clearance) // cutouts for the driver wheel s := Circle2D(driver_radius + clearance) s = Transform2D(s, Translate2d(V2{center_distance, 0})) s = RotateCopy2D(s, num_sectors) s_driven = Difference2D(s_driven, s) // cutouts for the pin slots slot_length := pin_offset + driven_radius - center_distance s = Line2D(2*slot_length, pin_radius+clearance) s = Transform2D(s, Translate2d(V2{driven_radius, 0})) s = RotateCopy2D(s, num_sectors) s = Transform2D(s, Rotate2d(theta)) s_driven = Difference2D(s_driven, s) // driver wheel s_driver := Circle2D(driver_radius - clearance) // cutout for the driven wheel s = Circle2D(driven_radius + clearance) s = Transform2D(s, Translate2d(V2{center_distance, 0})) s_driver = Difference2D(s_driver, s) // driver pin s = Circle2D(pin_radius) s = Transform2D(s, Translate2d(V2{pin_offset, 0})) s_driver = Union2D(s_driver, s) return s_driver, s_driven, nil } //-----------------------------------------------------------------------------
sdf/cams.go
0.775265
0.505249
cams.go
starcoder
package vtree import ( "strings" "testing" ) // AssertElementCount asserts the number of elements func AssertElementCount(t *testing.T, elements []*Element, count int) { if l := len(elements); l != count { t.Errorf("Expected %d elements but got %d", count, l) } } // AssertElement asserts that el is of the specified type func AssertElement(t *testing.T, el *Element, Type string) { t.Helper() if el.Type != Type { t.Errorf("Expected <%s> tag, got %s in stead", Type, el.Type) } } // AssertElementAttributes asserts that element has exactly the specified // attributes, excluding g-* expression attributes func AssertElementAttributes(t *testing.T, el *Element, Attributes Attributes) { t.Helper() attrCount := 0 for k := range el.Attributes { if !strings.HasPrefix(k, "g-") { attrCount++ } } if attrCount != len(Attributes) { t.Errorf("Amount of attributes doesn't match, expected %d but got %d", len(Attributes), attrCount) } for k, v := range Attributes { gotV, ok := el.Attributes[k] if !ok { t.Errorf("Didn't get expected attribute/value %s->%s", k, v) } else if v != gotV { t.Errorf("Value for %s didn't match, expected %s but got %s", k, v, gotV) } } } // AssertTextNode asserts that node is a TextNode with the specified string content func AssertTextNode(t *testing.T, node Node, content string) { t.Helper() tNode, ok := node.(*Text) if !ok { t.Errorf("Expected node to be Text, got %T", node) } if tNode.Text != content { t.Errorf("Expected text to match '%s', got '%s'", content, tNode.Text) } } // AssertAttribute asserts the presence and value of an attribute on an element func AssertAttribute(t *testing.T, e *Element, key string, value string) { t.Helper() if val, ok := e.Attributes[key]; !ok || val != value { t.Errorf("Didn't get expected attribute, got %s", val) } } // AssertAttributeNotPresent asserts a specific attribute does not exist on an element func AssertAttributeNotPresent(t *testing.T, e *Element, key string) { t.Helper() if val, ok := e.Attributes[key]; ok { t.Errorf("Unexpectedly found attribute %s with value %s", key, val) } }
vtree/vtree_helpers.go
0.600188
0.435241
vtree_helpers.go
starcoder
package matrix import ( "github.com/pkg/errors" "strconv" "strings" ) // Matrix represents a two dimensional matrix type Matrix struct { table [][]int } // New creates a new Matrix from a given string, // such as that "1 4 9\n16 25 36" will create a matrix representing: // 0 1 2 // |----------- // 0 | 1 4 9 // 1 | 16 15 36 func New(input string) (*Matrix, error) { table, err := createTable(input) if err != nil { return nil, err } return &Matrix{table: table}, nil } // Set sets a given int value on the given row and column index func (m Matrix) Set(row int, col int, val int) bool { if row > len(m.table)-1 || row < 0 || col > len(m.table[0])-1 || col < 0 { return false } m.table[row][col] = val return true } // Rows returns the rows of the matrix e.g. // 0 1 2 // |----------- // 0 | 1 4 9 // 1 | 16 15 36 // returns // 1 4 9 // 16 15 36 func (m Matrix) Rows() [][]int { return copyTable(m.table) } // Cols returns the columns of the matrix e.g. // 0 1 2 // |----------- // 0 | 1 4 9 // 1 | 16 15 36 // returns // 1 16 // 4 15 // 9 36 func (m Matrix) Cols() [][]int { return transpose(m.table) } func createTable(input string) ([][]int, error) { rows := strings.Split(input, "\n") table := make([][]int, len(rows)) for i, row := range rows { columns, err := createColumns(strings.Fields(row)) if err != nil { return nil, err } if i > 0 && len(columns) != len(table[0]) { return nil, errors.New("uneven length of row") } table[i] = columns } return table, nil } func createColumns(fields []string) ([]int, error) { columns := make([]int, len(fields)) for j, field := range fields { value, err := strconv.Atoi(field) if err != nil { return nil, err } columns[j] = value } return columns, nil } func copyTable(table [][]int) [][]int { tableCopy := make([][]int, len(table)) for i, row := range table { rowCopy := make([]int, len(row)) copy(rowCopy, row) tableCopy[i] = rowCopy } return tableCopy } func transpose(table [][]int) [][]int { rowCount := len(table) colCount := len(table[0]) tableCopy := make([][]int, colCount) for i := 0; i < colCount; i++ { transCol := make([]int, rowCount) for j := 0; j < rowCount; j++ { transCol[j] = table[j][i] } tableCopy[i] = transCol } return tableCopy }
matrix/matrix.go
0.754553
0.437283
matrix.go
starcoder
package day02 import ( "fmt" "io" "os" "sort" "strconv" "strings" "unicode/utf8" ) /* Solve1 solves the following AOC problem: The elves are running low on wrapping paper, and so they need to submit an order for more. They have a list of the dimensions (length l, width w, and height h) of each present, and only want to order exactly as much as they need. Fortunately, every present is a box (a perfect right rectangular prism), which makes calculating the required wrapping paper for each gift a little easier: find the surface area of the box, which is 2*l*w + 2*w*h + 2*h*l. The elves also need a little extra paper for each present: the area of the smallest side. For example: A present with dimensions 2x3x4 requires 2*6 + 2*12 + 2*8 = 52 square feet of wrapping paper plus 6 square feet of slack, for a total of 58 square feet. A present with dimensions 1x1x10 requires 2*1 + 2*10 + 2*10 = 42 square feet of wrapping paper plus 1 square foot of slack, for a total of 43 square feet. All numbers in the elves' list are in feet. How many total square feet of wrapping paper should they order? */ func Solve1(input io.Reader) (totalSurfaceArea int, err error) { for { var line string _, err = fmt.Fscanln(input, &line) if err == io.EOF { err = nil break } else if err != nil { return } var l, w, h int l, w, h, err = parseLine(line) if err != nil { return } totalSurfaceArea += wrappingPaperArea(l, w, h) } return } /* Solve2 solves the following AOC 2015 problem: The elves are also running low on ribbon. Ribbon is all the same width, so they only have to worry about the length they need to order, which they would again like to be exact. The ribbon required to wrap a present is the shortest distance around its sides, or the smallest perimeter of any one face. Each present also requires a bow made out of ribbon as well; the feet of ribbon required for the perfect bow is equal to the cubic feet of volume of the present. Don't ask how they tie the bow, though; they'll never tell. For example: A present with dimensions 2x3x4 requires 2+2+3+3 = 10 feet of ribbon to wrap the present plus 2*3*4 = 24 feet of ribbon for the bow, for a total of 34 feet. A present with dimensions 1x1x10 requires 1+1+1+1 = 4 feet of ribbon to wrap the present plus 1*1*10 = 10 feet of ribbon for the bow, for a total of 14 feet. How many total feet of ribbon should they order? */ func Solve2(input io.Reader) (totalLength int, err error) { for { var line string _, err = fmt.Fscanln(input, &line) if err == io.EOF { err = nil break } else if err != nil { return } var l, w, h int l, w, h, err = parseLine(line) if err != nil { return } totalLength += ribbonLength(l, w, h) } return } func ribbonLength(l int, w int, h int) int { s := []int{l, w, h} sort.Ints(s) return 2*s[0] + 2*s[1] + l*w*h } func wrappingPaperArea(l int, w int, h int) int { var min int t1 := l * w t2 := l * h t3 := w * h // Find the area of the smallest face if t1 < t2 { min = t1 } else { min = t2 } if t3 < min { min = t3 } // Total paper area = surface area + area of smallest face return 2*(t1+t2+t3) + min } func parseLine(line string) (l int, w int, h int, err error) { // skip empty lines // this is ugly but at least it's unicode-aware buf := []byte(line) if utf8.RuneCount(buf) == 0 { return } subs := strings.Split(line, "x") if len(subs) != 3 { err = fmt.Errorf("Wrong number of dimensions: %d from %q", len(subs), line) return } var se error l, se = strconv.Atoi(subs[0]) w, se = strconv.Atoi(subs[1]) h, se = strconv.Atoi(subs[2]) if l < 0 || w < 0 || h < 0 || se != nil { err = fmt.Errorf("Invalid box measurements %dx%dx%d", l, w, h) } return } /* Solver holds the File reference for this day's input and implements the SolutionPrinter interface. */ type Solver struct { Input *os.File } /* PrintSolutions prints the solutions for this day's problems. */ func (s Solver) PrintSolutions() { defer s.Input.Close() res, err := Solve1(s.Input) if err != nil { fmt.Println("ERROR:", err) } else { fmt.Printf("Day 2, Part 1: The elves should order %d square feet of wrapping paper.\n", res) } s.Input.Seek(0, io.SeekStart) res, err = Solve2(s.Input) if err != nil { fmt.Println("ERROR:", err) } else { fmt.Printf("Day 2, Part 2: The elves should order %d feet of ribbon.\n", res) } }
day02/day02.go
0.604866
0.563858
day02.go
starcoder
package nmea import ( "fmt" "github.com/martinlindhe/unit" ) const ( // TypeVWR type for VWR sentences TypeVWR = "VWR" LeftOfBow = "L" RightOfBow = "R" ) // Sentence info: // 1 Measured angle relative to the vessel, left/right of vessel heading, to the nearest 0.1 degree // 2 L: Left, or R: Right // 3 Measured wind speed, knots, to the nearest 0.1 knot // 4 N: knots // 5 Wind speed, meters per second, to the nearest 0.1 m/s // 6 M: meters per second // 7 Wind speed, km/h, to the nearest km/h // 8 K: km/h // VWR - Relative (Apparent) Wind Speed and Angle type VWR struct { BaseSentence Angle Float64 LeftRightOfBow String WindSpeedInKnots Float64 WindSpeedInMetersPerSecond Float64 WindSpeedInKilometersPerHour Float64 } // newVWR constructor func newVWR(s BaseSentence) (VWR, error) { p := NewParser(s) p.AssertType(TypeVWR) m := VWR{ BaseSentence: s, Angle: p.Float64(0, "Angle"), LeftRightOfBow: p.EnumString(1, "LeftRightOfBow", LeftOfBow, RightOfBow), WindSpeedInKnots: p.Float64(2, "WindSpeedInKnots"), WindSpeedInMetersPerSecond: p.Float64(4, "WindSpeedInMetersPerSecond"), WindSpeedInKilometersPerHour: p.Float64(6, "WindSpeedInKilometersPerHour"), } return m, p.Err() } // GetRelativeWindDirection retrieves the true wind direction from the sentence func (s VWR) GetRelativeWindDirection() (float64, error) { if v, err := s.Angle.GetValue(); err == nil { if s.LeftRightOfBow.Value == LeftOfBow { return -(unit.Angle(v) * unit.Degree).Radians(), nil } if s.LeftRightOfBow.Value == RightOfBow { return (unit.Angle(v) * unit.Degree).Radians(), nil } } return 0, fmt.Errorf("value is unavailable") } // GetWindSpeed retrieves wind speed from the sentence func (s VWR) GetWindSpeed() (float64, error) { if v, err := s.WindSpeedInMetersPerSecond.GetValue(); err == nil { return v, nil } if v, err := s.WindSpeedInKilometersPerHour.GetValue(); err == nil { return (unit.Speed(v) * unit.KilometersPerHour).MetersPerSecond(), nil } if v, err := s.WindSpeedInKnots.GetValue(); err == nil { return (unit.Speed(v) * unit.Knot).MetersPerSecond(), nil } return 0, fmt.Errorf("value is unavailable") }
vwr.go
0.677367
0.418875
vwr.go
starcoder
package convert import "strconv" // ToInt convert to int func ToInt(str interface{}) int { switch str.(type) { case uint: return int(str.(uint)) case uint64: return int(str.(uint64)) case int: return str.(int) case int64: return int(str.(int64)) case string: atoi, _ := strconv.Atoi(str.(string)) return atoi case float64: return int(str.(float64)) case float32: return int(str.(float32)) case bool: if str.(bool) { return 1 } return 0 default: return 0 } } // ToUInt convert to uint func ToUInt(str interface{}) uint { switch str.(type) { case uint64: return uint(str.(uint64)) case uint: return str.(uint) case int: return uint(str.(int)) case int64: return uint(str.(int64)) case string: atoi, _ := strconv.Atoi(str.(string)) return uint(atoi) case float64: return uint(str.(float64)) case float32: return uint(str.(float32)) default: return 0 } } // ToUInt64 convert to uint64 func ToUInt64(str interface{}) uint64 { switch str.(type) { case uint64: return str.(uint64) case uint: return uint64(str.(uint)) case int: return uint64(str.(int)) case int64: return uint64(str.(int64)) case string: atoi, _ := strconv.Atoi(str.(string)) return uint64(atoi) case float64: return uint64(str.(float64)) case float32: return uint64(str.(float32)) default: return 0 } } // ToInt64 convert to int64 func ToInt64(str interface{}) int64 { switch str.(type) { case uint64: return int64(str.(uint64)) case uint: return int64(str.(uint)) case int: return int64(str.(int)) case int64: return str.(int64) case string: atoi, _ := strconv.Atoi(str.(string)) return int64(atoi) case float64: return int64(str.(float64)) case float32: return int64(str.(float32)) default: return 0 } } // ToFloat64 convert to float64 func ToFloat64(str interface{}) float64 { switch str.(type) { case uint64: return float64(str.(uint64)) case uint: return float64(str.(uint)) case int: return float64(str.(int)) case int64: return float64(str.(int64)) case string: float, _ := strconv.ParseFloat(ToString(str), 64) return float case float64: return str.(float64) case float32: return float64(str.(float32)) default: return float64(0) } }
convert/number.go
0.503174
0.481515
number.go
starcoder
package primitives import ( "github.com/alexandreLamarre/Golang-Ray-Tracing-Renderer/pkg/algebra" "github.com/alexandreLamarre/Golang-Ray-Tracing-Renderer/pkg/canvas" "math" ) //Cube defines a 3d cube Shape type Cube struct { parent Shape transform *algebra.Matrix material *canvas.Material } //NewCube returns a new Cube Shape with an identity matrix/ default material func NewCube(m *algebra.Matrix) *Cube { mat := m if m == nil || len(m.Get()) != 4 || len(m.Get()[0]) != 4 { mat = algebra.IdentityMatrix(4) } return &Cube{transform: mat, material: canvas.NewDefaultMaterial(), parent: nil} } // Shape interface functions //GetTransform Getter for Cube transform, Shape interface method func (c *Cube) GetTransform() *algebra.Matrix { return c.transform } //SetTransform Setter for Cube transform, Shape interface method func (c *Cube) SetTransform(m *algebra.Matrix) { if len(m.Get()) != 4 || len(m.Get()[0]) != 4 { panic(algebra.ExpectedDimension(4)) } c.transform = m } //GetMaterial Getter for Cube material, Shape interface method func (c *Cube) GetMaterial() *canvas.Material { return c.material } //SetMaterial Setter for Cube material, Shape interface method func (c *Cube) SetMaterial(m *canvas.Material) { c.material = m } //SetParent Setter for parent shape func (c *Cube) SetParent(shape Shape) { c.parent = shape } //GetParent Getter for parent shape func (c *Cube) GetParent() Shape { return c.parent } //GetBounds Getter for default bounds of this Shape func (c *Cube) GetBounds() (*algebra.Vector, *algebra.Vector) { return algebra.NewPoint(-1, -1, -1), algebra.NewPoint(1, 1, 1) } //LocalIntersect returns the itersection values for a Ray with a Cube func (c *Cube) LocalIntersect(ray *algebra.Ray) ([]*Intersection, bool) { origin := ray.Get()["origin"] direction := ray.Get()["direction"] xtmin, xtmax := checkAxis(origin.Get()[0], direction.Get()[0]) ytmin, ytmax := checkAxis(origin.Get()[1], direction.Get()[1]) ztmin, ztmax := checkAxis(origin.Get()[2], direction.Get()[2]) tmin := max(xtmin, ytmin, ztmin) tmax := min(xtmax, ytmax, ztmax) if tmin > tmax { return []*Intersection{}, false } return []*Intersection{NewIntersection(c, tmin), NewIntersection(c, tmax)}, true } //LocalNormalAt returns the normal at a ray intersection point func (c *Cube) LocalNormalAt(p *algebra.Vector, intersection *Intersection) (*algebra.Vector, error) { maxc := max(math.Abs(p.Get()[0]), math.Abs(p.Get()[1]), math.Abs(p.Get()[2])) if maxc == math.Abs(p.Get()[0]) { return algebra.NewVector(p.Get()[0], 0, 0), nil } else if maxc == math.Abs(p.Get()[1]) { return algebra.NewVector(0, p.Get()[1], 0), nil } return algebra.NewVector(0, 0, p.Get()[2]), nil } //helpers for cube methods func checkAxis(origin, direction float64) (float64, float64) { tminNumerator := -1 - origin tmaxNumerator := 1 - origin var tmin float64 var tmax float64 EPSILON := 0.0001 if math.Abs(direction) >= EPSILON { tmin = tminNumerator / direction tmax = tmaxNumerator / direction } else { tmin = tminNumerator * math.Inf(1) tmax = tmaxNumerator * math.Inf(1) } if tmin > tmax { temp := tmin tmin = tmax tmax = temp } return tmin, tmax } func max(values ...float64) float64 { if len(values) == 1 { return values[0] } maxVal := math.Inf(-1) for i := 0; i < len(values); i++ { maxVal = math.Max(values[i], maxVal) } return maxVal } func min(values ...float64) float64 { if len(values) == 1 { return values[0] } minVal := math.Inf(1) for i := 0; i < len(values); i++ { minVal = math.Min(values[i], minVal) } return minVal }
pkg/geometry/primitives/cube.go
0.735357
0.469095
cube.go
starcoder
package ent import ( "fmt" "strings" "time" "entgo.io/ent/dialect/sql" "github.com/DanielTitkov/anomaly-detection-service/internal/repository/entgo/ent/detectionjob" ) // DetectionJob is the model entity for the DetectionJob schema. type DetectionJob struct { config `json:"-"` // ID of the ent. ID int `json:"id,omitempty"` // CreateTime holds the value of the "create_time" field. CreateTime time.Time `json:"create_time,omitempty"` // UpdateTime holds the value of the "update_time" field. UpdateTime time.Time `json:"update_time,omitempty"` // Schedule holds the value of the "schedule" field. Schedule *string `json:"schedule,omitempty"` // Method holds the value of the "method" field. Method string `json:"method,omitempty"` // SiteID holds the value of the "site_id" field. SiteID string `json:"site_id,omitempty"` // Metric holds the value of the "metric" field. Metric string `json:"metric,omitempty"` // Attribute holds the value of the "attribute" field. Attribute string `json:"attribute,omitempty"` // TimeAgo holds the value of the "time_ago" field. TimeAgo string `json:"time_ago,omitempty"` // TimeStep holds the value of the "time_step" field. TimeStep string `json:"time_step,omitempty"` // Description holds the value of the "description" field. Description string `json:"description,omitempty"` // Edges holds the relations/edges for other nodes in the graph. // The values are being populated by the DetectionJobQuery when eager-loading is set. Edges DetectionJobEdges `json:"edges"` } // DetectionJobEdges holds the relations/edges for other nodes in the graph. type DetectionJobEdges struct { // Instance holds the value of the instance edge. Instance []*DetectionJobInstance `json:"instance,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. loadedTypes [1]bool } // InstanceOrErr returns the Instance value or an error if the edge // was not loaded in eager-loading. func (e DetectionJobEdges) InstanceOrErr() ([]*DetectionJobInstance, error) { if e.loadedTypes[0] { return e.Instance, nil } return nil, &NotLoadedError{edge: "instance"} } // scanValues returns the types for scanning values from sql.Rows. func (*DetectionJob) scanValues(columns []string) ([]interface{}, error) { values := make([]interface{}, len(columns)) for i := range columns { switch columns[i] { case detectionjob.FieldID: values[i] = &sql.NullInt64{} case detectionjob.FieldSchedule, detectionjob.FieldMethod, detectionjob.FieldSiteID, detectionjob.FieldMetric, detectionjob.FieldAttribute, detectionjob.FieldTimeAgo, detectionjob.FieldTimeStep, detectionjob.FieldDescription: values[i] = &sql.NullString{} case detectionjob.FieldCreateTime, detectionjob.FieldUpdateTime: values[i] = &sql.NullTime{} default: return nil, fmt.Errorf("unexpected column %q for type DetectionJob", columns[i]) } } return values, nil } // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the DetectionJob fields. func (dj *DetectionJob) assignValues(columns []string, values []interface{}) error { if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } for i := range columns { switch columns[i] { case detectionjob.FieldID: value, ok := values[i].(*sql.NullInt64) if !ok { return fmt.Errorf("unexpected type %T for field id", value) } dj.ID = int(value.Int64) case detectionjob.FieldCreateTime: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field create_time", values[i]) } else if value.Valid { dj.CreateTime = value.Time } case detectionjob.FieldUpdateTime: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field update_time", values[i]) } else if value.Valid { dj.UpdateTime = value.Time } case detectionjob.FieldSchedule: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field schedule", values[i]) } else if value.Valid { dj.Schedule = new(string) *dj.Schedule = value.String } case detectionjob.FieldMethod: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field method", values[i]) } else if value.Valid { dj.Method = value.String } case detectionjob.FieldSiteID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field site_id", values[i]) } else if value.Valid { dj.SiteID = value.String } case detectionjob.FieldMetric: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field metric", values[i]) } else if value.Valid { dj.Metric = value.String } case detectionjob.FieldAttribute: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field attribute", values[i]) } else if value.Valid { dj.Attribute = value.String } case detectionjob.FieldTimeAgo: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field time_ago", values[i]) } else if value.Valid { dj.TimeAgo = value.String } case detectionjob.FieldTimeStep: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field time_step", values[i]) } else if value.Valid { dj.TimeStep = value.String } case detectionjob.FieldDescription: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field description", values[i]) } else if value.Valid { dj.Description = value.String } } } return nil } // QueryInstance queries the "instance" edge of the DetectionJob entity. func (dj *DetectionJob) QueryInstance() *DetectionJobInstanceQuery { return (&DetectionJobClient{config: dj.config}).QueryInstance(dj) } // Update returns a builder for updating this DetectionJob. // Note that you need to call DetectionJob.Unwrap() before calling this method if this DetectionJob // was returned from a transaction, and the transaction was committed or rolled back. func (dj *DetectionJob) Update() *DetectionJobUpdateOne { return (&DetectionJobClient{config: dj.config}).UpdateOne(dj) } // Unwrap unwraps the DetectionJob entity that was returned from a transaction after it was closed, // so that all future queries will be executed through the driver which created the transaction. func (dj *DetectionJob) Unwrap() *DetectionJob { tx, ok := dj.config.driver.(*txDriver) if !ok { panic("ent: DetectionJob is not a transactional entity") } dj.config.driver = tx.drv return dj } // String implements the fmt.Stringer. func (dj *DetectionJob) String() string { var builder strings.Builder builder.WriteString("DetectionJob(") builder.WriteString(fmt.Sprintf("id=%v", dj.ID)) builder.WriteString(", create_time=") builder.WriteString(dj.CreateTime.Format(time.ANSIC)) builder.WriteString(", update_time=") builder.WriteString(dj.UpdateTime.Format(time.ANSIC)) if v := dj.Schedule; v != nil { builder.WriteString(", schedule=") builder.WriteString(*v) } builder.WriteString(", method=") builder.WriteString(dj.Method) builder.WriteString(", site_id=") builder.WriteString(dj.SiteID) builder.WriteString(", metric=") builder.WriteString(dj.Metric) builder.WriteString(", attribute=") builder.WriteString(dj.Attribute) builder.WriteString(", time_ago=") builder.WriteString(dj.TimeAgo) builder.WriteString(", time_step=") builder.WriteString(dj.TimeStep) builder.WriteString(", description=") builder.WriteString(dj.Description) builder.WriteByte(')') return builder.String() } // DetectionJobs is a parsable slice of DetectionJob. type DetectionJobs []*DetectionJob func (dj DetectionJobs) config(cfg config) { for _i := range dj { dj[_i].config = cfg } }
internal/repository/entgo/ent/detectionjob.go
0.72526
0.422624
detectionjob.go
starcoder
package stream import ( "os" "testing" "vincent.click/pkg/preflight/expect" ) // Writable is a set of expectations about a writable stream type Writable struct { *testing.T r reader b []byte } // ExpectWritten returns expectations based on a function that writes to a stream func ExpectWritten(t *testing.T, consumer Consumer) Expectations { w, err := os.CreateTemp(os.TempDir(), "preflight-") if err != nil { return Faulty(t, err) } consumer(w) // open for reading r, err := os.OpenFile(w.Name(), os.O_RDONLY, 0) if err != nil { return Faulty(t, err) } return &Writable{ T: t, r: r, } } // Close the stream and remove the temporary file func (w *Writable) Close() error { if err := w.r.Close(); err != nil { return err } return os.Remove(w.r.Name()) } // Size returns an Expectation about the number of bytes written func (w *Writable) Size() expect.Expectation { stat, err := w.r.Stat() if err != nil { return expect.Faulty(w.T, err) } return expect.Value(w.T, stat.Size()) } // Text returns an Expectation about all text written to the stream func (w *Writable) Text() expect.Expectation { txt, err := readAll(w.r) if err != nil { return expect.Faulty(w.T, err) } return expect.Value(w.T, string(txt)) } // NextText returns an Expectation about the next chunk of text written to the stream func (w *Writable) NextText(bytes int) expect.Expectation { data, err := read(w.r, bytes) if err != nil { return expect.Faulty(w.T, err) } return expect.Value(w.T, string(data)) } // TextAt returns an Expectation about the text written at a specific position func (w *Writable) TextAt(pos int64, bytes int) expect.Expectation { data, err := readAt(w.r, pos, bytes) if err != nil { return expect.Faulty(w.T, err) } return expect.Value(w.T, string(data)) } // Bytes returns an Expectation about all bytes written to the stream func (w *Writable) Bytes() expect.Expectation { bytes, err := readAll(w.r) if err != nil { return expect.Faulty(w.T, err) } return expect.Value(w.T, bytes) } // NextBytes returns an Expectation about the next chunk of bytes written to the stream func (w *Writable) NextBytes(bytes int) expect.Expectation { data, err := read(w.r, bytes) if err != nil { return expect.Faulty(w.T, err) } return expect.Value(w.T, data) } // BytesAt returns an Expectation about the bytes written at a specific position func (w *Writable) BytesAt(pos int64, bytes int) expect.Expectation { data, err := readAt(w.r, pos, bytes) if err != nil { return expect.Faulty(w.T, err) } return expect.Value(w.T, data) } // Lines returns an Expectation about all lines of text written to the stream func (w *Writable) Lines() expect.Expectation { lines := []string{} for { line, bytes, err := readLine(w.r, w.b) if err != nil { return expect.Faulty(w.T, err) } w.b = bytes if len(line) < 1 { break } lines = append(lines, string(line)) } return expect.Value(w.T, lines) } // NextLine returns an Expectation about the next line of text func (w *Writable) NextLine() expect.Expectation { line, bytes, err := readLine(w.r, w.b) if err != nil { return expect.Faulty(w.T, err) } w.b = bytes return expect.Value(w.T, string(line)) } // ContentType returns an Expectation about content type written to the stream func (w *Writable) ContentType() expect.Expectation { if typ, err := detectContentType(w.r); err != nil { return expect.Faulty(w.T, err) } else { return expect.Value(w.T, typ) } }
stream/writable.go
0.768386
0.470493
writable.go
starcoder
package binomial import ( "golang.org/x/exp/constraints" ) const ( isNil = 0 notNil = 1 ) // Binomial is a binomial queue type Binomial[O constraints.Ordered] struct { size int trees []*node[O] } // New return a binomial queue with default capacity func New[O constraints.Ordered]() *Binomial[O] { return &Binomial[O]{ trees: make([]*node[O], 8), } } // Merge bq1 to bq. ErrExceedCap returned when merge would exceed capacity func (b *Binomial[O]) Merge(b2 *Binomial[O]) { if len(b2.trees) > len(b.trees) { *b, *b2 = *b2, *b } b.size += b2.size n := len(b.trees) var carry *node[O] for i := 0; i < n; i++ { switch carry.isNil()<<2 + b2.isNil(i)<<1 + b.isNil(i) { case 2: // 010 b.trees[i] = b2.trees[i] case 3: // 011 carry = merge(b.trees[i], b2.trees[i]) b.trees[i] = nil case 4: // 100 b.trees[i] = carry carry = nil case 5: // 101 carry = merge(carry, b.trees[i]) b.trees[i] = nil case 6: // 110 fallthrough case 7: // 111 carry = merge(carry, b2.trees[i]) default: // 000, 001 } } if carry != nil { b.trees = append(b.trees, carry) } } func (b *Binomial[O]) isNil(i int) int { if i >= len(b.trees) { return isNil } return b.trees[i].isNil() } func (b *Binomial[O]) Push(p O) { b.Merge(&Binomial[O]{ size: 1, trees: []*node[O]{{p: p}}, }) } func (b *Binomial[O]) Pop() O { index := 0 // index of node to pop for ; index < len(b.trees); index++ { if b.trees[index] != nil { break } } for i := index + 1; i < len(b.trees); i++ { if b.trees[i] != nil && b.trees[i].p < b.trees[index].p { index = i } } // remove tree at index popNode := b.trees[index] b.trees[index] = nil b.size -= 1 << uint(index) // trees left by popNode become a new binomial trees := popNode.son b2 := &Binomial[O]{ trees: make([]*node[O], index), } for i := index - 1; i >= 0; i-- { b2.trees[i] = trees sibling := trees.sibling trees.sibling = nil trees = sibling } b2.size = 1<<uint(index) - 1 // merge b2 back b.Merge(b2) return popNode.p } // Size get the current size of this binomial queue func (b *Binomial[O]) Size() int { return b.size } type node[O constraints.Ordered] struct { p O sibling *node[O] son *node[O] } func (n *node[O]) isNil() int { if n == nil { return isNil } return notNil } // both a and b MUST not be nil func merge[O constraints.Ordered](a, b *node[O]) *node[O] { if a.p > b.p { *a, *b = *b, *a } b.sibling = a.son a.son = b return a }
pq/binomial/binomial.go
0.575349
0.47171
binomial.go
starcoder
package interfaces //UserPermission Permissions are based on a 64bit uint64, the following is comparisons for that type UserPermission uint64 //So quick overview of how this will work //We choose powers of 2 //1, 2, 4, 8... because in binary these map to specific bits //0001, 0010, 0100, 1000 //When you bit-and two numbers together, only bits that are both 1 will be kept. //Since each permission only has 1 bit with 1, we can do a bitand and see if the result is the same as the permission we are look for //Example, permission 3 is 0011, we want to see if this permission has AddTags, which is 2 or 0010. //0010 & 0011 = 0010, so the output is same as the permission we are checking, user has that permission const ( //ViewImagesAndTags View only access to Images and Tags ViewImagesAndTags UserPermission = 0 //ModifyImageTags Allows a user to add and remove tags to/from an image, but not create or delete tags themselves ModifyImageTags UserPermission = 1 //AddTags Allows a user to add a new tag to the system (But not delete) AddTags UserPermission = 2 //ModifyTags Allows a user to modify a tag from the system ModifyTags UserPermission = 4 //RemoveTags Allows a user to remove a tag from the system RemoveTags UserPermission = 8 //UploadImage Allows a user to upload an image UploadImage UserPermission = 16 //Note that it is probably a good idea to ensure users have ModifyImageTags at a minimum //RemoveOtherImages Allows a user to remove an uploaded image. (Note that we can short circuit this in other code to allow a user to remove their own images) RemoveImage UserPermission = 32 //DisableUser Allows a user to disable another user DisableUser UserPermission = 64 //EditUserPermissions Allows a user to edit permissions of another user EditUserPermissions UserPermission = 128 //BulkTagOperations BulkTagOperations UserPermission = 256 //ScoreImage Allows a user to vote on an image's score ScoreImage UserPermission = 512 //SourceImage Allows a user to change an image's source SourceImage UserPermission = 1024 //AddCollections Allows a user to add a new collection to the system (But not delete) AddCollections UserPermission = 2048 //ModifyCollections Allows a user to modify a collection in the system ModifyCollections UserPermission = 4096 //RemoveCollections Allows a user to remove a collection from the system RemoveCollections UserPermission = 8192 //ModifyCollectionMembers Allows a user to add and remove images to/from a collection, but not create or delete collections themselves ModifyCollectionMembers UserPermission = 16384 //APIWriteAccess grants a user access to the API for making changes. The user is still limited by their other permissions however. //Read access is generally given to authenticated users. APIWriteAccess UserPermission = 32768 //Add more permissions here as needed in future. Keep using powers of 2 for this to work. //Max number will be 18446744073709551615, after 64 possible permission assignments. ) //HasPermission checks the current permission set to see if it matches the provided permission func (Permission UserPermission) HasPermission(CheckPermission UserPermission) bool { return (Permission & CheckPermission) == CheckPermission }
interfaces/permissions.go
0.649245
0.428114
permissions.go
starcoder
package honu import ( "math" "math/rand" ) // BanditStrategy specifies the methods required by an algorithm to compute // multi-armed bandit probabilities for reinforcement learning. The basic // mechanism allows you to initialize a strategy with n arms (or n choices). // The Select() method will return a selected index based on the internal // strategy, and the Update() method allows external callers to update the // reward function for the selected arm. type BanditStrategy interface { Init(nArms int) // Initialize the bandit with n choices Select() int // Selects an arm and returns the index of the choice Update(arm int, reward float64) // Update the given arm with a reward Counts() []uint64 // The frequency of each arm being selected Values() []float64 // The reward distributions for each arm Serialize() interface{} // Return a JSON representation of the strategy } //=========================================================================== // Epsilon Greedy Multi-Armed Bandit //=========================================================================== // EpsilonGreedy implements a reinforcement learning strategy such that the // maximizing value is selected with probability epsilon and a uniform random // selection is made with probability 1-epsilon. type EpsilonGreedy struct { Epsilon float64 // Probability of selecting maximizing value counts []uint64 // Number of times each index was selected values []float64 // Reward values conditioned by frequency history *BanditHistory // History of reward values per iteration } // Init the bandit with nArms number of possible choices, which are referred // to by index in both the Counts and Values arrays. func (b *EpsilonGreedy) Init(nArms int) { b.counts = make([]uint64, nArms, nArms) b.values = make([]float64, nArms, nArms) b.history = NewBanditHistory() } // Select the arm with the maximizing value with probability epsilon, // otherwise uniform random selection of all arms with probability 1-epsilon. func (b *EpsilonGreedy) Select() int { if rand.Float64() > b.Epsilon { // Select the maximal value from values. max := -1.0 idx := -1 // Find the index of the maximal value. for i, val := range b.values { if val > max { max = val idx = i } } return idx } // Otherwise return any of the values return rand.Intn(len(b.values)) } // Update the selected arm with the reward so that the strategy can learn the // maximizing value (conditioned by the frequency of selection). func (b *EpsilonGreedy) Update(arm int, reward float64) { // Update the frequency b.counts[arm]++ n := float64(b.counts[arm]) value := b.values[arm] b.values[arm] = ((n-1)/n)*value + (1/n)*reward b.history.Update(arm, reward) } // Counts returns the frequency each arm was selected func (b *EpsilonGreedy) Counts() []uint64 { return b.counts } // Values returns the reward distribution of each arm func (b *EpsilonGreedy) Values() []float64 { return b.values } // Serialize the bandit strategy to dump to JSON. func (b *EpsilonGreedy) Serialize() interface{} { data := make(map[string]interface{}) data["strategy"] = "epsilon greedy" data["epsilon"] = b.Epsilon data["counts"] = b.counts data["values"] = b.values data["history"] = b.history return data } //=========================================================================== // Annealing Epsilon Greedy Multi-Armed Bandit //=========================================================================== // AnnealingEpsilonGreedy implements a reinforcement learning strategy such // that value of epsilon starts small then grows increasingly bigger, leading // to an exploring learning strategy at start and prefering exploitation as // more selections are made. type AnnealingEpsilonGreedy struct { counts []uint64 // Number of times each index was selected values []float64 // Reward values condition by frequency history *BanditHistory // History of reward values per iteration } // Init the bandit with nArms number of possible choices, which are referred // to by index in both the Counts and Values arrays. func (b *AnnealingEpsilonGreedy) Init(nArms int) { b.counts = make([]uint64, nArms, nArms) b.values = make([]float64, nArms, nArms) b.history = NewBanditHistory() } // Epsilon is computed by the current number of trials such that the more // trials have occured, the smaller epsilon is (on a log scale). func (b *AnnealingEpsilonGreedy) Epsilon() float64 { // Compute epsilon based on the total number of trials t := uint64(1) for _, i := range b.counts { t += i } // The more trials the smaller that epsilon is return 1 / math.Log(float64(t)+0.0000001) } // Select the arm with the maximizing value with probability epsilon, // otherwise uniform random selection of all arms with probability 1-epsilon. func (b *AnnealingEpsilonGreedy) Select() int { if rand.Float64() > b.Epsilon() { // Select the maximal value from values. max := -1.0 idx := -1 // Find the index of the maximal value. for i, val := range b.values { if val > max { max = val idx = i } } return idx } // Otherwise return any of the values return rand.Intn(len(b.values)) } // Update the selected arm with the reward so that the strategy can learn the // maximizing value (conditioned by the frequency of selection). func (b *AnnealingEpsilonGreedy) Update(arm int, reward float64) { // Update the frequency b.counts[arm]++ n := float64(b.counts[arm]) value := b.values[arm] b.values[arm] = ((n-1)/n)*value + (1/n)*reward b.history.Update(arm, reward) } // Counts returns the frequency each arm was selected func (b *AnnealingEpsilonGreedy) Counts() []uint64 { return b.counts } // Values returns the reward distribution of each arm func (b *AnnealingEpsilonGreedy) Values() []float64 { return b.values } // Serialize the bandit strategy to dump to JSON. func (b *AnnealingEpsilonGreedy) Serialize() interface{} { data := make(map[string]interface{}) data["strategy"] = "annealing epsilon greedy" data["epsilon"] = b.Epsilon() data["counts"] = b.counts data["values"] = b.values data["history"] = b.history return data } //=========================================================================== // Uniform strategy //=========================================================================== // Uniform selects all values with an equal likelihood on every selection. // While it tracks the frequency of selection and the reward costs, this // information does not affect the way it selects values. type Uniform struct { counts []uint64 // Number of times each index was selected values []float64 // Reward values condition by frequency history *BanditHistory // History of reward values per iteration } // Init the bandit with nArms number of possible choices, which are referred // to by index in both the Counts and Values arrays. func (b *Uniform) Init(nArms int) { b.counts = make([]uint64, nArms, nArms) b.values = make([]float64, nArms, nArms) b.history = NewBanditHistory() } // Select the arm with equal probability for each choice. func (b *Uniform) Select() int { return rand.Intn(len(b.values)) } // Update the selected arm with the reward so that the strategy can learn the // maximizing value (conditioned by the frequency of selection). func (b *Uniform) Update(arm int, reward float64) { // Update the frequency b.counts[arm]++ n := float64(b.counts[arm]) value := b.values[arm] b.values[arm] = ((n-1)/n)*value + (1/n)*reward b.history.Update(arm, reward) } // Counts returns the frequency each arm was selected func (b *Uniform) Counts() []uint64 { return b.counts } // Values returns the reward distribution of each arm func (b *Uniform) Values() []float64 { return b.values } // Serialize the bandit strategy to dump to JSON. func (b *Uniform) Serialize() interface{} { data := make(map[string]interface{}) data["strategy"] = "uniform selection" data["counts"] = b.counts data["values"] = b.values data["history"] = b.history return data } //=========================================================================== // Bandity History - For Experimentation //=========================================================================== // NewBanditHistory creates and returns a bandit history struct. func NewBanditHistory() *BanditHistory { history := new(BanditHistory) history.Arms = make([]int, 0, 10000) history.Rewards = make([]float64, 0, 10000) return history } // BanditHistory tracks the selected arms and their rewards over time. type BanditHistory struct { Arms []int `json:"arms"` // selected arms per iteration Rewards []float64 `json:"rewards"` // reward values per iteration } // Update the history func (h *BanditHistory) Update(arm int, reward float64) { h.Arms = append(h.Arms, arm) h.Rewards = append(h.Rewards, reward) }
bandit.go
0.868952
0.670494
bandit.go
starcoder
package utils import ( "fmt" "strconv" "strings" ) // GetIndexFromKey return an int index out of query part if possible func GetIndexFromKey(key string) (bool, bool, int, error) { before := false after := false key = strings.Replace(key, "[", "", -1) key = strings.Replace(key, "]", "", -1) if len(key) == 0 { return false, false, -1, fmt.Errorf("not valid") } if key[0] == ':' { after = true } else if key[len(key)-1] == ':' { before = true } key = strings.Replace(key, ":", "", -1) value, err := strconv.Atoi(key) return before, after, value, err } // SetArrayInDataTo set a new array value of data processing (on actual or previous pointer) func SetArrayInDataTo(data *interface{}, key string, previousData *interface{}, previousKey string, newData interface{}) error { if previousData != nil { if previousDataM, ok := (*previousData).(map[string]interface{}); ok { previousDataM[previousKey] = newData return nil } else if previousDataA, ok := (*previousData).([]interface{}); ok { if key == "[*]" { *previousData = newData return nil } _, _, index, err := GetIndexFromKey(key) if err != nil { return fmt.Errorf("index value of \"%s\", \"%v\" is not a number", key, index) } if index >= len(previousDataA) { return fmt.Errorf("index value \"%v\" is out of range", index) } previousDataA[index] = newData return nil } } else { *data = newData return nil } return fmt.Errorf("key \"%s\" not found", key) } // StringCaster try to create int, float etc. from string if possible func StringCaster(data string) interface{} { if c, err := strconv.Atoi(data); err == nil { return c } else if c, err := strconv.ParseBool(data); err == nil { return c } else if c, err := strconv.ParseFloat(data, 64); err == nil { return c } else if c, err := strconv.ParseInt(data, 10, 64); err == nil { return c } return data } // DataTypeIsJSON checks if given data type match json func DataTypeIsJSON(dataType string) bool { return dataType == "j" || dataType == "json" || dataType == "extension" } // DataTypeIsToml checks if given data type match toml func DataTypeIsToml(dataType string) bool { return dataType == "t" || dataType == "toml" } // DataTypeIsYaml checks if given data type match yaml func DataTypeIsYaml(dataType string) bool { return dataType == "y" || dataType == "yml" || dataType == "yaml" } // Min value of two int func Min(x int, y int) int { if x < y { return x } return y } // Max value of two int func Max(x int, y int) int { if x > y { return x } return y } type Dummy struct { internal interface{} } func CreateEmptyMap() *interface{} { data := Dummy{ internal: make(map[string]interface{}), } return &data.internal } func CreateInterfaceFromMap(m map[string]interface{}) *interface{} { data := Dummy{ internal: m, } return &data.internal } func CreateEmptyArray() *interface{} { data := Dummy{ internal: []interface{}{}, } return &data.internal } func CreateInterfaceFromArray(a []interface{}) *interface{} { data := Dummy{ internal: a, } return &data.internal }
utils/utils.go
0.597843
0.435541
utils.go
starcoder
package mod import ( "errors" "fmt" "io" "github.com/nsf/sexp" ) // Point2D represents a point in 2-dimensional space. type Point2D struct { X float64 `json:"x"` Y float64 `json:"y"` } // FpLine represents a graphical line. type FpLine struct { Start Point2D `json:"start"` End Point2D `json:"end"` Layer string `json:"layer"` Width float64 `json:"width"` } // FpCircle represents a graphical circle. type FpCircle struct { Center Point2D `json:"center"` End Point2D `json:"end"` Layer string `json:"layer"` Width float64 `json:"width"` } // FpArc represents a graphical arc. type FpArc struct { Start Point2D `json:"start"` End Point2D `json:"end"` Layer string `json:"layer"` Angle float64 `json:"angle"` Width float64 `json:"width"` } // FpPoly represents a graphical polygon. type FpPoly struct { At Point2D `json:"position"` Points []Point2D `json:"points"` Layer string `json:"layer"` Width float64 `json:"width"` } // FpText represents graphical text. type FpText struct { Pos Point2D `json:"position"` Kind string `json:"kind"` Value string `json:"value"` Layer string `json:"layer"` Hidden bool `json:"hidden"` Size Point2D `json:"size"` Thickness float64 `json:"thickness"` } // Pad represents a pad in a component footprint. type Pad struct { Pin int `json:"pin"` Kind string `json:"kind"` Shape string `json:"shape"` Drill Drill `json:"drill"` Pos Point2D `json:"position"` Size Point2D `json:"size"` Layers []string `json:"layers"` } // Drill represents pad drill parameters. type Drill struct { Kind string `json:"kind"` Scalar float64 `json:"scalar"` Ellipse Point2D `json:"ellipse"` Offset Point2D `json:"offset"` } // Module represents a Kicad module. type Module struct { Name string `json:"name"` Tedit string `json:"tedit"` Description string `json:"description"` Layer string `json:"layer"` Position Point2D `json:"position"` Clearance float64 `json:"clearance,omitempty"` Model string `json:"model"` SolderMaskMargin float64 `json:"solder_mask_margin,omitempty"` SolderPasteMargin float64 `json:"solder_paste_margin,omitempty"` SolderPasteRatio float64 `json:"solder_paste_ratio,omitempty"` Tags []string `json:"tags"` Attrs []string `json:"attrs"` Lines []FpLine `json:"lines"` Arcs []FpArc `json:"arcs"` Circles []FpCircle `json:"circles"` Polygons []FpPoly `json:"polygons"` Texts []FpText `json:"texts"` Pads []Pad `json:"pads"` } // DecodeModule reads a .kicad_mod file from a reader. func DecodeModule(r io.RuneReader) (*Module, error) { out := &Module{} ast, err := sexp.Parse(r, nil) if !ast.IsList() { return nil, errors.New("invalid format: expected s-expression list at top level") } if ast.NumChildren() != 1 { return nil, errors.New("invalid format: top level list of size 1") } mainAST, _ := ast.Nth(0) if !mainAST.IsList() { return nil, errors.New("invalid format: expected s-expression list at 1st level") } if mainAST.NumChildren() < 3 { return nil, errors.New("invalid format: missing minimum elements") } if s, err2 := sexp.Help(mainAST).Child(0).String(); err2 != nil || s != "module" { return nil, errors.New("invalid format: missing module prefix") } out.Name, err = sexp.Help(mainAST).Child(1).String() if err != nil { return nil, errors.New("invalid format: expected string value for module name") } for i := 2; i < mainAST.NumChildren(); i++ { n := sexp.Help(mainAST).Child(i) if n.IsList() && n.Child(1).IsValid() { switch n.Child(0).MustString() { case "zone_connect", "path", "autoplace_cost90", "autoplace_cost180": // ignore case "layer": out.Layer, err = n.Child(1).String() if err != nil { return nil, errors.New("invalid format: layer value must be a string") } case "tedit": out.Tedit, err = n.Child(1).String() if err != nil { return nil, errors.New("invalid format: tedit value must be a string") } case "descr": out.Description, err = n.Child(1).String() if err != nil { return nil, errors.New("invalid format: tedit value must be a string") } case "tags": for x := 1; x < n.MustNode().NumChildren(); x++ { var t string t, err = n.Child(1).String() if err != nil { return nil, errors.New("invalid format: tag value must be a string") } out.Tags = append(out.Tags, t) } case "attr": for x := 1; x < n.MustNode().NumChildren(); x++ { var t string t, err = n.Child(1).String() if err != nil { return nil, errors.New("invalid format: tag value must be a string") } out.Attrs = append(out.Attrs, t) } case "at": out.Position = Point2D{X: n.Child(1).MustFloat64(), Y: n.Child(2).MustFloat64()} case "clearance": out.Clearance = n.Child(1).MustFloat64() case "solder_mask_margin": out.SolderMaskMargin = n.Child(1).MustFloat64() case "solder_paste_margin": out.SolderPasteMargin = n.Child(1).MustFloat64() case "solder_paste_ratio": out.SolderPasteRatio = n.Child(1).MustFloat64() case "model": out.Model, err = n.Child(1).String() if err != nil { return nil, errors.New("invalid format: model value must be a string") } case "fp_line": line, err := unmarshalFpLine(n) if err != nil { return nil, err } out.Lines = append(out.Lines, line) case "fp_circle": c, err := unmarshalFpCircle(n) if err != nil { return nil, err } out.Circles = append(out.Circles, c) case "fp_arc": a, err := unmarshalFpArc(n) if err != nil { return nil, err } out.Arcs = append(out.Arcs, a) case "fp_poly": p, err := unmarshalFpPoly(n) if err != nil { return nil, err } out.Polygons = append(out.Polygons, p) case "fp_text": txt, err := unmarshalFpText(n) if err != nil { return nil, err } out.Texts = append(out.Texts, txt) case "pad": pad, err := unmarshalPad(n) if err != nil { return nil, err } out.Pads = append(out.Pads, pad) default: return nil, errors.New("cannot handle expression: " + n.Child(0).MustString()) } } } return out, nil } func unmarshalFpArc(n sexp.Helper) (FpArc, error) { arc := FpArc{} for x := 1; x < n.MustNode().NumChildren(); x++ { switch n.Child(x).Child(0).MustString() { case "start": arc.Start = Point2D{X: n.Child(x).Child(1).MustFloat64(), Y: n.Child(x).Child(2).MustFloat64()} case "end": arc.End = Point2D{X: n.Child(x).Child(1).MustFloat64(), Y: n.Child(x).Child(2).MustFloat64()} case "layer": arc.Layer = n.Child(x).Child(1).MustString() case "width": arc.Width = n.Child(x).Child(1).MustFloat64() case "angle": arc.Angle = n.Child(x).Child(1).MustFloat64() } } return arc, nil } func unmarshalFpCircle(n sexp.Helper) (FpCircle, error) { circle := FpCircle{} for x := 1; x < n.MustNode().NumChildren(); x++ { switch n.Child(x).Child(0).MustString() { case "center": circle.Center = Point2D{X: n.Child(x).Child(1).MustFloat64(), Y: n.Child(x).Child(2).MustFloat64()} case "end": circle.End = Point2D{X: n.Child(x).Child(1).MustFloat64(), Y: n.Child(x).Child(2).MustFloat64()} case "layer": circle.Layer = n.Child(x).Child(1).MustString() case "width": circle.Width = n.Child(x).Child(1).MustFloat64() } } return circle, nil } func unmarshalFpPoly(n sexp.Helper) (FpPoly, error) { p := FpPoly{} for x := 1; x < n.MustNode().NumChildren(); x++ { switch n.Child(x).Child(0).MustString() { case "at": p.At = Point2D{X: n.Child(x).Child(1).MustFloat64(), Y: n.Child(x).Child(2).MustFloat64()} case "pts": for i := 1; i < n.Child(x).MustNode().NumChildren(); i++ { if n.Child(x).Child(i).Child(0).MustString() == "xy" { p.Points = append(p.Points, Point2D{X: n.Child(x).Child(i).Child(1).MustFloat64(), Y: n.Child(x).Child(i).Child(2).MustFloat64()}) } else { return FpPoly{}, fmt.Errorf("cannot handle expression of type %q in fp_poly.pts stanza", n.Child(x).Child(i).Child(0).MustString()) } } case "layer": p.Layer = n.Child(x).Child(1).MustString() case "width": p.Width = n.Child(x).Child(1).MustFloat64() } } return p, nil } func unmarshalFpLine(n sexp.Helper) (FpLine, error) { line := FpLine{} for x := 1; x < n.MustNode().NumChildren(); x++ { switch n.Child(x).Child(0).MustString() { case "start": line.Start = Point2D{X: n.Child(x).Child(1).MustFloat64(), Y: n.Child(x).Child(2).MustFloat64()} case "end": line.End = Point2D{X: n.Child(x).Child(1).MustFloat64(), Y: n.Child(x).Child(2).MustFloat64()} case "layer": line.Layer = n.Child(x).Child(1).MustString() case "width": line.Width = n.Child(x).Child(1).MustFloat64() } } return line, nil } func unmarshalFpText(n sexp.Helper) (FpText, error) { txt := FpText{ Kind: n.Child(1).MustString(), Value: n.Child(2).MustString(), } for x := 3; x < n.MustNode().NumChildren(); x++ { if n.Child(x).IsScalar() { if s, err := n.Child(x).String(); err == nil { switch s { case "hide": txt.Hidden = true } continue } } switch n.Child(x).Child(0).MustString() { case "at": txt.Pos = Point2D{X: n.Child(x).Child(1).MustFloat64(), Y: n.Child(x).Child(2).MustFloat64()} case "layer": txt.Layer = n.Child(x).Child(1).MustString() case "effects": s := n.Child(x).Child(1) for i := 1; i < s.MustNode().NumChildren(); i++ { if !s.Child(i).Child(0).IsScalar() { continue } switch s.Child(i).Child(0).MustString() { case "size": txt.Size = Point2D{X: s.Child(i).Child(1).MustFloat64(), Y: s.Child(i).Child(2).MustFloat64()} case "thickness": txt.Thickness = s.Child(i).Child(1).MustFloat64() } } } } return txt, nil } func decodeDrill(n sexp.Helper) (Drill, error) { d := Drill{} for x := 1; x < n.MustNode().NumChildren(); x++ { if n.Child(x).IsList() { switch n.Child(x).Child(0).MustString() { case "offset": d.Offset = Point2D{X: n.Child(x).Child(1).MustFloat64(), Y: n.Child(x).Child(2).MustFloat64()} } } else { if _, err := n.Child(x).Float64(); err != nil { // kind + 2d parameters d.Kind = n.Child(x).MustString() d.Ellipse = Point2D{X: n.Child(x + 1).MustFloat64(), Y: n.Child(x + 2).MustFloat64()} x += 2 return d, nil } else { // just a scalar (radius) d.Scalar = n.Child(1).MustFloat64() } } } return d, nil } func unmarshalPad(n sexp.Helper) (Pad, error) { var err error pad := Pad{ Kind: n.Child(2).MustString(), Shape: n.Child(3).MustString(), } if v, err := n.Child(1).Int(); err == nil { // Pads without an int pin are just disconnected ones pad.Pin = v } for x := 4; x < n.MustNode().NumChildren(); x++ { switch n.Child(x).Child(0).MustString() { case "at": pad.Pos = Point2D{X: n.Child(x).Child(1).MustFloat64(), Y: n.Child(x).Child(2).MustFloat64()} case "size": pad.Size = Point2D{X: n.Child(x).Child(1).MustFloat64(), Y: n.Child(x).Child(2).MustFloat64()} case "drill": pad.Drill, err = decodeDrill(n.Child(x)) if err != nil { return pad, err } case "layers": s := n.Child(x) for i := 1; i < s.MustNode().NumChildren(); i++ { pad.Layers = append(pad.Layers, s.Child(i).MustString()) } } } return pad, nil }
src/kcdb/mod/modDecoder.go
0.757166
0.400691
modDecoder.go
starcoder
package af import ( "reflect" ) // Definition is a struct containing a function definition type Definition struct { Inputs []interface{} // an array of types or kinds Output interface{} // the type or kind returned by the defined function } // IsBoolean returns true if the definition returns a boolean value. func (d Definition) IsBoolean() bool { if k, ok := d.Output.(reflect.Kind); ok { if k == reflect.Bool { return true } } return false } // IsInteger returns true if the definition returns an integer value. func (d Definition) IsInteger() bool { if k, ok := d.Output.(reflect.Kind); ok { if k == reflect.Int || k == reflect.Int8 || k == reflect.Int16 || k == reflect.Int32 || k == reflect.Int64 || k == reflect.Uint || k == reflect.Uint8 || k == reflect.Uint16 || k == reflect.Uint32 || k == reflect.Uint64 { return true } } return false } // IsFloat returns true if the definition returns a floating point number value. func (d Definition) IsFloat() bool { if k, ok := d.Output.(reflect.Kind); ok { if k == reflect.Float32 || k == reflect.Float64 { return true } } return false } // IsNumber returns true if the definition returns a numeric value. func (d Definition) IsNumber() bool { return d.IsInteger() || d.IsFloat() } // IsString returns true if the definition returns a string value. func (d Definition) IsString() bool { if k, ok := d.Output.(reflect.Kind); ok { if k == reflect.String { return true } } return false } // IsValid returns true if the args match the kinds or types or the definition. func (d Definition) IsValid(args ...interface{}) bool { if d.Inputs == nil { return true } if len(args) != len(d.Inputs) { return false } for i, a := range args { switch x := d.Inputs[i].(type) { case reflect.Type: xv := reflect.ValueOf(x) av := reflect.ValueOf(a) if !xv.IsNil() { if !av.IsValid() { return false } if ak := reflect.TypeOf(a).Kind(); (ak == reflect.Chan || ak == reflect.Func || ak == reflect.Map || ak == reflect.Ptr || ak == reflect.Slice) && av.IsNil() { return false } if !av.Type().AssignableTo(x) { return false } } case reflect.Kind: xv := reflect.ValueOf(x) av := reflect.ValueOf(a) if xv.IsValid() || !xv.IsNil() { if !av.IsValid() { return false } if xv.IsValid() && av.Type().Kind() != x { return false } } } } return true }
pkg/af/Definition.go
0.690872
0.428652
Definition.go
starcoder
package stats import ( "fmt" "sort" "sync" ) type rootScope struct { c Collector sync.Mutex counters map[string]*atomicInt64Vector gauges map[string]*atomicInt64Vector histograms map[string]*histogramVector } func RootScope(c Collector) Scope { return scopeWrapper{ &rootScope{ c: c, counters: make(map[string]*atomicInt64Vector), gauges: make(map[string]*atomicInt64Vector), histograms: make(map[string]*histogramVector), }, } } func (rs *rootScope) assertMetricUniqueness(n string) { if _, ok := rs.counters[n]; ok { panic(fmt.Sprintf("counter with the same name already registered: %q", n)) } if _, ok := rs.gauges[n]; ok { panic(fmt.Sprintf("gauge with the same name already registered: %q", n)) } if _, ok := rs.histograms[n]; ok { panic(fmt.Sprintf("hisogram with the same name already registered: %q", n)) } } type labelOrderer interface { order([]string) []string } type mappingLabelOdrderer struct { mapping map[int]int } func (mlo mappingLabelOdrderer) order(in []string) []string { if len(mlo.mapping) != len(in) { panic("wrong number of labels passed") } var out = make([]string, len(in)) for i, v := range in { out[mlo.mapping[i]] = v } return out } func buildLabelOrderer(base, target []string) labelOrderer { if len(base) != len(target) { panic("Another metric is already created with different number of label") } var ( baseCopy = append(base[:0:0], base...) targetCopy = append(target[:0:0], target...) ) sort.Sort(sort.StringSlice(baseCopy)) sort.Sort(sort.StringSlice(targetCopy)) for i, bv := range baseCopy { if targetCopy[i] != bv { panic("Another metric is already created with different label") } } var transferMap = make(map[int]int, len(base)) for i, tv := range target { for j, bv := range base { if tv == bv { transferMap[i] = j break } } } return mappingLabelOdrderer{mapping: transferMap} } func (rs *rootScope) registerHistogram(n string, ls []string, opts ...HistogramOption) HistogramVector { rs.Lock() defer rs.Unlock() if h, ok := rs.histograms[n]; ok { // TODO: ensure the cutoffs are similare or panic return reorderHistogramVector{ hv: h, labelOrderer: buildLabelOrderer(h.labels, ls), } } rs.assertMetricUniqueness(n) v := &histogramVector{ cutoffs: defaultCutoffs, labels: ls, hs: map[uint64]*histogram{}, marshaler: newDefaultMarshaler(), } for _, opt := range opts { opt(v) } rs.histograms[n] = v rs.c.RegisterHistogram(n, v) return v } func (rs *rootScope) registerGauge(n string, ls []string) GaugeVector { rs.Lock() defer rs.Unlock() if c, ok := rs.gauges[n]; ok { return reorderGaugeVector{ gv: gaugeVector{c}, labelOrderer: buildLabelOrderer(c.labels, ls), } } rs.assertMetricUniqueness(n) v := &atomicInt64Vector{ labels: ls, cs: make(map[uint64]*atomicInt64), marshaler: newDefaultMarshaler(), } rs.gauges[n] = v rs.c.RegisterGauge(n, v) return gaugeVector{v} } func (rs *rootScope) registerCounter(n string, ls []string) CounterVector { rs.Lock() defer rs.Unlock() if c, ok := rs.counters[n]; ok { return reorderCounterVector{ cv: counterVector{c}, labelOrderer: buildLabelOrderer(c.labels, ls), } } rs.assertMetricUniqueness(n) v := &atomicInt64Vector{ labels: ls, cs: make(map[uint64]*atomicInt64), marshaler: newDefaultMarshaler(), } rs.counters[n] = v rs.c.RegisterCounter(n, v) return counterVector{v} } func (*rootScope) namespace() string { return "" } func (*rootScope) tags() map[string]string { return nil } func (rs *rootScope) rootScope() *rootScope { return rs }
vendor/github.com/upfluence/stats/root_scope.go
0.534127
0.577674
root_scope.go
starcoder
package main import( "fmt" "strconv" ) // Thought about big-O for here and figured it's all ∈ O(1) since they all take only a single input // value and the value of that input has no real effect on the number of operations - except // PopCountSmartShift, but even there the max n of 64 is negligible. // pc[i] is population count of i - we only need 8 bit numbers since larger numbers can be broken // down into 8x8-bit chunks w/o affecting the number of non-zero bits. var pc [256]byte func init() { // Multiply by 2 shifts all bits to the left by one, not affecting the amount of non-zero bits. // For every odd number, the last bit is `1` so we add one to the population count. // In reverse: number of non-zero bits for `i` is the same as for `i/2` with one added for odd // numbers. (i&1 means 'apply bitmask 1', i.e. get value of the rightmost bit) for i := range pc { pc[i] = pc[i/2] + byte(i&1) } } func PopCountExp(num uint64) uint8 { // Cast `byte(num>>n)` has similar effect as `num>>n&&255` - cuts off all bits left of the last // 8 binary digits. This only works if num is a variable, if it'd be a constant the code wouldn't // compile res := pc[byte(num>>(0*8))] + pc[byte(num>>(1*8))] + pc[byte(num>>(2*8))] + pc[byte(num>>(3*8))] + pc[byte(num>>(4*8))] + pc[byte(num>>(5*8))] + pc[byte(num>>(6*8))] + pc[byte(num>>(7*8))] return res } // Same as PopCountExp but using a loop instead. Looks more elegant (dynamic, yeah) but is slower // than PopCountExp. Apparently little point in having a loop if the size is fixed. func PopCountLoop(num uint64) uint8 { var i, res uint8 for i = 0; i < 8; i++ { res += pc[byte(num>>(i*8))] } return res } // Shifts through each bit of the input, adds up non-zero bit. Always needs 64 operations. This is // obviously the slowest approach. func PopCountShift(num uint64) uint8 { var cnt uint8 for ; num > 0; num = num >> 1 { cnt += byte(num & 1) } return cnt } // Taking advantage of x&(x-1) clearing the rightmost non-zero bit. Needs 64 ops at max. Faster // then PopCountShift but still slower than PopCountExp and PopCountLoop func PopCountSmartShift(num uint64) uint8 { var cnt uint8 for x := num; x > 0; x = x&(x-1) { cnt++ } return cnt } func printPopCount(num uint64) { fmt.Printf("%s: %v\n", strconv.FormatInt(int64(num), 2), PopCountExp(num)) } func main() { printPopCount(16) printPopCount(25) printPopCount(2413) printPopCount(412353451) }
ch02/popcount/popcount.go
0.538255
0.476092
popcount.go
starcoder
package corner import "math" // Rose generates a set of n evenly-spaced Directions func Rose(n int, offset float64) []Direction { dirs := make([]Direction, n) if offset == 0 { // special cases north := rectDirection{0, -1} south := rectDirection{0, 1} east := rectDirection{1, 0} west := rectDirection{-1, 0} if n == 1 { dirs[0] = north return dirs } if n == 2 { dirs[0] = north dirs[1] = south return dirs } if n == 4 { dirs[0] = north dirs[1] = east dirs[2] = south dirs[3] = west return dirs } if n == 8 { dirs[0] = north dirs[1] = rectDirection{1, -1} dirs[2] = east dirs[3] = rectDirection{1, 1} dirs[4] = south dirs[5] = rectDirection{-1, 1} dirs[6] = west dirs[7] = rectDirection{-1, -1} return dirs } } // general case alpha := 2 * math.Pi / float64(n) for i := range dirs { dirs[i] = thetaDirection{float64(i)*alpha + offset} } return dirs } // A Direction is a representation of a direction in 2-d space type Direction interface { Angle() float64 Minus(Direction) float64 Basis(float64, float64, Point) Point Cos() float64 Sin() float64 Equal(Direction) bool Normal() Direction } type thetaDirection struct { theta float64 } func modTau(theta float64) float64 { thetaMod := math.Mod(theta, 2*math.Pi) if thetaMod < 0 { return thetaMod + 2*math.Pi } return thetaMod } func newThetaDirection(theta float64) thetaDirection { return thetaDirection{modTau(theta)} } func (d thetaDirection) Minus(other Direction) float64 { return modTau(d.theta - other.Angle()) } func (d thetaDirection) Angle() float64 { return d.theta } func (d thetaDirection) Cos() float64 { return math.Cos(d.theta) } func (d thetaDirection) Sin() float64 { return math.Sin(d.theta) } func (d thetaDirection) Basis(u, v float64, o Point) Point { c := d.Cos() s := d.Sin() return Point{o.X + u*c - v*s, o.Y + u*s + v*c} } func (d thetaDirection) Equal(other Direction) bool { return d.theta == other.Angle() } func (d thetaDirection) Normal() Direction { return newThetaDirection(d.theta + math.Pi/2) } type rectDirection struct { x float64 y float64 } func (d rectDirection) Minus(other Direction) float64 { switch other := other.(type) { case rectDirection: dot := d.x*other.x + d.y*other.y cross := d.x*other.y - d.y*other.x return modTau(math.Atan2(-cross, dot)) default: return modTau(d.Angle() - other.Angle()) } } func (d rectDirection) r() float64 { return math.Sqrt(d.x*d.x + d.y*d.y) } func (d rectDirection) Cos() float64 { return d.x / d.r() } func (d rectDirection) Sin() float64 { return d.y / d.r() } func (d rectDirection) Angle() float64 { return math.Atan2(d.y, d.x) } func (d rectDirection) Basis(u, v float64, o Point) Point { return Point{o.X + (u*d.x-v*d.y)/d.r(), o.Y + (u*d.y+v*d.x)/d.r()} } func (d rectDirection) Equal(other Direction) bool { switch other := other.(type) { case rectDirection: return d.x*other.y == d.y*other.x default: return d.Angle() == other.Angle() } } func (d rectDirection) Normal() Direction { return rectDirection{-d.y, d.x} }
corner/direction.go
0.821796
0.509825
direction.go
starcoder
package big_polynomial import ( "math/big" "github.com/PaddlePaddle/PaddleDTX/crypto/common/math/rand" ) type PolynomialClient struct { // A big prime which is used for Galois Field computing prime *big.Int } // New new PolynomialClient with a prime func New(prime *big.Int) *PolynomialClient { pc := new(PolynomialClient) pc.prime = prime return pc } // RandomGenerate make a random polynomials F(x) of Degree [degree], and the const(X-Intercept) is [intercept] // 给定最高次方和x截距,生成一个系数随机的多项式 func (pc *PolynomialClient) RandomGenerate(degree int, secret []byte) ([]*big.Int, error) { // 字节数组转big int intercept := big.NewInt(0).SetBytes(secret) // 多项式参数格式是次方数+1(代表常数) result := make([]*big.Int, degree+1) // 多项式的常数项就是x截距 // 多个bytes组成一个bigint,作为多项式的系数 coefficientFactor := 32 index := 0 result[index] = intercept // 生成非最高次方位的随机参数 if degree > 1 { randomBytes, err := rand.GenerateSeedWithStrengthAndKeyLen(rand.KeyStrengthHard, coefficientFactor*(degree-1)) if err != nil { return nil, err } for i := 0; i < len(randomBytes); i += coefficientFactor { byteSlice := randomBytes[i : i+coefficientFactor] result[index+1] = big.NewInt(0).SetBytes(byteSlice) index++ } } // This coefficient can't be zero, otherwise it will be a polynomial, // the degree of which is [degree-1] other than [degree] // 生成最高次方位的随机参数,该值不能为0,否则最高次方会退化为次一级 for { randomBytes, err := rand.GenerateSeedWithStrengthAndKeyLen(rand.KeyStrengthHard, coefficientFactor) if err != nil { return nil, err } highestDegreeCoefficient := big.NewInt(0).SetBytes(randomBytes) if highestDegreeCoefficient != big.NewInt(0) { result[degree] = highestDegreeCoefficient return result, nil } } } // Evaluate Given the specified value, get the compution result of the polynomial // 给出指定x值,计算出指定多项式f(x)的值 func (pc *PolynomialClient) Evaluate(polynomialCoefficients []*big.Int, specifiedValue *big.Int) *big.Int { degree := len(polynomialCoefficients) - 1 // 注意这里要用set,否则会出现上层业务逻辑的指针重复使用的问题 result := big.NewInt(0).Set(polynomialCoefficients[degree]) for i := degree - 1; i >= 0; i-- { result = result.Mul(result, specifiedValue) result = result.Add(result, polynomialCoefficients[i]) } return result } // Add 对2个多项式进行加法操作 func (pc *PolynomialClient) Add(a []*big.Int, b []*big.Int) []*big.Int { degree := len(a) c := make([]*big.Int, degree) // 初始化big int数组 for i := range c { c[i] = big.NewInt(0) } for i := 0; i < degree; i++ { c[i] = a[i].Add(a[i], b[i]) c[i] = big.NewInt(0).Mod(c[i], pc.prime) } return c } // Multiply 对2个多项式进行乘法操作 func (pc *PolynomialClient) Multiply(a []*big.Int, b []*big.Int) []*big.Int { degA := len(a) degB := len(b) result := make([]*big.Int, degA+degB-1) // 初始化big int数组 for i := range result { result[i] = big.NewInt(0) } for i := 0; i < degA; i++ { for j := 0; j < degB; j++ { temp := a[i].Mul(a[i], b[j]) result[i+j] = result[i+j].Add(result[i+j], temp) } } return result } // Scale 将1个多项式与指定系数k进行乘法操作 func (pc *PolynomialClient) Scale(a []*big.Int, k *big.Int) []*big.Int { b := make([]*big.Int, len(a)) for i := 0; i < len(a); i++ { b[i] = a[i].Mul(a[i], k) b[i] = big.NewInt(0).Mod(b[i], pc.prime) } return b } // GetLagrangeBasePolynomial 获取拉格朗日基本多项式(插值基函数) func (pc *PolynomialClient) GetLagrangeBasePolynomial(xs []*big.Int, xpos int) []*big.Int { var poly []*big.Int poly = append(poly, big.NewInt(1)) denominator := big.NewInt(1) for i := 0; i < len(xs); i++ { if i != xpos { currentTerm := make([]*big.Int, 2) currentTerm[0] = big.NewInt(1) currentTerm[1] = big.NewInt(0).Sub(big.NewInt(0), xs[i]) denominator = denominator.Mul(denominator, big.NewInt(0).Sub(xs[xpos], xs[i])) poly = pc.Multiply(poly, currentTerm) } } inverser := big.NewInt(0).ModInverse(denominator, pc.prime) return pc.Scale(poly, inverser) } // GetPolynomialByPoints 利用Lagrange Polynomial Interpolation Formula,通过给定坐标点集合来计算多项式 func (pc *PolynomialClient) GetPolynomialByPoints(points map[int]*big.Int) []*big.Int { degree := len(points) bases := make([][]*big.Int, degree) result := make([]*big.Int, degree) for i := range result { result[i] = big.NewInt(0) } var xs []*big.Int var ys []*big.Int for k, v := range points { xs = append(xs, big.NewInt(int64(k))) ys = append(ys, v) } for i := 0; i < degree; i++ { bases[i] = pc.GetLagrangeBasePolynomial(xs, i) } for i := 0; i < degree; i++ { result = pc.Add(result, pc.Scale(bases[i], ys[i])) } return result }
crypto/common/math/big_polynomial/polynomial.go
0.622574
0.542136
polynomial.go
starcoder
package main import ( "github.com/go-gl/gl/v4.1-core/gl" ) // ShaderData Maps shader data type ShaderData struct { VertexAttributes uint32 NormalAttributes uint32 VertexTextureCoords uint32 } // InstanceShader Stores shader data var InstanceShader ShaderData // ShaderVertex Defines code for vertex shader var ShaderVertex = ` #version 330 uniform mat4 projectionUniform; uniform mat4 cameraUniform; uniform mat4 modelUniform; uniform mat3 normalUniform; uniform vec3 pointLightingLocationUniform; uniform vec3 pointLightingColorUniform; uniform int isLightEmitterUniform; in vec3 vertexAttributes; in vec3 vertexNormalAttributes; in vec2 vertexTextureCoords; out vec3 N; out vec2 shaderTextureCoords; out vec3 vertexLighting; void main() { vec4 modelViewPosition = modelUniform * vec4(vertexAttributes, 1); gl_Position = projectionUniform * cameraUniform * modelViewPosition; shaderTextureCoords = vertexTextureCoords; // Process lighting if (isLightEmitterUniform == 1) { // Light emitter vec3 lightDirection = normalize(pointLightingLocationUniform - modelViewPosition.xyz); vec3 transformedNormal = normalUniform * vertexNormalAttributes; float directionalLighting = max(dot(transformedNormal, lightDirection), 0.0); vertexLighting = pointLightingColorUniform * directionalLighting; } else { // Light receiver vertexLighting = vec3(1.0, 1.0, 1.0); } } ` + "\x00" // ShaderFragment Defines code for fragment shader var ShaderFragment = ` #version 330 uniform sampler2D textureUniform; uniform int isLightReceiverUniform; in vec2 shaderTextureCoords; in vec3 vertexLighting; out vec4 objectColor; void main() { vec4 objectColorTexture = texture(textureUniform, shaderTextureCoords); // Apply lighting to pixel if (isLightReceiverUniform == 1) { objectColor = vec4(objectColorTexture.rgb * vertexLighting, objectColorTexture.a); } else { objectColor = objectColorTexture; } } ` + "\x00" func getShader() (*ShaderData) { return &InstanceShader } func initializeShaders(program uint32) { shader := getShader() // Bind buffer to shaders attributes shader.VertexAttributes = uint32(gl.GetAttribLocation(program, gl.Str("vertexAttributes\x00"))) gl.EnableVertexAttribArray(shader.VertexAttributes) shader.NormalAttributes = uint32(gl.GetAttribLocation(program, gl.Str("vertexNormalAttributes\x00"))) gl.EnableVertexAttribArray(shader.NormalAttributes) shader.VertexTextureCoords = uint32(gl.GetAttribLocation(program, gl.Str("vertexTextureCoords\x00"))) gl.EnableVertexAttribArray(shader.VertexTextureCoords) // Bind misc. shaders uniforms setLightUniforms(program) setMatrixUniforms(program) }
shader.go
0.760384
0.416441
shader.go
starcoder
package schemax import "sync" /* MatchingRuleUseCollection describes all MatchingRuleUses-based types. */ type MatchingRuleUseCollection interface { // Get returns the *MatchingRuleUse instance retrieved as a result // of a term search, based on Name or OID. If no match is found, // nil is returned. Get(interface{}) *MatchingRuleUse // Index returns the *MatchingRuleUse instance stored at the nth // index within the receiver, or nil. Index(int) *MatchingRuleUse // Equal performs a deep-equal between the receiver and the // interface MatchingRuleUseCollection provided. Equal(MatchingRuleUseCollection) bool // Set returns an error instance based on an attempt to add // the provided *MatchingRuleUse instance to the receiver. Set(*MatchingRuleUse) error // Refresh will update the collection of MatchingRuleUse // instances based on the contents of the provided instance // of AttributeTypeCollection. Refresh(AttributeTypeCollection) error // Contains returns the index number and presence boolean that // reflects the result of a term search within the receiver. Contains(interface{}) (int, bool) // String returns a properly-delimited sequence of string // values, either as a Name or OID, for the receiver type. String() string // Label returns the field name associated with the interface // types, or a zero string if no label is appropriate. Label() string // IsZero returns a boolean value indicative of whether the // receiver is considered zero, or undefined. IsZero() bool // Len returns an integer value indicative of the current // number of elements stored within the receiver. Len() int // SetSpecifier assigns a string value to all definitions within // the receiver. This value is used in cases where a definition // type name (e.g.: attributetype, objectclass, etc.) is required. // This value will be displayed at the beginning of the definition // value during the unmarshal or unsafe stringification process. SetSpecifier(string) // SetUnmarshaler assigns the provided DefinitionUnmarshaler // signature to all definitions within the receiver. The provided // function shall be executed during the unmarshal or unsafe // stringification process. SetUnmarshaler(DefinitionUnmarshaler) } /* MatchingRuleUse conforms to the specifications of RFC4512 Section 4.1.4. Boolean values, e.g: 'OBSOLETE', are supported internally and are not explicit fields. */ type MatchingRuleUse struct { OID OID Name Name Description Description Applies AttributeTypeCollection Extensions Extensions flags definitionFlags ufn DefinitionUnmarshaler spec string info []byte } /* MatchingRuleUses is a thread-safe collection of *MatchingRuleUse slice instances. */ type MatchingRuleUses struct { mutex *sync.Mutex slice collection } /* Type returns the formal name of the receiver in order to satisfy signature requirements of the Definition interface type. */ func (r *MatchingRuleUse) Type() string { return `MatchingRuleUse` } /* Equal performs a deep-equal between the receiver and the provided collection type. */ func (r MatchingRuleUses) Equal(x MatchingRuleUseCollection) bool { return r.slice.equal(x.(*MatchingRuleUses).slice) } /* SetSpecifier is a convenience method that executes the SetSpecifier method in iterative fashion for all definitions within the receiver. */ func (r *MatchingRuleUses) SetSpecifier(spec string) { for i := 0; i < r.Len(); i++ { r.Index(i).SetSpecifier(spec) } } /* SetUnmarshaler is a convenience method that executes the SetUnmarshaler method in iterative fashion for all definitions within the receiver. */ func (r *MatchingRuleUses) SetUnmarshaler(fn DefinitionUnmarshaler) { for i := 0; i < r.Len(); i++ { r.Index(i).SetUnmarshaler(fn) } } /* Contains is a thread-safe method that returns a collection slice element index integer and a presence-indicative boolean value based on a term search conducted within the receiver. */ func (r MatchingRuleUses) Contains(x interface{}) (int, bool) { r.mutex.Lock() defer r.mutex.Unlock() return r.slice.contains(x) } /* Index is a thread-safe method that returns the nth collection slice element if defined, else nil. This method supports use of negative indices which should be used with special care. */ func (r MatchingRuleUses) Index(idx int) *MatchingRuleUse { r.mutex.Lock() defer r.mutex.Unlock() assert, _ := r.slice.index(idx).(*MatchingRuleUse) return assert } /* Get combines Contains and Index method executions to return an entry based on a term search conducted within the receiver. */ func (r MatchingRuleUses) Get(x interface{}) *MatchingRuleUse { idx, found := r.Contains(x) if !found { return nil } return r.Index(idx) } /* Len is a thread-safe method that returns the effective length of the receiver slice collection. */ func (r MatchingRuleUses) Len() int { r.mutex.Lock() defer r.mutex.Unlock() return r.slice.len() } /* String is a non-functional stringer method needed to satisfy interface type requirements and should not be used. There is no practical application for a list of matchingRuleUse names or object identifiers in this package. */ func (r MatchingRuleUses) String() string { return `` } /* String is an unsafe convenience wrapper for Unmarshal(r). If an error is encountered, an empty string definition is returned. If reliability and error handling are important, use Unmarshal. */ func (r MatchingRuleUse) String() (def string) { def, _ = r.unmarshal() return } /* SetSpecifier assigns a string value to the receiver, useful for placement into configurations that require a type name (e.g.: matchingruleuse). This will be displayed at the beginning of the definition value during the unmarshal or unsafe stringification process. */ func (r *MatchingRuleUse) SetSpecifier(spec string) { r.spec = spec } /* IsZero returns a boolean value indicative of whether the receiver is considered empty or uninitialized. */ func (r MatchingRuleUses) IsZero() bool { return r.slice.len() == 0 } /* IsZero returns a boolean value indicative of whether the receiver is considered empty or uninitialized. */ func (r *MatchingRuleUse) IsZero() bool { return r == nil } /* Set is a thread-safe append method that returns an error instance indicative of whether the append operation failed in some manner. Uniqueness is enforced for new elements based on Object Identifier and not the effective Name of the definition, if defined. */ func (r *MatchingRuleUses) Set(x *MatchingRuleUse) error { if _, exists := r.Contains(x.OID); exists { return nil //silent } r.mutex.Lock() defer r.mutex.Unlock() return r.slice.append(x) } /* Refresh accepts an AttributeTypeCollection which will be processed and used to create new, or update existing, *MatchingRuleUse instances within the receiver. */ func (r *MatchingRuleUses) Refresh(atc AttributeTypeCollection) (err error) { if atc.IsZero() { err = raise(noContent, "%T is nil", atc) return } createOrAppend := func(o OID, n Name, at *AttributeType) error { // If the definition exists already, save the index number. // If not found, handle it properly. idx, found := r.Contains(o) if !found { // Create an empty definition // to start with. r.Set(&MatchingRuleUse{ OID: o, Name: n, Applies: NewApplicableAttributeTypes(), }) // Make sure it actually got added idx, found = r.Contains(o) if !found { return raise(invalidMatchingRuleUse, "Attempt to register %s within %T failed for reasons unknown", o, r) } } // Append attributeType to receiver. Any definitions // already present as APPLIES values are silently // ignored. if e := r.Index(idx).Applies.Set(at); e != nil { return e } return nil } for i := 0; i < atc.Len(); i++ { a := atc.Index(i) if a.IsZero() { continue } if !a.Equality.IsZero() { if err = createOrAppend(a.Equality.OID, a.Equality.Name, a); err != nil { return } } if !a.Substring.IsZero() { if err = createOrAppend(a.Substring.OID, a.Substring.Name, a); err != nil { return } } if !a.Ordering.IsZero() { if err = createOrAppend(a.Ordering.OID, a.Ordering.Name, a); err != nil { return } } } return } /* SetInfo assigns the byte slice to the receiver. This is a user-leveraged field intended to allow arbitrary information (documentation?) to be assigned to the definition. */ func (r *MatchingRuleUse) SetInfo(info []byte) { r.info = info } /* Info returns the assigned informational byte slice instance stored within the receiver. */ func (r *MatchingRuleUse) Info() []byte { return r.info } /* SetUnmarshaler assigns the provided DefinitionUnmarshaler signature value to the receiver. The provided function shall be executed during the unmarshal or unsafe stringification process. */ func (r *MatchingRuleUse) SetUnmarshaler(fn DefinitionUnmarshaler) { r.ufn = fn } /* Equal performs a deep-equal between the receiver and the provided collection type. Description text is ignored. */ func (r *MatchingRuleUse) Equal(x interface{}) (equals bool) { z, ok := x.(MatchingRuleUse) if !ok { return } if z.IsZero() && r.IsZero() { equals = true return } else if z.IsZero() || r.IsZero() { return } if !z.OID.Equal(r.OID) { return } if !z.Name.Equal(r.Name) { return } if z.flags != r.flags { return } if !z.Applies.Equal(r.Applies) { return } equals = r.Extensions.Equal(z.Extensions) return } /* NewMatchingRuleUses initializes and returns a new MatchingRuleUsesCollection interface object. */ func NewMatchingRuleUses() MatchingRuleUseCollection { var x interface{} = &MatchingRuleUses{ mutex: &sync.Mutex{}, slice: make(collection, 0, 0), } return x.(MatchingRuleUseCollection) } /* is returns a boolean value indicative of whether the provided interface argument is an enabled definitionFlags option. */ func (r *MatchingRuleUse) is(b interface{}) bool { switch tv := b.(type) { case *AttributeType: if _, x := r.Applies.Contains(tv); !x { return false } case definitionFlags: return r.flags.is(tv) } return false } /* Validate returns an error that reflects any fatal condition observed regarding the receiver configuration. */ func (r *MatchingRuleUse) Validate() (err error) { return r.validate() } func (r *MatchingRuleUse) validate() (err error) { if r.IsZero() { return raise(isZero, "%T.validate", r) } if r.OID.IsZero() { return raise(isZero, "%T.validate: no %T", r, r.OID) } if err = validateNames(r.Name.strings()...); err != nil { return } if err = validateDesc(r.Description); err != nil { return } if r.Applies.IsZero() { return raise(isZero, "%T.validate: no %T", r, r.Applies) } if err = validateFlag(r.flags); err != nil { return } return } func (r *MatchingRuleUse) unmarshal() (string, error) { if err := r.validate(); err != nil { err = raise(invalidUnmarshal, err.Error()) return ``, err } if r.ufn != nil { return r.ufn(r) } return r.unmarshalBasic() } /* Map is a convenience method that returns a map[string][]string instance containing the effective contents of the receiver. */ func (r *MatchingRuleUse) Map() (def map[string][]string) { if err := r.Validate(); err != nil { return } def = make(map[string][]string, 14) def[`RAW`] = []string{r.String()} def[`OID`] = []string{r.OID.String()} def[`TYPE`] = []string{r.Type()} if len(r.info) > 0 { def[`INFO`] = []string{string(r.info)} } if !r.Name.IsZero() { def[`NAME`] = make([]string, 0) for i := 0; i < r.Name.Len(); i++ { def[`NAME`] = append(def[`NAME`], r.Name.Index(i)) } } if len(r.Description) > 0 { def[`DESC`] = []string{r.Description.String()} } if !r.Applies.IsZero() { def[`APPLIES`] = make([]string, 0) for i := 0; i < r.Applies.Len(); i++ { appl := r.Applies.Index(i) term := appl.Name.Index(0) if len(term) == 0 { term = appl.OID.String() } def[`APPLIES`] = append(def[`APPLIES`], term) } } if !r.Extensions.IsZero() { for k, v := range r.Extensions { def[k] = v } } if r.Obsolete() { def[`OBSOLETE`] = []string{`TRUE`} } return def } /* MatchingRuleUseUnmarshaler is a package-included function that honors the signature of the first class (closure) DefinitionUnmarshaler type. The purpose of this function, and similar user-devised ones, is to unmarshal a definition with specific formatting included, such as linebreaks, leading specifier declarations and indenting. */ func MatchingRuleUseUnmarshaler(x interface{}) (def string, err error) { var r *MatchingRuleUse switch tv := x.(type) { case *MatchingRuleUse: if tv.IsZero() { err = raise(isZero, "%T is nil", tv) return } r = tv default: err = raise(unexpectedType, "Bad type for unmarshal (%T)", tv) return } var ( WHSP string = ` ` idnt string = "\n\t" head string = `(` tail string = `)` ) if len(r.spec) > 0 { head = r.spec + WHSP + head } def += head + WHSP + r.OID.String() if !r.Name.IsZero() { def += idnt + r.Name.Label() def += WHSP + r.Name.String() } if !r.Description.IsZero() { def += idnt + r.Description.Label() def += WHSP + r.Description.String() } if r.Obsolete() { def += idnt + Obsolete.String() } // Applies will never be zero def += idnt + r.Applies.Label() def += WHSP + r.Applies.String() if !r.Extensions.IsZero() { def += idnt + r.Extensions.String() } def += WHSP + tail return } func (r *MatchingRuleUse) unmarshalBasic() (def string, err error) { var ( WHSP string = ` ` head string = `(` tail string = `)` ) if len(r.spec) > 0 { head = r.spec + WHSP + head } def += head + WHSP + r.OID.String() if !r.Name.IsZero() { def += WHSP + r.Name.Label() def += WHSP + r.Name.String() } if !r.Description.IsZero() { def += WHSP + r.Description.Label() def += WHSP + r.Description.String() } if r.Obsolete() { def += WHSP + Obsolete.String() } // Applies will never be zero def += WHSP + r.Applies.Label() def += WHSP + r.Applies.String() if !r.Extensions.IsZero() { def += WHSP + r.Extensions.String() } def += WHSP + tail return }
mru.go
0.77552
0.485539
mru.go
starcoder
package types import ( "fmt" sdk "github.com/Dipper-Labs/Dipper-Protocol/types" ) // Minter represents the minting state. type Minter struct { Inflation sdk.Dec `json:"inflation" yaml:"inflation"` // current annual inflation rate AnnualProvisions sdk.Dec `json:"annual_provisions" yaml:"annual_provisions"` // current annual expected provisions CurrentProvisions sdk.Dec `json:"current_provisions" yaml:"current_provisions"` } // NewMinter returns a new Minter object with the given inflation, provisions values // and current provisions func NewMinter(inflation, annualProvisions, currentProvisions sdk.Dec) Minter { return Minter{ Inflation: inflation, AnnualProvisions: annualProvisions, CurrentProvisions: currentProvisions, } } // InitialMinter returns an initial Minter object with a given inflation value. func InitialMinter(inflation sdk.Dec) Minter { return NewMinter( inflation, sdk.NewDec(0), sdk.NewDec(0), ) } // DefaultInitialMinter returns a default initial Minter object for a new chain // which uses an inflation rate of 4%. func DefaultInitialMinter() Minter { return InitialMinter( sdk.NewDecWithPrec(4, 2), ) } // ValidateMinter validates minter func ValidateMinter(minter Minter) error { if minter.Inflation.LT(sdk.ZeroDec()) { return fmt.Errorf("mint parameter Inflation should be positive, is %s", minter.Inflation.String()) } return nil } // NextInflationRate returns the new inflation rate for the next block. func (m Minter) NextInflationRate(params Params, bondedRatio sdk.Dec) sdk.Dec { // The target annual inflation rate is recalculated for each previsions cycle. The // inflation is also subject to a rate change (positive or negative) depending on // the distance from the desired ratio (67%). The maximum rate change possible is // defined to be 6% per year, however the annual inflation is capped as between // 4% and 10%. // (1 - bondedRatio/GoalBonded) * InflationRateChange inflationRateChangePerYear := sdk.OneDec(). Sub(bondedRatio.Quo(params.GoalBonded)). Mul(params.InflationRateChange) inflationRateChange := inflationRateChangePerYear.Quo(sdk.NewDec(int64(params.BlocksPerYear))) // adjust the new annual inflation for this next cycle inflation := m.Inflation.Add(inflationRateChange) // note inflationRateChange may be negative if inflation.GT(params.InflationMax) { inflation = params.InflationMax } if inflation.LT(params.InflationMin) { inflation = params.InflationMin } return inflation } // NextAnnualProvisions returns the annual provisions based on current total // supply and inflation rate. func (m Minter) NextAnnualProvisions(_ Params, totalSupply sdk.Int) sdk.Dec { return m.Inflation.MulInt(totalSupply) } // BlockProvision returns the provisions for a block based on the annual // provisions rate. func (m Minter) BlockProvision(params Params) sdk.Coin { provisionAmt := m.AnnualProvisions.QuoInt(sdk.NewInt(int64(params.BlocksPerYear))) return sdk.NewCoin(params.MintDenom, provisionAmt.TruncateInt()) }
app/v0/mint/internal/types/minter.go
0.832985
0.443118
minter.go
starcoder
package voprf import ( "github.com/bytemare/cryptotools/encoding" "github.com/bytemare/cryptotools/hashtogroup/group" ) type ppbEncoded struct { BlindedGenerator []byte `json:"g"` BlindedPubKey []byte `json:"p"` } // PreprocessedBlind groups pre-computed values to be used as blinding by the Client/Verifier. type PreprocessedBlind struct { blindedGenerator group.Element blindedPubKey group.Element } // Encode returns the encoding of the PreprocessedBlind in the given format. func (p *PreprocessedBlind) Encode(enc encoding.Encoding) ([]byte, error) { e := &ppbEncoded{ BlindedGenerator: p.blindedGenerator.Bytes(), BlindedPubKey: p.blindedPubKey.Bytes(), } return enc.Encode(e) } // Start is a wrapper to Blind() and does strictly the same as Blind(). func (c *Client) Start(input []byte) []byte { return c.Blind(input) } // Finish groups the client's actions after receiving the server evaluation, and decodes and unblinds it, and returns // the a hash of the protocol transcript. func (c *Client) Finish(evaluation []byte, enc encoding.Encoding) (output []byte, err error) { if err := c.DecodeEvaluation(evaluation, enc); err != nil { return nil, err } if _, err := c.Unblind(); err != nil { return nil, err } return c.Finalize(), nil } func (c *Client) verifyProof(proofC, proofS group.Scalar, blindedElementList, evaluatedElementList []group.Element) bool { publicKey := c.serverPublicKey a1, a2 := c.computeComposite(nil, publicKey, blindedElementList, evaluatedElementList) ab := c.group.Base().Mult(proofS) ap := publicKey.Mult(proofC) a3 := ab.Add(ap) bm := a1.Mult(proofS) bz := a2.Mult(proofC) a4 := bm.Add(bz) expectedC := c.proofScalar(publicKey, a1, a2, a3, a4) return ctEqual(expectedC.Bytes(), proofC.Bytes()) } /* TODO for info Curious, I just looked up the different document versions and can't find why I thought it was of a specific format, I built it like "RFCXXX-$contextstring". I think it's this paragraph: > Note that in the final output, the client computes Finalize over some auxiliary input data info. This parameter SHOULD be used for domain separation in the (V)OPRF protocol. Specifically, any system which has multiple (V)OPRF applications should use separate auxiliary values to ensure finalized outputs are separate. Guidance for constructing info can be found in {{!I-D.irtf-cfrg-hash-to-curve}}; Section 3.1. i.e. build after "app-version-ciphersuite". But now I see I wasn Todo: Clarify Batched evaluations 0. Why only in verifiable mode ? 1. Not available in additive mode, since we're using multiple blinds. Explain the rationale. 2. Need API for client when setting up batch 3. Need API for server to know if we're playing with batch 4. Inner workings of Evaluation (done) 5. Client needs a flag to know it's handling a batch 6. Describe client API for unblinding batch (I saw the implem in the poc, but nothing in the I-D) 7. Finalize version of batched unblinded elements Notes: order MUST be preserved, or unblinding will not have desired result. I suppose rate-limiting / anti-dos must be implemented by higher level applications. */
.old/client.go
0.603114
0.40204
client.go
starcoder
package main import "sort" // Topic represents a CLI topic. // For example, in the command `heroku apps:create` the topic would be `apps`. type Topic struct { Name string `json:"name"` Description string `json:"description"` Hidden bool `json:"hidden"` Namespace *Namespace `json:"namespace"` Commands []*Command } func (t *Topic) String() string { if t.Namespace == nil || t.Namespace.Name == getDefaultNamespace() { return t.Name } return t.Namespace.Name + ":" + t.Name } // Topics are a list of topics type Topics []*Topic // ByName returns a topic in the set matching the name. func (topics Topics) ByName(name string) *Topic { for _, topic := range topics { if topic.Name == name { return topic } } return nil } // Concat joins 2 topic sets together func (topics Topics) Concat(more Topics) Topics { for _, topic := range more { if topics.ByName(topic.Name) == nil { topics = append(topics, topic) } } return topics } func (topics Topics) Len() int { return len(topics) } func (topics Topics) Less(i, j int) bool { return topics[i].Name < topics[j].Name } func (topics Topics) Swap(i, j int) { topics[i], topics[j] = topics[j], topics[i] } // AllTopics gets all go/core/user topics func AllTopics() Topics { topics := CLITopics topics = topics.Concat(CorePlugins.Topics()) topics = topics.Concat(UserPlugins.Topics()) return topics } // NonHidden returns a set of topics that are not hidden func (topics Topics) NonHidden() Topics { to := make(Topics, 0, len(topics)) for _, topic := range topics { if !topic.Hidden { to = append(to, topic) } } return to } // Namespaces returns a set of namespace from the set of topics func (topics Topics) Namespaces() Namespaces { to := make(Namespaces, 0, len(topics)) unique := make(map[string]bool) for _, topic := range topics { if topic.Namespace != nil && !unique[topic.Namespace.Name] { unique[topic.Namespace.Name] = true to = append(to, topic.Namespace) } } return to } // Namespace returns a set of topics that are part of the cli namespace func (topics Topics) Namespace(name string) Topics { to := make(Topics, 0, len(topics)) for _, topic := range topics { matchedNoNamespace := topic.Namespace == nil && name == "" matchedNamespace := topic.Namespace != nil && topic.Namespace.Name == name matchedDefault := topic.Namespace != nil && topic.Namespace.Name == getDefaultNamespace() && name == "" if matchedNoNamespace || matchedNamespace || matchedDefault { to = append(to, topic) } } return to } // NamespaceAndTopicDescriptions returns a map of namespace and namespaceless // topic descriptions // i.e. it will group all topics by namespace except for topics that don't have a // namespace func (topics Topics) NamespaceAndTopicDescriptions() map[string]string { to := make(map[string]string) for _, topic := range topics { if topic.Namespace == nil || topic.Namespace.Name == getDefaultNamespace() { if to[topic.Name] == "" { to[topic.Name] = topic.Description } } else if desc, ok := to[topic.Namespace.Name]; ok || desc == "" { to[topic.Namespace.Name] = topic.Namespace.Description } } // Check for namespaces to be loaded for _, namespace := range AllNamespaces() { if desc, ok := to[namespace.Name]; ok || desc == "" { to[namespace.Name] = namespace.Description } } return to } // Sort sorts the set func (topics Topics) Sort() Topics { sort.Sort(topics) return topics } // Commands returns all the commands of all the topics func (topics Topics) Commands() Commands { commands := Commands{} for _, topic := range topics { for _, command := range topic.Commands { command.Topic = topic.Name commands = append(commands, command) } } return commands }
topic.go
0.721841
0.400251
topic.go
starcoder
package aes import "encoding/binary" // rotword perform a left rotation on the s of a word func rotword(word uint32) uint32 { return word<<8 | word>>24 } // subword applies the AES S-box to a 4-byte word func subword(word uint32) (output uint32) { s := make([]byte, 4) wb := make([]byte, 4) binary.BigEndian.PutUint32(wb, word) for i := 0; i < 4; i++ { s[i] = sboxForward[wb[i]] } return binary.BigEndian.Uint32(s) } // invSubword applies the AES inverse S-box to a 4-byte word func invSubword(word uint32) (output uint32) { s := make([]byte, 4) wb := make([]byte, 4) binary.BigEndian.PutUint32(wb, word) for i := 0; i < 4; i++ { s[i] = sboxInverse[wb[i]] } return binary.BigEndian.Uint32(s) } // keyExpansion implements the AES key schedule func keyExpansion(Nk int, Nr int, key []uint32) (encKeys [][]uint32, decKeys [][]uint32) { w := make([]uint32, 4*(Nr+1)) i := 0 for i < Nk { w[i] = key[i] i++ } var temp uint32 for i < (4 * (Nr + 1)) { temp = w[i-1] if i%Nk == 0 { temp = subword(rotword(temp)) ^ rcon[i/Nk-1] } else if Nk > 6 && i%Nk == 4 { temp = subword(temp) } w[i] = w[i-Nk] ^ temp i++ } // Split the keys by round Nb := 4 encKeys = make([][]uint32, (Nr + 1)) decKeys = make([][]uint32, (Nr + 1)) for i := 0; i <= Nr; i++ { encKeys[i] = make([]uint32, Nb) decKeys[i] = make([]uint32, Nb) } round := 0 for index, keyByte := range w { encKeys[round][index%Nb] = keyByte decKeys[round][index%Nb] = keyByte if (index+1)%Nb == 0 { round++ } } // Decryption keys for the equivalent inverse cipher for i := 1; i < Nr; i++ { decKeys[i] = invMixColumns(decKeys[i]) } return encKeys, decKeys } // subBytes applies the S-box on each byte of the state // Here the state is represented as an array of columns func subBytes(state []uint32) []uint32 { output := make([]uint32, len(state)) for i := 0; i < len(state); i++ { output[i] = subword(state[i]) } return output } // invSubBytes applies the inverse S-box on each byte of the state // Here the state is represented as an array of columns func invSubBytes(state []uint32) []uint32 { output := make([]uint32, len(state)) for i := 0; i < len(state); i++ { output[i] = invSubword(state[i]) } return output } // shiftRows applies a rotation each row of the state // Here the state is represented as an array of columns func shiftRows(state []uint32) []uint32 { stateRows := columnsToRows(state) for i := 0; i < len(state); i++ { highBits := stateRows[i] << (i * 8) lowBits := stateRows[i] >> ((len(state) - i) * 8) stateRows[i] = highBits | lowBits } return rowsToColumns(stateRows) } // invShiftRows applies a rotation each row of the state // Here the state is represented as an array of columns func invShiftRows(state []uint32) []uint32 { stateRows := columnsToRows(state) for i := 0; i < len(state); i++ { highBits := stateRows[i] >> (i * 8) lowBits := stateRows[i] << ((len(state) - i) * 8) stateRows[i] = highBits | lowBits } return rowsToColumns(stateRows) } // columnsToRows converts the representation of the state from columns to rows func columnsToRows(state []uint32) []uint32 { output := make([]uint32, len(state)) // Iterate through each column for c := 0; c < len(state); c++ { // Iterate through each row for r := 0; r < len(state); r++ { shift := len(state) - 1 - r // (0xff << 8*shift) selects the byte in the column // (>> 8*shift) puts back the byte in the least significant position // << (len(state)-c-1) * 8 places the byte in the correct position in the row output[r] = (((state[c] & (0xff << (shift * 8))) >> (shift * 8)) << ((len(state) - 1 - c) * 8)) | output[r] } } return output } // rowsToColumns converts the representation of the state from rows to columns func rowsToColumns(state []uint32) []uint32 { output := make([]uint32, len(state)) // Iterate through each row for r := 0; r < len(state); r++ { // Iterate through each column for c := 0; c < len(state); c++ { shift := len(state) - 1 - c // select the row byte with (0xff << shift) // place back the byte in least significant position with >> shift*8 // place the byte in the correct position in the column with << r*8 output[c] = (((state[r] & (0x000000ff << (shift * 8))) >> (shift * 8)) << ((len(state) - 1 - r) * 8)) | output[c] } } return output } // mul computes the multiplication of two s as defined in FIPS-197 func mul(a byte, b byte) byte { // We are basically doing a long multiplication except that additions // are replaced by XOR : https://en.wikipedia.org/wiki/Multiplication_algorithm#Long_multiplication var output byte for i := 0; i < 8; i++ { // add if (b & 1) != 0 { output = output ^ a } // shift a = xtime(a) b = b >> 1 } return output } // xtime as defined in FIPS-197 func xtime(x byte) byte { var b7 byte = 0x80 /* to test if the high bit is set */ var temp byte = x << 1 if (b7 & x) == b7 { temp ^= 0x1b /* x^8 + x^4 + x^3 + x + 1*/ } return temp } // mixColumns as defined in FIPS-197 func mixColumns(state []uint32) []uint32 { var two byte = 0x02 var three byte = 0x03 newState := make([]uint32, len(state)) for c := 0; c < len(state); c++ { s := make([]byte, 4) binary.BigEndian.PutUint32(s, state[c]) b0 := mul(two, s[0]) ^ mul(three, s[1]) ^ s[2] ^ s[3] b1 := s[0] ^ mul(two, s[1]) ^ mul(three, s[2]) ^ s[3] b2 := s[0] ^ s[1] ^ mul(two, s[2]) ^ mul(three, s[3]) b3 := mul(three, s[0]) ^ s[1] ^ s[2] ^ mul(two, s[3]) newState[c] = binary.BigEndian.Uint32([]byte{b0, b1, b2, b3}) } return newState } // invMixColumns as defined in FIPS-197 func invMixColumns(state []uint32) []uint32 { var e byte = 0x0e var b byte = 0x0b var d byte = 0x0d var n byte = 0x09 newState := make([]uint32, len(state)) for c := 0; c < len(state); c++ { s := make([]byte, 4) binary.BigEndian.PutUint32(s, state[c]) b0 := mul(e, s[0]) ^ mul(b, s[1]) ^ mul(d, s[2]) ^ mul(n, s[3]) b1 := mul(n, s[0]) ^ mul(e, s[1]) ^ mul(b, s[2]) ^ mul(d, s[3]) b2 := mul(d, s[0]) ^ mul(n, s[1]) ^ mul(e, s[2]) ^ mul(b, s[3]) b3 := mul(b, s[0]) ^ mul(d, s[1]) ^ mul(n, s[2]) ^ mul(e, s[3]) newState[c] = binary.BigEndian.Uint32([]byte{b0, b1, b2, b3}) } return newState } // addRoundKey XOR the state with the round key func addRoundKey(state []uint32, key []uint32) []uint32 { out := make([]uint32, len(state)) for i := 0; i < len(state); i++ { out[i] = state[i] ^ key[i] } return out } // EncryptBlock encrypts a 128-bit block with the AES algorithm // This implementation is as close to the specification as possible but // there are better implementations in terms of speed and readability // Check out https://golang.org/src/crypto/aes/block.go func EncryptBlock(plaintext []uint32, key []uint32, Nk int, Nr int) []uint32 { roundKeys, _ := keyExpansion(Nk, Nr, key) // Init state := plaintext // Round 0 state = addRoundKey(roundKeys[0], state) // Round 1 to (Nr-1) for round := 1; round < Nr; round++ { state = addRoundKey(mixColumns(shiftRows(subBytes(state))), roundKeys[round]) } // Round Nr state = addRoundKey(shiftRows(subBytes(state)), roundKeys[Nr]) return state } // DecryptBlock decrypts a 128-bit block with the AES algorithm // This implementation is as close to the specification as possible but // there are better implementations in terms of speed and readability // Check out https://golang.org/src/crypto/aes/block.go func DecryptBlock(ciphertext []uint32, key []uint32, Nk int, Nr int) []uint32 { _, roundKeys := keyExpansion(Nk, Nr, key) // Init state := ciphertext // Round Nr state = addRoundKey(roundKeys[Nr], state) // Round Nr-1 to 1 for round := (Nr - 1); round > 0; round-- { state = addRoundKey(invMixColumns(invShiftRows(invSubBytes(state))), roundKeys[round]) } // Round 0 state = addRoundKey(invShiftRows(invSubBytes(state)), roundKeys[0]) return state }
aes/block.go
0.661376
0.547525
block.go
starcoder
package rasterize import "github.com/RH12503/Triangula/geom" // DDATriangleLines calls function line for each horizontal line a geom.Triangle covers // using a digital differential analyzing algorithm. func DDATriangleLines(triangle geom.Triangle, line func(x0, x1, y int)) { p0 := triangle.Points[0] p1 := triangle.Points[1] p2 := triangle.Points[2] // Sort vertices by height, where y0 has the lowest y value x0, y0 := p0.X, p0.Y x1, y1 := p1.X, p1.Y x2, y2 := p2.X, p2.Y if y1 > y0 { x0, x1 = x1, x0 y0, y1 = y1, y0 } if y2 > y1 { x1, x2 = x2, x1 y1, y2 = y2, y1 if y1 > y0 { x0, x1 = x1, x0 y0, y1 = y1, y0 } } if y1 == y2 { // If the bottom 2 vertices are equal, rasterize a triangle with a flat bottom if x2 < x1 { x1, x2 = x2, x1 y1 = y2 } bottomTriangleLines(x1, x2, y1, x0, y0, line) } else if y0 == y1 { // If the top 2 vertices are equal, rasterize a triangle with a flat top if x0 > x1 { x0, x1 = x1, x0 y0 = y1 } topTriangleLines(x0, x1, y0, x2, y2, line) } else { // If all the y values are different, rasterize the triangle normally normalTriangleLines(x0, y0, x1, y1, x2, y2, line) } } // normalTriangleLines rasterizes a triangle with different y values. // The y values must be sorted where y0 has the lowest value. func normalTriangleLines(x0, y0, x1, y1, x2, y2 int, line func(x0, x1, y int)) { // Calculate the slopes of the first two lines m0 := float64(x2-x0) / float64(y2-y0) m1 := float64(x2-x1) / float64(y2-y1) // Swap the slopes so m0 is the slope of the left line and m1 is the slope of the right line swap := m0 > m1 if swap { m0, m1 = m1, m0 } // Start from the top vertex b0 := float64(x2) b1 := float64(x2) var nX0, nX1 float64 for i := y2; i < y1; i++ { nX0 = m0*float64(i-y2) + b0 nX1 = m1*float64(i-y2) + b1 line(int(nX0), int(nX1), i) } var d0, d1 int // One slope will always remain the same, and the second one needs to be calculated if swap { m0 = float64(x1-x0) / float64(y1-y0) b0 = float64(x1) d1 = y1 - y2 } else { m1 = float64(x1-x0) / float64(y1-y0) b1 = float64(x1) d0 = y1 - y2 } for i := y1; i < y0; i++ { nX0 = m0*float64(i-y1+d0) + b0 nX1 = m1*float64(i-y1+d1) + b1 line(int(nX0), int(nX1), i) } } // bottomTriangleLines rasterizes a triangle with a flat bottom of coordinate y. func bottomTriangleLines(x0, x1, y, x2, y2 int, line func(x0, x1, y int)) { flatTriangleLines(x2, y2, x0, y, x1-x2, x1, line) } // topTriangleLines rasterizes a triangle with a flat top of coordinate y. func topTriangleLines(x0, x1, y, x2, y2 int, line func(x0, x1, y int)) { flatTriangleLines(x0, y, x2, y2, x2-x1, x2, line) } // flatTriangleLines rasterizes a triangle with a flat top or bottom. func flatTriangleLines(x0, y, x2, y2, i2, p int, line func(x0, x1, y int)) { m0 := float64(x2-x0) / float64(y2-y) m1 := float64(i2) / float64(y2-y) fillTriangleLines(y2, y, float64(x2), float64(p), m0, m1, line) } // fillTriangleLines rasterizes a flat triangle given the linear equations of its two lines. func fillTriangleLines(minY, maxY int, lX0, lX1, m0, m1 float64, line func(x0, x1, y int)) { for i := minY; i < maxY; i++ { nX0 := m0*float64(i-minY) + lX0 nX1 := m1*float64(i-minY) + lX1 line(int(nX0), int(nX1), i) } }
rasterize/lines.go
0.628407
0.815012
lines.go
starcoder
package metrics import ( "context" "fmt" "sync" "time" "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/types" "github.com/Jeffail/benthos/v3/lib/util/aws/session" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/cloudwatch" "github.com/aws/aws-sdk-go/service/cloudwatch/cloudwatchiface" ) //------------------------------------------------------------------------------ func init() { Constructors[TypeCloudWatch] = TypeSpec{ constructor: NewCloudWatch, Summary: ` Send metrics to AWS CloudWatch using the PutMetricData endpoint.`, Description: ` It is STRONGLY recommended that you reduce the metrics that are exposed with a ` + "`path_mapping`" + ` like this: ` + "```yaml" + ` metrics: cloudwatch: namespace: Foo path_mapping: | if ![ "input.received", "input.latency", "output.sent", ].contains(this) { deleted() } ` + "```" + ``, FieldSpecs: append(docs.FieldSpecs{ docs.FieldCommon("namespace", "The namespace used to distinguish metrics from other services."), docs.FieldAdvanced("flush_period", "The period of time between PutMetricData requests."), pathMappingDocs(true), }, session.FieldSpecs()...), } } //------------------------------------------------------------------------------ // CloudWatchConfig contains config fields for the CloudWatch metrics type. type CloudWatchConfig struct { session.Config `json:",inline" yaml:",inline"` Namespace string `json:"namespace" yaml:"namespace"` FlushPeriod string `json:"flush_period" yaml:"flush_period"` PathMapping string `json:"path_mapping" yaml:"path_mapping"` } // NewCloudWatchConfig creates an CloudWatchConfig struct with default values. func NewCloudWatchConfig() CloudWatchConfig { return CloudWatchConfig{ Config: session.NewConfig(), Namespace: "Benthos", FlushPeriod: "100ms", PathMapping: "", } } //------------------------------------------------------------------------------ const maxCloudWatchMetrics = 20 const maxCloudWatchValues = 150 const maxCloudWatchDimensions = 10 type cloudWatchDatum struct { MetricName string Unit string Dimensions []*cloudwatch.Dimension Timestamp time.Time Value int64 Values map[int64]int64 } type cloudWatchStat struct { root *CloudWatch id string name string unit string dimensions []*cloudwatch.Dimension } // Trims a map of datum values to a ceiling. The primary goal here is to be fast // and efficient rather than accurately preserving the most common values. func trimValuesMap(m map[int64]int64) { ceiling := maxCloudWatchValues // Start off by randomly removing values that have been seen only once. for k, v := range m { if len(m) <= ceiling { // If we reach our ceiling already then we're done. return } if v == 1 { delete(m, k) } } // Next, randomly remove any values until ceiling is hit. for k := range m { if len(m) <= ceiling { return } delete(m, k) } } func (c *cloudWatchStat) appendValue(v int64) { c.root.datumLock.Lock() existing := c.root.datumses[c.id] if existing == nil { existing = &cloudWatchDatum{ MetricName: c.name, Unit: c.unit, Dimensions: c.dimensions, Timestamp: time.Now(), Values: map[int64]int64{v: 1}, } c.root.datumses[c.id] = existing } else { tally := existing.Values[v] existing.Values[v] = tally + 1 if len(existing.Values) > maxCloudWatchValues*5 { trimValuesMap(existing.Values) } } c.root.datumLock.Unlock() } func (c *cloudWatchStat) addValue(v int64) { c.root.datumLock.Lock() existing := c.root.datumses[c.id] if existing == nil { existing = &cloudWatchDatum{ MetricName: c.name, Unit: c.unit, Dimensions: c.dimensions, Timestamp: time.Now(), Value: v, } c.root.datumses[c.id] = existing } else { existing.Value = existing.Value + v } c.root.datumLock.Unlock() } // Incr increments a metric by an amount. func (c *cloudWatchStat) Incr(count int64) error { c.addValue(count) return nil } // Decr decrements a metric by an amount. func (c *cloudWatchStat) Decr(count int64) error { c.addValue(-count) return nil } // Timing sets a timing metric. func (c *cloudWatchStat) Timing(delta int64) error { // Most granular value for timing metrics in cloudwatch is microseconds // versus nanoseconds. c.appendValue(delta / 1000) return nil } // Set sets a gauge metric. func (c *cloudWatchStat) Set(value int64) error { c.appendValue(value) return nil } type cloudWatchStatVec struct { root *CloudWatch name string unit string labelNames []string } func (c *cloudWatchStatVec) with(labelValues ...string) *cloudWatchStat { lDim := len(c.labelNames) if lDim >= maxCloudWatchDimensions { lDim = maxCloudWatchDimensions } dimensions := make([]*cloudwatch.Dimension, lDim) for i, k := range c.labelNames { if len(labelValues) <= i || i >= maxCloudWatchDimensions { break } dimensions[i] = &cloudwatch.Dimension{ Name: aws.String(k), Value: aws.String(labelValues[i]), } } return &cloudWatchStat{ root: c.root, id: c.name + fmt.Sprintf("%v", labelValues), name: c.name, unit: c.unit, dimensions: dimensions, } } type cloudWatchCounterVec struct { cloudWatchStatVec } func (c *cloudWatchCounterVec) With(labelValues ...string) StatCounter { return c.with(labelValues...) } type cloudWatchTimerVec struct { cloudWatchStatVec } func (c *cloudWatchTimerVec) With(labelValues ...string) StatTimer { return c.with(labelValues...) } type cloudWatchGaugeVec struct { cloudWatchStatVec } func (c *cloudWatchGaugeVec) With(labelValues ...string) StatGauge { return c.with(labelValues...) } //------------------------------------------------------------------------------ // CloudWatch is a stats object with capability to hold internal stats as a JSON // endpoint. type CloudWatch struct { client cloudwatchiface.CloudWatchAPI datumses map[string]*cloudWatchDatum datumLock *sync.Mutex flushPeriod time.Duration ctx context.Context cancel func() pathMapping *pathMapping config CloudWatchConfig log log.Modular } // NewCloudWatch creates and returns a new CloudWatch object. func NewCloudWatch(config Config, opts ...func(Type)) (Type, error) { c := &CloudWatch{ config: config.CloudWatch, datumses: map[string]*cloudWatchDatum{}, datumLock: &sync.Mutex{}, log: log.Noop(), } c.ctx, c.cancel = context.WithCancel(context.Background()) for _, opt := range opts { opt(c) } var err error if c.pathMapping, err = newPathMapping(config.CloudWatch.PathMapping, c.log); err != nil { return nil, fmt.Errorf("failed to init path mapping: %v", err) } sess, err := config.CloudWatch.GetSession() if err != nil { return nil, err } if c.flushPeriod, err = time.ParseDuration(config.CloudWatch.FlushPeriod); err != nil { return nil, fmt.Errorf("failed to parse flush period: %v", err) } c.client = cloudwatch.New(sess) go c.loop() return c, nil } //------------------------------------------------------------------------------ func (c *CloudWatch) toCMName(dotSepName string) (string, []string, []string) { return c.pathMapping.mapPathWithTags(dotSepName) } // GetCounter returns a stat counter object for a path. func (c *CloudWatch) GetCounter(path string) StatCounter { name, labels, values := c.toCMName(path) if len(name) == 0 { return DudStat{} } if len(labels) == 0 { return &cloudWatchStat{ root: c, id: name, name: name, unit: cloudwatch.StandardUnitCount, } } return (&cloudWatchCounterVec{ cloudWatchStatVec: cloudWatchStatVec{ root: c, name: name, unit: cloudwatch.StandardUnitCount, labelNames: labels, }, }).With(values...) } // GetCounterVec returns a stat counter object for a path with the labels func (c *CloudWatch) GetCounterVec(path string, n []string) StatCounterVec { name, labels, values := c.toCMName(path) if len(name) == 0 { return fakeCounterVec(func([]string) StatCounter { return DudStat{} }) } if len(labels) > 0 { labels = append(labels, n...) return fakeCounterVec(func(vs []string) StatCounter { fvs := append([]string{}, values...) fvs = append(fvs, vs...) return (&cloudWatchCounterVec{ cloudWatchStatVec: cloudWatchStatVec{ root: c, name: name, unit: cloudwatch.StandardUnitCount, labelNames: labels, }, }).With(fvs...) }) } return &cloudWatchCounterVec{ cloudWatchStatVec: cloudWatchStatVec{ root: c, name: name, unit: cloudwatch.StandardUnitCount, labelNames: n, }, } } // GetTimer returns a stat timer object for a path. func (c *CloudWatch) GetTimer(path string) StatTimer { name, labels, values := c.toCMName(path) if len(name) == 0 { return DudStat{} } if len(labels) == 0 { return &cloudWatchStat{ root: c, id: name, name: name, unit: cloudwatch.StandardUnitMicroseconds, } } return (&cloudWatchTimerVec{ cloudWatchStatVec: cloudWatchStatVec{ root: c, name: name, unit: cloudwatch.StandardUnitMicroseconds, labelNames: labels, }, }).With(values...) } // GetTimerVec returns a stat timer object for a path with the labels func (c *CloudWatch) GetTimerVec(path string, n []string) StatTimerVec { name, labels, values := c.toCMName(path) if len(name) == 0 { return fakeTimerVec(func([]string) StatTimer { return DudStat{} }) } if len(labels) > 0 { labels = append(labels, n...) return fakeTimerVec(func(vs []string) StatTimer { fvs := append([]string{}, values...) fvs = append(fvs, vs...) return (&cloudWatchTimerVec{ cloudWatchStatVec: cloudWatchStatVec{ root: c, name: name, unit: cloudwatch.StandardUnitMicroseconds, labelNames: labels, }, }).With(fvs...) }) } return &cloudWatchTimerVec{ cloudWatchStatVec: cloudWatchStatVec{ root: c, name: name, unit: cloudwatch.StandardUnitMicroseconds, labelNames: n, }, } } // GetGauge returns a stat gauge object for a path. func (c *CloudWatch) GetGauge(path string) StatGauge { name, labels, values := c.toCMName(path) if len(name) == 0 { return DudStat{} } if len(labels) == 0 { return &cloudWatchStat{ root: c, id: name, name: name, unit: cloudwatch.StandardUnitNone, } } return (&cloudWatchGaugeVec{ cloudWatchStatVec: cloudWatchStatVec{ root: c, name: name, unit: cloudwatch.StandardUnitNone, labelNames: labels, }, }).With(values...) } // GetGaugeVec returns a stat timer object for a path with the labels func (c *CloudWatch) GetGaugeVec(path string, n []string) StatGaugeVec { name, labels, values := c.toCMName(path) if len(name) == 0 { return fakeGaugeVec(func([]string) StatGauge { return DudStat{} }) } if len(labels) > 0 { labels = append(labels, n...) return fakeGaugeVec(func(vs []string) StatGauge { fvs := append([]string{}, values...) fvs = append(fvs, vs...) return (&cloudWatchGaugeVec{ cloudWatchStatVec: cloudWatchStatVec{ root: c, name: name, unit: cloudwatch.StandardUnitNone, labelNames: labels, }, }).With(fvs...) }) } return &cloudWatchGaugeVec{ cloudWatchStatVec: cloudWatchStatVec{ root: c, name: name, unit: cloudwatch.StandardUnitNone, labelNames: n, }, } } //------------------------------------------------------------------------------ func (c *CloudWatch) loop() { ticker := time.NewTicker(c.flushPeriod) defer ticker.Stop() for { select { case <-c.ctx.Done(): return case <-ticker.C: c.flush() } } } func valuesMapToSlices(m map[int64]int64) (values []*float64, counts []*float64) { ceiling := maxCloudWatchValues lM := len(m) useCounts := false if lM < ceiling { values = make([]*float64, 0, lM) counts = make([]*float64, 0, lM) for k, v := range m { values = append(values, aws.Float64(float64(k))) counts = append(counts, aws.Float64(float64(v))) if v > 1 { useCounts = true } } if !useCounts { counts = nil } return } values = make([]*float64, 0, ceiling) counts = make([]*float64, 0, ceiling) // Try and make our target without taking values with one count. for k, v := range m { if len(values) == ceiling { return } if v > 1 { values = append(values, aws.Float64(float64(k))) counts = append(counts, aws.Float64(float64(v))) useCounts = true delete(m, k) } } // Otherwise take randomly. for k, v := range m { if len(values) == ceiling { break } values = append(values, aws.Float64(float64(k))) counts = append(counts, aws.Float64(float64(v))) } if !useCounts { counts = nil } return } func (c *CloudWatch) flush() error { c.datumLock.Lock() datumMap := c.datumses c.datumses = map[string]*cloudWatchDatum{} c.datumLock.Unlock() datums := []*cloudwatch.MetricDatum{} for _, v := range datumMap { if v != nil { d := cloudwatch.MetricDatum{ MetricName: &v.MetricName, Dimensions: v.Dimensions, Unit: &v.Unit, Timestamp: &v.Timestamp, } if len(v.Values) > 0 { d.Values, d.Counts = valuesMapToSlices(v.Values) } else { d.Value = aws.Float64(float64(v.Value)) } datums = append(datums, &d) } } input := cloudwatch.PutMetricDataInput{ Namespace: &c.config.Namespace, MetricData: datums, } throttled := false for len(input.MetricData) > 0 { if !throttled { if len(datums) > maxCloudWatchMetrics { input.MetricData, datums = datums[:maxCloudWatchMetrics], datums[maxCloudWatchMetrics:] } else { datums = nil } } throttled = false if _, err := c.client.PutMetricData(&input); err != nil { if request.IsErrorThrottle(err) { throttled = true c.log.Warnln("Metrics request was throttled. Either increase flush period or reduce number of services sending metrics.") } else { c.log.Errorf("Failed to send metric data: %v\n", err) } select { case <-time.After(time.Second): case <-c.ctx.Done(): return types.ErrTimeout } } if !throttled { input.MetricData = datums } } return nil } //------------------------------------------------------------------------------ // SetLogger sets the logger used to print connection errors. func (c *CloudWatch) SetLogger(log log.Modular) { c.log = log } // Close stops the CloudWatch object from aggregating metrics and cleans up // resources. func (c *CloudWatch) Close() error { c.cancel() c.flush() return nil } //------------------------------------------------------------------------------
lib/metrics/cloudwatch.go
0.709724
0.510558
cloudwatch.go
starcoder
package client import ( "encoding/json" ) // MemorySummary struct for MemorySummary type MemorySummary struct { TotalSystemMemoryGiB NullableFloat32 `json:"TotalSystemMemoryGiB,omitempty"` TotalSystemPersistentMemoryGiB NullableFloat32 `json:"TotalSystemPersistentMemoryGiB,omitempty"` Status *Status `json:"Status,omitempty"` } // NewMemorySummary instantiates a new MemorySummary 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 NewMemorySummary() *MemorySummary { this := MemorySummary{} return &this } // NewMemorySummaryWithDefaults instantiates a new MemorySummary 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 NewMemorySummaryWithDefaults() *MemorySummary { this := MemorySummary{} return &this } // GetTotalSystemMemoryGiB returns the TotalSystemMemoryGiB field value if set, zero value otherwise (both if not set or set to explicit null). func (o *MemorySummary) GetTotalSystemMemoryGiB() float32 { if o == nil || o.TotalSystemMemoryGiB.Get() == nil { var ret float32 return ret } return *o.TotalSystemMemoryGiB.Get() } // GetTotalSystemMemoryGiBOk returns a tuple with the TotalSystemMemoryGiB field value if set, nil otherwise // 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 *MemorySummary) GetTotalSystemMemoryGiBOk() (*float32, bool) { if o == nil { return nil, false } return o.TotalSystemMemoryGiB.Get(), o.TotalSystemMemoryGiB.IsSet() } // HasTotalSystemMemoryGiB returns a boolean if a field has been set. func (o *MemorySummary) HasTotalSystemMemoryGiB() bool { if o != nil && o.TotalSystemMemoryGiB.IsSet() { return true } return false } // SetTotalSystemMemoryGiB gets a reference to the given NullableFloat32 and assigns it to the TotalSystemMemoryGiB field. func (o *MemorySummary) SetTotalSystemMemoryGiB(v float32) { o.TotalSystemMemoryGiB.Set(&v) } // SetTotalSystemMemoryGiBNil sets the value for TotalSystemMemoryGiB to be an explicit nil func (o *MemorySummary) SetTotalSystemMemoryGiBNil() { o.TotalSystemMemoryGiB.Set(nil) } // UnsetTotalSystemMemoryGiB ensures that no value is present for TotalSystemMemoryGiB, not even an explicit nil func (o *MemorySummary) UnsetTotalSystemMemoryGiB() { o.TotalSystemMemoryGiB.Unset() } // GetTotalSystemPersistentMemoryGiB returns the TotalSystemPersistentMemoryGiB field value if set, zero value otherwise (both if not set or set to explicit null). func (o *MemorySummary) GetTotalSystemPersistentMemoryGiB() float32 { if o == nil || o.TotalSystemPersistentMemoryGiB.Get() == nil { var ret float32 return ret } return *o.TotalSystemPersistentMemoryGiB.Get() } // GetTotalSystemPersistentMemoryGiBOk returns a tuple with the TotalSystemPersistentMemoryGiB field value if set, nil otherwise // 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 *MemorySummary) GetTotalSystemPersistentMemoryGiBOk() (*float32, bool) { if o == nil { return nil, false } return o.TotalSystemPersistentMemoryGiB.Get(), o.TotalSystemPersistentMemoryGiB.IsSet() } // HasTotalSystemPersistentMemoryGiB returns a boolean if a field has been set. func (o *MemorySummary) HasTotalSystemPersistentMemoryGiB() bool { if o != nil && o.TotalSystemPersistentMemoryGiB.IsSet() { return true } return false } // SetTotalSystemPersistentMemoryGiB gets a reference to the given NullableFloat32 and assigns it to the TotalSystemPersistentMemoryGiB field. func (o *MemorySummary) SetTotalSystemPersistentMemoryGiB(v float32) { o.TotalSystemPersistentMemoryGiB.Set(&v) } // SetTotalSystemPersistentMemoryGiBNil sets the value for TotalSystemPersistentMemoryGiB to be an explicit nil func (o *MemorySummary) SetTotalSystemPersistentMemoryGiBNil() { o.TotalSystemPersistentMemoryGiB.Set(nil) } // UnsetTotalSystemPersistentMemoryGiB ensures that no value is present for TotalSystemPersistentMemoryGiB, not even an explicit nil func (o *MemorySummary) UnsetTotalSystemPersistentMemoryGiB() { o.TotalSystemPersistentMemoryGiB.Unset() } // GetStatus returns the Status field value if set, zero value otherwise. func (o *MemorySummary) GetStatus() Status { if o == nil || o.Status == nil { var ret Status return ret } return *o.Status } // GetStatusOk returns a tuple with the Status field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *MemorySummary) GetStatusOk() (*Status, bool) { if o == nil || o.Status == nil { return nil, false } return o.Status, true } // HasStatus returns a boolean if a field has been set. func (o *MemorySummary) HasStatus() bool { if o != nil && o.Status != nil { return true } return false } // SetStatus gets a reference to the given Status and assigns it to the Status field. func (o *MemorySummary) SetStatus(v Status) { o.Status = &v } func (o MemorySummary) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.TotalSystemMemoryGiB.IsSet() { toSerialize["TotalSystemMemoryGiB"] = o.TotalSystemMemoryGiB.Get() } if o.TotalSystemPersistentMemoryGiB.IsSet() { toSerialize["TotalSystemPersistentMemoryGiB"] = o.TotalSystemPersistentMemoryGiB.Get() } if o.Status != nil { toSerialize["Status"] = o.Status } return json.Marshal(toSerialize) } type NullableMemorySummary struct { value *MemorySummary isSet bool } func (v NullableMemorySummary) Get() *MemorySummary { return v.value } func (v *NullableMemorySummary) Set(val *MemorySummary) { v.value = val v.isSet = true } func (v NullableMemorySummary) IsSet() bool { return v.isSet } func (v *NullableMemorySummary) Unset() { v.value = nil v.isSet = false } func NewNullableMemorySummary(val *MemorySummary) *NullableMemorySummary { return &NullableMemorySummary{value: val, isSet: true} } func (v NullableMemorySummary) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableMemorySummary) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
client/model_memory_summary.go
0.812682
0.42185
model_memory_summary.go
starcoder
package monkit import ( "sort" ) // FloatDist keeps statistics about values such as // low/high/recent/average/quantiles. Not threadsafe. Construct with // NewFloatDist(). Fields are expected to be read from but not written to. type FloatDist struct { // Low and High are the lowest and highest values observed since // construction or the last reset. Low, High float64 // Recent is the last observed value. Recent float64 // Count is the number of observed values since construction or the last // reset. Count int64 // Sum is the sum of all the observed values since construction or the last // reset. Sum float64 key SeriesKey reservoir [ReservoirSize]float32 rng xorshift128 sorted bool } func initFloatDist(v *FloatDist, key SeriesKey) { v.key = key v.rng = newXORShift128() } // NewFloatDist creates a distribution of float64s. func NewFloatDist(key SeriesKey) (d *FloatDist) { d = &FloatDist{} initFloatDist(d, key) return d } // Insert adds a value to the distribution, updating appropriate values. func (d *FloatDist) Insert(val float64) { if d.Count != 0 { if val < d.Low { d.Low = val } if val > d.High { d.High = val } } else { d.Low = val d.High = val } d.Recent = val d.Sum += val index := d.Count d.Count += 1 if index < ReservoirSize { d.reservoir[index] = float32(val) d.sorted = false } else { window := d.Count // careful, the capitalization of Window is important if Window > 0 && window > Window { window = Window } // fast, but kind of biased. probably okay j := d.rng.Uint64() % uint64(window) if j < ReservoirSize { d.reservoir[int(j)] = float32(val) d.sorted = false } } } // FullAverage calculates and returns the average of all inserted values. func (d *FloatDist) FullAverage() float64 { if d.Count > 0 { return d.Sum / float64(d.Count) } return 0 } // ReservoirAverage calculates the average of the current reservoir. func (d *FloatDist) ReservoirAverage() float64 { amount := ReservoirSize if d.Count < int64(amount) { amount = int(d.Count) } if amount <= 0 { return 0 } var sum float32 for i := 0; i < amount; i++ { sum += d.reservoir[i] } return float64(sum / float32(amount)) } // Query will return the approximate value at the given quantile from the // reservoir, where 0 <= quantile <= 1. func (d *FloatDist) Query(quantile float64) float64 { rlen := int(ReservoirSize) if int64(rlen) > d.Count { rlen = int(d.Count) } if rlen < 2 { return float64(d.reservoir[0]) } reservoir := d.reservoir[:rlen] if !d.sorted { sort.Sort(float32Slice(reservoir)) d.sorted = true } if quantile <= 0 { return float64(reservoir[0]) } if quantile >= 1 { return float64(reservoir[rlen-1]) } idx_float := quantile * float64(rlen-1) idx := int(idx_float) diff := idx_float - float64(idx) prior := float64(reservoir[idx]) return float64(prior + diff*(float64(reservoir[idx+1])-prior)) } // Copy returns a full copy of the entire distribution. func (d *FloatDist) Copy() *FloatDist { cp := *d cp.rng = newXORShift128() return &cp } func (d *FloatDist) Reset() { d.Low, d.High, d.Recent, d.Count, d.Sum = 0, 0, 0, 0, 0 // resetting count will reset the quantile reservoir } func (d *FloatDist) Stats(cb func(key SeriesKey, field string, val float64)) { count := d.Count cb(d.key, "count", float64(count)) if count > 0 { cb(d.key, "sum", d.toFloat64(d.Sum)) cb(d.key, "min", d.toFloat64(d.Low)) cb(d.key, "avg", d.toFloat64(d.FullAverage())) cb(d.key, "max", d.toFloat64(d.High)) cb(d.key, "rmin", d.toFloat64(d.Query(0))) cb(d.key, "ravg", d.toFloat64(d.ReservoirAverage())) cb(d.key, "r10", d.toFloat64(d.Query(.1))) cb(d.key, "r50", d.toFloat64(d.Query(.5))) cb(d.key, "r90", d.toFloat64(d.Query(.9))) cb(d.key, "rmax", d.toFloat64(d.Query(1))) cb(d.key, "recent", d.toFloat64(d.Recent)) } }
vendor/github.com/spacemonkeygo/monkit/v3/floatdist.go
0.716417
0.604807
floatdist.go
starcoder
package datadog import ( "encoding/json" ) // GetCreator returns the Creator field if non-nil, zero value otherwise. func (a *Alert) GetCreator() int { if a == nil || a.Creator == nil { return 0 } return *a.Creator } // GetOkCreator returns a tuple with the Creator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetCreatorOk() (int, bool) { if a == nil || a.Creator == nil { return 0, false } return *a.Creator, true } // HasCreator returns a boolean if a field has been set. func (a *Alert) HasCreator() bool { if a != nil && a.Creator != nil { return true } return false } // SetCreator allocates a new a.Creator and returns the pointer to it. func (a *Alert) SetCreator(v int) { a.Creator = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (a *Alert) GetId() int { if a == nil || a.Id == nil { return 0 } return *a.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetIdOk() (int, bool) { if a == nil || a.Id == nil { return 0, false } return *a.Id, true } // HasId returns a boolean if a field has been set. func (a *Alert) HasId() bool { if a != nil && a.Id != nil { return true } return false } // SetId allocates a new a.Id and returns the pointer to it. func (a *Alert) SetId(v int) { a.Id = &v } // GetMessage returns the Message field if non-nil, zero value otherwise. func (a *Alert) GetMessage() string { if a == nil || a.Message == nil { return "" } return *a.Message } // GetOkMessage returns a tuple with the Message field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetMessageOk() (string, bool) { if a == nil || a.Message == nil { return "", false } return *a.Message, true } // HasMessage returns a boolean if a field has been set. func (a *Alert) HasMessage() bool { if a != nil && a.Message != nil { return true } return false } // SetMessage allocates a new a.Message and returns the pointer to it. func (a *Alert) SetMessage(v string) { a.Message = &v } // GetName returns the Name field if non-nil, zero value otherwise. func (a *Alert) GetName() string { if a == nil || a.Name == nil { return "" } return *a.Name } // GetOkName returns a tuple with the Name field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetNameOk() (string, bool) { if a == nil || a.Name == nil { return "", false } return *a.Name, true } // HasName returns a boolean if a field has been set. func (a *Alert) HasName() bool { if a != nil && a.Name != nil { return true } return false } // SetName allocates a new a.Name and returns the pointer to it. func (a *Alert) SetName(v string) { a.Name = &v } // GetNotifyNoData returns the NotifyNoData field if non-nil, zero value otherwise. func (a *Alert) GetNotifyNoData() bool { if a == nil || a.NotifyNoData == nil { return false } return *a.NotifyNoData } // GetOkNotifyNoData returns a tuple with the NotifyNoData field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetNotifyNoDataOk() (bool, bool) { if a == nil || a.NotifyNoData == nil { return false, false } return *a.NotifyNoData, true } // HasNotifyNoData returns a boolean if a field has been set. func (a *Alert) HasNotifyNoData() bool { if a != nil && a.NotifyNoData != nil { return true } return false } // SetNotifyNoData allocates a new a.NotifyNoData and returns the pointer to it. func (a *Alert) SetNotifyNoData(v bool) { a.NotifyNoData = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (a *Alert) GetQuery() string { if a == nil || a.Query == nil { return "" } return *a.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetQueryOk() (string, bool) { if a == nil || a.Query == nil { return "", false } return *a.Query, true } // HasQuery returns a boolean if a field has been set. func (a *Alert) HasQuery() bool { if a != nil && a.Query != nil { return true } return false } // SetQuery allocates a new a.Query and returns the pointer to it. func (a *Alert) SetQuery(v string) { a.Query = &v } // GetSilenced returns the Silenced field if non-nil, zero value otherwise. func (a *Alert) GetSilenced() bool { if a == nil || a.Silenced == nil { return false } return *a.Silenced } // GetOkSilenced returns a tuple with the Silenced field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetSilencedOk() (bool, bool) { if a == nil || a.Silenced == nil { return false, false } return *a.Silenced, true } // HasSilenced returns a boolean if a field has been set. func (a *Alert) HasSilenced() bool { if a != nil && a.Silenced != nil { return true } return false } // SetSilenced allocates a new a.Silenced and returns the pointer to it. func (a *Alert) SetSilenced(v bool) { a.Silenced = &v } // GetState returns the State field if non-nil, zero value otherwise. func (a *Alert) GetState() string { if a == nil || a.State == nil { return "" } return *a.State } // GetOkState returns a tuple with the State field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetStateOk() (string, bool) { if a == nil || a.State == nil { return "", false } return *a.State, true } // HasState returns a boolean if a field has been set. func (a *Alert) HasState() bool { if a != nil && a.State != nil { return true } return false } // SetState allocates a new a.State and returns the pointer to it. func (a *Alert) SetState(v string) { a.State = &v } // GetAccount returns the Account field if non-nil, zero value otherwise. func (c *ChannelSlackRequest) GetAccount() string { if c == nil || c.Account == nil { return "" } return *c.Account } // GetOkAccount returns a tuple with the Account field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChannelSlackRequest) GetAccountOk() (string, bool) { if c == nil || c.Account == nil { return "", false } return *c.Account, true } // HasAccount returns a boolean if a field has been set. func (c *ChannelSlackRequest) HasAccount() bool { if c != nil && c.Account != nil { return true } return false } // SetAccount allocates a new c.Account and returns the pointer to it. func (c *ChannelSlackRequest) SetAccount(v string) { c.Account = &v } // GetChannelName returns the ChannelName field if non-nil, zero value otherwise. func (c *ChannelSlackRequest) GetChannelName() string { if c == nil || c.ChannelName == nil { return "" } return *c.ChannelName } // GetOkChannelName returns a tuple with the ChannelName field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChannelSlackRequest) GetChannelNameOk() (string, bool) { if c == nil || c.ChannelName == nil { return "", false } return *c.ChannelName, true } // HasChannelName returns a boolean if a field has been set. func (c *ChannelSlackRequest) HasChannelName() bool { if c != nil && c.ChannelName != nil { return true } return false } // SetChannelName allocates a new c.ChannelName and returns the pointer to it. func (c *ChannelSlackRequest) SetChannelName(v string) { c.ChannelName = &v } // GetTransferAllUserComments returns the TransferAllUserComments field if non-nil, zero value otherwise. func (c *ChannelSlackRequest) GetTransferAllUserComments() bool { if c == nil || c.TransferAllUserComments == nil { return false } return *c.TransferAllUserComments } // GetOkTransferAllUserComments returns a tuple with the TransferAllUserComments field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChannelSlackRequest) GetTransferAllUserCommentsOk() (bool, bool) { if c == nil || c.TransferAllUserComments == nil { return false, false } return *c.TransferAllUserComments, true } // HasTransferAllUserComments returns a boolean if a field has been set. func (c *ChannelSlackRequest) HasTransferAllUserComments() bool { if c != nil && c.TransferAllUserComments != nil { return true } return false } // SetTransferAllUserComments allocates a new c.TransferAllUserComments and returns the pointer to it. func (c *ChannelSlackRequest) SetTransferAllUserComments(v bool) { c.TransferAllUserComments = &v } // GetCheck returns the Check field if non-nil, zero value otherwise. func (c *Check) GetCheck() string { if c == nil || c.Check == nil { return "" } return *c.Check } // GetOkCheck returns a tuple with the Check field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Check) GetCheckOk() (string, bool) { if c == nil || c.Check == nil { return "", false } return *c.Check, true } // HasCheck returns a boolean if a field has been set. func (c *Check) HasCheck() bool { if c != nil && c.Check != nil { return true } return false } // SetCheck allocates a new c.Check and returns the pointer to it. func (c *Check) SetCheck(v string) { c.Check = &v } // GetHostName returns the HostName field if non-nil, zero value otherwise. func (c *Check) GetHostName() string { if c == nil || c.HostName == nil { return "" } return *c.HostName } // GetOkHostName returns a tuple with the HostName field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Check) GetHostNameOk() (string, bool) { if c == nil || c.HostName == nil { return "", false } return *c.HostName, true } // HasHostName returns a boolean if a field has been set. func (c *Check) HasHostName() bool { if c != nil && c.HostName != nil { return true } return false } // SetHostName allocates a new c.HostName and returns the pointer to it. func (c *Check) SetHostName(v string) { c.HostName = &v } // GetMessage returns the Message field if non-nil, zero value otherwise. func (c *Check) GetMessage() string { if c == nil || c.Message == nil { return "" } return *c.Message } // GetOkMessage returns a tuple with the Message field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Check) GetMessageOk() (string, bool) { if c == nil || c.Message == nil { return "", false } return *c.Message, true } // HasMessage returns a boolean if a field has been set. func (c *Check) HasMessage() bool { if c != nil && c.Message != nil { return true } return false } // SetMessage allocates a new c.Message and returns the pointer to it. func (c *Check) SetMessage(v string) { c.Message = &v } // GetStatus returns the Status field if non-nil, zero value otherwise. func (c *Check) GetStatus() Status { if c == nil || c.Status == nil { return 0 } return *c.Status } // GetOkStatus returns a tuple with the Status field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Check) GetStatusOk() (Status, bool) { if c == nil || c.Status == nil { return 0, false } return *c.Status, true } // HasStatus returns a boolean if a field has been set. func (c *Check) HasStatus() bool { if c != nil && c.Status != nil { return true } return false } // SetStatus allocates a new c.Status and returns the pointer to it. func (c *Check) SetStatus(v Status) { c.Status = &v } // GetTimestamp returns the Timestamp field if non-nil, zero value otherwise. func (c *Check) GetTimestamp() string { if c == nil || c.Timestamp == nil { return "" } return *c.Timestamp } // GetOkTimestamp returns a tuple with the Timestamp field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Check) GetTimestampOk() (string, bool) { if c == nil || c.Timestamp == nil { return "", false } return *c.Timestamp, true } // HasTimestamp returns a boolean if a field has been set. func (c *Check) HasTimestamp() bool { if c != nil && c.Timestamp != nil { return true } return false } // SetTimestamp allocates a new c.Timestamp and returns the pointer to it. func (c *Check) SetTimestamp(v string) { c.Timestamp = &v } // GetHandle returns the Handle field if non-nil, zero value otherwise. func (c *Comment) GetHandle() string { if c == nil || c.Handle == nil { return "" } return *c.Handle } // GetOkHandle returns a tuple with the Handle field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Comment) GetHandleOk() (string, bool) { if c == nil || c.Handle == nil { return "", false } return *c.Handle, true } // HasHandle returns a boolean if a field has been set. func (c *Comment) HasHandle() bool { if c != nil && c.Handle != nil { return true } return false } // SetHandle allocates a new c.Handle and returns the pointer to it. func (c *Comment) SetHandle(v string) { c.Handle = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (c *Comment) GetId() int { if c == nil || c.Id == nil { return 0 } return *c.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Comment) GetIdOk() (int, bool) { if c == nil || c.Id == nil { return 0, false } return *c.Id, true } // HasId returns a boolean if a field has been set. func (c *Comment) HasId() bool { if c != nil && c.Id != nil { return true } return false } // SetId allocates a new c.Id and returns the pointer to it. func (c *Comment) SetId(v int) { c.Id = &v } // GetMessage returns the Message field if non-nil, zero value otherwise. func (c *Comment) GetMessage() string { if c == nil || c.Message == nil { return "" } return *c.Message } // GetOkMessage returns a tuple with the Message field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Comment) GetMessageOk() (string, bool) { if c == nil || c.Message == nil { return "", false } return *c.Message, true } // HasMessage returns a boolean if a field has been set. func (c *Comment) HasMessage() bool { if c != nil && c.Message != nil { return true } return false } // SetMessage allocates a new c.Message and returns the pointer to it. func (c *Comment) SetMessage(v string) { c.Message = &v } // GetRelatedId returns the RelatedId field if non-nil, zero value otherwise. func (c *Comment) GetRelatedId() int { if c == nil || c.RelatedId == nil { return 0 } return *c.RelatedId } // GetOkRelatedId returns a tuple with the RelatedId field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Comment) GetRelatedIdOk() (int, bool) { if c == nil || c.RelatedId == nil { return 0, false } return *c.RelatedId, true } // HasRelatedId returns a boolean if a field has been set. func (c *Comment) HasRelatedId() bool { if c != nil && c.RelatedId != nil { return true } return false } // SetRelatedId allocates a new c.RelatedId and returns the pointer to it. func (c *Comment) SetRelatedId(v int) { c.RelatedId = &v } // GetResource returns the Resource field if non-nil, zero value otherwise. func (c *Comment) GetResource() string { if c == nil || c.Resource == nil { return "" } return *c.Resource } // GetOkResource returns a tuple with the Resource field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Comment) GetResourceOk() (string, bool) { if c == nil || c.Resource == nil { return "", false } return *c.Resource, true } // HasResource returns a boolean if a field has been set. func (c *Comment) HasResource() bool { if c != nil && c.Resource != nil { return true } return false } // SetResource allocates a new c.Resource and returns the pointer to it. func (c *Comment) SetResource(v string) { c.Resource = &v } // GetUrl returns the Url field if non-nil, zero value otherwise. func (c *Comment) GetUrl() string { if c == nil || c.Url == nil { return "" } return *c.Url } // GetOkUrl returns a tuple with the Url field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Comment) GetUrlOk() (string, bool) { if c == nil || c.Url == nil { return "", false } return *c.Url, true } // HasUrl returns a boolean if a field has been set. func (c *Comment) HasUrl() bool { if c != nil && c.Url != nil { return true } return false } // SetUrl allocates a new c.Url and returns the pointer to it. func (c *Comment) SetUrl(v string) { c.Url = &v } // GetColor returns the Color field if non-nil, zero value otherwise. func (c *ConditionalFormat) GetColor() string { if c == nil || c.Color == nil { return "" } return *c.Color } // GetOkColor returns a tuple with the Color field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ConditionalFormat) GetColorOk() (string, bool) { if c == nil || c.Color == nil { return "", false } return *c.Color, true } // HasColor returns a boolean if a field has been set. func (c *ConditionalFormat) HasColor() bool { if c != nil && c.Color != nil { return true } return false } // SetColor allocates a new c.Color and returns the pointer to it. func (c *ConditionalFormat) SetColor(v string) { c.Color = &v } // GetComparator returns the Comparator field if non-nil, zero value otherwise. func (c *ConditionalFormat) GetComparator() string { if c == nil || c.Comparator == nil { return "" } return *c.Comparator } // GetOkComparator returns a tuple with the Comparator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ConditionalFormat) GetComparatorOk() (string, bool) { if c == nil || c.Comparator == nil { return "", false } return *c.Comparator, true } // HasComparator returns a boolean if a field has been set. func (c *ConditionalFormat) HasComparator() bool { if c != nil && c.Comparator != nil { return true } return false } // SetComparator allocates a new c.Comparator and returns the pointer to it. func (c *ConditionalFormat) SetComparator(v string) { c.Comparator = &v } // GetImageURL returns the ImageURL field if non-nil, zero value otherwise. func (c *ConditionalFormat) GetImageURL() string { if c == nil || c.ImageURL == nil { return "" } return *c.ImageURL } // GetOkImageURL returns a tuple with the ImageURL field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ConditionalFormat) GetImageURLOk() (string, bool) { if c == nil || c.ImageURL == nil { return "", false } return *c.ImageURL, true } // HasImageURL returns a boolean if a field has been set. func (c *ConditionalFormat) HasImageURL() bool { if c != nil && c.ImageURL != nil { return true } return false } // SetImageURL allocates a new c.ImageURL and returns the pointer to it. func (c *ConditionalFormat) SetImageURL(v string) { c.ImageURL = &v } // GetInvert returns the Invert field if non-nil, zero value otherwise. func (c *ConditionalFormat) GetInvert() bool { if c == nil || c.Invert == nil { return false } return *c.Invert } // GetOkInvert returns a tuple with the Invert field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ConditionalFormat) GetInvertOk() (bool, bool) { if c == nil || c.Invert == nil { return false, false } return *c.Invert, true } // HasInvert returns a boolean if a field has been set. func (c *ConditionalFormat) HasInvert() bool { if c != nil && c.Invert != nil { return true } return false } // SetInvert allocates a new c.Invert and returns the pointer to it. func (c *ConditionalFormat) SetInvert(v bool) { c.Invert = &v } // GetPalette returns the Palette field if non-nil, zero value otherwise. func (c *ConditionalFormat) GetPalette() string { if c == nil || c.Palette == nil { return "" } return *c.Palette } // GetOkPalette returns a tuple with the Palette field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ConditionalFormat) GetPaletteOk() (string, bool) { if c == nil || c.Palette == nil { return "", false } return *c.Palette, true } // HasPalette returns a boolean if a field has been set. func (c *ConditionalFormat) HasPalette() bool { if c != nil && c.Palette != nil { return true } return false } // SetPalette allocates a new c.Palette and returns the pointer to it. func (c *ConditionalFormat) SetPalette(v string) { c.Palette = &v } // GetValue returns the Value field if non-nil, zero value otherwise. func (c *ConditionalFormat) GetValue() string { if c == nil || c.Value == nil { return "" } return *c.Value } // GetOkValue returns a tuple with the Value field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ConditionalFormat) GetValueOk() (string, bool) { if c == nil || c.Value == nil { return "", false } return *c.Value, true } // HasValue returns a boolean if a field has been set. func (c *ConditionalFormat) HasValue() bool { if c != nil && c.Value != nil { return true } return false } // SetValue allocates a new c.Value and returns the pointer to it. func (c *ConditionalFormat) SetValue(v string) { c.Value = &v } // GetEmail returns the Email field if non-nil, zero value otherwise. func (c *Creator) GetEmail() string { if c == nil || c.Email == nil { return "" } return *c.Email } // GetOkEmail returns a tuple with the Email field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Creator) GetEmailOk() (string, bool) { if c == nil || c.Email == nil { return "", false } return *c.Email, true } // HasEmail returns a boolean if a field has been set. func (c *Creator) HasEmail() bool { if c != nil && c.Email != nil { return true } return false } // SetEmail allocates a new c.Email and returns the pointer to it. func (c *Creator) SetEmail(v string) { c.Email = &v } // GetHandle returns the Handle field if non-nil, zero value otherwise. func (c *Creator) GetHandle() string { if c == nil || c.Handle == nil { return "" } return *c.Handle } // GetOkHandle returns a tuple with the Handle field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Creator) GetHandleOk() (string, bool) { if c == nil || c.Handle == nil { return "", false } return *c.Handle, true } // HasHandle returns a boolean if a field has been set. func (c *Creator) HasHandle() bool { if c != nil && c.Handle != nil { return true } return false } // SetHandle allocates a new c.Handle and returns the pointer to it. func (c *Creator) SetHandle(v string) { c.Handle = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (c *Creator) GetId() int { if c == nil || c.Id == nil { return 0 } return *c.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Creator) GetIdOk() (int, bool) { if c == nil || c.Id == nil { return 0, false } return *c.Id, true } // HasId returns a boolean if a field has been set. func (c *Creator) HasId() bool { if c != nil && c.Id != nil { return true } return false } // SetId allocates a new c.Id and returns the pointer to it. func (c *Creator) SetId(v int) { c.Id = &v } // GetName returns the Name field if non-nil, zero value otherwise. func (c *Creator) GetName() string { if c == nil || c.Name == nil { return "" } return *c.Name } // GetOkName returns a tuple with the Name field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Creator) GetNameOk() (string, bool) { if c == nil || c.Name == nil { return "", false } return *c.Name, true } // HasName returns a boolean if a field has been set. func (c *Creator) HasName() bool { if c != nil && c.Name != nil { return true } return false } // SetName allocates a new c.Name and returns the pointer to it. func (c *Creator) SetName(v string) { c.Name = &v } // GetDescription returns the Description field if non-nil, zero value otherwise. func (d *Dashboard) GetDescription() string { if d == nil || d.Description == nil { return "" } return *d.Description } // GetOkDescription returns a tuple with the Description field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Dashboard) GetDescriptionOk() (string, bool) { if d == nil || d.Description == nil { return "", false } return *d.Description, true } // HasDescription returns a boolean if a field has been set. func (d *Dashboard) HasDescription() bool { if d != nil && d.Description != nil { return true } return false } // SetDescription allocates a new d.Description and returns the pointer to it. func (d *Dashboard) SetDescription(v string) { d.Description = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (d *Dashboard) GetId() int { if d == nil || d.Id == nil { return 0 } return *d.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Dashboard) GetIdOk() (int, bool) { if d == nil || d.Id == nil { return 0, false } return *d.Id, true } // HasId returns a boolean if a field has been set. func (d *Dashboard) HasId() bool { if d != nil && d.Id != nil { return true } return false } // SetId allocates a new d.Id and returns the pointer to it. func (d *Dashboard) SetId(v int) { d.Id = &v } // GetReadOnly returns the ReadOnly field if non-nil, zero value otherwise. func (d *Dashboard) GetReadOnly() bool { if d == nil || d.ReadOnly == nil { return false } return *d.ReadOnly } // GetOkReadOnly returns a tuple with the ReadOnly field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Dashboard) GetReadOnlyOk() (bool, bool) { if d == nil || d.ReadOnly == nil { return false, false } return *d.ReadOnly, true } // HasReadOnly returns a boolean if a field has been set. func (d *Dashboard) HasReadOnly() bool { if d != nil && d.ReadOnly != nil { return true } return false } // SetReadOnly allocates a new d.ReadOnly and returns the pointer to it. func (d *Dashboard) SetReadOnly(v bool) { d.ReadOnly = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (d *Dashboard) GetTitle() string { if d == nil || d.Title == nil { return "" } return *d.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Dashboard) GetTitleOk() (string, bool) { if d == nil || d.Title == nil { return "", false } return *d.Title, true } // HasTitle returns a boolean if a field has been set. func (d *Dashboard) HasTitle() bool { if d != nil && d.Title != nil { return true } return false } // SetTitle allocates a new d.Title and returns the pointer to it. func (d *Dashboard) SetTitle(v string) { d.Title = &v } // GetComparator returns the Comparator field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetComparator() string { if d == nil || d.Comparator == nil { return "" } return *d.Comparator } // GetOkComparator returns a tuple with the Comparator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetComparatorOk() (string, bool) { if d == nil || d.Comparator == nil { return "", false } return *d.Comparator, true } // HasComparator returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasComparator() bool { if d != nil && d.Comparator != nil { return true } return false } // SetComparator allocates a new d.Comparator and returns the pointer to it. func (d *DashboardConditionalFormat) SetComparator(v string) { d.Comparator = &v } // GetCustomBgColor returns the CustomBgColor field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetCustomBgColor() string { if d == nil || d.CustomBgColor == nil { return "" } return *d.CustomBgColor } // GetOkCustomBgColor returns a tuple with the CustomBgColor field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetCustomBgColorOk() (string, bool) { if d == nil || d.CustomBgColor == nil { return "", false } return *d.CustomBgColor, true } // HasCustomBgColor returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasCustomBgColor() bool { if d != nil && d.CustomBgColor != nil { return true } return false } // SetCustomBgColor allocates a new d.CustomBgColor and returns the pointer to it. func (d *DashboardConditionalFormat) SetCustomBgColor(v string) { d.CustomBgColor = &v } // GetCustomFgColor returns the CustomFgColor field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetCustomFgColor() string { if d == nil || d.CustomFgColor == nil { return "" } return *d.CustomFgColor } // GetOkCustomFgColor returns a tuple with the CustomFgColor field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetCustomFgColorOk() (string, bool) { if d == nil || d.CustomFgColor == nil { return "", false } return *d.CustomFgColor, true } // HasCustomFgColor returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasCustomFgColor() bool { if d != nil && d.CustomFgColor != nil { return true } return false } // SetCustomFgColor allocates a new d.CustomFgColor and returns the pointer to it. func (d *DashboardConditionalFormat) SetCustomFgColor(v string) { d.CustomFgColor = &v } // GetCustomImageUrl returns the CustomImageUrl field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetCustomImageUrl() string { if d == nil || d.CustomImageUrl == nil { return "" } return *d.CustomImageUrl } // GetOkCustomImageUrl returns a tuple with the CustomImageUrl field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetCustomImageUrlOk() (string, bool) { if d == nil || d.CustomImageUrl == nil { return "", false } return *d.CustomImageUrl, true } // HasCustomImageUrl returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasCustomImageUrl() bool { if d != nil && d.CustomImageUrl != nil { return true } return false } // SetCustomImageUrl allocates a new d.CustomImageUrl and returns the pointer to it. func (d *DashboardConditionalFormat) SetCustomImageUrl(v string) { d.CustomImageUrl = &v } // GetInverted returns the Inverted field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetInverted() bool { if d == nil || d.Inverted == nil { return false } return *d.Inverted } // GetOkInverted returns a tuple with the Inverted field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetInvertedOk() (bool, bool) { if d == nil || d.Inverted == nil { return false, false } return *d.Inverted, true } // HasInverted returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasInverted() bool { if d != nil && d.Inverted != nil { return true } return false } // SetInverted allocates a new d.Inverted and returns the pointer to it. func (d *DashboardConditionalFormat) SetInverted(v bool) { d.Inverted = &v } // GetPalette returns the Palette field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetPalette() string { if d == nil || d.Palette == nil { return "" } return *d.Palette } // GetOkPalette returns a tuple with the Palette field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetPaletteOk() (string, bool) { if d == nil || d.Palette == nil { return "", false } return *d.Palette, true } // HasPalette returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasPalette() bool { if d != nil && d.Palette != nil { return true } return false } // SetPalette allocates a new d.Palette and returns the pointer to it. func (d *DashboardConditionalFormat) SetPalette(v string) { d.Palette = &v } // GetValue returns the Value field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetValue() json.Number { if d == nil || d.Value == nil { return "" } return *d.Value } // GetOkValue returns a tuple with the Value field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetValueOk() (json.Number, bool) { if d == nil || d.Value == nil { return "", false } return *d.Value, true } // HasValue returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasValue() bool { if d != nil && d.Value != nil { return true } return false } // SetValue allocates a new d.Value and returns the pointer to it. func (d *DashboardConditionalFormat) SetValue(v json.Number) { d.Value = &v } // GetDashboardCount returns the DashboardCount field if non-nil, zero value otherwise. func (d *DashboardList) GetDashboardCount() int { if d == nil || d.DashboardCount == nil { return 0 } return *d.DashboardCount } // GetOkDashboardCount returns a tuple with the DashboardCount field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardList) GetDashboardCountOk() (int, bool) { if d == nil || d.DashboardCount == nil { return 0, false } return *d.DashboardCount, true } // HasDashboardCount returns a boolean if a field has been set. func (d *DashboardList) HasDashboardCount() bool { if d != nil && d.DashboardCount != nil { return true } return false } // SetDashboardCount allocates a new d.DashboardCount and returns the pointer to it. func (d *DashboardList) SetDashboardCount(v int) { d.DashboardCount = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (d *DashboardList) GetId() int { if d == nil || d.Id == nil { return 0 } return *d.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardList) GetIdOk() (int, bool) { if d == nil || d.Id == nil { return 0, false } return *d.Id, true } // HasId returns a boolean if a field has been set. func (d *DashboardList) HasId() bool { if d != nil && d.Id != nil { return true } return false } // SetId allocates a new d.Id and returns the pointer to it. func (d *DashboardList) SetId(v int) { d.Id = &v } // GetName returns the Name field if non-nil, zero value otherwise. func (d *DashboardList) GetName() string { if d == nil || d.Name == nil { return "" } return *d.Name } // GetOkName returns a tuple with the Name field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardList) GetNameOk() (string, bool) { if d == nil || d.Name == nil { return "", false } return *d.Name, true } // HasName returns a boolean if a field has been set. func (d *DashboardList) HasName() bool { if d != nil && d.Name != nil { return true } return false } // SetName allocates a new d.Name and returns the pointer to it. func (d *DashboardList) SetName(v string) { d.Name = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (d *DashboardListItem) GetId() int { if d == nil || d.Id == nil { return 0 } return *d.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardListItem) GetIdOk() (int, bool) { if d == nil || d.Id == nil { return 0, false } return *d.Id, true } // HasId returns a boolean if a field has been set. func (d *DashboardListItem) HasId() bool { if d != nil && d.Id != nil { return true } return false } // SetId allocates a new d.Id and returns the pointer to it. func (d *DashboardListItem) SetId(v int) { d.Id = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (d *DashboardListItem) GetType() string { if d == nil || d.Type == nil { return "" } return *d.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardListItem) GetTypeOk() (string, bool) { if d == nil || d.Type == nil { return "", false } return *d.Type, true } // HasType returns a boolean if a field has been set. func (d *DashboardListItem) HasType() bool { if d != nil && d.Type != nil { return true } return false } // SetType allocates a new d.Type and returns the pointer to it. func (d *DashboardListItem) SetType(v string) { d.Type = &v } // GetDescription returns the Description field if non-nil, zero value otherwise. func (d *DashboardLite) GetDescription() string { if d == nil || d.Description == nil { return "" } return *d.Description } // GetOkDescription returns a tuple with the Description field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardLite) GetDescriptionOk() (string, bool) { if d == nil || d.Description == nil { return "", false } return *d.Description, true } // HasDescription returns a boolean if a field has been set. func (d *DashboardLite) HasDescription() bool { if d != nil && d.Description != nil { return true } return false } // SetDescription allocates a new d.Description and returns the pointer to it. func (d *DashboardLite) SetDescription(v string) { d.Description = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (d *DashboardLite) GetId() int { if d == nil || d.Id == nil { return 0 } return *d.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardLite) GetIdOk() (int, bool) { if d == nil || d.Id == nil { return 0, false } return *d.Id, true } // HasId returns a boolean if a field has been set. func (d *DashboardLite) HasId() bool { if d != nil && d.Id != nil { return true } return false } // SetId allocates a new d.Id and returns the pointer to it. func (d *DashboardLite) SetId(v int) { d.Id = &v } // GetResource returns the Resource field if non-nil, zero value otherwise. func (d *DashboardLite) GetResource() string { if d == nil || d.Resource == nil { return "" } return *d.Resource } // GetOkResource returns a tuple with the Resource field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardLite) GetResourceOk() (string, bool) { if d == nil || d.Resource == nil { return "", false } return *d.Resource, true } // HasResource returns a boolean if a field has been set. func (d *DashboardLite) HasResource() bool { if d != nil && d.Resource != nil { return true } return false } // SetResource allocates a new d.Resource and returns the pointer to it. func (d *DashboardLite) SetResource(v string) { d.Resource = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (d *DashboardLite) GetTitle() string { if d == nil || d.Title == nil { return "" } return *d.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardLite) GetTitleOk() (string, bool) { if d == nil || d.Title == nil { return "", false } return *d.Title, true } // HasTitle returns a boolean if a field has been set. func (d *DashboardLite) HasTitle() bool { if d != nil && d.Title != nil { return true } return false } // SetTitle allocates a new d.Title and returns the pointer to it. func (d *DashboardLite) SetTitle(v string) { d.Title = &v } // GetActive returns the Active field if non-nil, zero value otherwise. func (d *Downtime) GetActive() bool { if d == nil || d.Active == nil { return false } return *d.Active } // GetOkActive returns a tuple with the Active field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetActiveOk() (bool, bool) { if d == nil || d.Active == nil { return false, false } return *d.Active, true } // HasActive returns a boolean if a field has been set. func (d *Downtime) HasActive() bool { if d != nil && d.Active != nil { return true } return false } // SetActive allocates a new d.Active and returns the pointer to it. func (d *Downtime) SetActive(v bool) { d.Active = &v } // GetCanceled returns the Canceled field if non-nil, zero value otherwise. func (d *Downtime) GetCanceled() int { if d == nil || d.Canceled == nil { return 0 } return *d.Canceled } // GetOkCanceled returns a tuple with the Canceled field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetCanceledOk() (int, bool) { if d == nil || d.Canceled == nil { return 0, false } return *d.Canceled, true } // HasCanceled returns a boolean if a field has been set. func (d *Downtime) HasCanceled() bool { if d != nil && d.Canceled != nil { return true } return false } // SetCanceled allocates a new d.Canceled and returns the pointer to it. func (d *Downtime) SetCanceled(v int) { d.Canceled = &v } // GetDisabled returns the Disabled field if non-nil, zero value otherwise. func (d *Downtime) GetDisabled() bool { if d == nil || d.Disabled == nil { return false } return *d.Disabled } // GetOkDisabled returns a tuple with the Disabled field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetDisabledOk() (bool, bool) { if d == nil || d.Disabled == nil { return false, false } return *d.Disabled, true } // HasDisabled returns a boolean if a field has been set. func (d *Downtime) HasDisabled() bool { if d != nil && d.Disabled != nil { return true } return false } // SetDisabled allocates a new d.Disabled and returns the pointer to it. func (d *Downtime) SetDisabled(v bool) { d.Disabled = &v } // GetEnd returns the End field if non-nil, zero value otherwise. func (d *Downtime) GetEnd() int { if d == nil || d.End == nil { return 0 } return *d.End } // GetOkEnd returns a tuple with the End field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetEndOk() (int, bool) { if d == nil || d.End == nil { return 0, false } return *d.End, true } // HasEnd returns a boolean if a field has been set. func (d *Downtime) HasEnd() bool { if d != nil && d.End != nil { return true } return false } // SetEnd allocates a new d.End and returns the pointer to it. func (d *Downtime) SetEnd(v int) { d.End = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (d *Downtime) GetId() int { if d == nil || d.Id == nil { return 0 } return *d.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetIdOk() (int, bool) { if d == nil || d.Id == nil { return 0, false } return *d.Id, true } // HasId returns a boolean if a field has been set. func (d *Downtime) HasId() bool { if d != nil && d.Id != nil { return true } return false } // SetId allocates a new d.Id and returns the pointer to it. func (d *Downtime) SetId(v int) { d.Id = &v } // GetMessage returns the Message field if non-nil, zero value otherwise. func (d *Downtime) GetMessage() string { if d == nil || d.Message == nil { return "" } return *d.Message } // GetOkMessage returns a tuple with the Message field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetMessageOk() (string, bool) { if d == nil || d.Message == nil { return "", false } return *d.Message, true } // HasMessage returns a boolean if a field has been set. func (d *Downtime) HasMessage() bool { if d != nil && d.Message != nil { return true } return false } // SetMessage allocates a new d.Message and returns the pointer to it. func (d *Downtime) SetMessage(v string) { d.Message = &v } // GetMonitorId returns the MonitorId field if non-nil, zero value otherwise. func (d *Downtime) GetMonitorId() int { if d == nil || d.MonitorId == nil { return 0 } return *d.MonitorId } // GetOkMonitorId returns a tuple with the MonitorId field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetMonitorIdOk() (int, bool) { if d == nil || d.MonitorId == nil { return 0, false } return *d.MonitorId, true } // HasMonitorId returns a boolean if a field has been set. func (d *Downtime) HasMonitorId() bool { if d != nil && d.MonitorId != nil { return true } return false } // SetMonitorId allocates a new d.MonitorId and returns the pointer to it. func (d *Downtime) SetMonitorId(v int) { d.MonitorId = &v } // GetRecurrence returns the Recurrence field if non-nil, zero value otherwise. func (d *Downtime) GetRecurrence() Recurrence { if d == nil || d.Recurrence == nil { return Recurrence{} } return *d.Recurrence } // GetOkRecurrence returns a tuple with the Recurrence field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetRecurrenceOk() (Recurrence, bool) { if d == nil || d.Recurrence == nil { return Recurrence{}, false } return *d.Recurrence, true } // HasRecurrence returns a boolean if a field has been set. func (d *Downtime) HasRecurrence() bool { if d != nil && d.Recurrence != nil { return true } return false } // SetRecurrence allocates a new d.Recurrence and returns the pointer to it. func (d *Downtime) SetRecurrence(v Recurrence) { d.Recurrence = &v } // GetStart returns the Start field if non-nil, zero value otherwise. func (d *Downtime) GetStart() int { if d == nil || d.Start == nil { return 0 } return *d.Start } // GetOkStart returns a tuple with the Start field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetStartOk() (int, bool) { if d == nil || d.Start == nil { return 0, false } return *d.Start, true } // HasStart returns a boolean if a field has been set. func (d *Downtime) HasStart() bool { if d != nil && d.Start != nil { return true } return false } // SetStart allocates a new d.Start and returns the pointer to it. func (d *Downtime) SetStart(v int) { d.Start = &v } // GetAggregation returns the Aggregation field if non-nil, zero value otherwise. func (e *Event) GetAggregation() string { if e == nil || e.Aggregation == nil { return "" } return *e.Aggregation } // GetOkAggregation returns a tuple with the Aggregation field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetAggregationOk() (string, bool) { if e == nil || e.Aggregation == nil { return "", false } return *e.Aggregation, true } // HasAggregation returns a boolean if a field has been set. func (e *Event) HasAggregation() bool { if e != nil && e.Aggregation != nil { return true } return false } // SetAggregation allocates a new e.Aggregation and returns the pointer to it. func (e *Event) SetAggregation(v string) { e.Aggregation = &v } // GetAlertType returns the AlertType field if non-nil, zero value otherwise. func (e *Event) GetAlertType() string { if e == nil || e.AlertType == nil { return "" } return *e.AlertType } // GetOkAlertType returns a tuple with the AlertType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetAlertTypeOk() (string, bool) { if e == nil || e.AlertType == nil { return "", false } return *e.AlertType, true } // HasAlertType returns a boolean if a field has been set. func (e *Event) HasAlertType() bool { if e != nil && e.AlertType != nil { return true } return false } // SetAlertType allocates a new e.AlertType and returns the pointer to it. func (e *Event) SetAlertType(v string) { e.AlertType = &v } // GetEventType returns the EventType field if non-nil, zero value otherwise. func (e *Event) GetEventType() string { if e == nil || e.EventType == nil { return "" } return *e.EventType } // GetOkEventType returns a tuple with the EventType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetEventTypeOk() (string, bool) { if e == nil || e.EventType == nil { return "", false } return *e.EventType, true } // HasEventType returns a boolean if a field has been set. func (e *Event) HasEventType() bool { if e != nil && e.EventType != nil { return true } return false } // SetEventType allocates a new e.EventType and returns the pointer to it. func (e *Event) SetEventType(v string) { e.EventType = &v } // GetHost returns the Host field if non-nil, zero value otherwise. func (e *Event) GetHost() string { if e == nil || e.Host == nil { return "" } return *e.Host } // GetOkHost returns a tuple with the Host field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetHostOk() (string, bool) { if e == nil || e.Host == nil { return "", false } return *e.Host, true } // HasHost returns a boolean if a field has been set. func (e *Event) HasHost() bool { if e != nil && e.Host != nil { return true } return false } // SetHost allocates a new e.Host and returns the pointer to it. func (e *Event) SetHost(v string) { e.Host = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (e *Event) GetId() int { if e == nil || e.Id == nil { return 0 } return *e.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetIdOk() (int, bool) { if e == nil || e.Id == nil { return 0, false } return *e.Id, true } // HasId returns a boolean if a field has been set. func (e *Event) HasId() bool { if e != nil && e.Id != nil { return true } return false } // SetId allocates a new e.Id and returns the pointer to it. func (e *Event) SetId(v int) { e.Id = &v } // GetPriority returns the Priority field if non-nil, zero value otherwise. func (e *Event) GetPriority() string { if e == nil || e.Priority == nil { return "" } return *e.Priority } // GetOkPriority returns a tuple with the Priority field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetPriorityOk() (string, bool) { if e == nil || e.Priority == nil { return "", false } return *e.Priority, true } // HasPriority returns a boolean if a field has been set. func (e *Event) HasPriority() bool { if e != nil && e.Priority != nil { return true } return false } // SetPriority allocates a new e.Priority and returns the pointer to it. func (e *Event) SetPriority(v string) { e.Priority = &v } // GetResource returns the Resource field if non-nil, zero value otherwise. func (e *Event) GetResource() string { if e == nil || e.Resource == nil { return "" } return *e.Resource } // GetOkResource returns a tuple with the Resource field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetResourceOk() (string, bool) { if e == nil || e.Resource == nil { return "", false } return *e.Resource, true } // HasResource returns a boolean if a field has been set. func (e *Event) HasResource() bool { if e != nil && e.Resource != nil { return true } return false } // SetResource allocates a new e.Resource and returns the pointer to it. func (e *Event) SetResource(v string) { e.Resource = &v } // GetSourceType returns the SourceType field if non-nil, zero value otherwise. func (e *Event) GetSourceType() string { if e == nil || e.SourceType == nil { return "" } return *e.SourceType } // GetOkSourceType returns a tuple with the SourceType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetSourceTypeOk() (string, bool) { if e == nil || e.SourceType == nil { return "", false } return *e.SourceType, true } // HasSourceType returns a boolean if a field has been set. func (e *Event) HasSourceType() bool { if e != nil && e.SourceType != nil { return true } return false } // SetSourceType allocates a new e.SourceType and returns the pointer to it. func (e *Event) SetSourceType(v string) { e.SourceType = &v } // GetText returns the Text field if non-nil, zero value otherwise. func (e *Event) GetText() string { if e == nil || e.Text == nil { return "" } return *e.Text } // GetOkText returns a tuple with the Text field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetTextOk() (string, bool) { if e == nil || e.Text == nil { return "", false } return *e.Text, true } // HasText returns a boolean if a field has been set. func (e *Event) HasText() bool { if e != nil && e.Text != nil { return true } return false } // SetText allocates a new e.Text and returns the pointer to it. func (e *Event) SetText(v string) { e.Text = &v } // GetTime returns the Time field if non-nil, zero value otherwise. func (e *Event) GetTime() int { if e == nil || e.Time == nil { return 0 } return *e.Time } // GetOkTime returns a tuple with the Time field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetTimeOk() (int, bool) { if e == nil || e.Time == nil { return 0, false } return *e.Time, true } // HasTime returns a boolean if a field has been set. func (e *Event) HasTime() bool { if e != nil && e.Time != nil { return true } return false } // SetTime allocates a new e.Time and returns the pointer to it. func (e *Event) SetTime(v int) { e.Time = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (e *Event) GetTitle() string { if e == nil || e.Title == nil { return "" } return *e.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetTitleOk() (string, bool) { if e == nil || e.Title == nil { return "", false } return *e.Title, true } // HasTitle returns a boolean if a field has been set. func (e *Event) HasTitle() bool { if e != nil && e.Title != nil { return true } return false } // SetTitle allocates a new e.Title and returns the pointer to it. func (e *Event) SetTitle(v string) { e.Title = &v } // GetUrl returns the Url field if non-nil, zero value otherwise. func (e *Event) GetUrl() string { if e == nil || e.Url == nil { return "" } return *e.Url } // GetOkUrl returns a tuple with the Url field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetUrlOk() (string, bool) { if e == nil || e.Url == nil { return "", false } return *e.Url, true } // HasUrl returns a boolean if a field has been set. func (e *Event) HasUrl() bool { if e != nil && e.Url != nil { return true } return false } // SetUrl allocates a new e.Url and returns the pointer to it. func (e *Event) SetUrl(v string) { e.Url = &v } // GetDefinition returns the Definition field if non-nil, zero value otherwise. func (g *Graph) GetDefinition() GraphDefinition { if g == nil || g.Definition == nil { return GraphDefinition{} } return *g.Definition } // GetOkDefinition returns a tuple with the Definition field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *Graph) GetDefinitionOk() (GraphDefinition, bool) { if g == nil || g.Definition == nil { return GraphDefinition{}, false } return *g.Definition, true } // HasDefinition returns a boolean if a field has been set. func (g *Graph) HasDefinition() bool { if g != nil && g.Definition != nil { return true } return false } // SetDefinition allocates a new g.Definition and returns the pointer to it. func (g *Graph) SetDefinition(v GraphDefinition) { g.Definition = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (g *Graph) GetTitle() string { if g == nil || g.Title == nil { return "" } return *g.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *Graph) GetTitleOk() (string, bool) { if g == nil || g.Title == nil { return "", false } return *g.Title, true } // HasTitle returns a boolean if a field has been set. func (g *Graph) HasTitle() bool { if g != nil && g.Title != nil { return true } return false } // SetTitle allocates a new g.Title and returns the pointer to it. func (g *Graph) SetTitle(v string) { g.Title = &v } // GetAutoscale returns the Autoscale field if non-nil, zero value otherwise. func (g *GraphDefinition) GetAutoscale() bool { if g == nil || g.Autoscale == nil { return false } return *g.Autoscale } // GetOkAutoscale returns a tuple with the Autoscale field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetAutoscaleOk() (bool, bool) { if g == nil || g.Autoscale == nil { return false, false } return *g.Autoscale, true } // HasAutoscale returns a boolean if a field has been set. func (g *GraphDefinition) HasAutoscale() bool { if g != nil && g.Autoscale != nil { return true } return false } // SetAutoscale allocates a new g.Autoscale and returns the pointer to it. func (g *GraphDefinition) SetAutoscale(v bool) { g.Autoscale = &v } // GetCustomUnit returns the CustomUnit field if non-nil, zero value otherwise. func (g *GraphDefinition) GetCustomUnit() string { if g == nil || g.CustomUnit == nil { return "" } return *g.CustomUnit } // GetOkCustomUnit returns a tuple with the CustomUnit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetCustomUnitOk() (string, bool) { if g == nil || g.CustomUnit == nil { return "", false } return *g.CustomUnit, true } // HasCustomUnit returns a boolean if a field has been set. func (g *GraphDefinition) HasCustomUnit() bool { if g != nil && g.CustomUnit != nil { return true } return false } // SetCustomUnit allocates a new g.CustomUnit and returns the pointer to it. func (g *GraphDefinition) SetCustomUnit(v string) { g.CustomUnit = &v } // GetIncludeNoMetricHosts returns the IncludeNoMetricHosts field if non-nil, zero value otherwise. func (g *GraphDefinition) GetIncludeNoMetricHosts() bool { if g == nil || g.IncludeNoMetricHosts == nil { return false } return *g.IncludeNoMetricHosts } // GetOkIncludeNoMetricHosts returns a tuple with the IncludeNoMetricHosts field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetIncludeNoMetricHostsOk() (bool, bool) { if g == nil || g.IncludeNoMetricHosts == nil { return false, false } return *g.IncludeNoMetricHosts, true } // HasIncludeNoMetricHosts returns a boolean if a field has been set. func (g *GraphDefinition) HasIncludeNoMetricHosts() bool { if g != nil && g.IncludeNoMetricHosts != nil { return true } return false } // SetIncludeNoMetricHosts allocates a new g.IncludeNoMetricHosts and returns the pointer to it. func (g *GraphDefinition) SetIncludeNoMetricHosts(v bool) { g.IncludeNoMetricHosts = &v } // GetIncludeUngroupedHosts returns the IncludeUngroupedHosts field if non-nil, zero value otherwise. func (g *GraphDefinition) GetIncludeUngroupedHosts() bool { if g == nil || g.IncludeUngroupedHosts == nil { return false } return *g.IncludeUngroupedHosts } // GetOkIncludeUngroupedHosts returns a tuple with the IncludeUngroupedHosts field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetIncludeUngroupedHostsOk() (bool, bool) { if g == nil || g.IncludeUngroupedHosts == nil { return false, false } return *g.IncludeUngroupedHosts, true } // HasIncludeUngroupedHosts returns a boolean if a field has been set. func (g *GraphDefinition) HasIncludeUngroupedHosts() bool { if g != nil && g.IncludeUngroupedHosts != nil { return true } return false } // SetIncludeUngroupedHosts allocates a new g.IncludeUngroupedHosts and returns the pointer to it. func (g *GraphDefinition) SetIncludeUngroupedHosts(v bool) { g.IncludeUngroupedHosts = &v } // GetPrecision returns the Precision field if non-nil, zero value otherwise. func (g *GraphDefinition) GetPrecision() string { if g == nil || g.Precision == nil { return "" } return *g.Precision } // GetOkPrecision returns a tuple with the Precision field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetPrecisionOk() (string, bool) { if g == nil || g.Precision == nil { return "", false } return *g.Precision, true } // HasPrecision returns a boolean if a field has been set. func (g *GraphDefinition) HasPrecision() bool { if g != nil && g.Precision != nil { return true } return false } // SetPrecision allocates a new g.Precision and returns the pointer to it. func (g *GraphDefinition) SetPrecision(v string) { g.Precision = &v } // GetStyle returns the Style field if non-nil, zero value otherwise. func (g *GraphDefinition) GetStyle() Style { if g == nil || g.Style == nil { return Style{} } return *g.Style } // GetOkStyle returns a tuple with the Style field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetStyleOk() (Style, bool) { if g == nil || g.Style == nil { return Style{}, false } return *g.Style, true } // HasStyle returns a boolean if a field has been set. func (g *GraphDefinition) HasStyle() bool { if g != nil && g.Style != nil { return true } return false } // SetStyle allocates a new g.Style and returns the pointer to it. func (g *GraphDefinition) SetStyle(v Style) { g.Style = &v } // GetTextAlign returns the TextAlign field if non-nil, zero value otherwise. func (g *GraphDefinition) GetTextAlign() string { if g == nil || g.TextAlign == nil { return "" } return *g.TextAlign } // GetOkTextAlign returns a tuple with the TextAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetTextAlignOk() (string, bool) { if g == nil || g.TextAlign == nil { return "", false } return *g.TextAlign, true } // HasTextAlign returns a boolean if a field has been set. func (g *GraphDefinition) HasTextAlign() bool { if g != nil && g.TextAlign != nil { return true } return false } // SetTextAlign allocates a new g.TextAlign and returns the pointer to it. func (g *GraphDefinition) SetTextAlign(v string) { g.TextAlign = &v } // GetViz returns the Viz field if non-nil, zero value otherwise. func (g *GraphDefinition) GetViz() string { if g == nil || g.Viz == nil { return "" } return *g.Viz } // GetOkViz returns a tuple with the Viz field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetVizOk() (string, bool) { if g == nil || g.Viz == nil { return "", false } return *g.Viz, true } // HasViz returns a boolean if a field has been set. func (g *GraphDefinition) HasViz() bool { if g != nil && g.Viz != nil { return true } return false } // SetViz allocates a new g.Viz and returns the pointer to it. func (g *GraphDefinition) SetViz(v string) { g.Viz = &v } // GetLabel returns the Label field if non-nil, zero value otherwise. func (g *GraphDefinitionMarker) GetLabel() string { if g == nil || g.Label == nil { return "" } return *g.Label } // GetOkLabel returns a tuple with the Label field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionMarker) GetLabelOk() (string, bool) { if g == nil || g.Label == nil { return "", false } return *g.Label, true } // HasLabel returns a boolean if a field has been set. func (g *GraphDefinitionMarker) HasLabel() bool { if g != nil && g.Label != nil { return true } return false } // SetLabel allocates a new g.Label and returns the pointer to it. func (g *GraphDefinitionMarker) SetLabel(v string) { g.Label = &v } // GetMax returns the Max field if non-nil, zero value otherwise. func (g *GraphDefinitionMarker) GetMax() json.Number { if g == nil || g.Max == nil { return "" } return *g.Max } // GetOkMax returns a tuple with the Max field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionMarker) GetMaxOk() (json.Number, bool) { if g == nil || g.Max == nil { return "", false } return *g.Max, true } // HasMax returns a boolean if a field has been set. func (g *GraphDefinitionMarker) HasMax() bool { if g != nil && g.Max != nil { return true } return false } // SetMax allocates a new g.Max and returns the pointer to it. func (g *GraphDefinitionMarker) SetMax(v json.Number) { g.Max = &v } // GetMin returns the Min field if non-nil, zero value otherwise. func (g *GraphDefinitionMarker) GetMin() json.Number { if g == nil || g.Min == nil { return "" } return *g.Min } // GetOkMin returns a tuple with the Min field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionMarker) GetMinOk() (json.Number, bool) { if g == nil || g.Min == nil { return "", false } return *g.Min, true } // HasMin returns a boolean if a field has been set. func (g *GraphDefinitionMarker) HasMin() bool { if g != nil && g.Min != nil { return true } return false } // SetMin allocates a new g.Min and returns the pointer to it. func (g *GraphDefinitionMarker) SetMin(v json.Number) { g.Min = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (g *GraphDefinitionMarker) GetType() string { if g == nil || g.Type == nil { return "" } return *g.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionMarker) GetTypeOk() (string, bool) { if g == nil || g.Type == nil { return "", false } return *g.Type, true } // HasType returns a boolean if a field has been set. func (g *GraphDefinitionMarker) HasType() bool { if g != nil && g.Type != nil { return true } return false } // SetType allocates a new g.Type and returns the pointer to it. func (g *GraphDefinitionMarker) SetType(v string) { g.Type = &v } // GetVal returns the Val field if non-nil, zero value otherwise. func (g *GraphDefinitionMarker) GetVal() json.Number { if g == nil || g.Val == nil { return "" } return *g.Val } // GetOkVal returns a tuple with the Val field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionMarker) GetValOk() (json.Number, bool) { if g == nil || g.Val == nil { return "", false } return *g.Val, true } // HasVal returns a boolean if a field has been set. func (g *GraphDefinitionMarker) HasVal() bool { if g != nil && g.Val != nil { return true } return false } // SetVal allocates a new g.Val and returns the pointer to it. func (g *GraphDefinitionMarker) SetVal(v json.Number) { g.Val = &v } // GetValue returns the Value field if non-nil, zero value otherwise. func (g *GraphDefinitionMarker) GetValue() string { if g == nil || g.Value == nil { return "" } return *g.Value } // GetOkValue returns a tuple with the Value field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionMarker) GetValueOk() (string, bool) { if g == nil || g.Value == nil { return "", false } return *g.Value, true } // HasValue returns a boolean if a field has been set. func (g *GraphDefinitionMarker) HasValue() bool { if g != nil && g.Value != nil { return true } return false } // SetValue allocates a new g.Value and returns the pointer to it. func (g *GraphDefinitionMarker) SetValue(v string) { g.Value = &v } // GetAggregator returns the Aggregator field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetAggregator() string { if g == nil || g.Aggregator == nil { return "" } return *g.Aggregator } // GetOkAggregator returns a tuple with the Aggregator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetAggregatorOk() (string, bool) { if g == nil || g.Aggregator == nil { return "", false } return *g.Aggregator, true } // HasAggregator returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasAggregator() bool { if g != nil && g.Aggregator != nil { return true } return false } // SetAggregator allocates a new g.Aggregator and returns the pointer to it. func (g *GraphDefinitionRequest) SetAggregator(v string) { g.Aggregator = &v } // GetChangeType returns the ChangeType field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetChangeType() string { if g == nil || g.ChangeType == nil { return "" } return *g.ChangeType } // GetOkChangeType returns a tuple with the ChangeType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetChangeTypeOk() (string, bool) { if g == nil || g.ChangeType == nil { return "", false } return *g.ChangeType, true } // HasChangeType returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasChangeType() bool { if g != nil && g.ChangeType != nil { return true } return false } // SetChangeType allocates a new g.ChangeType and returns the pointer to it. func (g *GraphDefinitionRequest) SetChangeType(v string) { g.ChangeType = &v } // GetCompareTo returns the CompareTo field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetCompareTo() string { if g == nil || g.CompareTo == nil { return "" } return *g.CompareTo } // GetOkCompareTo returns a tuple with the CompareTo field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetCompareToOk() (string, bool) { if g == nil || g.CompareTo == nil { return "", false } return *g.CompareTo, true } // HasCompareTo returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasCompareTo() bool { if g != nil && g.CompareTo != nil { return true } return false } // SetCompareTo allocates a new g.CompareTo and returns the pointer to it. func (g *GraphDefinitionRequest) SetCompareTo(v string) { g.CompareTo = &v } // GetExtraCol returns the ExtraCol field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetExtraCol() string { if g == nil || g.ExtraCol == nil { return "" } return *g.ExtraCol } // GetOkExtraCol returns a tuple with the ExtraCol field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetExtraColOk() (string, bool) { if g == nil || g.ExtraCol == nil { return "", false } return *g.ExtraCol, true } // HasExtraCol returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasExtraCol() bool { if g != nil && g.ExtraCol != nil { return true } return false } // SetExtraCol allocates a new g.ExtraCol and returns the pointer to it. func (g *GraphDefinitionRequest) SetExtraCol(v string) { g.ExtraCol = &v } // GetIncreaseGood returns the IncreaseGood field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetIncreaseGood() bool { if g == nil || g.IncreaseGood == nil { return false } return *g.IncreaseGood } // GetOkIncreaseGood returns a tuple with the IncreaseGood field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetIncreaseGoodOk() (bool, bool) { if g == nil || g.IncreaseGood == nil { return false, false } return *g.IncreaseGood, true } // HasIncreaseGood returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasIncreaseGood() bool { if g != nil && g.IncreaseGood != nil { return true } return false } // SetIncreaseGood allocates a new g.IncreaseGood and returns the pointer to it. func (g *GraphDefinitionRequest) SetIncreaseGood(v bool) { g.IncreaseGood = &v } // GetOrderBy returns the OrderBy field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetOrderBy() string { if g == nil || g.OrderBy == nil { return "" } return *g.OrderBy } // GetOkOrderBy returns a tuple with the OrderBy field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetOrderByOk() (string, bool) { if g == nil || g.OrderBy == nil { return "", false } return *g.OrderBy, true } // HasOrderBy returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasOrderBy() bool { if g != nil && g.OrderBy != nil { return true } return false } // SetOrderBy allocates a new g.OrderBy and returns the pointer to it. func (g *GraphDefinitionRequest) SetOrderBy(v string) { g.OrderBy = &v } // GetOrderDirection returns the OrderDirection field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetOrderDirection() string { if g == nil || g.OrderDirection == nil { return "" } return *g.OrderDirection } // GetOkOrderDirection returns a tuple with the OrderDirection field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetOrderDirectionOk() (string, bool) { if g == nil || g.OrderDirection == nil { return "", false } return *g.OrderDirection, true } // HasOrderDirection returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasOrderDirection() bool { if g != nil && g.OrderDirection != nil { return true } return false } // SetOrderDirection allocates a new g.OrderDirection and returns the pointer to it. func (g *GraphDefinitionRequest) SetOrderDirection(v string) { g.OrderDirection = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetQuery() string { if g == nil || g.Query == nil { return "" } return *g.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetQueryOk() (string, bool) { if g == nil || g.Query == nil { return "", false } return *g.Query, true } // HasQuery returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasQuery() bool { if g != nil && g.Query != nil { return true } return false } // SetQuery allocates a new g.Query and returns the pointer to it. func (g *GraphDefinitionRequest) SetQuery(v string) { g.Query = &v } // GetStacked returns the Stacked field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetStacked() bool { if g == nil || g.Stacked == nil { return false } return *g.Stacked } // GetOkStacked returns a tuple with the Stacked field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetStackedOk() (bool, bool) { if g == nil || g.Stacked == nil { return false, false } return *g.Stacked, true } // HasStacked returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasStacked() bool { if g != nil && g.Stacked != nil { return true } return false } // SetStacked allocates a new g.Stacked and returns the pointer to it. func (g *GraphDefinitionRequest) SetStacked(v bool) { g.Stacked = &v } // GetStyle returns the Style field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetStyle() GraphDefinitionRequestStyle { if g == nil || g.Style == nil { return GraphDefinitionRequestStyle{} } return *g.Style } // GetOkStyle returns a tuple with the Style field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetStyleOk() (GraphDefinitionRequestStyle, bool) { if g == nil || g.Style == nil { return GraphDefinitionRequestStyle{}, false } return *g.Style, true } // HasStyle returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasStyle() bool { if g != nil && g.Style != nil { return true } return false } // SetStyle allocates a new g.Style and returns the pointer to it. func (g *GraphDefinitionRequest) SetStyle(v GraphDefinitionRequestStyle) { g.Style = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetType() string { if g == nil || g.Type == nil { return "" } return *g.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetTypeOk() (string, bool) { if g == nil || g.Type == nil { return "", false } return *g.Type, true } // HasType returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasType() bool { if g != nil && g.Type != nil { return true } return false } // SetType allocates a new g.Type and returns the pointer to it. func (g *GraphDefinitionRequest) SetType(v string) { g.Type = &v } // GetPalette returns the Palette field if non-nil, zero value otherwise. func (g *GraphDefinitionRequestStyle) GetPalette() string { if g == nil || g.Palette == nil { return "" } return *g.Palette } // GetOkPalette returns a tuple with the Palette field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequestStyle) GetPaletteOk() (string, bool) { if g == nil || g.Palette == nil { return "", false } return *g.Palette, true } // HasPalette returns a boolean if a field has been set. func (g *GraphDefinitionRequestStyle) HasPalette() bool { if g != nil && g.Palette != nil { return true } return false } // SetPalette allocates a new g.Palette and returns the pointer to it. func (g *GraphDefinitionRequestStyle) SetPalette(v string) { g.Palette = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (g *GraphDefinitionRequestStyle) GetType() string { if g == nil || g.Type == nil { return "" } return *g.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequestStyle) GetTypeOk() (string, bool) { if g == nil || g.Type == nil { return "", false } return *g.Type, true } // HasType returns a boolean if a field has been set. func (g *GraphDefinitionRequestStyle) HasType() bool { if g != nil && g.Type != nil { return true } return false } // SetType allocates a new g.Type and returns the pointer to it. func (g *GraphDefinitionRequestStyle) SetType(v string) { g.Type = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (g *GraphDefinitionRequestStyle) GetWidth() string { if g == nil || g.Width == nil { return "" } return *g.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequestStyle) GetWidthOk() (string, bool) { if g == nil || g.Width == nil { return "", false } return *g.Width, true } // HasWidth returns a boolean if a field has been set. func (g *GraphDefinitionRequestStyle) HasWidth() bool { if g != nil && g.Width != nil { return true } return false } // SetWidth allocates a new g.Width and returns the pointer to it. func (g *GraphDefinitionRequestStyle) SetWidth(v string) { g.Width = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (g *GraphEvent) GetQuery() string { if g == nil || g.Query == nil { return "" } return *g.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphEvent) GetQueryOk() (string, bool) { if g == nil || g.Query == nil { return "", false } return *g.Query, true } // HasQuery returns a boolean if a field has been set. func (g *GraphEvent) HasQuery() bool { if g != nil && g.Query != nil { return true } return false } // SetQuery allocates a new g.Query and returns the pointer to it. func (g *GraphEvent) SetQuery(v string) { g.Query = &v } // GetEndTime returns the EndTime field if non-nil, zero value otherwise. func (h *HostActionMute) GetEndTime() string { if h == nil || h.EndTime == nil { return "" } return *h.EndTime } // GetOkEndTime returns a tuple with the EndTime field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostActionMute) GetEndTimeOk() (string, bool) { if h == nil || h.EndTime == nil { return "", false } return *h.EndTime, true } // HasEndTime returns a boolean if a field has been set. func (h *HostActionMute) HasEndTime() bool { if h != nil && h.EndTime != nil { return true } return false } // SetEndTime allocates a new h.EndTime and returns the pointer to it. func (h *HostActionMute) SetEndTime(v string) { h.EndTime = &v } // GetMessage returns the Message field if non-nil, zero value otherwise. func (h *HostActionMute) GetMessage() string { if h == nil || h.Message == nil { return "" } return *h.Message } // GetOkMessage returns a tuple with the Message field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostActionMute) GetMessageOk() (string, bool) { if h == nil || h.Message == nil { return "", false } return *h.Message, true } // HasMessage returns a boolean if a field has been set. func (h *HostActionMute) HasMessage() bool { if h != nil && h.Message != nil { return true } return false } // SetMessage allocates a new h.Message and returns the pointer to it. func (h *HostActionMute) SetMessage(v string) { h.Message = &v } // GetOverride returns the Override field if non-nil, zero value otherwise. func (h *HostActionMute) GetOverride() bool { if h == nil || h.Override == nil { return false } return *h.Override } // GetOkOverride returns a tuple with the Override field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostActionMute) GetOverrideOk() (bool, bool) { if h == nil || h.Override == nil { return false, false } return *h.Override, true } // HasOverride returns a boolean if a field has been set. func (h *HostActionMute) HasOverride() bool { if h != nil && h.Override != nil { return true } return false } // SetOverride allocates a new h.Override and returns the pointer to it. func (h *HostActionMute) SetOverride(v bool) { h.Override = &v } // GetAccountID returns the AccountID field if non-nil, zero value otherwise. func (i *IntegrationAWSAccount) GetAccountID() string { if i == nil || i.AccountID == nil { return "" } return *i.AccountID } // GetOkAccountID returns a tuple with the AccountID field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IntegrationAWSAccount) GetAccountIDOk() (string, bool) { if i == nil || i.AccountID == nil { return "", false } return *i.AccountID, true } // HasAccountID returns a boolean if a field has been set. func (i *IntegrationAWSAccount) HasAccountID() bool { if i != nil && i.AccountID != nil { return true } return false } // SetAccountID allocates a new i.AccountID and returns the pointer to it. func (i *IntegrationAWSAccount) SetAccountID(v string) { i.AccountID = &v } // GetRoleName returns the RoleName field if non-nil, zero value otherwise. func (i *IntegrationAWSAccount) GetRoleName() string { if i == nil || i.RoleName == nil { return "" } return *i.RoleName } // GetOkRoleName returns a tuple with the RoleName field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IntegrationAWSAccount) GetRoleNameOk() (string, bool) { if i == nil || i.RoleName == nil { return "", false } return *i.RoleName, true } // HasRoleName returns a boolean if a field has been set. func (i *IntegrationAWSAccount) HasRoleName() bool { if i != nil && i.RoleName != nil { return true } return false } // SetRoleName allocates a new i.RoleName and returns the pointer to it. func (i *IntegrationAWSAccount) SetRoleName(v string) { i.RoleName = &v } // GetAccountID returns the AccountID field if non-nil, zero value otherwise. func (i *IntegrationAWSAccountDeleteRequest) GetAccountID() string { if i == nil || i.AccountID == nil { return "" } return *i.AccountID } // GetOkAccountID returns a tuple with the AccountID field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IntegrationAWSAccountDeleteRequest) GetAccountIDOk() (string, bool) { if i == nil || i.AccountID == nil { return "", false } return *i.AccountID, true } // HasAccountID returns a boolean if a field has been set. func (i *IntegrationAWSAccountDeleteRequest) HasAccountID() bool { if i != nil && i.AccountID != nil { return true } return false } // SetAccountID allocates a new i.AccountID and returns the pointer to it. func (i *IntegrationAWSAccountDeleteRequest) SetAccountID(v string) { i.AccountID = &v } // GetRoleName returns the RoleName field if non-nil, zero value otherwise. func (i *IntegrationAWSAccountDeleteRequest) GetRoleName() string { if i == nil || i.RoleName == nil { return "" } return *i.RoleName } // GetOkRoleName returns a tuple with the RoleName field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IntegrationAWSAccountDeleteRequest) GetRoleNameOk() (string, bool) { if i == nil || i.RoleName == nil { return "", false } return *i.RoleName, true } // HasRoleName returns a boolean if a field has been set. func (i *IntegrationAWSAccountDeleteRequest) HasRoleName() bool { if i != nil && i.RoleName != nil { return true } return false } // SetRoleName allocates a new i.RoleName and returns the pointer to it. func (i *IntegrationAWSAccountDeleteRequest) SetRoleName(v string) { i.RoleName = &v } // GetAPIToken returns the APIToken field if non-nil, zero value otherwise. func (i *integrationPD) GetAPIToken() string { if i == nil || i.APIToken == nil { return "" } return *i.APIToken } // GetOkAPIToken returns a tuple with the APIToken field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *integrationPD) GetAPITokenOk() (string, bool) { if i == nil || i.APIToken == nil { return "", false } return *i.APIToken, true } // HasAPIToken returns a boolean if a field has been set. func (i *integrationPD) HasAPIToken() bool { if i != nil && i.APIToken != nil { return true } return false } // SetAPIToken allocates a new i.APIToken and returns the pointer to it. func (i *integrationPD) SetAPIToken(v string) { i.APIToken = &v } // GetSubdomain returns the Subdomain field if non-nil, zero value otherwise. func (i *integrationPD) GetSubdomain() string { if i == nil || i.Subdomain == nil { return "" } return *i.Subdomain } // GetOkSubdomain returns a tuple with the Subdomain field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *integrationPD) GetSubdomainOk() (string, bool) { if i == nil || i.Subdomain == nil { return "", false } return *i.Subdomain, true } // HasSubdomain returns a boolean if a field has been set. func (i *integrationPD) HasSubdomain() bool { if i != nil && i.Subdomain != nil { return true } return false } // SetSubdomain allocates a new i.Subdomain and returns the pointer to it. func (i *integrationPD) SetSubdomain(v string) { i.Subdomain = &v } // GetAPIToken returns the APIToken field if non-nil, zero value otherwise. func (i *IntegrationPDRequest) GetAPIToken() string { if i == nil || i.APIToken == nil { return "" } return *i.APIToken } // GetOkAPIToken returns a tuple with the APIToken field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IntegrationPDRequest) GetAPITokenOk() (string, bool) { if i == nil || i.APIToken == nil { return "", false } return *i.APIToken, true } // HasAPIToken returns a boolean if a field has been set. func (i *IntegrationPDRequest) HasAPIToken() bool { if i != nil && i.APIToken != nil { return true } return false } // SetAPIToken allocates a new i.APIToken and returns the pointer to it. func (i *IntegrationPDRequest) SetAPIToken(v string) { i.APIToken = &v } // GetRunCheck returns the RunCheck field if non-nil, zero value otherwise. func (i *IntegrationPDRequest) GetRunCheck() bool { if i == nil || i.RunCheck == nil { return false } return *i.RunCheck } // GetOkRunCheck returns a tuple with the RunCheck field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IntegrationPDRequest) GetRunCheckOk() (bool, bool) { if i == nil || i.RunCheck == nil { return false, false } return *i.RunCheck, true } // HasRunCheck returns a boolean if a field has been set. func (i *IntegrationPDRequest) HasRunCheck() bool { if i != nil && i.RunCheck != nil { return true } return false } // SetRunCheck allocates a new i.RunCheck and returns the pointer to it. func (i *IntegrationPDRequest) SetRunCheck(v bool) { i.RunCheck = &v } // GetSubdomain returns the Subdomain field if non-nil, zero value otherwise. func (i *IntegrationPDRequest) GetSubdomain() string { if i == nil || i.Subdomain == nil { return "" } return *i.Subdomain } // GetOkSubdomain returns a tuple with the Subdomain field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IntegrationPDRequest) GetSubdomainOk() (string, bool) { if i == nil || i.Subdomain == nil { return "", false } return *i.Subdomain, true } // HasSubdomain returns a boolean if a field has been set. func (i *IntegrationPDRequest) HasSubdomain() bool { if i != nil && i.Subdomain != nil { return true } return false } // SetSubdomain allocates a new i.Subdomain and returns the pointer to it. func (i *IntegrationPDRequest) SetSubdomain(v string) { i.Subdomain = &v } // GetRunCheck returns the RunCheck field if non-nil, zero value otherwise. func (i *IntegrationSlackRequest) GetRunCheck() bool { if i == nil || i.RunCheck == nil { return false } return *i.RunCheck } // GetOkRunCheck returns a tuple with the RunCheck field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IntegrationSlackRequest) GetRunCheckOk() (bool, bool) { if i == nil || i.RunCheck == nil { return false, false } return *i.RunCheck, true } // HasRunCheck returns a boolean if a field has been set. func (i *IntegrationSlackRequest) HasRunCheck() bool { if i != nil && i.RunCheck != nil { return true } return false } // SetRunCheck allocates a new i.RunCheck and returns the pointer to it. func (i *IntegrationSlackRequest) SetRunCheck(v bool) { i.RunCheck = &v } // GetHost returns the Host field if non-nil, zero value otherwise. func (m *Metric) GetHost() string { if m == nil || m.Host == nil { return "" } return *m.Host } // GetOkHost returns a tuple with the Host field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Metric) GetHostOk() (string, bool) { if m == nil || m.Host == nil { return "", false } return *m.Host, true } // HasHost returns a boolean if a field has been set. func (m *Metric) HasHost() bool { if m != nil && m.Host != nil { return true } return false } // SetHost allocates a new m.Host and returns the pointer to it. func (m *Metric) SetHost(v string) { m.Host = &v } // GetMetric returns the Metric field if non-nil, zero value otherwise. func (m *Metric) GetMetric() string { if m == nil || m.Metric == nil { return "" } return *m.Metric } // GetOkMetric returns a tuple with the Metric field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Metric) GetMetricOk() (string, bool) { if m == nil || m.Metric == nil { return "", false } return *m.Metric, true } // HasMetric returns a boolean if a field has been set. func (m *Metric) HasMetric() bool { if m != nil && m.Metric != nil { return true } return false } // SetMetric allocates a new m.Metric and returns the pointer to it. func (m *Metric) SetMetric(v string) { m.Metric = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (m *Metric) GetType() string { if m == nil || m.Type == nil { return "" } return *m.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Metric) GetTypeOk() (string, bool) { if m == nil || m.Type == nil { return "", false } return *m.Type, true } // HasType returns a boolean if a field has been set. func (m *Metric) HasType() bool { if m != nil && m.Type != nil { return true } return false } // SetType allocates a new m.Type and returns the pointer to it. func (m *Metric) SetType(v string) { m.Type = &v } // GetUnit returns the Unit field if non-nil, zero value otherwise. func (m *Metric) GetUnit() string { if m == nil || m.Unit == nil { return "" } return *m.Unit } // GetOkUnit returns a tuple with the Unit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Metric) GetUnitOk() (string, bool) { if m == nil || m.Unit == nil { return "", false } return *m.Unit, true } // HasUnit returns a boolean if a field has been set. func (m *Metric) HasUnit() bool { if m != nil && m.Unit != nil { return true } return false } // SetUnit allocates a new m.Unit and returns the pointer to it. func (m *Metric) SetUnit(v string) { m.Unit = &v } // GetDescription returns the Description field if non-nil, zero value otherwise. func (m *MetricMetadata) GetDescription() string { if m == nil || m.Description == nil { return "" } return *m.Description } // GetOkDescription returns a tuple with the Description field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *MetricMetadata) GetDescriptionOk() (string, bool) { if m == nil || m.Description == nil { return "", false } return *m.Description, true } // HasDescription returns a boolean if a field has been set. func (m *MetricMetadata) HasDescription() bool { if m != nil && m.Description != nil { return true } return false } // SetDescription allocates a new m.Description and returns the pointer to it. func (m *MetricMetadata) SetDescription(v string) { m.Description = &v } // GetPerUnit returns the PerUnit field if non-nil, zero value otherwise. func (m *MetricMetadata) GetPerUnit() string { if m == nil || m.PerUnit == nil { return "" } return *m.PerUnit } // GetOkPerUnit returns a tuple with the PerUnit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *MetricMetadata) GetPerUnitOk() (string, bool) { if m == nil || m.PerUnit == nil { return "", false } return *m.PerUnit, true } // HasPerUnit returns a boolean if a field has been set. func (m *MetricMetadata) HasPerUnit() bool { if m != nil && m.PerUnit != nil { return true } return false } // SetPerUnit allocates a new m.PerUnit and returns the pointer to it. func (m *MetricMetadata) SetPerUnit(v string) { m.PerUnit = &v } // GetShortName returns the ShortName field if non-nil, zero value otherwise. func (m *MetricMetadata) GetShortName() string { if m == nil || m.ShortName == nil { return "" } return *m.ShortName } // GetOkShortName returns a tuple with the ShortName field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *MetricMetadata) GetShortNameOk() (string, bool) { if m == nil || m.ShortName == nil { return "", false } return *m.ShortName, true } // HasShortName returns a boolean if a field has been set. func (m *MetricMetadata) HasShortName() bool { if m != nil && m.ShortName != nil { return true } return false } // SetShortName allocates a new m.ShortName and returns the pointer to it. func (m *MetricMetadata) SetShortName(v string) { m.ShortName = &v } // GetStatsdInterval returns the StatsdInterval field if non-nil, zero value otherwise. func (m *MetricMetadata) GetStatsdInterval() int { if m == nil || m.StatsdInterval == nil { return 0 } return *m.StatsdInterval } // GetOkStatsdInterval returns a tuple with the StatsdInterval field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *MetricMetadata) GetStatsdIntervalOk() (int, bool) { if m == nil || m.StatsdInterval == nil { return 0, false } return *m.StatsdInterval, true } // HasStatsdInterval returns a boolean if a field has been set. func (m *MetricMetadata) HasStatsdInterval() bool { if m != nil && m.StatsdInterval != nil { return true } return false } // SetStatsdInterval allocates a new m.StatsdInterval and returns the pointer to it. func (m *MetricMetadata) SetStatsdInterval(v int) { m.StatsdInterval = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (m *MetricMetadata) GetType() string { if m == nil || m.Type == nil { return "" } return *m.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *MetricMetadata) GetTypeOk() (string, bool) { if m == nil || m.Type == nil { return "", false } return *m.Type, true } // HasType returns a boolean if a field has been set. func (m *MetricMetadata) HasType() bool { if m != nil && m.Type != nil { return true } return false } // SetType allocates a new m.Type and returns the pointer to it. func (m *MetricMetadata) SetType(v string) { m.Type = &v } // GetUnit returns the Unit field if non-nil, zero value otherwise. func (m *MetricMetadata) GetUnit() string { if m == nil || m.Unit == nil { return "" } return *m.Unit } // GetOkUnit returns a tuple with the Unit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *MetricMetadata) GetUnitOk() (string, bool) { if m == nil || m.Unit == nil { return "", false } return *m.Unit, true } // HasUnit returns a boolean if a field has been set. func (m *MetricMetadata) HasUnit() bool { if m != nil && m.Unit != nil { return true } return false } // SetUnit allocates a new m.Unit and returns the pointer to it. func (m *MetricMetadata) SetUnit(v string) { m.Unit = &v } // GetCreator returns the Creator field if non-nil, zero value otherwise. func (m *Monitor) GetCreator() Creator { if m == nil || m.Creator == nil { return Creator{} } return *m.Creator } // GetOkCreator returns a tuple with the Creator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetCreatorOk() (Creator, bool) { if m == nil || m.Creator == nil { return Creator{}, false } return *m.Creator, true } // HasCreator returns a boolean if a field has been set. func (m *Monitor) HasCreator() bool { if m != nil && m.Creator != nil { return true } return false } // SetCreator allocates a new m.Creator and returns the pointer to it. func (m *Monitor) SetCreator(v Creator) { m.Creator = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (m *Monitor) GetId() int { if m == nil || m.Id == nil { return 0 } return *m.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetIdOk() (int, bool) { if m == nil || m.Id == nil { return 0, false } return *m.Id, true } // HasId returns a boolean if a field has been set. func (m *Monitor) HasId() bool { if m != nil && m.Id != nil { return true } return false } // SetId allocates a new m.Id and returns the pointer to it. func (m *Monitor) SetId(v int) { m.Id = &v } // GetMessage returns the Message field if non-nil, zero value otherwise. func (m *Monitor) GetMessage() string { if m == nil || m.Message == nil { return "" } return *m.Message } // GetOkMessage returns a tuple with the Message field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetMessageOk() (string, bool) { if m == nil || m.Message == nil { return "", false } return *m.Message, true } // HasMessage returns a boolean if a field has been set. func (m *Monitor) HasMessage() bool { if m != nil && m.Message != nil { return true } return false } // SetMessage allocates a new m.Message and returns the pointer to it. func (m *Monitor) SetMessage(v string) { m.Message = &v } // GetName returns the Name field if non-nil, zero value otherwise. func (m *Monitor) GetName() string { if m == nil || m.Name == nil { return "" } return *m.Name } // GetOkName returns a tuple with the Name field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetNameOk() (string, bool) { if m == nil || m.Name == nil { return "", false } return *m.Name, true } // HasName returns a boolean if a field has been set. func (m *Monitor) HasName() bool { if m != nil && m.Name != nil { return true } return false } // SetName allocates a new m.Name and returns the pointer to it. func (m *Monitor) SetName(v string) { m.Name = &v } // GetOptions returns the Options field if non-nil, zero value otherwise. func (m *Monitor) GetOptions() Options { if m == nil || m.Options == nil { return Options{} } return *m.Options } // GetOkOptions returns a tuple with the Options field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetOptionsOk() (Options, bool) { if m == nil || m.Options == nil { return Options{}, false } return *m.Options, true } // HasOptions returns a boolean if a field has been set. func (m *Monitor) HasOptions() bool { if m != nil && m.Options != nil { return true } return false } // SetOptions allocates a new m.Options and returns the pointer to it. func (m *Monitor) SetOptions(v Options) { m.Options = &v } // GetOverallState returns the OverallState field if non-nil, zero value otherwise. func (m *Monitor) GetOverallState() string { if m == nil || m.OverallState == nil { return "" } return *m.OverallState } // GetOkOverallState returns a tuple with the OverallState field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetOverallStateOk() (string, bool) { if m == nil || m.OverallState == nil { return "", false } return *m.OverallState, true } // HasOverallState returns a boolean if a field has been set. func (m *Monitor) HasOverallState() bool { if m != nil && m.OverallState != nil { return true } return false } // SetOverallState allocates a new m.OverallState and returns the pointer to it. func (m *Monitor) SetOverallState(v string) { m.OverallState = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (m *Monitor) GetQuery() string { if m == nil || m.Query == nil { return "" } return *m.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetQueryOk() (string, bool) { if m == nil || m.Query == nil { return "", false } return *m.Query, true } // HasQuery returns a boolean if a field has been set. func (m *Monitor) HasQuery() bool { if m != nil && m.Query != nil { return true } return false } // SetQuery allocates a new m.Query and returns the pointer to it. func (m *Monitor) SetQuery(v string) { m.Query = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (m *Monitor) GetType() string { if m == nil || m.Type == nil { return "" } return *m.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetTypeOk() (string, bool) { if m == nil || m.Type == nil { return "", false } return *m.Type, true } // HasType returns a boolean if a field has been set. func (m *Monitor) HasType() bool { if m != nil && m.Type != nil { return true } return false } // SetType allocates a new m.Type and returns the pointer to it. func (m *Monitor) SetType(v string) { m.Type = &v } // GetEscalationMessage returns the EscalationMessage field if non-nil, zero value otherwise. func (o *Options) GetEscalationMessage() string { if o == nil || o.EscalationMessage == nil { return "" } return *o.EscalationMessage } // GetOkEscalationMessage returns a tuple with the EscalationMessage field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetEscalationMessageOk() (string, bool) { if o == nil || o.EscalationMessage == nil { return "", false } return *o.EscalationMessage, true } // HasEscalationMessage returns a boolean if a field has been set. func (o *Options) HasEscalationMessage() bool { if o != nil && o.EscalationMessage != nil { return true } return false } // SetEscalationMessage allocates a new o.EscalationMessage and returns the pointer to it. func (o *Options) SetEscalationMessage(v string) { o.EscalationMessage = &v } // GetEvaluationDelay returns the EvaluationDelay field if non-nil, zero value otherwise. func (o *Options) GetEvaluationDelay() int { if o == nil || o.EvaluationDelay == nil { return 0 } return *o.EvaluationDelay } // GetOkEvaluationDelay returns a tuple with the EvaluationDelay field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetEvaluationDelayOk() (int, bool) { if o == nil || o.EvaluationDelay == nil { return 0, false } return *o.EvaluationDelay, true } // HasEvaluationDelay returns a boolean if a field has been set. func (o *Options) HasEvaluationDelay() bool { if o != nil && o.EvaluationDelay != nil { return true } return false } // SetEvaluationDelay allocates a new o.EvaluationDelay and returns the pointer to it. func (o *Options) SetEvaluationDelay(v int) { o.EvaluationDelay = &v } // GetIncludeTags returns the IncludeTags field if non-nil, zero value otherwise. func (o *Options) GetIncludeTags() bool { if o == nil || o.IncludeTags == nil { return false } return *o.IncludeTags } // GetOkIncludeTags returns a tuple with the IncludeTags field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetIncludeTagsOk() (bool, bool) { if o == nil || o.IncludeTags == nil { return false, false } return *o.IncludeTags, true } // HasIncludeTags returns a boolean if a field has been set. func (o *Options) HasIncludeTags() bool { if o != nil && o.IncludeTags != nil { return true } return false } // SetIncludeTags allocates a new o.IncludeTags and returns the pointer to it. func (o *Options) SetIncludeTags(v bool) { o.IncludeTags = &v } // GetLocked returns the Locked field if non-nil, zero value otherwise. func (o *Options) GetLocked() bool { if o == nil || o.Locked == nil { return false } return *o.Locked } // GetOkLocked returns a tuple with the Locked field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetLockedOk() (bool, bool) { if o == nil || o.Locked == nil { return false, false } return *o.Locked, true } // HasLocked returns a boolean if a field has been set. func (o *Options) HasLocked() bool { if o != nil && o.Locked != nil { return true } return false } // SetLocked allocates a new o.Locked and returns the pointer to it. func (o *Options) SetLocked(v bool) { o.Locked = &v } // GetNewHostDelay returns the NewHostDelay field if non-nil, zero value otherwise. func (o *Options) GetNewHostDelay() int { if o == nil || o.NewHostDelay == nil { return 0 } return *o.NewHostDelay } // GetOkNewHostDelay returns a tuple with the NewHostDelay field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetNewHostDelayOk() (int, bool) { if o == nil || o.NewHostDelay == nil { return 0, false } return *o.NewHostDelay, true } // HasNewHostDelay returns a boolean if a field has been set. func (o *Options) HasNewHostDelay() bool { if o != nil && o.NewHostDelay != nil { return true } return false } // SetNewHostDelay allocates a new o.NewHostDelay and returns the pointer to it. func (o *Options) SetNewHostDelay(v int) { o.NewHostDelay = &v } // GetNotifyAudit returns the NotifyAudit field if non-nil, zero value otherwise. func (o *Options) GetNotifyAudit() bool { if o == nil || o.NotifyAudit == nil { return false } return *o.NotifyAudit } // GetOkNotifyAudit returns a tuple with the NotifyAudit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetNotifyAuditOk() (bool, bool) { if o == nil || o.NotifyAudit == nil { return false, false } return *o.NotifyAudit, true } // HasNotifyAudit returns a boolean if a field has been set. func (o *Options) HasNotifyAudit() bool { if o != nil && o.NotifyAudit != nil { return true } return false } // SetNotifyAudit allocates a new o.NotifyAudit and returns the pointer to it. func (o *Options) SetNotifyAudit(v bool) { o.NotifyAudit = &v } // GetNotifyNoData returns the NotifyNoData field if non-nil, zero value otherwise. func (o *Options) GetNotifyNoData() bool { if o == nil || o.NotifyNoData == nil { return false } return *o.NotifyNoData } // GetOkNotifyNoData returns a tuple with the NotifyNoData field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetNotifyNoDataOk() (bool, bool) { if o == nil || o.NotifyNoData == nil { return false, false } return *o.NotifyNoData, true } // HasNotifyNoData returns a boolean if a field has been set. func (o *Options) HasNotifyNoData() bool { if o != nil && o.NotifyNoData != nil { return true } return false } // SetNotifyNoData allocates a new o.NotifyNoData and returns the pointer to it. func (o *Options) SetNotifyNoData(v bool) { o.NotifyNoData = &v } // GetRenotifyInterval returns the RenotifyInterval field if non-nil, zero value otherwise. func (o *Options) GetRenotifyInterval() int { if o == nil || o.RenotifyInterval == nil { return 0 } return *o.RenotifyInterval } // GetOkRenotifyInterval returns a tuple with the RenotifyInterval field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetRenotifyIntervalOk() (int, bool) { if o == nil || o.RenotifyInterval == nil { return 0, false } return *o.RenotifyInterval, true } // HasRenotifyInterval returns a boolean if a field has been set. func (o *Options) HasRenotifyInterval() bool { if o != nil && o.RenotifyInterval != nil { return true } return false } // SetRenotifyInterval allocates a new o.RenotifyInterval and returns the pointer to it. func (o *Options) SetRenotifyInterval(v int) { o.RenotifyInterval = &v } // GetRequireFullWindow returns the RequireFullWindow field if non-nil, zero value otherwise. func (o *Options) GetRequireFullWindow() bool { if o == nil || o.RequireFullWindow == nil { return false } return *o.RequireFullWindow } // GetOkRequireFullWindow returns a tuple with the RequireFullWindow field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetRequireFullWindowOk() (bool, bool) { if o == nil || o.RequireFullWindow == nil { return false, false } return *o.RequireFullWindow, true } // HasRequireFullWindow returns a boolean if a field has been set. func (o *Options) HasRequireFullWindow() bool { if o != nil && o.RequireFullWindow != nil { return true } return false } // SetRequireFullWindow allocates a new o.RequireFullWindow and returns the pointer to it. func (o *Options) SetRequireFullWindow(v bool) { o.RequireFullWindow = &v } // GetThresholds returns the Thresholds field if non-nil, zero value otherwise. func (o *Options) GetThresholds() ThresholdCount { if o == nil || o.Thresholds == nil { return ThresholdCount{} } return *o.Thresholds } // GetOkThresholds returns a tuple with the Thresholds field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetThresholdsOk() (ThresholdCount, bool) { if o == nil || o.Thresholds == nil { return ThresholdCount{}, false } return *o.Thresholds, true } // HasThresholds returns a boolean if a field has been set. func (o *Options) HasThresholds() bool { if o != nil && o.Thresholds != nil { return true } return false } // SetThresholds allocates a new o.Thresholds and returns the pointer to it. func (o *Options) SetThresholds(v ThresholdCount) { o.Thresholds = &v } // GetTimeoutH returns the TimeoutH field if non-nil, zero value otherwise. func (o *Options) GetTimeoutH() int { if o == nil || o.TimeoutH == nil { return 0 } return *o.TimeoutH } // GetOkTimeoutH returns a tuple with the TimeoutH field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetTimeoutHOk() (int, bool) { if o == nil || o.TimeoutH == nil { return 0, false } return *o.TimeoutH, true } // HasTimeoutH returns a boolean if a field has been set. func (o *Options) HasTimeoutH() bool { if o != nil && o.TimeoutH != nil { return true } return false } // SetTimeoutH allocates a new o.TimeoutH and returns the pointer to it. func (o *Options) SetTimeoutH(v int) { o.TimeoutH = &v } // GetCount returns the Count field if non-nil, zero value otherwise. func (p *Params) GetCount() string { if p == nil || p.Count == nil { return "" } return *p.Count } // GetOkCount returns a tuple with the Count field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (p *Params) GetCountOk() (string, bool) { if p == nil || p.Count == nil { return "", false } return *p.Count, true } // HasCount returns a boolean if a field has been set. func (p *Params) HasCount() bool { if p != nil && p.Count != nil { return true } return false } // SetCount allocates a new p.Count and returns the pointer to it. func (p *Params) SetCount(v string) { p.Count = &v } // GetSort returns the Sort field if non-nil, zero value otherwise. func (p *Params) GetSort() string { if p == nil || p.Sort == nil { return "" } return *p.Sort } // GetOkSort returns a tuple with the Sort field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (p *Params) GetSortOk() (string, bool) { if p == nil || p.Sort == nil { return "", false } return *p.Sort, true } // HasSort returns a boolean if a field has been set. func (p *Params) HasSort() bool { if p != nil && p.Sort != nil { return true } return false } // SetSort allocates a new p.Sort and returns the pointer to it. func (p *Params) SetSort(v string) { p.Sort = &v } // GetStart returns the Start field if non-nil, zero value otherwise. func (p *Params) GetStart() string { if p == nil || p.Start == nil { return "" } return *p.Start } // GetOkStart returns a tuple with the Start field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (p *Params) GetStartOk() (string, bool) { if p == nil || p.Start == nil { return "", false } return *p.Start, true } // HasStart returns a boolean if a field has been set. func (p *Params) HasStart() bool { if p != nil && p.Start != nil { return true } return false } // SetStart allocates a new p.Start and returns the pointer to it. func (p *Params) SetStart(v string) { p.Start = &v } // GetText returns the Text field if non-nil, zero value otherwise. func (p *Params) GetText() string { if p == nil || p.Text == nil { return "" } return *p.Text } // GetOkText returns a tuple with the Text field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (p *Params) GetTextOk() (string, bool) { if p == nil || p.Text == nil { return "", false } return *p.Text, true } // HasText returns a boolean if a field has been set. func (p *Params) HasText() bool { if p != nil && p.Text != nil { return true } return false } // SetText allocates a new p.Text and returns the pointer to it. func (p *Params) SetText(v string) { p.Text = &v } // GetPeriod returns the Period field if non-nil, zero value otherwise. func (r *Recurrence) GetPeriod() int { if r == nil || r.Period == nil { return 0 } return *r.Period } // GetOkPeriod returns a tuple with the Period field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *Recurrence) GetPeriodOk() (int, bool) { if r == nil || r.Period == nil { return 0, false } return *r.Period, true } // HasPeriod returns a boolean if a field has been set. func (r *Recurrence) HasPeriod() bool { if r != nil && r.Period != nil { return true } return false } // SetPeriod allocates a new r.Period and returns the pointer to it. func (r *Recurrence) SetPeriod(v int) { r.Period = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (r *Recurrence) GetType() string { if r == nil || r.Type == nil { return "" } return *r.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *Recurrence) GetTypeOk() (string, bool) { if r == nil || r.Type == nil { return "", false } return *r.Type, true } // HasType returns a boolean if a field has been set. func (r *Recurrence) HasType() bool { if r != nil && r.Type != nil { return true } return false } // SetType allocates a new r.Type and returns the pointer to it. func (r *Recurrence) SetType(v string) { r.Type = &v } // GetUntilDate returns the UntilDate field if non-nil, zero value otherwise. func (r *Recurrence) GetUntilDate() int { if r == nil || r.UntilDate == nil { return 0 } return *r.UntilDate } // GetOkUntilDate returns a tuple with the UntilDate field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *Recurrence) GetUntilDateOk() (int, bool) { if r == nil || r.UntilDate == nil { return 0, false } return *r.UntilDate, true } // HasUntilDate returns a boolean if a field has been set. func (r *Recurrence) HasUntilDate() bool { if r != nil && r.UntilDate != nil { return true } return false } // SetUntilDate allocates a new r.UntilDate and returns the pointer to it. func (r *Recurrence) SetUntilDate(v int) { r.UntilDate = &v } // GetUntilOccurrences returns the UntilOccurrences field if non-nil, zero value otherwise. func (r *Recurrence) GetUntilOccurrences() int { if r == nil || r.UntilOccurrences == nil { return 0 } return *r.UntilOccurrences } // GetOkUntilOccurrences returns a tuple with the UntilOccurrences field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *Recurrence) GetUntilOccurrencesOk() (int, bool) { if r == nil || r.UntilOccurrences == nil { return 0, false } return *r.UntilOccurrences, true } // HasUntilOccurrences returns a boolean if a field has been set. func (r *Recurrence) HasUntilOccurrences() bool { if r != nil && r.UntilOccurrences != nil { return true } return false } // SetUntilOccurrences allocates a new r.UntilOccurrences and returns the pointer to it. func (r *Recurrence) SetUntilOccurrences(v int) { r.UntilOccurrences = &v } // GetComment returns the Comment field if non-nil, zero value otherwise. func (r *reqComment) GetComment() Comment { if r == nil || r.Comment == nil { return Comment{} } return *r.Comment } // GetOkComment returns a tuple with the Comment field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *reqComment) GetCommentOk() (Comment, bool) { if r == nil || r.Comment == nil { return Comment{}, false } return *r.Comment, true } // HasComment returns a boolean if a field has been set. func (r *reqComment) HasComment() bool { if r != nil && r.Comment != nil { return true } return false } // SetComment allocates a new r.Comment and returns the pointer to it. func (r *reqComment) SetComment(v Comment) { r.Comment = &v } // GetDashboard returns the Dashboard field if non-nil, zero value otherwise. func (r *reqGetDashboard) GetDashboard() Dashboard { if r == nil || r.Dashboard == nil { return Dashboard{} } return *r.Dashboard } // GetOkDashboard returns a tuple with the Dashboard field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *reqGetDashboard) GetDashboardOk() (Dashboard, bool) { if r == nil || r.Dashboard == nil { return Dashboard{}, false } return *r.Dashboard, true } // HasDashboard returns a boolean if a field has been set. func (r *reqGetDashboard) HasDashboard() bool { if r != nil && r.Dashboard != nil { return true } return false } // SetDashboard allocates a new r.Dashboard and returns the pointer to it. func (r *reqGetDashboard) SetDashboard(v Dashboard) { r.Dashboard = &v } // GetResource returns the Resource field if non-nil, zero value otherwise. func (r *reqGetDashboard) GetResource() string { if r == nil || r.Resource == nil { return "" } return *r.Resource } // GetOkResource returns a tuple with the Resource field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *reqGetDashboard) GetResourceOk() (string, bool) { if r == nil || r.Resource == nil { return "", false } return *r.Resource, true } // HasResource returns a boolean if a field has been set. func (r *reqGetDashboard) HasResource() bool { if r != nil && r.Resource != nil { return true } return false } // SetResource allocates a new r.Resource and returns the pointer to it. func (r *reqGetDashboard) SetResource(v string) { r.Resource = &v } // GetUrl returns the Url field if non-nil, zero value otherwise. func (r *reqGetDashboard) GetUrl() string { if r == nil || r.Url == nil { return "" } return *r.Url } // GetOkUrl returns a tuple with the Url field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *reqGetDashboard) GetUrlOk() (string, bool) { if r == nil || r.Url == nil { return "", false } return *r.Url, true } // HasUrl returns a boolean if a field has been set. func (r *reqGetDashboard) HasUrl() bool { if r != nil && r.Url != nil { return true } return false } // SetUrl allocates a new r.Url and returns the pointer to it. func (r *reqGetDashboard) SetUrl(v string) { r.Url = &v } // GetEvent returns the Event field if non-nil, zero value otherwise. func (r *reqGetEvent) GetEvent() Event { if r == nil || r.Event == nil { return Event{} } return *r.Event } // GetOkEvent returns a tuple with the Event field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *reqGetEvent) GetEventOk() (Event, bool) { if r == nil || r.Event == nil { return Event{}, false } return *r.Event, true } // HasEvent returns a boolean if a field has been set. func (r *reqGetEvent) HasEvent() bool { if r != nil && r.Event != nil { return true } return false } // SetEvent allocates a new r.Event and returns the pointer to it. func (r *reqGetEvent) SetEvent(v Event) { r.Event = &v } // GetTags returns the Tags field if non-nil, zero value otherwise. func (r *reqGetTags) GetTags() TagMap { if r == nil || r.Tags == nil { return TagMap{} } return *r.Tags } // GetOkTags returns a tuple with the Tags field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *reqGetTags) GetTagsOk() (TagMap, bool) { if r == nil || r.Tags == nil { return TagMap{}, false } return *r.Tags, true } // HasTags returns a boolean if a field has been set. func (r *reqGetTags) HasTags() bool { if r != nil && r.Tags != nil { return true } return false } // SetTags allocates a new r.Tags and returns the pointer to it. func (r *reqGetTags) SetTags(v TagMap) { r.Tags = &v } // GetColor returns the Color field if non-nil, zero value otherwise. func (r *Rule) GetColor() string { if r == nil || r.Color == nil { return "" } return *r.Color } // GetOkColor returns a tuple with the Color field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *Rule) GetColorOk() (string, bool) { if r == nil || r.Color == nil { return "", false } return *r.Color, true } // HasColor returns a boolean if a field has been set. func (r *Rule) HasColor() bool { if r != nil && r.Color != nil { return true } return false } // SetColor allocates a new r.Color and returns the pointer to it. func (r *Rule) SetColor(v string) { r.Color = &v } // GetThreshold returns the Threshold field if non-nil, zero value otherwise. func (r *Rule) GetThreshold() int { if r == nil || r.Threshold == nil { return 0 } return *r.Threshold } // GetOkThreshold returns a tuple with the Threshold field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *Rule) GetThresholdOk() (int, bool) { if r == nil || r.Threshold == nil { return 0, false } return *r.Threshold, true } // HasThreshold returns a boolean if a field has been set. func (r *Rule) HasThreshold() bool { if r != nil && r.Threshold != nil { return true } return false } // SetThreshold allocates a new r.Threshold and returns the pointer to it. func (r *Rule) SetThreshold(v int) { r.Threshold = &v } // GetTimeframe returns the Timeframe field if non-nil, zero value otherwise. func (r *Rule) GetTimeframe() string { if r == nil || r.Timeframe == nil { return "" } return *r.Timeframe } // GetOkTimeframe returns a tuple with the Timeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *Rule) GetTimeframeOk() (string, bool) { if r == nil || r.Timeframe == nil { return "", false } return *r.Timeframe, true } // HasTimeframe returns a boolean if a field has been set. func (r *Rule) HasTimeframe() bool { if r != nil && r.Timeframe != nil { return true } return false } // SetTimeframe allocates a new r.Timeframe and returns the pointer to it. func (r *Rule) SetTimeframe(v string) { r.Timeframe = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (s *Screenboard) GetHeight() string { if s == nil || s.Height == nil { return "" } return *s.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetHeightOk() (string, bool) { if s == nil || s.Height == nil { return "", false } return *s.Height, true } // HasHeight returns a boolean if a field has been set. func (s *Screenboard) HasHeight() bool { if s != nil && s.Height != nil { return true } return false } // SetHeight allocates a new s.Height and returns the pointer to it. func (s *Screenboard) SetHeight(v string) { s.Height = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (s *Screenboard) GetId() int { if s == nil || s.Id == nil { return 0 } return *s.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetIdOk() (int, bool) { if s == nil || s.Id == nil { return 0, false } return *s.Id, true } // HasId returns a boolean if a field has been set. func (s *Screenboard) HasId() bool { if s != nil && s.Id != nil { return true } return false } // SetId allocates a new s.Id and returns the pointer to it. func (s *Screenboard) SetId(v int) { s.Id = &v } // GetReadOnly returns the ReadOnly field if non-nil, zero value otherwise. func (s *Screenboard) GetReadOnly() bool { if s == nil || s.ReadOnly == nil { return false } return *s.ReadOnly } // GetOkReadOnly returns a tuple with the ReadOnly field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetReadOnlyOk() (bool, bool) { if s == nil || s.ReadOnly == nil { return false, false } return *s.ReadOnly, true } // HasReadOnly returns a boolean if a field has been set. func (s *Screenboard) HasReadOnly() bool { if s != nil && s.ReadOnly != nil { return true } return false } // SetReadOnly allocates a new s.ReadOnly and returns the pointer to it. func (s *Screenboard) SetReadOnly(v bool) { s.ReadOnly = &v } // GetShared returns the Shared field if non-nil, zero value otherwise. func (s *Screenboard) GetShared() bool { if s == nil || s.Shared == nil { return false } return *s.Shared } // GetOkShared returns a tuple with the Shared field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetSharedOk() (bool, bool) { if s == nil || s.Shared == nil { return false, false } return *s.Shared, true } // HasShared returns a boolean if a field has been set. func (s *Screenboard) HasShared() bool { if s != nil && s.Shared != nil { return true } return false } // SetShared allocates a new s.Shared and returns the pointer to it. func (s *Screenboard) SetShared(v bool) { s.Shared = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (s *Screenboard) GetTitle() string { if s == nil || s.Title == nil { return "" } return *s.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetTitleOk() (string, bool) { if s == nil || s.Title == nil { return "", false } return *s.Title, true } // HasTitle returns a boolean if a field has been set. func (s *Screenboard) HasTitle() bool { if s != nil && s.Title != nil { return true } return false } // SetTitle allocates a new s.Title and returns the pointer to it. func (s *Screenboard) SetTitle(v string) { s.Title = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (s *Screenboard) GetWidth() string { if s == nil || s.Width == nil { return "" } return *s.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetWidthOk() (string, bool) { if s == nil || s.Width == nil { return "", false } return *s.Width, true } // HasWidth returns a boolean if a field has been set. func (s *Screenboard) HasWidth() bool { if s != nil && s.Width != nil { return true } return false } // SetWidth allocates a new s.Width and returns the pointer to it. func (s *Screenboard) SetWidth(v string) { s.Width = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (s *ScreenboardLite) GetId() int { if s == nil || s.Id == nil { return 0 } return *s.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *ScreenboardLite) GetIdOk() (int, bool) { if s == nil || s.Id == nil { return 0, false } return *s.Id, true } // HasId returns a boolean if a field has been set. func (s *ScreenboardLite) HasId() bool { if s != nil && s.Id != nil { return true } return false } // SetId allocates a new s.Id and returns the pointer to it. func (s *ScreenboardLite) SetId(v int) { s.Id = &v } // GetResource returns the Resource field if non-nil, zero value otherwise. func (s *ScreenboardLite) GetResource() string { if s == nil || s.Resource == nil { return "" } return *s.Resource } // GetOkResource returns a tuple with the Resource field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *ScreenboardLite) GetResourceOk() (string, bool) { if s == nil || s.Resource == nil { return "", false } return *s.Resource, true } // HasResource returns a boolean if a field has been set. func (s *ScreenboardLite) HasResource() bool { if s != nil && s.Resource != nil { return true } return false } // SetResource allocates a new s.Resource and returns the pointer to it. func (s *ScreenboardLite) SetResource(v string) { s.Resource = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (s *ScreenboardLite) GetTitle() string { if s == nil || s.Title == nil { return "" } return *s.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *ScreenboardLite) GetTitleOk() (string, bool) { if s == nil || s.Title == nil { return "", false } return *s.Title, true } // HasTitle returns a boolean if a field has been set. func (s *ScreenboardLite) HasTitle() bool { if s != nil && s.Title != nil { return true } return false } // SetTitle allocates a new s.Title and returns the pointer to it. func (s *ScreenboardLite) SetTitle(v string) { s.Title = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (s *ScreenboardMonitor) GetId() int { if s == nil || s.Id == nil { return 0 } return *s.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *ScreenboardMonitor) GetIdOk() (int, bool) { if s == nil || s.Id == nil { return 0, false } return *s.Id, true } // HasId returns a boolean if a field has been set. func (s *ScreenboardMonitor) HasId() bool { if s != nil && s.Id != nil { return true } return false } // SetId allocates a new s.Id and returns the pointer to it. func (s *ScreenboardMonitor) SetId(v int) { s.Id = &v } // GetAggr returns the Aggr field if non-nil, zero value otherwise. func (s *Series) GetAggr() string { if s == nil || s.Aggr == nil { return "" } return *s.Aggr } // GetOkAggr returns a tuple with the Aggr field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetAggrOk() (string, bool) { if s == nil || s.Aggr == nil { return "", false } return *s.Aggr, true } // HasAggr returns a boolean if a field has been set. func (s *Series) HasAggr() bool { if s != nil && s.Aggr != nil { return true } return false } // SetAggr allocates a new s.Aggr and returns the pointer to it. func (s *Series) SetAggr(v string) { s.Aggr = &v } // GetDisplayName returns the DisplayName field if non-nil, zero value otherwise. func (s *Series) GetDisplayName() string { if s == nil || s.DisplayName == nil { return "" } return *s.DisplayName } // GetOkDisplayName returns a tuple with the DisplayName field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetDisplayNameOk() (string, bool) { if s == nil || s.DisplayName == nil { return "", false } return *s.DisplayName, true } // HasDisplayName returns a boolean if a field has been set. func (s *Series) HasDisplayName() bool { if s != nil && s.DisplayName != nil { return true } return false } // SetDisplayName allocates a new s.DisplayName and returns the pointer to it. func (s *Series) SetDisplayName(v string) { s.DisplayName = &v } // GetEnd returns the End field if non-nil, zero value otherwise. func (s *Series) GetEnd() float64 { if s == nil || s.End == nil { return 0 } return *s.End } // GetOkEnd returns a tuple with the End field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetEndOk() (float64, bool) { if s == nil || s.End == nil { return 0, false } return *s.End, true } // HasEnd returns a boolean if a field has been set. func (s *Series) HasEnd() bool { if s != nil && s.End != nil { return true } return false } // SetEnd allocates a new s.End and returns the pointer to it. func (s *Series) SetEnd(v float64) { s.End = &v } // GetExpression returns the Expression field if non-nil, zero value otherwise. func (s *Series) GetExpression() string { if s == nil || s.Expression == nil { return "" } return *s.Expression } // GetOkExpression returns a tuple with the Expression field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetExpressionOk() (string, bool) { if s == nil || s.Expression == nil { return "", false } return *s.Expression, true } // HasExpression returns a boolean if a field has been set. func (s *Series) HasExpression() bool { if s != nil && s.Expression != nil { return true } return false } // SetExpression allocates a new s.Expression and returns the pointer to it. func (s *Series) SetExpression(v string) { s.Expression = &v } // GetInterval returns the Interval field if non-nil, zero value otherwise. func (s *Series) GetInterval() int { if s == nil || s.Interval == nil { return 0 } return *s.Interval } // GetOkInterval returns a tuple with the Interval field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetIntervalOk() (int, bool) { if s == nil || s.Interval == nil { return 0, false } return *s.Interval, true } // HasInterval returns a boolean if a field has been set. func (s *Series) HasInterval() bool { if s != nil && s.Interval != nil { return true } return false } // SetInterval allocates a new s.Interval and returns the pointer to it. func (s *Series) SetInterval(v int) { s.Interval = &v } // GetLength returns the Length field if non-nil, zero value otherwise. func (s *Series) GetLength() int { if s == nil || s.Length == nil { return 0 } return *s.Length } // GetOkLength returns a tuple with the Length field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetLengthOk() (int, bool) { if s == nil || s.Length == nil { return 0, false } return *s.Length, true } // HasLength returns a boolean if a field has been set. func (s *Series) HasLength() bool { if s != nil && s.Length != nil { return true } return false } // SetLength allocates a new s.Length and returns the pointer to it. func (s *Series) SetLength(v int) { s.Length = &v } // GetMetric returns the Metric field if non-nil, zero value otherwise. func (s *Series) GetMetric() string { if s == nil || s.Metric == nil { return "" } return *s.Metric } // GetOkMetric returns a tuple with the Metric field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetMetricOk() (string, bool) { if s == nil || s.Metric == nil { return "", false } return *s.Metric, true } // HasMetric returns a boolean if a field has been set. func (s *Series) HasMetric() bool { if s != nil && s.Metric != nil { return true } return false } // SetMetric allocates a new s.Metric and returns the pointer to it. func (s *Series) SetMetric(v string) { s.Metric = &v } // GetScope returns the Scope field if non-nil, zero value otherwise. func (s *Series) GetScope() string { if s == nil || s.Scope == nil { return "" } return *s.Scope } // GetOkScope returns a tuple with the Scope field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetScopeOk() (string, bool) { if s == nil || s.Scope == nil { return "", false } return *s.Scope, true } // HasScope returns a boolean if a field has been set. func (s *Series) HasScope() bool { if s != nil && s.Scope != nil { return true } return false } // SetScope allocates a new s.Scope and returns the pointer to it. func (s *Series) SetScope(v string) { s.Scope = &v } // GetStart returns the Start field if non-nil, zero value otherwise. func (s *Series) GetStart() float64 { if s == nil || s.Start == nil { return 0 } return *s.Start } // GetOkStart returns a tuple with the Start field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetStartOk() (float64, bool) { if s == nil || s.Start == nil { return 0, false } return *s.Start, true } // HasStart returns a boolean if a field has been set. func (s *Series) HasStart() bool { if s != nil && s.Start != nil { return true } return false } // SetStart allocates a new s.Start and returns the pointer to it. func (s *Series) SetStart(v float64) { s.Start = &v } // GetUnits returns the Units field if non-nil, zero value otherwise. func (s *Series) GetUnits() UnitPair { if s == nil || s.Units == nil { return UnitPair{} } return *s.Units } // GetOkUnits returns a tuple with the Units field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetUnitsOk() (UnitPair, bool) { if s == nil || s.Units == nil { return UnitPair{}, false } return *s.Units, true } // HasUnits returns a boolean if a field has been set. func (s *Series) HasUnits() bool { if s != nil && s.Units != nil { return true } return false } // SetUnits allocates a new s.Units and returns the pointer to it. func (s *Series) SetUnits(v UnitPair) { s.Units = &v } // GetAccount returns the Account field if non-nil, zero value otherwise. func (s *ServiceHookSlackRequest) GetAccount() string { if s == nil || s.Account == nil { return "" } return *s.Account } // GetOkAccount returns a tuple with the Account field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *ServiceHookSlackRequest) GetAccountOk() (string, bool) { if s == nil || s.Account == nil { return "", false } return *s.Account, true } // HasAccount returns a boolean if a field has been set. func (s *ServiceHookSlackRequest) HasAccount() bool { if s != nil && s.Account != nil { return true } return false } // SetAccount allocates a new s.Account and returns the pointer to it. func (s *ServiceHookSlackRequest) SetAccount(v string) { s.Account = &v } // GetUrl returns the Url field if non-nil, zero value otherwise. func (s *ServiceHookSlackRequest) GetUrl() string { if s == nil || s.Url == nil { return "" } return *s.Url } // GetOkUrl returns a tuple with the Url field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *ServiceHookSlackRequest) GetUrlOk() (string, bool) { if s == nil || s.Url == nil { return "", false } return *s.Url, true } // HasUrl returns a boolean if a field has been set. func (s *ServiceHookSlackRequest) HasUrl() bool { if s != nil && s.Url != nil { return true } return false } // SetUrl allocates a new s.Url and returns the pointer to it. func (s *ServiceHookSlackRequest) SetUrl(v string) { s.Url = &v } // GetServiceKey returns the ServiceKey field if non-nil, zero value otherwise. func (s *servicePD) GetServiceKey() string { if s == nil || s.ServiceKey == nil { return "" } return *s.ServiceKey } // GetOkServiceKey returns a tuple with the ServiceKey field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *servicePD) GetServiceKeyOk() (string, bool) { if s == nil || s.ServiceKey == nil { return "", false } return *s.ServiceKey, true } // HasServiceKey returns a boolean if a field has been set. func (s *servicePD) HasServiceKey() bool { if s != nil && s.ServiceKey != nil { return true } return false } // SetServiceKey allocates a new s.ServiceKey and returns the pointer to it. func (s *servicePD) SetServiceKey(v string) { s.ServiceKey = &v } // GetServiceName returns the ServiceName field if non-nil, zero value otherwise. func (s *servicePD) GetServiceName() string { if s == nil || s.ServiceName == nil { return "" } return *s.ServiceName } // GetOkServiceName returns a tuple with the ServiceName field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *servicePD) GetServiceNameOk() (string, bool) { if s == nil || s.ServiceName == nil { return "", false } return *s.ServiceName, true } // HasServiceName returns a boolean if a field has been set. func (s *servicePD) HasServiceName() bool { if s != nil && s.ServiceName != nil { return true } return false } // SetServiceName allocates a new s.ServiceName and returns the pointer to it. func (s *servicePD) SetServiceName(v string) { s.ServiceName = &v } // GetServiceKey returns the ServiceKey field if non-nil, zero value otherwise. func (s *ServicePDRequest) GetServiceKey() string { if s == nil || s.ServiceKey == nil { return "" } return *s.ServiceKey } // GetOkServiceKey returns a tuple with the ServiceKey field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *ServicePDRequest) GetServiceKeyOk() (string, bool) { if s == nil || s.ServiceKey == nil { return "", false } return *s.ServiceKey, true } // HasServiceKey returns a boolean if a field has been set. func (s *ServicePDRequest) HasServiceKey() bool { if s != nil && s.ServiceKey != nil { return true } return false } // SetServiceKey allocates a new s.ServiceKey and returns the pointer to it. func (s *ServicePDRequest) SetServiceKey(v string) { s.ServiceKey = &v } // GetServiceName returns the ServiceName field if non-nil, zero value otherwise. func (s *ServicePDRequest) GetServiceName() string { if s == nil || s.ServiceName == nil { return "" } return *s.ServiceName } // GetOkServiceName returns a tuple with the ServiceName field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *ServicePDRequest) GetServiceNameOk() (string, bool) { if s == nil || s.ServiceName == nil { return "", false } return *s.ServiceName, true } // HasServiceName returns a boolean if a field has been set. func (s *ServicePDRequest) HasServiceName() bool { if s != nil && s.ServiceName != nil { return true } return false } // SetServiceName allocates a new s.ServiceName and returns the pointer to it. func (s *ServicePDRequest) SetServiceName(v string) { s.ServiceName = &v } // GetPalette returns the Palette field if non-nil, zero value otherwise. func (s *Style) GetPalette() string { if s == nil || s.Palette == nil { return "" } return *s.Palette } // GetOkPalette returns a tuple with the Palette field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Style) GetPaletteOk() (string, bool) { if s == nil || s.Palette == nil { return "", false } return *s.Palette, true } // HasPalette returns a boolean if a field has been set. func (s *Style) HasPalette() bool { if s != nil && s.Palette != nil { return true } return false } // SetPalette allocates a new s.Palette and returns the pointer to it. func (s *Style) SetPalette(v string) { s.Palette = &v } // GetPaletteFlip returns the PaletteFlip field if non-nil, zero value otherwise. func (s *Style) GetPaletteFlip() bool { if s == nil || s.PaletteFlip == nil { return false } return *s.PaletteFlip } // GetOkPaletteFlip returns a tuple with the PaletteFlip field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Style) GetPaletteFlipOk() (bool, bool) { if s == nil || s.PaletteFlip == nil { return false, false } return *s.PaletteFlip, true } // HasPaletteFlip returns a boolean if a field has been set. func (s *Style) HasPaletteFlip() bool { if s != nil && s.PaletteFlip != nil { return true } return false } // SetPaletteFlip allocates a new s.PaletteFlip and returns the pointer to it. func (s *Style) SetPaletteFlip(v bool) { s.PaletteFlip = &v } // GetDefault returns the Default field if non-nil, zero value otherwise. func (t *TemplateVariable) GetDefault() string { if t == nil || t.Default == nil { return "" } return *t.Default } // GetOkDefault returns a tuple with the Default field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TemplateVariable) GetDefaultOk() (string, bool) { if t == nil || t.Default == nil { return "", false } return *t.Default, true } // HasDefault returns a boolean if a field has been set. func (t *TemplateVariable) HasDefault() bool { if t != nil && t.Default != nil { return true } return false } // SetDefault allocates a new t.Default and returns the pointer to it. func (t *TemplateVariable) SetDefault(v string) { t.Default = &v } // GetName returns the Name field if non-nil, zero value otherwise. func (t *TemplateVariable) GetName() string { if t == nil || t.Name == nil { return "" } return *t.Name } // GetOkName returns a tuple with the Name field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TemplateVariable) GetNameOk() (string, bool) { if t == nil || t.Name == nil { return "", false } return *t.Name, true } // HasName returns a boolean if a field has been set. func (t *TemplateVariable) HasName() bool { if t != nil && t.Name != nil { return true } return false } // SetName allocates a new t.Name and returns the pointer to it. func (t *TemplateVariable) SetName(v string) { t.Name = &v } // GetPrefix returns the Prefix field if non-nil, zero value otherwise. func (t *TemplateVariable) GetPrefix() string { if t == nil || t.Prefix == nil { return "" } return *t.Prefix } // GetOkPrefix returns a tuple with the Prefix field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TemplateVariable) GetPrefixOk() (string, bool) { if t == nil || t.Prefix == nil { return "", false } return *t.Prefix, true } // HasPrefix returns a boolean if a field has been set. func (t *TemplateVariable) HasPrefix() bool { if t != nil && t.Prefix != nil { return true } return false } // SetPrefix allocates a new t.Prefix and returns the pointer to it. func (t *TemplateVariable) SetPrefix(v string) { t.Prefix = &v } // GetCritical returns the Critical field if non-nil, zero value otherwise. func (t *ThresholdCount) GetCritical() json.Number { if t == nil || t.Critical == nil { return "" } return *t.Critical } // GetOkCritical returns a tuple with the Critical field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ThresholdCount) GetCriticalOk() (json.Number, bool) { if t == nil || t.Critical == nil { return "", false } return *t.Critical, true } // HasCritical returns a boolean if a field has been set. func (t *ThresholdCount) HasCritical() bool { if t != nil && t.Critical != nil { return true } return false } // SetCritical allocates a new t.Critical and returns the pointer to it. func (t *ThresholdCount) SetCritical(v json.Number) { t.Critical = &v } // GetCriticalRecovery returns the CriticalRecovery field if non-nil, zero value otherwise. func (t *ThresholdCount) GetCriticalRecovery() json.Number { if t == nil || t.CriticalRecovery == nil { return "" } return *t.CriticalRecovery } // GetOkCriticalRecovery returns a tuple with the CriticalRecovery field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ThresholdCount) GetCriticalRecoveryOk() (json.Number, bool) { if t == nil || t.CriticalRecovery == nil { return "", false } return *t.CriticalRecovery, true } // HasCriticalRecovery returns a boolean if a field has been set. func (t *ThresholdCount) HasCriticalRecovery() bool { if t != nil && t.CriticalRecovery != nil { return true } return false } // SetCriticalRecovery allocates a new t.CriticalRecovery and returns the pointer to it. func (t *ThresholdCount) SetCriticalRecovery(v json.Number) { t.CriticalRecovery = &v } // GetOk returns the Ok field if non-nil, zero value otherwise. func (t *ThresholdCount) GetOk() json.Number { if t == nil || t.Ok == nil { return "" } return *t.Ok } // GetOkOk returns a tuple with the Ok field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ThresholdCount) GetOkOk() (json.Number, bool) { if t == nil || t.Ok == nil { return "", false } return *t.Ok, true } // HasOk returns a boolean if a field has been set. func (t *ThresholdCount) HasOk() bool { if t != nil && t.Ok != nil { return true } return false } // SetOk allocates a new t.Ok and returns the pointer to it. func (t *ThresholdCount) SetOk(v json.Number) { t.Ok = &v } // GetUnknown returns the Unknown field if non-nil, zero value otherwise. func (t *ThresholdCount) GetUnknown() json.Number { if t == nil || t.Unknown == nil { return "" } return *t.Unknown } // GetOkUnknown returns a tuple with the Unknown field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ThresholdCount) GetUnknownOk() (json.Number, bool) { if t == nil || t.Unknown == nil { return "", false } return *t.Unknown, true } // HasUnknown returns a boolean if a field has been set. func (t *ThresholdCount) HasUnknown() bool { if t != nil && t.Unknown != nil { return true } return false } // SetUnknown allocates a new t.Unknown and returns the pointer to it. func (t *ThresholdCount) SetUnknown(v json.Number) { t.Unknown = &v } // GetWarning returns the Warning field if non-nil, zero value otherwise. func (t *ThresholdCount) GetWarning() json.Number { if t == nil || t.Warning == nil { return "" } return *t.Warning } // GetOkWarning returns a tuple with the Warning field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ThresholdCount) GetWarningOk() (json.Number, bool) { if t == nil || t.Warning == nil { return "", false } return *t.Warning, true } // HasWarning returns a boolean if a field has been set. func (t *ThresholdCount) HasWarning() bool { if t != nil && t.Warning != nil { return true } return false } // SetWarning allocates a new t.Warning and returns the pointer to it. func (t *ThresholdCount) SetWarning(v json.Number) { t.Warning = &v } // GetWarningRecovery returns the WarningRecovery field if non-nil, zero value otherwise. func (t *ThresholdCount) GetWarningRecovery() json.Number { if t == nil || t.WarningRecovery == nil { return "" } return *t.WarningRecovery } // GetOkWarningRecovery returns a tuple with the WarningRecovery field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ThresholdCount) GetWarningRecoveryOk() (json.Number, bool) { if t == nil || t.WarningRecovery == nil { return "", false } return *t.WarningRecovery, true } // HasWarningRecovery returns a boolean if a field has been set. func (t *ThresholdCount) HasWarningRecovery() bool { if t != nil && t.WarningRecovery != nil { return true } return false } // SetWarningRecovery allocates a new t.WarningRecovery and returns the pointer to it. func (t *ThresholdCount) SetWarningRecovery(v json.Number) { t.WarningRecovery = &v } // GetAutoscale returns the Autoscale field if non-nil, zero value otherwise. func (t *TileDef) GetAutoscale() bool { if t == nil || t.Autoscale == nil { return false } return *t.Autoscale } // GetOkAutoscale returns a tuple with the Autoscale field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDef) GetAutoscaleOk() (bool, bool) { if t == nil || t.Autoscale == nil { return false, false } return *t.Autoscale, true } // HasAutoscale returns a boolean if a field has been set. func (t *TileDef) HasAutoscale() bool { if t != nil && t.Autoscale != nil { return true } return false } // SetAutoscale allocates a new t.Autoscale and returns the pointer to it. func (t *TileDef) SetAutoscale(v bool) { t.Autoscale = &v } // GetCustomUnit returns the CustomUnit field if non-nil, zero value otherwise. func (t *TileDef) GetCustomUnit() string { if t == nil || t.CustomUnit == nil { return "" } return *t.CustomUnit } // GetOkCustomUnit returns a tuple with the CustomUnit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDef) GetCustomUnitOk() (string, bool) { if t == nil || t.CustomUnit == nil { return "", false } return *t.CustomUnit, true } // HasCustomUnit returns a boolean if a field has been set. func (t *TileDef) HasCustomUnit() bool { if t != nil && t.CustomUnit != nil { return true } return false } // SetCustomUnit allocates a new t.CustomUnit and returns the pointer to it. func (t *TileDef) SetCustomUnit(v string) { t.CustomUnit = &v } // GetNodeType returns the NodeType field if non-nil, zero value otherwise. func (t *TileDef) GetNodeType() string { if t == nil || t.NodeType == nil { return "" } return *t.NodeType } // GetOkNodeType returns a tuple with the NodeType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDef) GetNodeTypeOk() (string, bool) { if t == nil || t.NodeType == nil { return "", false } return *t.NodeType, true } // HasNodeType returns a boolean if a field has been set. func (t *TileDef) HasNodeType() bool { if t != nil && t.NodeType != nil { return true } return false } // SetNodeType allocates a new t.NodeType and returns the pointer to it. func (t *TileDef) SetNodeType(v string) { t.NodeType = &v } // GetNoGroupHosts returns the NoGroupHosts field if non-nil, zero value otherwise. func (t *TileDef) GetNoGroupHosts() bool { if t == nil || t.NoGroupHosts == nil { return false } return *t.NoGroupHosts } // GetOkNoGroupHosts returns a tuple with the NoGroupHosts field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDef) GetNoGroupHostsOk() (bool, bool) { if t == nil || t.NoGroupHosts == nil { return false, false } return *t.NoGroupHosts, true } // HasNoGroupHosts returns a boolean if a field has been set. func (t *TileDef) HasNoGroupHosts() bool { if t != nil && t.NoGroupHosts != nil { return true } return false } // SetNoGroupHosts allocates a new t.NoGroupHosts and returns the pointer to it. func (t *TileDef) SetNoGroupHosts(v bool) { t.NoGroupHosts = &v } // GetNoMetricHosts returns the NoMetricHosts field if non-nil, zero value otherwise. func (t *TileDef) GetNoMetricHosts() bool { if t == nil || t.NoMetricHosts == nil { return false } return *t.NoMetricHosts } // GetOkNoMetricHosts returns a tuple with the NoMetricHosts field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDef) GetNoMetricHostsOk() (bool, bool) { if t == nil || t.NoMetricHosts == nil { return false, false } return *t.NoMetricHosts, true } // HasNoMetricHosts returns a boolean if a field has been set. func (t *TileDef) HasNoMetricHosts() bool { if t != nil && t.NoMetricHosts != nil { return true } return false } // SetNoMetricHosts allocates a new t.NoMetricHosts and returns the pointer to it. func (t *TileDef) SetNoMetricHosts(v bool) { t.NoMetricHosts = &v } // GetPrecision returns the Precision field if non-nil, zero value otherwise. func (t *TileDef) GetPrecision() string { if t == nil || t.Precision == nil { return "" } return *t.Precision } // GetOkPrecision returns a tuple with the Precision field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDef) GetPrecisionOk() (string, bool) { if t == nil || t.Precision == nil { return "", false } return *t.Precision, true } // HasPrecision returns a boolean if a field has been set. func (t *TileDef) HasPrecision() bool { if t != nil && t.Precision != nil { return true } return false } // SetPrecision allocates a new t.Precision and returns the pointer to it. func (t *TileDef) SetPrecision(v string) { t.Precision = &v } // GetStyle returns the Style field if non-nil, zero value otherwise. func (t *TileDef) GetStyle() TileDefStyle { if t == nil || t.Style == nil { return TileDefStyle{} } return *t.Style } // GetOkStyle returns a tuple with the Style field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDef) GetStyleOk() (TileDefStyle, bool) { if t == nil || t.Style == nil { return TileDefStyle{}, false } return *t.Style, true } // HasStyle returns a boolean if a field has been set. func (t *TileDef) HasStyle() bool { if t != nil && t.Style != nil { return true } return false } // SetStyle allocates a new t.Style and returns the pointer to it. func (t *TileDef) SetStyle(v TileDefStyle) { t.Style = &v } // GetTextAlign returns the TextAlign field if non-nil, zero value otherwise. func (t *TileDef) GetTextAlign() string { if t == nil || t.TextAlign == nil { return "" } return *t.TextAlign } // GetOkTextAlign returns a tuple with the TextAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDef) GetTextAlignOk() (string, bool) { if t == nil || t.TextAlign == nil { return "", false } return *t.TextAlign, true } // HasTextAlign returns a boolean if a field has been set. func (t *TileDef) HasTextAlign() bool { if t != nil && t.TextAlign != nil { return true } return false } // SetTextAlign allocates a new t.TextAlign and returns the pointer to it. func (t *TileDef) SetTextAlign(v string) { t.TextAlign = &v } // GetViz returns the Viz field if non-nil, zero value otherwise. func (t *TileDef) GetViz() string { if t == nil || t.Viz == nil { return "" } return *t.Viz } // GetOkViz returns a tuple with the Viz field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDef) GetVizOk() (string, bool) { if t == nil || t.Viz == nil { return "", false } return *t.Viz, true } // HasViz returns a boolean if a field has been set. func (t *TileDef) HasViz() bool { if t != nil && t.Viz != nil { return true } return false } // SetViz allocates a new t.Viz and returns the pointer to it. func (t *TileDef) SetViz(v string) { t.Viz = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (t *TileDefEvent) GetQuery() string { if t == nil || t.Query == nil { return "" } return *t.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefEvent) GetQueryOk() (string, bool) { if t == nil || t.Query == nil { return "", false } return *t.Query, true } // HasQuery returns a boolean if a field has been set. func (t *TileDefEvent) HasQuery() bool { if t != nil && t.Query != nil { return true } return false } // SetQuery allocates a new t.Query and returns the pointer to it. func (t *TileDefEvent) SetQuery(v string) { t.Query = &v } // GetLabel returns the Label field if non-nil, zero value otherwise. func (t *TileDefMarker) GetLabel() string { if t == nil || t.Label == nil { return "" } return *t.Label } // GetOkLabel returns a tuple with the Label field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefMarker) GetLabelOk() (string, bool) { if t == nil || t.Label == nil { return "", false } return *t.Label, true } // HasLabel returns a boolean if a field has been set. func (t *TileDefMarker) HasLabel() bool { if t != nil && t.Label != nil { return true } return false } // SetLabel allocates a new t.Label and returns the pointer to it. func (t *TileDefMarker) SetLabel(v string) { t.Label = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (t *TileDefMarker) GetType() string { if t == nil || t.Type == nil { return "" } return *t.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefMarker) GetTypeOk() (string, bool) { if t == nil || t.Type == nil { return "", false } return *t.Type, true } // HasType returns a boolean if a field has been set. func (t *TileDefMarker) HasType() bool { if t != nil && t.Type != nil { return true } return false } // SetType allocates a new t.Type and returns the pointer to it. func (t *TileDefMarker) SetType(v string) { t.Type = &v } // GetValue returns the Value field if non-nil, zero value otherwise. func (t *TileDefMarker) GetValue() string { if t == nil || t.Value == nil { return "" } return *t.Value } // GetOkValue returns a tuple with the Value field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefMarker) GetValueOk() (string, bool) { if t == nil || t.Value == nil { return "", false } return *t.Value, true } // HasValue returns a boolean if a field has been set. func (t *TileDefMarker) HasValue() bool { if t != nil && t.Value != nil { return true } return false } // SetValue allocates a new t.Value and returns the pointer to it. func (t *TileDefMarker) SetValue(v string) { t.Value = &v } // GetAggregator returns the Aggregator field if non-nil, zero value otherwise. func (t *TileDefRequest) GetAggregator() string { if t == nil || t.Aggregator == nil { return "" } return *t.Aggregator } // GetOkAggregator returns a tuple with the Aggregator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetAggregatorOk() (string, bool) { if t == nil || t.Aggregator == nil { return "", false } return *t.Aggregator, true } // HasAggregator returns a boolean if a field has been set. func (t *TileDefRequest) HasAggregator() bool { if t != nil && t.Aggregator != nil { return true } return false } // SetAggregator allocates a new t.Aggregator and returns the pointer to it. func (t *TileDefRequest) SetAggregator(v string) { t.Aggregator = &v } // GetChangeType returns the ChangeType field if non-nil, zero value otherwise. func (t *TileDefRequest) GetChangeType() string { if t == nil || t.ChangeType == nil { return "" } return *t.ChangeType } // GetOkChangeType returns a tuple with the ChangeType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetChangeTypeOk() (string, bool) { if t == nil || t.ChangeType == nil { return "", false } return *t.ChangeType, true } // HasChangeType returns a boolean if a field has been set. func (t *TileDefRequest) HasChangeType() bool { if t != nil && t.ChangeType != nil { return true } return false } // SetChangeType allocates a new t.ChangeType and returns the pointer to it. func (t *TileDefRequest) SetChangeType(v string) { t.ChangeType = &v } // GetCompareTo returns the CompareTo field if non-nil, zero value otherwise. func (t *TileDefRequest) GetCompareTo() string { if t == nil || t.CompareTo == nil { return "" } return *t.CompareTo } // GetOkCompareTo returns a tuple with the CompareTo field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetCompareToOk() (string, bool) { if t == nil || t.CompareTo == nil { return "", false } return *t.CompareTo, true } // HasCompareTo returns a boolean if a field has been set. func (t *TileDefRequest) HasCompareTo() bool { if t != nil && t.CompareTo != nil { return true } return false } // SetCompareTo allocates a new t.CompareTo and returns the pointer to it. func (t *TileDefRequest) SetCompareTo(v string) { t.CompareTo = &v } // GetExtraCol returns the ExtraCol field if non-nil, zero value otherwise. func (t *TileDefRequest) GetExtraCol() string { if t == nil || t.ExtraCol == nil { return "" } return *t.ExtraCol } // GetOkExtraCol returns a tuple with the ExtraCol field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetExtraColOk() (string, bool) { if t == nil || t.ExtraCol == nil { return "", false } return *t.ExtraCol, true } // HasExtraCol returns a boolean if a field has been set. func (t *TileDefRequest) HasExtraCol() bool { if t != nil && t.ExtraCol != nil { return true } return false } // SetExtraCol allocates a new t.ExtraCol and returns the pointer to it. func (t *TileDefRequest) SetExtraCol(v string) { t.ExtraCol = &v } // GetIncreaseGood returns the IncreaseGood field if non-nil, zero value otherwise. func (t *TileDefRequest) GetIncreaseGood() bool { if t == nil || t.IncreaseGood == nil { return false } return *t.IncreaseGood } // GetOkIncreaseGood returns a tuple with the IncreaseGood field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetIncreaseGoodOk() (bool, bool) { if t == nil || t.IncreaseGood == nil { return false, false } return *t.IncreaseGood, true } // HasIncreaseGood returns a boolean if a field has been set. func (t *TileDefRequest) HasIncreaseGood() bool { if t != nil && t.IncreaseGood != nil { return true } return false } // SetIncreaseGood allocates a new t.IncreaseGood and returns the pointer to it. func (t *TileDefRequest) SetIncreaseGood(v bool) { t.IncreaseGood = &v } // GetLimit returns the Limit field if non-nil, zero value otherwise. func (t *TileDefRequest) GetLimit() int { if t == nil || t.Limit == nil { return 0 } return *t.Limit } // GetOkLimit returns a tuple with the Limit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetLimitOk() (int, bool) { if t == nil || t.Limit == nil { return 0, false } return *t.Limit, true } // HasLimit returns a boolean if a field has been set. func (t *TileDefRequest) HasLimit() bool { if t != nil && t.Limit != nil { return true } return false } // SetLimit allocates a new t.Limit and returns the pointer to it. func (t *TileDefRequest) SetLimit(v int) { t.Limit = &v } // GetMetric returns the Metric field if non-nil, zero value otherwise. func (t *TileDefRequest) GetMetric() string { if t == nil || t.Metric == nil { return "" } return *t.Metric } // GetOkMetric returns a tuple with the Metric field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetMetricOk() (string, bool) { if t == nil || t.Metric == nil { return "", false } return *t.Metric, true } // HasMetric returns a boolean if a field has been set. func (t *TileDefRequest) HasMetric() bool { if t != nil && t.Metric != nil { return true } return false } // SetMetric allocates a new t.Metric and returns the pointer to it. func (t *TileDefRequest) SetMetric(v string) { t.Metric = &v } // GetOrderBy returns the OrderBy field if non-nil, zero value otherwise. func (t *TileDefRequest) GetOrderBy() string { if t == nil || t.OrderBy == nil { return "" } return *t.OrderBy } // GetOkOrderBy returns a tuple with the OrderBy field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetOrderByOk() (string, bool) { if t == nil || t.OrderBy == nil { return "", false } return *t.OrderBy, true } // HasOrderBy returns a boolean if a field has been set. func (t *TileDefRequest) HasOrderBy() bool { if t != nil && t.OrderBy != nil { return true } return false } // SetOrderBy allocates a new t.OrderBy and returns the pointer to it. func (t *TileDefRequest) SetOrderBy(v string) { t.OrderBy = &v } // GetOrderDir returns the OrderDir field if non-nil, zero value otherwise. func (t *TileDefRequest) GetOrderDir() string { if t == nil || t.OrderDir == nil { return "" } return *t.OrderDir } // GetOkOrderDir returns a tuple with the OrderDir field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetOrderDirOk() (string, bool) { if t == nil || t.OrderDir == nil { return "", false } return *t.OrderDir, true } // HasOrderDir returns a boolean if a field has been set. func (t *TileDefRequest) HasOrderDir() bool { if t != nil && t.OrderDir != nil { return true } return false } // SetOrderDir allocates a new t.OrderDir and returns the pointer to it. func (t *TileDefRequest) SetOrderDir(v string) { t.OrderDir = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (t *TileDefRequest) GetQuery() string { if t == nil || t.Query == nil { return "" } return *t.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetQueryOk() (string, bool) { if t == nil || t.Query == nil { return "", false } return *t.Query, true } // HasQuery returns a boolean if a field has been set. func (t *TileDefRequest) HasQuery() bool { if t != nil && t.Query != nil { return true } return false } // SetQuery allocates a new t.Query and returns the pointer to it. func (t *TileDefRequest) SetQuery(v string) { t.Query = &v } // GetQueryType returns the QueryType field if non-nil, zero value otherwise. func (t *TileDefRequest) GetQueryType() string { if t == nil || t.QueryType == nil { return "" } return *t.QueryType } // GetOkQueryType returns a tuple with the QueryType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetQueryTypeOk() (string, bool) { if t == nil || t.QueryType == nil { return "", false } return *t.QueryType, true } // HasQueryType returns a boolean if a field has been set. func (t *TileDefRequest) HasQueryType() bool { if t != nil && t.QueryType != nil { return true } return false } // SetQueryType allocates a new t.QueryType and returns the pointer to it. func (t *TileDefRequest) SetQueryType(v string) { t.QueryType = &v } // GetStyle returns the Style field if non-nil, zero value otherwise. func (t *TileDefRequest) GetStyle() TileDefRequestStyle { if t == nil || t.Style == nil { return TileDefRequestStyle{} } return *t.Style } // GetOkStyle returns a tuple with the Style field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetStyleOk() (TileDefRequestStyle, bool) { if t == nil || t.Style == nil { return TileDefRequestStyle{}, false } return *t.Style, true } // HasStyle returns a boolean if a field has been set. func (t *TileDefRequest) HasStyle() bool { if t != nil && t.Style != nil { return true } return false } // SetStyle allocates a new t.Style and returns the pointer to it. func (t *TileDefRequest) SetStyle(v TileDefRequestStyle) { t.Style = &v } // GetTextFilter returns the TextFilter field if non-nil, zero value otherwise. func (t *TileDefRequest) GetTextFilter() string { if t == nil || t.TextFilter == nil { return "" } return *t.TextFilter } // GetOkTextFilter returns a tuple with the TextFilter field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetTextFilterOk() (string, bool) { if t == nil || t.TextFilter == nil { return "", false } return *t.TextFilter, true } // HasTextFilter returns a boolean if a field has been set. func (t *TileDefRequest) HasTextFilter() bool { if t != nil && t.TextFilter != nil { return true } return false } // SetTextFilter allocates a new t.TextFilter and returns the pointer to it. func (t *TileDefRequest) SetTextFilter(v string) { t.TextFilter = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (t *TileDefRequest) GetType() string { if t == nil || t.Type == nil { return "" } return *t.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequest) GetTypeOk() (string, bool) { if t == nil || t.Type == nil { return "", false } return *t.Type, true } // HasType returns a boolean if a field has been set. func (t *TileDefRequest) HasType() bool { if t != nil && t.Type != nil { return true } return false } // SetType allocates a new t.Type and returns the pointer to it. func (t *TileDefRequest) SetType(v string) { t.Type = &v } // GetPalette returns the Palette field if non-nil, zero value otherwise. func (t *TileDefRequestStyle) GetPalette() string { if t == nil || t.Palette == nil { return "" } return *t.Palette } // GetOkPalette returns a tuple with the Palette field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequestStyle) GetPaletteOk() (string, bool) { if t == nil || t.Palette == nil { return "", false } return *t.Palette, true } // HasPalette returns a boolean if a field has been set. func (t *TileDefRequestStyle) HasPalette() bool { if t != nil && t.Palette != nil { return true } return false } // SetPalette allocates a new t.Palette and returns the pointer to it. func (t *TileDefRequestStyle) SetPalette(v string) { t.Palette = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (t *TileDefRequestStyle) GetType() string { if t == nil || t.Type == nil { return "" } return *t.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequestStyle) GetTypeOk() (string, bool) { if t == nil || t.Type == nil { return "", false } return *t.Type, true } // HasType returns a boolean if a field has been set. func (t *TileDefRequestStyle) HasType() bool { if t != nil && t.Type != nil { return true } return false } // SetType allocates a new t.Type and returns the pointer to it. func (t *TileDefRequestStyle) SetType(v string) { t.Type = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (t *TileDefRequestStyle) GetWidth() string { if t == nil || t.Width == nil { return "" } return *t.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefRequestStyle) GetWidthOk() (string, bool) { if t == nil || t.Width == nil { return "", false } return *t.Width, true } // HasWidth returns a boolean if a field has been set. func (t *TileDefRequestStyle) HasWidth() bool { if t != nil && t.Width != nil { return true } return false } // SetWidth allocates a new t.Width and returns the pointer to it. func (t *TileDefRequestStyle) SetWidth(v string) { t.Width = &v } // GetFillMax returns the FillMax field if non-nil, zero value otherwise. func (t *TileDefStyle) GetFillMax() string { if t == nil || t.FillMax == nil { return "" } return *t.FillMax } // GetOkFillMax returns a tuple with the FillMax field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefStyle) GetFillMaxOk() (string, bool) { if t == nil || t.FillMax == nil { return "", false } return *t.FillMax, true } // HasFillMax returns a boolean if a field has been set. func (t *TileDefStyle) HasFillMax() bool { if t != nil && t.FillMax != nil { return true } return false } // SetFillMax allocates a new t.FillMax and returns the pointer to it. func (t *TileDefStyle) SetFillMax(v string) { t.FillMax = &v } // GetFillMin returns the FillMin field if non-nil, zero value otherwise. func (t *TileDefStyle) GetFillMin() string { if t == nil || t.FillMin == nil { return "" } return *t.FillMin } // GetOkFillMin returns a tuple with the FillMin field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefStyle) GetFillMinOk() (string, bool) { if t == nil || t.FillMin == nil { return "", false } return *t.FillMin, true } // HasFillMin returns a boolean if a field has been set. func (t *TileDefStyle) HasFillMin() bool { if t != nil && t.FillMin != nil { return true } return false } // SetFillMin allocates a new t.FillMin and returns the pointer to it. func (t *TileDefStyle) SetFillMin(v string) { t.FillMin = &v } // GetPalette returns the Palette field if non-nil, zero value otherwise. func (t *TileDefStyle) GetPalette() string { if t == nil || t.Palette == nil { return "" } return *t.Palette } // GetOkPalette returns a tuple with the Palette field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefStyle) GetPaletteOk() (string, bool) { if t == nil || t.Palette == nil { return "", false } return *t.Palette, true } // HasPalette returns a boolean if a field has been set. func (t *TileDefStyle) HasPalette() bool { if t != nil && t.Palette != nil { return true } return false } // SetPalette allocates a new t.Palette and returns the pointer to it. func (t *TileDefStyle) SetPalette(v string) { t.Palette = &v } // GetPaletteFlip returns the PaletteFlip field if non-nil, zero value otherwise. func (t *TileDefStyle) GetPaletteFlip() string { if t == nil || t.PaletteFlip == nil { return "" } return *t.PaletteFlip } // GetOkPaletteFlip returns a tuple with the PaletteFlip field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefStyle) GetPaletteFlipOk() (string, bool) { if t == nil || t.PaletteFlip == nil { return "", false } return *t.PaletteFlip, true } // HasPaletteFlip returns a boolean if a field has been set. func (t *TileDefStyle) HasPaletteFlip() bool { if t != nil && t.PaletteFlip != nil { return true } return false } // SetPaletteFlip allocates a new t.PaletteFlip and returns the pointer to it. func (t *TileDefStyle) SetPaletteFlip(v string) { t.PaletteFlip = &v } // GetLiveSpan returns the LiveSpan field if non-nil, zero value otherwise. func (t *Time) GetLiveSpan() string { if t == nil || t.LiveSpan == nil { return "" } return *t.LiveSpan } // GetOkLiveSpan returns a tuple with the LiveSpan field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *Time) GetLiveSpanOk() (string, bool) { if t == nil || t.LiveSpan == nil { return "", false } return *t.LiveSpan, true } // HasLiveSpan returns a boolean if a field has been set. func (t *Time) HasLiveSpan() bool { if t != nil && t.LiveSpan != nil { return true } return false } // SetLiveSpan allocates a new t.LiveSpan and returns the pointer to it. func (t *Time) SetLiveSpan(v string) { t.LiveSpan = &v } // GetAccessRole returns the AccessRole field if non-nil, zero value otherwise. func (u *User) GetAccessRole() string { if u == nil || u.AccessRole == nil { return "" } return *u.AccessRole } // GetOkAccessRole returns a tuple with the AccessRole field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetAccessRoleOk() (string, bool) { if u == nil || u.AccessRole == nil { return "", false } return *u.AccessRole, true } // HasAccessRole returns a boolean if a field has been set. func (u *User) HasAccessRole() bool { if u != nil && u.AccessRole != nil { return true } return false } // SetAccessRole allocates a new u.AccessRole and returns the pointer to it. func (u *User) SetAccessRole(v string) { u.AccessRole = &v } // GetDisabled returns the Disabled field if non-nil, zero value otherwise. func (u *User) GetDisabled() bool { if u == nil || u.Disabled == nil { return false } return *u.Disabled } // GetOkDisabled returns a tuple with the Disabled field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetDisabledOk() (bool, bool) { if u == nil || u.Disabled == nil { return false, false } return *u.Disabled, true } // HasDisabled returns a boolean if a field has been set. func (u *User) HasDisabled() bool { if u != nil && u.Disabled != nil { return true } return false } // SetDisabled allocates a new u.Disabled and returns the pointer to it. func (u *User) SetDisabled(v bool) { u.Disabled = &v } // GetEmail returns the Email field if non-nil, zero value otherwise. func (u *User) GetEmail() string { if u == nil || u.Email == nil { return "" } return *u.Email } // GetOkEmail returns a tuple with the Email field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetEmailOk() (string, bool) { if u == nil || u.Email == nil { return "", false } return *u.Email, true } // HasEmail returns a boolean if a field has been set. func (u *User) HasEmail() bool { if u != nil && u.Email != nil { return true } return false } // SetEmail allocates a new u.Email and returns the pointer to it. func (u *User) SetEmail(v string) { u.Email = &v } // GetHandle returns the Handle field if non-nil, zero value otherwise. func (u *User) GetHandle() string { if u == nil || u.Handle == nil { return "" } return *u.Handle } // GetOkHandle returns a tuple with the Handle field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetHandleOk() (string, bool) { if u == nil || u.Handle == nil { return "", false } return *u.Handle, true } // HasHandle returns a boolean if a field has been set. func (u *User) HasHandle() bool { if u != nil && u.Handle != nil { return true } return false } // SetHandle allocates a new u.Handle and returns the pointer to it. func (u *User) SetHandle(v string) { u.Handle = &v } // GetIsAdmin returns the IsAdmin field if non-nil, zero value otherwise. func (u *User) GetIsAdmin() bool { if u == nil || u.IsAdmin == nil { return false } return *u.IsAdmin } // GetOkIsAdmin returns a tuple with the IsAdmin field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetIsAdminOk() (bool, bool) { if u == nil || u.IsAdmin == nil { return false, false } return *u.IsAdmin, true } // HasIsAdmin returns a boolean if a field has been set. func (u *User) HasIsAdmin() bool { if u != nil && u.IsAdmin != nil { return true } return false } // SetIsAdmin allocates a new u.IsAdmin and returns the pointer to it. func (u *User) SetIsAdmin(v bool) { u.IsAdmin = &v } // GetName returns the Name field if non-nil, zero value otherwise. func (u *User) GetName() string { if u == nil || u.Name == nil { return "" } return *u.Name } // GetOkName returns a tuple with the Name field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetNameOk() (string, bool) { if u == nil || u.Name == nil { return "", false } return *u.Name, true } // HasName returns a boolean if a field has been set. func (u *User) HasName() bool { if u != nil && u.Name != nil { return true } return false } // SetName allocates a new u.Name and returns the pointer to it. func (u *User) SetName(v string) { u.Name = &v } // GetRole returns the Role field if non-nil, zero value otherwise. func (u *User) GetRole() string { if u == nil || u.Role == nil { return "" } return *u.Role } // GetOkRole returns a tuple with the Role field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetRoleOk() (string, bool) { if u == nil || u.Role == nil { return "", false } return *u.Role, true } // HasRole returns a boolean if a field has been set. func (u *User) HasRole() bool { if u != nil && u.Role != nil { return true } return false } // SetRole allocates a new u.Role and returns the pointer to it. func (u *User) SetRole(v string) { u.Role = &v } // GetVerified returns the Verified field if non-nil, zero value otherwise. func (u *User) GetVerified() bool { if u == nil || u.Verified == nil { return false } return *u.Verified } // GetOkVerified returns a tuple with the Verified field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetVerifiedOk() (bool, bool) { if u == nil || u.Verified == nil { return false, false } return *u.Verified, true } // HasVerified returns a boolean if a field has been set. func (u *User) HasVerified() bool { if u != nil && u.Verified != nil { return true } return false } // SetVerified allocates a new u.Verified and returns the pointer to it. func (u *User) SetVerified(v bool) { u.Verified = &v } // GetAlertID returns the AlertID field if non-nil, zero value otherwise. func (w *Widget) GetAlertID() int { if w == nil || w.AlertID == nil { return 0 } return *w.AlertID } // GetOkAlertID returns a tuple with the AlertID field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetAlertIDOk() (int, bool) { if w == nil || w.AlertID == nil { return 0, false } return *w.AlertID, true } // HasAlertID returns a boolean if a field has been set. func (w *Widget) HasAlertID() bool { if w != nil && w.AlertID != nil { return true } return false } // SetAlertID allocates a new w.AlertID and returns the pointer to it. func (w *Widget) SetAlertID(v int) { w.AlertID = &v } // GetAutoRefresh returns the AutoRefresh field if non-nil, zero value otherwise. func (w *Widget) GetAutoRefresh() bool { if w == nil || w.AutoRefresh == nil { return false } return *w.AutoRefresh } // GetOkAutoRefresh returns a tuple with the AutoRefresh field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetAutoRefreshOk() (bool, bool) { if w == nil || w.AutoRefresh == nil { return false, false } return *w.AutoRefresh, true } // HasAutoRefresh returns a boolean if a field has been set. func (w *Widget) HasAutoRefresh() bool { if w != nil && w.AutoRefresh != nil { return true } return false } // SetAutoRefresh allocates a new w.AutoRefresh and returns the pointer to it. func (w *Widget) SetAutoRefresh(v bool) { w.AutoRefresh = &v } // GetBgcolor returns the Bgcolor field if non-nil, zero value otherwise. func (w *Widget) GetBgcolor() string { if w == nil || w.Bgcolor == nil { return "" } return *w.Bgcolor } // GetOkBgcolor returns a tuple with the Bgcolor field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetBgcolorOk() (string, bool) { if w == nil || w.Bgcolor == nil { return "", false } return *w.Bgcolor, true } // HasBgcolor returns a boolean if a field has been set. func (w *Widget) HasBgcolor() bool { if w != nil && w.Bgcolor != nil { return true } return false } // SetBgcolor allocates a new w.Bgcolor and returns the pointer to it. func (w *Widget) SetBgcolor(v string) { w.Bgcolor = &v } // GetCheck returns the Check field if non-nil, zero value otherwise. func (w *Widget) GetCheck() string { if w == nil || w.Check == nil { return "" } return *w.Check } // GetOkCheck returns a tuple with the Check field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetCheckOk() (string, bool) { if w == nil || w.Check == nil { return "", false } return *w.Check, true } // HasCheck returns a boolean if a field has been set. func (w *Widget) HasCheck() bool { if w != nil && w.Check != nil { return true } return false } // SetCheck allocates a new w.Check and returns the pointer to it. func (w *Widget) SetCheck(v string) { w.Check = &v } // GetColor returns the Color field if non-nil, zero value otherwise. func (w *Widget) GetColor() string { if w == nil || w.Color == nil { return "" } return *w.Color } // GetOkColor returns a tuple with the Color field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetColorOk() (string, bool) { if w == nil || w.Color == nil { return "", false } return *w.Color, true } // HasColor returns a boolean if a field has been set. func (w *Widget) HasColor() bool { if w != nil && w.Color != nil { return true } return false } // SetColor allocates a new w.Color and returns the pointer to it. func (w *Widget) SetColor(v string) { w.Color = &v } // GetColorPreference returns the ColorPreference field if non-nil, zero value otherwise. func (w *Widget) GetColorPreference() string { if w == nil || w.ColorPreference == nil { return "" } return *w.ColorPreference } // GetOkColorPreference returns a tuple with the ColorPreference field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetColorPreferenceOk() (string, bool) { if w == nil || w.ColorPreference == nil { return "", false } return *w.ColorPreference, true } // HasColorPreference returns a boolean if a field has been set. func (w *Widget) HasColorPreference() bool { if w != nil && w.ColorPreference != nil { return true } return false } // SetColorPreference allocates a new w.ColorPreference and returns the pointer to it. func (w *Widget) SetColorPreference(v string) { w.ColorPreference = &v } // GetColumns returns the Columns field if non-nil, zero value otherwise. func (w *Widget) GetColumns() string { if w == nil || w.Columns == nil { return "" } return *w.Columns } // GetOkColumns returns a tuple with the Columns field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetColumnsOk() (string, bool) { if w == nil || w.Columns == nil { return "", false } return *w.Columns, true } // HasColumns returns a boolean if a field has been set. func (w *Widget) HasColumns() bool { if w != nil && w.Columns != nil { return true } return false } // SetColumns allocates a new w.Columns and returns the pointer to it. func (w *Widget) SetColumns(v string) { w.Columns = &v } // GetDisplayFormat returns the DisplayFormat field if non-nil, zero value otherwise. func (w *Widget) GetDisplayFormat() string { if w == nil || w.DisplayFormat == nil { return "" } return *w.DisplayFormat } // GetOkDisplayFormat returns a tuple with the DisplayFormat field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetDisplayFormatOk() (string, bool) { if w == nil || w.DisplayFormat == nil { return "", false } return *w.DisplayFormat, true } // HasDisplayFormat returns a boolean if a field has been set. func (w *Widget) HasDisplayFormat() bool { if w != nil && w.DisplayFormat != nil { return true } return false } // SetDisplayFormat allocates a new w.DisplayFormat and returns the pointer to it. func (w *Widget) SetDisplayFormat(v string) { w.DisplayFormat = &v } // GetEnv returns the Env field if non-nil, zero value otherwise. func (w *Widget) GetEnv() string { if w == nil || w.Env == nil { return "" } return *w.Env } // GetOkEnv returns a tuple with the Env field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetEnvOk() (string, bool) { if w == nil || w.Env == nil { return "", false } return *w.Env, true } // HasEnv returns a boolean if a field has been set. func (w *Widget) HasEnv() bool { if w != nil && w.Env != nil { return true } return false } // SetEnv allocates a new w.Env and returns the pointer to it. func (w *Widget) SetEnv(v string) { w.Env = &v } // GetEventSize returns the EventSize field if non-nil, zero value otherwise. func (w *Widget) GetEventSize() string { if w == nil || w.EventSize == nil { return "" } return *w.EventSize } // GetOkEventSize returns a tuple with the EventSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetEventSizeOk() (string, bool) { if w == nil || w.EventSize == nil { return "", false } return *w.EventSize, true } // HasEventSize returns a boolean if a field has been set. func (w *Widget) HasEventSize() bool { if w != nil && w.EventSize != nil { return true } return false } // SetEventSize allocates a new w.EventSize and returns the pointer to it. func (w *Widget) SetEventSize(v string) { w.EventSize = &v } // GetFontSize returns the FontSize field if non-nil, zero value otherwise. func (w *Widget) GetFontSize() string { if w == nil || w.FontSize == nil { return "" } return *w.FontSize } // GetOkFontSize returns a tuple with the FontSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetFontSizeOk() (string, bool) { if w == nil || w.FontSize == nil { return "", false } return *w.FontSize, true } // HasFontSize returns a boolean if a field has been set. func (w *Widget) HasFontSize() bool { if w != nil && w.FontSize != nil { return true } return false } // SetFontSize allocates a new w.FontSize and returns the pointer to it. func (w *Widget) SetFontSize(v string) { w.FontSize = &v } // GetGroup returns the Group field if non-nil, zero value otherwise. func (w *Widget) GetGroup() string { if w == nil || w.Group == nil { return "" } return *w.Group } // GetOkGroup returns a tuple with the Group field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetGroupOk() (string, bool) { if w == nil || w.Group == nil { return "", false } return *w.Group, true } // HasGroup returns a boolean if a field has been set. func (w *Widget) HasGroup() bool { if w != nil && w.Group != nil { return true } return false } // SetGroup allocates a new w.Group and returns the pointer to it. func (w *Widget) SetGroup(v string) { w.Group = &v } // GetGrouping returns the Grouping field if non-nil, zero value otherwise. func (w *Widget) GetGrouping() string { if w == nil || w.Grouping == nil { return "" } return *w.Grouping } // GetOkGrouping returns a tuple with the Grouping field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetGroupingOk() (string, bool) { if w == nil || w.Grouping == nil { return "", false } return *w.Grouping, true } // HasGrouping returns a boolean if a field has been set. func (w *Widget) HasGrouping() bool { if w != nil && w.Grouping != nil { return true } return false } // SetGrouping allocates a new w.Grouping and returns the pointer to it. func (w *Widget) SetGrouping(v string) { w.Grouping = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (w *Widget) GetHeight() int { if w == nil || w.Height == nil { return 0 } return *w.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetHeightOk() (int, bool) { if w == nil || w.Height == nil { return 0, false } return *w.Height, true } // HasHeight returns a boolean if a field has been set. func (w *Widget) HasHeight() bool { if w != nil && w.Height != nil { return true } return false } // SetHeight allocates a new w.Height and returns the pointer to it. func (w *Widget) SetHeight(v int) { w.Height = &v } // GetHideZeroCounts returns the HideZeroCounts field if non-nil, zero value otherwise. func (w *Widget) GetHideZeroCounts() bool { if w == nil || w.HideZeroCounts == nil { return false } return *w.HideZeroCounts } // GetOkHideZeroCounts returns a tuple with the HideZeroCounts field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetHideZeroCountsOk() (bool, bool) { if w == nil || w.HideZeroCounts == nil { return false, false } return *w.HideZeroCounts, true } // HasHideZeroCounts returns a boolean if a field has been set. func (w *Widget) HasHideZeroCounts() bool { if w != nil && w.HideZeroCounts != nil { return true } return false } // SetHideZeroCounts allocates a new w.HideZeroCounts and returns the pointer to it. func (w *Widget) SetHideZeroCounts(v bool) { w.HideZeroCounts = &v } // GetHTML returns the HTML field if non-nil, zero value otherwise. func (w *Widget) GetHTML() string { if w == nil || w.HTML == nil { return "" } return *w.HTML } // GetOkHTML returns a tuple with the HTML field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetHTMLOk() (string, bool) { if w == nil || w.HTML == nil { return "", false } return *w.HTML, true } // HasHTML returns a boolean if a field has been set. func (w *Widget) HasHTML() bool { if w != nil && w.HTML != nil { return true } return false } // SetHTML allocates a new w.HTML and returns the pointer to it. func (w *Widget) SetHTML(v string) { w.HTML = &v } // GetLayoutVersion returns the LayoutVersion field if non-nil, zero value otherwise. func (w *Widget) GetLayoutVersion() string { if w == nil || w.LayoutVersion == nil { return "" } return *w.LayoutVersion } // GetOkLayoutVersion returns a tuple with the LayoutVersion field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetLayoutVersionOk() (string, bool) { if w == nil || w.LayoutVersion == nil { return "", false } return *w.LayoutVersion, true } // HasLayoutVersion returns a boolean if a field has been set. func (w *Widget) HasLayoutVersion() bool { if w != nil && w.LayoutVersion != nil { return true } return false } // SetLayoutVersion allocates a new w.LayoutVersion and returns the pointer to it. func (w *Widget) SetLayoutVersion(v string) { w.LayoutVersion = &v } // GetLegend returns the Legend field if non-nil, zero value otherwise. func (w *Widget) GetLegend() bool { if w == nil || w.Legend == nil { return false } return *w.Legend } // GetOkLegend returns a tuple with the Legend field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetLegendOk() (bool, bool) { if w == nil || w.Legend == nil { return false, false } return *w.Legend, true } // HasLegend returns a boolean if a field has been set. func (w *Widget) HasLegend() bool { if w != nil && w.Legend != nil { return true } return false } // SetLegend allocates a new w.Legend and returns the pointer to it. func (w *Widget) SetLegend(v bool) { w.Legend = &v } // GetLegendSize returns the LegendSize field if non-nil, zero value otherwise. func (w *Widget) GetLegendSize() string { if w == nil || w.LegendSize == nil { return "" } return *w.LegendSize } // GetOkLegendSize returns a tuple with the LegendSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetLegendSizeOk() (string, bool) { if w == nil || w.LegendSize == nil { return "", false } return *w.LegendSize, true } // HasLegendSize returns a boolean if a field has been set. func (w *Widget) HasLegendSize() bool { if w != nil && w.LegendSize != nil { return true } return false } // SetLegendSize allocates a new w.LegendSize and returns the pointer to it. func (w *Widget) SetLegendSize(v string) { w.LegendSize = &v } // GetLogset returns the Logset field if non-nil, zero value otherwise. func (w *Widget) GetLogset() string { if w == nil || w.Logset == nil { return "" } return *w.Logset } // GetOkLogset returns a tuple with the Logset field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetLogsetOk() (string, bool) { if w == nil || w.Logset == nil { return "", false } return *w.Logset, true } // HasLogset returns a boolean if a field has been set. func (w *Widget) HasLogset() bool { if w != nil && w.Logset != nil { return true } return false } // SetLogset allocates a new w.Logset and returns the pointer to it. func (w *Widget) SetLogset(v string) { w.Logset = &v } // GetManageStatusShowTitle returns the ManageStatusShowTitle field if non-nil, zero value otherwise. func (w *Widget) GetManageStatusShowTitle() bool { if w == nil || w.ManageStatusShowTitle == nil { return false } return *w.ManageStatusShowTitle } // GetOkManageStatusShowTitle returns a tuple with the ManageStatusShowTitle field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetManageStatusShowTitleOk() (bool, bool) { if w == nil || w.ManageStatusShowTitle == nil { return false, false } return *w.ManageStatusShowTitle, true } // HasManageStatusShowTitle returns a boolean if a field has been set. func (w *Widget) HasManageStatusShowTitle() bool { if w != nil && w.ManageStatusShowTitle != nil { return true } return false } // SetManageStatusShowTitle allocates a new w.ManageStatusShowTitle and returns the pointer to it. func (w *Widget) SetManageStatusShowTitle(v bool) { w.ManageStatusShowTitle = &v } // GetManageStatusTitleAlign returns the ManageStatusTitleAlign field if non-nil, zero value otherwise. func (w *Widget) GetManageStatusTitleAlign() string { if w == nil || w.ManageStatusTitleAlign == nil { return "" } return *w.ManageStatusTitleAlign } // GetOkManageStatusTitleAlign returns a tuple with the ManageStatusTitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetManageStatusTitleAlignOk() (string, bool) { if w == nil || w.ManageStatusTitleAlign == nil { return "", false } return *w.ManageStatusTitleAlign, true } // HasManageStatusTitleAlign returns a boolean if a field has been set. func (w *Widget) HasManageStatusTitleAlign() bool { if w != nil && w.ManageStatusTitleAlign != nil { return true } return false } // SetManageStatusTitleAlign allocates a new w.ManageStatusTitleAlign and returns the pointer to it. func (w *Widget) SetManageStatusTitleAlign(v string) { w.ManageStatusTitleAlign = &v } // GetManageStatusTitleSize returns the ManageStatusTitleSize field if non-nil, zero value otherwise. func (w *Widget) GetManageStatusTitleSize() string { if w == nil || w.ManageStatusTitleSize == nil { return "" } return *w.ManageStatusTitleSize } // GetOkManageStatusTitleSize returns a tuple with the ManageStatusTitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetManageStatusTitleSizeOk() (string, bool) { if w == nil || w.ManageStatusTitleSize == nil { return "", false } return *w.ManageStatusTitleSize, true } // HasManageStatusTitleSize returns a boolean if a field has been set. func (w *Widget) HasManageStatusTitleSize() bool { if w != nil && w.ManageStatusTitleSize != nil { return true } return false } // SetManageStatusTitleSize allocates a new w.ManageStatusTitleSize and returns the pointer to it. func (w *Widget) SetManageStatusTitleSize(v string) { w.ManageStatusTitleSize = &v } // GetManageStatusTitleText returns the ManageStatusTitleText field if non-nil, zero value otherwise. func (w *Widget) GetManageStatusTitleText() string { if w == nil || w.ManageStatusTitleText == nil { return "" } return *w.ManageStatusTitleText } // GetOkManageStatusTitleText returns a tuple with the ManageStatusTitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetManageStatusTitleTextOk() (string, bool) { if w == nil || w.ManageStatusTitleText == nil { return "", false } return *w.ManageStatusTitleText, true } // HasManageStatusTitleText returns a boolean if a field has been set. func (w *Widget) HasManageStatusTitleText() bool { if w != nil && w.ManageStatusTitleText != nil { return true } return false } // SetManageStatusTitleText allocates a new w.ManageStatusTitleText and returns the pointer to it. func (w *Widget) SetManageStatusTitleText(v string) { w.ManageStatusTitleText = &v } // GetMargin returns the Margin field if non-nil, zero value otherwise. func (w *Widget) GetMargin() string { if w == nil || w.Margin == nil { return "" } return *w.Margin } // GetOkMargin returns a tuple with the Margin field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetMarginOk() (string, bool) { if w == nil || w.Margin == nil { return "", false } return *w.Margin, true } // HasMargin returns a boolean if a field has been set. func (w *Widget) HasMargin() bool { if w != nil && w.Margin != nil { return true } return false } // SetMargin allocates a new w.Margin and returns the pointer to it. func (w *Widget) SetMargin(v string) { w.Margin = &v } // GetMonitor returns the Monitor field if non-nil, zero value otherwise. func (w *Widget) GetMonitor() ScreenboardMonitor { if w == nil || w.Monitor == nil { return ScreenboardMonitor{} } return *w.Monitor } // GetOkMonitor returns a tuple with the Monitor field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetMonitorOk() (ScreenboardMonitor, bool) { if w == nil || w.Monitor == nil { return ScreenboardMonitor{}, false } return *w.Monitor, true } // HasMonitor returns a boolean if a field has been set. func (w *Widget) HasMonitor() bool { if w != nil && w.Monitor != nil { return true } return false } // SetMonitor allocates a new w.Monitor and returns the pointer to it. func (w *Widget) SetMonitor(v ScreenboardMonitor) { w.Monitor = &v } // GetMustShowBreakdown returns the MustShowBreakdown field if non-nil, zero value otherwise. func (w *Widget) GetMustShowBreakdown() bool { if w == nil || w.MustShowBreakdown == nil { return false } return *w.MustShowBreakdown } // GetOkMustShowBreakdown returns a tuple with the MustShowBreakdown field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetMustShowBreakdownOk() (bool, bool) { if w == nil || w.MustShowBreakdown == nil { return false, false } return *w.MustShowBreakdown, true } // HasMustShowBreakdown returns a boolean if a field has been set. func (w *Widget) HasMustShowBreakdown() bool { if w != nil && w.MustShowBreakdown != nil { return true } return false } // SetMustShowBreakdown allocates a new w.MustShowBreakdown and returns the pointer to it. func (w *Widget) SetMustShowBreakdown(v bool) { w.MustShowBreakdown = &v } // GetMustShowDistribution returns the MustShowDistribution field if non-nil, zero value otherwise. func (w *Widget) GetMustShowDistribution() bool { if w == nil || w.MustShowDistribution == nil { return false } return *w.MustShowDistribution } // GetOkMustShowDistribution returns a tuple with the MustShowDistribution field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetMustShowDistributionOk() (bool, bool) { if w == nil || w.MustShowDistribution == nil { return false, false } return *w.MustShowDistribution, true } // HasMustShowDistribution returns a boolean if a field has been set. func (w *Widget) HasMustShowDistribution() bool { if w != nil && w.MustShowDistribution != nil { return true } return false } // SetMustShowDistribution allocates a new w.MustShowDistribution and returns the pointer to it. func (w *Widget) SetMustShowDistribution(v bool) { w.MustShowDistribution = &v } // GetMustShowErrors returns the MustShowErrors field if non-nil, zero value otherwise. func (w *Widget) GetMustShowErrors() bool { if w == nil || w.MustShowErrors == nil { return false } return *w.MustShowErrors } // GetOkMustShowErrors returns a tuple with the MustShowErrors field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetMustShowErrorsOk() (bool, bool) { if w == nil || w.MustShowErrors == nil { return false, false } return *w.MustShowErrors, true } // HasMustShowErrors returns a boolean if a field has been set. func (w *Widget) HasMustShowErrors() bool { if w != nil && w.MustShowErrors != nil { return true } return false } // SetMustShowErrors allocates a new w.MustShowErrors and returns the pointer to it. func (w *Widget) SetMustShowErrors(v bool) { w.MustShowErrors = &v } // GetMustShowHits returns the MustShowHits field if non-nil, zero value otherwise. func (w *Widget) GetMustShowHits() bool { if w == nil || w.MustShowHits == nil { return false } return *w.MustShowHits } // GetOkMustShowHits returns a tuple with the MustShowHits field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetMustShowHitsOk() (bool, bool) { if w == nil || w.MustShowHits == nil { return false, false } return *w.MustShowHits, true } // HasMustShowHits returns a boolean if a field has been set. func (w *Widget) HasMustShowHits() bool { if w != nil && w.MustShowHits != nil { return true } return false } // SetMustShowHits allocates a new w.MustShowHits and returns the pointer to it. func (w *Widget) SetMustShowHits(v bool) { w.MustShowHits = &v } // GetMustShowLatency returns the MustShowLatency field if non-nil, zero value otherwise. func (w *Widget) GetMustShowLatency() bool { if w == nil || w.MustShowLatency == nil { return false } return *w.MustShowLatency } // GetOkMustShowLatency returns a tuple with the MustShowLatency field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetMustShowLatencyOk() (bool, bool) { if w == nil || w.MustShowLatency == nil { return false, false } return *w.MustShowLatency, true } // HasMustShowLatency returns a boolean if a field has been set. func (w *Widget) HasMustShowLatency() bool { if w != nil && w.MustShowLatency != nil { return true } return false } // SetMustShowLatency allocates a new w.MustShowLatency and returns the pointer to it. func (w *Widget) SetMustShowLatency(v bool) { w.MustShowLatency = &v } // GetMustShowResourceList returns the MustShowResourceList field if non-nil, zero value otherwise. func (w *Widget) GetMustShowResourceList() bool { if w == nil || w.MustShowResourceList == nil { return false } return *w.MustShowResourceList } // GetOkMustShowResourceList returns a tuple with the MustShowResourceList field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetMustShowResourceListOk() (bool, bool) { if w == nil || w.MustShowResourceList == nil { return false, false } return *w.MustShowResourceList, true } // HasMustShowResourceList returns a boolean if a field has been set. func (w *Widget) HasMustShowResourceList() bool { if w != nil && w.MustShowResourceList != nil { return true } return false } // SetMustShowResourceList allocates a new w.MustShowResourceList and returns the pointer to it. func (w *Widget) SetMustShowResourceList(v bool) { w.MustShowResourceList = &v } // GetParams returns the Params field if non-nil, zero value otherwise. func (w *Widget) GetParams() Params { if w == nil || w.Params == nil { return Params{} } return *w.Params } // GetOkParams returns a tuple with the Params field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetParamsOk() (Params, bool) { if w == nil || w.Params == nil { return Params{}, false } return *w.Params, true } // HasParams returns a boolean if a field has been set. func (w *Widget) HasParams() bool { if w != nil && w.Params != nil { return true } return false } // SetParams allocates a new w.Params and returns the pointer to it. func (w *Widget) SetParams(v Params) { w.Params = &v } // GetPrecision returns the Precision field if non-nil, zero value otherwise. func (w *Widget) GetPrecision() string { if w == nil || w.Precision == nil { return "" } return *w.Precision } // GetOkPrecision returns a tuple with the Precision field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetPrecisionOk() (string, bool) { if w == nil || w.Precision == nil { return "", false } return *w.Precision, true } // HasPrecision returns a boolean if a field has been set. func (w *Widget) HasPrecision() bool { if w != nil && w.Precision != nil { return true } return false } // SetPrecision allocates a new w.Precision and returns the pointer to it. func (w *Widget) SetPrecision(v string) { w.Precision = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (w *Widget) GetQuery() string { if w == nil || w.Query == nil { return "" } return *w.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetQueryOk() (string, bool) { if w == nil || w.Query == nil { return "", false } return *w.Query, true } // HasQuery returns a boolean if a field has been set. func (w *Widget) HasQuery() bool { if w != nil && w.Query != nil { return true } return false } // SetQuery allocates a new w.Query and returns the pointer to it. func (w *Widget) SetQuery(v string) { w.Query = &v } // GetServiceName returns the ServiceName field if non-nil, zero value otherwise. func (w *Widget) GetServiceName() string { if w == nil || w.ServiceName == nil { return "" } return *w.ServiceName } // GetOkServiceName returns a tuple with the ServiceName field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetServiceNameOk() (string, bool) { if w == nil || w.ServiceName == nil { return "", false } return *w.ServiceName, true } // HasServiceName returns a boolean if a field has been set. func (w *Widget) HasServiceName() bool { if w != nil && w.ServiceName != nil { return true } return false } // SetServiceName allocates a new w.ServiceName and returns the pointer to it. func (w *Widget) SetServiceName(v string) { w.ServiceName = &v } // GetServiceService returns the ServiceService field if non-nil, zero value otherwise. func (w *Widget) GetServiceService() string { if w == nil || w.ServiceService == nil { return "" } return *w.ServiceService } // GetOkServiceService returns a tuple with the ServiceService field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetServiceServiceOk() (string, bool) { if w == nil || w.ServiceService == nil { return "", false } return *w.ServiceService, true } // HasServiceService returns a boolean if a field has been set. func (w *Widget) HasServiceService() bool { if w != nil && w.ServiceService != nil { return true } return false } // SetServiceService allocates a new w.ServiceService and returns the pointer to it. func (w *Widget) SetServiceService(v string) { w.ServiceService = &v } // GetSizeVersion returns the SizeVersion field if non-nil, zero value otherwise. func (w *Widget) GetSizeVersion() string { if w == nil || w.SizeVersion == nil { return "" } return *w.SizeVersion } // GetOkSizeVersion returns a tuple with the SizeVersion field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetSizeVersionOk() (string, bool) { if w == nil || w.SizeVersion == nil { return "", false } return *w.SizeVersion, true } // HasSizeVersion returns a boolean if a field has been set. func (w *Widget) HasSizeVersion() bool { if w != nil && w.SizeVersion != nil { return true } return false } // SetSizeVersion allocates a new w.SizeVersion and returns the pointer to it. func (w *Widget) SetSizeVersion(v string) { w.SizeVersion = &v } // GetSizing returns the Sizing field if non-nil, zero value otherwise. func (w *Widget) GetSizing() string { if w == nil || w.Sizing == nil { return "" } return *w.Sizing } // GetOkSizing returns a tuple with the Sizing field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetSizingOk() (string, bool) { if w == nil || w.Sizing == nil { return "", false } return *w.Sizing, true } // HasSizing returns a boolean if a field has been set. func (w *Widget) HasSizing() bool { if w != nil && w.Sizing != nil { return true } return false } // SetSizing allocates a new w.Sizing and returns the pointer to it. func (w *Widget) SetSizing(v string) { w.Sizing = &v } // GetText returns the Text field if non-nil, zero value otherwise. func (w *Widget) GetText() string { if w == nil || w.Text == nil { return "" } return *w.Text } // GetOkText returns a tuple with the Text field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTextOk() (string, bool) { if w == nil || w.Text == nil { return "", false } return *w.Text, true } // HasText returns a boolean if a field has been set. func (w *Widget) HasText() bool { if w != nil && w.Text != nil { return true } return false } // SetText allocates a new w.Text and returns the pointer to it. func (w *Widget) SetText(v string) { w.Text = &v } // GetTextAlign returns the TextAlign field if non-nil, zero value otherwise. func (w *Widget) GetTextAlign() string { if w == nil || w.TextAlign == nil { return "" } return *w.TextAlign } // GetOkTextAlign returns a tuple with the TextAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTextAlignOk() (string, bool) { if w == nil || w.TextAlign == nil { return "", false } return *w.TextAlign, true } // HasTextAlign returns a boolean if a field has been set. func (w *Widget) HasTextAlign() bool { if w != nil && w.TextAlign != nil { return true } return false } // SetTextAlign allocates a new w.TextAlign and returns the pointer to it. func (w *Widget) SetTextAlign(v string) { w.TextAlign = &v } // GetTextSize returns the TextSize field if non-nil, zero value otherwise. func (w *Widget) GetTextSize() string { if w == nil || w.TextSize == nil { return "" } return *w.TextSize } // GetOkTextSize returns a tuple with the TextSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTextSizeOk() (string, bool) { if w == nil || w.TextSize == nil { return "", false } return *w.TextSize, true } // HasTextSize returns a boolean if a field has been set. func (w *Widget) HasTextSize() bool { if w != nil && w.TextSize != nil { return true } return false } // SetTextSize allocates a new w.TextSize and returns the pointer to it. func (w *Widget) SetTextSize(v string) { w.TextSize = &v } // GetTick returns the Tick field if non-nil, zero value otherwise. func (w *Widget) GetTick() bool { if w == nil || w.Tick == nil { return false } return *w.Tick } // GetOkTick returns a tuple with the Tick field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTickOk() (bool, bool) { if w == nil || w.Tick == nil { return false, false } return *w.Tick, true } // HasTick returns a boolean if a field has been set. func (w *Widget) HasTick() bool { if w != nil && w.Tick != nil { return true } return false } // SetTick allocates a new w.Tick and returns the pointer to it. func (w *Widget) SetTick(v bool) { w.Tick = &v } // GetTickEdge returns the TickEdge field if non-nil, zero value otherwise. func (w *Widget) GetTickEdge() string { if w == nil || w.TickEdge == nil { return "" } return *w.TickEdge } // GetOkTickEdge returns a tuple with the TickEdge field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTickEdgeOk() (string, bool) { if w == nil || w.TickEdge == nil { return "", false } return *w.TickEdge, true } // HasTickEdge returns a boolean if a field has been set. func (w *Widget) HasTickEdge() bool { if w != nil && w.TickEdge != nil { return true } return false } // SetTickEdge allocates a new w.TickEdge and returns the pointer to it. func (w *Widget) SetTickEdge(v string) { w.TickEdge = &v } // GetTickPos returns the TickPos field if non-nil, zero value otherwise. func (w *Widget) GetTickPos() string { if w == nil || w.TickPos == nil { return "" } return *w.TickPos } // GetOkTickPos returns a tuple with the TickPos field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTickPosOk() (string, bool) { if w == nil || w.TickPos == nil { return "", false } return *w.TickPos, true } // HasTickPos returns a boolean if a field has been set. func (w *Widget) HasTickPos() bool { if w != nil && w.TickPos != nil { return true } return false } // SetTickPos allocates a new w.TickPos and returns the pointer to it. func (w *Widget) SetTickPos(v string) { w.TickPos = &v } // GetTileDef returns the TileDef field if non-nil, zero value otherwise. func (w *Widget) GetTileDef() TileDef { if w == nil || w.TileDef == nil { return TileDef{} } return *w.TileDef } // GetOkTileDef returns a tuple with the TileDef field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTileDefOk() (TileDef, bool) { if w == nil || w.TileDef == nil { return TileDef{}, false } return *w.TileDef, true } // HasTileDef returns a boolean if a field has been set. func (w *Widget) HasTileDef() bool { if w != nil && w.TileDef != nil { return true } return false } // SetTileDef allocates a new w.TileDef and returns the pointer to it. func (w *Widget) SetTileDef(v TileDef) { w.TileDef = &v } // GetTime returns the Time field if non-nil, zero value otherwise. func (w *Widget) GetTime() Time { if w == nil || w.Time == nil { return Time{} } return *w.Time } // GetOkTime returns a tuple with the Time field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTimeOk() (Time, bool) { if w == nil || w.Time == nil { return Time{}, false } return *w.Time, true } // HasTime returns a boolean if a field has been set. func (w *Widget) HasTime() bool { if w != nil && w.Time != nil { return true } return false } // SetTime allocates a new w.Time and returns the pointer to it. func (w *Widget) SetTime(v Time) { w.Time = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (w *Widget) GetTitle() bool { if w == nil || w.Title == nil { return false } return *w.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTitleOk() (bool, bool) { if w == nil || w.Title == nil { return false, false } return *w.Title, true } // HasTitle returns a boolean if a field has been set. func (w *Widget) HasTitle() bool { if w != nil && w.Title != nil { return true } return false } // SetTitle allocates a new w.Title and returns the pointer to it. func (w *Widget) SetTitle(v bool) { w.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (w *Widget) GetTitleAlign() string { if w == nil || w.TitleAlign == nil { return "" } return *w.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTitleAlignOk() (string, bool) { if w == nil || w.TitleAlign == nil { return "", false } return *w.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (w *Widget) HasTitleAlign() bool { if w != nil && w.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new w.TitleAlign and returns the pointer to it. func (w *Widget) SetTitleAlign(v string) { w.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (w *Widget) GetTitleSize() int { if w == nil || w.TitleSize == nil { return 0 } return *w.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTitleSizeOk() (int, bool) { if w == nil || w.TitleSize == nil { return 0, false } return *w.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (w *Widget) HasTitleSize() bool { if w != nil && w.TitleSize != nil { return true } return false } // SetTitleSize allocates a new w.TitleSize and returns the pointer to it. func (w *Widget) SetTitleSize(v int) { w.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (w *Widget) GetTitleText() string { if w == nil || w.TitleText == nil { return "" } return *w.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTitleTextOk() (string, bool) { if w == nil || w.TitleText == nil { return "", false } return *w.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (w *Widget) HasTitleText() bool { if w != nil && w.TitleText != nil { return true } return false } // SetTitleText allocates a new w.TitleText and returns the pointer to it. func (w *Widget) SetTitleText(v string) { w.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (w *Widget) GetType() string { if w == nil || w.Type == nil { return "" } return *w.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTypeOk() (string, bool) { if w == nil || w.Type == nil { return "", false } return *w.Type, true } // HasType returns a boolean if a field has been set. func (w *Widget) HasType() bool { if w != nil && w.Type != nil { return true } return false } // SetType allocates a new w.Type and returns the pointer to it. func (w *Widget) SetType(v string) { w.Type = &v } // GetUnit returns the Unit field if non-nil, zero value otherwise. func (w *Widget) GetUnit() string { if w == nil || w.Unit == nil { return "" } return *w.Unit } // GetOkUnit returns a tuple with the Unit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetUnitOk() (string, bool) { if w == nil || w.Unit == nil { return "", false } return *w.Unit, true } // HasUnit returns a boolean if a field has been set. func (w *Widget) HasUnit() bool { if w != nil && w.Unit != nil { return true } return false } // SetUnit allocates a new w.Unit and returns the pointer to it. func (w *Widget) SetUnit(v string) { w.Unit = &v } // GetURL returns the URL field if non-nil, zero value otherwise. func (w *Widget) GetURL() string { if w == nil || w.URL == nil { return "" } return *w.URL } // GetOkURL returns a tuple with the URL field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetURLOk() (string, bool) { if w == nil || w.URL == nil { return "", false } return *w.URL, true } // HasURL returns a boolean if a field has been set. func (w *Widget) HasURL() bool { if w != nil && w.URL != nil { return true } return false } // SetURL allocates a new w.URL and returns the pointer to it. func (w *Widget) SetURL(v string) { w.URL = &v } // GetVizType returns the VizType field if non-nil, zero value otherwise. func (w *Widget) GetVizType() string { if w == nil || w.VizType == nil { return "" } return *w.VizType } // GetOkVizType returns a tuple with the VizType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetVizTypeOk() (string, bool) { if w == nil || w.VizType == nil { return "", false } return *w.VizType, true } // HasVizType returns a boolean if a field has been set. func (w *Widget) HasVizType() bool { if w != nil && w.VizType != nil { return true } return false } // SetVizType allocates a new w.VizType and returns the pointer to it. func (w *Widget) SetVizType(v string) { w.VizType = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (w *Widget) GetWidth() int { if w == nil || w.Width == nil { return 0 } return *w.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetWidthOk() (int, bool) { if w == nil || w.Width == nil { return 0, false } return *w.Width, true } // HasWidth returns a boolean if a field has been set. func (w *Widget) HasWidth() bool { if w != nil && w.Width != nil { return true } return false } // SetWidth allocates a new w.Width and returns the pointer to it. func (w *Widget) SetWidth(v int) { w.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (w *Widget) GetX() int { if w == nil || w.X == nil { return 0 } return *w.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetXOk() (int, bool) { if w == nil || w.X == nil { return 0, false } return *w.X, true } // HasX returns a boolean if a field has been set. func (w *Widget) HasX() bool { if w != nil && w.X != nil { return true } return false } // SetX allocates a new w.X and returns the pointer to it. func (w *Widget) SetX(v int) { w.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (w *Widget) GetY() int { if w == nil || w.Y == nil { return 0 } return *w.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetYOk() (int, bool) { if w == nil || w.Y == nil { return 0, false } return *w.Y, true } // HasY returns a boolean if a field has been set. func (w *Widget) HasY() bool { if w != nil && w.Y != nil { return true } return false } // SetY allocates a new w.Y and returns the pointer to it. func (w *Widget) SetY(v int) { w.Y = &v } // GetMax returns the Max field if non-nil, zero value otherwise. func (y *Yaxis) GetMax() float64 { if y == nil || y.Max == nil { return 0 } return *y.Max } // GetOkMax returns a tuple with the Max field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (y *Yaxis) GetMaxOk() (float64, bool) { if y == nil || y.Max == nil { return 0, false } return *y.Max, true } // HasMax returns a boolean if a field has been set. func (y *Yaxis) HasMax() bool { if y != nil && y.Max != nil { return true } return false } // SetMax allocates a new y.Max and returns the pointer to it. func (y *Yaxis) SetMax(v float64) { y.Max = &v } // GetMin returns the Min field if non-nil, zero value otherwise. func (y *Yaxis) GetMin() float64 { if y == nil || y.Min == nil { return 0 } return *y.Min } // GetOkMin returns a tuple with the Min field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (y *Yaxis) GetMinOk() (float64, bool) { if y == nil || y.Min == nil { return 0, false } return *y.Min, true } // HasMin returns a boolean if a field has been set. func (y *Yaxis) HasMin() bool { if y != nil && y.Min != nil { return true } return false } // SetMin allocates a new y.Min and returns the pointer to it. func (y *Yaxis) SetMin(v float64) { y.Min = &v } // GetScale returns the Scale field if non-nil, zero value otherwise. func (y *Yaxis) GetScale() string { if y == nil || y.Scale == nil { return "" } return *y.Scale } // GetOkScale returns a tuple with the Scale field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (y *Yaxis) GetScaleOk() (string, bool) { if y == nil || y.Scale == nil { return "", false } return *y.Scale, true } // HasScale returns a boolean if a field has been set. func (y *Yaxis) HasScale() bool { if y != nil && y.Scale != nil { return true } return false } // SetScale allocates a new y.Scale and returns the pointer to it. func (y *Yaxis) SetScale(v string) { y.Scale = &v }
vendor/github.com/zorkian/go-datadog-api/datadog-accessors.go
0.789031
0.434761
datadog-accessors.go
starcoder
package converter import ( "context" "go.opentelemetry.io/collector/consumer" "go.opentelemetry.io/collector/consumer/consumerdata" "go.opentelemetry.io/collector/consumer/pdata" "go.opentelemetry.io/collector/consumer/pdatautil" "go.opentelemetry.io/collector/translator/internaldata" ) // NewInternalToOCTraceConverter creates new internalToOCTraceConverter that takes TraceConsumer and // implements ConsumeTraces interface. func NewInternalToOCTraceConverter(tc consumer.TraceConsumerOld) consumer.TraceConsumer { return &internalToOCTraceConverter{tc} } // internalToOCTraceConverter is a internal to oc translation shim that takes TraceConsumer and // implements ConsumeTraces interface. type internalToOCTraceConverter struct { traceConsumer consumer.TraceConsumerOld } // ConsumeTraces takes new-style data.Traces method, converts it to OC and uses old-style ConsumeTraceData method // to process the trace data. func (tc *internalToOCTraceConverter) ConsumeTraces(ctx context.Context, td pdata.Traces) error { ocTraces := internaldata.TraceDataToOC(td) for i := range ocTraces { err := tc.traceConsumer.ConsumeTraceData(ctx, ocTraces[i]) if err != nil { return err } } return nil } var _ consumer.TraceConsumer = (*internalToOCTraceConverter)(nil) // NewInternalToOCMetricsConverter creates new internalToOCMetricsConverter that takes MetricsConsumer and // implements ConsumeTraces interface. func NewInternalToOCMetricsConverter(mc consumer.MetricsConsumerOld) consumer.MetricsConsumer { return &internalToOCMetricsConverter{mc} } // internalToOCMetricsConverter is a internal to oc translation shim that takes MetricsConsumer and // implements ConsumeMetrics interface. type internalToOCMetricsConverter struct { metricsConsumer consumer.MetricsConsumerOld } // ConsumeMetrics takes new-style data.MetricData method, converts it to OC and uses old-style ConsumeMetricsData method // to process the metrics data. func (tc *internalToOCMetricsConverter) ConsumeMetrics(ctx context.Context, md pdata.Metrics) error { ocMetrics := pdatautil.MetricsToMetricsData(md) for i := range ocMetrics { err := tc.metricsConsumer.ConsumeMetricsData(ctx, ocMetrics[i]) if err != nil { return err } } return nil } var _ consumer.MetricsConsumer = (*internalToOCMetricsConverter)(nil) // NewOCToInternalTraceConverter creates new ocToInternalTraceConverter that takes TraceConsumer and // implements ConsumeTraces interface. func NewOCToInternalTraceConverter(tc consumer.TraceConsumer) consumer.TraceConsumerOld { return &ocToInternalTraceConverter{tc} } // ocToInternalTraceConverter is a internal to oc translation shim that takes TraceConsumer and // implements ConsumeTraces interface. type ocToInternalTraceConverter struct { traceConsumer consumer.TraceConsumer } // ConsumeTraces takes new-style data.Traces method, converts it to OC and uses old-style ConsumeTraceData method // to process the trace data. func (tc *ocToInternalTraceConverter) ConsumeTraceData(ctx context.Context, td consumerdata.TraceData) error { traceData := internaldata.OCToTraceData(td) err := tc.traceConsumer.ConsumeTraces(ctx, traceData) if err != nil { return err } return nil } var _ consumer.TraceConsumerOld = (*ocToInternalTraceConverter)(nil) // NewOCToInternalMetricsConverter creates new ocToInternalMetricsConverter that takes MetricsConsumer and // implements ConsumeTraces interface. func NewOCToInternalMetricsConverter(tc consumer.MetricsConsumer) consumer.MetricsConsumerOld { return &ocToInternalMetricsConverter{tc} } // ocToInternalMetricsConverter is a internal to oc translation shim that takes MetricsConsumer and // implements ConsumeMetrics interface. type ocToInternalMetricsConverter struct { metricsConsumer consumer.MetricsConsumer } // ConsumeMetrics takes new-style data.MetricData method, converts it to OC and uses old-style ConsumeMetricsData method // to process the metrics data. func (tc *ocToInternalMetricsConverter) ConsumeMetricsData(ctx context.Context, md consumerdata.MetricsData) error { metricsData := pdatautil.MetricsFromMetricsData([]consumerdata.MetricsData{md}) err := tc.metricsConsumer.ConsumeMetrics(ctx, metricsData) if err != nil { return err } return nil } var _ consumer.MetricsConsumerOld = (*ocToInternalMetricsConverter)(nil)
consumer/converter/converter.go
0.607663
0.438966
converter.go
starcoder
package licensediff import ( "github.com/swinslow/spdx-go/v0/spdx" ) // LicensePair is a result set where we are talking about two license strings, // potentially differing, for a single filename between two SPDX Packages. type LicensePair struct { First string Second string } // MakePairs essentially just consolidates all files and LicenseConcluded // strings into a single data structure. func MakePairs(p1 *spdx.Package2_1, p2 *spdx.Package2_1) (map[string]LicensePair, error) { pairs := map[string]LicensePair{} // first, go through and add all files/licenses from p1 for _, f := range p1.Files { pair := LicensePair{First: f.LicenseConcluded, Second: ""} pairs[f.FileName] = pair } // now, go through all files/licenses from p2. If already // present, add as .second; if not, create new pair for _, f := range p2.Files { firstLic := "" existingPair, ok := pairs[f.FileName] if ok { // already present; update it firstLic = existingPair.First } // now, update what's there, either way pair := LicensePair{First: firstLic, Second: f.LicenseConcluded} pairs[f.FileName] = pair } return pairs, nil } // LicenseDiff is a structured version of the output of MakePairs. It is // meant to make it easier to find and report on, e.g., just the files that // have different licenses, or those that are in just one scan. type LicenseDiff struct { InBothChanged map[string]LicensePair InBothSame map[string]string InFirstOnly map[string]string InSecondOnly map[string]string } // MakeResults creates a more structured set of results from the output // of MakePairs. func MakeResults(pairs map[string]LicensePair) (*LicenseDiff, error) { diff := &LicenseDiff{ InBothChanged: map[string]LicensePair{}, InBothSame: map[string]string{}, InFirstOnly: map[string]string{}, InSecondOnly: map[string]string{}, } // walk through pairs and allocate them where they belong for filename, pair := range pairs { if pair.First == pair.Second { diff.InBothSame[filename] = pair.First } else { if pair.First == "" { diff.InSecondOnly[filename] = pair.Second } else if pair.Second == "" { diff.InFirstOnly[filename] = pair.First } else { diff.InBothChanged[filename] = pair } } } return diff, nil }
v0/licensediff/licensediff.go
0.668664
0.400867
licensediff.go
starcoder
package gologic import "container/list" type color int const ( red color = iota black ) type Element interface { Key() int Merge(Element) Element } type Rbnode struct { color color element Element left *Rbnode right *Rbnode } func Node(e Element) *Rbnode { return &Rbnode{red,e,nil,nil} } func case1 (color color, a *Rbnode, y Element, b *Rbnode) bool { if color == black && a != nil && a.color == red { a_ := a.left return a_.color == red } else { return false } } func case2 (color color, a *Rbnode, y Element, b *Rbnode) bool { if color == black && a != nil && red == a.color { a_ := a.right return red == a_.color } else { return false } } func case3 (color color, a *Rbnode, y Element, b *Rbnode) bool { if color == black && b != nil && red == b.color { b_ := b.left return red == b_.color } else { return false } } func case4 (color color, a *Rbnode, y Element, b *Rbnode) bool { if color == black && b != nil && red == b.color { b_ := b.right return red == b_.color } else { return false } } func make_black (s *Rbnode) *Rbnode { if s.color == red { return s } else { return &Rbnode{black, s.element, s.left, s.right} } } func tree(a *Rbnode,x Element,b *Rbnode,y Element,c *Rbnode, z Element,d *Rbnode) *Rbnode { return &Rbnode{red,y,&Rbnode{black,x,a,b},&Rbnode{black,z,c,d}} } func balance (x Element, color color, a *Rbnode, y Element, b *Rbnode) *Rbnode { if case1(color, a, y, b) { z := y d := b y := a.element a_left := a.left c := a.right x := a_left.element a := a_left.left b := a_left.right return tree(a,x,b,y,c,z,d) } else if case2(color,a,y,b) { z := y d := b x := a.element a := a.left a_right := a.right y := a_right.element b := a_right.left c := a_right.right return tree(a,x,b,y,c,z,d) } else if case3(color,a,y,b) { z := b.element b_left := b.left d := b.right y := b_left.element b := b_left.left c := b_left.right return tree(a,x,b,y,c,z,d) } else if case4(color,a,y,b) { y := b.element b := b.left b_right := b.right z := b_right.element c := b_right.left d := b_right.right return tree(a,x,b,y,c,z,d) } else { return &Rbnode{color,y,a,b} } } func ins (tree *Rbnode, x Element) *Rbnode { if tree == nil { return Node(x); } else { color := tree.color y := tree.element a := tree.left b := tree.right y_key := y.Key() x_key := x.Key() if y_key > x_key { return balance(x, color, ins(a,x), y, b) } else if x_key == y_key { return &Rbnode{color,y.Merge(x),a,b} } else { return balance(x,color,a,y,ins(b,x)) } } } func Insert (t *Rbnode, e Element) *Rbnode { return make_black(ins(t,e)) } func Locate (tree *Rbnode, n int) (Element, bool) { for { if tree == nil { return nil, false } else { x := tree.element l := tree.left r := tree.right if x.Key() == n { return tree.element, true } else if x.Key() > n { tree = l } else { tree = r } } } } type ducer func (interface{}, Element) (interface{}, bool) func Fold (init interface{}, f ducer, tree *Rbnode) (interface{}, bool) { c := make(chan Element) go func () { stack := list.New() stack.PushFront(tree) for { if stack.Len() > 0 { a := stack.Front().Value x, ok := a.(Rbnode) if !ok {panic("oh no")} c <- x.element if x.left != nil { stack.PushFront(x.left) } if x.right != nil { stack.PushFront(x.right) } } else { break } } }() r := init for item := <- c; item != nil; item = <- c { a,cont := f(r,item) if !cont { close(c) return a,cont } r = a } return r,true }
redblack.go
0.68616
0.4184
redblack.go
starcoder
package engine import ( "github.com/MathieuMoalic/mms/cuda" "github.com/MathieuMoalic/mms/data" ) var ( TotalShift, TotalYShift float64 // accumulated window shift (X and Y) in meter ShiftMagL, ShiftMagR, ShiftMagU, ShiftMagD data.Vector // when shifting m, put these value at the left/right edge. ShiftM, ShiftGeom, ShiftRegions bool = true, true, true // should shift act on magnetization, geometry, regions? ) func init() { DeclFunc("Shift", Shift, "Shifts the simulation by +1/-1 cells along X") DeclVar("ShiftMagL", &ShiftMagL, "Upon shift, insert this magnetization from the left") DeclVar("ShiftMagR", &ShiftMagR, "Upon shift, insert this magnetization from the right") DeclVar("ShiftMagU", &ShiftMagU, "Upon shift, insert this magnetization from the top") DeclVar("ShiftMagD", &ShiftMagD, "Upon shift, insert this magnetization from the bottom") DeclVar("ShiftM", &ShiftM, "Whether Shift() acts on magnetization") DeclVar("ShiftGeom", &ShiftGeom, "Whether Shift() acts on geometry") DeclVar("ShiftRegions", &ShiftRegions, "Whether Shift() acts on regions") DeclVar("TotalShift", &TotalShift, "Amount by which the simulation has been shifted (m).") } // position of the window lab frame func GetShiftPos() float64 { return -TotalShift } func GetShiftYPos() float64 { return -TotalYShift } // shift the simulation window over dx cells in X direction func Shift(dx int) { TotalShift += float64(dx) * Mesh().CellSize()[X] // needed to re-init geom, regions if ShiftM { shiftMag(M.Buffer(), dx) // TODO: M.shift? } if ShiftRegions { regions.shift(dx) } if ShiftGeom { geometry.shift(dx) } M.normalize() } func shiftMag(m *data.Slice, dx int) { m2 := cuda.Buffer(1, m.Size()) defer cuda.Recycle(m2) for c := 0; c < m.NComp(); c++ { comp := m.Comp(c) cuda.ShiftX(m2, comp, dx, float32(ShiftMagL[c]), float32(ShiftMagR[c])) data.Copy(comp, m2) // str0 ? } } // shift the simulation window over dy cells in Y direction func YShift(dy int) { TotalYShift += float64(dy) * Mesh().CellSize()[Y] // needed to re-init geom, regions if ShiftM { shiftMagY(M.Buffer(), dy) } if ShiftRegions { regions.shiftY(dy) } if ShiftGeom { geometry.shiftY(dy) } M.normalize() } func shiftMagY(m *data.Slice, dy int) { m2 := cuda.Buffer(1, m.Size()) defer cuda.Recycle(m2) for c := 0; c < m.NComp(); c++ { comp := m.Comp(c) cuda.ShiftY(m2, comp, dy, float32(ShiftMagU[c]), float32(ShiftMagD[c])) data.Copy(comp, m2) // str0 ? } }
engine/shift.go
0.552298
0.434221
shift.go
starcoder
package graphutil import ( "container/heap" "fmt" ) // Edge represents a line from one node to another type Edge struct { Cost int Node Node } // Node is a structure to hold graphs type Node struct { Value int Children []Edge marked bool } // CostType is a structure to hold shortest distance from a node and the previous vertex type CostType struct { minCost int previousVertex int } // MinCostMap is a hashmap of keys that stores the lowest cost from a source node type MinCostMap map[int]CostType func (minCostMap MinCostMap) initKey(key int, source bool) { _, ok := minCostMap[key] if !ok { if source { minCostMap[key] = CostType{minCost: 0, previousVertex: -1} } else { minCostMap[key] = CostType{minCost: -1, previousVertex: -1} } } } // Visit prints the current node's value func (n Node) Visit() { fmt.Println(n.Value, "-") } func searchGraphDfs(graph Node, src int, dest int, maxStops int, stops int, currCost int) (minCost int) { minCost = 99999 for _, edge := range graph.Children { var cost int if edge.Node.Value == dest && stops <= maxStops { cost = currCost + edge.Cost } else { cost = searchGraphDfs(edge.Node, src, dest, maxStops, stops+1, currCost+edge.Cost) } if cost < minCost { minCost = cost } } return minCost } func searchGraphBfs(graph Node, src int, dest int, maxStops int) (minCost int) { pq := &PriorityQueue{} graph.marked = true heap.Init(pq) item := Item{Value: graph.Value, Priority: 0, Node: graph, Depth: 0} heap.Push(pq, &item) minCostMap := make(MinCostMap) for pq.Len() > 0 { parentNode := heap.Pop(pq).(*Item) source := false if src == parentNode.Value { source = true } minCostMap.initKey(parentNode.Value, source) for _, edge := range parentNode.Node.Children { childNode := edge.Node source := false if src == childNode.Value { source = true } minCostMap.initKey(childNode.Value, source) currMinCost := minCostMap[childNode.Value].minCost newCost := minCostMap[parentNode.Value].minCost + edge.Cost item := Item{Value: childNode.Value, Priority: newCost, Node: childNode, Depth: parentNode.Depth + 1} // Visited first time, so update min cost and previous vertex if currMinCost == -1 { minCostMap[childNode.Value] = CostType{minCost: newCost, previousVertex: parentNode.Value} if item.Depth <= maxStops { heap.Push(pq, &item) } } // Update distance and previous vertex if the new cost is smaller than the old cost if currMinCost > newCost { minCostMap[childNode.Value] = CostType{minCost: newCost, previousVertex: parentNode.Value} pq.update(&item, item.Value, item.Priority, item.Depth) } fmt.Println(minCostMap) } } return minCostMap[dest].minCost } // MinCostRouteDfs finds the minimum cost between src to dest with max Stops constraint, using Depth First Search func MinCostRouteDfs(graph Node, src int, dest int, maxStops int) (minCost int) { /* Perform a depth first search on the graph On each iteration, first locate source. Then check if destination is reached. Along the way, keep accumulating cost and also keep an eye on max Stops constrint */ return searchGraphDfs(graph, src, dest, maxStops, 0, minCost) } // MinCostRouteBfs finds the minimum cost between src to dest with max Stops constraint, using Breadth First Search func MinCostRouteBfs(graph Node, src int, dest int, maxStops int) (minCost int) { return searchGraphBfs(graph, src, dest, maxStops) }
graphutil/graphutil.go
0.737631
0.42471
graphutil.go
starcoder
package tables import ( "fmt" "github.com/aaronland/go-sqlite" ) // TBD: move these in to aaronland/go-sqlite ? // WrapError returns a new error wrapping 'err' and prepending with the value of 't's Name() method. func WrapError(t sqlite.Table, err error) error { return fmt.Errorf("[%s] %w", t.Name(), err) } // InitializeTableError returns a new error with a default message for database initialization problems wrapping 'err' and prepending with the value of 't's Name() method. func InitializeTableError(t sqlite.Table, err error) error { return WrapError(t, fmt.Errorf("Failed to initialize database table, %w", err)) } // MissingPropertyError returns a new error with a default message for problems deriving a given property ('prop') from a record, wrapping 'err' and prepending with the value of 't's Name() method. func MissingPropertyError(t sqlite.Table, prop string, err error) error { return WrapError(t, fmt.Errorf("Failed to determine value for '%s' property, %w", prop, err)) } // DatabaseConnectionError returns a new error with a default message for database connection problems wrapping 'err' and prepending with the value of 't's Name() method. func DatabaseConnectionError(t sqlite.Table, err error) error { return WrapError(t, fmt.Errorf("Failed to establish database connection, %w", err)) } // BeginTransactionError returns a new error with a default message for database transaction initialization problems wrapping 'err' and prepending with the value of 't's Name() method. func BeginTransactionError(t sqlite.Table, err error) error { return WrapError(t, fmt.Errorf("Failed to begin database transaction, %w", err)) } // CommitTransactionError returns a new error with a default message for problems committing database transactions wrapping 'err' and prepending with the value of 't's Name() method. func CommitTransactionError(t sqlite.Table, err error) error { return WrapError(t, fmt.Errorf("Failed to commit database transaction, %w", err)) } // PrepareStatementError returns a new error with a default message for problems preparing database (SQL) statements wrapping 'err' and prepending with the value of 't's Name() method. func PrepareStatementError(t sqlite.Table, err error) error { return WrapError(t, fmt.Errorf("Failed to prepare SQL statement, %w", err)) } // ExecuteStatementError returns a new error with a default message for problems executing database (SQL) statements wrapping 'err' and prepending with the value of 't's Name() method. func ExecuteStatementError(t sqlite.Table, err error) error { return WrapError(t, fmt.Errorf("Failed to execute SQL statement, %w", err)) }
vendor/github.com/whosonfirst/go-whosonfirst-sqlite-features/tables/error.go
0.80525
0.400984
error.go
starcoder
// nolint: lll package projects import ( "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/go/pulumi" ) // Four different resources help you manage your IAM policy for a project. Each of these resources serves a different use case: // // * `projects.IAMPolicy`: Authoritative. Sets the IAM policy for the project and replaces any existing policy already attached. // * `projects.IAMBinding`: Authoritative for a given role. Updates the IAM policy to grant a role to a list of members. Other roles within the IAM policy for the project are preserved. // * `projects.IAMMember`: Non-authoritative. Updates the IAM policy to grant a role to a new member. Other members for the role for the project are preserved. // * `projects.IAMAuditConfig`: Authoritative for a given service. Updates the IAM policy to enable audit logging for the given service. // // // > **Note:** `projects.IAMPolicy` **cannot** be used in conjunction with `projects.IAMBinding`, `projects.IAMMember`, or `projects.IAMAuditConfig` or they will fight over what your policy should be. // // > **Note:** `projects.IAMBinding` resources **can be** used in conjunction with `projects.IAMMember` resources **only if** they do not grant privilege to the same role. // // > This content is derived from https://github.com/terraform-providers/terraform-provider-google/blob/master/website/docs/r/project_iam_audit_config.html.markdown. type IAMAuditConfig struct { pulumi.CustomResourceState // The configuration for logging of each type of permission. This can be specified multiple times. Structure is documented below. AuditLogConfigs IAMAuditConfigAuditLogConfigArrayOutput `pulumi:"auditLogConfigs"` // (Computed) The etag of the project's IAM policy. Etag pulumi.StringOutput `pulumi:"etag"` // The project ID. If not specified for `projects.IAMBinding`, `projects.IAMMember`, or `projects.IAMAuditConfig`, uses the ID of the project configured with the provider. // Required for `projects.IAMPolicy` - you must explicitly set the project, and it // will not be inferred from the provider. Project pulumi.StringOutput `pulumi:"project"` // Service which will be enabled for audit logging. The special value `allServices` covers all services. Note that if there are google\_project\_iam\_audit\_config resources covering both `allServices` and a specific service then the union of the two AuditConfigs is used for that service: the `logTypes` specified in each `auditLogConfig` are enabled, and the `exemptedMembers` in each `auditLogConfig` are exempted. Service pulumi.StringOutput `pulumi:"service"` } // NewIAMAuditConfig registers a new resource with the given unique name, arguments, and options. func NewIAMAuditConfig(ctx *pulumi.Context, name string, args *IAMAuditConfigArgs, opts ...pulumi.ResourceOption) (*IAMAuditConfig, error) { if args == nil || args.AuditLogConfigs == nil { return nil, errors.New("missing required argument 'AuditLogConfigs'") } if args == nil || args.Service == nil { return nil, errors.New("missing required argument 'Service'") } if args == nil { args = &IAMAuditConfigArgs{} } var resource IAMAuditConfig err := ctx.RegisterResource("gcp:projects/iAMAuditConfig:IAMAuditConfig", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetIAMAuditConfig gets an existing IAMAuditConfig resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetIAMAuditConfig(ctx *pulumi.Context, name string, id pulumi.IDInput, state *IAMAuditConfigState, opts ...pulumi.ResourceOption) (*IAMAuditConfig, error) { var resource IAMAuditConfig err := ctx.ReadResource("gcp:projects/iAMAuditConfig:IAMAuditConfig", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering IAMAuditConfig resources. type iamauditConfigState struct { // The configuration for logging of each type of permission. This can be specified multiple times. Structure is documented below. AuditLogConfigs []IAMAuditConfigAuditLogConfig `pulumi:"auditLogConfigs"` // (Computed) The etag of the project's IAM policy. Etag *string `pulumi:"etag"` // The project ID. If not specified for `projects.IAMBinding`, `projects.IAMMember`, or `projects.IAMAuditConfig`, uses the ID of the project configured with the provider. // Required for `projects.IAMPolicy` - you must explicitly set the project, and it // will not be inferred from the provider. Project *string `pulumi:"project"` // Service which will be enabled for audit logging. The special value `allServices` covers all services. Note that if there are google\_project\_iam\_audit\_config resources covering both `allServices` and a specific service then the union of the two AuditConfigs is used for that service: the `logTypes` specified in each `auditLogConfig` are enabled, and the `exemptedMembers` in each `auditLogConfig` are exempted. Service *string `pulumi:"service"` } type IAMAuditConfigState struct { // The configuration for logging of each type of permission. This can be specified multiple times. Structure is documented below. AuditLogConfigs IAMAuditConfigAuditLogConfigArrayInput // (Computed) The etag of the project's IAM policy. Etag pulumi.StringPtrInput // The project ID. If not specified for `projects.IAMBinding`, `projects.IAMMember`, or `projects.IAMAuditConfig`, uses the ID of the project configured with the provider. // Required for `projects.IAMPolicy` - you must explicitly set the project, and it // will not be inferred from the provider. Project pulumi.StringPtrInput // Service which will be enabled for audit logging. The special value `allServices` covers all services. Note that if there are google\_project\_iam\_audit\_config resources covering both `allServices` and a specific service then the union of the two AuditConfigs is used for that service: the `logTypes` specified in each `auditLogConfig` are enabled, and the `exemptedMembers` in each `auditLogConfig` are exempted. Service pulumi.StringPtrInput } func (IAMAuditConfigState) ElementType() reflect.Type { return reflect.TypeOf((*iamauditConfigState)(nil)).Elem() } type iamauditConfigArgs struct { // The configuration for logging of each type of permission. This can be specified multiple times. Structure is documented below. AuditLogConfigs []IAMAuditConfigAuditLogConfig `pulumi:"auditLogConfigs"` // The project ID. If not specified for `projects.IAMBinding`, `projects.IAMMember`, or `projects.IAMAuditConfig`, uses the ID of the project configured with the provider. // Required for `projects.IAMPolicy` - you must explicitly set the project, and it // will not be inferred from the provider. Project *string `pulumi:"project"` // Service which will be enabled for audit logging. The special value `allServices` covers all services. Note that if there are google\_project\_iam\_audit\_config resources covering both `allServices` and a specific service then the union of the two AuditConfigs is used for that service: the `logTypes` specified in each `auditLogConfig` are enabled, and the `exemptedMembers` in each `auditLogConfig` are exempted. Service string `pulumi:"service"` } // The set of arguments for constructing a IAMAuditConfig resource. type IAMAuditConfigArgs struct { // The configuration for logging of each type of permission. This can be specified multiple times. Structure is documented below. AuditLogConfigs IAMAuditConfigAuditLogConfigArrayInput // The project ID. If not specified for `projects.IAMBinding`, `projects.IAMMember`, or `projects.IAMAuditConfig`, uses the ID of the project configured with the provider. // Required for `projects.IAMPolicy` - you must explicitly set the project, and it // will not be inferred from the provider. Project pulumi.StringPtrInput // Service which will be enabled for audit logging. The special value `allServices` covers all services. Note that if there are google\_project\_iam\_audit\_config resources covering both `allServices` and a specific service then the union of the two AuditConfigs is used for that service: the `logTypes` specified in each `auditLogConfig` are enabled, and the `exemptedMembers` in each `auditLogConfig` are exempted. Service pulumi.StringInput } func (IAMAuditConfigArgs) ElementType() reflect.Type { return reflect.TypeOf((*iamauditConfigArgs)(nil)).Elem() }
sdk/go/gcp/projects/iamauditConfig.go
0.633864
0.446495
iamauditConfig.go
starcoder
package pretty_poly import "math" type geohash struct { values [ ] bool } type geohash2d struct { xs [ ] bool ys [ ] bool } type interval struct { lower float64 upper float64 } type interval2d struct { x interval y interval } type point2d struct { x float64 y float64 } func Interval (lower float64, upper float64) interval { return interval { lower: lower, upper: upper, } } func (interval0 *interval) AddXInterval (interval1 interval) interval2d { return interval2d { x: interval1, y: *interval0, } } func (interval0 *interval) AddYInterval (interval1 interval) interval2d { return interval2d { x: *interval0, y: interval1, } } func Interval2d (lowerx float64, upperx float64, lowery float64, uppery float64) interval2d { return interval2d { x: Interval(lowerx, upperx), y: Interval(lowery, uppery), } } func (hash0 geohash) Equal(hash1 geohash) bool { for ith := 0; ith < len(hash0.values); ith++ { if hash0.values[ith] != hash1.values[ith] { return false } } return true } func (hash geohash) Decompress ( ) geohash2d { xs := make([ ] bool, len(hash.values) / 2, len(hash.values) / 2) ys := make([ ] bool, len(hash.values) / 2, len(hash.values) / 2) xcount := 0 ycount := 0 for ith := 0; ith < len(hash.values); ith++ { if ith % 2 == 0 { xs[xcount] = hash.values[ith] xcount++ } else { ys[ycount] = hash.values[ith] ycount++ } } return geohash2d { xs: xs, ys: ys, } } func Geohash (precision int8, bounds interval, num float64) geohash { values := make([ ]bool, precision, precision) var isUpperBucket bool tmpInterval := interval { lower: bounds.lower, upper: bounds.upper, } for ith := 0; ith < int(precision); ith++ { offset := (bounds.upper - bounds.lower) / math.Pow(2, float64(ith + 1)) pivot := tmpInterval.lower + ((tmpInterval.upper - tmpInterval.lower) / 2.0) isUpperBucket = num > float64(pivot) values[ith] = isUpperBucket if pivot < bounds.lower || pivot > bounds.upper { panic("pivot out of bounds.") } if isUpperBucket { tmpInterval.lower += offset } else { tmpInterval.upper -= offset } } return geohash { values: values, } } func (hash0 geohash2d) Equal(hash1 geohash2d) bool { for ith := 0; ith < len(hash0.xs); ith++ { if hash0.xs[ith] != hash1.xs[ith] { return false } } for ith := 0; ith < len(hash0.ys); ith++ { if hash0.ys[ith] != hash1.ys[ith] { return false } } return true } func (hash geohash2d) Compress ( ) geohash { outputLength := len(hash.xs) + len(hash.ys) output := make([ ] bool, outputLength, outputLength) xcount := 0 ycount := 0 for ith := 0; ith < outputLength; ith++ { if ith % 2 == 0 { output[ith] = hash.xs[xcount] xcount++ } else { output[ith] = hash.ys[ycount] ycount++ } } return geohash { values: output, } } func Geohash2d (precision int8, interval interval2d, point2d point2d) geohash2d { _ = Geohash(precision, interval.x, point2d.x).values return geohash2d { xs: Geohash(precision, interval.x, point2d.x).values, ys: Geohash(precision, interval.y, point2d.y).values, } } func (hash0 *geohash) AddXAxis (hash1 geohash) geohash2d { return geohash2d { xs: hash1.values, ys: hash0.values, } } func (hash0 *geohash) AddYAxis (hash1 geohash) geohash2d { return geohash2d { xs: hash0.values, ys: hash1.values, } } func Geohash2dAsUint64 (hash geohash2d) (uint64, error) { return fromBitsLittleEndian(IntersperseBool(hash.xs, hash.ys)), nil } func Uint64AsGeohash2d (precision int8, hash uint64) (geohash2d, error) { bitCount := 2 * int(precision) bits := toBits(hash, bitCount) xs, ys, err := DisperseBool(bits) if err != nil { return geohash2d {xs: nil, ys: nil}, err } else { return geohash2d { xs: xs, ys: ys, }, nil } } func (hash geohash) AsPoint (interval interval) float64 { point := 0.0 for ith := 0; ith < len(hash.values); ith++ { divisor := math.Pow(2, float64(ith + 1)) if hash.values[ith] == true { point += (interval.upper - interval.lower) / float64(divisor) } } return math.Floor(point) } func (hash geohash2d) AsPoint (interval interval2d) point2d { x := (geohash {values: hash.xs }).AsPoint(interval.x) y := (geohash {values: hash.ys }).AsPoint(interval.y) return point2d { x: x, y: y, } }
src/github.com/rgrannell/pretty_poly/geocode.go
0.610918
0.626124
geocode.go
starcoder
package ffmpeg_go import ( "bytes" "fmt" ) type ViewType string const ( // FlowChart the diagram type for output in flowchart style (https://mermaid-js.github.io/mermaid/#/flowchart) (including current state ViewTypeFlowChart ViewType = "flowChart" // StateDiagram the diagram type for output in stateDiagram style (https://mermaid-js.github.io/mermaid/#/stateDiagram) ViewTypeStateDiagram ViewType = "stateDiagram" ) func (s *Stream) View(viewType ViewType) (string, error) { switch viewType { case ViewTypeFlowChart: return visualizeForMermaidAsFlowChart(s) case ViewTypeStateDiagram: return visualizeForMermaidAsStateDiagram(s) default: return "", fmt.Errorf("unknown ViewType: %s", viewType) } } func visualizeForMermaidAsStateDiagram(s *Stream) (string, error) { var buf bytes.Buffer nodes := getStreamSpecNodes([]*Stream{s}) var dagNodes []DagNode for i := range nodes { dagNodes = append(dagNodes, nodes[i]) } sorted, outGoingMap, err := TopSort(dagNodes) if err != nil { return "", err } buf.WriteString("stateDiagram\n") for _, node := range sorted { next := outGoingMap[node.Hash()] for k, v := range next { for _, nextNode := range v { label := string(k) if label == "" { label = "<>" } buf.WriteString(fmt.Sprintf(` %s --> %s: %s`, node.ShortRepr(), nextNode.Node.ShortRepr(), label)) buf.WriteString("\n") } } } return buf.String(), nil } // visualizeForMermaidAsFlowChart outputs a visualization of a FSM in Mermaid format (including highlighting of current state). func visualizeForMermaidAsFlowChart(s *Stream) (string, error) { var buf bytes.Buffer nodes := getStreamSpecNodes([]*Stream{s}) var dagNodes []DagNode for i := range nodes { dagNodes = append(dagNodes, nodes[i]) } sorted, outGoingMap, err := TopSort(dagNodes) if err != nil { return "", err } buf.WriteString("graph LR\n") for _, node := range sorted { buf.WriteString(fmt.Sprintf(` %d[%s]`, node.Hash(), node.ShortRepr())) buf.WriteString("\n") } buf.WriteString("\n") for _, node := range sorted { next := outGoingMap[node.Hash()] for k, v := range next { for _, nextNode := range v { // todo ignore merged output label := string(k) if label == "" { label = "<>" } buf.WriteString(fmt.Sprintf(` %d --> |%s| %d`, node.Hash(), fmt.Sprintf("%s:%s", nextNode.Label, label), nextNode.Node.Hash())) buf.WriteString("\n") } } } buf.WriteString("\n") return buf.String(), nil }
view.go
0.541894
0.469824
view.go
starcoder
package binary_tree_postorder_traversal /* 145. 二叉树的后序遍历 https://leetcode-cn.com/problems/binary-tree-postorder-traversal 给定一个二叉树,返回它的 后序 遍历。 示例: 输入: [1,null,2,3] 1 \ 2 / 3 输出: [3,2,1] */ type TreeNode struct { Val int Left *TreeNode Right *TreeNode } // 递归解决 func postorderTraversal(root *TreeNode) []int { var result []int var postororder func(root *TreeNode) postororder = func(node *TreeNode) { if node == nil { return } // left -> right -> root postororder(node.Left) postororder(node.Right) result = append(result, node.Val) } postororder(root) return result } /* 迭代,节点标记法 在出入栈的时候,标记节点,具体为: 标记节点的状态,新节点为false,已使用(在这道题里是指将节点值追加到结果数组)的节点true。 如果遇到未标记的节点,则将其标记为true,然后将其自身、右节点、左节点依次入栈;注意到顺序与遍历次序正好相反。 如果遇到的节点标记为true,则使用该节点。 这个方法在前序、中序、后续遍历里的实现代码总体逻辑一致,只是入栈的顺序稍微调整即可 */ func postorderTraversal2(root *TreeNode) []int { var result []int stack := []*TreeNode{root} marked := map[*TreeNode]bool{} for len(stack) > 0 { node := stack[len(stack)-1] stack = stack[:len(stack)-1] if node == nil { continue } if marked[node] { result = append(result, node.Val) continue } marked[node] = true stack = append(stack, node) stack = append(stack, node.Right) stack = append(stack, node.Left) } return result } /* morris 迭代实现 优秀的是空间复杂度 详见 94. 二叉树的中序遍历 问题 morris 迭代实现解法说明 */ var res []int func postorderTraversalMorris(root *TreeNode) []int { res = nil dummy := &TreeNode{Left: root} cur := dummy var node *TreeNode for cur != nil { if cur.Left == nil { cur = cur.Right continue } // 找 cur 的前驱 node = cur.Left for node.Right != nil && node.Right != cur { node = node.Right } if node.Right == nil { // 还没线索化,建立线索 node.Right = cur cur = cur.Left } else { // 已经线索化,访问节点并删除线索以恢复树的结构 node.Right = nil visitPath(cur.Left) cur = cur.Right } } dummy.Left = nil return res } func visitPath(node *TreeNode) { end := reversePath(node) for p := end; p != nil; p = p.Right { res = append(res, p.Val) } _ = reversePath(end) } func reversePath(node *TreeNode) *TreeNode { var prev *TreeNode for node != nil { prev, node, node.Right = node, node.Right, prev } return prev }
solutions/binary-tree-postorder-traversal/d.go
0.631935
0.493775
d.go
starcoder
package block import ( "github.com/df-mc/dragonfly/dragonfly/item" "github.com/df-mc/dragonfly/dragonfly/world" "github.com/go-gl/mathgl/mgl64" "math/rand" ) // MelonSeeds grow melon blocks. type MelonSeeds struct { crop // Direction is the direction from the stem to the melon. Direction world.Face } // NeighbourUpdateTick ... func (m MelonSeeds) NeighbourUpdateTick(pos, _ world.BlockPos, w *world.World) { if _, ok := w.Block(pos.Side(world.FaceDown)).(Farmland); !ok { w.BreakBlock(pos) } else if m.Direction != world.FaceDown { if _, ok := w.Block(pos.Side(m.Direction)).(Melon); !ok { m.Direction = world.FaceDown w.PlaceBlock(pos, m) } } } // RandomTick ... func (m MelonSeeds) RandomTick(pos world.BlockPos, w *world.World, r *rand.Rand) { if rand.Float64() <= m.CalculateGrowthChance(pos, w) && w.Light(pos) >= 8 { if m.Growth < 7 { m.Growth++ w.PlaceBlock(pos, m) } else { directions := []world.Direction{world.North, world.South, world.West, world.East} for _, i := range directions { if _, ok := w.Block(pos.Side(i.Face())).(Melon); ok { return } } direction := directions[rand.Intn(len(directions))].Face() stemPos := pos.Side(direction) if _, ok := w.Block(stemPos).(Air); ok { switch w.Block(stemPos.Side(world.FaceDown)).(type) { case Farmland: case Dirt: case Grass: m.Direction = direction w.PlaceBlock(pos, m) w.PlaceBlock(stemPos, Melon{}) } } } } } // BoneMeal ... func (m MelonSeeds) BoneMeal(pos world.BlockPos, w *world.World) bool { if m.Growth == 7 { return false } m.Growth = min(m.Growth+rand.Intn(4)+2, 7) w.PlaceBlock(pos, m) return true } // UseOnBlock ... func (m MelonSeeds) UseOnBlock(pos world.BlockPos, face world.Face, _ mgl64.Vec3, w *world.World, user item.User, ctx *item.UseContext) bool { pos, _, used := firstReplaceable(w, pos, face, m) if !used { return false } if _, ok := w.Block(pos.Side(world.FaceDown)).(Farmland); !ok { return false } place(w, pos, m, user, ctx) return placed(ctx) } // BreakInfo ... func (m MelonSeeds) BreakInfo() BreakInfo { return BreakInfo{ Hardness: 0, Harvestable: alwaysHarvestable, Effective: nothingEffective, Drops: simpleDrops(item.NewStack(m, 1)), } } // EncodeItem ... func (m MelonSeeds) EncodeItem() (id int32, meta int16) { return 362, 0 } // EncodeBlock ... func (m MelonSeeds) EncodeBlock() (name string, properties map[string]interface{}) { return "minecraft:melon_stem", map[string]interface{}{"facing_direction": int32(m.Direction), "growth": int32(m.Growth)} } // Hash ... func (m MelonSeeds) Hash() uint64 { return hashMelonStem | (uint64(m.Growth) << 32) | (uint64(m.Direction) << 35) } // allMelonStems func allMelonStems() (stems []world.Block) { for i := 0; i <= 7; i++ { for j := world.Face(0); j <= 5; j++ { stems = append(stems, MelonSeeds{Direction: j, crop: crop{Growth: i}}) } } return }
dragonfly/block/melon_seeds.go
0.585812
0.459319
melon_seeds.go
starcoder
package base32 import ( "errors" "fmt" ) // EncodedLen returns the length of the base32 encoding of an input buffer of length n. func EncodedLen(n int) int { return (n*8 + 4) / 5 } // Encode encodes src into EncodedLen(len(src)) digits of dst. // As a convenience, it returns the number of digits written to dst, // but this value is always EncodedLen(len(src)). // Encode implements base32 encoding. func Encode(dst []uint8, src []byte) int { n := EncodedLen(len(src)) for len(src) > 0 { var carry byte // unpack 8x 5-bit source blocks into a 5 byte destination quantum switch len(src) { default: dst[7] = src[4] & 0x1F carry = src[4] >> 5 fallthrough case 4: dst[6] = carry | (src[3]<<3)&0x1F dst[5] = (src[3] >> 2) & 0x1F carry = src[3] >> 7 fallthrough case 3: dst[4] = carry | (src[2]<<1)&0x1F carry = (src[2] >> 4) & 0x1F fallthrough case 2: dst[3] = carry | (src[1]<<4)&0x1F dst[2] = (src[1] >> 1) & 0x1F carry = (src[1] >> 6) & 0x1F fallthrough case 1: dst[1] = carry | (src[0]<<2)&0x1F dst[0] = src[0] >> 3 } if len(src) < 5 { break } src = src[5:] dst = dst[8:] } return n } var ( // ErrInvalidLength reports an attempt to decode an input of invalid length. ErrInvalidLength = errors.New("invalid length") // ErrNonZeroPadding reports an attempt to decode an input without zero padding. ErrNonZeroPadding = errors.New("non-zero padding") ) // A CorruptInputError is a description of a base32 syntax error. type CorruptInputError struct { err error // wrapped error Offset int // error occurred after reading Offset bytes } func (e CorruptInputError) Error() string { return fmt.Sprintf("%s at input byte %d", e.err, e.Offset) } func (e CorruptInputError) Unwrap() error { return e.err } // DecodedLen returns the maximum length in bytes of the decoded data corresponding to n base32-encoded values. func DecodedLen(n int) int { return n * 5 / 8 } // Decode decodes src into DecodedLen(len(src)) bytes, returning the actual number of bytes written to dst. // If the input is malformed, Decode returns an error and the number of bytes decoded before the error. func Decode(dst []byte, src []uint8) (int, error) { written := 0 read := 0 for len(src) > 0 { n := len(src) if n == 1 || n == 3 || n == 6 { return written, &CorruptInputError{ErrInvalidLength, read} } // pack 8x 5-bit source blocks into 5 byte destination quantum switch n { default: dst[4] = src[6]<<5 | src[7] written++ fallthrough case 7: dst[3] = src[4]<<7 | src[5]<<2 | src[6]>>3 written++ fallthrough case 5: dst[2] = src[3]<<4 | src[4]>>1 written++ fallthrough case 4: dst[1] = src[1]<<6 | src[2]<<1 | src[3]>>4 written++ fallthrough case 2: dst[0] = src[0]<<3 | src[1]>>2 written++ } if n < 8 { // check for non-zero padding switch { case n == 2 && src[1]&(1<<2-1) != 0: return written, &CorruptInputError{ErrNonZeroPadding, read + 1} case n == 4 && src[3]&(1<<4-1) != 0: return written, &CorruptInputError{ErrNonZeroPadding, read + 3} case n == 5 && src[4]&(1<<1-1) != 0: return written, &CorruptInputError{ErrNonZeroPadding, read + 4} case n == 7 && src[6]&(1<<3-1) != 0: return written, &CorruptInputError{ErrNonZeroPadding, read + 6} } break } dst = dst[5:] src = src[8:] read += 8 } return written, nil }
bech32/internal/base32/base32.go
0.693784
0.457197
base32.go
starcoder
package unit import ( "fmt" "math" "reflect" ) type LessConstraint struct { expected interface{} } func NewLessConstraint(expected interface{}) Constraint { switch reflect.ValueOf(expected).Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64: return &LessConstraint{expected: expected} } err := NewInvalidNumericComparisonTypeError("expectedKinds", expected) panic(err) } func (c *LessConstraint) Check(actual interface{}) bool { expectedValue := reflect.ValueOf(c.expected) actualValue := reflect.ValueOf(actual) switch expectedValue.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: switch actualValue.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return expectedValue.Int() > actualValue.Int() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: expectedInt := expectedValue.Int() actualUint := actualValue.Uint() if actualUint <= math.MaxInt64 { return expectedInt > int64(actualUint) } if expectedInt >= 0 { return uint64(expectedInt) > actualUint } return float64(expectedInt) > float64(actualUint) case reflect.Float32, reflect.Float64: return float64(expectedValue.Int()) > actualValue.Float() } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: switch actualValue.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: xUint := expectedValue.Uint() yInt := actualValue.Int() if xUint <= math.MaxInt64 { return int64(xUint) > yInt } if yInt >= 0 { return xUint > uint64(yInt) } return float64(xUint) > float64(yInt) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return expectedValue.Uint() > actualValue.Uint() case reflect.Float32, reflect.Float64: return float64(expectedValue.Uint()) > actualValue.Float() } case reflect.Float32, reflect.Float64: switch actualValue.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return expectedValue.Float() > float64(actualValue.Int()) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return expectedValue.Float() > float64(actualValue.Uint()) case reflect.Float32, reflect.Float64: return expectedValue.Float() > actualValue.Float() } } err := NewInvalidNumericComparisonTypeError("actual", actual) panic(err) } func (c *LessConstraint) String() string { return fmt.Sprintf("be less than %v", c.expected) } func (c *LessConstraint) Details(actual interface{}) string { return "" }
unit/less_constraint.go
0.71103
0.634062
less_constraint.go
starcoder
package models import ( i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization" ) // CloudPcDomainJoinConfiguration type CloudPcDomainJoinConfiguration struct { // Stores additional data not described in the OpenAPI description found when deserializing. Can be used for serialization as well. additionalData map[string]interface{} // The Azure network connection ID that matches the virtual network IT admins want the provisioning policy to use when they create Cloud PCs. You can use this property in both domain join types: Azure AD joined or Hybrid Azure AD joined. If you enter an onPremisesConnectionId, leave regionName as empty. onPremisesConnectionId *string // The supported Azure region where the IT admin wants the provisioning policy to create Cloud PCs. The underlying virtual network will be created and managed by the Windows 365 service. This can only be entered if the IT admin chooses Azure AD joined as the domain join type. If you enter a regionName, leave onPremisesConnectionId as empty. regionName *string // Specifies how the provisioned Cloud PC will be joined to Azure AD. If you choose the hybridAzureADJoin type, only provide a value for the onPremisesConnectionId property and leave regionName as empty. If you choose the azureADJoin type, provide a value for either onPremisesConnectionId or regionName. The possible values are: azureADJoin, hybridAzureADJoin, unknownFutureValue. type_escaped *CloudPcDomainJoinType } // NewCloudPcDomainJoinConfiguration instantiates a new cloudPcDomainJoinConfiguration and sets the default values. func NewCloudPcDomainJoinConfiguration()(*CloudPcDomainJoinConfiguration) { m := &CloudPcDomainJoinConfiguration{ } m.SetAdditionalData(make(map[string]interface{})); return m } // CreateCloudPcDomainJoinConfigurationFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value func CreateCloudPcDomainJoinConfigurationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) { return NewCloudPcDomainJoinConfiguration(), nil } // 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 *CloudPcDomainJoinConfiguration) GetAdditionalData()(map[string]interface{}) { if m == nil { return nil } else { return m.additionalData } } // GetFieldDeserializers the deserialization information for the current model func (m *CloudPcDomainJoinConfiguration) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) { res := make(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) res["onPremisesConnectionId"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetOnPremisesConnectionId(val) } return nil } res["regionName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetRegionName(val) } return nil } res["type"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetEnumValue(ParseCloudPcDomainJoinType) if err != nil { return err } if val != nil { m.SetType(val.(*CloudPcDomainJoinType)) } return nil } return res } // GetOnPremisesConnectionId gets the onPremisesConnectionId property value. The Azure network connection ID that matches the virtual network IT admins want the provisioning policy to use when they create Cloud PCs. You can use this property in both domain join types: Azure AD joined or Hybrid Azure AD joined. If you enter an onPremisesConnectionId, leave regionName as empty. func (m *CloudPcDomainJoinConfiguration) GetOnPremisesConnectionId()(*string) { if m == nil { return nil } else { return m.onPremisesConnectionId } } // GetRegionName gets the regionName property value. The supported Azure region where the IT admin wants the provisioning policy to create Cloud PCs. The underlying virtual network will be created and managed by the Windows 365 service. This can only be entered if the IT admin chooses Azure AD joined as the domain join type. If you enter a regionName, leave onPremisesConnectionId as empty. func (m *CloudPcDomainJoinConfiguration) GetRegionName()(*string) { if m == nil { return nil } else { return m.regionName } } // GetType gets the type property value. Specifies how the provisioned Cloud PC will be joined to Azure AD. If you choose the hybridAzureADJoin type, only provide a value for the onPremisesConnectionId property and leave regionName as empty. If you choose the azureADJoin type, provide a value for either onPremisesConnectionId or regionName. The possible values are: azureADJoin, hybridAzureADJoin, unknownFutureValue. func (m *CloudPcDomainJoinConfiguration) GetType()(*CloudPcDomainJoinType) { if m == nil { return nil } else { return m.type_escaped } } // Serialize serializes information the current object func (m *CloudPcDomainJoinConfiguration) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) { { err := writer.WriteStringValue("onPremisesConnectionId", m.GetOnPremisesConnectionId()) if err != nil { return err } } { err := writer.WriteStringValue("regionName", m.GetRegionName()) if err != nil { return err } } if m.GetType() != nil { cast := (*m.GetType()).String() err := writer.WriteStringValue("type", &cast) if err != nil { return err } } { err := writer.WriteAdditionalData(m.GetAdditionalData()) if err != nil { return err } } return nil } // 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 *CloudPcDomainJoinConfiguration) SetAdditionalData(value map[string]interface{})() { if m != nil { m.additionalData = value } } // SetOnPremisesConnectionId sets the onPremisesConnectionId property value. The Azure network connection ID that matches the virtual network IT admins want the provisioning policy to use when they create Cloud PCs. You can use this property in both domain join types: Azure AD joined or Hybrid Azure AD joined. If you enter an onPremisesConnectionId, leave regionName as empty. func (m *CloudPcDomainJoinConfiguration) SetOnPremisesConnectionId(value *string)() { if m != nil { m.onPremisesConnectionId = value } } // SetRegionName sets the regionName property value. The supported Azure region where the IT admin wants the provisioning policy to create Cloud PCs. The underlying virtual network will be created and managed by the Windows 365 service. This can only be entered if the IT admin chooses Azure AD joined as the domain join type. If you enter a regionName, leave onPremisesConnectionId as empty. func (m *CloudPcDomainJoinConfiguration) SetRegionName(value *string)() { if m != nil { m.regionName = value } } // SetType sets the type property value. Specifies how the provisioned Cloud PC will be joined to Azure AD. If you choose the hybridAzureADJoin type, only provide a value for the onPremisesConnectionId property and leave regionName as empty. If you choose the azureADJoin type, provide a value for either onPremisesConnectionId or regionName. The possible values are: azureADJoin, hybridAzureADJoin, unknownFutureValue. func (m *CloudPcDomainJoinConfiguration) SetType(value *CloudPcDomainJoinType)() { if m != nil { m.type_escaped = value } }
models/cloud_pc_domain_join_configuration.go
0.689515
0.420838
cloud_pc_domain_join_configuration.go
starcoder
package main import ( "log" "math" ) /** 题目:https://leetcode-cn.com/problems/divide-two-integers/ 两数相除 给定两个整数,被除数dividend和除数divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。 返回被除数dividend除以除数divisor得到的商。 整数除法的结果应当截去(truncate)其小数部分,例如:truncate(8.345) = 8 以及 truncate(-2.7335) = -2 示例1: 输入: dividend = 10, divisor = 3 输出: 3 解释: 10/3 = truncate(3.33333..) = truncate(3) = 3 示例2: 输入: dividend = 7, divisor = -3 输出: -2 解释: 7/-3 = truncate(-2.33333..) = -2 提示: 被除数和除数均为 32 位有符号整数。 除数不为0。 假设我们的环境只能存储 32 位有符号整数,其数值范围是 [−2^31, 2^31− 1]。本题中,如果除法结果溢出,则返回 2^31− 1。 思路: 1.不能使用*,/,%等符号 2.考虑溢出 3.使用移位每次扩大步长,然后使用减法,如果减法也不让用,那么就使用位运算模拟 4.考虑异常情况,被除数最小,除数为1,-1 5.除数最小,被除数为最小或者其他 6.除数为0 */ func main() { dividend := -2147483648 divisor := -1 log.Println("两数相除:", divide(dividend, divisor)) } func divide(dividend int, divisor int) int { // 提前把异常情况过滤 if dividend == math.MinInt32 { // 考虑被除数为最小值的情况 if divisor == 1 { return math.MinInt32 } // 题目有说明,-1的时候除法结果溢出,返回最大值 if divisor == -1 { return math.MaxInt32 } } if divisor == math.MinInt32 { // 考虑除数为最小值的情况 if dividend == math.MinInt32 { return 1 } return 0 } if dividend == 0 { // 考虑被除数为 0 的情况 return 0 } var res int // 第一步确定最终结果的符号 sign := -1 if (dividend ^ divisor) >= 0 { sign = 1 } // 第二步骤:两个数字都转成负数,此处不能求绝对值,因为转为正数的过程中可能会溢出,所以都转换为负数 var dividendTemp int if dividend < 0 { dividendTemp = dividend } else { dividendTemp = -dividend } var divisorTemp int if divisor < 0 { divisorTemp = divisor } else { divisorTemp = -divisor } // 第三步骤:阈值 threshold := math.MinInt >> 1 // 第四步骤:因为此处都是负数,所以正好相反 for dividendTemp <= divisorTemp { tmp := divisorTemp times := 1 //除数divisor的倍数 // tmp移位之后还是负数 for tmp >= threshold && dividendTemp <= (tmp<<1) { tmp <<= 1 times <<= 1 } // 更新被除数 dividendTemp -= tmp // 累加次数 res += times } if sign < 0 { res = -res } if res > math.MaxInt { res = math.MaxInt } return res } // https://blog.csdn.net/jjwwwww/article/details/82745855 // Subtraction 位运算模拟减法 func Subtraction(num1, num2 int) int { x := num1 ^ num2 y := x & num2 for y != 0 { y = y << 1 x = x ^ y y = x & y } return x } // Addition 位运算实现加法 func Addition(num1, num2 int) int { x := num1 ^ num2 // a^b得到原位和(相当于按位相加没有进位) y := num1 & num2 for y != 0 { y = y << 1 temp := x x = x ^ y y = temp & y } return x }
algorithm/leetcodeQuestion/divide/divide.go
0.608012
0.442155
divide.go
starcoder
package plaid import ( "encoding/json" ) // ProcessorNumber An object containing identifying numbers used for making electronic transfers to and from the `account`. The identifying number type (ACH, EFT, IBAN, or BACS) used will depend on the country of the account. An account may have more than one number type. If a particular identifying number type is not used by the `account` for which auth data has been requested, a null value will be returned. type ProcessorNumber struct { Ach NullableNumbersACHNullable `json:"ach,omitempty"` Eft NullableNumbersEFTNullable `json:"eft,omitempty"` International NullableNumbersInternationalNullable `json:"international,omitempty"` Bacs NullableNumbersBACSNullable `json:"bacs,omitempty"` AdditionalProperties map[string]interface{} } type _ProcessorNumber ProcessorNumber // NewProcessorNumber instantiates a new ProcessorNumber 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 NewProcessorNumber() *ProcessorNumber { this := ProcessorNumber{} return &this } // NewProcessorNumberWithDefaults instantiates a new ProcessorNumber 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 NewProcessorNumberWithDefaults() *ProcessorNumber { this := ProcessorNumber{} return &this } // GetAch returns the Ach field value if set, zero value otherwise (both if not set or set to explicit null). func (o *ProcessorNumber) GetAch() NumbersACHNullable { if o == nil || o.Ach.Get() == nil { var ret NumbersACHNullable return ret } return *o.Ach.Get() } // GetAchOk returns a tuple with the Ach field value if set, nil otherwise // 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 *ProcessorNumber) GetAchOk() (*NumbersACHNullable, bool) { if o == nil { return nil, false } return o.Ach.Get(), o.Ach.IsSet() } // HasAch returns a boolean if a field has been set. func (o *ProcessorNumber) HasAch() bool { if o != nil && o.Ach.IsSet() { return true } return false } // SetAch gets a reference to the given NullableNumbersACHNullable and assigns it to the Ach field. func (o *ProcessorNumber) SetAch(v NumbersACHNullable) { o.Ach.Set(&v) } // SetAchNil sets the value for Ach to be an explicit nil func (o *ProcessorNumber) SetAchNil() { o.Ach.Set(nil) } // UnsetAch ensures that no value is present for Ach, not even an explicit nil func (o *ProcessorNumber) UnsetAch() { o.Ach.Unset() } // GetEft returns the Eft field value if set, zero value otherwise (both if not set or set to explicit null). func (o *ProcessorNumber) GetEft() NumbersEFTNullable { if o == nil || o.Eft.Get() == nil { var ret NumbersEFTNullable return ret } return *o.Eft.Get() } // GetEftOk returns a tuple with the Eft field value if set, nil otherwise // 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 *ProcessorNumber) GetEftOk() (*NumbersEFTNullable, bool) { if o == nil { return nil, false } return o.Eft.Get(), o.Eft.IsSet() } // HasEft returns a boolean if a field has been set. func (o *ProcessorNumber) HasEft() bool { if o != nil && o.Eft.IsSet() { return true } return false } // SetEft gets a reference to the given NullableNumbersEFTNullable and assigns it to the Eft field. func (o *ProcessorNumber) SetEft(v NumbersEFTNullable) { o.Eft.Set(&v) } // SetEftNil sets the value for Eft to be an explicit nil func (o *ProcessorNumber) SetEftNil() { o.Eft.Set(nil) } // UnsetEft ensures that no value is present for Eft, not even an explicit nil func (o *ProcessorNumber) UnsetEft() { o.Eft.Unset() } // GetInternational returns the International field value if set, zero value otherwise (both if not set or set to explicit null). func (o *ProcessorNumber) GetInternational() NumbersInternationalNullable { if o == nil || o.International.Get() == nil { var ret NumbersInternationalNullable return ret } return *o.International.Get() } // GetInternationalOk returns a tuple with the International field value if set, nil otherwise // 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 *ProcessorNumber) GetInternationalOk() (*NumbersInternationalNullable, bool) { if o == nil { return nil, false } return o.International.Get(), o.International.IsSet() } // HasInternational returns a boolean if a field has been set. func (o *ProcessorNumber) HasInternational() bool { if o != nil && o.International.IsSet() { return true } return false } // SetInternational gets a reference to the given NullableNumbersInternationalNullable and assigns it to the International field. func (o *ProcessorNumber) SetInternational(v NumbersInternationalNullable) { o.International.Set(&v) } // SetInternationalNil sets the value for International to be an explicit nil func (o *ProcessorNumber) SetInternationalNil() { o.International.Set(nil) } // UnsetInternational ensures that no value is present for International, not even an explicit nil func (o *ProcessorNumber) UnsetInternational() { o.International.Unset() } // GetBacs returns the Bacs field value if set, zero value otherwise (both if not set or set to explicit null). func (o *ProcessorNumber) GetBacs() NumbersBACSNullable { if o == nil || o.Bacs.Get() == nil { var ret NumbersBACSNullable return ret } return *o.Bacs.Get() } // GetBacsOk returns a tuple with the Bacs field value if set, nil otherwise // 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 *ProcessorNumber) GetBacsOk() (*NumbersBACSNullable, bool) { if o == nil { return nil, false } return o.Bacs.Get(), o.Bacs.IsSet() } // HasBacs returns a boolean if a field has been set. func (o *ProcessorNumber) HasBacs() bool { if o != nil && o.Bacs.IsSet() { return true } return false } // SetBacs gets a reference to the given NullableNumbersBACSNullable and assigns it to the Bacs field. func (o *ProcessorNumber) SetBacs(v NumbersBACSNullable) { o.Bacs.Set(&v) } // SetBacsNil sets the value for Bacs to be an explicit nil func (o *ProcessorNumber) SetBacsNil() { o.Bacs.Set(nil) } // UnsetBacs ensures that no value is present for Bacs, not even an explicit nil func (o *ProcessorNumber) UnsetBacs() { o.Bacs.Unset() } func (o ProcessorNumber) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Ach.IsSet() { toSerialize["ach"] = o.Ach.Get() } if o.Eft.IsSet() { toSerialize["eft"] = o.Eft.Get() } if o.International.IsSet() { toSerialize["international"] = o.International.Get() } if o.Bacs.IsSet() { toSerialize["bacs"] = o.Bacs.Get() } for key, value := range o.AdditionalProperties { toSerialize[key] = value } return json.Marshal(toSerialize) } func (o *ProcessorNumber) UnmarshalJSON(bytes []byte) (err error) { varProcessorNumber := _ProcessorNumber{} if err = json.Unmarshal(bytes, &varProcessorNumber); err == nil { *o = ProcessorNumber(varProcessorNumber) } additionalProperties := make(map[string]interface{}) if err = json.Unmarshal(bytes, &additionalProperties); err == nil { delete(additionalProperties, "ach") delete(additionalProperties, "eft") delete(additionalProperties, "international") delete(additionalProperties, "bacs") o.AdditionalProperties = additionalProperties } return err } type NullableProcessorNumber struct { value *ProcessorNumber isSet bool } func (v NullableProcessorNumber) Get() *ProcessorNumber { return v.value } func (v *NullableProcessorNumber) Set(val *ProcessorNumber) { v.value = val v.isSet = true } func (v NullableProcessorNumber) IsSet() bool { return v.isSet } func (v *NullableProcessorNumber) Unset() { v.value = nil v.isSet = false } func NewNullableProcessorNumber(val *ProcessorNumber) *NullableProcessorNumber { return &NullableProcessorNumber{value: val, isSet: true} } func (v NullableProcessorNumber) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableProcessorNumber) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
plaid/model_processor_number.go
0.829699
0.547464
model_processor_number.go
starcoder
package gl import ( "fmt" "github.com/glycerine/gxui" "github.com/glycerine/gxui/math" "github.com/goxjs/gl" ) type shaderUniform struct { name string size int ty shaderDataType location gl.Uniform textureUnit int } func (u *shaderUniform) bind(context *context, v interface{}) { switch u.ty { case stFloatMat2: gl.UniformMatrix2fv(u.location, v.([]float32)) case stFloatMat3: switch m := v.(type) { case math.Mat3: gl.UniformMatrix3fv(u.location, m[:]) case []float32: gl.UniformMatrix3fv(u.location, m) } case stFloatMat4: gl.UniformMatrix4fv(u.location, v.([]float32)) case stFloatVec1: switch v := v.(type) { case float32: gl.Uniform1f(u.location, v) case []float32: gl.Uniform1fv(u.location, v) } case stFloatVec2: switch v := v.(type) { case math.Vec2: gl.Uniform2fv(u.location, []float32{v.X, v.Y}) case []float32: if len(v)%2 != 0 { panic(fmt.Errorf("Uniform '%s' of type vec2 should be an float32 array with a multiple of two length", u.name)) } gl.Uniform2fv(u.location, v) } case stFloatVec3: switch v := v.(type) { case math.Vec3: gl.Uniform3fv(u.location, []float32{v.X, v.Y, v.Z}) case []float32: if len(v)%3 != 0 { panic(fmt.Errorf("Uniform '%s' of type vec3 should be an float32 array with a multiple of three length", u.name)) } gl.Uniform3fv(u.location, v) } case stFloatVec4: switch v := v.(type) { case math.Vec4: gl.Uniform4fv(u.location, []float32{v.X, v.Y, v.Z, v.W}) case gxui.Color: gl.Uniform4fv(u.location, []float32{v.R, v.G, v.B, v.A}) case []float32: if len(v)%4 != 0 { panic(fmt.Errorf("Uniform '%s' of type vec4 should be an float32 array with a multiple of four length", u.name)) } gl.Uniform4fv(u.location, v) } case stSampler2d: tc := v.(*textureContext) gl.ActiveTexture(gl.Enum(gl.TEXTURE0 + u.textureUnit)) gl.BindTexture(gl.TEXTURE_2D, tc.texture) gl.Uniform1i(u.location, u.textureUnit) default: panic(fmt.Errorf("Uniform of unsupported type %s", u.ty)) } }
drivers/gl/shader_uniform.go
0.50293
0.406361
shader_uniform.go
starcoder
package parse // Code for assignment, a little intricate as there are many cases and many // validity checks. import ( "robpike.io/ivy/value" ) // Assignment is an implementation of Value that is created as the result of an assignment. // It can be type-asserted to discover whether the returned value was created by assignment, // such as is done in the interpreter to avoid printing the results of assignment expressions. type Assignment struct { value.Value } var scalarShape = []int{1} // The assignment shape vector for a scalar value. func assignment(context value.Context, b *binary) value.Value { // We know the left is a variableExpr or index expression. // Special handling as we must not evaluate the left - it is an l-value. // But we need to process the indexing, if it is an index expression. rhs := b.right.Eval(context).Inner() switch lhs := b.left.(type) { case variableExpr: context.Assign(lhs.name, rhs) return Assignment{Value: rhs} case *binary: if lhs.op == "[]" { return indexedAssignment(context, lhs, b.right, rhs) } } value.Errorf("cannot assign %s to %s", b.left.ProgString(), b.right.ProgString()) panic("not reached") } // indexedAssignment handles general assignment to indexed expressions on the LHS. // The LHS must be derived from a variable to make sure it is an l-value. func indexedAssignment(context value.Context, lhs *binary, rhsExpr value.Expr, rhs value.Value) value.Value { // We walk down the index chain evaluating indexes and // comparing them to the shape vector of the LHS. // Once we're there, we copy the rhs to the lhs, doing a slice copy. // rhsExpr is for diagnostics (only), as it gives a better error print. slice, shape := dataAndShape(true, lhs, lvalueOf(context, lhs.left)) indexes := indexesOf(context, lhs) origin := int(value.Int(context.Config().Origin())) offset := 0 var i int for i = range shape { if i >= len(indexes) { value.Errorf("rank error assigning %s to %s", rhs, lhs.ProgString()) } size := shapeProduct(shape[i+1:]) index := indexes[i] - origin if index < 0 || shape[i] <= index { value.Errorf("index of out of range in assignment") } // We're either going to skip this block, or we're at the // end of the indexes and we're going to assign it. if i < len(indexes)-1 { // Skip. offset += index * size continue } // Assign. rhsData, rhsShape := dataAndShape(false, rhsExpr, rhs) dataSize := shapeProduct(rhsShape) // Shapes must match. if !sameShape(shape[i+1:], rhsShape) { value.Errorf("data size/shape mismatch assigning %s to %s", rhs, lhs.ProgString()) } offset += index * size if dataSize == 1 { slice[offset] = rhsData[0] } else { copy(slice[offset:offset+size], rhsData) } return Assignment{Value: rhs} } value.Errorf("cannot assign to element of %s", lhs.left.ProgString()) panic("not reached") } func dataAndShape(mustBeLvalue bool, expr value.Expr, val value.Value) ([]value.Value, []int) { switch v := val.(type) { case value.Vector: return v, toInt([]value.Value{value.Int(len(v))}) case *value.Matrix: return v.Data(), v.Shape() default: if mustBeLvalue { return nil, nil } return []value.Value{val}, scalarShape } } func shapeProduct(shape []int) int { elemSize := 1 for _, v := range shape { elemSize *= v } return elemSize } // sameShape reports whether the two assignment shape vectors are equivalent. // The lhs in particular can be empty if we have exhausted the indexes, but that // just means we are assigning to a scalar element, and is OK. func sameShape(a, b []int) bool { if len(a) == 0 { a = scalarShape } if len(b) == 0 { b = scalarShape } if len(a) != len(b) { return false } for i, av := range a { if av != b[i] { return false } } return true } func toInt(v []value.Value) []int { res := make([]int, len(v)) for i, val := range v { res[i] = int(val.(value.Int)) } return res } // lvalueOf walks the index tree to find the variable that roots it. // It must evaluate to a non-scalar to be indexable. func lvalueOf(context value.Context, item value.Expr) value.Value { switch lhs := item.(type) { case variableExpr: lvalue := lhs.Eval(context) if lvalue.Rank() == 0 { break } return lvalue case *binary: if lhs.op == "[]" { return lvalueOf(context, lhs.left) } } value.Errorf("cannot index %s in assignment", item.ProgString()) panic("not reached") } func indexesOf(context value.Context, item value.Expr) []int { switch v := item.(type) { case *binary: if v.op == "[]" { if _, ok := v.left.(variableExpr); ok { return indexesOf(context, v.right) } return append(indexesOf(context, v.left), indexesOf(context, v.right)...) } default: v = v.Eval(context) if i, ok := v.(value.Int); ok { return []int{int(i)} } value.Errorf("cannot index by %s in assignment", item.ProgString()) } return nil }
parse/assign.go
0.662687
0.675042
assign.go
starcoder
package vec import ( "fmt" "math" ) // Vec2 is a 2D Vec2 type type Vec2 struct { X,Y float64 } // TypeError is a type alias for errors returned from the "type agnostic" operator methods exported by this package. type TypeError error // Add is a more type agnostic Add shorthand, that casts some compatible types to float64. Use specific versions whenever // possible. When a non-supported type is encountered, returns a specific error type alias TypeError. // Currently supports Vec2, *Vec2, ints and floats func (v Vec2) Add(i interface{}) (Vec2, TypeError) { switch o := i.(type) { case Vec2: return v.AddV(o), nil case *Vec2: return v.AddV(*o), nil case int: return v.AddS(float64(o)), nil case int32: return v.AddS(float64(o)), nil case int64: return v.AddS(float64(o)), nil case float32: return v.AddS(float64(o)), nil case float64: return v.AddS(float64(o)), nil default: return Vec2{}, fmt.Errorf("Incompatible type: %t\n", o) } } // AddV returns the component-wise addition of v and o. func (v Vec2) AddV(o Vec2) Vec2 { v.X += o.X v.Y += o.Y return v } // AddS adds scalar o component-wise to vec2 v in-place (mutates it). func (v Vec2) AddS(o float64) Vec2 { v.X += o v.Y += o return v } // Add is a more type agnostic Add shorthand, that casts some compatible types to float64. Use specific versions whenever // possible. When a non-supported type is encountered, returns a specific error type alias TypeError. // Currently supports Vec2, *Vec2, ints and floats func (v Vec2) Mul(i interface{}) (Vec2, TypeError) { switch o := i.(type) { case Vec2: return v.MulV(o), nil case *Vec2: return v.MulV(*o), nil case int: return v.MulS(float64(o)), nil case int32: return v.MulS(float64(o)), nil case int64: return v.MulS(float64(o)), nil case float32: return v.MulS(float64(o)), nil case float64: return v.MulS(o), nil default: return Vec2{}, fmt.Errorf("Incompatible type: %t\n", o) } } // MulV multiplies v by vec2 o func (v Vec2) MulV(o Vec2) Vec2 { v.X *= o.X v.Y *= o.Y return v } // MulS multiplies v by scalar o func (v Vec2) MulS(o float64) Vec2 { v.X *= o v.Y *= o return v } // Sub is a type agnostic substraction shorthand. Returns specific result and error type alias. Use typed versions when possible. func (v Vec2) Sub(i interface{}) (Vec2, TypeError) { switch o := i.(type) { case Vec2: return v.SubV(o), nil case int: return v.SubS(float64(o)), nil case float32: return v.SubS(float64(o)), nil default: return Vec2{}, fmt.Errorf("Incompatible type: %t\n", o) } } func (v Vec2) SubV(o Vec2) Vec2 { v.X -= o.X v.Y -= o.Y return v } func (v Vec2) SubS(o float64) Vec2 { v.X -= o v.Y -= o return v } func (v Vec2) Div(i interface{}) (Vec2, TypeError) { switch o := i.(type) { case Vec2: return v.DivV(o), nil case int: return v.DivS(float64(o)), nil case float32: return v.DivS(float64(o)), nil default: return Vec2{}, fmt.Errorf("Incompatible type: %t\n", o) } } // DivV divides v component-wise by vec2 o, returns result func (v Vec2) DivV(o Vec2) Vec2 { v.X /= o.X v.Y /= o.Y return v } // DivS divides v component-wise by scalar o, returns result func (v Vec2) DivS(o float64) Vec2 { v.X /= o v.Y /= o return v } // Project projects vector v to axis o func (v Vec2) Project(o Vec2) Vec2 { dot := v.Dot(o) v.X = (dot / (o.X*o.X + o.Y*o.Y)) * o.X v.Y = (dot / (o.X*o.X + o.Y*o.Y)) * o.Y return v } // Dot returns the dot product for v and o func (v Vec2) Dot(o Vec2) float64 { return v.X*o.X + v.Y*o.Y } // Cross returns the cross product for v and o func (v Vec2) Cross(o Vec2) float64 { return v.X*o.Y - v.Y*o.X } // CrossF returns the component-wise scalar cross-product of v func (v Vec2) CrossF(o float64) Vec2 { return Vec2{-v.Y * o, v.X * o} } // LengthSquared returns the squared length of v. Useful for distance checks etc. func (v Vec2) LengthSquared() float64 { return v.X*v.X + v.Y*v.Y } // Length returns the scalar magnitude of v. Use LengthSquared whenever possible - it's cheaper for distance checks etc. func (v Vec2) Length() float64 { sum := v.X*v.X + v.Y*v.Y if sum == 0.0 { return sum } return math.Sqrt(sum) } // Normalize normalizes v (scales it to unit-length 1) in-place (mutates it) func (v *Vec2) Normalize() { *v = v.Normalized() } // Normalized returns a normalized (unit length of 1) version of v func (v Vec2) Normalized() Vec2 { l := v.Length() if l == 0.0 { return v } return Scale(v, 1.0/l) } // Add adds to Vec2s together, returns the result func Add(v, o Vec2) Vec2 { return Vec2{v.X + o.X, v.Y + o.Y} } // Sub two vectors func Sub(v, o Vec2) Vec2 { return Vec2{v.X - o.X, v.Y - o.Y} } // Div divides v by o component-wise, returns result func Div(v, o Vec2) Vec2 { return Vec2{ X: v.X / o.X, Y: v.Y / o.Y, } } // Mul multiplies v by o component-wise, returns result func Mul(v, o Vec2) Vec2 { return Vec2{ X: v.X * o.X, Y: v.Y * o.Y, } } func (v Vec2) Scale(r float64) Vec2 { return Scale(v, r) } // Scale multiplies v by scalar r (component-wise) func Scale(v Vec2, r float64) Vec2 { return Vec2{v.X * r, v.Y * r} } // Equals is a simple component-wise equality check func Equals(v, o Vec2) bool { return v.X == o.X && v.Y == o.Y }
vec2.go
0.897812
0.555194
vec2.go
starcoder
package network import ( "fmt" "math" "errors" "github.com/elmware/goNEAT/neat/utils" ) // The connection descriptor for fast network type FastNetworkLink struct { // The index of source neuron SourceIndx int // The index of target neuron TargetIndx int // The weight of this link Weight float64 // The signal relayed by this link Signal float64 } // The module relay (control node) descriptor for fast network type FastControlNode struct { // The activation function for control node ActivationType utils.NodeActivationType // The indexes of the input nodes InputIndxs []int // The indexes of the output nodes OutputIndxs []int } // The fast modular network solver implementation to be used for big neural networks simulation. type FastModularNetworkSolver struct { // A network id Id int // Is a name of this network */ Name string // The current activation values per each neuron neuronSignals []float64 // This array is a parallel of neuronSignals and used to test network relaxation neuronSignalsBeingProcessed []float64 // The activation functions per neuron, must be in the same order as neuronSignals. Has nil entries for // neurons that are inputs or outputs of a module. activationFunctions []utils.NodeActivationType // The bias values associated with neurons biasList []float64 // The control nodes relaying between network modules modules []*FastControlNode // The connections connections []*FastNetworkLink // The number of input neurons inputNeuronCount int // The total number of sensors in the network (input + bias). This is also the index of the first output neuron in the neuron signals. sensorNeuronCount int // The number of output neurons outputNeuronCount int // The bias neuron count (usually one). This is also the index of the first input neuron in the neuron signals. biasNeuronCount int // The total number of neurons in network totalNeuronCount int // For recursive activation, marks whether we have finished this node yet activated []bool // For recursive activation, makes whether a node is currently being calculated (recurrent connections processing) inActivation []bool // For recursive activation, the previous activation values of recurrent connections (recurrent connections processing) lastActivation []float64 // The adjacent list to hold IDs of outgoing nodes for each network node adjacentList [][]int // The adjacent list to hold IDs of incoming nodes for each network node reverseAdjacentList [][]int // The adjacent matrix to hold connection weights between all connected nodes adjacentMatrix [][]float64 } // Creates new fast modular network solver func NewFastModularNetworkSolver(biasNeuronCount, inputNeuronCount, outputNeuronCount, totalNeuronCount int, activationFunctions []utils.NodeActivationType, connections []*FastNetworkLink, biasList []float64, modules []*FastControlNode) *FastModularNetworkSolver { fmm := FastModularNetworkSolver{ biasNeuronCount:biasNeuronCount, inputNeuronCount:inputNeuronCount, sensorNeuronCount:biasNeuronCount + inputNeuronCount, outputNeuronCount:outputNeuronCount, totalNeuronCount:totalNeuronCount, activationFunctions:activationFunctions, biasList:biasList, modules:modules, connections:connections, } // Allocate the arrays that store the states at different points in the neural network. // The neuron signals are initialised to 0 by default. Only bias nodes need setting to 1. fmm.neuronSignals = make([]float64, totalNeuronCount) fmm.neuronSignalsBeingProcessed = make([]float64, totalNeuronCount) for i := 0; i < biasNeuronCount; i++ { fmm.neuronSignals[i] = 1.0 // BIAS neuron signal } // Allocate activation arrays fmm.activated = make([]bool, totalNeuronCount) fmm.inActivation = make([]bool, totalNeuronCount) fmm.lastActivation = make([]float64, totalNeuronCount) // Build adjacent lists and matrix for fast access of incoming/outgoing nodes and connection weights fmm.adjacentList = make([][]int, totalNeuronCount) fmm.reverseAdjacentList = make([][]int, totalNeuronCount) fmm.adjacentMatrix = make([][]float64, totalNeuronCount) for i := 0; i < totalNeuronCount; i++ { fmm.adjacentList[i] = make([]int, 0) fmm.reverseAdjacentList[i] = make([]int, 0) fmm.adjacentMatrix[i] = make([]float64, totalNeuronCount) } for i := 0; i < len(connections); i++ { crs := connections[i].SourceIndx crt := connections[i].TargetIndx // Holds outgoing nodes fmm.adjacentList[crs] = append(fmm.adjacentList[crs], crt) // Holds incoming nodes fmm.reverseAdjacentList[crt] = append(fmm.reverseAdjacentList[crt], crs) // Holds link weight fmm.adjacentMatrix[crs][crt] = connections[i].Weight } return &fmm } // Propagates activation wave through all network nodes provided number of steps in forward direction. // Returns true if activation wave passed from all inputs to the outputs. func (fmm *FastModularNetworkSolver) ForwardSteps(steps int) (res bool, err error) { for i := 0; i < steps; i++ { if res, err = fmm.forwardStep(0); err != nil { return false, err } } return res, nil } // Propagates activation wave through all network nodes provided number of steps by recursion from output nodes // Returns true if activation wave passed from all inputs to the outputs. This method is preferred method // of network activation when number of forward steps can not be easy calculated and no network modules are set. func (fmm *FastModularNetworkSolver) RecursiveSteps() (res bool, err error) { if len(fmm.modules) > 0 { return false, errors.New("recursive activation can not be used for network with defined modules") } // Initialize boolean arrays and set the last activation signal for output/hidden neurons for i := 0; i < fmm.totalNeuronCount; i++ { // Set as activated if i is an input node, otherwise ensure it is unactivated (false) fmm.activated[i] = i < fmm.sensorNeuronCount fmm.inActivation[i] = false // set last activation for output/hidden neurons if i >= fmm.sensorNeuronCount { fmm.lastActivation[i] = fmm.neuronSignals[i] } } // Get each output node activation recursively for i := 0; i < fmm.outputNeuronCount; i++ { if res, err = fmm.recursiveActivateNode(fmm.sensorNeuronCount + i); err != nil { return false, err } } return true, nil } // Propagate activation wave by recursively looking for input signals graph for a given output neuron func (fmm *FastModularNetworkSolver) recursiveActivateNode(currentNode int) (res bool, err error) { // If we've reached an input node then return since the signal is already set if fmm.activated[currentNode] { fmm.inActivation[currentNode] = false return true, nil } // Mark that the node is currently being calculated fmm.inActivation[currentNode] = true // Set the pre-signal to 0 fmm.neuronSignalsBeingProcessed[currentNode] = 0 // Adjacency list in reverse holds incoming connections, go through each one and activate it for i := 0; i < len(fmm.reverseAdjacentList[currentNode]); i++ { crntAdjNode := fmm.reverseAdjacentList[currentNode][i] // If this node is currently being activated then we have reached a cycle, or recurrent connection. // Use the previous activation in this case if fmm.inActivation[crntAdjNode] { fmm.neuronSignalsBeingProcessed[currentNode] += fmm.lastActivation[crntAdjNode] * fmm.adjacentMatrix[crntAdjNode][currentNode] } else { // Otherwise proceed as normal // Recurse if this neuron has not been activated yet if !fmm.activated[crntAdjNode] { res, err = fmm.recursiveActivateNode(crntAdjNode) if err != nil { // recursive activation failed return false, err } } // Add it to the new activation fmm.neuronSignalsBeingProcessed[currentNode] += fmm.neuronSignals[crntAdjNode] * fmm.adjacentMatrix[crntAdjNode][currentNode] } } // Mark this neuron as completed fmm.activated[currentNode] = true // This is no longer being calculated (for cycle detection) fmm.inActivation[currentNode] = false // Set this signal after running it through the activation function if fmm.neuronSignals[currentNode], err = utils.NodeActivators.ActivateByType( fmm.neuronSignalsBeingProcessed[currentNode], nil, fmm.activationFunctions[currentNode]); err != nil { // failed to activate res = false } return res, err } // Attempts to relax network given amount of steps until giving up. The network considered relaxed when absolute // value of the change at any given point is less than maxAllowedSignalDelta during activation waves propagation. // If maxAllowedSignalDelta value is less than or equal to 0, the method will return true without checking for relaxation. func (fmm *FastModularNetworkSolver) Relax(maxSteps int, maxAllowedSignalDelta float64) (relaxed bool, err error) { for i := 0; i < maxSteps; i++ { if relaxed, err = fmm.forwardStep(maxAllowedSignalDelta); err != nil { return false, err } else if relaxed { break // no need to iterate any further, already reached desired accuracy } } return relaxed, nil } // Performs single forward step through the network and tests if network become relaxed. The network considered relaxed // when absolute value of the change at any given point is less than maxAllowedSignalDelta during activation waves propagation. func (fmm *FastModularNetworkSolver) forwardStep(maxAllowedSignalDelta float64) (isRelaxed bool, err error) { isRelaxed = true // Calculate output signal per each connection and add the signals to the target neurons for _, conn := range fmm.connections { fmm.neuronSignalsBeingProcessed[conn.TargetIndx] += fmm.neuronSignals[conn.SourceIndx] * conn.Weight } // Pass the signals through the single-valued activation functions for i := fmm.sensorNeuronCount; i < fmm.totalNeuronCount; i++ { signal := fmm.neuronSignalsBeingProcessed[i] if fmm.biasNeuronCount > 0 { // append BIAS value to the signal if appropriate signal += fmm.biasList[i] } if fmm.neuronSignalsBeingProcessed[i], err = utils.NodeActivators.ActivateByType( signal, nil, fmm.activationFunctions[i]); err != nil { return false, err } } // Pass the signals through each module (activation function with more than one input or output) for _, module := range fmm.modules { inputs := make([]float64, len(module.InputIndxs)) for i, in_index := range module.InputIndxs { inputs[i] = fmm.neuronSignalsBeingProcessed[in_index] } if outputs, err := utils.NodeActivators.ActivateModuleByType(inputs, nil, module.ActivationType); err == nil { // save outputs for i, out_index := range module.OutputIndxs { fmm.neuronSignalsBeingProcessed[out_index] = outputs[i] } } else { return false, err } } // Move all the neuron signals we changed while processing this network activation into storage. if maxAllowedSignalDelta <= 0 { // iterate through output and hidden neurons and collect activations for i := fmm.sensorNeuronCount; i < fmm.totalNeuronCount; i++ { fmm.neuronSignals[i] = fmm.neuronSignalsBeingProcessed[i] fmm.neuronSignalsBeingProcessed[i] = 0 } } else { for i := fmm.sensorNeuronCount; i < fmm.totalNeuronCount; i++ { // First check whether any location in the network has changed by more than a small amount. isRelaxed = isRelaxed && !(math.Abs(fmm.neuronSignals[i] - fmm.neuronSignalsBeingProcessed[i]) > maxAllowedSignalDelta) fmm.neuronSignals[i] = fmm.neuronSignalsBeingProcessed[i] fmm.neuronSignalsBeingProcessed[i] = 0 } } return isRelaxed, err } // Flushes network state by removing all current activations. Returns true if network flushed successfully or // false in case of error. func (fmm *FastModularNetworkSolver) Flush() (bool, error) { for i := fmm.biasNeuronCount; i < fmm.totalNeuronCount; i++ { fmm.neuronSignals[i] = 0.0 } return true, nil } // Set sensors values to the input nodes of the network func (fmm *FastModularNetworkSolver) LoadSensors(inputs []float64) error { if len(inputs) == fmm.inputNeuronCount { // only inputs should be provided for i := 0; i < fmm.inputNeuronCount; i++ { fmm.neuronSignals[fmm.biasNeuronCount + i] = inputs[i] } } else { return NetErrUnsupportedSensorsArraySize } return nil } // Read output values from the output nodes of the network func (fmm *FastModularNetworkSolver) ReadOutputs() []float64 { return fmm.neuronSignals[fmm.sensorNeuronCount:fmm.sensorNeuronCount + fmm.outputNeuronCount] } // Returns the total number of neural units in the network func (fmm *FastModularNetworkSolver) NodeCount() int { return fmm.totalNeuronCount + len(fmm.modules) } // Returns the total number of links between nodes in the network func (fmm *FastModularNetworkSolver) LinkCount() int { // count all connections num_links := len(fmm.connections) // count all bias links if any if fmm.biasNeuronCount > 0 { for _, b := range fmm.biasList { if b != 0 { num_links++ } } } // count all modules links if len(fmm.modules) != 0 { for _, module := range fmm.modules { num_links += len(module.InputIndxs) + len(module.OutputIndxs) } } return num_links } // Stringer func (fmm *FastModularNetworkSolver) String() string { str := fmt.Sprintf("FastModularNetwork, id: %d, name: [%s], neurons: %d,\n\tinputs: %d,\tbias: %d,\toutputs:%d,\t hidden: %d", fmm.Id, fmm.Name, fmm.totalNeuronCount, fmm.inputNeuronCount, fmm.biasNeuronCount, fmm.outputNeuronCount, fmm.totalNeuronCount - fmm.sensorNeuronCount - fmm.outputNeuronCount) return str }
neat/network/fast_network.go
0.682256
0.560674
fast_network.go
starcoder
package crosslink import ( "math" "unsafe" ) // CLPosImp is a position x-z interface type CLPosImp interface { x() CLPosValType z() CLPosValType } // CLNodeImp is a general node interface type CLNodeImp interface { CLPosImp isTriggerNode() bool isEntity() bool order() uint8 // here otherNode CLNodeImp should be a pointer to some struct, but not value of struct crossedX(otherNode CLNodeImp, positiveCross bool, otherOldX CLPosValType, otherOldZ CLPosValType) crossedZ(otherNode CLNodeImp, positiveCross bool, otherOldX CLPosValType, otherOldZ CLPosValType) moveToPrevX() moveToNextX() moveToPrevZ() moveToNextZ() clNodeType() CLNodeValType nodeID() unsafe.Pointer prevX() CLNodeImp prevZ() CLNodeImp nextX() CLNodeImp nextZ() CLNodeImp isTail() bool getCLNodePtr() *CLNode getEntityID() EntityIDValType } // CLNode is a base Node struct for the cross linked list // it implements interface CLNodeImp type CLNode struct { pPrevX *CLNode pNextX *CLNode pPrevZ *CLNode pNextZ *CLNode nodeType CLNodeValType } // implement interface CLNodeImp: begin func getParentInst(ptr *CLNode) CLNodeImp { if ptr == nil { return nil } if ptr.nodeType == CLNODE_ENTITY { return (*EntityListNode)(unsafe.Pointer((uintptr)(unsafe.Pointer(ptr)) - g_offsetEntityListNode)) } else if ptr.nodeType == CLNODE_TRIGGER { return (*RangeTriggerNode)(unsafe.Pointer((uintptr)(unsafe.Pointer(ptr)) - g_offsetEntityListNode)) } return nil } func (thisNode *CLNode) prevX() CLNodeImp { return getParentInst(thisNode.pPrevX) } func (thisNode *CLNode) prevZ() CLNodeImp { return getParentInst(thisNode.pPrevZ) } func (thisNode *CLNode) nextX() CLNodeImp { return getParentInst(thisNode.pNextX) } func (thisNode *CLNode) nextZ() CLNodeImp { return getParentInst(thisNode.pNextZ) } func (thisNode *CLNode) clNodeType() CLNodeValType { return thisNode.nodeType } func (thisNode *CLNode) isTriggerNode() bool { return thisNode.nodeType == CLNODE_TRIGGER } func (thisNode *CLNode) isEntity() bool { return thisNode.nodeType == CLNODE_ENTITY } func (thisNode *CLNode) order() uint8 { return 0 } func (thisNode *CLNode) crossedX(otherNode CLNodeImp, positiveCross bool, otherOldX CLPosValType, otherOldZ CLPosValType) { panic("override this func") } func (thisNode *CLNode) crossedZ(otherNode CLNodeImp, positiveCross bool, otherOldX CLPosValType, otherOldZ CLPosValType) { panic("override this func") } func (thisNode *CLNode) moveToPrevX() { if thisNode.pNextX != nil { thisNode.pNextX.pPrevX = thisNode.pPrevX } thisNode.pPrevX.pNextX = thisNode.pNextX thisNode.pNextX = thisNode.pPrevX thisNode.pPrevX = thisNode.pPrevX.pPrevX if thisNode.pPrevX != nil { thisNode.pPrevX.pNextX = thisNode } thisNode.pNextX.pPrevX = thisNode } func (thisNode *CLNode) moveToNextX() { if thisNode.pPrevX != nil { thisNode.pPrevX.pNextX = thisNode.pNextX } thisNode.pNextX.pPrevX = thisNode.pPrevX thisNode.pPrevX = thisNode.pNextX thisNode.pNextX = thisNode.pNextX.pNextX if thisNode.pNextX != nil { thisNode.pNextX.pPrevX = thisNode } thisNode.pPrevX.pNextX = thisNode } func (thisNode *CLNode) moveToPrevZ() { if thisNode.pNextZ != nil { thisNode.pNextZ.pPrevZ = thisNode.pPrevZ } thisNode.pPrevZ.pNextZ = thisNode.pNextZ thisNode.pNextZ = thisNode.pPrevZ thisNode.pPrevZ = thisNode.pPrevZ.pPrevZ if thisNode.pPrevZ != nil { thisNode.pPrevZ.pNextZ = thisNode } thisNode.pNextZ.pPrevZ = thisNode } func (thisNode *CLNode) moveToNextZ() { if thisNode.pPrevZ != nil { thisNode.pPrevZ.pNextZ = thisNode.pNextZ } thisNode.pNextZ.pPrevZ = thisNode.pPrevZ thisNode.pPrevZ = thisNode.pNextZ thisNode.pNextZ = thisNode.pNextZ.pNextZ if thisNode.pNextZ != nil { thisNode.pNextZ.pPrevZ = thisNode } thisNode.pPrevZ.pNextZ = thisNode } func (thisNode *CLNode) nodeID() unsafe.Pointer { return unsafe.Pointer(thisNode) } func (thisNode *CLNode) isTail() bool { return false } func (thisNode *CLNode) getCLNodePtr() *CLNode { return thisNode } // implement interface CLNodeImp: end // removeFromRangeList remove this node from linked list, process pointers only func (thisNode *CLNode) removeFromRangeList() { if thisNode.pPrevX != nil { thisNode.pPrevX.pNextX = thisNode.pNextX } if thisNode.pNextX != nil { thisNode.pNextX.pPrevX = thisNode.pPrevX } if thisNode.pPrevZ != nil { thisNode.pPrevZ.pNextZ = thisNode.pNextZ } if thisNode.pNextZ != nil { thisNode.pNextZ.pPrevZ = thisNode.pPrevZ } thisNode.pPrevX = nil thisNode.pNextX = nil thisNode.pPrevZ = nil thisNode.pNextZ = nil } func (thisNode *CLNode) insertBeforeX(newNode *CLNode) { if thisNode.pPrevX != nil { thisNode.pPrevX.pNextX = newNode } newNode.pPrevX = thisNode.pPrevX thisNode.pPrevX = newNode newNode.pNextX = thisNode } func (thisNode *CLNode) insertBeforeZ(newNode *CLNode) { if thisNode.pPrevZ != nil { thisNode.pPrevZ.pNextZ = newNode } newNode.pPrevZ = thisNode.pPrevZ thisNode.pPrevZ = newNode newNode.pNextZ = thisNode } // CLNodeTail is a terminator type CLNodeTail struct { CLNode } func newCLNodeTail() *CLNodeTail { tail := new(CLNodeTail) tail.nodeType = CLNODE_TAIL return tail } func (thisNode *CLNodeTail) isTail() bool { return true } func (thisNode *CLNodeTail) x() CLPosValType { return math.MaxFloat32 } func (thisNode *CLNodeTail) z() CLPosValType { return math.MaxFloat32 } // shuffleX make this node in right position of X linked list func shuffleX(thisNode CLNodeImp, oldX CLPosValType, oldZ CLPosValType) { thisPos := thisNode.x() for { prevNode := thisNode.prevX() if prevNode == nil { break } prevPos := prevNode.x() if thisPos < prevPos || (thisPos == prevPos && thisNode.order() < prevNode.order()) { if thisNode.isTriggerNode() && !prevNode.isTriggerNode() { thisNode.crossedX(prevNode, true, prevPos, prevNode.z()) } else if !thisNode.isTriggerNode() && prevNode.isTriggerNode() { prevNode.crossedX(thisNode, false, oldX, oldZ) } thisNode.moveToPrevX() } else { break } } for { nextNode := thisNode.nextX() if nextNode == nil { break } nextPos := nextNode.x() if thisPos > nextPos || (thisPos == nextPos && thisNode.order() < nextNode.order()) { if thisNode.isTriggerNode() && !nextNode.isTriggerNode() { thisNode.crossedX(nextNode, false, nextPos, nextNode.z()) } else if !thisNode.isTriggerNode() && nextNode.isTriggerNode() { nextNode.crossedX(thisNode, true, oldX, oldZ) } thisNode.moveToNextX() } else { break } } } // shuffleZ make this node in right position of Z linked list func shuffleZ(thisNode CLNodeImp, oldX CLPosValType, oldZ CLPosValType) { thisPos := thisNode.z() for { prevNode := thisNode.prevZ() if prevNode == nil { break } prevPos := prevNode.z() if thisPos < prevPos || (thisPos == prevPos && thisNode.order() < prevNode.order()) { if thisNode.isTriggerNode() && !prevNode.isTriggerNode() { thisNode.crossedZ(prevNode, true, prevNode.x(), prevPos) } else if !thisNode.isTriggerNode() && prevNode.isTriggerNode() { prevNode.crossedZ(thisNode, false, oldX, oldZ) } thisNode.moveToPrevZ() } else { break } } for { nextNode := thisNode.nextZ() if nextNode == nil { break } nextPos := nextNode.z() if thisPos > nextPos || (thisPos == nextPos && thisNode.order() < nextNode.order()) { if thisNode.isTriggerNode() && !nextNode.isTriggerNode() { thisNode.crossedZ(nextNode, false, nextNode.x(), nextNode.z()) } else if !thisNode.isTriggerNode() && nextNode.isTriggerNode() { nextNode.crossedZ(thisNode, true, oldX, oldZ) } thisNode.moveToNextZ() } else { break } } } // shuffleXThenZ make this node in right position of cross linked list func shuffleXThenZ(thisNode CLNodeImp, oldX CLPosValType, oldZ CLPosValType) { shuffleX(thisNode, oldX, oldZ) shuffleZ(thisNode, oldX, oldZ) }
aoi/aoi_cross_link/cross_list_node.go
0.58676
0.476945
cross_list_node.go
starcoder
package nbs import ( "bytes" "context" "crypto/sha512" "encoding/base32" "encoding/binary" "hash/crc32" "io" "sync" "github.com/dolthub/dolt/go/store/atomicerr" "github.com/dolthub/dolt/go/store/chunks" "github.com/dolthub/dolt/go/store/hash" ) /* An NBS Table stores N byte slices ("chunks") which are addressed by a 20-byte hash of their contents. The footer encodes N as well as the total bytes consumed by all contained chunks. An Index maps each address to the position of its corresponding chunk. Addresses are logically sorted within the Index, but the corresponding chunks need not be. Table: +----------------+----------------+-----+----------------+-------+--------+ | Chunk Record 0 | Chunk Record 1 | ... | Chunk Record N | Index | Footer | +----------------+----------------+-----+----------------+-------+--------+ Chunk Record: +---------------------------+----------------+ | (Chunk Length) Chunk Data | (Uint32) CRC32 | +---------------------------+----------------+ Index: +------------+---------+----------+ | Prefix Map | Lengths | Suffixes | +------------+---------+----------+ Prefix Map: +--------------+--------------+-----+----------------+ | Prefix Tuple | Prefix Tuple | ... | Prefix Tuple N | +--------------+--------------+-----+----------------+ -The Prefix Map contains N Prefix Tuples. -Each Prefix Tuple corresponds to a unique Chunk Record in the Table. -The Prefix Tuples are sorted in increasing lexicographic order within the Prefix Map. -NB: THE SAME PREFIX MAY APPEAR MULTIPLE TIMES, as distinct Hashes (referring to distinct Chunks) may share the same Prefix. Prefix Tuple: +-----------------+------------------+ | (8) Hash Prefix | (Uint32) Ordinal | +-----------------+------------------+ -First 8 bytes of a Chunk's Hash -Ordinal is the 0-based ordinal position of the associated record within the sequence of chunk records, the associated Length within Lengths, and the associated Hash Suffix within Suffixes. Lengths: +-----------------+-----------------+-----+-------------------+ | (Uint32) Length | (Uint32) Length | ... | (Uint32) Length N | +-----------------+-----------------+-----+-------------------+ - Each Length is the length of a Chunk Record in this Table. - Length M must correspond to Chunk Record M for 0 <= M <= N Suffixes: +------------------+------------------+-----+--------------------+ | (12) Hash Suffix | (12) Hash Suffix | ... | (12) Hash Suffix N | +------------------+------------------+-----+--------------------+ - Each Hash Suffix is the last 12 bytes of a Chunk in this Table. - Hash Suffix M must correspond to Chunk Record M for 0 <= M <= N Footer: +----------------------+----------------------------------------+------------------+ | (Uint32) Chunk Count | (Uint64) Total Uncompressed Chunk Data | (8) Magic Number | +----------------------+----------------------------------------+------------------+ -Total Uncompressed Chunk Data is the sum of the uncompressed byte lengths of all contained chunk byte slices. -Magic Number is the first 8 bytes of the SHA256 hash of "https://github.com/attic-labs/nbs". NOTE: Unsigned integer quanities, hashes and hash suffix are all encoded big-endian Looking up Chunks in an NBS Table There are two phases to loading chunk data for a given Hash from an NBS Table: Checking for the chunk's presence, and fetching the chunk's bytes. When performing a has-check, only the first phase is necessary. Phase one: Chunk presence - Slice off the first 8 bytes of your Hash to create a Prefix - Since the Prefix Tuples in the Prefix Map are in lexicographic order, binary search the Prefix Map for the desired Prefix. - For all Prefix Tuples with a matching Prefix: - Load the Ordinal - Use the Ordinal to index into Suffixes - Check the Suffix of your Hash against the loaded Suffix - If they match, your chunk is in this Table in the Chunk Record indicated by Ordinal - If they don't match, continue to the next matching Prefix Tuple - If not found, your chunk is not in this Table. Phase two: Loading Chunk data - Take the Ordinal discovered in Phase one - Calculate the Offset of your desired Chunk Record: Sum(Lengths[0]...Lengths[Ordinal-1]) - Load Lengths[Ordinal] bytes from Table[Offset] - Check the first 4 bytes of the loaded data against the last 4 bytes of your desired Hash. They should match, and the rest of the data is your Chunk data. */ const ( addrSize = 20 addrPrefixSize = 8 addrSuffixSize = addrSize - addrPrefixSize uint64Size = 8 uint32Size = 4 ordinalSize = uint32Size lengthSize = uint32Size magicNumber = "\xff\xb5\xd8\xc2\x24\x63\xee\x50" magicNumberSize = 8 //len(magicNumber) footerSize = uint32Size + uint64Size + magicNumberSize prefixTupleSize = addrPrefixSize + ordinalSize checksumSize = uint32Size maxChunkSize = 0xffffffff // Snappy won't compress slices bigger than this ) var crcTable = crc32.MakeTable(crc32.Castagnoli) func crc(b []byte) uint32 { return crc32.Update(0, crcTable, b) } func computeAddrDefault(data []byte) addr { r := sha512.Sum512(data) h := addr{} copy(h[:], r[:addrSize]) return h } var computeAddr = computeAddrDefault type addr [addrSize]byte var encoding = base32.NewEncoding("0123456789abcdefghijklmnopqrstuv") func (a addr) String() string { return encoding.EncodeToString(a[:]) } func (a addr) Prefix() uint64 { return binary.BigEndian.Uint64(a[:]) } func (a addr) Checksum() uint32 { return binary.BigEndian.Uint32(a[addrSize-checksumSize:]) } func parseAddr(str string) (addr, error) { var h addr _, err := encoding.Decode(h[:], []byte(str)) return h, err } func ValidateAddr(s string) bool { _, err := encoding.DecodeString(s) return err == nil } type addrSlice []addr func (hs addrSlice) Len() int { return len(hs) } func (hs addrSlice) Less(i, j int) bool { return bytes.Compare(hs[i][:], hs[j][:]) < 0 } func (hs addrSlice) Swap(i, j int) { hs[i], hs[j] = hs[j], hs[i] } type hasRecord struct { a *addr prefix uint64 order int has bool } type hasRecordByPrefix []hasRecord func (hs hasRecordByPrefix) Len() int { return len(hs) } func (hs hasRecordByPrefix) Less(i, j int) bool { return hs[i].prefix < hs[j].prefix } func (hs hasRecordByPrefix) Swap(i, j int) { hs[i], hs[j] = hs[j], hs[i] } type hasRecordByOrder []hasRecord func (hs hasRecordByOrder) Len() int { return len(hs) } func (hs hasRecordByOrder) Less(i, j int) bool { return hs[i].order < hs[j].order } func (hs hasRecordByOrder) Swap(i, j int) { hs[i], hs[j] = hs[j], hs[i] } type getRecord struct { a *addr prefix uint64 found bool } type getRecordByPrefix []getRecord func (hs getRecordByPrefix) Len() int { return len(hs) } func (hs getRecordByPrefix) Less(i, j int) bool { return hs[i].prefix < hs[j].prefix } func (hs getRecordByPrefix) Swap(i, j int) { hs[i], hs[j] = hs[j], hs[i] } type extractRecord struct { a addr data []byte err error } type chunkReader interface { has(h addr) (bool, error) hasMany(addrs []hasRecord) (bool, error) get(ctx context.Context, h addr, stats *Stats) ([]byte, error) getMany(ctx context.Context, reqs []getRecord, foundChunks chan<- *chunks.Chunk, wg *sync.WaitGroup, ae *atomicerr.AtomicError, stats *Stats) bool getManyCompressed(ctx context.Context, reqs []getRecord, foundCmpChunks chan<- CompressedChunk, wg *sync.WaitGroup, ae *atomicerr.AtomicError, stats *Stats) bool extract(ctx context.Context, chunks chan<- extractRecord) error count() (uint32, error) uncompressedLen() (uint64, error) // Close releases resources retained by the |chunkReader|. Close() error } type chunkReadPlanner interface { findOffsets(reqs []getRecord) (ors offsetRecSlice, remaining bool) getManyAtOffsets( ctx context.Context, reqs []getRecord, offsetRecords offsetRecSlice, foundChunks chan<- *chunks.Chunk, wg *sync.WaitGroup, ae *atomicerr.AtomicError, stats *Stats, ) getManyCompressedAtOffsets( ctx context.Context, reqs []getRecord, offsetRecords offsetRecSlice, foundCmpChunks chan<- CompressedChunk, wg *sync.WaitGroup, ae *atomicerr.AtomicError, stats *Stats, ) } type chunkSource interface { chunkReader hash() (addr, error) calcReads(reqs []getRecord, blockSize uint64) (reads int, remaining bool, err error) // opens a Reader to the first byte of the chunkData segment of this table. reader(context.Context) (io.Reader, error) index() (tableIndex, error) // Clone returns a |chunkSource| with the same contents as the // original, but with independent |Close| behavior. A |chunkSource| // cannot be |Close|d more than once, so if a |chunkSource| is being // retained in two objects with independent life-cycle, it should be // |Clone|d first. Clone() chunkSource } type chunkSources []chunkSource // TableFile is an interface for working with an existing table file type TableFile interface { // FileID gets the id of the file FileID() string // NumChunks returns the number of chunks in a table file NumChunks() int // Open returns an io.ReadCloser which can be used to read the bytes of a table file. Open(ctx context.Context) (io.ReadCloser, error) } // Describes what is possible to do with TableFiles in a TableFileStore. type TableFileStoreOps struct { // True is the TableFileStore supports reading table files. CanRead bool // True is the TableFileStore supports writing table files. CanWrite bool // True is the TableFileStore supports pruning unused table files. CanPrune bool // True is the TableFileStore supports garbage collecting chunks. CanGC bool } // TableFileStore is an interface for interacting with table files directly type TableFileStore interface { // Sources retrieves the current root hash, and a list of all the table files. Sources(ctx context.Context) (hash.Hash, []TableFile, error) // Size returns the total size, in bytes, of the table files in this Store. Size(ctx context.Context) (uint64, error) // WriteTableFile will read a table file from the provided reader and write it to the TableFileStore. WriteTableFile(ctx context.Context, fileId string, numChunks int, rd io.Reader, contentLength uint64, contentHash []byte) error // PruneTableFiles deletes old table files that are no longer referenced in the manifest. PruneTableFiles(ctx context.Context) error // SetRootChunk changes the root chunk hash from the previous value to the new root. SetRootChunk(ctx context.Context, root, previous hash.Hash) error // SupportedOperations returns a description of the support TableFile operations. Some stores only support reading table files, not writing. SupportedOperations() TableFileStoreOps }
go/store/nbs/table.go
0.674694
0.403479
table.go
starcoder
package types import ( "encoding/json" "math/big" "<KEY>" "<KEY>" cbor "<KEY>" "gx/ipfs/QmdBzoMxsBpojBfN1cv5GnKtB7sfYBMoLH7p9qSyEVYXcu/refmt/obj/atlas" ) // NOTE -- All *BytesAmount methods must call ensureBytesAmounts with refs to every user-supplied value before use. func init() { cbor.RegisterCborType(bytesAmountAtlasEntry) ZeroBytes = NewBytesAmount(0) } // ZeroBytes represents a BytesAmount of 0 var ZeroBytes *BytesAmount // ensureBytesAmounts takes a variable number of refs -- variables holding *BytesAmount -- and sets their values // to ZeroBytes (the zero value for the type) if their values are nil. func ensureBytesAmounts(refs ...**BytesAmount) { for _, ref := range refs { if *ref == nil { *ref = ZeroBytes } } } var bytesAmountAtlasEntry = atlas.BuildEntry(BytesAmount{}).Transform(). TransformMarshal(atlas.MakeMarshalTransformFunc( func(i BytesAmount) ([]byte, error) { return i.Bytes(), nil })). TransformUnmarshal(atlas.MakeUnmarshalTransformFunc( func(x []byte) (BytesAmount, error) { return *NewBytesAmountFromBytes(x), nil })). Complete() // UnmarshalJSON converts a byte array to a BytesAmount. func (z *BytesAmount) UnmarshalJSON(b []byte) error { var s string if err := json.Unmarshal(b, &s); err != nil { return err } bytes, ok := NewBytesAmountFromString(s, 10) if !ok { return errors.New("Cannot convert string to bytes amount") } *z = *bytes return nil } // MarshalJSON converts a BytesAmount to a byte array and returns it. func (z BytesAmount) MarshalJSON() ([]byte, error) { return json.Marshal(z.val.String()) } // An BytesAmount represents a signed multi-precision integer. // The zero value for a BytesAmount represents the value 0. type BytesAmount struct{ val *big.Int } // NewBytesAmount allocates and returns a new BytesAmount set to x. func NewBytesAmount(x uint64) *BytesAmount { return &BytesAmount{val: big.NewInt(0).SetUint64(x)} } // NewBytesAmountFromBytes allocates and returns a new BytesAmount set // to the value of buf as the bytes of a big-endian unsigned integer. func NewBytesAmountFromBytes(buf []byte) *BytesAmount { ba := NewBytesAmount(0) ba.val = leb128.ToBigInt(buf) return ba } // NewBytesAmountFromString allocates a new BytesAmount set to the value of s, // interpreted in the given base, and returns it and a boolean indicating success. func NewBytesAmountFromString(s string, base int) (*BytesAmount, bool) { ba := NewBytesAmount(0) val, ok := ba.val.SetString(s, base) ba.val = val // overkill return ba, ok } // Add sets z to the sum x+y and returns z. func (z *BytesAmount) Add(y *BytesAmount) *BytesAmount { ensureBytesAmounts(&z, &y) newVal := big.NewInt(0) newVal.Add(z.val, y.val) newZ := BytesAmount{val: newVal} return &newZ } // Sub sets z to the difference x-y and returns z. func (z *BytesAmount) Sub(y *BytesAmount) *BytesAmount { ensureBytesAmounts(&z, &y) newVal := big.NewInt(0) newVal.Sub(z.val, y.val) newZ := BytesAmount{val: newVal} return &newZ } // Mul sets z to x*y and returns z. func (z *BytesAmount) Mul(y *BytesAmount) *BytesAmount { ensureBytesAmounts(&z, &y) newVal := big.NewInt(0) newVal.Mul(z.val, y.val) newZ := BytesAmount{val: newVal} return &newZ } // Equal returns true if z = y func (z *BytesAmount) Equal(y *BytesAmount) bool { ensureBytesAmounts(&z, &y) return z.val.Cmp(y.val) == 0 } // LessThan returns true if z < y func (z *BytesAmount) LessThan(y *BytesAmount) bool { ensureBytesAmounts(&z, &y) return z.val.Cmp(y.val) < 0 } // GreaterThan returns true if z > y func (z *BytesAmount) GreaterThan(y *BytesAmount) bool { ensureBytesAmounts(&z, &y) return z.val.Cmp(y.val) > 0 } // LessEqual returns true if z <= y func (z *BytesAmount) LessEqual(y *BytesAmount) bool { ensureBytesAmounts(&z, &y) return z.val.Cmp(y.val) <= 0 } // GreaterEqual returns true if z >= y func (z *BytesAmount) GreaterEqual(y *BytesAmount) bool { ensureBytesAmounts(&z, &y) return z.val.Cmp(y.val) >= 0 } // IsPositive returns true if z is greater than zero. func (z *BytesAmount) IsPositive() bool { ensureBytesAmounts(&z) return z.GreaterThan(ZeroBytes) } // IsNegative returns true if z is less than zero. func (z *BytesAmount) IsNegative() bool { ensureBytesAmounts(&z) return z.LessThan(ZeroBytes) } // IsZero returns true if z equals zero. func (z *BytesAmount) IsZero() bool { ensureBytesAmounts(&z) return z.Equal(ZeroBytes) } // Bytes returns the absolute value of x as a big-endian byte slice. func (z *BytesAmount) Bytes() []byte { ensureBytesAmounts(&z) return leb128.FromBigInt(z.val) } func (z *BytesAmount) String() string { ensureBytesAmounts(&z) return z.val.String() } // Uint64 returns the uint64 representation of x. If x cannot be represented in a uint64, the result is undefined. func (z *BytesAmount) Uint64() uint64 { return z.val.Uint64() }
types/bytes_amount.go
0.776962
0.443841
bytes_amount.go
starcoder
package gript import ( "errors" "fmt" "reflect" "regexp" "strings" ) type intExpression int func (e intExpression) Eval(c Context) (interface{}, error) { return int(e), nil } type floatExpression float64 func (e floatExpression) Eval(c Context) (interface{}, error) { return float64(e), nil } type stringExpression string func (e stringExpression) Eval(c Context) (interface{}, error) { return string(e), nil } type identExpression string func (e identExpression) Eval(c Context) (interface{}, error) { switch e { case "true": return true, nil case "false": return false, nil case "nil": return nil, nil } r, found := c.Value(string(e)) if !found { return nil, fmt.Errorf("undefined variable '%s'", e) } return r, nil } type binaryExpression struct { operator string left Expression right Expression } func or(l, r interface{}) (bool, error) { vl, ok := l.(bool) if !ok { return false, errors.New("boolean expected in OR expression") } vr, ok := r.(bool) if !ok { return false, errors.New("boolean expected in OR expression") } return vl || vr, nil } func and(l, r interface{}) (bool, error) { vl, ok := l.(bool) if !ok { return false, errors.New("boolean expected in AND expression") } vr, ok := r.(bool) if !ok { return false, errors.New("boolean expected in AND expression") } return vl && vr, nil } func less(l, r interface{}) (bool, error) { switch vl := l.(type) { case int: if vr, ok := r.(int); ok { return vl < vr, nil } case float64: if vr, ok := r.(float64); ok { return vl < vr, nil } case string: if vr, ok := r.(string); ok { return vl < vr, nil } } return false, errors.New("incompatible types in comparison") } func sum(l, r interface{}) (interface{}, error) { switch vl := l.(type) { case int: if vr, ok := r.(int); ok { return vl + vr, nil } case float64: if vr, ok := r.(float64); ok { return vl + vr, nil } case string: if vr, ok := r.(string); ok { return vl + vr, nil } } return nil, errors.New("incompatible types in sum") } func difference(l, r interface{}) (interface{}, error) { switch vl := l.(type) { case int: if vr, ok := r.(int); ok { return vl - vr, nil } case float64: if vr, ok := r.(float64); ok { return vl - vr, nil } } return nil, errors.New("incompatible types in difference") } func product(l, r interface{}) (interface{}, error) { switch vl := l.(type) { case int: if vr, ok := r.(int); ok { return vl * vr, nil } case float64: if vr, ok := r.(float64); ok { return vl * vr, nil } } return nil, errors.New("incompatible types in product") } func quotient(l, r interface{}) (interface{}, error) { switch vl := l.(type) { case int: if vr, ok := r.(int); ok { return vl / vr, nil } case float64: if vr, ok := r.(float64); ok { return vl / vr, nil } } return nil, errors.New("incompatible types in quotient") } func modulo(l, r interface{}) (interface{}, error) { switch vl := l.(type) { case int: if vr, ok := r.(int); ok { return vl % vr, nil } } return nil, errors.New("incompatible types in modulo") } func in(l, r interface{}) (interface{}, error) { rValue := reflect.ValueOf(r) lValue := reflect.ValueOf(l) switch rValue.Kind() { case reflect.Array, reflect.Slice: if !lValue.Type().AssignableTo(rValue.Type().Elem()) { return nil, errors.New("invalid type in operator in") } for i := 0; i < rValue.Len(); i++ { if rValue.Index(i).Interface() == lValue.Interface() { return true, nil } } return false, nil case reflect.Map: if !lValue.Type().AssignableTo(rValue.Type().Key()) { return nil, errors.New("invalid key type in operator in") } return rValue.MapIndex(lValue).IsValid(), nil case reflect.Struct: found := rValue.FieldByNameFunc(func(name string) bool { return strings.ToLower(name) == strings.ToLower(lValue.String()) }) return found.IsValid(), nil } return nil, errors.New("unsupported types in operator in") } func match(l, r interface{}) (interface{}, error) { vl, okl := l.(string) vr, okr := r.(string) if okl && okr { return regexp.MatchString(vr, vl) } return nil, errors.New("unsupported types in operator match") } func (e binaryExpression) Eval(c Context) (interface{}, error) { l, err := e.left.Eval(c) if err != nil { return nil, err } //Fast exit: in some cases, no need to compute right part of the expression switch e.operator { case "&&": vl, ok := l.(bool) if ok && !vl { return false, nil } case "||": vl, ok := l.(bool) if ok && vl { return true, nil } } r, err := e.right.Eval(c) if err != nil { return nil, err } switch e.operator { case "==": return l == r, nil case "!=": return l != r, nil case ">": return less(r, l) case ">=": if l == r { return true, nil } return less(r, l) case "<": return less(l, r) case "<=": if l == r { return true, nil } return less(l, r) case "||": return or(l, r) case "&&": return and(l, r) case "+": return sum(l, r) case "-": return difference(l, r) case "*": return product(l, r) case "/": return quotient(l, r) case "%": return modulo(l, r) case "in": return in(l, r) case "match": return match(l, r) } return nil, fmt.Errorf("Unsupported operator '%s'", e.operator) }
expression.go
0.598782
0.433262
expression.go
starcoder
package iso20022 // Net position of a segregated holding, in a single security, within the overall position held in a securities account at a specified place of safekeeping. type AggregateBalancePerSafekeepingPlace30 struct { // Place where the securities are safe-kept, physically or notionally. This place can be, for example, a local custodian, a Central Securities Depository (CSD) or an International Central Securities Depository (ICSD). SafekeepingPlace *SafeKeepingPlace2 `xml:"SfkpgPlc"` // Market(s) on which the security is listed. PlaceOfListing *MarketIdentification4Choice `xml:"PlcOfListg,omitempty"` // Choice between formats for the entity to which the financial instruments are pledged. Pledgee *Pledgee2 `xml:"Pldgee,omitempty"` // Total quantity of financial instruments of the balance. AggregateBalance *Balance10 `xml:"AggtBal"` // Price of the financial instrument in one or more currencies. PriceDetails []*PriceInformation14 `xml:"PricDtls"` // Information needed to process a currency exchange or conversion. ForeignExchangeDetails []*ForeignExchangeTerms31 `xml:"FXDtls,omitempty"` // Specifies the number of days used for calculating the accrued interest amount. DaysAccrued *Number `xml:"DaysAcrd,omitempty"` // Valuation amounts provided in the base currency of the account. AccountBaseCurrencyAmounts *BalanceAmounts5 `xml:"AcctBaseCcyAmts"` // Valuation amounts provided in the currency of the financial instrument. InstrumentCurrencyAmounts *BalanceAmounts5 `xml:"InstrmCcyAmts,omitempty"` // Valuation amounts provided in another currency than the base currency of the account. AlternateReportingCurrencyAmounts *BalanceAmounts5 `xml:"AltrnRptgCcyAmts,omitempty"` // Breakdown of the aggregate quantity reported into significant lots, for example, tax lots. QuantityBreakdown []*QuantityBreakdown39 `xml:"QtyBrkdwn,omitempty"` // Specifies the underlying business area/type of trade causing the collateral movement. ExposureType *ExposureType17Choice `xml:"XpsrTp,omitempty"` // Breakdown of the aggregate balance per meaningful sub-balances and availability. BalanceBreakdown []*SubBalanceInformation16 `xml:"BalBrkdwn,omitempty"` // Provides additional instrument sub-balance information on all or parts of the reported financial instrument (unregistered, tax exempt, etc.). AdditionalBalanceBreakdown []*AdditionalBalanceInformation16 `xml:"AddtlBalBrkdwn,omitempty"` // Provides additional information on the holding. HoldingAdditionalDetails *RestrictedFINXMax350Text `xml:"HldgAddtlDtls,omitempty"` } func (a *AggregateBalancePerSafekeepingPlace30) AddSafekeepingPlace() *SafeKeepingPlace2 { a.SafekeepingPlace = new(SafeKeepingPlace2) return a.SafekeepingPlace } func (a *AggregateBalancePerSafekeepingPlace30) AddPlaceOfListing() *MarketIdentification4Choice { a.PlaceOfListing = new(MarketIdentification4Choice) return a.PlaceOfListing } func (a *AggregateBalancePerSafekeepingPlace30) AddPledgee() *Pledgee2 { a.Pledgee = new(Pledgee2) return a.Pledgee } func (a *AggregateBalancePerSafekeepingPlace30) AddAggregateBalance() *Balance10 { a.AggregateBalance = new(Balance10) return a.AggregateBalance } func (a *AggregateBalancePerSafekeepingPlace30) AddPriceDetails() *PriceInformation14 { newValue := new(PriceInformation14) a.PriceDetails = append(a.PriceDetails, newValue) return newValue } func (a *AggregateBalancePerSafekeepingPlace30) AddForeignExchangeDetails() *ForeignExchangeTerms31 { newValue := new(ForeignExchangeTerms31) a.ForeignExchangeDetails = append(a.ForeignExchangeDetails, newValue) return newValue } func (a *AggregateBalancePerSafekeepingPlace30) SetDaysAccrued(value string) { a.DaysAccrued = (*Number)(&value) } func (a *AggregateBalancePerSafekeepingPlace30) AddAccountBaseCurrencyAmounts() *BalanceAmounts5 { a.AccountBaseCurrencyAmounts = new(BalanceAmounts5) return a.AccountBaseCurrencyAmounts } func (a *AggregateBalancePerSafekeepingPlace30) AddInstrumentCurrencyAmounts() *BalanceAmounts5 { a.InstrumentCurrencyAmounts = new(BalanceAmounts5) return a.InstrumentCurrencyAmounts } func (a *AggregateBalancePerSafekeepingPlace30) AddAlternateReportingCurrencyAmounts() *BalanceAmounts5 { a.AlternateReportingCurrencyAmounts = new(BalanceAmounts5) return a.AlternateReportingCurrencyAmounts } func (a *AggregateBalancePerSafekeepingPlace30) AddQuantityBreakdown() *QuantityBreakdown39 { newValue := new(QuantityBreakdown39) a.QuantityBreakdown = append(a.QuantityBreakdown, newValue) return newValue } func (a *AggregateBalancePerSafekeepingPlace30) AddExposureType() *ExposureType17Choice { a.ExposureType = new(ExposureType17Choice) return a.ExposureType } func (a *AggregateBalancePerSafekeepingPlace30) AddBalanceBreakdown() *SubBalanceInformation16 { newValue := new(SubBalanceInformation16) a.BalanceBreakdown = append(a.BalanceBreakdown, newValue) return newValue } func (a *AggregateBalancePerSafekeepingPlace30) AddAdditionalBalanceBreakdown() *AdditionalBalanceInformation16 { newValue := new(AdditionalBalanceInformation16) a.AdditionalBalanceBreakdown = append(a.AdditionalBalanceBreakdown, newValue) return newValue } func (a *AggregateBalancePerSafekeepingPlace30) SetHoldingAdditionalDetails(value string) { a.HoldingAdditionalDetails = (*RestrictedFINXMax350Text)(&value) }
AggregateBalancePerSafekeepingPlace30.go
0.876872
0.424949
AggregateBalancePerSafekeepingPlace30.go
starcoder
package color import ( "image/color" "math" "math/rand" "github.com/jphsd/graphics2d/util" ) // HSL describes a color in HSL space. All values are in range [0,1]. type HSL struct { H, S, L, A float64 } // HSL conversions (see https://www.w3.org/TR/css-color-3/#hsl-color) // RGBA implements the RGBA function from the color.Color interface. func (c *HSL) RGBA() (uint32, uint32, uint32, uint32) { m2 := 0.0 if c.L > 0.5 { m2 = c.L + c.S - c.L*c.S } else { m2 = c.L * (1 + c.S) } m1 := c.L*2 - m2 r := uint32(hueConv(m1, m2, c.H+1/3.0) * c.A * 0xffff) g := uint32(hueConv(m1, m2, c.H) * c.A * 0xffff) b := uint32(hueConv(m1, m2, c.H-1/3.0) * c.A * 0xffff) a := uint32(c.A * 0xffff) return r, g, b, a } func hueConv(m1, m2, h float64) float64 { if h < 0 { h += 1 } else if h > 1 { h -= 1 } if h*6 < 1 { return m1 + (m2-m1)*h*6 } else if h*2 < 1 { return m2 } else if h*3 < 2 { return m1 + (m2-m1)*(2/3.0-h)*6 } return m1 } // HSLModel standard HSL color type with all values in range [0,1] var HSLModel color.Model = color.ModelFunc(hslModel) func hslModel(col color.Color) color.Color { hsl, ok := col.(*HSL) if !ok { hsl = NewHSL(col) } return hsl } // NewHSL returns the color as an HSL triplet. func NewHSL(col color.Color) *HSL { ir, ig, ib, ia := col.RGBA() if ia == 0 { return &HSL{0, 0, 0, 0} } // Convert to [0,1] r, g, b, a := float64(ir)/0xffff, float64(ig)/0xffff, float64(ib)/0xffff, float64(ia)/0xffff r /= a g /= a b /= a min := math.Min(math.Min(r, g), b) max := math.Max(math.Max(r, g), b) l := (max + min) / 2 var s, h float64 if util.Equals(min, max) { s = 0 h = 0 } else { d := max - min if l < 0.5 { s = d / (max + min) } else { s = d / (2.0 - max - min) } if max == r { h = (g - b) / d } else if max == g { h = 2 + (b-r)/d } else { h = 4 + (r-g)/d } h /= 6 if h < 0 { h += 1 } } return &HSL{h, s, l, a} } // Complement returns the color's complement. func Complement(col color.Color) color.Color { hsl := NewHSL(col) hsl.H += 0.5 if hsl.H > 1 { hsl.H -= 1 } return hsl } // Monochrome returns the color's monochrome palette (excluding black and white). // Note the palette may not contain the original color since the values are equally // spaced over L. func Monochrome(col color.Color, n int) []color.Color { if n < 2 { return []color.Color{NewHSL(col)} } res := make([]color.Color, n) dl := 1.0 / float64(n-1) l := dl for i := 0; i < n; i++ { hsl := NewHSL(col) hsl.L = l res[i] = hsl l += dl } return res } // Analogous returns the color's analogous colors. func Analogous(col color.Color) []color.Color { a1, a2 := NewHSL(col), NewHSL(col) d := 1 / float64(12) a1.H += d if a1.H > 1 { a1.H -= 1 } a2.H -= d if a2.H < 0 { a2.H += 1 } return []color.Color{a1, a2} } // Triad returns the color's other two triadics. func Triad(col color.Color) []color.Color { a1, a2 := NewHSL(col), NewHSL(col) d := 1 / float64(3) a1.H += d if a1.H > 1 { a1.H -= 1 } a2.H -= d if a2.H < 0 { a2.H += 1 } return []color.Color{a1, a2} } // Tetrad returns the color's other three tetradics. func Tetrad(col color.Color) []color.Color { a1, a2, a3 := NewHSL(col), NewHSL(col), NewHSL(col) d := 0.25 a1.H += d if a1.H > 1 { a1.H -= 1 } a2.H -= d if a2.H < 0 { a2.H += 1 } a3.H += 0.5 if a3.H > 1 { a3.H -= 1 } return []color.Color{a1, a3, a2} } // Warmer returns the color shifted towards red. func Warmer(col color.Color) color.Color { hsl := NewHSL(col) if util.Equals(hsl.H, 0) { return hsl } if hsl.H < 0.5 { if hsl.H < 0.1 { hsl.H = 0 return hsl } hsl.H -= 0.1 return hsl } if hsl.H > 0.9 { hsl.H = 0 return hsl } hsl.H += 0.1 return hsl } // Cooler returns the color shifted toward cyan. func Cooler(col color.Color) color.Color { hsl := NewHSL(col) if util.Equals(hsl.H, 0.5) { return hsl } if hsl.H < 0.5 { if hsl.H > 0.4 { hsl.H = 0.5 return hsl } hsl.H += 0.1 return hsl } if hsl.H < 0.6 { hsl.H = 0.5 return hsl } hsl.H -= 0.1 return hsl } // Tint returns the color shifted towards white. func Tint(col color.Color) color.Color { hsl := NewHSL(col) if util.Equals(hsl.L, 1) { return hsl } if hsl.L > 0.9 { hsl.L = 1 return hsl } hsl.L += 0.1 return hsl } // Shade returns the color shifted towards black. func Shade(col color.Color) color.Color { hsl := NewHSL(col) if util.Equals(hsl.L, 0) { return hsl } if hsl.L < 0.1 { hsl.L = 0 return hsl } hsl.L -= 0.1 return hsl } // Boost returns the color shifted away from gray. func Boost(col color.Color) color.Color { hsl := NewHSL(col) if util.Equals(hsl.S, 1) { return hsl } if hsl.S > 0.9 { hsl.S = 1 return hsl } hsl.S += 0.1 return hsl } // Tone returns the color shifted towards gray. func Tone(col color.Color) color.Color { hsl := NewHSL(col) if util.Equals(hsl.S, 0) { return hsl } if hsl.S < 0.1 { hsl.S = 0 return hsl } hsl.S -= 0.1 return hsl } // Compound returns the colors analogous to the color's complement. func Compound(col color.Color) []color.Color { return Analogous(Complement(col)) } // RandomHue returns an HSL color with a randon hue, fully saturated and 50% lightness. func RandomHue() color.Color { return &HSL{rand.Float64(), 1, 0.5, 1} }
color/hsl.go
0.807271
0.455622
hsl.go
starcoder
package world import ( "github.com/hajimehoshi/ebiten" "github.com/hajimehoshi/ebiten/ebitenutil" "github.com/stephenhoran/reborn/utilities" "image/color" "log" "strconv" ) type Chunks map[string]*Chunk type Chunk struct { tiles [][]*Tile x int y int } func (c Chunks) NewChunk(x, y int) { chunk := Chunk{ tiles: make([][]*Tile, ChunkSize), x: x, y: y, } ty := y for i := range chunk.tiles { tx := x tw := make([]*Tile, ChunkSize.Int()) for t := range tw { tile := NewTile() tile.SetX(tx) tile.SetY(ty) tw[t] = tile tx += TileSize.Int() } chunk.tiles[i] = tw ty -= TileSize.Int() } chunkName := "Chunk_" + strconv.Itoa(x) + "_" + strconv.Itoa(y) c[chunkName] = &chunk } func (c *Chunk) X() int { return c.x } func (c *Chunk) Y() int { return c.y } func (c *Chunk) SetX(x int) { c.x = x } func (c *Chunk) SetY(y int) { c.y = y } func (c Chunks) FindChunkAtPosition(x, y int) *Chunk { chunkX, chunkY := findUnit(x, y, ChunkPixel) return c.GetChunk(c.buildChunkName(chunkX, chunkY)) } func (c Chunks) FindTileAtPosition(x, y int) *Tile { chunk := c.FindChunkAtPosition(x, y) if chunk == nil { return nil } tileX, tileY := findUnit(x, y, TileSize) indexX := utilities.Abs((tileX - chunk.X()) / TileSize.Int()) indexY := utilities.Abs((tileY - chunk.Y()) / TileSize.Int()) return chunk.Tile(indexX, indexY) } func (c Chunks) buildChunkName(x, y int) string { return "Chunk_" + strconv.Itoa(x) + "_" + strconv.Itoa(y) } func (c Chunks) GetChunk(name string) *Chunk { chunk, ok := c[name] if !ok { log.Println("Cannot find chunk " + name) } return chunk } // Draw is used to draw all of the chunks on the screen for debugging purposed. Currently this will draw every chunk, not // get what is visible in the viewport. func (c Chunks) Draw(screen *ebiten.Image, offsetX int, offsetY int) { for _, chunk := range c { chunk.Draw(screen, offsetX, offsetY) } } // Draw (chunk) is used to draw the box for an entire chunk. func (c Chunk) Draw(screen *ebiten.Image, offsetX int, offsetY int) { x := c.X() y := c.Y() // Top Line - Left Line - Bottom Line - Right Line ebitenutil.DrawLine(screen, float64(x+offsetX), float64(offsetY-y), float64(x+offsetX+ChunkPixel.Int()), float64(offsetY-y), color.RGBA{R: 48, G: 48, B: 48, A: 255}) ebitenutil.DrawLine(screen, float64(x+offsetX), float64(offsetY-y), float64(x+offsetX), float64(offsetY-y+ChunkPixel.Int()), color.RGBA{R: 48, G: 48, B: 48, A: 255}) ebitenutil.DrawLine(screen, float64(x+offsetX), float64(offsetY-y+ChunkPixel.Int()), float64(x+offsetX+ChunkPixel.Int()), float64(offsetY-y+ChunkPixel.Int()), color.RGBA{R: 48, G: 48, B: 48, A: 255}) ebitenutil.DrawLine(screen, float64(x+offsetX+ChunkPixel.Int()), float64(offsetY-y), float64(x+offsetX+ChunkPixel.Int()), float64(offsetY-y+ChunkPixel.Int()), color.RGBA{R: 48, G: 48, B: 48, A: 255}) } func (c *Chunk) Tile(x, y int) *Tile { return c.tiles[y][x] } func (c *Chunk) DrawChunkTiles(screen *ebiten.Image, offsetX int, offsetY int) { for _, tileRow := range c.tiles { for _, tile := range tileRow { tile.Draw(screen, offsetX, offsetY) } } }
world/chunk.go
0.657209
0.400046
chunk.go
starcoder
package p0 import "fmt" /* 给定一个按照升序排列的整数数组 nums,和一个目标值 target。 找出给定目标值在数组中的开始位置和结束位置。 你的算法时间复杂度必须是 O(log n) 级别。 如果数组中不存在目标值,返回 [-1, -1]。 示例 1: 输入: nums = [5,7,7,8,8,10], target = 8 输出: [3,4] 示例 2: 输入: nums = [5,7,7,8,8,10], target = 6 输出: [-1,-1] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ func searchRange(nums []int, target int) []int { result := []int{-1, -1} if left := searchRangeLeft(nums, target); left != -1 { result[0] = left result[1] = searchRangeRight(nums[left:], target) + left } return result } func searchRangeLeft(nums []int, target int) int { if len(nums) == 0 { return -1 } var lo, hi, mid int for lo, hi = 0, len(nums); lo < hi; { mid = lo + (hi-lo)/2 if nums[mid] < target { lo = mid + 1 } else { hi = mid } } if hi == len(nums) { return -1 } if nums[hi] == target { return hi } return -1 } func searchRangeRight(nums []int, target int) int { if len(nums) == 0 { return -1 } var lo, hi, mid int for lo, hi = 0, len(nums); lo < hi; { mid = lo + (hi-lo)/2 if nums[mid] > target { hi = mid } else { lo = mid + 1 } } if hi == 0 { return -1 } if nums[hi-1] == target { return hi - 1 } return -1 } func searchRange1(nums []int, target int) []int { if len(nums) == 0 { return []int{-1, -1} } var lo, hi int for lo, hi = 0, len(nums)-1; lo <= hi; { mid := (lo + hi) / 2 switch { case nums[mid] < target: lo = mid + 1 case nums[mid] > target: hi = mid - 1 default: return []int{searchRangeLow(nums[lo:mid+1], target) + lo, searchRangeHigh(nums[mid:hi+1], target) + mid} } } return []int{-1, -1} } func searchRangeLow(nums []int, target int) int { fmt.Println(nums) if len(nums) == 0 { return 0 } var lo, hi int for lo, hi = 0, len(nums)-1; lo < hi; { mid := (lo + hi) / 2 if nums[mid] == target { hi = mid } else { lo = mid + 1 } } if nums[hi] == target { return hi } return -1 } func searchRangeHigh(nums []int, target int) int { fmt.Println(nums) if len(nums) == 0 { return 0 } var lo, hi int for lo, hi = 0, len(nums); lo < hi; { mid := (lo + hi) / 2 if nums[mid] != target { hi = mid } else { if lo == mid { break } lo = mid } } if nums[lo] == target { return lo } return -1 }
leetcode/p0/0034.go
0.514644
0.476153
0034.go
starcoder
package sync import ( "bytes" "github.com/pkg/errors" ) // EnsureValid ensures that Entry's invariants are respected. func (e *Entry) EnsureValid() error { // A nil entry is technically valid, at least in certain contexts. It // represents the absence of content. if e == nil { return nil } // Otherwise validate based on kind. if e.Kind == EntryKind_Directory { // Ensure that no invalid fields are set. if e.Executable { return errors.New("executable directory detected") } else if e.Digest != nil { return errors.New("non-nil directory digest detected") } else if e.Target != "" { return errors.New("non-empty symlink target detected for directory") } // Validate contents. Nil entries are NOT allowed as contents. for name, entry := range e.Contents { if name == "" { return errors.New("empty content name detected") } else if entry == nil { return errors.New("nil content detected") } else if err := entry.EnsureValid(); err != nil { return err } } } else if e.Kind == EntryKind_File { // Ensure that no invalid fields are set. if e.Contents != nil { return errors.New("non-nil file contents detected") } else if e.Target != "" { return errors.New("non-empty symlink target detected for file") } // Ensure that the digest is non-empty. if len(e.Digest) == 0 { return errors.New("file with empty digest detected") } } else if e.Kind == EntryKind_Symlink { // Ensure that no invalid fields are set. if e.Executable { return errors.New("executable symlink detected") } else if e.Digest != nil { return errors.New("non-nil symlink digest detected") } else if e.Contents != nil { return errors.New("non-nil symlink contents detected") } // Ensure that the target is non-empty. if e.Target == "" { return errors.New("symlink with empty target detected") } // We intentionally avoid any validation on the symlink target itself // because there's no validation that we can perform in POSIX raw mode. } else { return errors.New("unknown entry kind detected") } // Success. return nil } // equalShallow returns true if and only if the existence, kind, executability, // and digest of the two entries are equivalent. It pays no attention to the // contents of either entry. func (e *Entry) equalShallow(other *Entry) bool { // If both are nil, they can be considered equal. if e == nil && other == nil { return true } // If only one is nil, they can't be equal. if e == nil || other == nil { return false } // Check properties. return e.Kind == other.Kind && e.Executable == other.Executable && bytes.Equal(e.Digest, other.Digest) && e.Target == other.Target } // Equal determines whether or not another entry is entirely (recursively) equal // to this one. func (e *Entry) Equal(other *Entry) bool { // Verify that the entries are shallow equal first. if !e.equalShallow(other) { return false } // If both are nil, then we're done. if e == nil && other == nil { return true } // Compare contents. if len(e.Contents) != len(other.Contents) { return false } for name, entry := range e.Contents { otherEntry, ok := other.Contents[name] if !ok || !entry.Equal(otherEntry) { return false } } // Success. return true } // CopyShallow creates a shallow copy of the entry (excluding directory // contents, if any). func (e *Entry) CopyShallow() *Entry { // If the entry is nil, the copy is nil. if e == nil { return nil } // Create the shallow copy. return &Entry{ Kind: e.Kind, Executable: e.Executable, Digest: e.Digest, Target: e.Target, } } // Copy creates a deep copy of the entry. func (e *Entry) Copy() *Entry { // If the entry is nil, the copy is nil. if e == nil { return nil } // Create the result. result := &Entry{ Kind: e.Kind, Executable: e.Executable, Digest: e.Digest, Target: e.Target, } // If the original entry doesn't have any contents, return now to save an // allocation. if len(e.Contents) == 0 { return result } // Copy contents. result.Contents = make(map[string]*Entry) for name, entry := range e.Contents { result.Contents[name] = entry.Copy() } // Done. return result }
pkg/sync/entry.go
0.693058
0.420897
entry.go
starcoder
package plaid import ( "encoding/json" ) // SenderBACSNullable struct for SenderBACSNullable type SenderBACSNullable struct { // The account number of the account. Maximum of 10 characters. Account *string `json:"account,omitempty"` // The 6-character sort code of the account. SortCode *string `json:"sort_code,omitempty"` } // NewSenderBACSNullable instantiates a new SenderBACSNullable 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 NewSenderBACSNullable() *SenderBACSNullable { this := SenderBACSNullable{} return &this } // NewSenderBACSNullableWithDefaults instantiates a new SenderBACSNullable 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 NewSenderBACSNullableWithDefaults() *SenderBACSNullable { this := SenderBACSNullable{} return &this } // GetAccount returns the Account field value if set, zero value otherwise. func (o *SenderBACSNullable) GetAccount() string { if o == nil || o.Account == nil { var ret string return ret } return *o.Account } // GetAccountOk returns a tuple with the Account field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SenderBACSNullable) GetAccountOk() (*string, bool) { if o == nil || o.Account == nil { return nil, false } return o.Account, true } // HasAccount returns a boolean if a field has been set. func (o *SenderBACSNullable) HasAccount() bool { if o != nil && o.Account != nil { return true } return false } // SetAccount gets a reference to the given string and assigns it to the Account field. func (o *SenderBACSNullable) SetAccount(v string) { o.Account = &v } // GetSortCode returns the SortCode field value if set, zero value otherwise. func (o *SenderBACSNullable) GetSortCode() string { if o == nil || o.SortCode == nil { var ret string return ret } return *o.SortCode } // GetSortCodeOk returns a tuple with the SortCode field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SenderBACSNullable) GetSortCodeOk() (*string, bool) { if o == nil || o.SortCode == nil { return nil, false } return o.SortCode, true } // HasSortCode returns a boolean if a field has been set. func (o *SenderBACSNullable) HasSortCode() bool { if o != nil && o.SortCode != nil { return true } return false } // SetSortCode gets a reference to the given string and assigns it to the SortCode field. func (o *SenderBACSNullable) SetSortCode(v string) { o.SortCode = &v } func (o SenderBACSNullable) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Account != nil { toSerialize["account"] = o.Account } if o.SortCode != nil { toSerialize["sort_code"] = o.SortCode } return json.Marshal(toSerialize) } type NullableSenderBACSNullable struct { value *SenderBACSNullable isSet bool } func (v NullableSenderBACSNullable) Get() *SenderBACSNullable { return v.value } func (v *NullableSenderBACSNullable) Set(val *SenderBACSNullable) { v.value = val v.isSet = true } func (v NullableSenderBACSNullable) IsSet() bool { return v.isSet } func (v *NullableSenderBACSNullable) Unset() { v.value = nil v.isSet = false } func NewNullableSenderBACSNullable(val *SenderBACSNullable) *NullableSenderBACSNullable { return &NullableSenderBACSNullable{value: val, isSet: true} } func (v NullableSenderBACSNullable) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableSenderBACSNullable) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
plaid/model_sender_bacs_nullable.go
0.779574
0.41253
model_sender_bacs_nullable.go
starcoder
package vbptc import ( "errors" "fmt" ) var ( // See page 136 of the DMR AI. spec. for the generator matrix. hamming_16_11_generator_matrix = []byte{ 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, // These are used to determine errors in the Hamming checksum bits. 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, } ) type VBPTC struct { matrix []byte row, col uint8 expectedRows uint8 } func New(expectedRows uint8) *VBPTC { return &VBPTC{ matrix: make([]byte, int(expectedRows)*16), expectedRows: expectedRows, } } func (v *VBPTC) freeSpace() int { var size = int(v.expectedRows) * 16 var used = int(v.expectedRows)*int(v.col) + int(v.row) return size - used } // AddBurst adds the embedded signalling data to the matrix. func (v *VBPTC) AddBurst(bits []byte) error { if v.matrix == nil { return errors.New("vbptc: matrix can't be nil") } var free = v.freeSpace() if free == 0 { return errors.New("vbptc: no free space in matrix") } var adds = len(bits) if adds > free { adds = free } for i := 0; i < adds; i++ { v.matrix[v.col+v.row*16] = bits[i] v.row++ if v.row == v.expectedRows { v.col++ v.row = 0 } } return nil } // CheckAndRepair checks data for errors and tries to repair them func (v *VBPTC) CheckAndRepair() error { if v.matrix == nil || v.expectedRows < 2 { return fmt.Errorf("vbptc: no data") } var ( row, col uint8 errs = make([]byte, 5) ) // -1 because the last row contains only single parity check bits for row = 0; row < v.expectedRows-1; row++ { if !checkRow(v.matrix[row*16:], errs) { // If the Hamming(16, 11, 4) column check failed, see if we can find // the bit error location. pos, found := findPosition(errs) if !found { return fmt.Errorf("vbptc: hamming(16,11) check error, can't repair row #%d", row) } // Flip wrong bit v.matrix[row*16+pos] ^= 1 if !checkRow(v.matrix[row*16:], errs) { return fmt.Errorf("vbptc: hamming(16,11) check error, couldn't repair row #%d", row) } } } for col = 0; col < 16; col++ { var parity uint8 for row = 0; row < v.expectedRows-1; row++ { parity = (parity + v.matrix[row*16+col]) % 2 } if parity != v.matrix[(v.expectedRows-1)*16+col] { return fmt.Errorf("vbptc: parity check error in column #%d", col) } } return nil } // Clear resets the variable BPTC matrix and cursor position func (v *VBPTC) Clear() { v.row = 0 v.col = 0 v.matrix = make([]byte, int(v.expectedRows)*16) } // GetData extracts data bits (discarding Hamming (16,11) and parity check bits) from the vbptc matrix. func (v *VBPTC) GetData(bits []byte) error { if v.matrix == nil || v.expectedRows == 0 { return errors.New("vbptc: no data in matrix") } if bits == nil { return errors.New("vbptc: bits can't be nil") } if len(bits) < 77 { return fmt.Errorf("vbptc: need at least 77 bits buffer, got %d", len(bits)) } var row, col uint8 for row = 0; row < v.expectedRows-1; row++ { for col = 0; col < 11; col++ { bits[row*11+col] = v.matrix[row*16+col] } } return nil } func checkRow(bits, errs []byte) bool { if bits == nil || errs == nil { return false } getParity(bits, errs) errs[0] ^= bits[11] errs[1] ^= bits[12] errs[2] ^= bits[13] errs[3] ^= bits[14] errs[4] ^= bits[15] return errs[0] == 0 && errs[1] == 0 && errs[2] == 0 && errs[3] == 0 && errs[4] == 0 } func findPosition(errs []byte) (uint8, bool) { for row := uint8(0); row < 16; row++ { var found = true switch { case hamming_16_11_generator_matrix[row*5] != errs[0]: found = false break case hamming_16_11_generator_matrix[row*5+1] != errs[1]: found = false break case hamming_16_11_generator_matrix[row*5+2] != errs[2]: found = false break case hamming_16_11_generator_matrix[row*5+3] != errs[3]: found = false break } if found { return row, true } } return 0, false } func getParity(bits, errs []byte) { errs[0] = (bits[0] ^ bits[1] ^ bits[2] ^ bits[3] ^ bits[5] ^ bits[7] ^ bits[8]) errs[1] = (bits[1] ^ bits[2] ^ bits[3] ^ bits[4] ^ bits[6] ^ bits[8] ^ bits[9]) errs[2] = (bits[2] ^ bits[3] ^ bits[4] ^ bits[5] ^ bits[7] ^ bits[9] ^ bits[10]) errs[3] = (bits[0] ^ bits[1] ^ bits[2] ^ bits[4] ^ bits[6] ^ bits[7] ^ bits[10]) errs[4] = (bits[0] ^ bits[2] ^ bits[5] ^ bits[6] ^ bits[8] ^ bits[9] ^ bits[10]) }
vbptc/vbptc.go
0.566738
0.454291
vbptc.go
starcoder
package schema import ( "fmt" "strings" log "github.com/sirupsen/logrus" ) // TypeRef is a GraphQL reference to a Type. type TypeRef struct { Name string `json:"name,omitempty"` Description string `json:"description,omitempty"` Kind Kind `json:"kind,omitempty"` OfType *TypeRef `json:"ofType,omitempty"` } // GetKinds returns an array or the type kind func (r *TypeRef) GetKinds() []Kind { tree := []Kind{} if r.Kind != "" { tree = append(tree, r.Kind) } // Recursion FTW if r.OfType != nil { tree = append(tree, r.OfType.GetKinds()...) } return tree } // GetName returns a recusive lookup of the type name func (r *TypeRef) GetName() string { return formatGoName(r.Name) } // GetTypeName returns the name of the current type, or performs a recursive lookup to determine the name of the nested OfType object's name. In the case that neither are matched, the string "UNKNOWN" is returned. In the GraphQL schema, a non-empty name seems to appear only once in a TypeRef tree, so we want to find the first non-empty. func (r *TypeRef) GetTypeName() string { if r != nil { if r.Name != "" { return r.Name } // Recursion FTW if r.OfType != nil { return r.OfType.GetTypeName() } } log.Errorf("failed to get name for %#v", *r) return "UNKNOWN" } // GetType resolves the given SchemaInputField into a field name to use on a go struct. // type, recurse, error func (r *TypeRef) GetType() (string, bool, error) { if r == nil { return "", false, fmt.Errorf("can not get type of nil TypeRef") } switch n := r.GetTypeName(); n { case "String": return "string", false, nil case "Int": return "int", false, nil case "Boolean": return "bool", false, nil case "Float": return "float64", false, nil case "ID": // ID is a nested object, but behaves like an integer. This may be true of other SCALAR types as well, so logic here could potentially be moved. return "int", false, nil case "": return "", true, fmt.Errorf("empty field name: %+v", r) default: return formatGoName(n), true, nil } } // GetDescription looks for anything in the description before \n\n---\n // and filters off anything after that (internal messaging that is not useful here) func (r *TypeRef) GetDescription() string { if strings.TrimSpace(r.Description) == "" { return "" } return formatDescription("", r.Description) } func (r *TypeRef) IsInputObject() bool { kinds := r.GetKinds() // Lots of kinds for _, k := range kinds { if k == KindInputObject { return true } } return false } func (r *TypeRef) IsScalarID() bool { return r.OfType != nil && r.OfType.Kind == KindScalar && r.GetTypeName() == "ID" } // IsNonNull walks down looking for NON_NULL kind, however that can appear // multiple times, so this is likely a bit deceiving... // Example: // { // "name": "tags", // "description": "An array of key-values pairs to represent a tag. For example: Team:TeamName.", // "type": { // "kind": "NON_NULL", // "ofType": { // "kind": "LIST", // "ofType": { // "kind": "NON_NULL", // "ofType": { // "name": "TaggingTagInput", // "kind": "INPUT_OBJECT" // } // } // } // } // } // ] // } func (r *TypeRef) IsNonNull() bool { kinds := r.GetKinds() // Lots of kinds for _, k := range kinds { if k == KindNonNull { return true } } return false } // IsList determines if a TypeRef is of a KIND LIST. func (r *TypeRef) IsList() bool { kinds := r.GetKinds() // Lots of kinds for _, k := range kinds { if k == KindList { return true } } return false } // IsList determines if a TypeRef is of a KIND INTERFACE. func (r *TypeRef) IsInterface() bool { kinds := r.GetKinds() // Lots of kinds for _, k := range kinds { if k == KindInterface { return true } } return false }
internal/schema/typeref.go
0.727975
0.417093
typeref.go
starcoder
package definitions import ( "strings" ) // TypeCategory is the category to which a type belongs. // The different categories are defined as constants. type TypeCategory int const ( // Builtin types (int, int8, string, bool, etc) Builtin = TypeCategory(iota + 1) // Simple types. eg: `type myInt int` Simple // Slice types. eg: `type mySlice []int` Slice // Map types. eg: `type myMap map[keyType]valueType` Map // Struct types. eg: `type myStruct struct{}` Struct ) // StructField defines a single field in a struct type StructField struct { Name string Type *Type } // Type is the type of a parameter // It's value should be a valid go TypeName (http://golang.org/ref/spec#TypeName) type Type struct { // Name is the identifier of the type Name string // Category indicates the Type's category (builtin, simple, slice, map, struct) Category TypeCategory // SimpleType defines the type for the type that this type maps to SimpleType *Type // SliceElementType defines the type for the slice elements SliceElementType *Type // MapKeyType and MapValueType define the key and value types for the map MapKeyType *Type MapValueType *Type // StructFields holds the struct field definitions, only used when Category is Struct. StructFields []StructField } // CapitalizedName returns the name, capitalized func (t *Type) CapitalizedName() string { return strings.ToUpper(t.Name[:1]) + t.Name[1:] } // GoIsBuiltin returns true when the type is a Go builtin type func (t *Type) GoIsBuiltin() bool { return t.Category == Builtin } // GoName returns the Go identifier for this type. // The Go identifier is capitalized when the type is not a builtin Go type. func (t *Type) GoName() string { if t.Category == Builtin { return t.Name } return t.CapitalizedName() } func (t *Type) GoTypeDefinition() string { switch t.Category { case Builtin: return t.Name case Simple: return t.SimpleType.GoName() case Slice: return `[]` + t.SliceElementType.GoName() case Map: return `map[` + t.MapKeyType.GoName() + `]` + t.MapValueType.GoName() case Struct: s := "struct {\n" for _, f := range t.StructFields { s += strings.ToUpper(f.Name[:1]) + f.Name[1:] + ` ` + f.Type.GoTypeDefinition() + "\n" } s += `}` return s default: panic("unknown type") } } // Builtin types var ( TypeInt = &Type{Name: "int", Category: Builtin} TypeInt8 = &Type{Name: "int8", Category: Builtin} TypeInt16 = &Type{Name: "int16", Category: Builtin} TypeInt32 = &Type{Name: "int32", Category: Builtin} TypeInt64 = &Type{Name: "int64", Category: Builtin} TypeUint = &Type{Name: "uint", Category: Builtin} TypeUint8 = &Type{Name: "uint8", Category: Builtin} TypeUint16 = &Type{Name: "uint16", Category: Builtin} TypeUint32 = &Type{Name: "uint32", Category: Builtin} TypeUint64 = &Type{Name: "uint64", Category: Builtin} TypeString = &Type{Name: "string", Category: Builtin} TypeBool = &Type{Name: "bool", Category: Builtin} BuiltinTypes = map[string]*Type{ TypeInt.Name: TypeInt, TypeInt8.Name: TypeInt8, TypeInt16.Name: TypeInt16, TypeInt32.Name: TypeInt32, TypeInt64.Name: TypeInt64, TypeUint.Name: TypeUint, TypeUint8.Name: TypeUint8, TypeUint16.Name: TypeUint16, TypeUint32.Name: TypeUint32, TypeUint64.Name: TypeUint64, TypeString.Name: TypeString, TypeBool.Name: TypeBool, } )
definitions/type.go
0.704364
0.449936
type.go
starcoder
package bigo import ( "fmt" "image/color" "math" "gonum.org/v1/plot/vg/draw" "github.com/montanaflynn/stats" "gonum.org/v1/plot" "gonum.org/v1/plot/plotter" "gonum.org/v1/plot/vg" ) // PlotSeriesList a list PlotSeries. type PlotSeriesList []PlotSeries // PlotSeries a list of result values assigned to a name. type PlotSeries struct { Name string Results Results } const defaultPlotWidth = 6 const defaultPlotHeight = 6 const legendThumbnailWidth = 0.5 // DefaultPlotConfig is used when calling PlotTestResults. var DefaultPlotConfig = PlotConfig{ ReferencePlots: false, PlotWidth: defaultPlotWidth * vg.Inch, PlotHeight: defaultPlotHeight * vg.Inch, LegendThumbNailWidth: legendThumbnailWidth * vg.Inch, } // PlotConfig enables to configure the plot. type PlotConfig struct { ReferencePlots bool PlotWidth vg.Length PlotHeight vg.Length LegendThumbNailWidth vg.Length } // PlotTestResults plots the given results to a file prefixed with the given name. func PlotTestResults(name string, plotSeries PlotSeriesList) { PlotTestResultsWithConfig(name, plotSeries, DefaultPlotConfig) } // PlotTestResultsWithConfig allows to plot with custom configuration. //nolint:funlen func PlotTestResultsWithConfig(name string, plotSeries PlotSeriesList, plotConfig PlotConfig) { p := plot.New() p.Title.Text = name p.X.Label.Text = "N" p.Y.Label.Text = "O" pal := newPalette() var ( maxO, minO = 0.0, math.MaxFloat64 maxN, minN = 0.0, math.MaxFloat64 ) for _, series := range plotSeries { c := pal.Next() seriesName := series.Name var ( O stats.Float64Data ptsMin, ptsMax, ptsMean, all plotter.XYs ) for _, results := range series.Results { var max, min, mean float64 n := results.N for _, result := range results.OMeasures { all = append(all, plotter.XY{X: n, Y: result.O}) O = append(O, result.O) max = mustFloat64(stats.Max(O)) mean = mustFloat64(stats.Mean(O)) min = mustFloat64(stats.Min(O)) } ptsMin = append(ptsMin, plotter.XY{X: n, Y: min}) ptsMax = append(ptsMax, plotter.XY{X: n, Y: max}) ptsMean = append(ptsMean, plotter.XY{X: n, Y: mean}) minO = math.Min(minO, min) maxO = math.Max(maxO, max) minN = math.Min(minN, n) maxN = math.Max(maxN, n) O = stats.Float64Data{} } lMin, err := plotter.NewLine(ptsMin) panicOnError(err) lMax, err := plotter.NewLine(ptsMax) panicOnError(err) lMean, err := plotter.NewLine(ptsMean) panicOnError(err) lAll, err := plotter.NewScatter(all) panicOnError(err) lMin.Color = c lMin.Dashes = []vg.Length{vg.Points(2), vg.Points(2)} //nolint:gomnd lMax.Color = c lMax.Dashes = []vg.Length{vg.Points(2), vg.Points(2)} //nolint:gomnd lMean.Color = c lMean.Dashes = []vg.Length{vg.Points(0.5), vg.Points(0.5)} //nolint:gomnd lAll.Color = c lAll.Shape = draw.PlusGlyph{} lAll.Radius = vg.Length(5) //nolint:gomnd p.Add(lMin, lMax, lMean, lAll) p.Legend.Add(fmt.Sprintf("%s min", seriesName), lMin) p.Legend.Add(fmt.Sprintf("%s max", seriesName), lMax) p.Legend.Add(fmt.Sprintf("%s mean", seriesName), lMean) p.Legend.Add(fmt.Sprintf("%s all", seriesName), lAll) panicOnError(err) } if plotConfig.ReferencePlots { addReferencePlots(minN, maxN, minO, maxO, p) } p.Legend.ThumbnailWidth = plotConfig.LegendThumbNailWidth if err := p.Save(plotConfig.PlotWidth, plotConfig.PlotHeight, normalizeFileName(name, "png")); err != nil { panic(err) } } func mustFloat64(v float64, err error) float64 { if err != nil { panic(err) } return v } func addReferencePlots(minN float64, maxN float64, minO float64, maxO float64, p *plot.Plot) { quad := plotter.NewFunction(scaledFunction(minN, maxN, minO, maxO, func(x float64) float64 { return math.Pow(x, 2) })) quad.Color = color.RGBA{B: 0, G: 0, A: 60} //nolint:gomnd quad.Width = 1 log := plotter.NewFunction(scaledFunction(minN, maxN, minO, maxO, logLimited)) log.Color = color.RGBA{B: 0, G: 0, A: 60} //nolint:gomnd log.Width = 1 p.Add(quad, log) p.Legend.Add("x^2", quad) p.Legend.Add("log x", log) } func scaledFunction(minN, maxN, minO, maxO float64, f func(x float64) float64) func(x float64) float64 { return func(x float64) float64 { xScaled := scaleX(minN, maxN, x) xApplied := f(xScaled) yScaled := scaleY(minO, maxO, xApplied) return yScaled } } func scaleX(minN, maxN, n float64) float64 { const h = 100 n -= minN nPercent := h / (maxN / n) scaledN := h / (h * nPercent) return scaledN } func scaleY(minO, maxO float64, n float64) float64 { o := maxO / (100 * n) o += minO return o } func logLimited(x float64) float64 { l := math.Log(x) if l < 0 { l = 0 } return l } func panicOnError(err error) { if err != nil { panic(err) } } func newPalette() palette { return palette{ //nolint:gomnd colors: []color.RGBA{ {R: 211, G: 69, B: 0, A: 255}, {R: 50, G: 211, B: 50, A: 255}, {R: 0, G: 191, B: 211, A: 255}, {R: 255, G: 215, B: 0, A: 255}, {R: 186, G: 85, B: 211, A: 255}, {R: 32, G: 178, B: 170, A: 255}, }, } } type palette struct { colors []color.RGBA idx int } func (p *palette) Next() color.RGBA { if p.idx >= len(p.colors) { p.idx = 0 } c := p.colors[p.idx] p.idx++ return c }
plot.go
0.808937
0.529872
plot.go
starcoder
package main /* Day 2: Part A: Given a space-separated list of space-separated numbers in a multi-line file compute the line-wise sum of checksums (highest-lowest number). ex: 5 1 9 5 = 8 7 5 3 = 4 2 4 6 8 = 6 checksum = 8 + 4 + 6 = 18 Part B: For each row, find the two numbers that cleanly divide into each other and add up the result for each row. 5 9 2 8 = 8 / 2 = 4 9 4 7 3 = 9 / 3 = 3 3 8 6 5 = 6 / 3 = 2 checksum = 4 + 3 + 2 = 9 Need to store each parsed number in a list so that they can be iterated over. Need to compare each with the other, numerator and denominator, ex: i = 0 j = 0 next j if i == j if remainder of d[i] / d[j] == 0 # got it end end */ import ( "bufio" "flag" "fmt" "math" "os" "strconv" "strings" ) var inputFile = flag.String("inputFile", "inputs/day02-example.txt", "Input file for Day 2") var partB = flag.Bool("partB", false, "Perform part B solution?") func main() { flag.Parse() input, err := os.Open(*inputFile) if err != nil { fmt.Printf("Couldn't open %s for read: %v", inputFile, err) os.Exit(1) } sum := 0 lineReader := bufio.NewScanner(input) for lineReader.Scan() { var lowest = math.MaxInt32 var highest = -1 var lineNumbers []int for _, d := range strings.Split(lineReader.Text(), "\t") { // Parse numbers on the line number, err := strconv.Atoi(d) if err != nil { fmt.Printf("Couldn't convert >%s< to a number: %v", d, err) os.Exit(1) } if *partB { // part B lineNumbers = append(lineNumbers, number) } else { // part A if number < lowest { lowest = number } if number > highest { highest = number } } } // done processing numbers for this line, make checksum if *partB { for i := 0; i < len(lineNumbers); i++ { inner: for j := 0; j < len(lineNumbers); j++ { if j == i { continue inner } if math.Remainder(float64(lineNumbers[i]), float64(lineNumbers[j])) == 0 { sum += lineNumbers[i] / lineNumbers[j] } } } } else { sum += highest - lowest } } fmt.Printf("Table checksum: %d\n", sum) }
2017/day02.go
0.519278
0.446917
day02.go
starcoder
package models import ( i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization" ) // BookingBusiness type BookingBusiness struct { Entity // The street address of the business. The address property, together with phone and webSiteUrl, appear in the footer of a business scheduling page. address PhysicalAddressable // All the appointments of this business. Read-only. Nullable. appointments []BookingAppointmentable // The hours of operation for the business. businessHours []BookingWorkHoursable // The type of business. businessType *string // The set of appointments of this business in a specified date range. Read-only. Nullable. calendarView []BookingAppointmentable // All the customers of this business. Read-only. Nullable. customers []BookingCustomerBaseable // All the custom questions of this business. Read-only. Nullable. customQuestions []BookingCustomQuestionable // The code for the currency that the business operates in on Microsoft Bookings. defaultCurrencyIso *string // The name of the business, which interfaces with customers. This name appears at the top of the business scheduling page. displayName *string // The email address for the business. email *string // The scheduling page has been made available to external customers. Use the publish and unpublish actions to set this property. Read-only. isPublished *bool // The telephone number for the business. The phone property, together with address and webSiteUrl, appear in the footer of a business scheduling page. phone *string // The URL for the scheduling page, which is set after you publish or unpublish the page. Read-only. publicUrl *string // Specifies how bookings can be created for this business. schedulingPolicy BookingSchedulingPolicyable // All the services offered by this business. Read-only. Nullable. services []BookingServiceable // All the staff members that provide services in this business. Read-only. Nullable. staffMembers []BookingStaffMemberBaseable // The URL of the business web site. The webSiteUrl property, together with address, phone, appear in the footer of a business scheduling page. webSiteUrl *string } // NewBookingBusiness instantiates a new bookingBusiness and sets the default values. func NewBookingBusiness()(*BookingBusiness) { m := &BookingBusiness{ Entity: *NewEntity(), } return m } // CreateBookingBusinessFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value func CreateBookingBusinessFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) { return NewBookingBusiness(), nil } // GetAddress gets the address property value. The street address of the business. The address property, together with phone and webSiteUrl, appear in the footer of a business scheduling page. func (m *BookingBusiness) GetAddress()(PhysicalAddressable) { if m == nil { return nil } else { return m.address } } // GetAppointments gets the appointments property value. All the appointments of this business. Read-only. Nullable. func (m *BookingBusiness) GetAppointments()([]BookingAppointmentable) { if m == nil { return nil } else { return m.appointments } } // GetBusinessHours gets the businessHours property value. The hours of operation for the business. func (m *BookingBusiness) GetBusinessHours()([]BookingWorkHoursable) { if m == nil { return nil } else { return m.businessHours } } // GetBusinessType gets the businessType property value. The type of business. func (m *BookingBusiness) GetBusinessType()(*string) { if m == nil { return nil } else { return m.businessType } } // GetCalendarView gets the calendarView property value. The set of appointments of this business in a specified date range. Read-only. Nullable. func (m *BookingBusiness) GetCalendarView()([]BookingAppointmentable) { if m == nil { return nil } else { return m.calendarView } } // GetCustomers gets the customers property value. All the customers of this business. Read-only. Nullable. func (m *BookingBusiness) GetCustomers()([]BookingCustomerBaseable) { if m == nil { return nil } else { return m.customers } } // GetCustomQuestions gets the customQuestions property value. All the custom questions of this business. Read-only. Nullable. func (m *BookingBusiness) GetCustomQuestions()([]BookingCustomQuestionable) { if m == nil { return nil } else { return m.customQuestions } } // GetDefaultCurrencyIso gets the defaultCurrencyIso property value. The code for the currency that the business operates in on Microsoft Bookings. func (m *BookingBusiness) GetDefaultCurrencyIso()(*string) { if m == nil { return nil } else { return m.defaultCurrencyIso } } // GetDisplayName gets the displayName property value. The name of the business, which interfaces with customers. This name appears at the top of the business scheduling page. func (m *BookingBusiness) GetDisplayName()(*string) { if m == nil { return nil } else { return m.displayName } } // GetEmail gets the email property value. The email address for the business. func (m *BookingBusiness) GetEmail()(*string) { if m == nil { return nil } else { return m.email } } // GetFieldDeserializers the deserialization information for the current model func (m *BookingBusiness) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) { res := m.Entity.GetFieldDeserializers() res["address"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetObjectValue(CreatePhysicalAddressFromDiscriminatorValue) if err != nil { return err } if val != nil { m.SetAddress(val.(PhysicalAddressable)) } return nil } res["appointments"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetCollectionOfObjectValues(CreateBookingAppointmentFromDiscriminatorValue) if err != nil { return err } if val != nil { res := make([]BookingAppointmentable, len(val)) for i, v := range val { res[i] = v.(BookingAppointmentable) } m.SetAppointments(res) } return nil } res["businessHours"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetCollectionOfObjectValues(CreateBookingWorkHoursFromDiscriminatorValue) if err != nil { return err } if val != nil { res := make([]BookingWorkHoursable, len(val)) for i, v := range val { res[i] = v.(BookingWorkHoursable) } m.SetBusinessHours(res) } return nil } res["businessType"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetBusinessType(val) } return nil } res["calendarView"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetCollectionOfObjectValues(CreateBookingAppointmentFromDiscriminatorValue) if err != nil { return err } if val != nil { res := make([]BookingAppointmentable, len(val)) for i, v := range val { res[i] = v.(BookingAppointmentable) } m.SetCalendarView(res) } return nil } res["customers"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetCollectionOfObjectValues(CreateBookingCustomerBaseFromDiscriminatorValue) if err != nil { return err } if val != nil { res := make([]BookingCustomerBaseable, len(val)) for i, v := range val { res[i] = v.(BookingCustomerBaseable) } m.SetCustomers(res) } return nil } res["customQuestions"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetCollectionOfObjectValues(CreateBookingCustomQuestionFromDiscriminatorValue) if err != nil { return err } if val != nil { res := make([]BookingCustomQuestionable, len(val)) for i, v := range val { res[i] = v.(BookingCustomQuestionable) } m.SetCustomQuestions(res) } return nil } res["defaultCurrencyIso"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetDefaultCurrencyIso(val) } return nil } res["displayName"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetDisplayName(val) } return nil } res["email"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetEmail(val) } return nil } res["isPublished"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetBoolValue() if err != nil { return err } if val != nil { m.SetIsPublished(val) } return nil } res["phone"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetPhone(val) } return nil } res["publicUrl"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetPublicUrl(val) } return nil } res["schedulingPolicy"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetObjectValue(CreateBookingSchedulingPolicyFromDiscriminatorValue) if err != nil { return err } if val != nil { m.SetSchedulingPolicy(val.(BookingSchedulingPolicyable)) } return nil } res["services"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetCollectionOfObjectValues(CreateBookingServiceFromDiscriminatorValue) if err != nil { return err } if val != nil { res := make([]BookingServiceable, len(val)) for i, v := range val { res[i] = v.(BookingServiceable) } m.SetServices(res) } return nil } res["staffMembers"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetCollectionOfObjectValues(CreateBookingStaffMemberBaseFromDiscriminatorValue) if err != nil { return err } if val != nil { res := make([]BookingStaffMemberBaseable, len(val)) for i, v := range val { res[i] = v.(BookingStaffMemberBaseable) } m.SetStaffMembers(res) } return nil } res["webSiteUrl"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error { val, err := n.GetStringValue() if err != nil { return err } if val != nil { m.SetWebSiteUrl(val) } return nil } return res } // GetIsPublished gets the isPublished property value. The scheduling page has been made available to external customers. Use the publish and unpublish actions to set this property. Read-only. func (m *BookingBusiness) GetIsPublished()(*bool) { if m == nil { return nil } else { return m.isPublished } } // GetPhone gets the phone property value. The telephone number for the business. The phone property, together with address and webSiteUrl, appear in the footer of a business scheduling page. func (m *BookingBusiness) GetPhone()(*string) { if m == nil { return nil } else { return m.phone } } // GetPublicUrl gets the publicUrl property value. The URL for the scheduling page, which is set after you publish or unpublish the page. Read-only. func (m *BookingBusiness) GetPublicUrl()(*string) { if m == nil { return nil } else { return m.publicUrl } } // GetSchedulingPolicy gets the schedulingPolicy property value. Specifies how bookings can be created for this business. func (m *BookingBusiness) GetSchedulingPolicy()(BookingSchedulingPolicyable) { if m == nil { return nil } else { return m.schedulingPolicy } } // GetServices gets the services property value. All the services offered by this business. Read-only. Nullable. func (m *BookingBusiness) GetServices()([]BookingServiceable) { if m == nil { return nil } else { return m.services } } // GetStaffMembers gets the staffMembers property value. All the staff members that provide services in this business. Read-only. Nullable. func (m *BookingBusiness) GetStaffMembers()([]BookingStaffMemberBaseable) { if m == nil { return nil } else { return m.staffMembers } } // GetWebSiteUrl gets the webSiteUrl property value. The URL of the business web site. The webSiteUrl property, together with address, phone, appear in the footer of a business scheduling page. func (m *BookingBusiness) GetWebSiteUrl()(*string) { if m == nil { return nil } else { return m.webSiteUrl } } // Serialize serializes information the current object func (m *BookingBusiness) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) { err := m.Entity.Serialize(writer) if err != nil { return err } { err = writer.WriteObjectValue("address", m.GetAddress()) if err != nil { return err } } if m.GetAppointments() != nil { cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAppointments())) for i, v := range m.GetAppointments() { cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable) } err = writer.WriteCollectionOfObjectValues("appointments", cast) if err != nil { return err } } if m.GetBusinessHours() != nil { cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBusinessHours())) for i, v := range m.GetBusinessHours() { cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable) } err = writer.WriteCollectionOfObjectValues("businessHours", cast) if err != nil { return err } } { err = writer.WriteStringValue("businessType", m.GetBusinessType()) if err != nil { return err } } if m.GetCalendarView() != nil { cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCalendarView())) for i, v := range m.GetCalendarView() { cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable) } err = writer.WriteCollectionOfObjectValues("calendarView", cast) if err != nil { return err } } if m.GetCustomers() != nil { cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCustomers())) for i, v := range m.GetCustomers() { cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable) } err = writer.WriteCollectionOfObjectValues("customers", cast) if err != nil { return err } } if m.GetCustomQuestions() != nil { cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCustomQuestions())) for i, v := range m.GetCustomQuestions() { cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable) } err = writer.WriteCollectionOfObjectValues("customQuestions", cast) if err != nil { return err } } { err = writer.WriteStringValue("defaultCurrencyIso", m.GetDefaultCurrencyIso()) if err != nil { return err } } { err = writer.WriteStringValue("displayName", m.GetDisplayName()) if err != nil { return err } } { err = writer.WriteStringValue("email", m.GetEmail()) if err != nil { return err } } { err = writer.WriteBoolValue("isPublished", m.GetIsPublished()) if err != nil { return err } } { err = writer.WriteStringValue("phone", m.GetPhone()) if err != nil { return err } } { err = writer.WriteStringValue("publicUrl", m.GetPublicUrl()) if err != nil { return err } } { err = writer.WriteObjectValue("schedulingPolicy", m.GetSchedulingPolicy()) if err != nil { return err } } if m.GetServices() != nil { cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetServices())) for i, v := range m.GetServices() { cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable) } err = writer.WriteCollectionOfObjectValues("services", cast) if err != nil { return err } } if m.GetStaffMembers() != nil { cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetStaffMembers())) for i, v := range m.GetStaffMembers() { cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable) } err = writer.WriteCollectionOfObjectValues("staffMembers", cast) if err != nil { return err } } { err = writer.WriteStringValue("webSiteUrl", m.GetWebSiteUrl()) if err != nil { return err } } return nil } // SetAddress sets the address property value. The street address of the business. The address property, together with phone and webSiteUrl, appear in the footer of a business scheduling page. func (m *BookingBusiness) SetAddress(value PhysicalAddressable)() { if m != nil { m.address = value } } // SetAppointments sets the appointments property value. All the appointments of this business. Read-only. Nullable. func (m *BookingBusiness) SetAppointments(value []BookingAppointmentable)() { if m != nil { m.appointments = value } } // SetBusinessHours sets the businessHours property value. The hours of operation for the business. func (m *BookingBusiness) SetBusinessHours(value []BookingWorkHoursable)() { if m != nil { m.businessHours = value } } // SetBusinessType sets the businessType property value. The type of business. func (m *BookingBusiness) SetBusinessType(value *string)() { if m != nil { m.businessType = value } } // SetCalendarView sets the calendarView property value. The set of appointments of this business in a specified date range. Read-only. Nullable. func (m *BookingBusiness) SetCalendarView(value []BookingAppointmentable)() { if m != nil { m.calendarView = value } } // SetCustomers sets the customers property value. All the customers of this business. Read-only. Nullable. func (m *BookingBusiness) SetCustomers(value []BookingCustomerBaseable)() { if m != nil { m.customers = value } } // SetCustomQuestions sets the customQuestions property value. All the custom questions of this business. Read-only. Nullable. func (m *BookingBusiness) SetCustomQuestions(value []BookingCustomQuestionable)() { if m != nil { m.customQuestions = value } } // SetDefaultCurrencyIso sets the defaultCurrencyIso property value. The code for the currency that the business operates in on Microsoft Bookings. func (m *BookingBusiness) SetDefaultCurrencyIso(value *string)() { if m != nil { m.defaultCurrencyIso = value } } // SetDisplayName sets the displayName property value. The name of the business, which interfaces with customers. This name appears at the top of the business scheduling page. func (m *BookingBusiness) SetDisplayName(value *string)() { if m != nil { m.displayName = value } } // SetEmail sets the email property value. The email address for the business. func (m *BookingBusiness) SetEmail(value *string)() { if m != nil { m.email = value } } // SetIsPublished sets the isPublished property value. The scheduling page has been made available to external customers. Use the publish and unpublish actions to set this property. Read-only. func (m *BookingBusiness) SetIsPublished(value *bool)() { if m != nil { m.isPublished = value } } // SetPhone sets the phone property value. The telephone number for the business. The phone property, together with address and webSiteUrl, appear in the footer of a business scheduling page. func (m *BookingBusiness) SetPhone(value *string)() { if m != nil { m.phone = value } } // SetPublicUrl sets the publicUrl property value. The URL for the scheduling page, which is set after you publish or unpublish the page. Read-only. func (m *BookingBusiness) SetPublicUrl(value *string)() { if m != nil { m.publicUrl = value } } // SetSchedulingPolicy sets the schedulingPolicy property value. Specifies how bookings can be created for this business. func (m *BookingBusiness) SetSchedulingPolicy(value BookingSchedulingPolicyable)() { if m != nil { m.schedulingPolicy = value } } // SetServices sets the services property value. All the services offered by this business. Read-only. Nullable. func (m *BookingBusiness) SetServices(value []BookingServiceable)() { if m != nil { m.services = value } } // SetStaffMembers sets the staffMembers property value. All the staff members that provide services in this business. Read-only. Nullable. func (m *BookingBusiness) SetStaffMembers(value []BookingStaffMemberBaseable)() { if m != nil { m.staffMembers = value } } // SetWebSiteUrl sets the webSiteUrl property value. The URL of the business web site. The webSiteUrl property, together with address, phone, appear in the footer of a business scheduling page. func (m *BookingBusiness) SetWebSiteUrl(value *string)() { if m != nil { m.webSiteUrl = value } }
models/booking_business.go
0.541894
0.460532
booking_business.go
starcoder
package g2d import ( "math" ) var geometry_origin *Geometry // Geometry with only one vertex at (0,0) func NewGeometry_Origin() *Geometry { if geometry_origin == nil { // A singlton is shared for all the uses geometry_origin = NewGeometry().SetVertices([][2]float32{{0, 0}}) geometry_origin.BuildDataBuffers(true, false, false) } return geometry_origin } func NewGeometry_Rectangle(size float32) *Geometry { hs := size / 2 geometry := NewGeometry() // create an empty geometry geometry.SetVertices([][2]float32{{-hs, -hs}, {hs, -hs}, {hs, hs}, {-hs, hs}}) geometry.SetFaces([][]uint32{{0, 1, 2, 3}}) geometry.SetEdges([][]uint32{{0, 1, 2, 3}}) return geometry } func NewGeometry_Triangle(size float32) *Geometry { geometry := NewGeometry_Polygon(3, size, -30) // 3 vertices and 1 triangular face geometry.SetEdges([][]uint32{{0, 1, 2, 0}}) // 1 edge connecting all the vertices return geometry } func NewGeometry_Polygon(n int, radius float32, starting_angle_in_degree float32) *Geometry { geometry := NewGeometry() // create an empty geometry radian := float64(starting_angle_in_degree * (math.Pi / 180.0)) radian_step := (2 * math.Pi) / float64(n) face_indices := make([]uint32, n) for i := 0; i < n; i++ { geometry.AddVertex([2]float32{radius * float32(math.Cos(radian)), radius * float32(math.Sin(radian))}) face_indices[i] = uint32(i) radian += radian_step } geometry.AddFace(face_indices) return geometry } func NewGeometry_Arrow() *Geometry { geometry := NewGeometry() // ARROW pointing left, with tip at (0,0) and length 1.0 geometry.SetVertices([][2]float32{{0, 0}, {0.5, -0.3}, {0.5, -0.15}, {1, -0.15}, {1, 0.15}, {0.5, 0.15}, {0.5, 0.3}}) geometry.SetFaces([][]uint32{{0, 1, 2, 3, 4, 5, 6}}) geometry.SetEdges([][]uint32{{0, 1, 2, 3, 4, 5, 6, 0}}) return geometry } func NewGeometry_ArrowHead() *Geometry { geometry := NewGeometry() // ARROW_HEAD pointing left, with tip at (0,0) and length 1.0 geometry.SetVertices([][2]float32{{0, 0}, {1, -0.6}, {1, +0.6}}) geometry.SetFaces([][]uint32{{0, 1, 2}}) geometry.SetEdges([][]uint32{{0, 1, 2, 0}}) return geometry }
g2d/geometry_examples.go
0.807005
0.701662
geometry_examples.go
starcoder
package regressions import ( "io/ioutil" "log" "os" "path" "path/filepath" "testing" "github.com/sylabs/singularity/e2e/internal/e2e" "github.com/sylabs/singularity/e2e/internal/testhelper" ) type regressionsTests struct { env e2e.TestEnv } // This test will build an image from a multi-stage definition // file, the first stage compile a bad NSS library containing // a constructor forcing program to exit with code 255 when loaded, // the second stage will copy the bad NSS library in its root filesytem // to check that the post section executed by the build engine doesn't // load the bad NSS library from container image. // Most if not all NSS services point to the bad NSS library in // order to catch all the potential calls which could occur from // Go code inside the build engine, singularity engine is also tested. func (c regressionsTests) issue4203(t *testing.T) { image := filepath.Join(c.env.TestDir, "issue_4203.sif") c.env.RunSingularity( t, e2e.WithProfile(e2e.RootProfile), e2e.WithCommand("build"), e2e.WithArgs(image, "testdata/regressions/issue_4203.def"), e2e.PostRun(func(t *testing.T) { defer os.Remove(image) if t.Failed() { return } // also execute the image to check that singularity // engine doesn't try to load a NSS library from // container image c.env.RunSingularity( t, e2e.WithProfile(e2e.UserProfile), e2e.WithCommand("exec"), e2e.WithArgs(image, "true"), e2e.ExpectExit(0), ) }), e2e.ExpectExit(0), ) } // issue4407 checks that it's possible to build a sandbox image when the // destination directory contains a trailing slash and when it doesn't. func (c *regressionsTests) issue4407(t *testing.T) { e2e.EnsureImage(t, c.env) sandboxDir := func() string { name, err := ioutil.TempDir(c.env.TestDir, "sandbox.") if err != nil { log.Fatalf("failed to create temporary directory for sandbox: %v", err) } if err := os.Chmod(name, 0755); err != nil { log.Fatalf("failed to chmod temporary directory for sandbox: %v", err) } return name } tc := map[string]string{ "with slash": sandboxDir() + "/", "without slash": sandboxDir(), } for name, imagePath := range tc { args := []string{ "--force", "--sandbox", imagePath, c.env.ImagePath, } c.env.RunSingularity( t, e2e.AsSubtest(name), e2e.WithProfile(e2e.RootProfile), e2e.WithCommand("build"), e2e.WithArgs(args...), e2e.PostRun(func(t *testing.T) { if t.Failed() { return } defer os.RemoveAll(imagePath) c.env.ImageVerify(t, imagePath, e2e.RootProfile) }), e2e.ExpectExit(0), ) } } // This test will build a sandbox, as a non-root user from a dockerhub image // that contains a single folder and file with `000` permission. // It will verify that with `--fix-perms` we force files to be accessible, // moveable, removable by the user. We check for `700` and `400` permissions on // the folder and file respectively. func (c *regressionsTests) issue4524(t *testing.T) { sandbox := filepath.Join(c.env.TestDir, "issue_4524") c.env.RunSingularity( t, e2e.WithProfile(e2e.UserProfile), e2e.WithCommand("build"), e2e.WithArgs("--fix-perms", "--sandbox", sandbox, "docker://sylabsio/issue4524"), e2e.PostRun(func(t *testing.T) { // If we failed to build the sandbox completely, leave what we have for // investigation. if t.Failed() { t.Logf("Test %s failed, not removing directory %s", t.Name(), sandbox) return } if !e2e.PathPerms(t, path.Join(sandbox, "directory"), 0700) { t.Error("Expected 0700 permissions on 000 test directory in rootless sandbox") } if !e2e.PathPerms(t, path.Join(sandbox, "file"), 0600) { t.Error("Expected 0600 permissions on 000 test file in rootless sandbox") } // If the permissions aren't as we expect them to be, leave what we have for // investigation. if t.Failed() { t.Logf("Test %s failed, not removing directory %s", t.Name(), sandbox) return } err := os.RemoveAll(sandbox) if err != nil { t.Logf("Cannot remove sandbox directory: %#v", err) } }), e2e.ExpectExit(0), ) } // E2ETests is the main func to trigger the test suite func E2ETests(env e2e.TestEnv) func(*testing.T) { c := regressionsTests{ env: env, } return testhelper.TestRunner(map[string]func(*testing.T){ "issue 4203": c.issue4203, // https://github.com/sylabs/singularity/issues/4203 "issue 4407": c.issue4407, // https://github.com/sylabs/singularity/issues/4407 "issue 4524": c.issue4524, // https://github.com/sylabs/singularity/issues/4524 }) }
e2e/regressions/build.go
0.571408
0.499023
build.go
starcoder
package merkletree import ( "bytes" "crypto" ) // Verify returns true if the path given is valid. func (p Path) Verify1(leafContent []byte, hash crypto.Hash) (ok bool) { // Test plausibility of path. if !p.isPlausible() { return false } // Check if top element is ok. if !p[0].verifyMyLeafConstruction(leafContent, hash) { return false } return verifyPath(p, hash) } // verifyer assumes that the path is _plausible_. type verifyer struct { p Path hash crypto.Hash hashSize int mynode, leftNode, rightNode *PathElement // only debug } func verifyPath(p Path, hash crypto.Hash) (ok bool) { var hasBranch bool v := &verifyer{ p: p, hashSize: hash.New().Size(), hash: hash, } pos := 1 mynode := p[0] for hasBranch, mynode = v.genBranch(pos, mynode); hasBranch; hasBranch, mynode = v.genBranch(pos, mynode) { pos++ } rootNode, test := p.GetRoot() test = test && rootNode.IsLeft == mynode.IsLeft test = test && rootNode.IsLeaf == mynode.IsLeaf test = test && rootNode.Depths == mynode.Depths test = test && mynode.Depths == 0 if test { test = test && bytes.Equal(rootNode.Hash, mynode.Hash) } return test } func (v *verifyer) getNextSibling(pos int, mynode *PathElement) (sibling *PathElement) { if v.p[pos].Depths == mynode.Depths && v.p[pos].IsEmpty == false { // Found an entry, always ignore empty. sibling = v.p[pos] } else { sibling = emptyNode(!mynode.IsLeft, mynode.IsLeaf, mynode.Depths, v.hashSize, v.hash) } if mynode.Depths != sibling.Depths || sibling.IsLeft == mynode.IsLeft || mynode.IsLeaf != sibling.IsLeaf { panic("merkletree verification, genBranch, conflicting sibling. Programming error!") } return sibling } func (v *verifyer) sortNodes(a, b *PathElement) (leftNode, rightNode *PathElement) { if a.IsLeft { return a, b } return b, a } func (v *verifyer) nextNodeIsLeft(pos int, depths uint32) bool { if pos >= len(v.p) { // There are nodes left over. Must always be true on a plausible path. This is the Root check. panic("merkletree verification, genBranch, working on inplausible path. Programming error!") } if v.p[pos].Depths == depths { // Check if this branch is filled. if v.p[pos].Depths == 0 { // Root reached. It's always the last, and always on the left. return true } return !v.p[pos+1].IsLeft } if pos >= len(v.p)-1 { // There are nodes left over. Must always be true on a plausible path. This is if Root has not been reached. panic("merkletree verification, genBranch, working on inplausible path 2. Programming error!") } if v.p[pos+1].Depths == depths { // Check if next branch is filled. if v.p[pos+1].Depths == 0 { // Root reached. It's always the last, and always on the left. return true } return !v.p[pos+1].IsLeft } return true // Empty sibling means we're left. } func (v *verifyer) genBranch(pos int, mynode *PathElement) (ok bool, newNode *PathElement) { if mynode.Depths == 0 { return false, mynode } GeneratorLoop: for { sibling := v.getNextSibling(pos, mynode) leftnode, rightnode := v.sortNodes(sibling, mynode) isLeft := v.nextNodeIsLeft(pos, mynode.Depths-1) newNode = ParentPathElement(isLeft, leftnode, rightnode, v.hash) if newNode.Depths == 0 { // Root Reached. break GeneratorLoop } if newNode.Depths == v.p[pos+1].Depths { // Check if next node is depths of our, if not, we have to insert empties. break GeneratorLoop } else { mynode = newNode } } return true, newNode }
merkletree/verify1.go
0.606265
0.423756
verify1.go
starcoder
package path import ( "math/rand" "sync" "time" ) func init() { rand.Seed(time.Now().UnixNano()) } // TransitEdge is a direct transportation between two locations. type TransitEdge struct { VoyageNumber string `json:"voyage"` Origin string `json:"origin"` Destination string `json:"destination"` Departure time.Time `json:"departure"` Arrival time.Time `json:"arrival"` } // TransitPath is a series of transit edges. type TransitPath struct { Edges []TransitEdge `json:"edges"` } // FindShortestPath computes the shortest paths between two locations. func FindShortestPath(origin, destination string) []TransitPath { var candidates []TransitPath for p := range generateCandidates(origin, destination, 3+rand.Intn(3)) { candidates = append(candidates, p) } return candidates } // generateCandidates generates new candidates and pushes them into a channel. // Finding each candidate is potentially time-consuming, so we compute them in // parallel. func generateCandidates(origin, destination string, n int) chan TransitPath { ch := make(chan TransitPath) var wg sync.WaitGroup wg.Add(n) for i := 0; i < n; i++ { go func() { ch <- findCandidate(origin, destination, nextDate(time.Now())) wg.Done() }() } go func() { wg.Wait() close(ch) }() return ch } // findCandidate finds a random path between two locations starting from a // given time. func findCandidate(origin, destination string, start time.Time) TransitPath { v := allVertices(origin, destination) v = randChunk(v) var edges []TransitEdge edges, start = appendEdge(edges, origin, v[0], start) for j := 0; j < len(v)-1; j++ { edges, start = appendEdge(edges, v[j], v[j+1], start) } edges, _ = appendEdge(edges, v[len(v)-1], destination, start) return TransitPath{Edges: edges} } func appendEdge(edges []TransitEdge, curr, next string, date time.Time) ([]TransitEdge, time.Time) { var ( from = nextDate(date) to = nextDate(from) ) edges = append(edges, TransitEdge{ VoyageNumber: randVoyageNumber(), Origin: curr, Destination: next, Departure: from, Arrival: to, }) return edges, nextDate(to) } func allVertices(origin, destination string) []string { locations := []string{"CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL"} for i, l := range locations { if l == origin { locations = append(locations[:i], locations[i+1:]...) } } for i, l := range locations { if l == destination { locations = append(locations[:i], locations[i+1:]...) } } return locations } func randVoyageNumber() string { switch rand.Intn(5) { case 0: return "0100S" case 1: return "0200T" case 2: return "0300A" case 3: return "0301S" } return "0400S" } func randChunk(locations []string) []string { shuffle(locations) t := len(locations) var c int if t > 4 { c = 1 + rand.Intn(5) } else { c = t } return locations[:c] } func shuffle(slc []string) { for i := 1; i < len(slc); i++ { r := rand.Intn(i + 1) if i != r { slc[r], slc[i] = slc[i], slc[r] } } } func nextDate(t time.Time) time.Time { n := time.Duration(rand.Intn(1000) - 500) return t.Add(24 * time.Hour).Add(n * time.Minute) }
path/path.go
0.698227
0.50061
path.go
starcoder
package assert import ( "strings" "testing" "github.com/ppapapetrou76/go-testing/internal/pkg/values" ) // StringOpt is a configuration option to initialize an AssertableString. type StringOpt func(*AssertableString) // AssertableString is the implementation of CommonAssertable for string types. type AssertableString struct { t *testing.T actual values.StringValue } // IgnoringCase sets underlying value to lower case. func IgnoringCase() StringOpt { return func(c *AssertableString) { c.actual = c.actual.AddDecorator(strings.ToLower) } } // IgnoringWhiteSpaces removes the whitespaces from the value under assertion. func IgnoringWhiteSpaces() StringOpt { return func(c *AssertableString) { c.actual = c.actual.AddDecorator(values.RemoveSpaces) } } // ThatString returns an AssertableString structure initialized with the test reference and the actual value to assert. func ThatString(t *testing.T, actual string, opts ...StringOpt) AssertableString { t.Helper() assertable := &AssertableString{ t: t, actual: values.NewStringValue(actual), } for _, opt := range opts { if opt != nil { opt(assertable) } } return *assertable } // IsEqualTo asserts if the expected string is equal to the assertable string value // It errors the tests if the compared values (actual VS expected) are not equal. func (a AssertableString) IsEqualTo(expected interface{}) AssertableString { a.t.Helper() if !a.actual.IsEqualTo(expected) { a.t.Error(shouldBeEqual(a.actual, expected)) } return a } // IsNotEqualTo asserts if the expected string is not equal to the assertable string value // It errors the tests if the compared values (actual VS expected) are equal. func (a AssertableString) IsNotEqualTo(expected interface{}) AssertableString { a.t.Helper() if a.actual.IsEqualTo(expected) { a.t.Error(shouldNotBeEqual(a.actual, expected)) } return a } // IsEmpty asserts if the expected string is empty // It errors the tests if the string is not empty. func (a AssertableString) IsEmpty() AssertableString { a.t.Helper() if a.actual.IsNotEmpty() { a.t.Error(shouldBeEmpty(a.actual)) } return a } // IsLowerCase asserts if the expected string is lower case // It errors the tests if the string is not lower case. func (a AssertableString) IsLowerCase() AssertableString { a.t.Helper() if !a.actual.IsLowerCase() { a.t.Error(shouldBeLowerCase(a.actual)) } return a } // IsUpperCase asserts if the expected string is upper case // It errors the tests if the string is not upper case. func (a AssertableString) IsUpperCase() AssertableString { a.t.Helper() if !a.actual.IsUpperCase() { a.t.Error(shouldBeUpperCase(a.actual)) } return a } // IsNotEmpty asserts if the expected string is not empty // It errors the tests if the string is empty. func (a AssertableString) IsNotEmpty() AssertableString { a.t.Helper() if a.actual.IsEmpty() { a.t.Error(shouldNotBeEmpty(a.actual)) } return a } // Contains asserts if the assertable string contains the given element(s) // It errors the test if it does not contain it. func (a AssertableString) Contains(substring string) AssertableString { a.t.Helper() if a.actual.DoesNotContain(substring) { a.t.Error(shouldContain(a.actual, substring)) } return a } // ContainsIgnoringCase asserts if the assertable string contains the given element(s) case insensitively // It errors the test if it does not contain it. func (a AssertableString) ContainsIgnoringCase(substring string) AssertableString { a.t.Helper() if !a.actual.ContainsIgnoringCase(substring) { a.t.Error(shouldContainIgnoringCase(a.actual, substring)) } return a } // ContainsOnly asserts if the assertable string only contains the given substring // It errors the test if it does not contain it. func (a AssertableString) ContainsOnly(substring string) AssertableString { a.t.Helper() if !a.actual.ContainsOnly(substring) { a.t.Error(shouldContainOnly(a.actual, substring)) } return a } // ContainsOnlyOnce asserts if the assertable string contains the given substring only once // It errors the test if it does not contain it or contains more than once. func (a AssertableString) ContainsOnlyOnce(substring string) AssertableString { a.t.Helper() if !a.actual.ContainsOnlyOnce(substring) { a.t.Error(shouldContainOnlyOnce(a.actual, substring)) } return a } // ContainsWhitespaces asserts if the assertable string contains at least one whitespace // It errors the test if it does not contain any. func (a AssertableString) ContainsWhitespaces() AssertableString { a.t.Helper() if !a.actual.ContainsWhitespaces() { a.t.Error(shouldContainWhiteSpace(a.actual)) } return a } // DoesNotContainAnyWhitespaces asserts if the assertable string contains no whitespace // It errors the test if it does contain any. func (a AssertableString) DoesNotContainAnyWhitespaces() AssertableString { a.t.Helper() if a.actual.ContainsWhitespaces() { a.t.Error(shouldNotContainAnyWhiteSpace(a.actual)) } return a } // ContainsOnlyWhitespaces asserts if the assertable string contains only whitespaces // It errors the test if it contains any other character. func (a AssertableString) ContainsOnlyWhitespaces() AssertableString { a.t.Helper() if !a.actual.ContainsOnlyWhitespaces() { a.t.Error(shouldContainOnlyWhiteSpaces(a.actual)) } return a } // DoesNotContainOnlyWhitespaces asserts if the assertable string does not contain only whitespaces // It errors the test if it contains only whitespaces. func (a AssertableString) DoesNotContainOnlyWhitespaces() AssertableString { a.t.Helper() if a.actual.ContainsOnlyWhitespaces() { a.t.Error(shouldNotContainOnlyWhiteSpaces(a.actual)) } return a } // DoesNotContain asserts if the assertable string does not contain the given substring // It errors the test if it contains it. func (a AssertableString) DoesNotContain(substring string) AssertableString { a.t.Helper() if a.actual.Contains(substring) { a.t.Error(shouldNotContain(a.actual, substring)) } return a } // StartsWith asserts if the assertable string starts with the given substring // It errors the test if it doesn't start with the given substring. func (a AssertableString) StartsWith(substring string) AssertableString { a.t.Helper() if !a.actual.StartsWith(substring) { a.t.Error(shouldStartWith(a.actual, substring)) } return a } // DoesNotStartWith asserts if the assertable string doesn't start with the given substring // It errors the test if it starts with the given substring. func (a AssertableString) DoesNotStartWith(substring string) AssertableString { a.t.Helper() if a.actual.StartsWith(substring) { a.t.Error(shouldNotStartWith(a.actual, substring)) } return a } // EndsWith asserts if the assertable string ends with the given substring // It errors the test if it doesn't end with the given substring. func (a AssertableString) EndsWith(substring string) AssertableString { a.t.Helper() if !a.actual.EndsWith(substring) { a.t.Error(shouldEndWith(a.actual, substring)) } return a } // DoesNotEndWith asserts if the assertable string doesn't end with the given substring // It errors the test if it end with the given substring. func (a AssertableString) DoesNotEndWith(substring string) AssertableString { a.t.Helper() if a.actual.EndsWith(substring) { a.t.Error(shouldNotEndWith(a.actual, substring)) } return a } // HasSameSizeAs asserts if the assertable string has the same size with the given string // It errors the test if they don't have the same size. func (a AssertableString) HasSameSizeAs(substring string) AssertableString { a.t.Helper() if !(a.actual.HasSize(len(substring))) { a.t.Error(shouldHaveSameSizeAs(a.actual, substring)) } return a } // HasSizeBetween asserts if the assertable string has bigger size of the first given string and less size than the second given string // It errors the test if the assertable string has the same or less size than the first string or greater than or the same size to the second string. func (a AssertableString) HasSizeBetween(shortString, longString string) AssertableString { a.t.Helper() if a.actual.HasSizeLessThanOrEqual(len(shortString)) || a.actual.HasSizeGreaterThanOrEqual(len(longString)) { a.t.Error(shouldHaveSizeBetween(a.actual, shortString, longString)) } return a } // HasSizeGreaterThan asserts if the assertable string has bigger size of the given string // It errors the test if the assertable string has the less or equal size to the given one. func (a AssertableString) HasSizeGreaterThan(substring string) AssertableString { a.t.Helper() if !(a.actual.HasSizeGreaterThan(len(substring))) { a.t.Error(shouldHaveGreaterSizeThan(a.actual, substring)) } return a } // HasSizeGreaterThanOrEqualTo asserts if the assertable string has bigger os the same size of the given string // It errors the test if the assertable string has the less size to the given one. func (a AssertableString) HasSizeGreaterThanOrEqualTo(substring string) AssertableString { a.t.Helper() if !(a.actual.HasSizeGreaterThanOrEqual(len(substring))) { a.t.Error(shouldHaveGreaterSizeThanOrEqual(a.actual, substring)) } return a } // HasSizeLessThan asserts if the assertable string's length is less than the size of the given string // It errors the test if they don't have the same size. func (a AssertableString) HasSizeLessThan(substring string) AssertableString { a.t.Helper() if !(a.actual.HasSizeLessThan(len(substring))) { a.t.Error(shouldHaveLessSizeThan(a.actual, substring)) } return a } // HasSizeLessThanOrEqualTo asserts if the assertable string's length is less than or equal to the size of the given string // It errors the test if they don't have the same size. func (a AssertableString) HasSizeLessThanOrEqualTo(substring string) AssertableString { a.t.Helper() if !(a.actual.HasSizeLessThanOrEqual(len(substring))) { a.t.Error(shouldHaveLessSizeThanOrEqual(a.actual, substring)) } return a } // ContainsOnlyDigits asserts if the expected string contains only digits // It errors the tests if the string has other characters than digits. func (a AssertableString) ContainsOnlyDigits() AssertableString { a.t.Helper() if !(a.actual.HasDigitsOnly()) { a.t.Error(shouldContainOnlyDigits(a.actual)) } return a }
assert/string.go
0.797202
0.664778
string.go
starcoder
package money import ( "fmt" "math" "math/big" "github.com/wadey/go-rounding" ) // some operations var bigOne = big.NewInt(1) // temporary, before https://github.com/wadey/go-rounding/pull/6 is merged func roundToInt(rat *big.Rat, method rounding.RoundingMode) *big.Int { c := new(big.Rat).Set(rat) rounding.Round(c, 0, method) if !c.IsInt() { // this should never happen panic(fmt.Errorf("unexpected unrounded rational")) } // as c is int, denominator is 1 and numerator is the int value return c.Num() } // SameCurrency check if given Money has the same currency func (m Money) SameCurrency(om Money) bool { return m.currency == om.currency // note that comparing structs compares fields } func (m Money) assertSameCurrency(om Money) error { same := m.SameCurrency(om) if !same { return fmt.Errorf( "currencies %s and %s don't match", m.currency.String(), om.currency.String(), ) } return nil } func (m Money) compare(om Money) int { return m.getMinorAmount().Cmp(om.getMinorAmount()) } // Equals checks equality between two Money types. // Returns error if different currencies. func (m Money) Equals(om Money) (bool, error) { if err := m.assertSameCurrency(om); err != nil { return false, err } return m.compare(om) == 0, nil } // More checks whether the value of Money is greater than the other. // Returns error if different currencies. func (m Money) More(om Money) (bool, error) { if err := m.assertSameCurrency(om); err != nil { return false, err } return m.compare(om) == 1, nil } // MoreEqual checks whether the value of Money is greater or equal than the other. // Returns error if different currencies. func (m Money) MoreEqual(om Money) (bool, error) { if err := m.assertSameCurrency(om); err != nil { return false, err } return m.compare(om) >= 0, nil } // Less checks whether the value of Money is less than the other. // Returns error if different currencies. func (m Money) Less(om Money) (bool, error) { if err := m.assertSameCurrency(om); err != nil { return false, err } return m.compare(om) == -1, nil } // Between checks whether the value of Money is between two values, both ends inclusive. // Returns error if different currencies, or min > max func (m Money) Between(min, max Money) (bool, error) { isInterval, err := min.LessEqual(max) if err != nil { return false, err } if !isInterval { return false, fmt.Errorf("minimal is bigger than maximal") } more, err := m.MoreEqual(min) if err != nil { return false, err } less, err := m.LessEqual(max) if err != nil { return false, err } return more && less, nil } // LessEqual checks whether the value of Money is less or equal than the other. // Returns error if different currencies. func (m Money) LessEqual(om Money) (bool, error) { if err := m.assertSameCurrency(om); err != nil { return false, err } return m.compare(om) <= 0, nil } // IsZero returns boolean of whether the value of Money is equals to zero. func (m Money) IsZero() bool { return m.getMinorAmount().Cmp(new(big.Int)) == 0 } // IsPositive returns boolean of whether the value of Money is positive. func (m Money) IsPositive() bool { return m.getMinorAmount().Cmp(new(big.Int)) > 0 } // IsNegative returns boolean of whether the value of Money is negative. func (m Money) IsNegative() bool { return m.getMinorAmount().Cmp(new(big.Int)) < 0 } // Absolute returns new Money struct from given Money using absolute monetary value. func (m Money) Absolute() *Money { r := (new(big.Int)).Abs(m.getMinorAmount()) return &Money{minorAmount: r, currency: m.currency} } // Negative returns new Money struct from given Money using negative monetary value. func (m Money) Negative() *Money { r := (new(big.Int)).Neg(m.getMinorAmount()) return &Money{minorAmount: r, currency: m.currency} } // Add returns new Money struct with value representing sum of Self and Other Money. // Returns error if different currencies. func (m Money) Add(om Money) (*Money, error) { if err := m.assertSameCurrency(om); err != nil { return nil, err } r := (new(big.Int)).Add(m.getMinorAmount(), om.getMinorAmount()) return &Money{minorAmount: r, currency: m.currency}, nil } // Subtract returns new Money struct with value representing difference of Self and Other Money. func (m Money) Subtract(om Money) (*Money, error) { if err := m.assertSameCurrency(om); err != nil { return nil, err } omNeg := (new(big.Int)).Neg(om.getMinorAmount()) r := (new(big.Int)).Add(m.getMinorAmount(), omNeg) return &Money{minorAmount: r, currency: m.currency}, nil } // Multiply returns new Money struct with value representing Self multiplied value by multiplier. func (m Money) Multiply(mul int64) (*Money, error) { r := (new(big.Int)).Mul(m.getMinorAmount(), big.NewInt(mul)) return &Money{minorAmount: r, currency: m.currency}, nil } // Divide divides. NOTE: You might want to use Split instead. func (m Money) Divide(d int64, round rounding.RoundingMode) (*Money, error) { if d == 0 { return nil, fmt.Errorf("division by zero") } rat := (new(big.Rat)).SetFrac(bigOne, big.NewInt(d)) return m.MultiplyBigRat(rat, round), nil } // MultiplyRat returns new Money struct with value representing Self multiplied value by multiplier, // that is a rational string. // All inputs that are allowed in big.Rat are allowed - including "1/3" func (m Money) MultiplyRat(ratString string, round rounding.RoundingMode) (*Money, error) { rat, ok := (new(big.Rat)).SetString(ratString) if !ok { return nil, fmt.Errorf("%s is not a valid rational amount", ratString) } return m.MultiplyBigRat(rat, round), nil } // MultiplyBigRat returns new Money struct with value representing Self multiplied value by // big.Rat value func (m Money) MultiplyBigRat(rat *big.Rat, round rounding.RoundingMode) *Money { if rat == nil { return m.currency.zero() } a := (new(big.Rat)).SetInt(m.getMinorAmount()) c := a.Mul(a, rat) minor := roundToInt(c, round) return &Money{minorAmount: minor, currency: m.currency} } // DivideRat returns new Money struct with value representing Self divided value by divider, // that is a rational string.. // All inputs that are allowed in big.Rat are allowed - // including "1/3" - which would multiply by 3. func (m Money) DivideRat(ratString string, round rounding.RoundingMode) (*Money, error) { rat, ok := (new(big.Rat)).SetString(ratString) if !ok { return nil, fmt.Errorf("%s is not a valid rational amount", ratString) } if rat.Sign() == 0 { return nil, fmt.Errorf("division by zero") } return m.DivideBigRat(rat, round) } // DivideBigRat returns new Money struct with value representing Self divided value by big.Rat. func (m Money) DivideBigRat(rat *big.Rat, round rounding.RoundingMode) (*Money, error) { if rat == nil { return nil, fmt.Errorf("nil rational") } if rat.Sign() == 0 { return nil, fmt.Errorf("division by zero") } a := (new(big.Rat)).SetInt(m.getMinorAmount()) c := a.Quo(a, rat) minor := roundToInt(c, round) return &Money{minorAmount: minor, currency: m.currency}, nil } // HasCents returns true if the value is not rounded to major units func (m Money) HasCents() (bool, error) { dec := m.currency.Decimals if dec == 0 { return false, nil } rounded := m.RoundToMajor(rounding.Down) k, err := m.Subtract(*rounded) if err != nil { return false, err } isZero := k.IsZero() return !isZero, nil } // LessMajor checks whether the value of Money is less than an int, in major value. func (m Money) LessMajor(i int64) bool { other := FromMajorInt(i, m.currency) return m.compare(*other) == -1 } // MoreMajor checks whether the value of Money is more than an int, in major value. func (m Money) MoreMajor(i int64) bool { other := FromMajorInt(i, m.currency) return m.compare(*other) == 1 } // LessEqualMajor checks whether the value of Money is less or equal than an int, in major value. func (m Money) LessEqualMajor(i int64) bool { other := FromMajorInt(i, m.currency) return m.compare(*other) <= 0 } // MoreEqualMajor checks whether the value of Money is more or equal than an int, in major value. func (m Money) MoreEqualMajor(i int64) bool { other := FromMajorInt(i, m.currency) return m.compare(*other) >= 0 } // BetweenMajor checks whether the value of Money is between two ints, in major value. // Returns error if min > max func (m Money) BetweenMajor(min, max int64) (bool, error) { minM := FromMajorInt(min, m.currency) maxM := FromMajorInt(max, m.currency) is, err := m.Between(*minM, *maxM) if err != nil { return false, err } return is, nil } // LessMinor checks whether the value of Money is less than an int, in minor value. func (m Money) LessMinor(i int64) bool { other := FromMinorInt(i, m.currency) return m.compare(*other) == -1 } // MoreMinor checks whether the value of Money is more than an int, in minor value. func (m Money) MoreMinor(i int64) bool { other := FromMinorInt(i, m.currency) return m.compare(*other) == 1 } // LessEqualMinor checks whether the value of Money is less or equal than an int, in minor value. func (m Money) LessEqualMinor(i int64) bool { other := FromMinorInt(i, m.currency) return m.compare(*other) <= 0 } // MoreEqualMinor checks whether the value of Money is more or equal than an int, in minor value. func (m Money) MoreEqualMinor(i int64) bool { other := FromMinorInt(i, m.currency) return m.compare(*other) >= 0 } // BetweenMinor checks whether the value of Money is between two ints, in minor value. // Returns error if min > max func (m Money) BetweenMinor(min, max int64) (bool, error) { minM := FromMinorInt(min, m.currency) maxM := FromMinorInt(max, m.currency) is, err := m.Between(*minM, *maxM) if err != nil { return false, err } return is, nil } // RoundToMajor returns new Money struct with value rounded to major unit and with a given // strategy func (m Money) RoundToMajor(round rounding.RoundingMode) *Money { dec := m.currency.Decimals if dec == 0 { return &m } exp := big.NewInt(int64(math.Pow10(dec))) rat := (new(big.Rat)).SetFrac(m.getMinorAmount(), exp) i := roundToInt(rat, round) i = i.Mul(i, exp) return &Money{minorAmount: i, currency: m.currency} } // Split returns slice of Money structs with split Self value in given number. // After division leftover pennies will be distributed round-robin amongst the parties. // This means that parties listed first can receive more pennies than ones that are listed later. func (m Money) Split(n int) ([]*Money, error) { if n <= 0 { return nil, fmt.Errorf("split must be higher than zero, is %d", n) } fl := m.getMinorAmount() neg := m.IsNegative() if neg { fl = (new(big.Int)).Neg(fl) } quo, rem := (new(big.Int)).QuoRem(fl, big.NewInt(int64(n)), new(big.Int)) ms := make([]*Money, 0, n) for i := 0; i < n; i++ { ms = append(ms, &Money{minorAmount: (new(big.Int)).Set(quo), currency: m.currency}) } l := int(rem.Int64()) // Add leftovers to the first parties. for p := 0; l != 0; p++ { ms[p].minorAmount = ms[p].minorAmount.Add(ms[p].minorAmount, bigOne) l-- } if neg { for i := 0; i < n; i++ { ms[i].minorAmount = ms[i].minorAmount.Neg(ms[i].minorAmount) } } return ms, nil } // Allocate returns slice of Money structs with split Self value in given ratios. // It lets split money by given ratios without losing pennies and as Split operations distributes // leftover pennies amongst the parties with round-robin principle. func (m Money) Allocate(rs ...int) ([]*Money, error) { if len(rs) == 0 { return nil, fmt.Errorf("no ratios specified") } fl := m.getMinorAmount() neg := m.IsNegative() if neg { fl = (new(big.Int)).Neg(fl) } // Calculate sum of ratios. var sum int for _, r := range rs { sum += r } total := new(big.Int) ms := make([]*Money, 0, len(rs)) for _, r := range rs { mul := (new(big.Int)).Mul(fl, big.NewInt(int64(r))) quo := (new(big.Int)).Quo(mul, big.NewInt(int64(sum))) party := &Money{ minorAmount: quo, currency: m.currency, } ms = append(ms, party) total = total.Add(total, quo) } // Calculate leftover value and divide to first parties. lo := (new(big.Int)).Sub(fl, total) l := lo.Int64() // Add leftovers to the first parties. for p := 0; l != 0; p++ { ms[p].minorAmount = ms[p].minorAmount.Add(ms[p].minorAmount, bigOne) l-- } if neg { for i := 0; i < len(rs); i++ { ms[i].minorAmount = ms[i].minorAmount.Neg(ms[i].minorAmount) } } return ms, nil }
operations.go
0.885582
0.569853
operations.go
starcoder
package main import ( "fmt" "math" "math/rand" "github.com/MattSwanson/raylib-go/raylib" "github.com/jakecoffman/cp" ) var grabbableMaskBit uint = 1 << 31 var grabFilter = cp.ShapeFilter{ cp.NO_GROUP, grabbableMaskBit, grabbableMaskBit, } func randUnitCircle() cp.Vector { v := cp.Vector{X: rand.Float64()*2.0 - 1.0, Y: rand.Float64()*2.0 - 1.0} if v.LengthSq() < 1.0 { return v } return randUnitCircle() } var simpleTerrainVerts = []cp.Vector{ {350.00, 425.07}, {336.00, 436.55}, {272.00, 435.39}, {258.00, 427.63}, {225.28, 420.00}, {202.82, 396.00}, {191.81, 388.00}, {189.00, 381.89}, {173.00, 380.39}, {162.59, 368.00}, {150.47, 319.00}, {128.00, 311.55}, {119.14, 286.00}, {126.84, 263.00}, {120.56, 227.00}, {141.14, 178.00}, {137.52, 162.00}, {146.51, 142.00}, {156.23, 136.00}, {158.00, 118.27}, {170.00, 100.77}, {208.43, 84.00}, {224.00, 69.65}, {249.30, 68.00}, {257.00, 54.77}, {363.00, 45.94}, {374.15, 54.00}, {386.00, 69.60}, {413.00, 70.73}, {456.00, 84.89}, {468.09, 99.00}, {467.09, 123.00}, {464.92, 135.00}, {469.00, 141.03}, {497.00, 148.67}, {513.85, 180.00}, {509.56, 223.00}, {523.51, 247.00}, {523.00, 277.00}, {497.79, 311.00}, {478.67, 348.00}, {467.90, 360.00}, {456.76, 382.00}, {432.95, 389.00}, {417.00, 411.32}, {373.00, 433.19}, {361.00, 430.02}, {350.00, 425.07}, } // creates a circle with random placement func addCircle(space *cp.Space, radius float64) { mass := radius * radius / 25.0 body := space.AddBody(cp.NewBody(mass, cp.MomentForCircle(mass, 0, radius, cp.Vector{}))) body.SetPosition(randUnitCircle().Mult(180)) shape := space.AddShape(cp.NewCircle(body, radius, cp.Vector{})) shape.SetElasticity(0) shape.SetFriction(0.9) } // creates a simple terrain to contain bodies func simpleTerrain() *cp.Space { space := cp.NewSpace() space.Iterations = 10 space.SetGravity(cp.Vector{0, -100}) space.SetCollisionSlop(0.5) offset := cp.Vector{X: -320, Y: -240} for i := 0; i < len(simpleTerrainVerts)-1; i++ { a := simpleTerrainVerts[i] b := simpleTerrainVerts[i+1] space.AddShape(cp.NewSegment(space.StaticBody, a.Add(offset), b.Add(offset), 0)) } return space } func main() { const width, height = 800, 450 const physicsTickrate = 1.0 / 60.0 rl.SetConfigFlags(rl.FlagVsyncHint) rl.InitWindow(width, height, "raylib [physics] example - chipmunk") offset := rl.Vector2{X: width / 2, Y: height / 2} // since the example ported from elsewhere, flip the camera 180 and offset to center it camera := rl.NewCamera2D(offset, rl.Vector2{}, 180, 1) space := simpleTerrain() for i := 0; i < 1000; i++ { addCircle(space, 5) } mouseBody := cp.NewKinematicBody() var mouse cp.Vector var mouseJoint *cp.Constraint var accumulator, dt float32 lastTime := rl.GetTime() for !rl.WindowShouldClose() { // calculate dt now := rl.GetTime() dt = now - lastTime lastTime = now // update the mouse position mousePos := rl.GetMousePosition() // alter the mouse coordinates based on the camera position, rotation mouse.X = float64(mousePos.X-camera.Offset.X) * -1 mouse.Y = float64(mousePos.Y-camera.Offset.Y) * -1 // smooth mouse movements to new position newPoint := mouseBody.Position().Lerp(mouse, 0.25) mouseBody.SetVelocityVector(newPoint.Sub(mouseBody.Position()).Mult(60.0)) mouseBody.SetPosition(newPoint) // handle grabbing if rl.IsMouseButtonPressed(rl.MouseLeftButton) { result := space.PointQueryNearest(mouse, 5, grabFilter) if result.Shape != nil && result.Shape.Body().Mass() < cp.INFINITY { var nearest cp.Vector if result.Distance > 0 { nearest = result.Point } else { nearest = mouse } // create a new constraint where the mouse is to draw the body towards the mouse body := result.Shape.Body() mouseJoint = cp.NewPivotJoint2(mouseBody, body, cp.Vector{}, body.WorldToLocal(nearest)) mouseJoint.SetMaxForce(50000) mouseJoint.SetErrorBias(math.Pow(1.0-0.15, 60.0)) space.AddConstraint(mouseJoint) } } else if rl.IsMouseButtonReleased(rl.MouseLeftButton) && mouseJoint != nil { space.RemoveConstraint(mouseJoint) mouseJoint = nil } // perform a fixed rate physics tick accumulator += dt for accumulator >= physicsTickrate { space.Step(physicsTickrate) accumulator -= physicsTickrate } rl.BeginDrawing() rl.ClearBackground(rl.RayWhite) rl.BeginMode2D(camera) // this is a generic way to iterate over the shapes in a space, // to avoid the type switch just keep a pointer to the shapes when they've been created space.EachShape(func(s *cp.Shape) { switch s.Class.(type) { case *cp.Segment: segment := s.Class.(*cp.Segment) a := segment.A() b := segment.B() rl.DrawLineV(v(a), v(b), rl.Black) case *cp.Circle: circle := s.Class.(*cp.Circle) pos := circle.Body().Position() rl.DrawCircleV(v(pos), float32(circle.Radius()), rl.Red) default: fmt.Println("unexpected shape", s.Class) } }) rl.EndMode2D() rl.DrawFPS(0, 0) rl.EndDrawing() } rl.CloseWindow() } func v(v cp.Vector) rl.Vector2 { return rl.Vector2{X: float32(v.X), Y: float32(v.Y)} }
examples/physics/chipmunk/main.go
0.62395
0.526586
main.go
starcoder
package message import ( "github.com/woojiahao/torrent.go/internal/message" . "github.com/woojiahao/torrent.go/internal/utility" "testing" ) type testType func(*testing.T, int, message.MessageID, ...byte) var block = []byte{25, 69, 112, 187, 115, 1, 0, 255, 199, 100, 1, 0} // Test with payload of <index><begin><length> func testWithPayload(t *testing.T, lengthPrefix int, id message.MessageID, test testType) { generatePayload := func(index, begin, length int) []byte { buf := make([]byte, 0, 12) buf = append(buf, ToBigEndian(index, 4)...) buf = append(buf, ToBigEndian(begin, 4)...) buf = append(buf, ToBigEndian(length, 4)...) return buf } for index := 1; index <= 100; index++ { for begin := 1; begin <= 100; begin++ { for length := 1; length <= 100; length++ { payload := generatePayload(index, begin, length) test(t, lengthPrefix, id, payload...) } } } } func testHave(t *testing.T, test testType) { for index := 0; index < 9999; index++ { test(t, 5, message.HaveID, ToBigEndian(index, 4)...) } } func testPiece(t *testing.T, test testType) { generatePiece := func(index, begin int) []byte { buf := make([]byte, 0, 8+len(block)) buf = append(buf, ToBigEndian(index, 4)...) buf = append(buf, ToBigEndian(begin, 4)...) buf = append(buf, block...) return buf } for index := 1; index < 99; index++ { for begin := 1; begin < 99; begin++ { piece := generatePiece(index, begin) test(t, 9+len(block), message.PieceID, piece...) } } } func testBitfield(t *testing.T, test testType) { generateBitfield := func(initial byte, size int) []byte { bitfield := make([]byte, size) for i := range bitfield { bitfield[i] = initial } return bitfield } for size := 1; size < 50; size++ { for initial := 1; initial < 100; initial++ { bitfield := generateBitfield(byte(initial), size) test(t, 1+len(bitfield), message.BitfieldID, bitfield...) } } } func testPort(t *testing.T, test testType) { for port1 := 0; port1 < 100; port1++ { for port2 := 0; port2 < 100; port2++ { test(t, 3, message.PortID, byte(port1), byte(port2)) } } }
test/message/utility.go
0.639061
0.4081
utility.go
starcoder
package Challenge3_Cycle_in_a_Circular_Array /* We are given an array containing positive and negative numbers. Suppose the array contains a number ‘M’ at a particular index. Now, if ‘M’ is positive we will move forward ‘M’ indices and if ‘M’ is negative move backwards ‘M’ indices. You should assume that the array is circular which means two things: 1. If, while moving forward, we reach the end of the array, we will jump to the first element to continue the movement. 2. If, while moving backward, we reach the beginning of the array, we will jump to the last element to continue the movement. Write a method to determine if the array has a cycle. The cycle should have more than one element and should follow one direction which means the cycle should not contain both forward and backward movements. Input: [1, 2, -1, 2, 2] Output: true Explanation: The array has a cycle among indices: 0 -> 1 -> 3 -> 0 Input: [2, 2, -1, 2] Output: true Explanation: The array has a cycle among indices: 1 -> 3 -> 1 Input: [2, 1, -1, -2] Output: false Explanation: The array does not have any cycle. */ func findNextIndex(arr []int, isForward bool, currentIndex int) int { var direction = arr[currentIndex] >= 0 if isForward != direction { return -1 } nextIndex := (currentIndex + arr[currentIndex] + len(arr)) % len(arr) if nextIndex == currentIndex { nextIndex = -1 } return nextIndex } func loopExists(arr []int) bool { for i := 0; i < len(arr); i++ { isForward := arr[i] >= 0 slow, fast := i, i // 先进行一次move slow = findNextIndex(arr, isForward, slow) fast = findNextIndex(arr, isForward, fast) if fast != -1 { fast = findNextIndex(arr, isForward, fast) } for slow != -1 && fast != -1 && fast != slow { slow = findNextIndex(arr, isForward, slow) fast = findNextIndex(arr, isForward, fast) if fast != -1 { fast = findNextIndex(arr, isForward, fast) } } // 追逐直到汇聚的时候,如果fast和slow的方向都不变且没有单元素的环则说明符合要求 if slow != -1 && fast == slow { return true } } return false }
Pattern03 - Fast and Slow pointers/Challenge3-Cycle_in_a_Circular_Array/solution.go
0.750827
0.873323
solution.go
starcoder
package boolean import ( "sync" ) // MutexMatrix a matrix wrapper that has a mutex lock support type MutexMatrix struct { sync.RWMutex matrix Matrix } // NewMutexMatrix returns a MutexMatrix func NewMutexMatrix(matrix Matrix) *MutexMatrix { return &MutexMatrix{ matrix: matrix, } } // Columns the number of columns of the matrix func (s *MutexMatrix) Columns() int { return s.matrix.Columns() } // Rows the number of rows of the matrix func (s *MutexMatrix) Rows() int { return s.matrix.Rows() } // Update does a At and Set on the matrix element at r-th, c-th func (s *MutexMatrix) Update(r, c int, f func(bool) bool) { s.Lock() defer s.Unlock() s.matrix.Update(r, c, f) } // At returns the value of a matrix element at r-th, c-th func (s *MutexMatrix) At(r, c int) bool { s.RLock() defer s.RUnlock() return s.matrix.At(r, c) } // Set sets the value at r-th, c-th of the matrix func (s *MutexMatrix) Set(r, c int, value bool) { s.Lock() defer s.Unlock() s.matrix.Set(r, c, value) } // ColumnsAt return the columns at c-th func (s *MutexMatrix) ColumnsAt(c int) Vector { s.RLock() defer s.RUnlock() return s.matrix.ColumnsAt(c) } // RowsAt return the rows at r-th func (s *MutexMatrix) RowsAt(r int) Vector { s.RLock() defer s.RUnlock() return s.matrix.RowsAt(r) } // RowsAtToArray return the rows at r-th func (s *MutexMatrix) RowsAtToArray(r int) []bool { s.RLock() defer s.RUnlock() return s.matrix.RowsAtToArray(r) } // Copy copies the matrix func (s *MutexMatrix) Copy() Matrix { s.RLock() defer s.RUnlock() return s.matrix.Copy() } // Transpose swaps the rows and columns func (s *MutexMatrix) Transpose() Matrix { s.RLock() defer s.RUnlock() return s.matrix.Transpose() } // Equal the two matrices are equal func (s *MutexMatrix) Equal(m Matrix) bool { s.RLock() defer s.RUnlock() return s.matrix.Equal(m) } // NotEqual the two matrices are not equal func (s *MutexMatrix) NotEqual(m Matrix) bool { s.RLock() defer s.RUnlock() return s.matrix.NotEqual(m) } // Size of the matrix func (s *MutexMatrix) Size() int { return s.matrix.Size() } // Values the number of elements in the matrix func (s *MutexMatrix) Values() int { return s.matrix.Values() } // Clear removes all elements from a matrix func (s *MutexMatrix) Clear() { s.RLock() defer s.RUnlock() s.matrix.Clear() } // Enumerate iterates through all non-zero elements, order is not guaranteed func (s *MutexMatrix) Enumerate() Enumerate { return s.matrix.Enumerate() } // Map replace each element with the result of applying a function to its value func (s *MutexMatrix) Map() Map { return s.matrix.Map() } // Element of the mask for each tuple that exists in the matrix for which the value of the tuple cast to Boolean is true func (s *MutexMatrix) Element(r, c int) bool { s.RLock() defer s.RUnlock() return s.matrix.Element(r, c) }
boolean/mutexMatrix.go
0.860618
0.52141
mutexMatrix.go
starcoder
package diff import ( "github.com/dolthub/dolt/go/libraries/doltcore/row" "github.com/dolthub/dolt/go/libraries/doltcore/rowconv" "github.com/dolthub/dolt/go/libraries/doltcore/schema" "github.com/dolthub/dolt/go/libraries/doltcore/table/pipeline" "github.com/dolthub/dolt/go/libraries/utils/valutil" ) const ( // DiffTypeProp is the name of a property added to each split row which tells if its added, removed, the modified // old value, or the new value after modification DiffTypeProp = "difftype" // CollChangesProp is the name of a property added to each modified row which is a map from collumn name to the // type of change. CollChangesProp = "collchanges" ) // DiffChType is an enum that represents the type of change type DiffChType int const ( // DiffAdded is the DiffTypeProp value for a row that was newly added (In new, but not in old) DiffAdded DiffChType = iota // DiffRemoved is the DiffTypeProp value for a row that was newly deleted (In old, but not in new) DiffRemoved // DiffModifiedOld is the DiffTypeProp value for the row which represents the old value of the row before it was changed. DiffModifiedOld // DiffModifiedNew is the DiffTypeProp value for the row which represents the new value of the row after it was changed. DiffModifiedNew ) // DiffTyped is an interface for an object that has a DiffChType type DiffTyped interface { // DiffType gets the DiffChType of an object DiffType() DiffChType } // DiffRow is a row.Row with a change type associated with it. type DiffRow struct { row.Row diffType DiffChType } // DiffType gets the DiffChType for the row. func (dr *DiffRow) DiffType() DiffChType { return dr.diffType } // DiffSplitter is a struct that can take a diff which is represented by a row with a column for every field in the old // version, and a column for every field in the new version and split it into two rows with properties which annotate // what each row is. This is used to show diffs as 2 lines, instead of 1. type DiffSplitter struct { joiner *rowconv.Joiner oldConv *rowconv.RowConverter newConv *rowconv.RowConverter } // NewDiffSplitter creates a DiffSplitter func NewDiffSplitter(joiner *rowconv.Joiner, oldConv, newConv *rowconv.RowConverter) *DiffSplitter { return &DiffSplitter{joiner, oldConv, newConv} } func convertNamedRow(rows map[string]row.Row, name string, rc *rowconv.RowConverter) (row.Row, error) { r, ok := rows[name] if !ok || r == nil { return nil, nil } return rc.Convert(r) } // SplitDiffIntoOldAndNew is a pipeline.TransformRowFunc which can be used in a pipeline to split single row diffs, // into 2 row diffs. func (ds *DiffSplitter) SplitDiffIntoOldAndNew(inRow row.Row, props pipeline.ReadableMap) (rowData []*pipeline.TransformedRowResult, badRowDetails string) { rows, err := ds.joiner.Split(inRow) mappedOld, err := convertNamedRow(rows, From, ds.oldConv) if err != nil { return nil, err.Error() } mappedNew, err := convertNamedRow(rows, To, ds.newConv) if err != nil { return nil, err.Error() } originalNewSch := ds.joiner.SchemaForName(From) originalOldSch := ds.joiner.SchemaForName(To) var oldProps = map[string]interface{}{DiffTypeProp: DiffRemoved} var newProps = map[string]interface{}{DiffTypeProp: DiffAdded} if mappedOld != nil && mappedNew != nil { oldColDiffs := make(map[string]DiffChType) newColDiffs := make(map[string]DiffChType) outSch := ds.newConv.DestSch outCols := outSch.GetAllCols() err := outCols.Iter(func(tag uint64, col schema.Column) (stop bool, err error) { oldVal, _ := mappedOld.GetColVal(tag) newVal, _ := mappedNew.GetColVal(tag) _, inOld := originalOldSch.GetAllCols().GetByTag(tag) _, inNew := originalNewSch.GetAllCols().GetByTag(tag) if inOld && inNew { if !valutil.NilSafeEqCheck(oldVal, newVal) { newColDiffs[col.Name] = DiffModifiedNew oldColDiffs[col.Name] = DiffModifiedOld } } else if inOld { oldColDiffs[col.Name] = DiffRemoved } else { newColDiffs[col.Name] = DiffAdded } return false, nil }) if err != nil { return nil, err.Error() } oldProps = map[string]interface{}{DiffTypeProp: DiffModifiedOld, CollChangesProp: oldColDiffs} newProps = map[string]interface{}{DiffTypeProp: DiffModifiedNew, CollChangesProp: newColDiffs} } var results []*pipeline.TransformedRowResult if mappedOld != nil { results = append(results, &pipeline.TransformedRowResult{RowData: mappedOld, PropertyUpdates: oldProps}) } if mappedNew != nil { results = append(results, &pipeline.TransformedRowResult{RowData: mappedNew, PropertyUpdates: newProps}) } return results, "" }
go/libraries/doltcore/diff/diff_splitter.go
0.619701
0.442155
diff_splitter.go
starcoder
package opr // These import ( "encoding/hex" "encoding/json" "errors" "fmt" "github.com/FactomProject/btcutil/base58" "github.com/FactomProject/factom" "github.com/pegnet/LXR256" "github.com/pegnet/pegnet/polling" "github.com/pegnet/pegnet/support" "github.com/zpatrick/go-config" "strings" "time" ) type OraclePriceRecord struct { // These fields are not part of the OPR, but track values associated with the OPR. Config *config.Config `json:"-"` // The config of the miner using the record Difficulty uint64 `json:"-"` // The difficulty of the given nonce Grade float64 `json:"-"` // The grade when OPR records are compared OPRHash []byte `json:"-"` // The hash of the OPR record (used by pegnetMining) EC *factom.ECAddress `json:"-"` // Entry Credit Address used by a miner Entry *factom.Entry `json:"-"` // Entry to record this record EntryHash string `json:"-"` // Entry Hash is communicated here in base58 StopMining chan int `json:"-"` // Bool that stops pegnetMining this OPR // These values define the context of the OPR, and they go into the PegNet OPR record, and are mined. OPRChainID string `json:oprchainid` // [base58] Chain ID of the chain used by the Oracle Miners Dbht int32 `json:dbht` // The Directory Block Height of the OPR. WinningPreviousOPR [10]string `json:winners` // [base58] Winning OPR entries in the previous block CoinbasePNTAddress string `json:coinbase` // [base58] PNT Address to pay PNT FactomDigitalID []string `did` // [unicode] Digital Identity of the miner // The Oracle values of the OPR, they are the meat of the OPR record, and are mined. PNT float64 USD float64 EUR float64 JPY float64 GBP float64 CAD float64 CHF float64 INR float64 SGD float64 CNY float64 HKD float64 XAU float64 XAG float64 XPD float64 XPT float64 XBT float64 ETH float64 LTC float64 XBC float64 FCT float64 } var LX lxr.LXRHash var OPRChainID string func init() { LX.Init(0xfafaececfafaecec, 25, 256, 5) } type Token struct { code string value float64 } func check(e error) { if e != nil { panic(e) } } // This function cannot validate the winners of the previous block, but it can do some sanity // checking of the structure and values of the OPR record. func (opr *OraclePriceRecord) Validate(c *config.Config) bool { protocol, err1 := c.String("Miner.Protocol") network, err2 := c.String("Miner.Network") if err1 != nil || err2 != nil { return false } if len(OPRChainID) == 0 { OPRChainID = base58.Encode(support.ComputeChainIDFromStrings([]string{protocol, network, "Oracle Price Records"})) } if opr.OPRChainID != OPRChainID { return false } ntype := support.INVALID switch network { case "MainNet": ntype = support.MAIN_NETWORK case "TestNet": ntype = support.TEST_NETWORK default: return false } pre, _, err := support.ConvertPegTAddrToRaw(ntype, opr.CoinbasePNTAddress) if err != nil || pre != "tPNT" { return false } if opr.USD == 0 || opr.EUR == 0 || opr.JPY == 0 || opr.GBP == 0 || opr.CAD == 0 || opr.CHF == 0 || opr.INR == 0 || opr.SGD == 0 || opr.CNY == 0 || opr.HKD == 0 || opr.XAU == 0 || opr.XAG == 0 || opr.XPD == 0 || opr.XPT == 0 || opr.XBT == 0 || opr.ETH == 0 || opr.LTC == 0 || opr.XBC == 0 || opr.FCT == 0 { return false } return true } func (opr *OraclePriceRecord) GetTokens() (tokens []Token) { tokens = append(tokens, Token{"PNT", opr.PNT}) tokens = append(tokens, Token{"USD", opr.USD}) tokens = append(tokens, Token{"EUR", opr.EUR}) tokens = append(tokens, Token{"JPY", opr.JPY}) tokens = append(tokens, Token{"GBP", opr.GBP}) tokens = append(tokens, Token{"CAD", opr.CAD}) tokens = append(tokens, Token{"CHF", opr.CHF}) tokens = append(tokens, Token{"INR", opr.INR}) tokens = append(tokens, Token{"SGD", opr.SGD}) tokens = append(tokens, Token{"CNY", opr.CNY}) tokens = append(tokens, Token{"HKD", opr.HKD}) tokens = append(tokens, Token{"XAU", opr.XAU}) tokens = append(tokens, Token{"XAG", opr.XAG}) tokens = append(tokens, Token{"XPD", opr.XPD}) tokens = append(tokens, Token{"XPT", opr.XPT}) tokens = append(tokens, Token{"XBT", opr.XBT}) tokens = append(tokens, Token{"ETH", opr.ETH}) tokens = append(tokens, Token{"LTC", opr.LTC}) tokens = append(tokens, Token{"XBC", opr.XBC}) tokens = append(tokens, Token{"FCT", opr.FCT}) return tokens } func (opr *OraclePriceRecord) GetHash() []byte { data, err := json.Marshal(opr) check(err) oprHash := LX.Hash(data) return oprHash } // ComputeDifficulty() // Difficulty the high order 8 bytes of the hash( hash(OPR record) + nonce) func (opr *OraclePriceRecord) ComputeDifficulty(nonce []byte) (difficulty uint64) { no := append(opr.OPRHash, nonce...) h := LX.Hash(no) // The high eight bytes of the hash(hash(entry.Content) + nonce) is the difficulty. // Because we don't have a difficulty bar, we can define difficulty as the greatest // value, rather than the minimum value. Our bar is the greatest difficulty found // within a 10 minute period. We compute difficulty as Big Endian. for i := uint64(0); i < 8; i++ { difficulty = difficulty<<8 + uint64(h[i]) } return difficulty } // Mine() // Mine the OraclePriceRecord for a given number of seconds func (opr *OraclePriceRecord) Mine(verbose bool) { // Pick a new nonce as a starting point. Take time + last best nonce and hash that. nonce := support.RandomByteSliceOfLen(32) if verbose { fmt.Printf("OPRHash %x\n", opr.OPRHash) } for i := 0; i < 5; i++ { nonce[i] = 0 } miningloop: for i := 0; ; i++ { select { case <-opr.StopMining: break miningloop default: } k := 0 for j := i; j > 0; j = j >> 8 { nonce[k] = byte(j) k++ } diff := opr.ComputeDifficulty(nonce) if diff > opr.Difficulty { opr.Difficulty = diff // Copy over the previous nonce opr.Entry.ExtIDs[0] = append(opr.Entry.ExtIDs[0][:0], nonce...) if verbose { fmt.Printf("%15v OPR Difficulty %016x on opr hash: %x nonce: %x\n", time.Now().Format("15:04:05.000"), diff, opr.OPRHash, nonce) } } } } func (opr *OraclePriceRecord) ShortString() string { fdid := "" for i, v := range opr.FactomDigitalID { if i > 0 { fdid = fdid + " --- " } fdid = fdid + v } str := fmt.Sprintf("DID %30x OPRHash %30x Nonce %33x Difficulty %15x Grade %20f", fdid, opr.OPRHash, opr.Entry.ExtIDs[0], opr.Difficulty, opr.Grade) return str } // String // Returns a human readable string for the Oracle Record func (opr *OraclePriceRecord) String() (str string) { str = fmt.Sprintf("%14sField%14sValue\n", "", "") str = fmt.Sprintf("%s%32s %v\n", str, "OPRChainID", opr.OPRChainID) str = str + fmt.Sprintf("%32s %v\n", "Difficulty", opr.Difficulty) str = str + fmt.Sprintf("%32s %v\n", "Directory Block Height", opr.Dbht) str = fmt.Sprintf("%s%32s %v\n", str, "WinningPreviousOPRs", "") for i, v := range opr.WinningPreviousOPR { str = fmt.Sprintf("%s%32s %2d, %s\n", str, "", i+1, v) } str = str + fmt.Sprintf("%32s %s\n", "Coinbase PNT", opr.CoinbasePNTAddress) // Make a display string out of the Digital Identity. did := "" for i, t := range opr.FactomDigitalID { if i > 0 { did = did + " --- " } did = did + t } str = fmt.Sprintf("%s%32s %v\n", str, "FactomDigitalID", did) str = fmt.Sprintf("%s%32s %v\n", str, "PNT", opr.PNT) str = fmt.Sprintf("%s%32s %v\n", str, "USD", opr.USD) str = fmt.Sprintf("%s%32s %v\n", str, "EUR", opr.EUR) str = fmt.Sprintf("%s%32s %v\n", str, "JPY", opr.JPY) str = fmt.Sprintf("%s%32s %v\n", str, "GBP", opr.GBP) str = fmt.Sprintf("%s%32s %v\n", str, "CAD", opr.CAD) str = fmt.Sprintf("%s%32s %v\n", str, "CHF", opr.CHF) str = fmt.Sprintf("%s%32s %v\n", str, "INR", opr.INR) str = fmt.Sprintf("%s%32s %v\n", str, "SGD", opr.SGD) str = fmt.Sprintf("%s%32s %v\n", str, "CNY", opr.CNY) str = fmt.Sprintf("%s%32s %v\n", str, "HKD", opr.HKD) str = fmt.Sprintf("%s%32s %v\n", str, "XAU", opr.XAU) str = fmt.Sprintf("%s%32s %v\n", str, "XAG", opr.XAG) str = fmt.Sprintf("%s%32s %v\n", str, "XPD", opr.XPD) str = fmt.Sprintf("%s%32s %v\n", str, "XPT", opr.XPT) str = fmt.Sprintf("%s%32s %v\n", str, "XBT", opr.XBT) str = fmt.Sprintf("%s%32s %v\n", str, "ETH", opr.ETH) str = fmt.Sprintf("%s%32s %v\n", str, "LTC", opr.LTC) str = fmt.Sprintf("%s%32s %v\n", str, "XBC", opr.XBC) str = fmt.Sprintf("%s%32s %v\n", str, "FCT", opr.FCT) return str } func (opr *OraclePriceRecord) SetPegValues(assets polling.PegAssets) { opr.PNT = assets.PNT.Value opr.USD = assets.USD.Value opr.EUR = assets.EUR.Value opr.JPY = assets.JPY.Value opr.GBP = assets.GBP.Value opr.CAD = assets.CAD.Value opr.CHF = assets.CHF.Value opr.INR = assets.INR.Value opr.SGD = assets.SGD.Value opr.CNY = assets.CNY.Value opr.HKD = assets.HKD.Value opr.XAU = assets.XAU.Value opr.XAG = assets.XAG.Value opr.XPD = assets.XPD.Value opr.XPT = assets.XPT.Value opr.XBT = assets.XBT.Value opr.ETH = assets.ETH.Value opr.LTC = assets.LTC.Value opr.XBC = assets.XBC.Value opr.FCT = assets.FCT.Value } // NewOpr() // collects all the information unique to this miner and its configuration, and also // goes and gets the oracle data. Also collects the winners from the prior block and // puts their entry hashes (base58) into this OPR func NewOpr(minerNumber int, dbht int32, c *config.Config, alert chan *OPRs) (*OraclePriceRecord, error) { opr := new(OraclePriceRecord) // create the channel to stop pegnetMining opr.StopMining = make(chan int, 1) // Save the config object opr.Config = c // Get the Entry Credit Address that we need to write our OPR records. if ecadrStr, err := c.String("Miner.ECAddress"); err != nil { return nil, err } else { ecAdr, err := factom.FetchECAddress(ecadrStr) if err != nil { return nil, err } opr.EC = ecAdr } // Get the Identity Chain Specification if chainID58, err := c.String("Miner.IdentityChain"); err != nil { return nil, errors.New("config file has no Miner.IdentityChain specified") } else { fields := strings.Split(chainID58, ",") if minerNumber > 0 { fields = append(fields, fmt.Sprintf("miner%03d", minerNumber)) } for i, v := range fields { if i > 0 { fmt.Print(" --- ") } fmt.Print(v) } fmt.Println() opr.FactomDigitalID = fields } // Get the protocol chain to be used for pegnetMining records protocol, err1 := c.String("Miner.Protocol") network, err2 := c.String("Miner.Network") if err1 != nil { return nil, errors.New("config file has no Miner.Protocol specified") } if err2 != nil { return nil, errors.New("config file has no Miner.Network specified") } opr.OPRChainID = base58.Encode(support.ComputeChainIDFromStrings([]string{protocol, network, "Oracle Price Records"})) opr.Dbht = dbht if str, err := c.String("Miner.CoinbasePNTAddress"); err != nil { return nil, errors.New("config file has no Coinbase PNT Address") } else { opr.CoinbasePNTAddress = str } winners := <-alert for i, w := range winners.ToBePaid { opr.WinningPreviousOPR[i] = w.EntryHash } opr.GetOPRecord(c) return opr, nil } func (opr *OraclePriceRecord) GetOPRecord(c *config.Config) { opr.Config = c //get asset values var Peg polling.PegAssets Peg = polling.PullPEGAssets(c) Peg.FillPriceBytes() opr.SetPegValues(Peg) var err error opr.Entry = new(factom.Entry) opr.Entry.ChainID = hex.EncodeToString(base58.Decode(opr.OPRChainID)) opr.Entry.ExtIDs = [][]byte{{}} opr.Entry.Content, err = json.Marshal(opr) if err != nil { panic(err) } opr.OPRHash = LX.Hash(opr.Entry.Content) }
opr/opr.go
0.661376
0.406391
opr.go
starcoder
package main import ( "math" "math/rand" "syscall/js" "github.com/gmlewis/go-babylonjs/babylon" ) func main() { doc := js.Global().Get("document") canvas := doc.Call("getElementById", "renderCanvas") // Get the canvas element b := babylon.New() engine := b.NewEngine(canvas, &babylon.NewEngineOpts{Antialias: Bool(true)}) // Generate the BABYLON 3D engine /******* Add the create scene function ******/ createScene := func() *babylon.Scene { scene := b.NewScene(engine, nil) /********** FOLLOW CAMERA EXAMPLE **************************/ // This creates and initially positions a follow camera camera := b.NewFollowCamera("FollowCam", b.NewVector3(0, 10, -10), scene, nil) //The goal distance of camera from target camera.SetRadius(30) // The goal height of camera above local origin (centre) of target camera.SetHeightOffset(10) // The goal rotation of camera around local origin (centre) of target in x y plane camera.SetRotationOffset(0) //Acceleration of camera in moving from current to goal position camera.SetCameraAcceleration(0.005) //The speed at which acceleration is halted camera.SetMaxCameraSpeed(10) //camera.target is set after the target's creation // This attaches the camera to the canvas camera.AttachControl(canvas, true) /**************************************************************/ // This creates a light, aiming 0,1,0 - to the sky (non-mesh) b.NewHemisphericLight("light", b.NewVector3(0, 1, 0), scene) //Material mat := b.NewStandardMaterial("mat1", scene) mat.SetAlpha(1.0) mat.SetDiffuseColor(b.NewColor3(0.5, 0.5, 1.0)) texture := b.NewTexture("https://i.imgur.com/vxH5bCg.jpg", scene, nil) mat.SetDiffuseTexture(texture.BaseTexture) //Different face for each side of box to show camera rotation hSpriteNb := 3.0 // 3 sprites per row vSpriteNb := 2.0 // 2 sprite rows faceUV := []*babylon.Vector4{} for i := 0.0; i < 6.0; i++ { faceUV = append(faceUV, b.NewVector4(i/hSpriteNb, 0, (i+1)/hSpriteNb, 1/vSpriteNb)) } // Shape to follow box := b.MeshBuilder().CreateBox("box", &babylon.BoxOpts{Size: Float64(2), FaceUV: faceUV}, scene) box.SetPosition(b.NewVector3(20, 0, 10)) box.SetMaterial(mat.Material) //create solid particle system of stationery grey boxes to show movement of box and camera boxesSPS := b.NewSolidParticleSystem("boxes", scene, &babylon.NewSolidParticleSystemOpts{Options: map[string]interface{}{"updatable": false}}) //function to position of grey boxes setBoxes := js.FuncOf(func(this js.Value, args []js.Value) interface{} { particle := babylon.MeshFromJSObject(args[0], this) particle.SetPosition(b.NewVector3(-50+rand.Float64()*100, -50+rand.Float64()*100, -50+rand.Float64()*100)) return nil }) //add 400 boxes boxesSPS.AddShape(box, 400, &babylon.SolidParticleSystemAddShapeOpts{Options: map[string]interface{}{"positionFunction": setBoxes}}) boxesSPS.BuildMesh() // mesh of boxes /*****************SET TARGET FOR CAMERA************************/ camera.SetLockedTarget(box.AbstractMesh) /**************************************************************/ //box movement variables alpha := 0.0 orbitRadius := 20.0 //Move the box to see that the camera follows it scene.RegisterBeforeRender(func(this js.Value, args []js.Value) interface{} { alpha += 0.01 box.Position().SetX(orbitRadius * math.Cos(alpha)) box.Position().SetY(orbitRadius * math.Sin(alpha)) box.Position().SetZ(10 * math.Sin(2*alpha)) //change the viewing angle of the camera as it follows the box camera.SetRotationOffset(math.Mod(18*alpha, 360)) return nil }) return scene } /******* End of the create scene function ******/ scene := createScene() //Call the createScene function // Register a render loop to repeatedly render the scene engine.RunRenderLoop(scene.RenderLoopFunc(nil)) // Watch for browser/canvas resize events window := js.Global().Get("window") // Note that engine.ResizeFunc is never released since it is needed for resizing. window.Call("addEventListener", "resize", engine.ResizeFunc()) // prevent program from terminating c := make(chan struct{}, 0) <-c } // Bool returns the pointer to the provided bool. func Bool(v bool) *bool { return &v } // Float64 returns the pointer to the provided float64. func Float64(v float64) *float64 { return &v }
examples/23-follow-camera/main.go
0.559049
0.450118
main.go
starcoder
package diff type ItemType int const ( Insertion ItemType = iota Unchanged Deletion ) func (t ItemType) String() string { switch t { case Insertion: return "+" case Unchanged: return " " case Deletion: return "-" } return "<error>" } // Item represents a single node in a diff result - it contains the type, which // indicates if the wrapped text was inserted, deleted, or unchanged from the // original, as well as the text itself alongside its index in the source. type Item struct { Type ItemType Line } func (i Item) String() string { return i.Type.String() + i.Text } // Items is a wrapper type for a slice of Item structs which facilitates // "pretty-printing" of the lines. type Items []Item func (it Items) String() string { out := "" for _, x := range it { if len(out) > 0 { out += "\n" } out += x.String() } return out } func uniqueLines(a []Line) (out []Line) { type entry struct { index, count int } m := make(map[string]entry) for _, x := range a { e := m[x.Text] e.count += 1 e.index = x.Index m[x.Text] = e } for _, x := range a { if m[x.Text].count == 1 { out = append(out, x) } } return } // Patience implements the patience diff algorithm, as described by // http://alfedenzo.livejournal.com/170301.html, between to slices // of strings. func Patience(a, b []string) []Item { if len(a) == 0 && len(b) == 0 { return nil } aLines := ToLines(a) bLines := ToLines(b) items := make([]Item, 0) if len(a) == 0 { for _, line := range bLines { items = append(items, Item{Insertion, line}) } return items } if len(b) == 0 { for _, line := range aLines { items = append(items, Item{Deletion, line}) } return items } for i := 0; i < len(a) && i < len(b); i++ { if a[i] != b[i] { break } items = append(items, Item{Unchanged, aLines[i]}) } if n := len(items); n != 0 { for _, item := range Patience(a[n:], b[n:]) { item.Index += n items = append(items, item) } return items } suffix := make([]Item, 0) for i := 0; i < len(a) && i < len(b); i++ { if a[len(a)-i-1] != b[len(b)-i-1] { break } item := Item{ Type: Unchanged, Line: aLines[len(a)-i-1], } suffix = append([]Item{item}, suffix...) } if len(suffix) != 0 { for _, item := range Patience(a[:len(a)-len(suffix)], b[:len(b)-len(suffix)]) { items = append(items, item) } items = append(items, suffix...) return items } table := NewLCSTable(uniqueLines(aLines), uniqueLines(bLines)) lcs := table.LongestCommonSubsequence() if len(lcs) == 0 { table := NewLCSTable(aLines, bLines) for _, d := range table.Diff() { items = append(items, d) } return items } lastA := 0 lastB := 0 for _, x := range lcs { for _, item := range Patience(a[lastA:x[0]], b[lastB:x[1]]) { item.Index += lastA items = append(items, item) } items = append(items, Item{ Type: Unchanged, Line: aLines[x[0]], }) lastA = x[0] + 1 lastB = x[1] + 1 } for _, item := range Patience(a[lastA:], b[lastB:]) { item.Index += lastA items = append(items, item) } return items }
patience.go
0.588653
0.401688
patience.go
starcoder
package operations // OPPushInt struct  represents a operation that pushes an integer onto the stack type OPPushInt struct { position Position value int64 } // NewOPPushInt function  creates a new OperationPushInt func NewOPPushInt(value int64, position Position) Operation { return OPPushInt{ value: value, position: position, } } // Position method  returns the position of the operation func (op OPPushInt) Position() Position { return op.position } // Type method  returns the type of the operation func (op OPPushInt) Type() OPType { return OP_PUSH_INT } // Value method  returns the value of the operation func (op OPPushInt) Value() int64 { return op.value } // OPPushFloat struct  represents a operation that pushes a float onto the stack type OPPushFloat struct { position Position value float64 } // NewOPPushFloat function  func NewOPPushFloat(value float64, position Position) Operation { return OPPushFloat{ value: value, position: position, } } // Position method  returns the position of the operation func (op OPPushFloat) Position() Position { return op.position } // Type method  returns the type of the operation func (op OPPushFloat) Type() OPType { return OP_PUSH_FLOAT } // Value method  returns the value of the operation func (op OPPushFloat) Value() float64 { return op.value } // OPPushString struct  represents a operation that pushes a string onto the stack type OPPushString struct { position Position value string } // NewOPPushString function  creates a new OperationPushStr func NewOPPushString(value string, position Position) Operation { return OPPushString{ value: value, position: position, } } // Position method  returns the position of the operation func (op OPPushString) Position() Position { return op.position } // Type method  returns the type of the operation func (op OPPushString) Type() OPType { return OP_PUSH_STRING } // Value method  returns the value of the operation func (op OPPushString) Value() string { return op.value } // OPPushBool struct  represents a operation that pushes a bool onto the stack type OPPushBool struct { position Position value bool } // NewOPPushBool function  creates a new OperationPushBool func NewOPPushBool(value bool, position Position) Operation { return OPPushBool{ value: value, position: position, } } // Position method  returns the position of the operation func (op OPPushBool) Position() Position { return op.position } // Type method  returns the type of the operation func (op OPPushBool) Type() OPType { return OP_PUSH_BOOL } // Value method  returns the value of the operation func (op OPPushBool) Value() bool { return op.value }
core/operations/push.go
0.822795
0.485844
push.go
starcoder
package rbf // Query the forest for a single point. Returns indices into the training feature-array // (since the caller/wrapper might have different things they want to do with this). // Since multiple trees might return the same result points, this method dedups the results. func (forest RandomBinaryForest) FindPointDedupResults(queryPoint []byte) map[int32]bool { // query each tree and get results (indices into training feature-array) resultIndices := make(map[int32]bool) for _, tree := range forest.Trees { treeResultIndices := tree.findPoint(queryPoint) for _, index := range treeResultIndices { resultIndices[index] = true } } return resultIndices } // Query the forest for a single point. // Returns: for each tree in the forest, a slice of indices into the training feature-array // (since the caller/wrapper might have different things they want to do with this). // This method does not dedup results -- each tree's results are a different slice. func (forest RandomBinaryForest) FindPointAllResults(queryPoint []byte) (count int, results [][]int32) { results = make([][]int32, len(forest.Trees)) for i, tree := range forest.Trees { results[i] = tree.findPoint(queryPoint) count += len(results[i]) } return } // A "point" is a feature-array. Search for one point in this tree. func (tree RandomBinaryTree) findPoint(queryPoint []byte) []int32 { arrayPos := int32(0) first := tree.treeFirst[arrayPos] // the condition checks if it's an internal node (== 0) or a leaf (== -1): for first>>high_bit == 0 { // internal node, so first (the entry in tree.treeFirst) is a feature-number and // the entry in tree.treeSecond is the feature-value at which to split: if int32(queryPoint[first]) <= tree.treeSecond[arrayPos] { arrayPos = (2 * arrayPos) + 1 } else { arrayPos = (2 * arrayPos) + 2 } first = tree.treeFirst[arrayPos] } // found a leaf; get values and return indexStart, indexEnd := high_bit_1^first, high_bit_1^tree.treeSecond[arrayPos] return tree.rowIndex[indexStart:indexEnd] }
rbf_search.go
0.774285
0.774924
rbf_search.go
starcoder