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 ytypes import ( "fmt" "github.com/openconfig/goyang/pkg/yang" ) // Refer to: https://tools.ietf.org/html/rfc6020#section-9.3. // ValidateDecimalRestrictions checks that the given decimal matches the // schema's range restrictions (if any). It returns an error if the validation // fails. func ValidateDecimalRestrictions(schemaType *yang.YangType, floatVal float64) error { if !isInRanges(schemaType.Range, yang.FromFloat(floatVal)) { return fmt.Errorf("decimal value %v is outside specified ranges", floatVal) } return nil } // validateDecimal validates value, which must be a Go float64 type, against the // given schema. func validateDecimal(schema *yang.Entry, value interface{}) error { // Check that the schema itself is valid. if err := validateDecimalSchema(schema); err != nil { return err } // Check that type of value is the type expected from the schema. f, ok := value.(float64) if !ok { return fmt.Errorf("non float64 type %T with value %v for schema %s", value, value, schema.Name) } if err := ValidateDecimalRestrictions(schema.Type, f); err != nil { return fmt.Errorf("schema %q: %v", schema.Name, err) } return nil } // validateDecimalSlice validates value, which must be a Go float64 slice type, // against the given schema. func validateDecimalSlice(schema *yang.Entry, value interface{}) error { // Check that the schema itself is valid. if err := validateDecimalSchema(schema); err != nil { return err } // Check that type of value is the type expected from the schema. slice, ok := value.([]float64) if !ok { return fmt.Errorf("non []float64 type %T with value: %v for schema %s", value, value, schema.Name) } // Each slice element must be valid and unique. tbl := make(map[float64]bool, len(slice)) for i, val := range slice { if err := validateDecimal(schema, val); err != nil { return fmt.Errorf("invalid element at index %d: %v for schema %s", i, err, schema.Name) } if tbl[val] { return fmt.Errorf("duplicate decimal: %v for schema %s", val, schema.Name) } tbl[val] = true } return nil } // validateDecimalSchema validates the given decimal type schema. This is a // quick check rather than a comprehensive validation against the RFC. It is // assumed that such a validation is done when the schema is parsed from source // YANG. func validateDecimalSchema(schema *yang.Entry) error { if schema == nil { return fmt.Errorf("decimal schema is nil") } if schema.Type == nil { return fmt.Errorf("decimal schema %s Type is nil", schema.Name) } if schema.Type.Kind != yang.Ydecimal64 { return fmt.Errorf("decimal schema %s has wrong type %v", schema.Name, schema.Type.Kind) } return nil }
ytypes/decimal_type.go
0.805632
0.460653
decimal_type.go
starcoder
package speller const ( letters = "abcdefghijklmnopqrstuvwxyz" // Sample provides a corpus used to train the dictionary Sample = "big.txt.gz" ) var ( wordFreq map[string]int wordTotal int ) // probability returns the percent of times `word` is found in the corpus func probability(word string) float64 { return float64(wordFreq[word]) / float64(wordTotal) } // Correction returns the most probable spelling correction for word func Correction(word string) string { return max(Candidates(word), probability) } // deleted returns splits with non-empty R side func deleted(s split, save func(string)) { if s.R != "" { save(s.L + s.R[1:]) } } // transpose transposes the first 2 characters func transpose(s split, save func(string)) { if len(s.R) > 1 { save(s.L + s.R[1:2] + s.R[0:1] + s.R[2:]) } } // replace replaces the "split" character with alphabetic permutations func replace(s split, save func(string)) { if len(s.R) > 0 { for _, b := range letters { c := string(b) save(s.L + c + s.R[1:]) } } } // insert inserts the alphabet mid-split func insert(s split, save func(string)) { for _, c := range letters { save(s.L + string(c) + s.R) } } // Candidates generate possible spelling corrections for word func Candidates(word string) []string { self := []string{word} if list := set(known(self)...); len(list) > 0 { return list } if list := set(edits1(word)...); len(list) > 0 { return list } if list := set(edits2(word)...); len(list) > 0 { return list } return self } // known returns the subset of `words` that appear in the dictionary of wordFreq func known(words []string) []string { m := make(map[string]struct{}) for _, word := range words { if _, ok := wordFreq[word]; ok { m[word] = struct{}{} } } return slice(m) } // edits1 returns all edits that are one edit away from `word` func edits1(word string) []string { return set(cleaves(word).comp(deleted, transpose, replace, insert)...) } // edits2 returns all edits that are two edits away from `word` func edits2(word string) (results []string) { for _, e1 := range edits1(word) { for _, e2 := range edits1(e1) { results = append(results, e2) } } return results } // InitFile initializes the dictionary using the given filename func InitFile(filename string) { wordFreq = counter(words(readFile(filename))) for _, occurs := range wordFreq { wordTotal += occurs } }
speller.go
0.796688
0.458409
speller.go
starcoder
package slice // FilterBool performs in place filtering of a bool slice based on a predicate func FilterBool(a []bool, keep func(x bool) bool) []bool { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterByte performs in place filtering of a byte slice based on a predicate func FilterByte(a []byte, keep func(x byte) bool) []byte { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterComplex128 performs in place filtering of a complex128 slice based on a predicate func FilterComplex128(a []complex128, keep func(x complex128) bool) []complex128 { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterComplex64 performs in place filtering of a complex64 slice based on a predicate func FilterComplex64(a []complex64, keep func(x complex64) bool) []complex64 { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterFloat32 performs in place filtering of a float32 slice based on a predicate func FilterFloat32(a []float32, keep func(x float32) bool) []float32 { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterFloat64 performs in place filtering of a float64 slice based on a predicate func FilterFloat64(a []float64, keep func(x float64) bool) []float64 { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterInt performs in place filtering of an int slice based on a predicate func FilterInt(a []int, keep func(x int) bool) []int { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterInt16 performs in place filtering of an int16 slice based on a predicate func FilterInt16(a []int16, keep func(x int16) bool) []int16 { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterInt32 performs in place filtering of an int32 slice based on a predicate func FilterInt32(a []int32, keep func(x int32) bool) []int32 { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterInt64 performs in place filtering of an int64 slice based on a predicate func FilterInt64(a []int64, keep func(x int64) bool) []int64 { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterInt8 performs in place filtering of an int8 slice based on a predicate func FilterInt8(a []int8, keep func(x int8) bool) []int8 { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterRune performs in place filtering of a rune slice based on a predicate func FilterRune(a []rune, keep func(x rune) bool) []rune { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterString performs in place filtering of a string slice based on a predicate func FilterString(a []string, keep func(x string) bool) []string { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterUint performs in place filtering of a uint slice based on a predicate func FilterUint(a []uint, keep func(x uint) bool) []uint { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterUint16 performs in place filtering of a uint16 slice based on a predicate func FilterUint16(a []uint16, keep func(x uint16) bool) []uint16 { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterUint32 performs in place filtering of a uint32 slice based on a predicate func FilterUint32(a []uint32, keep func(x uint32) bool) []uint32 { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterUint64 performs in place filtering of a uint64 slice based on a predicate func FilterUint64(a []uint64, keep func(x uint64) bool) []uint64 { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterUint8 performs in place filtering of a uint8 slice based on a predicate func FilterUint8(a []uint8, keep func(x uint8) bool) []uint8 { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] } // FilterUintptr performs in place filtering of a uintptr slice based on a predicate func FilterUintptr(a []uintptr, keep func(x uintptr) bool) []uintptr { if len(a) == 0 { return a } n := 0 for _, v := range a { if keep(v) { a[n] = v n++ } } return a[:n] }
filter.go
0.850717
0.569673
filter.go
starcoder
package binarysearchtree import ( "fmt" "github.com/kevinpollet/go-datastructures/errors" ) type node struct { value int left, right *node } // BinarySearchTree data structure implementation. type BinarySearchTree struct { root *node size int } // Add adds the given value to the tree. func (tree *BinarySearchTree) Add(value int) { tree.root = add(tree.root, value) tree.size++ } // Remove removes the given value from the tree. func (tree *BinarySearchTree) Remove(value int) (bool, error) { if tree.IsEmpty() { return false, errors.NewNoSuchValueError("cannot remove a value from an empty tree") } root, removed := remove(tree.root, value) tree.root = root if removed { tree.size-- } return removed, nil } // Contains returns true if the tree contains the given value, false otherwise. func (tree *BinarySearchTree) Contains(value int) bool { return !tree.IsEmpty() && contains(tree.root, value) } // IsEmpty returns true if the tree has no nodes, false otherwise. func (tree *BinarySearchTree) IsEmpty() bool { return tree.Size() == 0 } // Size returns the number of values in the tree. func (tree *BinarySearchTree) Size() int { return tree.size } func (tree BinarySearchTree) String() string { return stringify(tree.root) } func add(currentNode *node, value int) *node { if currentNode == nil { return &node{value: value} } if value > currentNode.value { currentNode.right = add(currentNode.right, value) } else if value < currentNode.value { currentNode.left = add(currentNode.left, value) } return currentNode } func contains(currentNode *node, value int) bool { found := false if currentNode != nil { if value == currentNode.value { return true } else if value > currentNode.value { return contains(currentNode.right, value) } else { return contains(currentNode.left, value) } } return found } func remove(currentNode *node, value int) (*node, bool) { if currentNode == nil { return nil, false } else if currentNode.value > value { left, removed := remove(currentNode.left, value) currentNode.left = left return currentNode, removed } else if currentNode.value < value { right, removed := remove(currentNode.right, value) currentNode.right = right return currentNode, removed } else if currentNode.left == nil && currentNode.right == nil { return nil, true } else if currentNode.left == nil { return currentNode.right, true } else if currentNode.right == nil { return currentNode.left, true } else { min, right := digMin(currentNode.right) return &node{value: min, left: currentNode.left, right: right}, true } } func digMin(currentNode *node) (int, *node) { if currentNode.left == nil { return currentNode.value, nil } min, left := digMin(currentNode.left) currentNode.left = left return min, currentNode } func stringify(currentNode *node) string { if currentNode == nil { return "nil" } return fmt.Sprintf("(%v, %v, %v)", currentNode.value, stringify(currentNode.left), stringify(currentNode.right)) }
binarysearchtree/binary_search_tree.go
0.883368
0.528594
binary_search_tree.go
starcoder
package util import ( "errors" "math/rand" "sort" ) // CopyStr copy a string slice to another func CopyStr(a []string) []string { var b []string b = append(a[:0:0], a...) // See https://github.com/go101/go101/wiki return b } // CutStr removes a sub-slice from start(inclusive in removed slice) // to end (exclusive in remve slice) from original slice func CutStr(a []string, start int, end int) ([]string, error) { var err error if start < 0 || start > len(a) { err = errors.New("`start` is out of bound") return nil, err } if end < 0 || end > len(a) { err = errors.New("`end` is out of bound") return nil, err } if start > end { err = errors.New("`end` should be greater than `start`") return nil, err } return append(a[:start], a[end:]...), nil } // DeleteStr deletes an string item at specified index and preserves order func DeleteStr(a []string, i int) ([]string, error) { var err error if i < 0 || i > len(a) { err = errors.New("`i` index is out of bound.") return nil, err } return append(a[:i], a[i+1:]...), nil } // ExpandStr expands capacity of slice from `start` (inclusive) to `end` exclusive point. func ExpandStr(a []string, start int, end int) ([]string, error) { var err error if start < 0 || start > len(a) { err = errors.New("`start` is out of bound") return nil, err } if end < 0 || end > len(a) { err = errors.New("`end` is out of bound") return nil, err } if start > end { err = errors.New("`end` should be greater than `start`") return nil, err } return append(a[:start], append(make([]string, end), a[start:]...)...), nil } // ExtendStr extends slice capacity by adding a spcified size at then end of slice. func ExtendStr(a []string, size int) ([]string, error) { if size <= 0 { err := errors.New("Extending size should be greater than zero.") return nil, err } return append(a, make([]string, size)...), nil } // FilterStr filters in place a string slice func FilterStr(a []string, ffunc func(string) bool) []string { n := 0 for _, x := range a { if ffunc(x) { a[n] = x n++ } } return a[:n] } // InsertStr inserts an string to slice of string at specified index i. func InsertStr(a []string, item string, i int) ([]string, error) { var err error if i < 0 || i > len(a) { err = errors.New("`i` index is out of bound.") return nil, err } return append(a[:i], append([]string{item}, a[i:]...)...), nil } // InsertVecStr inserts a slice (`b`) to origin slice (`a`) at specified index point func InsertVecStr(a []string, b []string, i int) ([]string, error) { var err error if i < 0 || i > len(a) { err = errors.New("`i` index point is out of bound.") return nil, err } return append(a[:i], append(b, a[i:]...)...), nil } // PushStr pushes an item to a slice at the end of it. func PushStr(a []string, item string) []string { return append(a, item) } // PopStr pops last item out of a give slice func PopStr(a []string) (string, []string) { return a[len(a)-1], a[:len(a)-1] } // PushFrontStr pushes an item to the front of a slice (unshift) func PushFrontStr(a []string, item string) []string { return append([]string{item}, a...) } // PopFrontStr pops the first item from the slice (shift) func PopFrontStr(a []string) (string, []string) { return a[0], a[1:] } // FilterStrNoAllocate filters a slice without allocating. // This trick uses the fact that a slice shares the same backing array // and capacity as the original, so the storage is reused for the filtered slice. // Of course, the original contents are modified. func FilterStrNoAllocate(a []string, f func(string) bool) []string { b := a[:0] for _, x := range a { if f(x) { b = append(b, x) } } // Garbage collected for i := len(b); i < len(a); i++ { a[i] = "" // nil or the zero value of T } return b } // ReverseStr replaces the contents of a slice with // the same elements but in reverse order func ReverseStr(a []string) []string { for i := len(a)/2 - 1; i >= 0; i-- { opp := len(a) - 1 - i a[i], a[opp] = a[opp], a[i] } return a } // ReverseLRStr does the same as ReverseStr except with 2 indices func ReverseLRStr(a []string) []string { for left, right := 0, len(a)-1; left < right; left, right = left+1, right-1 { a[left], a[right] = a[right], a[left] } return a } // ShuffleStr shuffles a slice using Fisher–Yates algorithm // Since go1.10, this is available at math/rand.Shuffle (https://godoc.org/math/rand#Shuffle) func ShuffleStr(a []string) []string { for i := len(a) - 1; i > 0; i-- { j := rand.Intn(i + 1) a[i], a[j] = a[j], a[i] } return a } // BatchStr slits a slice to batches (slice of slices) func BatchStr(a []string, size int) ([][]string, error) { var err error if size < 0 { err = errors.New("Batch size should be greater than zero") return nil, err } batches := make([][]string, 0, (len(a)+size-1)/size) for size < len(a) { a, batches = a[size:], append(batches, a[0:size:size]) } batches = append(batches, a) return batches, nil } // DeduplicateStr de-duplicates a slice in place func DeduplicateStr(a []string) []string { sort.Strings(a) j := 0 for i := 1; i < len(a); i++ { if a[j] == a[i] { continue } j++ // preserve the original data // a[i], a[j] = a[j], a[i] // only set what is required a[j] = a[i] } result := a[:j+1] return result }
util/slice/string.go
0.711832
0.40072
string.go
starcoder
package token import "strings" //go:generate go run gen/gen.go // A CharData token represents a run of text. type CharData struct { Position Value string } func (t *CharData) String() string { return t.Value } // SplitLines splits this token into one or more, one for each line. // This will return empty tokens for empty lines, as the newline-characters // are not included in the new tokens. func (t CharData) SplitLines() []*CharData { var result []*CharData // Keep track of the offset and advance it properly offset := t.Begin().Offset for i, line := range strings.Split(t.Value, "\n") { // The column will be 1, except for the first line. col := 1 if i == 0 { col = t.Begin().Col } result = append(result, &CharData{ Position: Position{ BeginPos: Pos{ File: t.Begin().File, Line: t.Begin().Line + i, Col: col, Offset: offset, }, EndPos: Pos{ File: t.EndPos.File, Line: t.Begin().Line + i, Col: col + len(line), Offset: offset + len(line), }, }, Value: line, }) // Add one to the line length for the newline char. offset += len(line) + 1 } return result } // Identifier is an identifier as you would expect from a programming language: [0-9a-zA-Z_]+. type Identifier struct { Position Value string } // BlockStart is a '{' that is the start of a block. type BlockStart struct { Position } // BlockEnd is a '}' that is the end of a block. type BlockEnd struct { Position } // GroupStart is a '(' that is the start of a group. type GroupStart struct { Position } // GroupEnd is a ')' that is the end of a group. type GroupEnd struct { Position } // GenericStart is a '<' that is the start of a generic group. type GenericStart struct { Position } // GenericEnd is a '>' that is the end of a generic group. type GenericEnd struct { Position } // G2Preamble is the '#!' preamble for a G2 grammar. type G2Preamble struct { Position } // DefineElement is the '#' before the name of an element. type DefineElement struct { Position Forward bool } // DefineAttribute is the '@' before the name of an attribute. type DefineAttribute struct { Position Forward bool } // Assign is the '=' in G2 attribute definitions. type Assign struct { Position } // G1LineEnd is a special newline, that is only emitted when a G1Line ends. type G1LineEnd struct { Position } // Comma ',' is used as a separator in G2. type Comma struct { Position } // Semicolon ';' is used as a separator in G2 and is interchangeable with Comma. type Semicolon struct { Position } // G1Comment is a '#?' that indicates a comment in G1. type G1Comment struct { Position } // G2Comment is a '//' that indicates a comment in G2. type G2Comment struct { Position } // G2Arrow is a '->' that indicates a return value in G2. type G2Arrow struct { Position }
token/token.go
0.622459
0.459137
token.go
starcoder
package pixelpusher import ( "encoding/binary" "fmt" "image" "image/color" ) // x, y and pitch should be int32, since they are likely to be used together with other int32 types. // go-sdl2 uses int32 for most things. // PixelsToImage converts a pixel buffer to an image.RGBA image func PixelsToImage(pixels []uint32, pitch int32) *image.RGBA { width := pitch height := int32(len(pixels)) / pitch img := image.NewRGBA(image.Rect(0, 0, int(width), int(height))) bs := make([]uint8, 4) for y := int32(0); y < height; y++ { for x := int32(0); x < width; x++ { binary.LittleEndian.PutUint32(bs, pixels[y*pitch+x]) c := color.RGBA{bs[2], bs[1], bs[0], bs[3]} img.Set(int(x), int(y), c) } } return img } // BlitImage blits an image on top of a pixel buffer, while blending func BlitImage(pixels []uint32, pitch int32, img *image.RGBA) error { width := pitch height := int32(len(pixels)) / pitch rectWidth := int32(img.Rect.Size().X) rectHeight := int32(img.Rect.Size().Y) if rectWidth < width || rectHeight < height { return fmt.Errorf("invalid size (%d, %d) for blitting on pixel buffer of size (%d, %d)", rectWidth, rectHeight, width, height) } // Loop through target coordinates for y := int32(0); y < height; y++ { offset := y * pitch for x := int32(0); x < width; x++ { cv := ColorToColorValue(img.At(int(x), int(y)).(color.RGBA)) pixels[offset+x] = Blend(pixels[offset+x], cv) } } return nil } // BlitImageOnTop blits an image on top of a pixel buffer, disregarding any previous pixels. // The resulting pixels are opaque. func BlitImageOnTop(pixels []uint32, pitch int32, img *image.RGBA) error { width := pitch height := int32(len(pixels)) / pitch rectWidth := int32(img.Rect.Size().X) rectHeight := int32(img.Rect.Size().Y) if rectWidth < width || rectHeight < height { return fmt.Errorf("invalid size (%d, %d) for blitting on pixel buffer of size (%d, %d)", rectWidth, rectHeight, width, height) } // Loop through target coordinates for y := int32(0); y < height; y++ { offset := y * pitch for x := int32(0); x < width; x++ { cv := ColorToColorValue(img.At(int(x), int(y)).(color.RGBA)) pixels[offset+x] = Add(pixels[offset+x], cv) } } return nil } // Clear changes all pixels to the given color func Clear(pixels []uint32, c color.RGBA) { colorValue := binary.BigEndian.Uint32([]uint8{c.A, c.R, c.G, c.B}) for i := range pixels { pixels[i] = colorValue } } // FastClear changes all pixels to the given uint32 color value, // like 0xff0000ff for: 0xff red, 0x00 green, 0x00 blue and 0xff alpha. func FastClear(pixels []uint32, colorValue uint32) { for i := range pixels { pixels[i] = colorValue } }
image.go
0.789234
0.519887
image.go
starcoder
package metrics import ( "encoding/json" "io" "time" ) // MarshalJSON returns a byte slice containing a JSON representation of all // the metrics in the Registry. func (r StandardRegistry) MarshalJSON() ([]byte, error) { data := make(map[string]map[string]interface{}) r.Each(func(name string, i interface{}) { values := make(map[string]interface{}) switch metric := i.(type) { case Counter: values["count"] = metric.Count() case Gauge: values["value"] = metric.Value() case GaugeFloat64: values["value"] = metric.Value() case Healthcheck: values["error"] = nil metric.Check() if err := metric.Error(); nil != err { values["error"] = metric.Error().Error() } case Histogram: h := metric.Snapshot() ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) values["count"] = h.Count() values["min"] = h.Min() values["max"] = h.Max() values["mean"] = h.Mean() values["stddev"] = h.StdDev() values["median"] = ps[0] values["75%"] = ps[1] values["95%"] = ps[2] values["99%"] = ps[3] values["99.9%"] = ps[4] case Meter: m := metric.Snapshot() values["count"] = m.Count() values["1m.rate"] = m.Rate1() values["5m.rate"] = m.Rate5() values["15m.rate"] = m.Rate15() values["mean.rate"] = m.RateMean() case Timer: t := metric.Snapshot() ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999}) values["count"] = t.Count() values["min"] = t.Min() values["max"] = t.Max() values["mean"] = t.Mean() values["stddev"] = t.StdDev() values["median"] = ps[0] values["75%"] = ps[1] values["95%"] = ps[2] values["99%"] = ps[3] values["99.9%"] = ps[4] values["1m.rate"] = t.Rate1() values["5m.rate"] = t.Rate5() values["15m.rate"] = t.Rate15() values["mean.rate"] = t.RateMean() } data[name] = values }) return json.Marshal(data) } // WriteJSON writes metrics from the given registry periodically to the // specified io.Writer as JSON. func WriteJSON(r Registry, d time.Duration, w io.Writer) { for _ = range time.Tick(d) { WriteJSONOnce(r, w) } } // WriteJSONOnce writes metrics from the given registry to the specified // io.Writer as JSON. func WriteJSONOnce(r Registry, w io.Writer) { json.NewEncoder(w).Encode(r) }
vendor/gx/ipfs/QmeYJHEk8UjVVZ4XCRTZe6dFQrb8pGWD81LYCgeLp8CvMB/go-metrics/json.go
0.718989
0.409634
json.go
starcoder
package dbx import ( "errors" "fmt" "sort" "strings" ) // Builder supports building SQL statements in a DB-agnostic way. // Builder mainly provides two sets of query building methods: those building SELECT statements // and those manipulating DB data or schema (e.g. INSERT statements, CREATE TABLE statements). type Builder interface { // NewQuery creates a new Query object with the given SQL statement. // The SQL statement may contain parameter placeholders which can be bound with actual parameter // values before the statement is executed. NewQuery(string) *Query // Select returns a new SelectQuery object that can be used to build a SELECT statement. // The parameters to this method should be the list column names to be selected. // A column name may have an optional alias name. For example, Select("id", "my_name AS name"). Select(...string) *SelectQuery // ModelQuery returns a new ModelQuery object that can be used to perform model insertion, update, and deletion. // The parameter to this method should be a pointer to the model struct that needs to be inserted, updated, or deleted. Model(interface{}) *ModelQuery // GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. GeneratePlaceholder(int) string // Quote quotes a string so that it can be embedded in a SQL statement as a string value. Quote(string) string // QuoteSimpleTableName quotes a simple table name. // A simple table name does not contain any schema prefix. QuoteSimpleTableName(string) string // QuoteSimpleColumnName quotes a simple column name. // A simple column name does not contain any table prefix. QuoteSimpleColumnName(string) string // QueryBuilder returns the query builder supporting the current DB. QueryBuilder() QueryBuilder // Insert creates a Query that represents an INSERT SQL statement. // The keys of cols are the column names, while the values of cols are the corresponding column // values to be inserted. Insert(table string, cols Params) *Query // Upsert creates a Query that represents an UPSERT SQL statement. // Upsert inserts a row into the table if the primary key or unique index is not found. // Otherwise it will update the row with the new values. // The keys of cols are the column names, while the values of cols are the corresponding column // values to be inserted. Upsert(table string, cols Params, constraints ...string) *Query // Update creates a Query that represents an UPDATE SQL statement. // The keys of cols are the column names, while the values of cols are the corresponding new column // values. If the "where" expression is nil, the UPDATE SQL statement will have no WHERE clause // (be careful in this case as the SQL statement will update ALL rows in the table). Update(table string, cols Params, where Expression) *Query // Delete creates a Query that represents a DELETE SQL statement. // If the "where" expression is nil, the DELETE SQL statement will have no WHERE clause // (be careful in this case as the SQL statement will delete ALL rows in the table). Delete(table string, where Expression) *Query // CreateTable creates a Query that represents a CREATE TABLE SQL statement. // The keys of cols are the column names, while the values of cols are the corresponding column types. // The optional "options" parameters will be appended to the generated SQL statement. CreateTable(table string, cols map[string]string, options ...string) *Query // RenameTable creates a Query that can be used to rename a table. RenameTable(oldName, newName string) *Query // DropTable creates a Query that can be used to drop a table. DropTable(table string) *Query // TruncateTable creates a Query that can be used to truncate a table. TruncateTable(table string) *Query // AddColumn creates a Query that can be used to add a column to a table. AddColumn(table, col, typ string) *Query // DropColumn creates a Query that can be used to drop a column from a table. DropColumn(table, col string) *Query // RenameColumn creates a Query that can be used to rename a column in a table. RenameColumn(table, oldName, newName string) *Query // AlterColumn creates a Query that can be used to change the definition of a table column. AlterColumn(table, col, typ string) *Query // AddPrimaryKey creates a Query that can be used to specify primary key(s) for a table. // The "name" parameter specifies the name of the primary key constraint. AddPrimaryKey(table, name string, cols ...string) *Query // DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table. DropPrimaryKey(table, name string) *Query // AddForeignKey creates a Query that can be used to add a foreign key constraint to a table. // The length of cols and refCols must be the same as they refer to the primary and referential columns. // The optional "options" parameters will be appended to the SQL statement. They can be used to // specify options such as "ON DELETE CASCADE". AddForeignKey(table, name string, cols, refCols []string, refTable string, options ...string) *Query // DropForeignKey creates a Query that can be used to remove the named foreign key constraint from a table. DropForeignKey(table, name string) *Query // CreateIndex creates a Query that can be used to create an index for a table. CreateIndex(table, name string, cols ...string) *Query // CreateUniqueIndex creates a Query that can be used to create a unique index for a table. CreateUniqueIndex(table, name string, cols ...string) *Query // DropIndex creates a Query that can be used to remove the named index from a table. DropIndex(table, name string) *Query } // BaseBuilder provides a basic implementation of the Builder interface. type BaseBuilder struct { db *DB executor Executor } // NewBaseBuilder creates a new BaseBuilder instance. func NewBaseBuilder(db *DB, executor Executor) *BaseBuilder { return &BaseBuilder{db, executor} } // DB returns the DB instance that this builder is associated with. func (b *BaseBuilder) DB() *DB { return b.db } // Executor returns the executor object (a DB instance or a transaction) for executing SQL statements. func (b *BaseBuilder) Executor() Executor { return b.executor } // NewQuery creates a new Query object with the given SQL statement. // The SQL statement may contain parameter placeholders which can be bound with actual parameter // values before the statement is executed. func (b *BaseBuilder) NewQuery(sql string) *Query { return NewQuery(b.db, b.executor, sql) } // GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. func (b *BaseBuilder) GeneratePlaceholder(int) string { return "?" } // Quote quotes a string so that it can be embedded in a SQL statement as a string value. func (b *BaseBuilder) Quote(s string) string { return "'" + strings.Replace(s, "'", "''", -1) + "'" } // QuoteSimpleTableName quotes a simple table name. // A simple table name does not contain any schema prefix. func (b *BaseBuilder) QuoteSimpleTableName(s string) string { if strings.Contains(s, `"`) { return s } return `"` + s + `"` } // QuoteSimpleColumnName quotes a simple column name. // A simple column name does not contain any table prefix. func (b *BaseBuilder) QuoteSimpleColumnName(s string) string { if strings.Contains(s, `"`) || s == "*" { return s } return `"` + s + `"` } // Insert creates a Query that represents an INSERT SQL statement. // The keys of cols are the column names, while the values of cols are the corresponding column // values to be inserted. func (b *BaseBuilder) Insert(table string, cols Params) *Query { names := make([]string, 0, len(cols)) for name := range cols { names = append(names, name) } sort.Strings(names) params := Params{} columns := make([]string, 0, len(names)) values := make([]string, 0, len(names)) for _, name := range names { columns = append(columns, b.db.QuoteColumnName(name)) value := cols[name] if e, ok := value.(Expression); ok { values = append(values, e.Build(b.db, params)) } else { values = append(values, fmt.Sprintf("{:p%v}", len(params))) params[fmt.Sprintf("p%v", len(params))] = value } } var sql string if len(names) == 0 { sql = fmt.Sprintf("INSERT INTO %v DEFAULT VALUES", b.db.QuoteTableName(table)) } else { sql = fmt.Sprintf("INSERT INTO %v (%v) VALUES (%v)", b.db.QuoteTableName(table), strings.Join(columns, ", "), strings.Join(values, ", "), ) } return b.NewQuery(sql).Bind(params) } // Upsert creates a Query that represents an UPSERT SQL statement. // Upsert inserts a row into the table if the primary key or unique index is not found. // Otherwise it will update the row with the new values. // The keys of cols are the column names, while the values of cols are the corresponding column // values to be inserted. func (b *BaseBuilder) Upsert(table string, cols Params, constraints ...string) *Query { q := b.NewQuery("") q.LastError = errors.New("Upsert is not supported") return q } // Update creates a Query that represents an UPDATE SQL statement. // The keys of cols are the column names, while the values of cols are the corresponding new column // values. If the "where" expression is nil, the UPDATE SQL statement will have no WHERE clause // (be careful in this case as the SQL statement will update ALL rows in the table). func (b *BaseBuilder) Update(table string, cols Params, where Expression) *Query { names := make([]string, 0, len(cols)) for name := range cols { names = append(names, name) } sort.Strings(names) params := Params{} lines := make([]string, 0, len(names)) for _, name := range names { value := cols[name] name = b.db.QuoteColumnName(name) if e, ok := value.(Expression); ok { lines = append(lines, name+"="+e.Build(b.db, params)) } else { lines = append(lines, fmt.Sprintf("%v={:p%v}", name, len(params))) params[fmt.Sprintf("p%v", len(params))] = value } } sql := fmt.Sprintf("UPDATE %v SET %v", b.db.QuoteTableName(table), strings.Join(lines, ", ")) if where != nil { w := where.Build(b.db, params) if w != "" { sql += " WHERE " + w } } return b.NewQuery(sql).Bind(params) } // Delete creates a Query that represents a DELETE SQL statement. // If the "where" expression is nil, the DELETE SQL statement will have no WHERE clause // (be careful in this case as the SQL statement will delete ALL rows in the table). func (b *BaseBuilder) Delete(table string, where Expression) *Query { sql := "DELETE FROM " + b.db.QuoteTableName(table) params := Params{} if where != nil { w := where.Build(b.db, params) if w != "" { sql += " WHERE " + w } } return b.NewQuery(sql).Bind(params) } // CreateTable creates a Query that represents a CREATE TABLE SQL statement. // The keys of cols are the column names, while the values of cols are the corresponding column types. // The optional "options" parameters will be appended to the generated SQL statement. func (b *BaseBuilder) CreateTable(table string, cols map[string]string, options ...string) *Query { names := []string{} for name := range cols { names = append(names, name) } sort.Strings(names) columns := []string{} for _, name := range names { columns = append(columns, b.db.QuoteColumnName(name)+" "+cols[name]) } sql := fmt.Sprintf("CREATE TABLE %v (%v)", b.db.QuoteTableName(table), strings.Join(columns, ", ")) for _, opt := range options { sql += " " + opt } return b.NewQuery(sql) } // RenameTable creates a Query that can be used to rename a table. func (b *BaseBuilder) RenameTable(oldName, newName string) *Query { sql := fmt.Sprintf("RENAME TABLE %v TO %v", b.db.QuoteTableName(oldName), b.db.QuoteTableName(newName)) return b.NewQuery(sql) } // DropTable creates a Query that can be used to drop a table. func (b *BaseBuilder) DropTable(table string) *Query { sql := "DROP TABLE " + b.db.QuoteTableName(table) return b.NewQuery(sql) } // TruncateTable creates a Query that can be used to truncate a table. func (b *BaseBuilder) TruncateTable(table string) *Query { sql := "TRUNCATE TABLE " + b.db.QuoteTableName(table) return b.NewQuery(sql) } // AddColumn creates a Query that can be used to add a column to a table. func (b *BaseBuilder) AddColumn(table, col, typ string) *Query { sql := fmt.Sprintf("ALTER TABLE %v ADD %v %v", b.db.QuoteTableName(table), b.db.QuoteColumnName(col), typ) return b.NewQuery(sql) } // DropColumn creates a Query that can be used to drop a column from a table. func (b *BaseBuilder) DropColumn(table, col string) *Query { sql := fmt.Sprintf("ALTER TABLE %v DROP COLUMN %v", b.db.QuoteTableName(table), b.db.QuoteColumnName(col)) return b.NewQuery(sql) } // RenameColumn creates a Query that can be used to rename a column in a table. func (b *BaseBuilder) RenameColumn(table, oldName, newName string) *Query { sql := fmt.Sprintf("ALTER TABLE %v RENAME COLUMN %v TO %v", b.db.QuoteTableName(table), b.db.QuoteColumnName(oldName), b.db.QuoteColumnName(newName)) return b.NewQuery(sql) } // AlterColumn creates a Query that can be used to change the definition of a table column. func (b *BaseBuilder) AlterColumn(table, col, typ string) *Query { col = b.db.QuoteColumnName(col) sql := fmt.Sprintf("ALTER TABLE %v CHANGE %v %v %v", b.db.QuoteTableName(table), col, col, typ) return b.NewQuery(sql) } // AddPrimaryKey creates a Query that can be used to specify primary key(s) for a table. // The "name" parameter specifies the name of the primary key constraint. func (b *BaseBuilder) AddPrimaryKey(table, name string, cols ...string) *Query { sql := fmt.Sprintf("ALTER TABLE %v ADD CONSTRAINT %v PRIMARY KEY (%v)", b.db.QuoteTableName(table), b.db.QuoteColumnName(name), b.quoteColumns(cols)) return b.NewQuery(sql) } // DropPrimaryKey creates a Query that can be used to remove the named primary key constraint from a table. func (b *BaseBuilder) DropPrimaryKey(table, name string) *Query { sql := fmt.Sprintf("ALTER TABLE %v DROP CONSTRAINT %v", b.db.QuoteTableName(table), b.db.QuoteColumnName(name)) return b.NewQuery(sql) } // AddForeignKey creates a Query that can be used to add a foreign key constraint to a table. // The length of cols and refCols must be the same as they refer to the primary and referential columns. // The optional "options" parameters will be appended to the SQL statement. They can be used to // specify options such as "ON DELETE CASCADE". func (b *BaseBuilder) AddForeignKey(table, name string, cols, refCols []string, refTable string, options ...string) *Query { sql := fmt.Sprintf("ALTER TABLE %v ADD CONSTRAINT %v FOREIGN KEY (%v) REFERENCES %v (%v)", b.db.QuoteTableName(table), b.db.QuoteColumnName(name), b.quoteColumns(cols), b.db.QuoteTableName(refTable), b.quoteColumns(refCols)) for _, opt := range options { sql += " " + opt } return b.NewQuery(sql) } // DropForeignKey creates a Query that can be used to remove the named foreign key constraint from a table. func (b *BaseBuilder) DropForeignKey(table, name string) *Query { sql := fmt.Sprintf("ALTER TABLE %v DROP CONSTRAINT %v", b.db.QuoteTableName(table), b.db.QuoteColumnName(name)) return b.NewQuery(sql) } // CreateIndex creates a Query that can be used to create an index for a table. func (b *BaseBuilder) CreateIndex(table, name string, cols ...string) *Query { sql := fmt.Sprintf("CREATE INDEX %v ON %v (%v)", b.db.QuoteColumnName(name), b.db.QuoteTableName(table), b.quoteColumns(cols)) return b.NewQuery(sql) } // CreateUniqueIndex creates a Query that can be used to create a unique index for a table. func (b *BaseBuilder) CreateUniqueIndex(table, name string, cols ...string) *Query { sql := fmt.Sprintf("CREATE UNIQUE INDEX %v ON %v (%v)", b.db.QuoteColumnName(name), b.db.QuoteTableName(table), b.quoteColumns(cols)) return b.NewQuery(sql) } // DropIndex creates a Query that can be used to remove the named index from a table. func (b *BaseBuilder) DropIndex(table, name string) *Query { sql := fmt.Sprintf("DROP INDEX %v ON %v", b.db.QuoteColumnName(name), b.db.QuoteTableName(table)) return b.NewQuery(sql) } // quoteColumns quotes a list of columns and concatenates them with commas. func (b *BaseBuilder) quoteColumns(cols []string) string { s := "" for i, col := range cols { if i == 0 { s = b.db.QuoteColumnName(col) } else { s += ", " + b.db.QuoteColumnName(col) } } return s }
builder.go
0.780537
0.584153
builder.go
starcoder
package distributions import ( "math" "gonum.org/v1/gonum/integrate/quad" "gonum.org/v1/gonum/stat/distuv" "scientificgo.org/special" ) // consistent interface for statistica distributions func findlimits(f func(x float64) float64) float64 { val := 0.0 x := 0.0 for !math.IsNaN(val) { val = f(x) x = x + 2 } // val = 0 for math.IsNaN(val) { val = f(x) x = x - .1 } return x //- .2 } // This is needed because of errors that sometimes result from // integrating t distributions func Integrate(f func(float64) float64, min float64, max float64) float64 { auc := quad.Fixed(f, min, max, 100, nil, 10000) if math.IsNaN(auc) { limits := findlimits(f) min := limits * -1 max := limits * 1 auc = quad.Fixed(f, min, max, 100000, nil, 10000) } else { auc = quad.Fixed(f, min, max, 100000, nil, 10000) } return auc } func Dunif(x float64, min float64, max float64) float64 { dist := distuv.Uniform{ Min: min, Max: max, Src: nil, } return dist.Prob(x) } func Dbinom(x float64, n float64, p float64) float64 { dist := distuv.Binomial{ N: n, P: p, Src: nil, } return dist.Prob(x) } func Dbeta(x float64, shape1 float64, shape2 float64) float64 { dist := distuv.Beta{ Alpha: shape1, Beta: shape2, Src: nil, } return dist.Prob(x) } func Scaled_shifted_t(x float64, mean float64, sd float64, df float64) float64 { dist := distuv.StudentsT{ Mu: mean, Sigma: sd, Nu: df, Src: nil, } return dist.Prob(x) } func Dnorm(x float64, mean float64, sd float64) float64 { dist := distuv.Normal{ Mu: mean, Sigma: sd, Src: nil, } return dist.Prob(x) } func Dt(x float64, df float64, ncp float64) float64 { var x2 float64 = x * x var ncx2 float64 = ncp * ncp * x2 var fac1 float64 = df + x2 lgammadf1, _ := math.Lgamma(df + 1) lgamma_halfdf, _ := math.Lgamma(df / 2) trm1 := df/2.*math.Log(df) + lgammadf1 trm1 -= df*math.Log(2) + ncp*ncp/2 + (df/2)*math.Log(fac1) + lgamma_halfdf var Px float64 = math.Exp(trm1) var valF float64 = ncx2 / (2 * fac1) trm1 = math.Sqrt(2) * ncp * x * special.HypPFQ([]float64{df/2 + 1}, []float64{1.5}, valF) trm1 /= fac1 * math.Gamma((df+1)/2) var trm2 float64 = special.HypPFQ([]float64{(df + 1) / 2}, []float64{0.5}, valF) trm2 /= math.Sqrt(fac1) * math.Gamma(df/2+1) Px *= trm1 + trm2 return Px } func Dcauchy(x float64, location float64, scale float64) float64 { dist := distuv.StudentsT{ Mu: location, Sigma: scale, Nu: 1, Src: nil, } return dist.Prob(x) }
distributions.go
0.832985
0.509886
distributions.go
starcoder
package xprop /* xprop/atom.go contains functions related to interning atoms and retrieving atom names from an atom identifier. It also manages an atom cache so that once an atom is interned from the X server, all future atom interns use that value. (So that one and only one request is sent for interning each atom.) */ import ( "fmt" "github.com/BurntSushi/xgb/xproto" "github.com/BurntSushi/xgbutil" ) // Atm is a short alias for Atom in the common case of interning an atom. // Namely, interning the atom always succeeds. (If the atom does not already // exist, a new one is created.) func Atm(xu *xgbutil.XUtil, name string) (xproto.Atom, error) { aid, err := Atom(xu, name, false) if err != nil { return 0, err } if aid == 0 { return 0, fmt.Errorf("Atm: '%s' returned an identifier of 0.", name) } return aid, err } // Atom interns an atom and panics if there is any error. func Atom(xu *xgbutil.XUtil, name string, onlyIfExists bool) (xproto.Atom, error) { // Check the cache first if aid, ok := atomGet(xu, name); ok { return aid, nil } reply, err := xproto.InternAtom(xu.Conn(), onlyIfExists, uint16(len(name)), name).Reply() if err != nil { return 0, fmt.Errorf("Atom: Error interning atom '%s': %s", name, err) } // If we're here, it means we didn't have this atom cached. So cache it! cacheAtom(xu, name, reply.Atom) return reply.Atom, nil } // AtomName fetches a string representation of an ATOM given its integer id. func AtomName(xu *xgbutil.XUtil, aid xproto.Atom) (string, error) { // Check the cache first if atomName, ok := atomNameGet(xu, aid); ok { return string(atomName), nil } reply, err := xproto.GetAtomName(xu.Conn(), aid).Reply() if err != nil { return "", fmt.Errorf("AtomName: Error fetching name for ATOM "+ "id '%d': %s", aid, err) } // If we're here, it means we didn't have ths ATOM id cached. So cache it. atomName := string(reply.Name) cacheAtom(xu, atomName, aid) return atomName, nil } // atomGet retrieves an atom identifier from a cache if it exists. func atomGet(xu *xgbutil.XUtil, name string) (xproto.Atom, bool) { xu.AtomsLck.RLock() defer xu.AtomsLck.RUnlock() aid, ok := xu.Atoms[name] return aid, ok } // atomNameGet retrieves an atom name from a cache if it exists. func atomNameGet(xu *xgbutil.XUtil, aid xproto.Atom) (string, bool) { xu.AtomNamesLck.RLock() defer xu.AtomNamesLck.RUnlock() name, ok := xu.AtomNames[aid] return name, ok } // cacheAtom puts an atom into the cache. func cacheAtom(xu *xgbutil.XUtil, name string, aid xproto.Atom) { xu.AtomsLck.Lock() xu.AtomNamesLck.Lock() defer xu.AtomsLck.Unlock() defer xu.AtomNamesLck.Unlock() xu.Atoms[name] = aid xu.AtomNames[aid] = name }
vendor/github.com/BurntSushi/xgbutil/xprop/atom.go
0.737536
0.605945
atom.go
starcoder
package soba import ( "fmt" "strings" "time" ) // A Field is an operation that add a key-value pair to the logger's context. // Most fields are lazily marshaled, so it's inexpensive to add fields to disabled debug-level log statements. type Field struct { name string handler func(Encoder) } // Name returns field key. func (field Field) Name() string { return field.name } // Write marshaled current field to given encoder so its key-value pair will be available in logger's context. func (field Field) Write(encoder Encoder) { field.handler(encoder) } // NewField creates a new field. func NewField(name string, handler func(Encoder)) Field { return Field{ name: strings.ToLower(name), handler: handler, } } // ---------------------------------------------------------------------------- // Object // ---------------------------------------------------------------------------- // Object creates a typesafe Field with given key and ObjectMarshaler. func Object(key string, value ObjectMarshaler) Field { return NewField(key, func(encoder Encoder) { encoder.AddObject(key, value) }) } // Int creates a typesafe Field with given key and int. func Int(key string, value int) Field { return NewField(key, func(encoder Encoder) { encoder.AddInt(key, value) }) } // Int8 creates a typesafe Field with given key and int8. func Int8(key string, value int8) Field { return NewField(key, func(encoder Encoder) { encoder.AddInt8(key, value) }) } // Int16 creates a typesafe Field with given key and int16. func Int16(key string, value int16) Field { return NewField(key, func(encoder Encoder) { encoder.AddInt16(key, value) }) } // Int32 creates a typesafe Field with given key and int32. func Int32(key string, value int32) Field { return NewField(key, func(encoder Encoder) { encoder.AddInt32(key, value) }) } // Int64 creates a typesafe Field with given key and int64. func Int64(key string, value int64) Field { return NewField(key, func(encoder Encoder) { encoder.AddInt64(key, value) }) } // Uint creates a typesafe Field with given key and uint. func Uint(key string, value uint) Field { return NewField(key, func(encoder Encoder) { encoder.AddUint(key, value) }) } // Uint8 creates a typesafe Field with given key and uint8. func Uint8(key string, value uint8) Field { return NewField(key, func(encoder Encoder) { encoder.AddUint8(key, value) }) } // Uint16 creates a typesafe Field with given key and uint16. func Uint16(key string, value uint16) Field { return NewField(key, func(encoder Encoder) { encoder.AddUint16(key, value) }) } // Uint32 creates a typesafe Field with given key and uint32. func Uint32(key string, value uint32) Field { return NewField(key, func(encoder Encoder) { encoder.AddUint32(key, value) }) } // Uint64 creates a typesafe Field with given key and uint64. func Uint64(key string, value uint64) Field { return NewField(key, func(encoder Encoder) { encoder.AddUint64(key, value) }) } // Float32 creates a typesafe Field with given key and float32. func Float32(key string, value float32) Field { return NewField(key, func(encoder Encoder) { encoder.AddFloat32(key, value) }) } // Float64 creates a typesafe Field with given key and float64. func Float64(key string, value float64) Field { return NewField(key, func(encoder Encoder) { encoder.AddFloat64(key, value) }) } // String creates a typesafe Field with given key and string. func String(key, value string) Field { return NewField(key, func(encoder Encoder) { encoder.AddString(key, value) }) } // Stringer creates a typesafe Field with given key and Stringer. func Stringer(key string, value fmt.Stringer) Field { return NewField(key, func(encoder Encoder) { encoder.AddStringer(key, value) }) } // Time creates a typesafe Field with given key and Time. func Time(key string, value time.Time) Field { return NewField(key, func(encoder Encoder) { encoder.AddTime(key, value) }) } // Duration creates a typesafe Field with given key and Duration. func Duration(key string, value time.Duration) Field { return NewField(key, func(encoder Encoder) { encoder.AddDuration(key, value) }) } // Bool creates a typesafe Field with given key and Bool. func Bool(key string, value bool) Field { return NewField(key, func(encoder Encoder) { encoder.AddBool(key, value) }) } // Binary creates a typesafe Field with given key and slice of byte. func Binary(key string, value []byte) Field { return NewField(key, func(encoder Encoder) { encoder.AddBinary(key, value) }) } // Skip is a no-op Field func Skip(key string) Field { return NewField(key, func(encoder Encoder) {}) } // Error is an alias of NamedError("error", err). func Error(err error) Field { return NamedError("error", err) } // NamedError creates a typesafe Field with given key and error. func NamedError(key string, err error) Field { if err == nil { return Skip(key) } return String(key, err.Error()) } // Null creates a typesafe Field with given key as null value. func Null(key string) Field { return NewField(key, func(encoder Encoder) { encoder.AddNull(key) }) } // ---------------------------------------------------------------------------- // Array // ---------------------------------------------------------------------------- // Objects creates a typesafe Field with given key and collection of ObjectMarshaler. func Objects(key string, values []ObjectMarshaler) Field { return NewField(key, func(encoder Encoder) { encoder.AddObjects(key, values) }) } // Array creates a typesafe Field with given key and ArrayMarshaler. func Array(key string, value ArrayMarshaler) Field { return NewField(key, func(encoder Encoder) { encoder.AddArray(key, value) }) } // Ints creates a typesafe Field with given key and slice of int. func Ints(key string, values []int) Field { return NewField(key, func(encoder Encoder) { encoder.AddInts(key, values) }) } // Int8s creates a typesafe Field with given key and slice of int8. func Int8s(key string, values []int8) Field { return NewField(key, func(encoder Encoder) { encoder.AddInt8s(key, values) }) } // Int16s creates a typesafe Field with given key and slice of int16. func Int16s(key string, values []int16) Field { return NewField(key, func(encoder Encoder) { encoder.AddInt16s(key, values) }) } // Int32s creates a typesafe Field with given key and slice of int32. func Int32s(key string, values []int32) Field { return NewField(key, func(encoder Encoder) { encoder.AddInt32s(key, values) }) } // Int64s creates a typesafe Field with given key and slice of int64. func Int64s(key string, values []int64) Field { return NewField(key, func(encoder Encoder) { encoder.AddInt64s(key, values) }) } // Uints creates a typesafe Field with given key and slice of uint. func Uints(key string, values []uint) Field { return NewField(key, func(encoder Encoder) { encoder.AddUints(key, values) }) } // Uint8s creates a typesafe Field with given key and slice of uint8. func Uint8s(key string, values []uint8) Field { return NewField(key, func(encoder Encoder) { encoder.AddUint8s(key, values) }) } // Uint16s creates a typesafe Field with given key and slice of uint16. func Uint16s(key string, values []uint16) Field { return NewField(key, func(encoder Encoder) { encoder.AddUint16s(key, values) }) } // Uint32s creates a typesafe Field with given key and slice of uint32. func Uint32s(key string, values []uint32) Field { return NewField(key, func(encoder Encoder) { encoder.AddUint32s(key, values) }) } // Uint64s creates a typesafe Field with given key and slice of uint64. func Uint64s(key string, values []uint64) Field { return NewField(key, func(encoder Encoder) { encoder.AddUint64s(key, values) }) } // Float32s creates a typesafe Field with given key and slice of float32. func Float32s(key string, values []float32) Field { return NewField(key, func(encoder Encoder) { encoder.AddFloat32s(key, values) }) } // Float64s creates a typesafe Field with given key and slice of float64. func Float64s(key string, values []float64) Field { return NewField(key, func(encoder Encoder) { encoder.AddFloat64s(key, values) }) } // Strings creates a typesafe Field with given key and slice of string. func Strings(key string, values []string) Field { return NewField(key, func(encoder Encoder) { encoder.AddStrings(key, values) }) } // Stringers creates a typesafe Field with given key and slice of Stringer. func Stringers(key string, values []fmt.Stringer) Field { return NewField(key, func(encoder Encoder) { encoder.AddStringers(key, values) }) } // Times creates a typesafe Field with given key and slice of Time. func Times(key string, values []time.Time) Field { return NewField(key, func(encoder Encoder) { encoder.AddTimes(key, values) }) } // Durations creates a typesafe Field with given key and slice of Duration. func Durations(key string, values []time.Duration) Field { return NewField(key, func(encoder Encoder) { encoder.AddDurations(key, values) }) } // Bools creates a typesafe Field with given key and slice of boolean. func Bools(key string, values []bool) Field { return NewField(key, func(encoder Encoder) { encoder.AddBools(key, values) }) } // Errors creates a typesafe Field with given key and slice of error. func Errors(key string, errors []error) Field { return NewField(key, func(encoder Encoder) { list := []string{} for i := range errors { list = append(list, errors[i].Error()) } encoder.AddStrings(key, list) }) }
fields.go
0.818011
0.415017
fields.go
starcoder
package e2e import ( "testing" "time" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/watch" "github.com/kok-stack/native-kubelet/internal/test/e2e/framework" "github.com/kok-stack/native-kubelet/internal/test/suite" ) const defaultWatchTimeout = 2 * time.Minute // f is a testing framework that is accessible across the e2e package var f *framework.Framework // EndToEndTestSuite holds the setup, teardown, and shouldSkipTest functions for a specific provider type EndToEndTestSuite struct { setup suite.SetUpFunc teardown suite.TeardownFunc shouldSkipTest suite.ShouldSkipTestFunc } // EndToEndTestSuiteConfig is the config passed to initialize the testing framework and test suite. type EndToEndTestSuiteConfig struct { // Kubeconfig is the path to the kubeconfig file to use when running the test suite outside a Kubernetes cluster. Kubeconfig string // Namespace is the name of the Kubernetes namespace to use for running the test suite (i.e. where to create pods). Namespace string // NodeName is the name of the virtual-kubelet node to test. NodeName string // WatchTimeout is the duration for which the framework watch a particular condition to be satisfied (e.g. watches a pod becoming ready) WatchTimeout time.Duration // Setup is a function that sets up provider-specific resource in the test suite Setup suite.SetUpFunc // Teardown is a function that tears down provider-specific resources from the test suite Teardown suite.TeardownFunc // ShouldSkipTest is a function that determines whether the test suite should skip certain tests ShouldSkipTest suite.ShouldSkipTestFunc } // Setup runs the setup function from the provider and other // procedures before running the test suite func (ts *EndToEndTestSuite) Setup(t *testing.T) { if err := ts.setup(); err != nil { t.Fatal(err) } // Wait for the virtual kubelet node resource to become fully ready if err := f.WaitUntilNodeCondition(func(ev watch.Event) (bool, error) { n := ev.Object.(*corev1.Node) if n.Name != f.NodeName { return false, nil } for _, c := range n.Status.Conditions { if c.Type != "Ready" { continue } t.Log(c.Status) return c.Status == corev1.ConditionTrue, nil } return false, nil }); err != nil { t.Fatal(err) } } // Teardown runs the teardown function from the provider and other // procedures after running the test suite func (ts *EndToEndTestSuite) Teardown() { if err := ts.teardown(); err != nil { panic(err) } } // ShouldSkipTest returns true if a provider wants to skip running a particular test func (ts *EndToEndTestSuite) ShouldSkipTest(testName string) bool { return ts.shouldSkipTest(testName) } // Run runs tests registered in the test suite func (ts *EndToEndTestSuite) Run(t *testing.T) { suite.Run(t, ts) } // NewEndToEndTestSuite returns a new EndToEndTestSuite given a test suite configuration, // setup, and teardown functions from provider func NewEndToEndTestSuite(cfg EndToEndTestSuiteConfig) *EndToEndTestSuite { if cfg.Namespace == "" { panic("Empty namespace") } else if cfg.NodeName == "" { panic("Empty node name") } if cfg.WatchTimeout == time.Duration(0) { cfg.WatchTimeout = defaultWatchTimeout } f = framework.NewTestingFramework(cfg.Kubeconfig, cfg.Namespace, cfg.NodeName, cfg.WatchTimeout) emptyFunc := func() error { return nil } if cfg.Setup == nil { cfg.Setup = emptyFunc } if cfg.Teardown == nil { cfg.Teardown = emptyFunc } if cfg.ShouldSkipTest == nil { // This will not skip any test in the test suite cfg.ShouldSkipTest = func(_ string) bool { return false } } return &EndToEndTestSuite{ setup: cfg.Setup, teardown: cfg.Teardown, shouldSkipTest: cfg.ShouldSkipTest, } }
test/e2e/suite.go
0.572842
0.420897
suite.go
starcoder
package semver import ( "fmt" "strconv" "strings" ) // SemVer is the immutable semantic version per https://semver.org type SemVer struct { major int minor int patch int } func New(major, minor, patch int) SemVer { return SemVer{ major: major, minor: minor, patch: patch, } } var zero = New(0, 0, 0) func Zero() SemVer { return zero } // Versions implements sort.Interface to get decreasing order. type Versions []SemVer func (v Versions) Len() int { return len(v) } func (v Versions) Less(i, j int) bool { return v[j].LessThan(v[i]) } func (v Versions) Swap(i, j int) { v[i], v[j] = v[j], v[i] } func Parse(raw string) (SemVer, error) { if len(raw) < 6 { // e.g. minimal length is 6, e.g. "v1.2.3" return zero, fmt.Errorf("%q too short to be a version", raw) } if raw[0] != 'v' { return zero, fmt.Errorf("%q must start with letter 'v'", raw) } fields := strings.Split(raw[1:], ".") if len(fields) < 3 { return zero, fmt.Errorf("%q doesn't have the form v1.2.3", raw) } n := make([]int, 3) for i := 0; i < 3; i++ { var err error n[i], err = strconv.Atoi(fields[i]) if err != nil { return zero, err } } return New(n[0], n[1], n[2]), nil } func (v SemVer) Bump(b SvBump) SemVer { switch b { case Major: return New(v.major+1, 0, 0) case Minor: return New(v.major, v.minor+1, 0) default: return New(v.major, v.minor, v.patch+1) } } func (v SemVer) BranchLabel() string { return fmt.Sprintf("v%d.%d", v.major, v.minor) } func (v SemVer) String() string { return fmt.Sprintf("v%d.%d.%d", v.major, v.minor, v.patch) } func (v SemVer) Pretty() string { if v.IsZero() { return "" } return v.String() } func (v SemVer) Equals(o SemVer) bool { return v.major == o.major && v.minor == o.minor && v.patch == o.patch } func (v SemVer) LessThan(o SemVer) bool { return v.major < o.major || (v.major == o.major && v.minor < o.minor) || (v.major == o.major && v.minor == o.minor && v.patch < o.patch) } func (v SemVer) IsZero() bool { return v.Equals(zero) }
cmd/gorepomod/internal/semver/semver.go
0.73659
0.40251
semver.go
starcoder
package pulsar import ( "net/url" "strconv" "strings" "github.com/streamnative/pulsarctl/pkg/pulsar/common" "github.com/streamnative/pulsarctl/pkg/pulsar/utils" ) // Namespaces is admin interface for namespaces management type Namespaces interface { // GetNamespaces returns the list of all the namespaces for a certain tenant GetNamespaces(tenant string) ([]string, error) // GetTopics returns the list of all the topics under a certain namespace GetTopics(namespace string) ([]string, error) // GetPolicies returns the dump all the policies specified for a namespace GetPolicies(namespace string) (*utils.Policies, error) // CreateNamespace creates a new empty namespace with no policies attached CreateNamespace(namespace string) error // CreateNsWithNumBundles creates a new empty namespace with no policies attached CreateNsWithNumBundles(namespace string, numBundles int) error // CreateNsWithPolices creates a new namespace with the specified policies CreateNsWithPolices(namespace string, polices utils.Policies) error // CreateNsWithBundlesData creates a new empty namespace with no policies attached CreateNsWithBundlesData(namespace string, bundleData *utils.BundlesData) error // DeleteNamespace deletes an existing namespace DeleteNamespace(namespace string) error // DeleteNamespaceBundle deletes an existing bundle in a namespace DeleteNamespaceBundle(namespace string, bundleRange string) error // SetNamespaceMessageTTL sets the messages Time to Live for all the topics within a namespace SetNamespaceMessageTTL(namespace string, ttlInSeconds int) error // GetNamespaceMessageTTL returns the message TTL for a namespace GetNamespaceMessageTTL(namespace string) (int, error) // GetRetention returns the retention configuration for a namespace GetRetention(namespace string) (*utils.RetentionPolicies, error) // SetRetention sets the retention configuration for all the topics on a namespace SetRetention(namespace string, policy utils.RetentionPolicies) error // GetBacklogQuotaMap returns backlog quota map on a namespace GetBacklogQuotaMap(namespace string) (map[utils.BacklogQuotaType]utils.BacklogQuota, error) // SetBacklogQuota sets a backlog quota for all the topics on a namespace SetBacklogQuota(namespace string, backlogQuota utils.BacklogQuota, backlogQuotaType utils.BacklogQuotaType) error // RemoveBacklogQuota removes a backlog quota policy from a namespace RemoveBacklogQuota(namespace string) error // SetTopicAutoCreation sets topic auto-creation config for a namespace, overriding broker settings SetTopicAutoCreation(namespace utils.NameSpaceName, config utils.TopicAutoCreationConfig) error // RemoveTopicAutoCreation removes topic auto-creation config for a namespace, defaulting to broker settings RemoveTopicAutoCreation(namespace utils.NameSpaceName) error // SetSchemaValidationEnforced sets schema validation enforced for namespace SetSchemaValidationEnforced(namespace utils.NameSpaceName, schemaValidationEnforced bool) error // GetSchemaValidationEnforced returns schema validation enforced for namespace GetSchemaValidationEnforced(namespace utils.NameSpaceName) (bool, error) // SetSchemaAutoUpdateCompatibilityStrategy sets the strategy used to check the a new schema provided // by a producer is compatible with the current schema before it is installed SetSchemaAutoUpdateCompatibilityStrategy(namespace utils.NameSpaceName, strategy utils.SchemaCompatibilityStrategy) error // GetSchemaAutoUpdateCompatibilityStrategy returns the strategy used to check the a new schema provided // by a producer is compatible with the current schema before it is installed GetSchemaAutoUpdateCompatibilityStrategy(namespace utils.NameSpaceName) (utils.SchemaCompatibilityStrategy, error) // ClearOffloadDeleteLag clears the offload deletion lag for a namespace. ClearOffloadDeleteLag(namespace utils.NameSpaceName) error // SetOffloadDeleteLag sets the offload deletion lag for a namespace SetOffloadDeleteLag(namespace utils.NameSpaceName, timeMs int64) error // GetOffloadDeleteLag returns the offload deletion lag for a namespace, in milliseconds GetOffloadDeleteLag(namespace utils.NameSpaceName) (int64, error) // SetOffloadThreshold sets the offloadThreshold for a namespace SetOffloadThreshold(namespace utils.NameSpaceName, threshold int64) error // GetOffloadThreshold returns the offloadThreshold for a namespace GetOffloadThreshold(namespace utils.NameSpaceName) (int64, error) // SetCompactionThreshold sets the compactionThreshold for a namespace SetCompactionThreshold(namespace utils.NameSpaceName, threshold int64) error // GetCompactionThreshold returns the compactionThreshold for a namespace GetCompactionThreshold(namespace utils.NameSpaceName) (int64, error) // SetMaxConsumersPerSubscription sets maxConsumersPerSubscription for a namespace. SetMaxConsumersPerSubscription(namespace utils.NameSpaceName, max int) error // GetMaxConsumersPerSubscription returns the maxConsumersPerSubscription for a namespace. GetMaxConsumersPerSubscription(namespace utils.NameSpaceName) (int, error) // SetMaxConsumersPerTopic sets maxConsumersPerTopic for a namespace. SetMaxConsumersPerTopic(namespace utils.NameSpaceName, max int) error // GetMaxConsumersPerTopic returns the maxProducersPerTopic for a namespace. GetMaxConsumersPerTopic(namespace utils.NameSpaceName) (int, error) // SetMaxProducersPerTopic sets maxProducersPerTopic for a namespace. SetMaxProducersPerTopic(namespace utils.NameSpaceName, max int) error // GetMaxProducersPerTopic returns the maxProducersPerTopic for a namespace. GetMaxProducersPerTopic(namespace utils.NameSpaceName) (int, error) // GetNamespaceReplicationClusters returns the replication clusters for a namespace GetNamespaceReplicationClusters(namespace string) ([]string, error) // SetNamespaceReplicationClusters returns the replication clusters for a namespace SetNamespaceReplicationClusters(namespace string, clusterIds []string) error // SetNamespaceAntiAffinityGroup sets anti-affinity group name for a namespace SetNamespaceAntiAffinityGroup(namespace string, namespaceAntiAffinityGroup string) error // GetAntiAffinityNamespaces returns all namespaces that grouped with given anti-affinity group GetAntiAffinityNamespaces(tenant, cluster, namespaceAntiAffinityGroup string) ([]string, error) // GetNamespaceAntiAffinityGroup returns anti-affinity group name for a namespace GetNamespaceAntiAffinityGroup(namespace string) (string, error) // DeleteNamespaceAntiAffinityGroup deletes anti-affinity group name for a namespace DeleteNamespaceAntiAffinityGroup(namespace string) error // SetDeduplicationStatus sets the deduplication status for all topics within a namespace // When deduplication is enabled, the broker will prevent to store the same Message multiple times SetDeduplicationStatus(namespace string, enableDeduplication bool) error // SetPersistence sets the persistence configuration for all the topics on a namespace SetPersistence(namespace string, persistence utils.PersistencePolicies) error // GetPersistence returns the persistence configuration for a namespace GetPersistence(namespace string) (*utils.PersistencePolicies, error) // SetBookieAffinityGroup sets bookie affinity group for a namespace to isolate namespace write to bookies that are // part of given affinity group SetBookieAffinityGroup(namespace string, bookieAffinityGroup utils.BookieAffinityGroupData) error // DeleteBookieAffinityGroup deletes bookie affinity group configured for a namespace DeleteBookieAffinityGroup(namespace string) error // GetBookieAffinityGroup returns bookie affinity group configured for a namespace GetBookieAffinityGroup(namespace string) (*utils.BookieAffinityGroupData, error) // Unload a namespace from the current serving broker Unload(namespace string) error // UnloadNamespaceBundle unloads namespace bundle UnloadNamespaceBundle(namespace, bundle string) error // SplitNamespaceBundle splits namespace bundle SplitNamespaceBundle(namespace, bundle string, unloadSplitBundles bool) error // GetNamespacePermissions returns permissions on a namespace GetNamespacePermissions(namespace utils.NameSpaceName) (map[string][]common.AuthAction, error) // GrantNamespacePermission grants permission on a namespace. GrantNamespacePermission(namespace utils.NameSpaceName, role string, action []common.AuthAction) error // RevokeNamespacePermission revokes permissions on a namespace. RevokeNamespacePermission(namespace utils.NameSpaceName, role string) error // GrantSubPermission grants permission to role to access subscription's admin-api GrantSubPermission(namespace utils.NameSpaceName, sName string, roles []string) error // RevokeSubPermission revoke permissions on a subscription's admin-api access RevokeSubPermission(namespace utils.NameSpaceName, sName, role string) error // SetSubscriptionAuthMode sets the given subscription auth mode on all topics on a namespace SetSubscriptionAuthMode(namespace utils.NameSpaceName, mode utils.SubscriptionAuthMode) error // SetEncryptionRequiredStatus sets the encryption required status for all topics within a namespace SetEncryptionRequiredStatus(namespace utils.NameSpaceName, encrypt bool) error // UnsubscribeNamespace unsubscribe the given subscription on all topics on a namespace UnsubscribeNamespace(namespace utils.NameSpaceName, sName string) error // UnsubscribeNamespaceBundle unsubscribe the given subscription on all topics on a namespace bundle UnsubscribeNamespaceBundle(namespace utils.NameSpaceName, bundle, sName string) error // ClearNamespaceBundleBacklogForSubscription clears backlog for a given subscription on all // topics on a namespace bundle ClearNamespaceBundleBacklogForSubscription(namespace utils.NameSpaceName, bundle, sName string) error // ClearNamespaceBundleBacklog clears backlog for all topics on a namespace bundle ClearNamespaceBundleBacklog(namespace utils.NameSpaceName, bundle string) error // ClearNamespaceBacklogForSubscription clears backlog for a given subscription on all topics on a namespace ClearNamespaceBacklogForSubscription(namespace utils.NameSpaceName, sName string) error // ClearNamespaceBacklog clears backlog for all topics on a namespace ClearNamespaceBacklog(namespace utils.NameSpaceName) error // SetReplicatorDispatchRate sets replicator-Message-dispatch-rate (Replicators under this namespace // can dispatch this many messages per second) SetReplicatorDispatchRate(namespace utils.NameSpaceName, rate utils.DispatchRate) error // Get replicator-Message-dispatch-rate (Replicators under this namespace // can dispatch this many messages per second) GetReplicatorDispatchRate(namespace utils.NameSpaceName) (utils.DispatchRate, error) // SetSubscriptionDispatchRate sets subscription-Message-dispatch-rate (subscriptions under this namespace // can dispatch this many messages per second) SetSubscriptionDispatchRate(namespace utils.NameSpaceName, rate utils.DispatchRate) error // GetSubscriptionDispatchRate returns subscription-Message-dispatch-rate (subscriptions under this namespace // can dispatch this many messages per second) GetSubscriptionDispatchRate(namespace utils.NameSpaceName) (utils.DispatchRate, error) // SetSubscribeRate sets namespace-subscribe-rate (topics under this namespace will limit by subscribeRate) SetSubscribeRate(namespace utils.NameSpaceName, rate utils.SubscribeRate) error // GetSubscribeRate returns namespace-subscribe-rate (topics under this namespace allow subscribe // times per consumer in a period) GetSubscribeRate(namespace utils.NameSpaceName) (utils.SubscribeRate, error) // SetDispatchRate sets Message-dispatch-rate (topics under this namespace can dispatch // this many messages per second) SetDispatchRate(namespace utils.NameSpaceName, rate utils.DispatchRate) error // GetDispatchRate returns Message-dispatch-rate (topics under this namespace can dispatch // this many messages per second) GetDispatchRate(namespace utils.NameSpaceName) (utils.DispatchRate, error) // SetPublishRate sets the maximum rate or number of messages that producers can publish to topics in this namespace SetPublishRate(namespace utils.NameSpaceName, pubRate utils.PublishRate) error // GetPublishRate gets the maximum rate or number of messages that producer can publish to topics in the namespace GetPublishRate(namespace utils.NameSpaceName) (utils.PublishRate, error) // SetIsAllowAutoUpdateSchema sets whether to allow auto update schema on a namespace SetIsAllowAutoUpdateSchema(namespace utils.NameSpaceName, isAllowAutoUpdateSchema bool) error // GetIsAllowAutoUpdateSchema gets whether to allow auto update schema on a namespace GetIsAllowAutoUpdateSchema(namespace utils.NameSpaceName) (bool, error) } type namespaces struct { pulsar *pulsarClient basePath string } // Namespaces is used to access the namespaces endpoints func (c *pulsarClient) Namespaces() Namespaces { return &namespaces{ pulsar: c, basePath: "/namespaces", } } func (n *namespaces) GetNamespaces(tenant string) ([]string, error) { var namespaces []string endpoint := n.pulsar.endpoint(n.basePath, tenant) err := n.pulsar.Client.Get(endpoint, &namespaces) return namespaces, err } func (n *namespaces) GetTopics(namespace string) ([]string, error) { var topics []string ns, err := utils.GetNamespaceName(namespace) if err != nil { return nil, err } endpoint := n.pulsar.endpoint(n.basePath, ns.String(), "topics") err = n.pulsar.Client.Get(endpoint, &topics) return topics, err } func (n *namespaces) GetPolicies(namespace string) (*utils.Policies, error) { var police utils.Policies ns, err := utils.GetNamespaceName(namespace) if err != nil { return nil, err } endpoint := n.pulsar.endpoint(n.basePath, ns.String()) err = n.pulsar.Client.Get(endpoint, &police) return &police, err } func (n *namespaces) CreateNsWithNumBundles(namespace string, numBundles int) error { return n.CreateNsWithBundlesData(namespace, utils.NewBundlesDataWithNumBundles(numBundles)) } func (n *namespaces) CreateNsWithPolices(namespace string, policies utils.Policies) error { ns, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, ns.String()) return n.pulsar.Client.Put(endpoint, &policies) } func (n *namespaces) CreateNsWithBundlesData(namespace string, bundleData *utils.BundlesData) error { ns, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, ns.String()) polices := new(utils.Policies) polices.Bundles = bundleData return n.pulsar.Client.Put(endpoint, &polices) } func (n *namespaces) CreateNamespace(namespace string) error { ns, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, ns.String()) return n.pulsar.Client.Put(endpoint, nil) } func (n *namespaces) DeleteNamespace(namespace string) error { ns, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, ns.String()) return n.pulsar.Client.Delete(endpoint) } func (n *namespaces) DeleteNamespaceBundle(namespace string, bundleRange string) error { ns, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, ns.String(), bundleRange) return n.pulsar.Client.Delete(endpoint) } func (n *namespaces) GetNamespaceMessageTTL(namespace string) (int, error) { var ttl int nsName, err := utils.GetNamespaceName(namespace) if err != nil { return 0, err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "messageTTL") err = n.pulsar.Client.Get(endpoint, &ttl) return ttl, err } func (n *namespaces) SetNamespaceMessageTTL(namespace string, ttlInSeconds int) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "messageTTL") return n.pulsar.Client.Post(endpoint, &ttlInSeconds) } func (n *namespaces) SetRetention(namespace string, policy utils.RetentionPolicies) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "retention") return n.pulsar.Client.Post(endpoint, &policy) } func (n *namespaces) GetRetention(namespace string) (*utils.RetentionPolicies, error) { var policy utils.RetentionPolicies nsName, err := utils.GetNamespaceName(namespace) if err != nil { return nil, err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "retention") err = n.pulsar.Client.Get(endpoint, &policy) return &policy, err } func (n *namespaces) GetBacklogQuotaMap(namespace string) (map[utils.BacklogQuotaType]utils.BacklogQuota, error) { var backlogQuotaMap map[utils.BacklogQuotaType]utils.BacklogQuota nsName, err := utils.GetNamespaceName(namespace) if err != nil { return nil, err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "backlogQuotaMap") err = n.pulsar.Client.Get(endpoint, &backlogQuotaMap) return backlogQuotaMap, err } func (n *namespaces) SetBacklogQuota(namespace string, backlogQuota utils.BacklogQuota, backlogQuotaType utils.BacklogQuotaType) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "backlogQuota") params := make(map[string]string) params["backlogQuotaType"] = string(backlogQuotaType) return n.pulsar.Client.PostWithQueryParams(endpoint, &backlogQuota, params) } func (n *namespaces) RemoveBacklogQuota(namespace string) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "backlogQuota") params := map[string]string{ "backlogQuotaType": string(utils.DestinationStorage), } return n.pulsar.Client.DeleteWithQueryParams(endpoint, params) } func (n *namespaces) SetTopicAutoCreation(namespace utils.NameSpaceName, config utils.TopicAutoCreationConfig) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "autoTopicCreation") return n.pulsar.Client.Post(endpoint, &config) } func (n *namespaces) RemoveTopicAutoCreation(namespace utils.NameSpaceName) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "autoTopicCreation") return n.pulsar.Client.Delete(endpoint) } func (n *namespaces) SetSchemaValidationEnforced(namespace utils.NameSpaceName, schemaValidationEnforced bool) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "schemaValidationEnforced") return n.pulsar.Client.Post(endpoint, schemaValidationEnforced) } func (n *namespaces) GetSchemaValidationEnforced(namespace utils.NameSpaceName) (bool, error) { var result bool endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "schemaValidationEnforced") err := n.pulsar.Client.Get(endpoint, &result) return result, err } func (n *namespaces) SetSchemaAutoUpdateCompatibilityStrategy(namespace utils.NameSpaceName, strategy utils.SchemaCompatibilityStrategy) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "schemaAutoUpdateCompatibilityStrategy") return n.pulsar.Client.Put(endpoint, strategy.String()) } func (n *namespaces) GetSchemaAutoUpdateCompatibilityStrategy(namespace utils.NameSpaceName) ( utils.SchemaCompatibilityStrategy, error) { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "schemaAutoUpdateCompatibilityStrategy") b, err := n.pulsar.Client.GetWithQueryParams(endpoint, nil, nil, false) if err != nil { return "", err } s, err := utils.ParseSchemaAutoUpdateCompatibilityStrategy(strings.ReplaceAll(string(b), "\"", "")) if err != nil { return "", err } return s, nil } func (n *namespaces) ClearOffloadDeleteLag(namespace utils.NameSpaceName) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "offloadDeletionLagMs") return n.pulsar.Client.Delete(endpoint) } func (n *namespaces) SetOffloadDeleteLag(namespace utils.NameSpaceName, timeMs int64) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "offloadDeletionLagMs") return n.pulsar.Client.Put(endpoint, timeMs) } func (n *namespaces) GetOffloadDeleteLag(namespace utils.NameSpaceName) (int64, error) { var result int64 endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "offloadDeletionLagMs") err := n.pulsar.Client.Get(endpoint, &result) return result, err } func (n *namespaces) SetMaxConsumersPerSubscription(namespace utils.NameSpaceName, max int) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "maxConsumersPerSubscription") return n.pulsar.Client.Post(endpoint, max) } func (n *namespaces) GetMaxConsumersPerSubscription(namespace utils.NameSpaceName) (int, error) { var result int endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "maxConsumersPerSubscription") err := n.pulsar.Client.Get(endpoint, &result) return result, err } func (n *namespaces) SetOffloadThreshold(namespace utils.NameSpaceName, threshold int64) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "offloadThreshold") return n.pulsar.Client.Put(endpoint, threshold) } func (n *namespaces) GetOffloadThreshold(namespace utils.NameSpaceName) (int64, error) { var result int64 endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "offloadThreshold") err := n.pulsar.Client.Get(endpoint, &result) return result, err } func (n *namespaces) SetMaxConsumersPerTopic(namespace utils.NameSpaceName, max int) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "maxConsumersPerTopic") return n.pulsar.Client.Post(endpoint, max) } func (n *namespaces) GetMaxConsumersPerTopic(namespace utils.NameSpaceName) (int, error) { var result int endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "maxConsumersPerTopic") err := n.pulsar.Client.Get(endpoint, &result) return result, err } func (n *namespaces) SetCompactionThreshold(namespace utils.NameSpaceName, threshold int64) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "compactionThreshold") return n.pulsar.Client.Put(endpoint, threshold) } func (n *namespaces) GetCompactionThreshold(namespace utils.NameSpaceName) (int64, error) { var result int64 endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "compactionThreshold") err := n.pulsar.Client.Get(endpoint, &result) return result, err } func (n *namespaces) SetMaxProducersPerTopic(namespace utils.NameSpaceName, max int) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "maxProducersPerTopic") return n.pulsar.Client.Post(endpoint, max) } func (n *namespaces) GetMaxProducersPerTopic(namespace utils.NameSpaceName) (int, error) { var result int endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "maxProducersPerTopic") err := n.pulsar.Client.Get(endpoint, &result) return result, err } func (n *namespaces) GetNamespaceReplicationClusters(namespace string) ([]string, error) { var data []string nsName, err := utils.GetNamespaceName(namespace) if err != nil { return nil, err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "replication") err = n.pulsar.Client.Get(endpoint, &data) return data, err } func (n *namespaces) SetNamespaceReplicationClusters(namespace string, clusterIds []string) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "replication") return n.pulsar.Client.Post(endpoint, &clusterIds) } func (n *namespaces) SetNamespaceAntiAffinityGroup(namespace string, namespaceAntiAffinityGroup string) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "antiAffinity") return n.pulsar.Client.Post(endpoint, namespaceAntiAffinityGroup) } func (n *namespaces) GetAntiAffinityNamespaces(tenant, cluster, namespaceAntiAffinityGroup string) ([]string, error) { var data []string endpoint := n.pulsar.endpoint(n.basePath, cluster, "antiAffinity", namespaceAntiAffinityGroup) params := map[string]string{ "property": tenant, } _, err := n.pulsar.Client.GetWithQueryParams(endpoint, &data, params, false) return data, err } func (n *namespaces) GetNamespaceAntiAffinityGroup(namespace string) (string, error) { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return "", err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "antiAffinity") data, err := n.pulsar.Client.GetWithQueryParams(endpoint, nil, nil, false) return string(data), err } func (n *namespaces) DeleteNamespaceAntiAffinityGroup(namespace string) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "antiAffinity") return n.pulsar.Client.Delete(endpoint) } func (n *namespaces) SetDeduplicationStatus(namespace string, enableDeduplication bool) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "deduplication") return n.pulsar.Client.Post(endpoint, enableDeduplication) } func (n *namespaces) SetPersistence(namespace string, persistence utils.PersistencePolicies) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "persistence") return n.pulsar.Client.Post(endpoint, &persistence) } func (n *namespaces) SetBookieAffinityGroup(namespace string, bookieAffinityGroup utils.BookieAffinityGroupData) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "persistence", "bookieAffinity") return n.pulsar.Client.Post(endpoint, &bookieAffinityGroup) } func (n *namespaces) DeleteBookieAffinityGroup(namespace string) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "persistence", "bookieAffinity") return n.pulsar.Client.Delete(endpoint) } func (n *namespaces) GetBookieAffinityGroup(namespace string) (*utils.BookieAffinityGroupData, error) { var data utils.BookieAffinityGroupData nsName, err := utils.GetNamespaceName(namespace) if err != nil { return nil, err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "persistence", "bookieAffinity") err = n.pulsar.Client.Get(endpoint, &data) return &data, err } func (n *namespaces) GetPersistence(namespace string) (*utils.PersistencePolicies, error) { var persistence utils.PersistencePolicies nsName, err := utils.GetNamespaceName(namespace) if err != nil { return nil, err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "persistence") err = n.pulsar.Client.Get(endpoint, &persistence) return &persistence, err } func (n *namespaces) Unload(namespace string) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), "unload") return n.pulsar.Client.Put(endpoint, "") } func (n *namespaces) UnloadNamespaceBundle(namespace, bundle string) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), bundle, "unload") return n.pulsar.Client.Put(endpoint, "") } func (n *namespaces) SplitNamespaceBundle(namespace, bundle string, unloadSplitBundles bool) error { nsName, err := utils.GetNamespaceName(namespace) if err != nil { return err } endpoint := n.pulsar.endpoint(n.basePath, nsName.String(), bundle, "split") params := map[string]string{ "unload": strconv.FormatBool(unloadSplitBundles), } return n.pulsar.Client.PutWithQueryParams(endpoint, "", nil, params) } func (n *namespaces) GetNamespacePermissions(namespace utils.NameSpaceName) (map[string][]common.AuthAction, error) { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "permissions") var permissions map[string][]common.AuthAction err := n.pulsar.Client.Get(endpoint, &permissions) return permissions, err } func (n *namespaces) GrantNamespacePermission(namespace utils.NameSpaceName, role string, action []common.AuthAction) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "permissions", role) s := make([]string, 0) for _, v := range action { s = append(s, v.String()) } return n.pulsar.Client.Post(endpoint, s) } func (n *namespaces) RevokeNamespacePermission(namespace utils.NameSpaceName, role string) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "permissions", role) return n.pulsar.Client.Delete(endpoint) } func (n *namespaces) GrantSubPermission(namespace utils.NameSpaceName, sName string, roles []string) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "permissions", "subscription", sName) return n.pulsar.Client.Post(endpoint, roles) } func (n *namespaces) RevokeSubPermission(namespace utils.NameSpaceName, sName, role string) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "permissions", "subscription", sName, role) return n.pulsar.Client.Delete(endpoint) } func (n *namespaces) SetSubscriptionAuthMode(namespace utils.NameSpaceName, mode utils.SubscriptionAuthMode) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "subscriptionAuthMode") return n.pulsar.Client.Post(endpoint, mode.String()) } func (n *namespaces) SetEncryptionRequiredStatus(namespace utils.NameSpaceName, encrypt bool) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "encryptionRequired") return n.pulsar.Client.Post(endpoint, strconv.FormatBool(encrypt)) } func (n *namespaces) UnsubscribeNamespace(namespace utils.NameSpaceName, sName string) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "unsubscribe", url.QueryEscape(sName)) return n.pulsar.Client.Post(endpoint, "") } func (n *namespaces) UnsubscribeNamespaceBundle(namespace utils.NameSpaceName, bundle, sName string) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), bundle, "unsubscribe", url.QueryEscape(sName)) return n.pulsar.Client.Post(endpoint, "") } func (n *namespaces) ClearNamespaceBundleBacklogForSubscription(namespace utils.NameSpaceName, bundle, sName string) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), bundle, "clearBacklog", url.QueryEscape(sName)) return n.pulsar.Client.Post(endpoint, "") } func (n *namespaces) ClearNamespaceBundleBacklog(namespace utils.NameSpaceName, bundle string) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), bundle, "clearBacklog") return n.pulsar.Client.Post(endpoint, "") } func (n *namespaces) ClearNamespaceBacklogForSubscription(namespace utils.NameSpaceName, sName string) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "clearBacklog", url.QueryEscape(sName)) return n.pulsar.Client.Post(endpoint, "") } func (n *namespaces) ClearNamespaceBacklog(namespace utils.NameSpaceName) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "clearBacklog") return n.pulsar.Client.Post(endpoint, "") } func (n *namespaces) SetReplicatorDispatchRate(namespace utils.NameSpaceName, rate utils.DispatchRate) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "replicatorDispatchRate") return n.pulsar.Client.Post(endpoint, rate) } func (n *namespaces) GetReplicatorDispatchRate(namespace utils.NameSpaceName) (utils.DispatchRate, error) { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "replicatorDispatchRate") var rate utils.DispatchRate err := n.pulsar.Client.Get(endpoint, &rate) return rate, err } func (n *namespaces) SetSubscriptionDispatchRate(namespace utils.NameSpaceName, rate utils.DispatchRate) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "subscriptionDispatchRate") return n.pulsar.Client.Post(endpoint, rate) } func (n *namespaces) GetSubscriptionDispatchRate(namespace utils.NameSpaceName) (utils.DispatchRate, error) { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "subscriptionDispatchRate") var rate utils.DispatchRate err := n.pulsar.Client.Get(endpoint, &rate) return rate, err } func (n *namespaces) SetSubscribeRate(namespace utils.NameSpaceName, rate utils.SubscribeRate) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "subscribeRate") return n.pulsar.Client.Post(endpoint, rate) } func (n *namespaces) GetSubscribeRate(namespace utils.NameSpaceName) (utils.SubscribeRate, error) { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "subscribeRate") var rate utils.SubscribeRate err := n.pulsar.Client.Get(endpoint, &rate) return rate, err } func (n *namespaces) SetDispatchRate(namespace utils.NameSpaceName, rate utils.DispatchRate) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "dispatchRate") return n.pulsar.Client.Post(endpoint, rate) } func (n *namespaces) GetDispatchRate(namespace utils.NameSpaceName) (utils.DispatchRate, error) { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "dispatchRate") var rate utils.DispatchRate err := n.pulsar.Client.Get(endpoint, &rate) return rate, err } func (n *namespaces) SetPublishRate(namespace utils.NameSpaceName, pubRate utils.PublishRate) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "publishRate") return n.pulsar.Client.Post(endpoint, pubRate) } func (n *namespaces) GetPublishRate(namespace utils.NameSpaceName) (utils.PublishRate, error) { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "publishRate") var pubRate utils.PublishRate err := n.pulsar.Client.Get(endpoint, &pubRate) return pubRate, err } func (n *namespaces) SetIsAllowAutoUpdateSchema(namespace utils.NameSpaceName, isAllowAutoUpdateSchema bool) error { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "isAllowAutoUpdateSchema") return n.pulsar.Client.Post(endpoint, &isAllowAutoUpdateSchema) } func (n *namespaces) GetIsAllowAutoUpdateSchema(namespace utils.NameSpaceName) (bool, error) { endpoint := n.pulsar.endpoint(n.basePath, namespace.String(), "isAllowAutoUpdateSchema") var result bool err := n.pulsar.Client.Get(endpoint, &result) return result, err }
pkg/pulsar/namespace.go
0.613584
0.425367
namespace.go
starcoder
package fragment import ( "github.com/ms-uzh/calc/models" ) func CalculateFragments(head models.Head, tail models.Tail, polyamines ...models.Polyamine) models.Fragments { fragments := make([]models.Fragment, len(polyamines)) fragments = calculateFromHead(fragments, head, tail, polyamines...) fragments = calculateFromTail(fragments, tail, polyamines...) return fragments } func calculateFromTail(fragments models.Fragments, tail models.Tail, polyamines ...models.Polyamine) models.Fragments { insertIndex := 0 previous := models.Fragment{Z: tail.Mass, Y: tail.Mass, Tz: tail.Mass} for iterateIndex := len(polyamines) - 1; iterateIndex >= 0; iterateIndex-- { polyamine := polyamines[iterateIndex] previousPolyamine := models.Polyamine{} if iterateIndex != len(polyamines)-1 { previousPolyamine = polyamines[iterateIndex+1] } isFirst := iterateIndex == len(polyamines)-1 z := calculateZ(previous.Z, tail, polyamine, previousPolyamine, isFirst) previous.Z = z fragments[insertIndex].Z = z y := calculateY(previous.Y, tail, polyamine, previousPolyamine, isFirst) previous.Y = y fragments[insertIndex].Y = y tz := calculateTz(previous.Tz, polyamine, isFirst) previous.Tz = tz fragments[insertIndex].Tz = tz insertIndex++ } return fragments } func calculateFromHead(fragments models.Fragments, head models.Head, tail models.Tail, polyamines ...models.Polyamine) models.Fragments { previous := models.Fragment{A: head.Mass, B: head.Mass, C: head.Mass, Ta: head.Mass} for i, polyamine := range polyamines { a := calculateA(previous.A, polyamine, i == 0) previous.A = a b := calculateB(previous.B, polyamine, i == 0) previous.B = b c := calculateC(previous.C, polyamine, i == 0) previous.C = c isLast := i == len(polyamines)-1 followingPolyamine := models.Polyamine{} if !isLast { followingPolyamine = polyamines[i+1] } ta := calculateTA(previous.Ta, polyamine, followingPolyamine, tail, i == 0, isLast) previous.Ta = ta fragment := models.Fragment{ A: a, B: b, C: c, Ta: ta, } fragments[i] = fragment } return fragments }
calculation/fragment/fragment.go
0.662796
0.509825
fragment.go
starcoder
package function import ( "fmt" "regexp" "strings" "github.com/src-d/go-mysql-server/sql" "github.com/src-d/go-mysql-server/sql/expression" errors "gopkg.in/src-d/go-errors.v1" ) // RegexpMatches returns the matches of a regular expression. type RegexpMatches struct { Text sql.Expression Pattern sql.Expression Flags sql.Expression cacheable bool re *regexp.Regexp } // NewRegexpMatches creates a new RegexpMatches expression. func NewRegexpMatches(args ...sql.Expression) (sql.Expression, error) { var r RegexpMatches switch len(args) { case 3: r.Flags = args[2] fallthrough case 2: r.Text = args[0] r.Pattern = args[1] default: return nil, sql.ErrInvalidArgumentNumber.New("regexp_matches", "2 or 3", len(args)) } if canBeCached(r.Pattern) && (r.Flags == nil || canBeCached(r.Flags)) { r.cacheable = true } return &r, nil } // Type implements the sql.Expression interface. func (r *RegexpMatches) Type() sql.Type { return sql.Array(sql.Text) } // IsNullable implements the sql.Expression interface. func (r *RegexpMatches) IsNullable() bool { return true } // Children implements the sql.Expression interface. func (r *RegexpMatches) Children() []sql.Expression { var result = []sql.Expression{r.Text, r.Pattern} if r.Flags != nil { result = append(result, r.Flags) } return result } // Resolved implements the sql.Expression interface. func (r *RegexpMatches) Resolved() bool { return r.Text.Resolved() && r.Pattern.Resolved() && (r.Flags == nil || r.Flags.Resolved()) } // WithChildren implements the sql.Expression interface. func (r *RegexpMatches) WithChildren(children ...sql.Expression) (sql.Expression, error) { required := 2 if r.Flags != nil { required = 3 } if len(children) != required { return nil, sql.ErrInvalidChildrenNumber.New(r, len(children), required) } return NewRegexpMatches(children...) } func (r *RegexpMatches) String() string { var args []string for _, e := range r.Children() { args = append(args, e.String()) } return fmt.Sprintf("regexp_matches(%s)", strings.Join(args, ", ")) } // Eval implements the sql.Expression interface. func (r *RegexpMatches) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { span, ctx := ctx.Span("function.RegexpMatches") defer span.Finish() var re *regexp.Regexp var err error if r.cacheable { if r.re == nil { r.re, err = r.compileRegex(ctx, nil) if err != nil { return nil, err } if r.re == nil { return nil, nil } } re = r.re } else { re, err = r.compileRegex(ctx, row) if err != nil { return nil, err } if re == nil { return nil, nil } } text, err := r.Text.Eval(ctx, row) if err != nil { return nil, err } if text == nil { return nil, nil } text, err = sql.Text.Convert(text) if err != nil { return nil, err } matches := re.FindAllStringSubmatch(text.(string), -1) if len(matches) == 0 { return nil, nil } var result []interface{} for _, m := range matches { for _, sm := range m { result = append(result, sm) } } return result, nil } func (r *RegexpMatches) compileRegex(ctx *sql.Context, row sql.Row) (*regexp.Regexp, error) { pattern, err := r.Pattern.Eval(ctx, row) if err != nil { return nil, err } if pattern == nil { return nil, nil } pattern, err = sql.Text.Convert(pattern) if err != nil { return nil, err } var flags string if r.Flags != nil { f, err := r.Flags.Eval(ctx, row) if err != nil { return nil, err } if f == nil { return nil, nil } f, err = sql.Text.Convert(f) if err != nil { return nil, err } flags = f.(string) for _, f := range flags { if !validRegexpFlags[f] { return nil, errInvalidRegexpFlag.New(f) } } flags = fmt.Sprintf("(?%s)", flags) } return regexp.Compile(flags + pattern.(string)) } var errInvalidRegexpFlag = errors.NewKind("invalid regexp flag: %v") var validRegexpFlags = map[rune]bool{ 'i': true, } func canBeCached(e sql.Expression) bool { var hasCols bool expression.Inspect(e, func(e sql.Expression) bool { if _, ok := e.(*expression.GetField); ok { hasCols = true } return true }) return !hasCols }
sql/expression/function/regexp_matches.go
0.626238
0.420005
regexp_matches.go
starcoder
package zng import ( "strconv" "github.com/brimsec/zq/pkg/byteconv" "github.com/brimsec/zq/zcode" ) func NewUint64(v uint64) Value { return Value{TypeUint64, EncodeUint(v)} } func EncodeByte(b byte) zcode.Bytes { return []byte{b} } func EncodeInt(i int64) zcode.Bytes { var b [8]byte n := zcode.EncodeCountedVarint(b[:], i) return b[:n] } func EncodeUint(i uint64) zcode.Bytes { var b [8]byte n := zcode.EncodeCountedUvarint(b[:], i) return b[:n] } func DecodeByte(zv zcode.Bytes) (byte, error) { if len(zv) != 1 { return 0, ErrUnset } return zv[0], nil } func DecodeInt(zv zcode.Bytes) (int64, error) { if zv == nil { return 0, ErrUnset } return zcode.DecodeCountedVarint(zv), nil } func DecodeUint(zv zcode.Bytes) (uint64, error) { if zv == nil { return 0, ErrUnset } return zcode.DecodeCountedUvarint(zv), nil } func stringOfInt(zv zcode.Bytes, t Type) string { i, err := DecodeInt(zv) if err != nil { return badZng(err, t, zv) } return strconv.FormatInt(i, 10) } func stringOfUint(zv zcode.Bytes, t Type) string { i, err := DecodeUint(zv) if err != nil { return badZng(err, t, zv) } return strconv.FormatUint(i, 10) } type TypeOfByte struct{} func (t *TypeOfByte) ID() int { return IdByte } func (t *TypeOfByte) String() string { return "byte" } func (t *TypeOfByte) Parse(in []byte) (zcode.Bytes, error) { b, err := byteconv.ParseUint8(in) if err != nil { return nil, err } return EncodeByte(b), nil } func (t *TypeOfByte) StringOf(zv zcode.Bytes, _ OutFmt, _ bool) string { b, err := DecodeByte(zv) if err != nil { return badZng(err, t, zv) } return strconv.FormatUint(uint64(b), 10) } func (t *TypeOfByte) Marshal(zv zcode.Bytes) (interface{}, error) { return DecodeByte(zv) } type TypeOfInt16 struct{} func (t *TypeOfInt16) ID() int { return IdInt16 } func (t *TypeOfInt16) String() string { return "int16" } func (t *TypeOfInt16) Parse(in []byte) (zcode.Bytes, error) { i, err := byteconv.ParseInt16(in) if err != nil { return nil, err } return EncodeInt(int64(i)), nil } func (t *TypeOfInt16) StringOf(zv zcode.Bytes, _ OutFmt, _ bool) string { return stringOfInt(zv, t) } func (t *TypeOfInt16) Marshal(zv zcode.Bytes) (interface{}, error) { return DecodeInt(zv) } type TypeOfUint16 struct{} func (t *TypeOfUint16) ID() int { return IdUint16 } func (t *TypeOfUint16) String() string { return "uint16" } func (t *TypeOfUint16) Parse(in []byte) (zcode.Bytes, error) { i, err := byteconv.ParseUint16(in) if err != nil { return nil, err } return EncodeUint(uint64(i)), nil } func (t *TypeOfUint16) StringOf(zv zcode.Bytes, _ OutFmt, _ bool) string { return stringOfUint(zv, t) } func (t *TypeOfUint16) Marshal(zv zcode.Bytes) (interface{}, error) { return DecodeUint(zv) } type TypeOfInt32 struct{} func (t *TypeOfInt32) ID() int { return IdInt32 } func (t *TypeOfInt32) String() string { return "int32" } func (t *TypeOfInt32) Parse(in []byte) (zcode.Bytes, error) { i, err := byteconv.ParseInt32(in) if err != nil { return nil, err } return EncodeInt(int64(i)), nil } func (t *TypeOfInt32) StringOf(zv zcode.Bytes, _ OutFmt, _ bool) string { return stringOfInt(zv, t) } func (t *TypeOfInt32) Marshal(zv zcode.Bytes) (interface{}, error) { return DecodeInt(zv) } type TypeOfUint32 struct{} func (t *TypeOfUint32) ID() int { return IdUint32 } func (t *TypeOfUint32) String() string { return "uint32" } func (t *TypeOfUint32) Parse(in []byte) (zcode.Bytes, error) { i, err := byteconv.ParseUint32(in) if err != nil { return nil, err } return EncodeUint(uint64(i)), nil } func (t *TypeOfUint32) StringOf(zv zcode.Bytes, _ OutFmt, _ bool) string { return stringOfUint(zv, t) } func (t *TypeOfUint32) Marshal(zv zcode.Bytes) (interface{}, error) { return DecodeUint(zv) } type TypeOfInt64 struct{} func (t *TypeOfInt64) ID() int { return IdInt64 } func (t *TypeOfInt64) String() string { return "int64" } func (t *TypeOfInt64) Parse(in []byte) (zcode.Bytes, error) { i, err := byteconv.ParseInt64(in) if err != nil { return nil, err } return EncodeInt(int64(i)), nil } func (t *TypeOfInt64) StringOf(zv zcode.Bytes, _ OutFmt, _ bool) string { return stringOfInt(zv, t) } func (t *TypeOfInt64) Marshal(zv zcode.Bytes) (interface{}, error) { return DecodeInt(zv) } type TypeOfUint64 struct{} func (t *TypeOfUint64) ID() int { return IdUint64 } func (t *TypeOfUint64) String() string { return "uint64" } func (t *TypeOfUint64) Parse(in []byte) (zcode.Bytes, error) { i, err := byteconv.ParseUint64(in) if err != nil { return nil, err } return EncodeUint(uint64(i)), nil } func (t *TypeOfUint64) StringOf(zv zcode.Bytes, _ OutFmt, _ bool) string { return stringOfUint(zv, t) } func (t *TypeOfUint64) Marshal(zv zcode.Bytes) (interface{}, error) { return DecodeUint(zv) }
zng/int.go
0.707607
0.417331
int.go
starcoder
package sort import ( "fmt" "sort" "strings" glsssn "github.com/hfmrow/gen_lib/strings/strNum" glte "github.com/hfmrow/gen_lib/types" gltsct "github.com/hfmrow/gen_lib/types/convert" ) // SliceSortDate: Sort 2d string slice with date inside func SliceSortDate(slice [][]string, fmtDate string, dateCol, secDateCol int, ascendant bool) [][]string { fieldsCount := len(slice[0]) // Get nb of columns var firstLine int var previous, after string var positiveidx, negativeidx int // compute unix date using given column numbers for idx := firstLine; idx < len(slice); idx++ { dateStr := glte.FindDate(slice[idx][dateCol], fmtDate) if dateStr != nil { // search for 1st column slice[idx] = append(slice[idx], fmt.Sprintf("%d", glte.FormatDate(fmtDate, dateStr[0]).Unix())) } else if secDateCol != -1 { // Check for second column if it was given dateStr = glte.FindDate(slice[idx][secDateCol], fmtDate) if dateStr != nil { // If date was not found in 1st column, search for 2nd column slice[idx] = append(slice[idx], fmt.Sprintf("%d", glte.FormatDate(fmtDate, slice[idx][secDateCol]).Unix())) } else { // in case where none of the columns given contain date field, put null string if there is no way to find a date slice[idx] = append(slice[idx], ``) } } else { // put null string if there is no way to find a date slice[idx] = append(slice[idx], ``) } } // Ensure we always have a value in sorting field (get previous or next closer) for idx := firstLine; idx < len(slice); idx++ { if slice[idx][fieldsCount] == `` { for idxFind := firstLine + 1; idxFind < len(slice); idxFind++ { positiveidx = idx + idxFind negativeidx = idx - idxFind if positiveidx >= len(slice) { // Check index to avoiding 'out of range' positiveidx = len(slice) - 1 } if negativeidx <= 0 { negativeidx = 0 } after = slice[positiveidx][fieldsCount] // Get previous or next value previous = slice[negativeidx][fieldsCount] if previous != `` { // Set value, prioritise the previous one. slice[idx][fieldsCount] = previous break } if after != `` { slice[idx][fieldsCount] = after break } } } } tmpLines := make([][]string, 0) if ascendant != true { // Sort by unix date preserving order descendant sort.SliceStable(slice, func(i, j int) bool { return slice[i][len(slice[i])-1] > slice[j][len(slice[i])-1] }) for idx := firstLine; idx < len(slice); idx++ { // Store row count elements - 1 tmpLines = append(tmpLines, slice[idx][:len(slice[idx])-1]) } } else { // Sort by unix date preserving order ascendant sort.SliceStable(slice, func(i, j int) bool { return slice[i][len(slice[i])-1] < slice[j][len(slice[i])-1] }) for idx := firstLine; idx < len(slice); idx++ { // Store row count elements - 1 tmpLines = append(tmpLines, slice[idx][:len(slice[idx])-1]) } } return tmpLines } // SliceSortString: Sort 2d string slice func SliceSortString(slice [][]string, col int, ascendant, caseSensitive, numbered bool) { if numbered { var tmpWordList []string for _, wrd := range slice { tmpWordList = append(tmpWordList, wrd[col]) } numberedWords := new(glsssn.WordWithDigit) numberedWords.Init(tmpWordList) if ascendant != true { // Sort string preserving order descendant sort.SliceStable(slice, func(i, j int) bool { return numberedWords.FillWordToMatchMaxLength(slice[i][col]) > numberedWords.FillWordToMatchMaxLength(slice[j][col]) }) } else { // Sort string preserving order ascendant sort.SliceStable(slice, func(i, j int) bool { return numberedWords.FillWordToMatchMaxLength(slice[i][col]) < numberedWords.FillWordToMatchMaxLength(slice[j][col]) }) } return } toLowerCase := func(inString string) string { return inString } if !caseSensitive { toLowerCase = func(inString string) string { return strings.ToLower(inString) } } if ascendant != true { // Sort string preserving order descendant sort.SliceStable(slice, func(i, j int) bool { return toLowerCase(slice[i][col]) > toLowerCase(slice[j][col]) }) } else { // Sort string preserving order ascendant sort.SliceStable(slice, func(i, j int) bool { return toLowerCase(slice[i][col]) < toLowerCase(slice[j][col]) }) } } // SliceSortFloat: Sort 2d string with float value func SliceSortFloat(slice [][]string, col int, ascendant bool, decimalChar string) { if ascendant != true { // Sort string (float) preserving order descendant sort.SliceStable(slice, func(i, j int) bool { return gltsct.StringDecimalSwitchFloat(decimalChar, slice[i][col]) > gcv.StringDecimalSwitchFloat(decimalChar, slice[j][col]) }) } else { // Sort string (float) preserving order ascendant sort.SliceStable(slice, func(i, j int) bool { return gltsct.StringDecimalSwitchFloat(decimalChar, slice[i][col]) < gcv.StringDecimalSwitchFloat(decimalChar, slice[j][col]) }) } }
slices/sort/sliceSort.go
0.519765
0.409103
sliceSort.go
starcoder
package plaid import ( "encoding/json" ) // DeductionsTotal An object representing the total deductions for the pay period type DeductionsTotal struct { // Raw amount of the deduction CurrentAmount NullableFloat32 `json:"current_amount,omitempty"` // The ISO-4217 currency code of the line item. Always `null` if `unofficial_currency_code` is non-null. IsoCurrencyCode NullableString `json:"iso_currency_code,omitempty"` // The unofficial currency code associated with the line item. Always `null` if `iso_currency_code` is non-`null`. Unofficial currency codes are used for currencies that do not have official ISO currency codes, such as cryptocurrencies and the currencies of certain countries. See the [currency code schema](https://plaid.com/docs/api/accounts#currency-code-schema) for a full listing of supported `iso_currency_code`s. UnofficialCurrencyCode NullableString `json:"unofficial_currency_code,omitempty"` // The year-to-date total amount of the deductions YtdAmount NullableFloat32 `json:"ytd_amount,omitempty"` AdditionalProperties map[string]interface{} } type _DeductionsTotal DeductionsTotal // NewDeductionsTotal instantiates a new DeductionsTotal 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 NewDeductionsTotal() *DeductionsTotal { this := DeductionsTotal{} return &this } // NewDeductionsTotalWithDefaults instantiates a new DeductionsTotal 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 NewDeductionsTotalWithDefaults() *DeductionsTotal { this := DeductionsTotal{} return &this } // GetCurrentAmount returns the CurrentAmount field value if set, zero value otherwise (both if not set or set to explicit null). func (o *DeductionsTotal) GetCurrentAmount() float32 { if o == nil || o.CurrentAmount.Get() == nil { var ret float32 return ret } return *o.CurrentAmount.Get() } // GetCurrentAmountOk returns a tuple with the CurrentAmount 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 *DeductionsTotal) GetCurrentAmountOk() (*float32, bool) { if o == nil { return nil, false } return o.CurrentAmount.Get(), o.CurrentAmount.IsSet() } // HasCurrentAmount returns a boolean if a field has been set. func (o *DeductionsTotal) HasCurrentAmount() bool { if o != nil && o.CurrentAmount.IsSet() { return true } return false } // SetCurrentAmount gets a reference to the given NullableFloat32 and assigns it to the CurrentAmount field. func (o *DeductionsTotal) SetCurrentAmount(v float32) { o.CurrentAmount.Set(&v) } // SetCurrentAmountNil sets the value for CurrentAmount to be an explicit nil func (o *DeductionsTotal) SetCurrentAmountNil() { o.CurrentAmount.Set(nil) } // UnsetCurrentAmount ensures that no value is present for CurrentAmount, not even an explicit nil func (o *DeductionsTotal) UnsetCurrentAmount() { o.CurrentAmount.Unset() } // GetIsoCurrencyCode returns the IsoCurrencyCode field value if set, zero value otherwise (both if not set or set to explicit null). func (o *DeductionsTotal) GetIsoCurrencyCode() string { if o == nil || o.IsoCurrencyCode.Get() == nil { var ret string return ret } return *o.IsoCurrencyCode.Get() } // GetIsoCurrencyCodeOk returns a tuple with the IsoCurrencyCode field value 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 *DeductionsTotal) GetIsoCurrencyCodeOk() (*string, bool) { if o == nil { return nil, false } return o.IsoCurrencyCode.Get(), o.IsoCurrencyCode.IsSet() } // HasIsoCurrencyCode returns a boolean if a field has been set. func (o *DeductionsTotal) HasIsoCurrencyCode() bool { if o != nil && o.IsoCurrencyCode.IsSet() { return true } return false } // SetIsoCurrencyCode gets a reference to the given NullableString and assigns it to the IsoCurrencyCode field. func (o *DeductionsTotal) SetIsoCurrencyCode(v string) { o.IsoCurrencyCode.Set(&v) } // SetIsoCurrencyCodeNil sets the value for IsoCurrencyCode to be an explicit nil func (o *DeductionsTotal) SetIsoCurrencyCodeNil() { o.IsoCurrencyCode.Set(nil) } // UnsetIsoCurrencyCode ensures that no value is present for IsoCurrencyCode, not even an explicit nil func (o *DeductionsTotal) UnsetIsoCurrencyCode() { o.IsoCurrencyCode.Unset() } // GetUnofficialCurrencyCode returns the UnofficialCurrencyCode field value if set, zero value otherwise (both if not set or set to explicit null). func (o *DeductionsTotal) GetUnofficialCurrencyCode() string { if o == nil || o.UnofficialCurrencyCode.Get() == nil { var ret string return ret } return *o.UnofficialCurrencyCode.Get() } // GetUnofficialCurrencyCodeOk returns a tuple with the UnofficialCurrencyCode field value 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 *DeductionsTotal) GetUnofficialCurrencyCodeOk() (*string, bool) { if o == nil { return nil, false } return o.UnofficialCurrencyCode.Get(), o.UnofficialCurrencyCode.IsSet() } // HasUnofficialCurrencyCode returns a boolean if a field has been set. func (o *DeductionsTotal) HasUnofficialCurrencyCode() bool { if o != nil && o.UnofficialCurrencyCode.IsSet() { return true } return false } // SetUnofficialCurrencyCode gets a reference to the given NullableString and assigns it to the UnofficialCurrencyCode field. func (o *DeductionsTotal) SetUnofficialCurrencyCode(v string) { o.UnofficialCurrencyCode.Set(&v) } // SetUnofficialCurrencyCodeNil sets the value for UnofficialCurrencyCode to be an explicit nil func (o *DeductionsTotal) SetUnofficialCurrencyCodeNil() { o.UnofficialCurrencyCode.Set(nil) } // UnsetUnofficialCurrencyCode ensures that no value is present for UnofficialCurrencyCode, not even an explicit nil func (o *DeductionsTotal) UnsetUnofficialCurrencyCode() { o.UnofficialCurrencyCode.Unset() } // GetYtdAmount returns the YtdAmount field value if set, zero value otherwise (both if not set or set to explicit null). func (o *DeductionsTotal) GetYtdAmount() float32 { if o == nil || o.YtdAmount.Get() == nil { var ret float32 return ret } return *o.YtdAmount.Get() } // GetYtdAmountOk returns a tuple with the YtdAmount 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 *DeductionsTotal) GetYtdAmountOk() (*float32, bool) { if o == nil { return nil, false } return o.YtdAmount.Get(), o.YtdAmount.IsSet() } // HasYtdAmount returns a boolean if a field has been set. func (o *DeductionsTotal) HasYtdAmount() bool { if o != nil && o.YtdAmount.IsSet() { return true } return false } // SetYtdAmount gets a reference to the given NullableFloat32 and assigns it to the YtdAmount field. func (o *DeductionsTotal) SetYtdAmount(v float32) { o.YtdAmount.Set(&v) } // SetYtdAmountNil sets the value for YtdAmount to be an explicit nil func (o *DeductionsTotal) SetYtdAmountNil() { o.YtdAmount.Set(nil) } // UnsetYtdAmount ensures that no value is present for YtdAmount, not even an explicit nil func (o *DeductionsTotal) UnsetYtdAmount() { o.YtdAmount.Unset() } func (o DeductionsTotal) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.CurrentAmount.IsSet() { toSerialize["current_amount"] = o.CurrentAmount.Get() } if o.IsoCurrencyCode.IsSet() { toSerialize["iso_currency_code"] = o.IsoCurrencyCode.Get() } if o.UnofficialCurrencyCode.IsSet() { toSerialize["unofficial_currency_code"] = o.UnofficialCurrencyCode.Get() } if o.YtdAmount.IsSet() { toSerialize["ytd_amount"] = o.YtdAmount.Get() } for key, value := range o.AdditionalProperties { toSerialize[key] = value } return json.Marshal(toSerialize) } func (o *DeductionsTotal) UnmarshalJSON(bytes []byte) (err error) { varDeductionsTotal := _DeductionsTotal{} if err = json.Unmarshal(bytes, &varDeductionsTotal); err == nil { *o = DeductionsTotal(varDeductionsTotal) } additionalProperties := make(map[string]interface{}) if err = json.Unmarshal(bytes, &additionalProperties); err == nil { delete(additionalProperties, "current_amount") delete(additionalProperties, "iso_currency_code") delete(additionalProperties, "unofficial_currency_code") delete(additionalProperties, "ytd_amount") o.AdditionalProperties = additionalProperties } return err } type NullableDeductionsTotal struct { value *DeductionsTotal isSet bool } func (v NullableDeductionsTotal) Get() *DeductionsTotal { return v.value } func (v *NullableDeductionsTotal) Set(val *DeductionsTotal) { v.value = val v.isSet = true } func (v NullableDeductionsTotal) IsSet() bool { return v.isSet } func (v *NullableDeductionsTotal) Unset() { v.value = nil v.isSet = false } func NewNullableDeductionsTotal(val *DeductionsTotal) *NullableDeductionsTotal { return &NullableDeductionsTotal{value: val, isSet: true} } func (v NullableDeductionsTotal) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableDeductionsTotal) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
plaid/model_deductions_total.go
0.801276
0.558207
model_deductions_total.go
starcoder
package vars //DummyDataFaker is used in tests type DummyDataFaker struct { Dummy string } func (ddf DummyDataFaker) Brand() string { return ddf.Dummy } func (ddf DummyDataFaker) Character() string { return ddf.Dummy } func (ddf DummyDataFaker) Characters() string { return ddf.Dummy } func (ddf DummyDataFaker) City() string { return ddf.Dummy } func (ddf DummyDataFaker) Color() string { return ddf.Dummy } func (ddf DummyDataFaker) Company() string { return ddf.Dummy } func (ddf DummyDataFaker) Continent() string { return ddf.Dummy } func (ddf DummyDataFaker) Country() string { return ddf.Dummy } func (ddf DummyDataFaker) CreditCardVisa() string { return ddf.Dummy } func (ddf DummyDataFaker) CreditCardMasterCard() string { return ddf.Dummy } func (ddf DummyDataFaker) CreditCardAmericanExpress() string { return ddf.Dummy } func (ddf DummyDataFaker) Currency() string { return ddf.Dummy } func (ddf DummyDataFaker) CurrencyCode() string { return ddf.Dummy } func (ddf DummyDataFaker) Day() string { return ddf.Dummy } func (ddf DummyDataFaker) Digits() string { return ddf.Dummy } func (ddf DummyDataFaker) EmailAddress() string { return ddf.Dummy } func (ddf DummyDataFaker) FirstName() string { return ddf.Dummy } func (ddf DummyDataFaker) FullName() string { return ddf.Dummy } func (ddf DummyDataFaker) LastName() string { return ddf.Dummy } func (ddf DummyDataFaker) Gender() string { return ddf.Dummy } func (ddf DummyDataFaker) IPv4() string { return ddf.Dummy } func (ddf DummyDataFaker) Language() string { return ddf.Dummy } func (ddf DummyDataFaker) Model() string { return ddf.Dummy } func (ddf DummyDataFaker) Month() string { return ddf.Dummy } func (ddf DummyDataFaker) Year() string { return ddf.Dummy } func (ddf DummyDataFaker) MonthShort() string { return ddf.Dummy } func (ddf DummyDataFaker) Paragraph() string { return ddf.Dummy } func (ddf DummyDataFaker) Paragraphs() string { return ddf.Dummy } func (ddf DummyDataFaker) Phone() string { return ddf.Dummy } func (ddf DummyDataFaker) Product() string { return ddf.Dummy } func (ddf DummyDataFaker) Sentence() string { return ddf.Dummy } func (ddf DummyDataFaker) Sentences() string { return ddf.Dummy } func (ddf DummyDataFaker) SimplePassword() string { return ddf.Dummy } func (ddf DummyDataFaker) State() string { return ddf.Dummy } func (ddf DummyDataFaker) StateAbbrev() string { return ddf.Dummy } func (ddf DummyDataFaker) Street() string { return ddf.Dummy } func (ddf DummyDataFaker) StreetAddress() string { return ddf.Dummy } func (ddf DummyDataFaker) UserName() string { return ddf.Dummy } func (ddf DummyDataFaker) WeekDay() string { return ddf.Dummy } func (ddf DummyDataFaker) Word() string { return ddf.Dummy } func (ddf DummyDataFaker) Words() string { return ddf.Dummy } func (ddf DummyDataFaker) Zip() string { return ddf.Dummy }
vars/dummy_data_faker.go
0.617743
0.731215
dummy_data_faker.go
starcoder
package trees import ( "math" "math/rand" "github.com/vodinhphuc/golearn/base" ) type IsolationForest struct { nTrees int maxDepth int subSpace int trees []regressorNode } // Select A random feature for splitting from the data. func selectFeature(data [][]float64) int64 { return int64(rand.Intn(len(data[0]))) } // Find the minimum and maximum values of a feature. Used so that we can choose a random threshold. func minMax(feature int64, data [][]float64) (float64, float64) { var min, max float64 min = math.Inf(1) max = math.Inf(-1) for _, instance := range data { if instance[feature] > max { max = instance[feature] } if instance[feature] < min { min = instance[feature] } } return min, max } // Select a random threshold between the minimum and maximum of the feature. func selectValue(min, max float64) float64 { val := min + (rand.Float64() * (max - min)) if val == min { val += 0.000001 } else if val == max { val -= 0.000001 } return val } // Split the data based on the threshold. func splitData(val float64, feature int64, data [][]float64) ([][]float64, [][]float64) { var leftData, rightData [][]float64 for _, instance := range data { if instance[feature] <= val { leftData = append(leftData, instance) } else { rightData = append(rightData, instance) } } return leftData, rightData } // Make sure that the data can still be split (all datapoints are not duplicate) func checkData(data [][]float64) bool { for _, instance := range data { for i, val := range instance { if val != data[0][i] { return true } } } return false } // Recusrively build a tree by randomly choosing a feature to split until nodes are pure or max depth is reached. func buildTree(data [][]float64, upperNode regressorNode, depth int, maxDepth int) regressorNode { depth++ upperNode.isNodeNeeded = true if (depth > maxDepth) || (len(data) <= 1) || !checkData(data) { upperNode.isNodeNeeded = false return upperNode } var featureToSplit int64 var splitVal float64 var min, max float64 min, max = 0.0, 0.0 for min == max { featureToSplit = selectFeature(data) min, max = minMax(featureToSplit, data) splitVal = selectValue(min, max) } leftData, rightData := splitData(splitVal, featureToSplit, data) upperNode.Feature = featureToSplit upperNode.Threshold = splitVal upperNode.LeftPred = float64(len(leftData)) upperNode.RightPred = float64(len(rightData)) var leftNode, rightNode regressorNode leftNode = buildTree(leftData, leftNode, depth, maxDepth) rightNode = buildTree(rightData, rightNode, depth, maxDepth) if leftNode.isNodeNeeded { upperNode.Left = &leftNode } if rightNode.isNodeNeeded { upperNode.Right = &rightNode } return upperNode } // Get a random subset of the data. Helps making each tree in forest different. func getRandomData(data [][]float64, subSpace int) [][]float64 { var randomData [][]float64 for i := 0; i < subSpace; i++ { randomData = append(randomData, data[rand.Intn(len(data))]) } return randomData } // Function to create a new isolation forest. nTrees is number of trees in Forest. Maxdepth is maximum depth of each tree. Subspace is number of data points to use per tree. func NewIsolationForest(nTrees int, maxDepth int, subSpace int) IsolationForest { var iForest IsolationForest iForest.nTrees = nTrees iForest.maxDepth = maxDepth iForest.subSpace = subSpace return iForest } // Fit the data based on hyperparameters and data. func (iForest *IsolationForest) Fit(X base.FixedDataGrid) { data := preprocessData(X) nTrees := iForest.nTrees subSpace := iForest.subSpace maxDepth := iForest.maxDepth var forest []regressorNode for i := 0; i < nTrees; i++ { subData := getRandomData(data, subSpace) var tree regressorNode tree = buildTree(subData, tree, 0, maxDepth) forest = append(forest, tree) } iForest.trees = forest } // Calculate the path length to reach a leaf node for a datapoint. Outliers have smaller path lengths than standard data points. func pathLength(tree regressorNode, instance []float64, path float64) float64 { path++ if instance[tree.Feature] <= tree.Threshold { if tree.Left == nil { if tree.LeftPred <= 1 { return path } else { return path + cFactor(int(tree.LeftPred)) } } path = pathLength(*tree.Left, instance, path) } else { if tree.Right == nil { if tree.RightPred <= 1 { return path } else { return path + cFactor(int(tree.RightPred)) } } path = pathLength(*tree.Right, instance, path) } return path } // Find the path length of a a datapoints from all trees in forest. func evaluateInstance(instance []float64, forest []regressorNode) []float64 { var paths []float64 for _, tree := range forest { paths = append(paths, pathLength(tree, instance, 0)) } return paths } // Helper function to calculate anomaly score. func cFactor(n int) float64 { return 2.0*(math.Log(float64(n-1))+0.5772156649) - (float64(2.0*(n-1)) / float64(n)) } // Anamoly Score - How anomalous is a data point. closer to 1 - higher chance of it being outlier. closer to 0 - low chance of it being outlier. func anomalyScore(instance []float64, forest []regressorNode, n int) float64 { paths := evaluateInstance(instance, forest) E := 0.0 for _, path := range paths { E += path } E /= float64(len(paths)) c := cFactor(n) return math.Pow(2, (-1 * E / c)) } // Return anamoly score for all datapoints. func (iForest *IsolationForest) Predict(X base.FixedDataGrid) []float64 { data := preprocessData(X) var preds []float64 for _, instance := range data { score := anomalyScore(instance, iForest.trees, iForest.subSpace) preds = append(preds, score) } return preds } // Extract data in the form of floats. Used in Fit and predict. Note that class labels are treated as normal data because Isolation Forest is unsupervised. func preprocessData(X base.FixedDataGrid) [][]float64 { data := convertInstancesToProblemVec(X) class, err := regressorConvertInstancesToLabelVec(X) if err != nil { panic(err) } for i, point := range class { data[i] = append(data[i], point) } return data }
trees/isolation.go
0.763131
0.656025
isolation.go
starcoder
package gointerfaces import ( "encoding/binary" "github.com/holiman/uint256" "github.com/ledgerwatch/erigon-lib/gointerfaces/types" ) func ConvertH256ToHash(h256 *types.H256) [32]byte { var hash [32]byte binary.BigEndian.PutUint64(hash[0:], h256.Hi.Hi) binary.BigEndian.PutUint64(hash[8:], h256.Hi.Lo) binary.BigEndian.PutUint64(hash[16:], h256.Lo.Hi) binary.BigEndian.PutUint64(hash[24:], h256.Lo.Lo) return hash } func ConvertHashesToH256(hashes [][32]byte) []*types.H256 { res := make([]*types.H256, len(hashes)) for i := range hashes { res[i] = ConvertHashToH256(hashes[i]) } return res } func ConvertHashToH256(hash [32]byte) *types.H256 { return &types.H256{ Lo: &types.H128{Lo: binary.BigEndian.Uint64(hash[24:]), Hi: binary.BigEndian.Uint64(hash[16:])}, Hi: &types.H128{Lo: binary.BigEndian.Uint64(hash[8:]), Hi: binary.BigEndian.Uint64(hash[0:])}, } } func ConvertH160toAddress(h160 *types.H160) [20]byte { var addr [20]byte binary.BigEndian.PutUint64(addr[0:], h160.Hi.Hi) binary.BigEndian.PutUint64(addr[8:], h160.Hi.Lo) binary.BigEndian.PutUint32(addr[16:], h160.Lo) return addr } func ConvertAddressToH160(addr [20]byte) *types.H160 { return &types.H160{ Lo: binary.BigEndian.Uint32(addr[16:]), Hi: &types.H128{Lo: binary.BigEndian.Uint64(addr[8:]), Hi: binary.BigEndian.Uint64(addr[0:])}, } } func ConvertH256ToUint256Int(h256 *types.H256) *uint256.Int { // Note: uint256.Int is an array of 4 uint64 in little-endian order, i.e. most significant word is [3] var i uint256.Int i[3] = h256.Hi.Hi i[2] = h256.Hi.Lo i[1] = h256.Lo.Hi i[0] = h256.Lo.Lo return &i } func ConvertUint256IntToH256(i *uint256.Int) *types.H256 { // Note: uint256.Int is an array of 4 uint64 in little-endian order, i.e. most significant word is [3] return &types.H256{ Lo: &types.H128{Lo: i[0], Hi: i[1]}, Hi: &types.H128{Lo: i[2], Hi: i[3]}, } } func ConvertH512ToBytes(h512 *types.H512) []byte { var b [64]byte binary.BigEndian.PutUint64(b[0:], h512.Hi.Hi.Hi) binary.BigEndian.PutUint64(b[8:], h512.Hi.Hi.Lo) binary.BigEndian.PutUint64(b[16:], h512.Hi.Lo.Hi) binary.BigEndian.PutUint64(b[24:], h512.Hi.Lo.Lo) binary.BigEndian.PutUint64(b[32:], h512.Lo.Hi.Hi) binary.BigEndian.PutUint64(b[40:], h512.Lo.Hi.Lo) binary.BigEndian.PutUint64(b[48:], h512.Lo.Lo.Hi) binary.BigEndian.PutUint64(b[56:], h512.Lo.Lo.Lo) return b[:] } func ConvertBytesToH512(b []byte) *types.H512 { if len(b) < 64 { var b1 [64]byte copy(b1[:], b) b = b1[:] } return &types.H512{ Lo: &types.H256{ Lo: &types.H128{Lo: binary.BigEndian.Uint64(b[56:]), Hi: binary.BigEndian.Uint64(b[48:])}, Hi: &types.H128{Lo: binary.BigEndian.Uint64(b[40:]), Hi: binary.BigEndian.Uint64(b[32:])}, }, Hi: &types.H256{ Lo: &types.H128{Lo: binary.BigEndian.Uint64(b[24:]), Hi: binary.BigEndian.Uint64(b[16:])}, Hi: &types.H128{Lo: binary.BigEndian.Uint64(b[8:]), Hi: binary.BigEndian.Uint64(b[0:])}, }, } }
gointerfaces/type_utils.go
0.617397
0.40439
type_utils.go
starcoder
package input import ( "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/lib/input/reader" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/message/batch" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/types" ) //------------------------------------------------------------------------------ func init() { Constructors[TypeGCPPubSub] = TypeSpec{ constructor: fromSimpleConstructor(NewGCPPubSub), Summary: ` Consumes messages from a GCP Cloud Pub/Sub subscription.`, Description: ` For information on how to set up credentials check out [this guide](https://cloud.google.com/docs/authentication/production). ### Metadata This input adds the following metadata fields to each message: ` + "``` text" + ` - gcp_pubsub_publish_time_unix - All message attributes ` + "```" + ` You can access these metadata fields using [function interpolation](/docs/configuration/interpolation#metadata).`, Categories: []Category{ CategoryServices, CategoryGCP, }, FieldSpecs: docs.FieldSpecs{ docs.FieldCommon("project", "The project ID of the target subscription."), docs.FieldCommon("subscription", "The target subscription ID."), docs.FieldCommon("max_outstanding_messages", "The maximum number of outstanding pending messages to be consumed at a given time."), docs.FieldCommon("max_outstanding_bytes", "The maximum number of outstanding pending messages to be consumed measured in bytes."), func() docs.FieldSpec { b := batch.FieldSpec() b.IsDeprecated = true return b }(), docs.FieldDeprecated("max_batch_count"), }, } } //------------------------------------------------------------------------------ // NewGCPPubSub creates a new GCP Cloud Pub/Sub input type. func NewGCPPubSub(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) { // TODO: V4 Remove this. if conf.GCPPubSub.MaxBatchCount > 1 { log.Warnf("Field '%v.max_batch_count' is deprecated, use '%v.batching.count' instead.\n", conf.Type, conf.Type) conf.GCPPubSub.Batching.Count = conf.GCPPubSub.MaxBatchCount } var c reader.Async var err error if c, err = reader.NewGCPPubSub(conf.GCPPubSub, log, stats); err != nil { return nil, err } if c, err = reader.NewAsyncBatcher(conf.GCPPubSub.Batching, c, mgr, log, stats); err != nil { return nil, err } c = reader.NewAsyncBundleUnacks(c) return NewAsyncReader(TypeGCPPubSub, true, c, log, stats) } //------------------------------------------------------------------------------
lib/input/gcp_pubsub.go
0.676727
0.706266
gcp_pubsub.go
starcoder
package structure // references: https://github.com/mitchellh/mapstructure import ( "fmt" "reflect" "strconv" "strings" ) // Option is the configuration that is used to create a new decoder type Option struct { TagName string WeaklyTypedInput bool } // Decoder is the core of structure type Decoder struct { option *Option } // NewDecoder return a Decoder by Option func NewDecoder(option Option) *Decoder { if option.TagName == "" { option.TagName = "structure" } return &Decoder{option: &option} } // Decode transform a map[string]interface{} to a struct func (d *Decoder) Decode(src map[string]interface{}, dst interface{}) error { if reflect.TypeOf(dst).Kind() != reflect.Ptr { return fmt.Errorf("Decode must recive a ptr struct") } t := reflect.TypeOf(dst).Elem() v := reflect.ValueOf(dst).Elem() for idx := 0; idx < v.NumField(); idx++ { field := t.Field(idx) tag := field.Tag.Get(d.option.TagName) str := strings.SplitN(tag, ",", 2) key := str[0] omitempty := false if len(str) > 1 { omitempty = str[1] == "omitempty" } value, ok := src[key] if !ok { if omitempty { continue } return fmt.Errorf("key %s missing", key) } err := d.decode(key, value, v.Field(idx)) if err != nil { return err } } return nil } func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error { switch val.Kind() { case reflect.Int: return d.decodeInt(name, data, val) case reflect.String: return d.decodeString(name, data, val) case reflect.Bool: return d.decodeBool(name, data, val) case reflect.Slice: return d.decodeSlice(name, data, val) case reflect.Map: return d.decodeMap(name, data, val) default: return fmt.Errorf("type %s not support", val.Kind().String()) } } func (d *Decoder) decodeInt(name string, data interface{}, val reflect.Value) (err error) { dataVal := reflect.ValueOf(data) kind := dataVal.Kind() switch { case kind == reflect.Int: val.SetInt(dataVal.Int()) case kind == reflect.String && d.option.WeaklyTypedInput: var i int64 i, err = strconv.ParseInt(dataVal.String(), 0, val.Type().Bits()) if err == nil { val.SetInt(i) } else { err = fmt.Errorf("cannot parse '%s' as int: %s", name, err) } default: err = fmt.Errorf( "'%s' expected type '%s', got unconvertible type '%s'", name, val.Type(), dataVal.Type(), ) } return err } func (d *Decoder) decodeString(name string, data interface{}, val reflect.Value) (err error) { dataVal := reflect.ValueOf(data) kind := dataVal.Kind() switch { case kind == reflect.String: val.SetString(dataVal.String()) case kind == reflect.Int && d.option.WeaklyTypedInput: val.SetString(strconv.FormatInt(dataVal.Int(), 10)) default: err = fmt.Errorf( "'%s' expected type'%s', got unconvertible type '%s'", name, val.Type(), dataVal.Type(), ) } return err } func (d *Decoder) decodeBool(name string, data interface{}, val reflect.Value) (err error) { dataVal := reflect.ValueOf(data) kind := dataVal.Kind() switch { case kind == reflect.Bool: val.SetBool(dataVal.Bool()) case kind == reflect.Int && d.option.WeaklyTypedInput: val.SetBool(dataVal.Int() != 0) default: err = fmt.Errorf( "'%s' expected type'%s', got unconvertible type '%s'", name, val.Type(), dataVal.Type(), ) } return err } func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) error { dataVal := reflect.Indirect(reflect.ValueOf(data)) valType := val.Type() valElemType := valType.Elem() if dataVal.Kind() != reflect.Slice { return fmt.Errorf("'%s' is not a slice", name) } valSlice := val for i := 0; i < dataVal.Len(); i++ { currentData := dataVal.Index(i).Interface() for valSlice.Len() <= i { valSlice = reflect.Append(valSlice, reflect.Zero(valElemType)) } currentField := valSlice.Index(i) fieldName := fmt.Sprintf("%s[%d]", name, i) if err := d.decode(fieldName, currentData, currentField); err != nil { return err } } val.Set(valSlice) return nil } func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) error { valType := val.Type() valKeyType := valType.Key() valElemType := valType.Elem() valMap := val if valMap.IsNil() { mapType := reflect.MapOf(valKeyType, valElemType) valMap = reflect.MakeMap(mapType) } dataVal := reflect.Indirect(reflect.ValueOf(data)) if dataVal.Kind() != reflect.Map { return fmt.Errorf("'%s' expected a map, got '%s'", name, dataVal.Kind()) } return d.decodeMapFromMap(name, dataVal, val, valMap) } func (d *Decoder) decodeMapFromMap(name string, dataVal reflect.Value, val reflect.Value, valMap reflect.Value) error { valType := val.Type() valKeyType := valType.Key() valElemType := valType.Elem() errors := make([]string, 0) if dataVal.Len() == 0 { if dataVal.IsNil() { if !val.IsNil() { val.Set(dataVal) } } else { val.Set(valMap) } return nil } for _, k := range dataVal.MapKeys() { fieldName := fmt.Sprintf("%s[%s]", name, k) currentKey := reflect.Indirect(reflect.New(valKeyType)) if err := d.decode(fieldName, k.Interface(), currentKey); err != nil { errors = append(errors, err.Error()) continue } v := dataVal.MapIndex(k).Interface() currentVal := reflect.Indirect(reflect.New(valElemType)) if err := d.decode(fieldName, v, currentVal); err != nil { errors = append(errors, err.Error()) continue } valMap.SetMapIndex(currentKey, currentVal) } val.Set(valMap) if len(errors) > 0 { return fmt.Errorf(strings.Join(errors, ",")) } return nil }
common/structure/structure.go
0.642096
0.461563
structure.go
starcoder
// The chromatic adaptation algorithms on this web site may all be implemented as a linear transformation of a // source color (XS, YS, ZS) into a destination color (XD, YD, ZD) by a linear transformation [M] // which is dependent on the source reference white (XWS, YWS, ZWS) and the // destination reference white (XWD, YWD, ZWD). The idea behind all of these algorithms is to follow three steps: // Transform from XYZ into a cone response domain, (ρ, γ, β). // Scale the vector components by factors dependent upon both the source and destination reference whites. // Transform from (ρ, γ, β) back to XYZ using the inverse transform of step 1. // Ref.: [26] package white // Bradford func bradford() (ma, maInv [3][3]float64) { ma = [3][3]float64{{0.8951000, 0.2664000, -0.1614000}, {-0.7502000, 1.7135000, 0.0367000}, {0.0389000, -0.0685000, 1.0296000}} maInv = [3][3]float64{{0.9869929, -0.1470543, 0.1599627}, {0.4323053, 0.5183603, 0.0492912}, {-0.0085287, 0.0400428, 0.9684867}} return } // <NAME> func vonKries() (ma, maInv [3][3]float64) { ma = [3][3]float64{{0.4002400, 0.7076000, -0.0808100}, {-0.2263000, 1.1653200, 0.0457000}, {0.0000000, 0.0000000, 0.9182200}} maInv = [3][3]float64{{1.8599364, -1.1293816, 0.2198974}, {0.3611914, 0.6388125, -0.0000064}, {0.0000000, 0.0000000, 1.0890636}} return } // XYZ Scaling func xyzScaling() (ma, maInv [3][3]float64) { ma = [3][3]float64{{1.0000000, 0.0000000, 0.0000000}, {0.0000000, 1.0000000, 0.0000000}, {0.0000000, 0.0000000, 1.0000000}} maInv = [3][3]float64{{1.0000000, 0.0000000, 0.0000000}, {0.0000000, 1.0000000, 0.0000000}, {0.0000000, 0.0000000, 1.0000000}} return } func ChromAd(xs, ys, zs, xws, yws, zws, xwd, ywd, zwd float64, method uint8) (xd, yd, zd float64) { var ma, maInv, m [3][3]float64 switch method { case 0: { // Bradford ma, maInv = bradford() } case 1: { ma, maInv = vonKries() } case 2: { ma, maInv = xyzScaling() } } // ρ, γ, β ρs := ma[0][0]*xws + ma[0][1]*yws + ma[0][2]*zws γs := ma[1][0]*xws + ma[1][1]*yws + ma[1][2]*zws βs := ma[2][0]*xws + ma[2][1]*yws + ma[2][2]*zws ρd := maInv[0][0]*xwd + maInv[0][1]*ywd + maInv[0][2]*zwd γd := maInv[1][0]*xwd + maInv[1][1]*ywd + maInv[1][2]*zwd βd := maInv[2][0]*xwd + maInv[2][1]*ywd + maInv[2][2]*zwd m[0][0] = maInv[0][0] * (ρd / ρs) m[0][1] = maInv[0][1] * (γd / γs) m[0][2] = maInv[0][2] * (βd / βs) m[1][0] = maInv[1][0] * (ρd / ρs) m[1][1] = maInv[1][1] * (γd / γs) m[1][2] = maInv[1][2] * (βd / βs) m[2][0] = maInv[2][0] * (ρd / ρs) m[2][1] = maInv[2][1] * (γd / γs) m[2][2] = maInv[2][2] * (βd / βs) m[0][0] = m[0][0]*ma[0][0] + m[0][1]*ma[1][0] + m[0][2]*ma[2][0] m[0][1] = m[0][0]*ma[0][1] + m[0][1]*ma[1][1] + m[0][2]*ma[2][1] m[0][2] = m[0][0]*ma[0][2] + m[0][1]*ma[1][2] + m[0][2]*ma[2][2] m[1][0] = m[1][0]*ma[0][0] + m[1][1]*ma[1][0] + m[1][2]*ma[2][0] m[1][1] = m[1][0]*ma[0][1] + m[1][1]*ma[1][1] + m[1][2]*ma[2][1] m[1][2] = m[1][0]*ma[0][2] + m[1][1]*ma[1][2] + m[1][2]*ma[2][2] m[2][0] = m[2][0]*ma[0][0] + m[2][1]*ma[1][0] + m[2][2]*ma[2][0] m[2][1] = m[2][0]*ma[0][1] + m[2][1]*ma[1][1] + m[2][2]*ma[2][1] m[2][2] = m[2][0]*ma[0][2] + m[2][1]*ma[1][2] + m[2][2]*ma[2][2] xd = m[0][0]*xs + m[0][1]*ys + m[0][2]*zs yd = m[1][0]*xs + m[1][1]*ys + m[1][2]*zs zd = m[2][0]*xs + m[2][1]*ys + m[2][2]*zs return }
f64/white/chrom_ad.go
0.593609
0.614914
chrom_ad.go
starcoder
package gmath import ( "math" "math/cmplx" "strconv" ) // Decbin Returns a string containing a binary representation of the given num argument. func Decbin(num int64) string { return strconv.FormatInt(num, 2) } // Dechex Returns a string containing a hexadecimal representation of the given unsigned num argument. func Dechex(num int64) string { return strconv.FormatInt(num, 16) } // Decoct Returns a string containing an octal representation of the given num argument. func Decoct(num int64) string { return strconv.FormatInt(num, 8) } // Max If the first and only parameter is an array, max() returns the highest value in that array. // If at least two parameters are provided, max() returns the biggest of these values. func Max(nums ...float64) float64 { if len(nums) < 2 { panic("nums: the nums length is less than 2") } max := nums[0] for i := 1; i < len(nums); i++ { max = math.Max(max, nums[i]) } return max } // Min If the first and only parameter is an array, min() returns the lowest value in that array. // If at least two parameters are provided, min() returns the smallest of these values. func Min(nums ...float64) float64 { if len(nums) < 2 { panic("nums: the nums length is less than 2") } min := nums[0] for i := 1; i < len(nums); i++ { min = math.Min(min, nums[i]) } return min } // Round Returns the rounded value of num to specified precision (number of digits after the decimal point). precision can also be negative or zero (default). func Round(num float64, precision int) float64 { p := math.Pow10(precision) return math.Trunc((num+0.5/p)*p) / p } // Floor Returns the next lowest integer value (as float) by rounding down num if necessary. func Floor(num float64) float64 { return math.Floor(num) } // Ceil Returns the next highest integer value by rounding up num if necessary. func Ceil(num float64) float64 { return math.Ceil(num) } // Pi Returns an approximation of pi. Also, you can use the M_PI constant which yields identical results to pi(). func Pi() float64 { return math.Pi } // Abs Returns the absolute value of num. func Abs(num float64) float64 { return math.Abs(num) } // Acos Returns the arc cosine of num in radians. acos() is the inverse function of cos(), which means that a==cos(acos(a)) for every value of a that is within acos()' range. func Acos(num complex128) complex128 { return cmplx.Acos(num) } // Acosh Returns the inverse hyperbolic cosine of num, i.e. the value whose hyperbolic cosine is num. func Acosh(num complex128) complex128 { return cmplx.Acosh(num) } // Asin Returns the arc sine of num in radians. asin() is the inverse function of sin(), which means that a==sin(asin(a)) for every value of a that is within asin()'s range. func Asin(num complex128) complex128 { return cmplx.Asin(num) } // Asinh Returns the inverse hyperbolic sine of num, i.e. the value whose hyperbolic sine is num. func Asinh(num complex128) complex128 { return cmplx.Asinh(num) } // Atan2 TThis function calculates the arc tangent of the two variables x and y. // It is similar to calculating the arc tangent of y / x, except that the signs of both arguments are used to determine the quadrant of the result. func Atan2(y, x float64) float64 { return math.Atan2(y, x) } // Atan Returns the arc tangent of num in radians. atan() is the inverse function of tan(), which means that a==tan(atan(a)) for every value of a that is within atan()'s range. func Atan(num complex128) complex128 { return cmplx.Atan(num) } // Atanh Returns the inverse hyperbolic tangent of num, i.e. the value whose hyperbolic tangent is num. func Atanh(num complex128) complex128 { return cmplx.Atanh(num) } // Cos Returns the cosine of the num parameter. The num parameter is in radians. func Cos(num float64) float64 { return math.Cos(num) } // Cosh Returns the hyperbolic cosine of num, defined as (exp(arg) + exp(-arg))/2. func Cosh(num float64) float64 { return math.Cosh(num) } // Exp Returns e raised to the power of num. func Exp(num float64) float64 { return math.Exp(num) } // Expm1 Returns the equivalent to 'exp(num) - 1' computed in a way that is accurate even if the value of num is near zero, a case where 'exp (num) - 1' would be inaccurate due to subtraction of two numbers that are nearly equal. func Expm1(num float64) float64 { return math.Exp(num) - 1 } // IsFinite Checks whether num is a legal finite on this platform. func IsFinite(num float64, sign int) bool { return !math.IsInf(num, sign) } // IsInfinite Returns true if num is infinite (positive or negative), like the result of log(0) or any value too big to fit into a float on this platform. func IsInfinite(num float64, sign int) bool { return math.IsInf(num, sign) } // IsNan Checks whether num is 'not a number', like the result of acos(1.01). func IsNan(num float64) bool { return math.IsNaN(num) } // Log Returns the natural logarithm of num. func Log(num float64) float64 { return math.Log(num) } // Log10 Returns the base-10 logarithm of num. func Log10(num float64) float64 { return math.Log10(num) } // Log1p Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero. func Log1p(num float64) float64 { return math.Log1p(num) } // Pow Returns num raised to the power of exponent. func Pow(num, exponent float64) float64 { return math.Pow(num, exponent) } // Sin Returns the sine of the num parameter. The num parameter is in radians. func Sin(num float64) float64 { return math.Sin(num) } // Sinh Returns the hyperbolic sine of num, defined as (exp(num) - exp(-num))/2. func Sinh(num float64) float64 { return math.Sinh(num) } // Sqrt Returns the square root of num. func Sqrt(num float64) float64 { return math.Sqrt(num) } // Tan Returns the tangent of the num parameter. The num parameter is in radians. func Tan(num float64) float64 { return math.Tan(num) } // Tanh Returns the hyperbolic tangent of num, defined as sinh(num)/cosh(num). func Tanh(num float64) float64 { return math.Tanh(num) } // BaseConvert Returns a string containing num represented in base to_base. // The base in which num is given is specified in from_base. // Both from_base and to_base have to be between 2 and 36, inclusive. // Digits in numbers with a base higher than 10 will be represented with the letters a-z, with a meaning 10, b meaning 11 and z meaning 35. // The case of the letters doesn't matter, i.e. num is interpreted case-insensitively. func BaseConvert(x string, fromBase, toBase int) (string, error) { i, err := strconv.ParseInt(x, fromBase, 0) if err != nil { return "", err } return strconv.FormatInt(i, toBase), nil }
util/gmath/gmath.go
0.940953
0.76176
gmath.go
starcoder
// Package drivertest provides a conformance test for implementations of // runtimevar. package drivertest import ( "context" "reflect" "testing" "github.com/Lioric/go-cloud/runtimevar" "github.com/google/go-cmp/cmp" ) // Harness descibes the functionality test harnesses must provide to run conformance tests. type Harness interface { // MakeVar creates a *runtimevar.Variable to watch the given variable. MakeVar(ctx context.Context, name string, decoder *runtimevar.Decoder) (*runtimevar.Variable, error) // CreateVariable creates the variable with the given contents in the provider. CreateVariable(ctx context.Context, name string, val []byte) error // UpdateVariable updates an existing variable to have the given contents in the provider. UpdateVariable(ctx context.Context, name string, val []byte) error // DeleteVariable deletes an existing variable in the provider. DeleteVariable(ctx context.Context, name string) error // Close is called when the test is complete. Close() } // HarnessMaker describes functions that construct a harness for running tests. // It is called exactly once per test; Harness.Close() will be called when the test is complete. type HarnessMaker func(t *testing.T) (Harness, error) // RunConformanceTests runs conformance tests for provider implementations // of runtimevar. func RunConformanceTests(t *testing.T, newHarness HarnessMaker) { t.Run("TestNonExistentVariable", func(t *testing.T) { testNonExistentVariable(t, newHarness) }) t.Run("TestWithCancelledContext", func(t *testing.T) { testWithCancelledContext(t, newHarness) }) t.Run("TestString", func(t *testing.T) { testString(t, newHarness) }) t.Run("TestJSON", func(t *testing.T) { testJSON(t, newHarness) }) t.Run("TestInvalidJSON", func(t *testing.T) { testInvalidJSON(t, newHarness) }) t.Run("TestUpdate", func(t *testing.T) { testUpdate(t, newHarness) }) t.Run("TestDelete", func(t *testing.T) { testDelete(t, newHarness) }) } func testNonExistentVariable(t *testing.T, newHarness HarnessMaker) { h, err := newHarness(t) if err != nil { t.Fatal(err) } defer h.Close() ctx := context.Background() v, err := h.MakeVar(ctx, "does-not-exist", runtimevar.StringDecoder) if err != nil { t.Fatal(err) } defer func() { if err := v.Close(); err != nil { t.Error(err) } }() got, err := v.Watch(ctx) if err == nil { t.Errorf("got %v expected not-found error", got.Value) } } func testWithCancelledContext(t *testing.T, newHarness HarnessMaker) { const ( name = "test-config-variable" content = "hello world" ) h, err := newHarness(t) if err != nil { t.Fatal(err) } defer h.Close() ctx := context.Background() if err := h.CreateVariable(ctx, name, []byte(content)); err != nil { t.Fatal(err) } defer func() { if err := h.DeleteVariable(ctx, name); err != nil { t.Fatal(err) } }() // Test initial watch fails if ctx is cancelled. cancelledCtx, cancel := context.WithCancel(ctx) cancel() v, err := h.MakeVar(ctx, name, runtimevar.StringDecoder) if err != nil { t.Fatal(err) } defer func() { if err := v.Close(); err != nil { t.Error(err) } }() got, err := v.Watch(cancelledCtx) if err == nil { t.Errorf("got %v expected cancelled context error", got.Value) } // But works with a valid one. got, err = v.Watch(ctx) if err != nil { t.Fatal(err) } if got.Value.(string) != content { t.Errorf("got %q want %q", got.Value, content) } // And fails again with cancelled. got, err = v.Watch(cancelledCtx) if err == nil { t.Errorf("got %v expected cancelled context error", got.Value) } } func testString(t *testing.T, newHarness HarnessMaker) { const ( name = "test-config-variable" content = "hello world" ) h, err := newHarness(t) if err != nil { t.Fatal(err) } defer h.Close() ctx := context.Background() if err := h.CreateVariable(ctx, name, []byte(content)); err != nil { t.Fatal(err) } defer func() { if err := h.DeleteVariable(ctx, name); err != nil { t.Fatal(err) } }() v, err := h.MakeVar(ctx, name, runtimevar.StringDecoder) if err != nil { t.Fatal(err) } defer func() { if err := v.Close(); err != nil { t.Error(err) } }() got, err := v.Watch(ctx) if err != nil { t.Fatal(err) } // The variable is decoded to a string and matches the expected content. if gotS, ok := got.Value.(string); !ok { t.Fatalf("got value of type %v expected string", reflect.TypeOf(got.Value)) } else if gotS != content { t.Errorf("got %q want %q", got.Value, content) } } // Message is used as a target for JSON decoding. type Message struct { Name, Text string } func testJSON(t *testing.T, newHarness HarnessMaker) { const ( name = "test-config-variable" jsonContent = `[ {"Name": "Ed", "Text": "Knock knock."}, {"Name": "Sam", "Text": "Who's there?"} ]` ) want := []*Message{{Name: "Ed", Text: "Knock knock."}, {Name: "Sam", Text: "Who's there?"}} h, err := newHarness(t) if err != nil { t.Fatal(err) } defer h.Close() ctx := context.Background() if err := h.CreateVariable(ctx, name, []byte(jsonContent)); err != nil { t.Fatal(err) } defer func() { if err := h.DeleteVariable(ctx, name); err != nil { t.Fatal(err) } }() var jsonData []*Message v, err := h.MakeVar(ctx, name, runtimevar.NewDecoder(jsonData, runtimevar.JSONDecode)) if err != nil { t.Fatal(err) } defer func() { if err := v.Close(); err != nil { t.Error(err) } }() got, err := v.Watch(ctx) if err != nil { t.Fatal(err) } // The variable is decoded to a []*Message and matches the expected content. if gotSlice, ok := got.Value.([]*Message); !ok { t.Fatalf("got value of type %v expected []*Message", reflect.TypeOf(got.Value)) } else if !cmp.Equal(gotSlice, want) { t.Errorf("got %v want %v", gotSlice, want) } } func testInvalidJSON(t *testing.T, newHarness HarnessMaker) { const ( name = "test-config-variable" content = "not-json" ) h, err := newHarness(t) if err != nil { t.Fatal(err) } defer h.Close() ctx := context.Background() if err := h.CreateVariable(ctx, name, []byte(content)); err != nil { t.Fatal(err) } defer func() { if err := h.DeleteVariable(ctx, name); err != nil { t.Fatal(err) } }() var jsonData []*Message v, err := h.MakeVar(ctx, name, runtimevar.NewDecoder(jsonData, runtimevar.JSONDecode)) if err != nil { t.Fatal(err) } defer func() { if err := v.Close(); err != nil { t.Error(err) } }() got, err := v.Watch(ctx) if err == nil { t.Errorf("got %v wanted invalid-json error", got.Value) } } func testUpdate(t *testing.T, newHarness HarnessMaker) { const ( name = "test-config-variable" content1 = "hello world" content2 = "goodbye world" ) h, err := newHarness(t) if err != nil { t.Fatal(err) } defer h.Close() ctx := context.Background() // Create the variable and verify Watch sees the value. if err := h.CreateVariable(ctx, name, []byte(content1)); err != nil { t.Fatal(err) } defer func() { _ = h.DeleteVariable(ctx, name) }() v, err := h.MakeVar(ctx, name, runtimevar.StringDecoder) if err != nil { t.Fatal(err) } defer func() { if err := v.Close(); err != nil { t.Error(err) } }() got, err := v.Watch(ctx) if err != nil { t.Fatal(err) } if got.Value.(string) != content1 { t.Errorf("got %q want %q", got.Value, content1) } // Update the variable and verify Watch sees the updated value. if err := h.UpdateVariable(ctx, name, []byte(content2)); err != nil { t.Fatal(err) } got, err = v.Watch(ctx) if err != nil { t.Fatal(err) } if got.Value.(string) != content2 { t.Errorf("got %q want %q", got.Value, content2) } } func testDelete(t *testing.T, newHarness HarnessMaker) { const ( name = "test-config-variable" content1 = "hello world" content2 = "goodbye world" ) h, err := newHarness(t) if err != nil { t.Fatal(err) } defer h.Close() ctx := context.Background() // Create the variable and verify Watch sees the value. if err := h.CreateVariable(ctx, name, []byte(content1)); err != nil { t.Fatal(err) } defer func() { _ = h.DeleteVariable(ctx, name) }() v, err := h.MakeVar(ctx, name, runtimevar.StringDecoder) if err != nil { t.Fatal(err) } defer func() { if err := v.Close(); err != nil { t.Error(err) } }() got, err := v.Watch(ctx) if err != nil { t.Fatal(err) } if got.Value.(string) != content1 { t.Errorf("got %q want %q", got.Value, content1) } prev := got // Delete the variable. if err := h.DeleteVariable(ctx, name); err != nil { t.Fatal(err) } // Watch should return an error now. if got, err = v.Watch(ctx); err == nil { t.Fatalf("got %v, want error because variable is deleted", got.Value) } // Reset the variable with new content and verify via Watch. if err := h.CreateVariable(ctx, name, []byte(content2)); err != nil { t.Fatal(err) } got, err = v.Watch(ctx) if err != nil { t.Fatal(err) } if got.Value.(string) != content2 { t.Errorf("got %q want %q", got.Value, content2) } if got.UpdateTime.Before(prev.UpdateTime) { t.Errorf("got UpdateTime %v < previous %v, want >=", got.UpdateTime, prev.UpdateTime) } }
runtimevar/drivertest/drivertest.go
0.663669
0.417093
drivertest.go
starcoder
package stringutils2 import ( "crypto/md5" "encoding/hex" "fmt" "math/rand" "strings" "time" ) func GetMD5Hash(text string) string { hasher := md5.New() hasher.Write([]byte(text)) return hex.EncodeToString(hasher.Sum(nil)) } func EscapeString(str string, pairs [][]string) string { if len(pairs) == 0 { pairs = [][]string{ {"\\", `\\`}, {"\n", `\n`}, {"\r", `\r`}, {"\t", `\t`}, {`"`, `\"`}, {"'", `\'`}, {"$", `\$`}, } } for _, pair := range pairs { k, v := pair[0], pair[1] str = strings.Replace(str, k, v, -1) } return str } func EscapeEchoString(str string) (string, error) { pairs := [][]string{ {"\\", `\\`}, {"\n", `\n`}, {"\r", `\r`}, {"\t", `\t`}, {`"`, `\"`}, } innerPairs := [][]string{ {"\\", `\\`}, {"\n", `\n`}, {"\r", `\r`}, {"\t", `\t`}, {`"`, `\"`}, {"$", `\$`}, } segs, err := SplitByQuotation(str) if err != nil { return "", err } ret := "" for idx := 0; idx < len(segs); idx++ { s := EscapeString(segs[idx], innerPairs) if idx%2 == 1 { s = EscapeString(segs[idx], pairs) s = `\"` + EscapeString(s, innerPairs) + `\"` } ret += s } return ret, nil } func findQuotationPos(line string, offset int) int { if offset > len(line) { return -1 } subStr := line[offset:] pos := strings.Index(subStr, `"`) if pos < 0 { return pos } pos += offset if pos > 0 && line[pos-1] == '\\' { return findQuotationPos(line, pos+1) } return pos } func SplitByQuotation(line string) ([]string, error) { segs := []string{} offset := 0 for offset < len(line) { pos := findQuotationPos(line, offset) if pos < 0 { segs = append(segs, line[offset:]) offset = len(line) } else { if pos == offset { offset += 1 } else { segs = append(segs, line[offset:pos]) offset = pos + 1 } pos = findQuotationPos(line, offset) if pos < 0 { return nil, fmt.Errorf("Unpaired quotations: %s", line[offset:]) } else { segs = append(segs, line[offset:pos]) offset = pos + 1 } } } return segs, nil } func GetCharTypeCount(str string) int { digitIdx := 0 lowerIdx := 1 upperIdx := 2 otherIdx := 3 complexity := make([]int, 4) for _, b := range []byte(str) { if b >= '0' && b <= '9' { complexity[digitIdx] += 1 } else if b >= 'a' && b <= 'z' { complexity[lowerIdx] += 1 } else if b >= 'A' && b <= 'Z' { complexity[upperIdx] += 1 } else { complexity[otherIdx] += 1 } } ret := 0 for i := range complexity { if complexity[i] > 0 { ret += 1 } } return ret } // Qcloud: 1-128个英文字母、数字和+=,.@_- // Aws: 请使用字母数字和‘+=,.@-_’字符。 最长 64 个字符 // Common: 1-64个字符, 数字字母或 +=,.@-_ func GenerateRoleName(roleName string) string { ret := "" for _, s := range roleName { if (s >= '0' && s <= '9') || (s >= 'a' && s <= 'z') || (s >= 'A' && s <= 'Z') || strings.Contains("+=,.@-_", string(s)) { ret += string(s) } } if len(ret) == 0 { return func(length int) string { bytes := []byte("23456789abcdefghijkmnpqrstuvwxyz") result := []byte{} r := rand.New(rand.NewSource(time.Now().UnixNano())) for i := 0; i < length; i++ { result = append(result, bytes[r.Intn(len(bytes))]) } return "role-" + string(result) }(12) } if len(ret) > 64 { return ret[:64] } return ret }
pkg/util/stringutils2/stringutils.go
0.575111
0.416085
stringutils.go
starcoder
package trietree import ( "context" ) // DTree is dynamic tree. type DTree struct { Root DNode lastEdgeID int } // DNode is a node of dynamic tree. type DNode struct { Label rune Low *DNode High *DNode Child *DNode EdgeID int Level int Failure *DNode } func (dn *DNode) dig(c rune) *DNode { p := dn.Child if p == nil { dn.Child = &DNode{Label: c} return dn.Child } for { if c == p.Label { return p } if c < p.Label { if p.Low == nil { p.Low = &DNode{Label: c} return p.Low } p = p.Low } else { if p.High == nil { p.High = &DNode{Label: c} return p.High } p = p.High } } } // Get obtains an existing child node for rune. func (dn *DNode) Get(r rune) *DNode { p := dn.Child for p != nil { if r == p.Label { return p } if r < p.Label { p = p.Low } else { p = p.High } } return nil } // Put puts an edige for key and emits ID for it. ID will be greater than zero. func (dt *DTree) Put(k string) int { n := &dt.Root level := 0 for _, r := range k { n = n.dig(r) level++ } if n.EdgeID <= 0 { dt.lastEdgeID++ n.EdgeID = dt.lastEdgeID } n.Level = level return n.EdgeID } // Scan scans a string to find matched words. func (dt *DTree) Scan(s string, r ScanReporter) error { return dt.ScanContext(context.Background(), s, r) } // ScanContext scans a string to find matched words. // ScanReporter r will receive reports for each characters when scan. func (dt *DTree) ScanContext(ctx context.Context, s string, r ScanReporter) error { sr := newScanReport(r, len(s)) curr := &dt.Root for i, c := range s { next := dt.nextNode(curr, c) // emit a scan event. sr.reset(i, c) for n := next; n != nil; n = n.Failure { if n.EdgeID > 0 { sr.add(n.EdgeID, n.Level) } } sr.emit() // prepare for next. if err := ctx.Err(); err != nil { return err } curr = next } return nil } func (dt *DTree) nextNode(curr *DNode, c rune) *DNode { root := &dt.Root for { next := curr.Get(c) if next != nil { return next } if curr == root { return root } curr = curr.Failure if curr == nil { curr = root } } } type procDNode func(*DNode) func (dn *DNode) eachSiblings(fn procDNode) { if dn == nil { return } dn.Low.eachSiblings(fn) fn(dn) dn.High.eachSiblings(fn) } // Get retrieve a node for key, otherwise returns nil. func (dt *DTree) Get(k string) *DNode { n := &dt.Root for _, r := range k { n = n.Get(r) if n == nil { return nil } } return n } // FillFailure fill Failure field with Aho-Corasick algorithm. func (dt *DTree) FillFailure() { dt.Root.Failure = &dt.Root dt.fillFailure(&dt.Root) dt.Root.Failure = nil } func (dt *DTree) fillFailure(parent *DNode) { if parent.Child == nil { return } //fmt.Printf("fillFailure: parent(%p)=%+[1]v\n", parent) pf := parent.Failure parent.Child.eachSiblings(func(curr *DNode) { f := dt.nextNode(pf, curr.Label) if f == curr { f = &dt.Root } curr.Failure = f //fmt.Printf(" curr(%p)=%+[1]v\n", curr) dt.fillFailure(curr) }) } // CountChild counts child nodes. func (dn *DNode) CountChild() int { c := 0 dn.Child.eachSiblings(func(*DNode) { c++ }) return c } // CountAll counts all descended nodes. func (dn *DNode) CountAll() int { c := 1 dn.Child.eachSiblings(func(n *DNode) { c += n.CountAll() }) return c }
dynamic.go
0.559049
0.439507
dynamic.go
starcoder
package main import ( "math" "math/cmplx" "github.com/fogleman/ln/ln" ) func main() { eye := ln.Vector{-2, -2, 5} center := ln.Vector{0.1, 0, 0} up := ln.Vector{0, 1, 0} scene := ln.Scene{} scene.Add(CalabiYau(5, math.Pi/4, 16, -1, 1)) dpi := 96.0 width := 11.0 * dpi height := 14.0 * dpi fovy := 45.0 paths := scene.Render(eye, center, up, width, height, fovy, 0.1, 10, 0.01) paths.WriteToPNG("calabi_yau.png", width, height) paths.WriteToSVG("calabi_yau.svg", width, height) } func CalabiYau(n int, alpha float64, count int, rmin float64, rmax float64) *ln.Mesh { cos := math.Cos(alpha) sin := math.Sin(alpha) dr := (rmax - rmin) / float64(count-1) di := (0.5 * math.Pi) / float64(count-1) vertices := []ln.Vector{} for k0 := 0; k0 < n; k0++ { for k1 := 0; k1 < n; k1++ { // Real and imaginary indices. for ir := 0; ir < count; ir++ { // Real and imaginary values. r := rmin + float64(ir)*dr for ii := 0; ii < count; ii++ { i := float64(ii) * di z0 := Z0k(r, i, float64(n), float64(k0)) z1 := Z1k(r, i, float64(n), float64(k1)) vertices = append(vertices, ln.Vector{X: real(z0), Y: real(z1), Z: cos*imag(z0) + sin*imag(z1)}) } } } } vertexCount := count patchVertexCount := int(math.Pow(float64(vertexCount), 2)) subdivisions := vertexCount - 1 triangles := []*ln.Triangle{} for i := 0; i < n*n; i++ { offset := i * patchVertexCount for y := 0; y < subdivisions; y++ { for x := 0; x < subdivisions; x++ { v0 := y*vertexCount + x v1 := y*vertexCount + (x + 1) v2 := (y+1)*vertexCount + x v3 := (y+1)*vertexCount + (x + 1) v0 += offset v1 += offset v2 += offset v3 += offset /** * 0 1 * o---o * | \ | * o---o * 2 3 */ triangles = append(triangles, ln.NewTriangle(vertices[v0], vertices[v2], vertices[v3])) triangles = append(triangles, ln.NewTriangle(vertices[v0], vertices[v3], vertices[v1])) } } } return ln.NewMesh(triangles) } func PhaseFactor(k float64, n float64) complex128 { x := 2 * math.Pi * k / n return complex(math.Cos(x), math.Sin(x)) } func U0(x complex128) complex128 { a := cmplx.Exp(x) b := cmplx.Exp(-x) return 0.5 * (a + b) } func U1(x complex128) complex128 { a := cmplx.Exp(x) b := cmplx.Exp(-x) return 0.5 * (a - b) } func Z0k(r float64, i float64, n float64, k float64) complex128 { phase := PhaseFactor(k, n) cos := U0(complex(r, i)) powcos := cmplx.Pow(cos, complex(2/n, 0)) return phase * powcos } func Z1k(r float64, i float64, n float64, k float64) complex128 { phase := PhaseFactor(k, n) sin := U1(complex(r, i)) powsin := cmplx.Pow(sin, complex(2/n, 0)) return phase * powsin }
examples/calabi_yau.go
0.639286
0.444022
calabi_yau.go
starcoder
package parser import ( "strconv" "github.com/Zac-Garby/radon/ast" "github.com/Zac-Garby/radon/token" ) // parseExpression parses an expression starting at the current token. It leaves // cur on the last token of the expression. func (p *Parser) parseExpression(precedence int) ast.Expression { nud, ok := p.nuds[p.cur.Type] if !ok { p.unexpected(p.cur.Type) return nil } left := nud() if p.peekIs(argTokens...) { left = p.parseFunctionCall(left) } for !p.peekIs(token.Semi) && precedence < p.peekPrecedence() { led, ok := p.leds[p.peek.Type] if !ok { return left } p.next() left = led(left) } return left } func (p *Parser) parseIdentifier() ast.Expression { return &ast.Identifier{ Value: p.cur.Literal, } } func (p *Parser) parseNumber() ast.Expression { val, _ := strconv.ParseFloat(p.cur.Literal, 64) return &ast.Number{ Value: val, } } func (p *Parser) parseBoolean() ast.Expression { return &ast.Boolean{ Value: p.cur.Type == token.True, } } func (p *Parser) parseNil() ast.Expression { return &ast.Nil{} } func (p *Parser) parseString() ast.Expression { return &ast.String{ Value: p.cur.Literal, } } func (p *Parser) parseGroupedExpression() ast.Expression { if p.peekIs(token.RightParen) { p.next() return &ast.Infix{ Operator: ",", } } p.next() expr := p.parseExpression(lowest) if !p.expect(token.RightParen) { return nil } return expr } func (p *Parser) parseList() ast.Expression { return &ast.List{ Value: p.parseExpressionList(token.RightSquare, token.Comma), } } func (p *Parser) parseMap() ast.Expression { return &ast.Map{ Value: p.parseExpressionPairs(token.RightBrace, token.Comma), } } func (p *Parser) parseBlock() ast.Expression { node := &ast.Block{ Value: make([]ast.Statement, 0, 8), } p.next() for !p.curIs(token.End) && !p.curIs(token.EOF) { stmt := p.parseStatement() if stmt != nil { node.Value = append(node.Value, stmt) } p.next() } return node } func (p *Parser) parsePrefix() ast.Expression { node := &ast.Prefix{ Operator: p.cur.Literal, } p.next() node.Right = p.parseExpression(prefix) return node } func (p *Parser) parseIf() ast.Expression { p.next() node := &ast.If{ Condition: p.parseExpression(lowest), } if p.peekIs(token.Do) { p.next() node.Consequence = p.parseBlock() } else { if !p.expect(token.Then) { return nil } p.next() node.Consequence = p.parseExpression(lowest) } if p.peekIs(token.Else) { p.next() p.next() node.Alternative = p.parseExpression(lowest) } else { node.Alternative = &ast.Nil{} } return node } func (p *Parser) parseMatch() ast.Expression { p.next() node := &ast.Match{ Input: p.parseExpression(lowest), } if !p.expect(token.Where) { return nil } for p.peekIs(token.BitOr) { pair := ast.MatchBranch{} p.next() p.next() pair.Condition = p.parseExpression(lowest) if !p.expect(token.RightArrow) { return nil } p.next() pair.Body = p.parseExpression(join) node.Branches = append(node.Branches, pair) if p.peekIs(token.Comma) { p.next() } else { break } } hasWildcard := false for _, branch := range node.Branches { if id, ok := branch.Condition.(*ast.Identifier); ok && id.Value == "_" { hasWildcard = true break } } if !hasWildcard { node.Branches = append(node.Branches, ast.MatchBranch{ Condition: &ast.Identifier{Value: "_"}, Body: &ast.Nil{}, }) } return node } func (p *Parser) parseModel() ast.Expression { p.next() node := &ast.Model{ Parameters: p.parseExpression(lowest), } if p.peekIs(token.Colon) { p.next() p.next() node.Parent = p.parseExpression(lowest) } return node } func (p *Parser) parseInfix(left ast.Expression) ast.Expression { node := &ast.Infix{ Operator: p.cur.Literal, Left: left, } precedence := p.curPrecedence() p.next() node.Right = p.parseExpression(precedence) return node } func (p *Parser) parseFunctionCall(left ast.Expression) ast.Expression { p.next() return &ast.Call{ Function: left, Argument: p.parseExpression(assign), } }
parser/expressions.go
0.703448
0.475057
expressions.go
starcoder
package sql import ( "io" ) // Row is a tuple of values. type Row []interface{} // NewRow creates a row from the given values. func NewRow(values ...interface{}) Row { row := make([]interface{}, len(values)) copy(row, values) return row } // Copy creates a new row with the same values as the current one. func (r Row) Copy() Row { return NewRow(r...) } // Append appends all the values in r2 to this row and returns the result func (r Row) Append(r2 Row) Row { row := make(Row, len(r)+len(r2)) for i := range r { row[i] = r[i] } for i := range r2 { row[i+len(r)] = r2[i] } return row } // Equals checks whether two rows are equal given a schema. func (r Row) Equals(row Row, schema Schema) (bool, error) { if len(row) != len(r) || len(row) != len(schema) { return false, nil } for i, colLeft := range r { colRight := row[i] cmp, err := schema[i].Type.Compare(colLeft, colRight) if err != nil { return false, err } if cmp != 0 { return false, nil } } return true, nil } // RowIter is an iterator that produces rows. type RowIter interface { // Next retrieves the next row. It will return io.EOF if it's the last row. // After retrieving the last row, Close will be automatically closed. Next() (Row, error) // Close the iterator. Close() error } // RowIterToRows converts a row iterator to a slice of rows. func RowIterToRows(i RowIter) ([]Row, error) { var rows []Row for { row, err := i.Next() if err == io.EOF { break } if err != nil { return nil, err } rows = append(rows, row) } return rows, i.Close() } // NodeToRows converts a node to a slice of rows. func NodeToRows(ctx *Context, n Node) ([]Row, error) { i, err := n.RowIter(ctx, nil) if err != nil { return nil, err } return RowIterToRows(i) } // RowsToRowIter creates a RowIter that iterates over the given rows. func RowsToRowIter(rows ...Row) RowIter { return &sliceRowIter{rows: rows} } type sliceRowIter struct { rows []Row idx int } func (i *sliceRowIter) Next() (Row, error) { if i.idx >= len(i.rows) { return nil, io.EOF } r := i.rows[i.idx] i.idx++ return r.Copy(), nil } func (i *sliceRowIter) Close() error { i.rows = nil return nil }
sql/row.go
0.773772
0.516961
row.go
starcoder
package missing_file_validation import ( "github.com/threagile/threagile/model" ) func Category() model.RiskCategory { return model.RiskCategory{ Id: "missing-file-validation", Title: "Missing File Validation", Description: "When a technical asset accepts files, these input files should be strictly validated about filename and type.", Impact: "If this risk is unmitigated, attackers might be able to provide malicious files to the application.", ASVS: "V12 - File and Resources Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html", Action: "File Validation", Mitigation: "Filter by file extension and discard (if feasible) the name provided. Whitelist the accepted file types " + "and determine the mime-type on the server-side (for example via \"Apache Tika\" or similar checks). If the file is retrievable by " + "endusers and/or backoffice employees, consider performing scans for popular malware (if the files can be retrieved much later than they " + "were uploaded, also apply a fresh malware scan during retrieval to scan with newer signatures of popular malware). Also enforce " + "limits on maximum file size to avoid denial-of-service like scenarios.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: model.Development, STRIDE: model.Spoofing, DetectionLogic: "In-scope technical assets with custom-developed code accepting file data formats.", RiskAssessment: "The risk rating depends on the sensitivity of the technical asset itself and of the data assets processed and stored.", FalsePositives: "Fully trusted (i.e. cryptographically signed or similar) files can be considered " + "as false positives after individual review.", ModelFailurePossibleReason: false, CWE: 434, } } func SupportedTags() []string { return []string{} } func GenerateRisks() []model.Risk { risks := make([]model.Risk, 0) for _, id := range model.SortedTechnicalAssetIDs() { technicalAsset := model.ParsedModelRoot.TechnicalAssets[id] if technicalAsset.OutOfScope || !technicalAsset.CustomDevelopedParts { continue } for _, format := range technicalAsset.DataFormatsAccepted { if format == model.File { risks = append(risks, createRisk(technicalAsset)) } } } return risks } func createRisk(technicalAsset model.TechnicalAsset) model.Risk { title := "<b>Missing File Validation</b> risk at <b>" + technicalAsset.Title + "</b>" impact := model.LowImpact if technicalAsset.HighestConfidentiality() == model.Sensitive || technicalAsset.HighestIntegrity() == model.MissionCritical || technicalAsset.HighestAvailability() == model.MissionCritical { impact = model.MediumImpact } risk := model.Risk{ Category: Category(), Severity: model.CalculateSeverity(model.VeryLikely, impact), ExploitationLikelihood: model.VeryLikely, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, DataBreachProbability: model.Probable, DataBreachTechnicalAssetIDs: []string{technicalAsset.Id}, } risk.SyntheticId = risk.Category.Id + "@" + technicalAsset.Id return risk }
risks/built-in/missing-file-validation/missing-file-validation-rule.go
0.612889
0.459743
missing-file-validation-rule.go
starcoder
package common import ( "errors" "fmt" "github.com/mikeyhu/glipso/interfaces" ) type evaluator func([]interfaces.Value, interfaces.Scope) (interfaces.Value, error) type lazyEvaluator func([]interfaces.Type, interfaces.Scope) (interfaces.Value, error) var inbuilt map[REF]FI func init() { inbuilt = map[REF]FI{} addInbuilt(FI{name: "=", evaluator: equals}) addInbuilt(FI{name: "+", evaluator: plusAll}) addInbuilt(FI{name: "-", evaluator: minusAll}) addInbuilt(FI{name: "*", evaluator: multiplyAll}) addInbuilt(FI{name: "%", evaluator: mod, argumentCount: 2}) addInbuilt(FI{name: "<", evaluator: lessThan}) addInbuilt(FI{name: ">", evaluator: greaterThan}) addInbuilt(FI{name: "<=", evaluator: lessThanEqual}) addInbuilt(FI{name: ">=", evaluator: greaterThanEqual}) addInbuilt(FI{name: "and", evaluator: and}) addInbuilt(FI{name: "assoc", evaluator: assoc}) addInbuilt(FI{name: "apply", lazyEvaluator: apply, argumentCount: 2}) addInbuilt(FI{name: "cons", evaluator: cons}) addInbuilt(FI{name: "def", lazyEvaluator: def, argumentCount: 2}) addInbuilt(FI{name: "do", lazyEvaluator: do}) addInbuilt(FI{name: "empty", evaluator: empty, argumentCount: 1}) addInbuilt(FI{name: "if", lazyEvaluator: iff, argumentCount: 3}) addInbuilt(FI{name: "filter", evaluator: filter, argumentCount: 2}) addInbuilt(FI{name: "first", evaluator: first, argumentCount: 1}) addInbuilt(FI{name: "get", evaluator: get, argumentCount: 2}) addInbuilt(FI{name: "fn", lazyEvaluator: fn, argumentCount: 2}) addInbuilt(FI{name: "hash-map", evaluator: hashmap}) addInbuilt(FI{name: "lazypair", lazyEvaluator: lazypair}) addInbuilt(FI{name: "let", lazyEvaluator: let, argumentCount: 2}) addInbuilt(FI{name: "macro", lazyEvaluator: macro, argumentCount: 2}) addInbuilt(FI{name: "map", evaluator: mapp, argumentCount: 2}) addInbuilt(FI{name: "or", evaluator: or}) addInbuilt(FI{name: "print", evaluator: printt}) addInbuilt(FI{name: "panic", evaluator: panicc, argumentCount: 1}) addInbuilt(FI{name: "range", evaluator: rnge, argumentCount: 2}) addInbuilt(FI{name: "tail", evaluator: tail, argumentCount: 1}) addInbuilt(FI{name: "take", evaluator: take, argumentCount: 2}) } func addInbuilt(info FI) { inbuilt[REF(info.name)] = info } func plusAll(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { return numericFlatten(arguments, func(a interfaces.Numeric, b interfaces.Numeric) interfaces.Numeric { return a.Add(b) }) } func minusAll(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { return numericFlatten(arguments, func(a interfaces.Numeric, b interfaces.Numeric) interfaces.Numeric { return a.Subtract(b) }) } func multiplyAll(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { return numericFlatten(arguments, func(a interfaces.Numeric, b interfaces.Numeric) interfaces.Numeric { return a.Multiply(b) }) } func mod(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { a, aok := arguments[0].(I) b, bok := arguments[1].(I) if aok && bok { return a.Mod(b), nil } return NILL, errors.New("mod : unsupported type") } func equals(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { first, fok := arguments[0].(interfaces.Equalable) second, sok := arguments[1].(interfaces.Equalable) if fok && sok { return first.Equals(second), nil } return NILL, fmt.Errorf("Equals : unsupported type %v or %v", arguments[0], arguments[1]) } func lessThan(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { first, fok := arguments[0].(interfaces.Comparable) second, sok := arguments[1].(interfaces.Comparable) if fok && sok { compare, err := first.CompareTo(second) if err != nil { return NILL, err } if err != nil { return NILL, err } return B(compare < 0), nil } return NILL, fmt.Errorf("lessThan : unsupported type %v or %v", arguments[0], arguments[1]) } func lessThanEqual(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { first, fok := arguments[0].(interfaces.Comparable) second, sok := arguments[1].(interfaces.Comparable) if fok && sok { compare, err := first.CompareTo(second) if err != nil { return NILL, err } return B(compare <= 0), nil } return NILL, fmt.Errorf("lessThanEqual : unsupported type %v or %v", arguments[0], arguments[1]) } func greaterThan(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { first, fok := arguments[0].(interfaces.Comparable) second, sok := arguments[1].(interfaces.Comparable) if fok && sok { compare, err := first.CompareTo(second) if err != nil { return NILL, err } return B(compare > 0), nil } return NILL, fmt.Errorf("greaterThan : unsupported type %v or %v", arguments[0], arguments[1]) } func greaterThanEqual(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { first, fok := arguments[0].(interfaces.Comparable) second, sok := arguments[1].(interfaces.Comparable) if fok && sok { compare, err := first.CompareTo(second) if err != nil { return NILL, err } return B(compare >= 0), nil } return NILL, fmt.Errorf("greaterThanEqual : unsupported type %v or %v", arguments[0], arguments[1]) } func cons(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { if len(arguments) == 0 { return ENDED, nil } else if len(arguments) == 1 { return P{arguments[0], ENDED}, nil } else if len(arguments) == 2 { tail, ok := arguments[1].(P) if ok { return P{arguments[0], tail}, nil } } return ENDED, nil } func first(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { pair, ok := arguments[0].(interfaces.Iterable) if ok { return pair.Head(), nil } return NILL, fmt.Errorf("first : %v is not of type Iterable", arguments[0]) } func tail(arguments []interfaces.Value, sco interfaces.Scope) (interfaces.Value, error) { pair, ok := arguments[0].(interfaces.Iterable) if ok { if pair.HasTail() { return pair.Iterate(sco) } return ENDED, nil } return NILL, fmt.Errorf("tail : %v is not of type Iterable", arguments[0]) } func apply(arguments []interfaces.Type, sco interfaces.Scope) (interfaces.Value, error) { list, err := evaluateToValue(arguments[1], sco) if err != nil { return NILL, err } s, okRef := arguments[0].(REF) p, okPair := list.(interfaces.Sliceable) if !okRef { return NILL, fmt.Errorf("apply : expected function, found %v", arguments[0]) } else if !okPair { return NILL, fmt.Errorf("apply : expected pair, found %v", list) } slice, err := p.ToSlice(sco.NewChildScope()) if err != nil { return NILL, err } return evaluateToValue(&EXP{Function: s, Arguments: slice}, sco) } func iff(arguments []interfaces.Type, sco interfaces.Scope) (interfaces.Value, error) { test, err := evaluateToValue(arguments[0], sco) if err != nil { return NILL, err } if iff, iok := test.(B); iok { if iff { return evaluateToValue(arguments[1], sco) } return evaluateToValue(arguments[2], sco) } return NILL, fmt.Errorf("if : expected first argument to evaluate to boolean, recieved %v", test) } func def(arguments []interfaces.Type, sco interfaces.Scope) (interfaces.Value, error) { value, err := evaluateToValue(arguments[1], sco) if err != nil { return NILL, err } GlobalEnvironment.CreateRef(arguments[0].(REF), value) return NILL, nil } func do(arguments []interfaces.Type, sco interfaces.Scope) (interfaces.Value, error) { var result interfaces.Value for _, a := range arguments { next, err := evaluateToValue(a, sco.NewChildScope()) if err != nil { return NILL, err } result = next } return result, nil } func rnge(arguments []interfaces.Value, sco interfaces.Scope) (interfaces.Value, error) { start := arguments[0].(I) end := arguments[1].(I) if start < end { return createLAZYP(sco, start, REF("range"), I(start.Int()+1), end), nil } return P{end, ENDED}, nil } func fn(arguments []interfaces.Type, sco interfaces.Scope) (interfaces.Value, error) { var argVec VEC if args, ok := arguments[0].(REF); ok { arg, err := args.Evaluate(sco) if err != nil { return NILL, err } argVec = arg.(VEC) } else { argVec = arguments[0].(VEC) } return FN{argVec, arguments[1].(interfaces.Evaluatable)}, nil } func filter(arguments []interfaces.Value, sco interfaces.Scope) (interfaces.Value, error) { ap, apok := arguments[0].(interfaces.Appliable) iter, iok := arguments[1].(interfaces.Iterable) var flt func(interfaces.Iterable) (interfaces.Iterable, error) flt = func(it interfaces.Iterable) (interfaces.Iterable, error) { head := it.Head() res, err := evaluateToValue(&EXP{Function: ap, Arguments: []interfaces.Type{head}}, sco.NewChildScope()) if err != nil { return ENDED, err } if include, iok := res.(B); iok { if it.HasTail() { next, err := it.Iterate(sco) if err != nil { return ENDED, err } if bool(include) { return createLAZYP(sco, head, REF("filter"), ap, next), nil } return flt(next) } if bool(include) { return &P{head, ENDED}, nil } return ENDED, nil } return ENDED, fmt.Errorf("filter : expected boolean value, recieved %v", res) } if apok && iok { return flt(iter) } return NILL, fmt.Errorf("filter : expected function and list. Recieved %v, %v", arguments[0], arguments[1]) } func mapp(arguments []interfaces.Value, sco interfaces.Scope) (interfaces.Value, error) { fn, fnok := arguments[0].(interfaces.Appliable) list, lok := arguments[1].(interfaces.Iterable) if fnok && lok { head := list.Head() res, err := evaluateToValue(&EXP{Function: fn, Arguments: []interfaces.Type{head}}, sco.NewChildScope()) if err == nil { if !list.HasTail() { return &P{res, ENDED}, nil } next, err := list.Iterate(sco) if err == nil { return createLAZYP(sco, res, REF("map"), fn, next), nil } } return ENDED, err } return ENDED, fmt.Errorf("map : expected function and list, recieved %v, %v", arguments[0], arguments[1]) } func lazypair(arguments []interfaces.Type, sco interfaces.Scope) (interfaces.Value, error) { head, err := evaluateToValue(arguments[0], sco) if err != nil { return NILL, err } if len(arguments) > 1 { if tail, ok := arguments[1].(interfaces.Evaluatable); ok { return LAZYP{head, BindEvaluation(tail, sco)}, nil } return NILL, fmt.Errorf("lazypair : expected EXP got %v", arguments[1]) } return LAZYP{head, nil}, nil } func macro(arguments []interfaces.Type, _ interfaces.Scope) (interfaces.Value, error) { return MAC{arguments[0].(VEC), arguments[1].(*EXP)}, nil } func printt(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { for _, arg := range arguments { fmt.Printf("%v\n", arg) } return NILL, nil } func empty(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { list, ok := arguments[0].(interfaces.Iterable) if !ok { return ENDED, fmt.Errorf("empty : expected Iterable got %v", arguments[0]) } if list != ENDED { return B(false), nil } return B(true), nil } func take(arguments []interfaces.Value, sco interfaces.Scope) (interfaces.Value, error) { num, nok := arguments[0].(I) list, lok := arguments[1].(interfaces.Iterable) if nok && lok { if num > 1 && list.HasTail() { next, err := list.Iterate(sco) if err != nil { return NILL, err } return createLAZYP(sco, list.Head(), REF("take"), num-1, next), nil } return P{list.Head(), ENDED}, nil } return ENDED, errors.New("take : expected number and list") } func let(arguments []interfaces.Type, sco interfaces.Scope) (interfaces.Value, error) { vectors, vok := arguments[0].(VEC) exp, eok := arguments[1].(interfaces.Evaluatable) childScope := sco.NewChildScope() if vok && eok { count := vectors.count() if count%2 > 0 { return NILL, fmt.Errorf("let : expected an even number of items in vector, recieved %v", count) } for i := 0; i < count; i += 2 { val, err := evaluateToValue(vectors.Get(i+1), childScope) if err != nil { return NILL, err } childScope.CreateRef(vectors.Get(i), val) } return exp.Evaluate(childScope) } return NILL, fmt.Errorf("let : expected VEC and EXP, received: %v, %v", arguments[0], arguments[1]) } func panicc(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { panic(arguments[0].String()) } func hashmap(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { return initialiseMAP(arguments) } func assoc(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { mp, ok := arguments[0].(*MAP) if !ok { return NILL, fmt.Errorf("assoc : first argument should be a MAP") } return mp.associate(arguments[1:]) } func get(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { k, kok := arguments[0].(interfaces.Equalable) mp, mok := arguments[1].(*MAP) if kok && mok { v, found := mp.lookup(k) if found { return v, nil } return NILL, nil } return NILL, fmt.Errorf("get : expected key and map") } func and(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { for _, a := range arguments { if asB, ok := a.(B); ok { if !asB { return B(false), nil } } else { return NILL, fmt.Errorf("and : expected all arguments to be B") } } return B(true), nil } func or(arguments []interfaces.Value, _ interfaces.Scope) (interfaces.Value, error) { for _, a := range arguments { if asB, ok := a.(B); ok { if asB { return B(true), nil } } else { return NILL, fmt.Errorf("or : expected all arguments to be B") } } return B(false), nil }
common/inbuilt.go
0.613237
0.483161
inbuilt.go
starcoder
package v1alpha1 import ( v1alpha1 "kubeform.dev/provider-oci-api/apis/ai/v1alpha1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" ) // AnomalyDetectionDataAssetLister helps list AnomalyDetectionDataAssets. // All objects returned here must be treated as read-only. type AnomalyDetectionDataAssetLister interface { // List lists all AnomalyDetectionDataAssets in the indexer. // Objects returned here must be treated as read-only. List(selector labels.Selector) (ret []*v1alpha1.AnomalyDetectionDataAsset, err error) // AnomalyDetectionDataAssets returns an object that can list and get AnomalyDetectionDataAssets. AnomalyDetectionDataAssets(namespace string) AnomalyDetectionDataAssetNamespaceLister AnomalyDetectionDataAssetListerExpansion } // anomalyDetectionDataAssetLister implements the AnomalyDetectionDataAssetLister interface. type anomalyDetectionDataAssetLister struct { indexer cache.Indexer } // NewAnomalyDetectionDataAssetLister returns a new AnomalyDetectionDataAssetLister. func NewAnomalyDetectionDataAssetLister(indexer cache.Indexer) AnomalyDetectionDataAssetLister { return &anomalyDetectionDataAssetLister{indexer: indexer} } // List lists all AnomalyDetectionDataAssets in the indexer. func (s *anomalyDetectionDataAssetLister) List(selector labels.Selector) (ret []*v1alpha1.AnomalyDetectionDataAsset, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.AnomalyDetectionDataAsset)) }) return ret, err } // AnomalyDetectionDataAssets returns an object that can list and get AnomalyDetectionDataAssets. func (s *anomalyDetectionDataAssetLister) AnomalyDetectionDataAssets(namespace string) AnomalyDetectionDataAssetNamespaceLister { return anomalyDetectionDataAssetNamespaceLister{indexer: s.indexer, namespace: namespace} } // AnomalyDetectionDataAssetNamespaceLister helps list and get AnomalyDetectionDataAssets. // All objects returned here must be treated as read-only. type AnomalyDetectionDataAssetNamespaceLister interface { // List lists all AnomalyDetectionDataAssets in the indexer for a given namespace. // Objects returned here must be treated as read-only. List(selector labels.Selector) (ret []*v1alpha1.AnomalyDetectionDataAsset, err error) // Get retrieves the AnomalyDetectionDataAsset from the indexer for a given namespace and name. // Objects returned here must be treated as read-only. Get(name string) (*v1alpha1.AnomalyDetectionDataAsset, error) AnomalyDetectionDataAssetNamespaceListerExpansion } // anomalyDetectionDataAssetNamespaceLister implements the AnomalyDetectionDataAssetNamespaceLister // interface. type anomalyDetectionDataAssetNamespaceLister struct { indexer cache.Indexer namespace string } // List lists all AnomalyDetectionDataAssets in the indexer for a given namespace. func (s anomalyDetectionDataAssetNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.AnomalyDetectionDataAsset, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1alpha1.AnomalyDetectionDataAsset)) }) return ret, err } // Get retrieves the AnomalyDetectionDataAsset from the indexer for a given namespace and name. func (s anomalyDetectionDataAssetNamespaceLister) Get(name string) (*v1alpha1.AnomalyDetectionDataAsset, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(v1alpha1.Resource("anomalydetectiondataasset"), name) } return obj.(*v1alpha1.AnomalyDetectionDataAsset), nil }
client/listers/ai/v1alpha1/anomalydetectiondataasset.go
0.612657
0.429788
anomalydetectiondataasset.go
starcoder
package core import ( "reflect" "github.com/lorenzodonini/ocpp-go/ocpp1.6/types" ) // -------------------- MeterValues (CP -> CS) -------------------- const MeterValuesFeatureName = "MeterValues" // The field definition of the MeterValues request payload sent by the Charge Point to the Central System. type MeterValuesRequest struct { ConnectorId int `json:"connectorId" validate:"gte=0"` TransactionId *int `json:"transactionId,omitempty"` MeterValue []types.MeterValue `json:"meterValue" validate:"required,min=1,dive"` } // This field definition of the Authorize confirmation payload, sent by the Charge Point to the Central System in response to an AuthorizeRequest. // In case the request was invalid, or couldn't be processed, an error will be sent instead. type MeterValuesConfirmation struct { } // A Charge Point MAY sample the electrical meter or other sensor/transducer hardware to provide extra information about its meter values. // It is up to the Charge Point to decide when it will send meter values. // This can be configured using the ChangeConfiguration message to specify data acquisition intervals and specify data to be acquired & reported. // The Charge Point SHALL send a MeterValuesRequest for offloading meter values. The request PDU SHALL contain for each sample: // 1. The id of the Connector from which samples were taken. If the connectorId is 0, it is associated with the entire Charge Point. // If the connectorId is 0 and the Measurand is energy related, the sample SHOULD be taken from the main energy meter. // 2. The transactionId of the transaction to which these values are related, if applicable. // If there is no transaction in progress or if the values are taken from the main meter, then transaction id may be omitted. // 3. One or more meterValue elements, of type MeterValue, each representing a set of one or more data values taken at a particular point in time. // Each MeterValue element contains a timestamp and a set of one or more individual sampledValue elements, all captured at the same point in time. // Each sampledValue element contains a single value datum. The nature of each sampledValue is determined by the optional measurand, context, location, unit, phase, and format fields. // The optional measurand field specifies the type of value being measured/reported. The optional context field specifies the reason/event triggering the reading. // The optional location field specifies where the measurement is taken (e.g. Inlet, Outlet). // The optional phase field specifies to which phase or phases of the electric installation the value applies. // The Charging Point SHALL report all phase number dependent values from the electrical meter (or grid connection when absent) point of view. // For individual connector phase rotation information, the Central System MAY query the ConnectorPhaseRotation configuration key on the Charging Point via GetConfiguration. // The Charge Point SHALL report the phase rotation in respect to the grid connection. Possible values per connector are: // NotApplicable, Unknown, RST, RTS, SRT, STR, TRS and TSR. see section Standard Configuration Key Names & Values for more information. // The EXPERIMENTAL optional format field specifies whether the data is represented in the normal (default) form as a simple numeric value ("Raw"), or as “SignedData”, an opaque digitally signed binary data block, represented as hex data. This experimental field may be deprecated and subsequently removed in later versions, when a more mature solution alternative is provided. // To retain backward compatibility, the default values of all of the optional fields on a sampledValue element are such that a value without any additional fields will be interpreted, as a register reading of active import energy in Wh (Watt-hour) units. // Upon receipt of a MeterValuesRequest, the Central System SHALL respond with a MeterValuesConfirmation. // It is likely that The Central System applies sanity checks to the data contained in a MeterValuesRequest it received. The outcome of such sanity checks SHOULD NOT ever cause the Central System to not respond with a MeterValuesConfirmation. Failing to respond with a MeterValues.conf will only cause the Charge Point to try the same message again as specified in Error responses to transaction-related messages. type MeterValuesFeature struct{} func (f MeterValuesFeature) GetFeatureName() string { return MeterValuesFeatureName } func (f MeterValuesFeature) GetRequestType() reflect.Type { return reflect.TypeOf(MeterValuesRequest{}) } func (f MeterValuesFeature) GetResponseType() reflect.Type { return reflect.TypeOf(MeterValuesConfirmation{}) } func (r MeterValuesRequest) GetFeatureName() string { return MeterValuesFeatureName } func (c MeterValuesConfirmation) GetFeatureName() string { return MeterValuesFeatureName } // Creates a new MeterValuesRequest, containing all required fields. Optional fields may be set afterwards. func NewMeterValuesRequest(connectorId int, meterValues []types.MeterValue) *MeterValuesRequest { return &MeterValuesRequest{ConnectorId: connectorId, MeterValue: meterValues} } // Creates a new MeterValuesConfirmation, which doesn't contain any required or optional fields. func NewMeterValuesConfirmation() *MeterValuesConfirmation { return &MeterValuesConfirmation{} }
ocpp1.6/core/meter_values.go
0.804713
0.530662
meter_values.go
starcoder
package tuikit import ( "strconv" "github.com/nsf/tulib" ) //---------------------------------------------------------------------------- // Point //---------------------------------------------------------------------------- // A Point is an X, Y coordinate pair. The axes increase right and down. type Point struct { X, Y int } // PointZero is the zero Point. var PointZero Point // NewPoint is shorthand for Point{X, Y}. func NewPoint(x, y int) Point { return Point{ X: x, Y: y, } } // String returns a string representation of p like "(x3,y4)". func (p Point) String() string { return "(x" + strconv.Itoa(p.X) + ",y" + strconv.Itoa(p.Y) + ")" } // Add returns the vector p+q. func (p Point) Add(q Point) Point { return Point{p.X + q.X, p.Y + q.Y} } // Sub returns the vector p-q. func (p Point) Sub(q Point) Point { return Point{p.X - q.X, p.Y - q.Y} } // Mul returns the vector p*k. func (p Point) Mul(k int) Point { return Point{p.X * k, p.Y * k} } // Div returns the vector p/k. func (p Point) Div(k int) Point { return Point{p.X / k, p.Y / k} } // Eq reports whether p and q are equal. func (p Point) Eq(q Point) bool { return p.X == q.X && p.Y == q.Y } // In reports whether p is in r. func (p Point) In(r Rect) bool { return r.X <= p.X && p.X < (r.X+r.Width) && r.Y <= p.Y && p.Y < (r.Y+r.Height) } //---------------------------------------------------------------------------- // Size //---------------------------------------------------------------------------- // A Size is a Width, Height pair. type Size struct { Width, Height int } // SizeZero is the zero Size. var SizeZero Size // NewSize is shorthand for Size{Width, Height}. func NewSize(w, h int) Size { return Size{w, h} } // String returns a string representation of s like "(w3,h4)". func (s Size) String() string { return "(w" + strconv.Itoa(s.Width) + ",h" + strconv.Itoa(s.Height) + ")" } // Eq reports whether s and t are equal. func (s Size) Eq(t Size) bool { return s.Width == t.Width && s.Height == t.Height } // Empty reports whether the size contains no points. func (s Size) Empty() bool { return s.Width <= 0 || s.Height <= 0 } //---------------------------------------------------------------------------- // Rect //---------------------------------------------------------------------------- // A Rect is the composition of an origin Point and a Size. type Rect struct { Point Size } // RectZero is the zero Rect. var RectZero Rect // NewRect is shorthand for Rect{Point{X, Y}, Size{Width, Height}}. func NewRect(x, y, w, h int) Rect { return Rect{NewPoint(x, y), NewSize(w, h)} } // NewRectFromTulib creates a Rect equal to rect. func NewRectFromTulib(rect tulib.Rect) Rect { return NewRect(rect.X, rect.Y, rect.Width, rect.Height) } // TulibRect returns r as a tulib.Rect. func (r Rect) TulibRect() tulib.Rect { return tulib.Rect{ X: r.X, Y: r.Y, Width: r.Width, Height: r.Height, } } // String returns a string representation of r like "(x3,y4)-(w6,h5)". func (r Rect) String() string { return r.Point.String() + "-" + r.Size.String() } // Eq reports whether r and s are equal. func (r Rect) Eq(s Rect) bool { return r.Point.Eq(s.Point) && r.Size.Eq(s.Size) } // Max returns the most bottom-right Point still inside r. func (r Rect) Max() Point { if r.Empty() { return r.Point } return NewPoint(r.X+r.Width-1, r.Y+r.Height-1) } // Add returns the rectangle r translated by p. func (r Rect) Add(p Point) Rect { return NewRect(r.X+p.X, r.Y+p.Y, r.Width, r.Height) } // Sub returns the rectangle r translated by -p. func (r Rect) Sub(p Point) Rect { return NewRect(r.X-p.X, r.Y-p.Y, r.Width, r.Height) } // Inset returns the rectangle r inset by n, which may be negative. If either // of r's dimensions is less than 2*n then an empty rectangle near the center // of r will be returned. func (r Rect) Inset(n int) Rect { if r.Width < 2*n { r.X = r.X + r.Width/2 r.Width = 0 } else { r.X += n r.Width -= 2 * n } if r.Height < 2*n { r.Y = r.Y + r.Height/2 r.Height = 0 } else { r.Y += n r.Height -= 2 * n } return r } // Intersect returns the largest rectangle contained by both r and s. If the // two rectangles do not overlap then the zero rectangle will be returned. func (r Rect) Intersect(s Rect) Rect { // Calculate Max() before any changes rm := r.Max() sm := s.Max() if r.X < s.X { r.X = s.X } if r.Y < s.Y { r.Y = s.Y } if rm.X > sm.X { r.Width = sm.X - r.X + 1 } if rm.Y > sm.Y { r.Height = sm.Y - r.Y + 1 } if !r.Valid() { return RectZero } return r } // Union returns the smallest rectangle that contains both r and s. func (r Rect) Union(s Rect) Rect { // Calculate Max() before any changes rm := r.Max() sm := s.Max() if r.X > s.X { r.X = s.X } if r.Y > s.Y { r.Y = s.Y } if rm.X < sm.X { r.Width = sm.X - r.X + 1 } if rm.Y < sm.Y { r.Height = sm.Y - r.Y + 1 } return r } // Valid reports whether r is a valid Rect. func (r Rect) Valid() bool { return r.Width >= 0 && r.Height >= 0 } // Empty reports whether the rectangle contains no points. func (r Rect) Empty() bool { return r.Size.Empty() } // Overlaps reports whether r and s have a non-empty intersection. func (r Rect) Overlaps(s Rect) bool { rm := r.Max() sm := s.Max() return r.X <= sm.X && s.X <= rm.X && r.Y <= sm.Y && s.Y <= rm.Y } // In reports whether every point in r is in s. func (r Rect) In(s Rect) bool { if r.Empty() { return true } rm := r.Max() sm := s.Max() return s.X <= r.X && rm.X <= sm.X && s.Y <= r.Y && rm.Y <= sm.Y }
tuikit/geometry.go
0.88639
0.59514
geometry.go
starcoder
package tart // Developed by <NAME>, the Accumulation Distribution // Line is a volume-based indicator designed to measure the // cumulative flow of money into and out of a security. // Chaikin originally referred to the indicator as the // Cumulative Money Flow Line. As with cumulative indicators, // the Accumulation Distribution Line is a running total of // each period's Money Flow Volume. First, a multiplier is // calculated based on the relationship of the close to the // high-low range. Second, the Money Flow Multiplier is // multiplied by the period's volume to come up with a // Money Flow Volume. A running total of the Money Flow // Volume forms the Accumulation Distribution Line. // Chartists can use this indicator to affirm a security's // underlying trend or anticipate reversals when the // indicator diverges from the security price. // https://school.stockcharts.com/doku.php?id=technical_indicators:accumulation_distribution_line // https://www.investopedia.com/terms/a/accumulationdistribution.asp // https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/accumulation-distribution type Ad struct { ad float64 } func NewAd() *Ad { return &Ad{ ad: 0, } } func (a *Ad) Update(h, l, c, v float64) float64 { h2l := h - l if h2l > 0.0 { a.ad += (((c - l) - (h - c)) / h2l) * v } return a.ad } func (a *Ad) InitPeriod() int64 { return 0 } func (a *Ad) Valid() bool { return true } // Developed by <NAME>, the Accumulation Distribution // Line is a volume-based indicator designed to measure the // cumulative flow of money into and out of a security. // Chaikin originally referred to the indicator as the // Cumulative Money Flow Line. As with cumulative indicators, // the Accumulation Distribution Line is a running total of // each period's Money Flow Volume. First, a multiplier is // calculated based on the relationship of the close to the // high-low range. Second, the Money Flow Multiplier is // multiplied by the period's volume to come up with a // Money Flow Volume. A running total of the Money Flow // Volume forms the Accumulation Distribution Line. // Chartists can use this indicator to affirm a security's // underlying trend or anticipate reversals when the // indicator diverges from the security price. // https://school.stockcharts.com/doku.php?id=technical_indicators:accumulation_distribution_line // https://www.investopedia.com/terms/a/accumulationdistribution.asp // https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/accumulation-distribution func AdArr(h, l, c, v []float64) []float64 { out := make([]float64, len(c)) a := NewAd() for i := 0; i < len(c); i++ { out[i] = a.Update(h[i], l[i], c[i], v[i]) } return out }
ad.go
0.757525
0.694173
ad.go
starcoder
package canvas import ( "image" "image/color" "image/draw" "golang.org/x/image/colornames" "gonum.org/v1/gonum/mat" ) // Constants used to define the location of an Axis primitive. const ( BottomAxis Alignment = 0 LeftAxis Alignment = 1 TopAxis Alignment = 2 RightAxis Alignment = 3 ) // Axis represents a Primitive for horizontal and vertical axes with Axes as its parent. type Axis struct { primitive Min, Max float64 Loc Alignment Parent *Axes Typer *fontType } // newAxis creates a new Axis linked to an Axes. // The parameter location can be set to BottomAxis, LeftAxis, TopAxis or RightAxis. func newAxis(parent *Axes, location Alignment) (*Axis, error) { var ax Axis var o, s [2]float64 switch location { case BottomAxis: o = [2]float64{0, -0.1} s = [2]float64{1, 0.2} case LeftAxis: o = [2]float64{-0.1, 0} s = [2]float64{0.2, 1} case TopAxis: o = [2]float64{0, 0.9} s = [2]float64{1, 0.2} case RightAxis: o = [2]float64{0.9, 0} s = [2]float64{0.2, 1} } ax.Parent = parent ax.Loc = location ax.Origin = o ax.Size = s Tc := mat.NewDense(3, 3, []float64{ s[0], 0, o[0], 0, s[1], o[1], 0, 0, 1, }) ax.T = append(ax.T, parent.T...) ax.T = append(ax.T, Tc) ax.FillColor = color.Transparent parent.children = append(parent.children, &ax) return &ax, nil } // Render creates a Typer to be used by the children Labels. // The size of Typer is calculated whenever Axis is requested to render. // This ensures the size is updated on any parent's change. func (a *Axis) Render(dst draw.Image) { if len(a.children) == 0 { return } l := a.children[0].(*Label) bounds := l.Bounds() height := bounds.Max.Y - bounds.Min.Y t, _ := newFont(height * 72 / 300) t.XAlign = l.XAlign t.YAlign = l.YAlign a.Typer = t } // Labels adds X labels to the Axis with regular spacing. func (a *Axis) Labels(X []string, padding float64) { var spacing = (1 - padding*2) / (float64(len(X)) - 1) switch a.Loc { case BottomAxis: for i := range X { l, _ := newLabel(a, padding+spacing*float64(i), a.Size[0]*(0.4), 0.5, X[i]) l.YAlign = TopAlign NewTick(a, padding+spacing*float64(i), a.Size[0]*(0.4), 0.2, 2) } case LeftAxis: spacing = (1 - padding) / (float64(len(X)) - 1) for i := range X { l, _ := newLabel(a, a.Size[1]*(0.4), spacing*float64(i), 0.1, X[i]) l.XAlign = RightAlign NewTick(a, a.Size[1]*(0.4), spacing*float64(i), 0.2, 2) } case TopAxis: for i := range X { l, _ := newLabel(a, padding+spacing*float64(i), a.Size[0]*(0.6), 0.5, X[i]) l.YAlign = BottomAlign } case RightAxis: for i := range X { l, _ := newLabel(a, a.Size[1]*(0.6), padding+spacing*float64(i), 0.1, X[i]) l.XAlign = LeftAlign } } } // Tick represents a tick to be drawn on an Axis type Tick struct { primitive W int Parent *Axis } // NewTick creates a new Tick linked to an Axis. func NewTick(parent *Axis, x, y, l float64, w int) (*Tick, error) { var t Tick t.Parent = parent t.Origin = [2]float64{x, y} switch parent.Loc { case BottomAxis: t.Size = [2]float64{0, l} case LeftAxis: t.Size = [2]float64{l, 0} } t.W = w Tc := mat.DenseCopyOf(iM) t.T = append(t.T, parent.T...) t.T = append(t.T, Tc) t.FillColor = colornames.Black parent.children = append(parent.children, &t) return &t, nil } // Render makes sure Tick's Bounds gets called. func (t *Tick) Render(dst draw.Image) { draw.Draw(dst, t.Bounds(), &image.Uniform{t.Color()}, image.ZP, draw.Over) } // Bounds returns a a specific width in pixels. func (t *Tick) Bounds() image.Rectangle { var x0, y0, x1, y1 int v := transform(t) x0 = int(v.At(0, 0)) y0 = int(v.At(1, 0)) x1 = int(v.At(0, 1)) y1 = int(v.At(1, 1)) if x0 == x1 { x0 -= t.W / 2 x1 += t.W / 2 } if y0 == y1 { y0 -= t.W / 2 y1 += t.W / 2 } return image.Rect(min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1)) }
canvas/axis.go
0.717705
0.54825
axis.go
starcoder
package ptr import "strconv" // IntToStringp converts x to a string pointer. func IntToStringp(x int) *string { str := strconv.FormatInt(int64(x), 10) return &str } // IntpToStringp converts x to a string pointer. // It returns nil if x is nil. func IntpToStringp(x *int) *string { if x == nil { return nil } return IntToStringp(*x) } // IntpToString converts x to a string. // It returns an empty string if x is nil. func IntpToString(x *int) string { if x == nil { return "" } return strconv.FormatInt(int64(*x), 10) } // Int32ToStringp converts x to a string pointer. func Int32ToStringp(x int32) *string { str := strconv.FormatInt(int64(x), 10) return &str } // Int32pToStringp converts x to a string pointer. // It returns nil if x is nil. func Int32pToStringp(x *int32) *string { if x == nil { return nil } return Int32ToStringp(*x) } // Int32pToString converts x to a string. // It returns an emtpy string if x is nil. func Int32pToString(x *int32) string { if x == nil { return "" } return strconv.FormatInt(int64(*x), 10) } // Int64ToStringp converts x to a string pointer. func Int64ToStringp(x int64) *string { str := strconv.FormatInt(x, 10) return &str } // Int64pToStringp converts x to a string pointer. // It returns nil if x is nil. func Int64pToStringp(x *int64) *string { if x == nil { return nil } return Int64ToStringp(*x) } // Int64pToString converts x to a string. // It returns an empty string if x is nil. func Int64pToString(x *int64) string { if x == nil { return "" } return strconv.FormatInt(*x, 10) } // StringToIntp converts x to an int pointer. // It returns nil if x is not a valid number string. func StringToIntp(x string) *int { i, err := strconv.ParseInt(x, 0, 0) if err != nil { return nil } ii := int(i) return &ii } // StringpToIntp converts x to an int pointer. // It returns nil if x is nil or not a valid number string. func StringpToIntp(x *string) *int { if x == nil { return nil } return StringToIntp(*x) } // StringpToInt converts x to an integer. // It returns zero if x is nil or not a valid number string. func StringpToInt(x *string) int { if x == nil { return 0 } i, _ := strconv.ParseInt(*x, 0, 0) return int(i) } // StringToInt32p converts x to an int32 pointer. // It returns nil if x is not a valid number string. func StringToInt32p(x string) *int32 { i, err := strconv.ParseInt(x, 0, 0) if err != nil { return nil } ii := int32(i) return &ii } // StringpToInt32p converts x to an int32 pointer. // It returns nil if x is nil or not a valid number string. func StringpToInt32p(x *string) *int32 { if x == nil { return nil } return StringToInt32p(*x) } // StringpToInt32 converts x to an integer. // It returns zero if x is nil or not a valid number string. func StringpToInt32(x *string) int32 { if x == nil { return 0 } i, _ := strconv.ParseInt(*x, 0, 0) return int32(i) } // StringToInt64p converts x to an int64 pointer. // It returns nil if x is not a valid number string. func StringToInt64p(x string) *int64 { i, err := strconv.ParseInt(x, 0, 0) if err != nil { return nil } return &i } // StringpToInt64p converts x to an int64 pointer. // It returns nil if x is nil or not a valid number string. func StringpToInt64p(x *string) *int64 { if x == nil { return nil } return StringToInt64p(*x) } // StringpToInt64 converts x to an int64 value. // It returns zero if x is nil or not a valid number string. func StringpToInt64(x *string) int64 { if x == nil { return 0 } i, _ := strconv.ParseInt(*x, 0, 0) return i }
ptr/convert.go
0.787686
0.435962
convert.go
starcoder
package basic import "strings" // ReducePtrTest reduces a list to a single value by combining elements via a supplied function func ReducePtrTest() string { return ` func TestReduce<FTYPE>Ptr(t *testing.T) { var v1 <TYPE> = 1 var v2 <TYPE> = 2 var v3 <TYPE> = 3 var v4 <TYPE> = 4 var v5 <TYPE> = 5 list := []*<TYPE>{&v1, &v2, &v3, &v4, &v5} var expected <TYPE> = 15 actual := Reduce<FTYPE>Ptr(plus<FTYPE>Ptr, list) if *actual != expected { t.Errorf("Reduce<FTYPE>Ptr failed. actual=%v, expected=%v", *actual, expected) } list = []*<TYPE>{&v1, &v2, &v3, &v4, &v5} expected = 18 actual = Reduce<FTYPE>Ptr(plus<FTYPE>Ptr, list, 3) if *actual != expected { t.Errorf("Reduce<FTYPE>Ptr failed. actual=%v, expected=%v", *actual, expected) } list = []*<TYPE>{&v1, &v2} expected = 3 actual = Reduce<FTYPE>Ptr(plus<FTYPE>Ptr, list) if *actual != expected { t.Errorf("ReduceInt failed. actual=%v, expected=%v", *actual, expected) } list = []*<TYPE>{&v1} expected = 1 actual = Reduce<FTYPE>Ptr(plus<FTYPE>Ptr, list) if *actual != expected { t.Errorf("Reduce<FTYPE>Ptr failed. actual=%v, expected=%v", *actual, expected) } list = []*<TYPE>{} expected = 0 actual = Reduce<FTYPE>Ptr(plus<FTYPE>Ptr, list) if *actual != expected { t.Errorf("Reduce<FTYPE>Ptr failed. actual=%v, expected=%v", *actual, expected) t.Errorf(reflect.String.String()) } } func plus<FTYPE>Ptr(num1, num2 *<TYPE>) *<TYPE> { c := *num1 + *num2 return &c } ` } // **********Reduce<FTYPE>PtrErr************* // ReducePtrErrTest reduces a list to a single value by combining elements via a supplied function func ReducePtrErrTest() string { return ` func TestReduce<FTYPE>PtrErr(t *testing.T) { var v1 <TYPE> = 1 var v2 <TYPE> = 2 var v3 <TYPE> = 3 var v4 <TYPE> = 4 var v5 <TYPE> = 5 var v0 <TYPE> list := []*<TYPE>{&v1, &v2, &v3, &v4, &v5} var expected <TYPE> = 15 actual, _ := Reduce<FTYPE>PtrErr(plus<FTYPE>PtrErr, list) if *actual != expected { t.Errorf("Reduce<FTYPE>PtrErr failed. actual=%v, expected=%v", *actual, expected) } list2 := []*<TYPE>{&v1, &v0, &v3, &v4, &v5} _, err := Reduce<FTYPE>PtrErr(plus<FTYPE>PtrErr, list2) if err == nil { t.Errorf("Reduce<FTYPE>PtrErr failed. actual=%v, expected=%v", *actual, expected) } list = []*<TYPE>{&v1, &v2, &v3, &v4, &v5} expected = 18 actual, _ = Reduce<FTYPE>PtrErr(plus<FTYPE>PtrErr, list, 3) if *actual != expected { t.Errorf("Reduce<FTYPE>PtrErr failed. actual=%v, expected=%v", *actual, expected) } list = []*<TYPE>{&v1, &v2} expected = 3 actual, _ = Reduce<FTYPE>PtrErr(plus<FTYPE>PtrErr, list) if *actual != expected { t.Errorf("Reduce<FTYPE>PtrErr failed. actual=%v, expected=%v", *actual, expected) } list = []*<TYPE>{&v1} expected = 1 actual, _ = Reduce<FTYPE>PtrErr(plus<FTYPE>PtrErr, list) if *actual != expected { t.Errorf("Reduce<FTYPE>PtrErr failed. actual=%v, expected=%v", *actual, expected) } list = []*<TYPE>{} expected = 0 actual, _ = Reduce<FTYPE>PtrErr(plus<FTYPE>PtrErr, list) if *actual != expected { t.Errorf("Reduce<FTYPE>PtrErr failed. actual=%v, expected=%v", *actual, expected) } } func plus<FTYPE>PtrErr(num1, num2 *<TYPE>) (*<TYPE>, error) { if *num1 == 0 || *num2 == 0 { return nil, errors.New("0 in not valid number for this test") } c := *num1 + *num2 return &c, nil } ` } // ReplaceActivityReducePtrErr replaces ... func ReplaceActivityReducePtrErr(code string) string { s1 := `import ( _ "errors" "reflect" "testing" ) func TestReduceIntPtrErr(t *testing.T) {` s2 := `import ( "errors" "testing" ) func TestReduceIntPtrErr(t *testing.T) {` code = strings.Replace(code, s1, s2, -1) s1 = `func TestReduceStrPtrErr(t *testing.T) { var v1 string = "1" var v2 string = "2" var v3 string = "3" var v4 string = "4" var v5 string = "5" var v0 string list := []*string{&v1, &v2, &v3, &v4, &v5} var expected string = 15 actual, _ := ReduceStrPtrErr(plusStrPtrErr, list) if *actual != expected { t.Errorf("ReduceStrPtrErr failed. actual=%v, expected=%v", *actual, expected) } list2 := []*string{&v1, &v0, &v3, &v4, &v5} _, err := ReduceStrPtrErr(plusStrPtrErr, list2) if err == nil { t.Errorf("ReduceStrPtrErr failed. actual=%v, expected=%v", *actual, expected) } list = []*string{&v1, &v2, &v3, &v4, &v5} expected = 18 actual, _ = ReduceStrPtrErr(plusStrPtrErr, list, 3) if *actual != expected { t.Errorf("ReduceStrPtrErr failed. actual=%v, expected=%v", *actual, expected) } list = []*string{&v1, &v2} expected = 3 actual, _ = ReduceStrPtrErr(plusStrPtrErr, list) if *actual != expected { t.Errorf("ReduceStrPtrErr failed. actual=%v, expected=%v", *actual, expected) } list = []*string{&v1} expected = 1 actual, _ = ReduceStrPtrErr(plusStrPtrErr, list) if *actual != expected { t.Errorf("ReduceStrPtrErr failed. actual=%v, expected=%v", *actual, expected) } list = []*string{} expected = 0 actual, _ = ReduceStrPtrErr(plusStrPtrErr, list) if *actual != expected { t.Errorf("ReduceStrPtrErr failed. actual=%v, expected=%v", *actual, expected) } } func plusStrPtrErr(num1, num2 *string) (*string, error) { if *num1 == 0 || *num2 == 0 { return nil, errors.New("0 in not valid number for this test") } c := *num1 + *num2 return &c, nil }` s2 = `func TestReduceStrPtrErr(t *testing.T) { var v1 string = "1" var v2 string = "2" var v3 string = "3" var v4 string = "4" var v5 string = "5" var v0 string = "0" list := []*string{&v1, &v2, &v3, &v4, &v5} var expected string = "12345" actual, _ := ReduceStrPtrErr(plusStrPtrErr, list) if *actual != expected { t.Errorf("ReduceStrPtrErr failed. actual=%v, expected=%v", *actual, expected) } list2 := []*string{&v1, &v0, &v3, &v4, &v5} _, err := ReduceStrPtrErr(plusStrPtrErr, list2) if err == nil { t.Errorf("ReduceStrPtrErr failed. actual=%v, expected=%v", *actual, expected) } list = []*string{&v1, &v2, &v3, &v4, &v5} expected = "312345" actual, _ = ReduceStrPtrErr(plusStrPtrErr, list, "3") if *actual != expected { t.Errorf("ReduceStrPtrErr failed. actual=%v, expected=%v", *actual, expected) } list = []*string{&v1, &v2} expected = "12" actual, _ = ReduceStrPtrErr(plusStrPtrErr, list) if *actual != expected { t.Errorf("ReduceStrPtrErr failed. actual=%v, expected=%v", *actual, expected) } list = []*string{&v1} expected = "1" actual, _ = ReduceStrPtrErr(plusStrPtrErr, list) if *actual != expected { t.Errorf("ReduceStrPtrErr failed. actual=%v, expected=%v", *actual, expected) } list = []*string{} expected = "" actual, _ = ReduceStrPtrErr(plusStrPtrErr, list) if *actual != expected { t.Errorf("ReduceStrPtrErr failed. actual=%v, expected=%v", *actual, expected) } } func plusStrPtrErr(num1, num2 *string) (*string, error) { if *num1 == "0" || *num2 == "0" { return nil, errors.New("0 in not valid number for this test") } c := *num1 + *num2 return &c, nil }` code = strings.Replace(code, s1, s2, -1) return code } // **********Reduce<FTYPE>Err************* // ReduceErrTest reduces a list to a single value by combining elements via a supplied function func ReduceErrTest() string { return ` func TestReduce<FTYPE>Err(t *testing.T) { var v1 <TYPE> = 1 var v2 <TYPE> = 2 var v3 <TYPE> = 3 var v4 <TYPE> = 4 var v5 <TYPE> = 5 var v0 <TYPE> = 0 list := []<TYPE>{v1, v2, v3, v4, v5} var expected <TYPE> = 15 actual, _ := Reduce<FTYPE>Err(plus<FTYPE>Err, list) if actual != expected { t.Errorf("Reduce<FTYPE>Err failed. actual=%v, expected=%v", actual, expected) } list2 := []<TYPE>{v1, v0, v3, v4, v5} _, err := Reduce<FTYPE>Err(plus<FTYPE>Err, list2) if err == nil { t.Errorf("Reduce<FTYPE>Err failed. actual=%v, expected=%v", actual, expected) } list = []<TYPE>{v1, v2, v3, v4, v5} expected = 18 actual, _ = Reduce<FTYPE>Err(plus<FTYPE>Err, list, 3) if actual != expected { t.Errorf("Reduce<FTYPE>Err failed. actual=%v, expected=%v", actual, expected) } list = []<TYPE>{v1, v2} expected = 3 actual, _ = Reduce<FTYPE>Err(plus<FTYPE>Err, list) if actual != expected { t.Errorf("Reduce<FTYPE>Err failed. actual=%v, expected=%v", actual, expected) } list = []<TYPE>{v1} expected = 1 actual, _ = Reduce<FTYPE>Err(plus<FTYPE>Err, list) if actual != expected { t.Errorf("Reduce<FTYPE>Err failed. actual=%v, expected=%v", actual, expected) } list = []<TYPE>{} expected = 0 actual, _ = Reduce<FTYPE>Err(plus<FTYPE>Err, list) if actual != expected { t.Errorf("Reduce<FTYPE>Err failed. actual=%v, expected=%v", actual, expected) } } func plus<FTYPE>Err(num1, num2 <TYPE>) (<TYPE>, error) { if num1 == 0 || num2 == 0 { return <TYPE>(0), errors.New("0 in not valid number for this test") } c := num1 + num2 return c, nil } ` } // ReplaceActivityReduceErr replaces ... func ReplaceActivityReduceErr(code string) string { s1 := `import ( _ "errors" "reflect" "testing" ) func TestReduceIntErr(t *testing.T) {` s2 := `import ( "errors" "testing" ) func TestReduceIntErr(t *testing.T) {` code = strings.Replace(code, s1, s2, -1) s1 = `func TestReduceStrErr(t *testing.T) { var v1 string = "1" var v2 string = "2" var v3 string = "3" var v4 string = "4" var v5 string = "5" var v0 string = "0" list := []string{v1, v2, v3, v4, v5} var expected string = 15 actual, _ := ReduceStrErr(plusStrErr, list) if actual != expected { t.Errorf("ReduceStrErr failed. actual=%v, expected=%v", actual, expected) } list2 := []string{v1, v0, v3, v4, v5} _, err := ReduceStrErr(plusStrErr, list2) if err == nil { t.Errorf("ReduceStrErr failed. actual=%v, expected=%v", actual, expected) } list = []string{v1, v2, v3, v4, v5} expected = 18 actual, _ = ReduceStrErr(plusStrErr, list, 3) if actual != expected { t.Errorf("ReduceStrErr failed. actual=%v, expected=%v", actual, expected) } list = []string{v1, v2} expected = 3 actual, _ = ReduceStrErr(plusStrErr, list) if actual != expected { t.Errorf("ReduceStrErr failed. actual=%v, expected=%v", actual, expected) } list = []string{v1} expected = 1 actual, _ = ReduceStrErr(plusStrErr, list) if actual != expected { t.Errorf("ReduceStrErr failed. actual=%v, expected=%v", actual, expected) } list = []string{} expected = 0 actual, _ = ReduceStrErr(plusStrErr, list) if actual != expected { t.Errorf("ReduceStrErr failed. actual=%v, expected=%v", actual, expected) } } func plusStrErr(num1, num2 string) (string, error) { if num1 == 0 || num2 == 0 { return 0, errors.New("0 in not valid number for this test") } c := num1 + num2 return c, nil }` s2 = `func TestReduceStrErr(t *testing.T) { var v1 string = "1" var v2 string = "2" var v3 string = "3" var v4 string = "4" var v5 string = "5" var v0 string = "0" list := []string{v1, v2, v3, v4, v5} var expected string = "12345" actual, _ := ReduceStrErr(plusStrErr, list) if actual != expected { t.Errorf("ReduceStrErr failed. actual=%v, expected=%v", actual, expected) } list2 := []string{v1, v0, v3, v4, v5} _, err := ReduceStrErr(plusStrErr, list2) if err == nil { t.Errorf("ReduceStrErr failed. actual=%v, expected=%v", actual, expected) } list = []string{v1, v2, v3, v4, v5} expected = "312345" actual, _ = ReduceStrErr(plusStrErr, list, "3") if actual != expected { t.Errorf("ReduceStrErr failed. actual=%v, expected=%v", actual, expected) } list = []string{v1, v2} expected = "12" actual, _ = ReduceStrErr(plusStrErr, list) if actual != expected { t.Errorf("ReduceStrErr failed. actual=%v, expected=%v", actual, expected) } list = []string{v1} expected = "1" actual, _ = ReduceStrErr(plusStrErr, list) if actual != expected { t.Errorf("ReduceStrErr failed. actual=%v, expected=%v", actual, expected) } list = []string{} expected = "" actual, _ = ReduceStrErr(plusStrErr, list) if actual != expected { t.Errorf("ReduceStrErr failed. actual=%v, expected=%v", actual, expected) } } func plusStrErr(num1, num2 string) (string, error) { if num1 == "0" || num2 == "0" { return "", errors.New("0 in not valid number for this test") } c := num1 + num2 return c, nil }` code = strings.Replace(code, s1, s2, -1) return code }
internal/template/basic/reduceptrtest.go
0.5564
0.560794
reduceptrtest.go
starcoder
package drawing import ( "fmt" ) // PathBuilder describes the interface for path drawing. type PathBuilder interface { // LastPoint returns the current point of the current sub path LastPoint() (x, y float64) // MoveTo creates a new subpath that start at the specified point MoveTo(x, y float64) // LineTo adds a line to the current subpath LineTo(x, y float64) // QuadCurveTo adds a quadratic Bézier curve to the current subpath QuadCurveTo(cx, cy, x, y float64) // CubicCurveTo adds a cubic Bézier curve to the current subpath CubicCurveTo(cx1, cy1, cx2, cy2, x, y float64) // Close creates a line from the current point to the last MoveTo // point (if not the same) and mark the path as closed so the // first and last lines join nicely. Close() } // PathComponent represents component of a path type PathComponent int const ( // MoveToComponent is a MoveTo component in a Path MoveToComponent PathComponent = iota // LineToComponent is a LineTo component in a Path LineToComponent // QuadCurveToComponent is a QuadCurveTo component in a Path QuadCurveToComponent // CubicCurveToComponent is a CubicCurveTo component in a Path CubicCurveToComponent // ArcToComponent is a ArcTo component in a Path ArcToComponent // CloseComponent is a ArcTo component in a Path CloseComponent ) // Path stores points type Path struct { // Components is a slice of PathComponent in a Path and mark the role of each points in the Path Components []PathComponent // Points are combined with Components to have a specific role in the path Points []float64 // Last Point of the Path x, y float64 } func (p *Path) appendToPath(cmd PathComponent, points ...float64) { p.Components = append(p.Components, cmd) p.Points = append(p.Points, points...) } // LastPoint returns the current point of the current path func (p *Path) LastPoint() (x, y float64) { return p.x, p.y } // MoveTo starts a new path at (x, y) position func (p *Path) MoveTo(x, y float64) { p.appendToPath(MoveToComponent, x, y) p.x = x p.y = y } // LineTo adds a line to the current path func (p *Path) LineTo(x, y float64) { if len(p.Components) == 0 { // special case when no move has been done p.MoveTo(0, 0) } p.appendToPath(LineToComponent, x, y) p.x = x p.y = y } // QuadCurveTo adds a quadratic bezier curve to the current path func (p *Path) QuadCurveTo(cx, cy, x, y float64) { if len(p.Components) == 0 { // special case when no move has been done p.MoveTo(0, 0) } p.appendToPath(QuadCurveToComponent, cx, cy, x, y) p.x = x p.y = y } // CubicCurveTo adds a cubic bezier curve to the current path func (p *Path) CubicCurveTo(cx1, cy1, cx2, cy2, x, y float64) { if len(p.Components) == 0 { // special case when no move has been done p.MoveTo(0, 0) } p.appendToPath(CubicCurveToComponent, cx1, cy1, cx2, cy2, x, y) p.x = x p.y = y } // Close closes the current path func (p *Path) Close() { p.appendToPath(CloseComponent) } // Copy make a clone of the current path and return it func (p *Path) Copy() (dest *Path) { dest = new(Path) dest.Components = make([]PathComponent, len(p.Components)) copy(dest.Components, p.Components) dest.Points = make([]float64, len(p.Points)) copy(dest.Points, p.Points) dest.x, dest.y = p.x, p.y return dest } // Clear reset the path func (p *Path) Clear() { p.Components = p.Components[0:0] p.Points = p.Points[0:0] } // IsEmpty returns true if the path is empty func (p *Path) IsEmpty() bool { return len(p.Components) == 0 } // String returns a debug text view of the path func (p *Path) String() string { s := "" j := 0 for _, cmd := range p.Components { switch cmd { case MoveToComponent: s += fmt.Sprintf("MoveTo: %f, %f\n", p.Points[j], p.Points[j+1]) j += 2 case LineToComponent: s += fmt.Sprintf("LineTo: %f, %f\n", p.Points[j], p.Points[j+1]) j += 2 case QuadCurveToComponent: s += fmt.Sprintf("QuadCurveTo: %f, %f, %f, %f\n", p.Points[j], p.Points[j+1], p.Points[j+2], p.Points[j+3]) j += 4 case CubicCurveToComponent: s += fmt.Sprintf("CubicCurveTo: %f, %f, %f, %f, %f, %f\n", p.Points[j], p.Points[j+1], p.Points[j+2], p.Points[j+3], p.Points[j+4], p.Points[j+5]) j += 6 case ArcToComponent: s += fmt.Sprintf("ArcTo: %f, %f, %f, %f, %f, %f\n", p.Points[j], p.Points[j+1], p.Points[j+2], p.Points[j+3], p.Points[j+4], p.Points[j+5]) j += 6 case CloseComponent: s += "Close\n" } } return s }
drawing/path.go
0.744471
0.675923
path.go
starcoder
package retry // Strategy is a plugin to the Retrier that provides a hook to manipulate retry behavior. type Strategy interface { // Get returns the retry strategy instance itself. The instance may have internal state to keep track of things like // how much time has elapsed since Get() was called. Get() StrategyInstance // CanClassifyErrors indicates if the strategy can determine if an error is retryable. At least one strategy with // this capability needs to be passed. CanClassifyErrors() bool // CanWait indicates if the retry strategy can wait in a loop. At least one strategy with this capability // needs to be passed. CanWait() bool // CanTimeout indicates that the retry strategy can properly abort a loop. At least one retry strategy with // this capability needs to be passed. CanTimeout() bool } // StrategyInstance is the instantiation of a strategy. It may have internal state to keep track of things like how much // time has been elapsed since it was created. type StrategyInstance interface { // CanRetry returns an error if no more tries should be attempted. The error will be returned directly from the // retry function. The passed action parameters can be used to create a meaningful error message. CanRetry(wrap WrapFunc, err error, action string) error // Wait returns a channel that is closed when the wait time expires. The channel can have any content, so it is // provided as an interface{}. This function may return nil if it doesn't provide a wait time. Wait(err error) interface{} // OnWaitExpired is a hook that gives the strategy the option to return an error if its wait has expired. It will // only be called if it is the first to reach its wait. If no error is returned the loop is continued. The passed // action name can be incorporated into an error message. OnWaitExpired(wrap WrapFunc, err error, action string) error } // NewStrategy creates a wrapper for a strategy instance with the specified parameters. func NewStrategy( factory func() StrategyInstance, canClassifyErrors bool, canWait bool, canTimeout bool, ) Strategy { return &strategy{ factory: factory, canClassifyErrors: canClassifyErrors, canWait: canWait, canTimeout: canTimeout, } } type strategy struct { factory func() StrategyInstance canClassifyErrors bool canWait bool canTimeout bool } func (s *strategy) Get() StrategyInstance { return s.factory() } func (s *strategy) CanClassifyErrors() bool { return s.canClassifyErrors } func (s *strategy) CanWait() bool { return s.canWait } func (s *strategy) CanTimeout() bool { return s.canTimeout }
strategy.go
0.752104
0.400808
strategy.go
starcoder
package losses import ( mat "github.com/nlpodyssey/spago/pkg/mat32" "github.com/nlpodyssey/spago/pkg/ml/ag" ) // MAE measures the mean absolute error (a.k.a. L1 Loss) between each element in the input x and target y. func MAE(g *ag.Graph, x ag.Node, y ag.Node, reduceMean bool) ag.Node { loss := g.Abs(g.Sub(x, y)) if reduceMean { return g.ReduceMean(loss) } return g.ReduceSum(loss) } // MSE measures the mean squared error (squared L2 norm) between each element in the input x and target y. func MSE(g *ag.Graph, x ag.Node, y ag.Node, reduceMean bool) ag.Node { loss := g.ProdScalar(g.Square(g.Sub(x, y)), g.NewScalar(0.5)) if reduceMean { return g.ReduceMean(loss) } return g.ReduceSum(loss) } // NLL returns the loss of the input x respect to the target y. // The target is expected to be a one-hot vector. func NLL(g *ag.Graph, x ag.Node, y ag.Node) ag.Node { return g.Neg(g.ReduceSum(g.Prod(y, g.Log(x)))) } // CrossEntropy implements a cross-entropy loss function. // c is the index of the gold class func CrossEntropy(g *ag.Graph, x ag.Node, c int) ag.Node { return g.Add(g.Neg(g.AtVec(x, c)), g.Log(g.ReduceSum(g.Exp(x)))) } // Perplexity computes the perplexity, implemented as exp over the cross-entropy. func Perplexity(g *ag.Graph, x ag.Node, c int) ag.Node { return g.Exp(CrossEntropy(g, x, c)) } // ZeroOneQuantization is a loss function that is minimized when each component // of x satisfies x(i) ≡ [x]i ∈ {0, 1}. func ZeroOneQuantization(g *ag.Graph, x ag.Node) ag.Node { return g.ReduceSum(g.Prod(g.Square(x), g.Square(g.ReverseSub(x, g.NewScalar(1.0))))) } // Norm2Quantization is a loss function that is minimized when norm2(x) = 1. func Norm2Quantization(g *ag.Graph, x ag.Node) ag.Node { return g.Square(g.SubScalar(g.ReduceSum(g.Square(x)), g.NewScalar(1.0))) } // OneHotQuantization is a loss function that pushes towards the x vector to be 1-hot. // q is the quantization regularizer weight (suggested 0.00001). func OneHotQuantization(g *ag.Graph, x ag.Node, q mat.Float) ag.Node { return g.ProdScalar(g.Add(ZeroOneQuantization(g, x), Norm2Quantization(g, x)), g.NewScalar(q)) } // Distance is a loss function that calculates the distance between target and x. func Distance(g *ag.Graph, x ag.Node, target mat.Float) ag.Node { return g.Abs(g.Sub(g.NewScalar(target), x)) } // MSESeq calculates the MSE loss on the given sequence. func MSESeq(g *ag.Graph, predicted []ag.Node, target []ag.Node, reduceMean bool) ag.Node { loss := MSE(g, predicted[0], target[0], false) for i := 1; i < len(predicted); i++ { loss = g.Add(loss, MSE(g, predicted[i], target[i], false)) } if reduceMean { return g.DivScalar(loss, g.NewScalar(mat.Float(len(predicted)))) } return loss } // MAESeq calculates the MAE loss on the given sequence. func MAESeq(g *ag.Graph, predicted []ag.Node, target []ag.Node, reduceMean bool) ag.Node { loss := MAE(g, predicted[0], target[0], false) for i := 1; i < len(predicted); i++ { loss = g.Add(loss, MAE(g, predicted[i], target[i], false)) } if reduceMean { return g.DivScalar(loss, g.NewScalar(mat.Float(len(predicted)))) } return loss } // CrossEntropySeq calculates the CrossEntropy loss on the given sequence. func CrossEntropySeq(g *ag.Graph, predicted []ag.Node, target []int, reduceMean bool) ag.Node { loss := CrossEntropy(g, predicted[0], target[0]) for i := 1; i < len(predicted); i++ { loss = g.Add(loss, CrossEntropy(g, predicted[i], target[i])) } if reduceMean { return g.DivScalar(loss, g.NewScalar(mat.Float(len(predicted)))) } return loss } // SPG (Softmax Policy Gradient) is a Gradient Policy used in Reinforcement Learning. // logPropActions are the log-probability of the chosen action by the Agent at each time; // logProbTargets are results of the reward function i.e. the predicted log-likelihood of the ground truth at each time; func SPG(g *ag.Graph, logPropActions []ag.Node, logProbTargets []ag.Node) ag.Node { var loss ag.Node for t := 0; t < len(logPropActions); t++ { loss = g.Add(loss, g.Prod(logPropActions[t], logProbTargets[t])) } return g.Neg(loss) }
pkg/ml/losses/losses.go
0.884339
0.682618
losses.go
starcoder
package v1 import ( "context" "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Create a set of phrase hints. Each item in the set can be a single word or a multi-word phrase. The items in the PhraseSet are favored by the recognition model when you send a call that includes the PhraseSet. type PhraseSet struct { pulumi.CustomResourceState // Hint Boost. Positive value will increase the probability that a specific phrase will be recognized over other similar sounding phrases. The higher the boost, the higher the chance of false positive recognition as well. Negative boost values would correspond to anti-biasing. Anti-biasing is not enabled, so negative boost will simply be ignored. Though `boost` can accept a wide range of positive values, most use cases are best served with values between 0 (exclusive) and 20. We recommend using a binary search approach to finding the optimal value for your use case. Speech recognition will skip PhraseSets with a boost value of 0. Boost pulumi.Float64Output `pulumi:"boost"` // The resource name of the phrase set. Name pulumi.StringOutput `pulumi:"name"` // A list of word and phrases. Phrases PhraseResponseArrayOutput `pulumi:"phrases"` } // NewPhraseSet registers a new resource with the given unique name, arguments, and options. func NewPhraseSet(ctx *pulumi.Context, name string, args *PhraseSetArgs, opts ...pulumi.ResourceOption) (*PhraseSet, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.PhraseSetId == nil { return nil, errors.New("invalid value for required argument 'PhraseSetId'") } var resource PhraseSet err := ctx.RegisterResource("google-native:speech/v1:PhraseSet", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetPhraseSet gets an existing PhraseSet 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 GetPhraseSet(ctx *pulumi.Context, name string, id pulumi.IDInput, state *PhraseSetState, opts ...pulumi.ResourceOption) (*PhraseSet, error) { var resource PhraseSet err := ctx.ReadResource("google-native:speech/v1:PhraseSet", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering PhraseSet resources. type phraseSetState struct { } type PhraseSetState struct { } func (PhraseSetState) ElementType() reflect.Type { return reflect.TypeOf((*phraseSetState)(nil)).Elem() } type phraseSetArgs struct { // Hint Boost. Positive value will increase the probability that a specific phrase will be recognized over other similar sounding phrases. The higher the boost, the higher the chance of false positive recognition as well. Negative boost values would correspond to anti-biasing. Anti-biasing is not enabled, so negative boost will simply be ignored. Though `boost` can accept a wide range of positive values, most use cases are best served with values between 0 (exclusive) and 20. We recommend using a binary search approach to finding the optimal value for your use case. Speech recognition will skip PhraseSets with a boost value of 0. Boost *float64 `pulumi:"boost"` Location *string `pulumi:"location"` // The resource name of the phrase set. Name *string `pulumi:"name"` // The ID to use for the phrase set, which will become the final component of the phrase set's resource name. This value should be 4-63 characters, and valid characters are /a-z-/. PhraseSetId string `pulumi:"phraseSetId"` // A list of word and phrases. Phrases []Phrase `pulumi:"phrases"` Project *string `pulumi:"project"` } // The set of arguments for constructing a PhraseSet resource. type PhraseSetArgs struct { // Hint Boost. Positive value will increase the probability that a specific phrase will be recognized over other similar sounding phrases. The higher the boost, the higher the chance of false positive recognition as well. Negative boost values would correspond to anti-biasing. Anti-biasing is not enabled, so negative boost will simply be ignored. Though `boost` can accept a wide range of positive values, most use cases are best served with values between 0 (exclusive) and 20. We recommend using a binary search approach to finding the optimal value for your use case. Speech recognition will skip PhraseSets with a boost value of 0. Boost pulumi.Float64PtrInput Location pulumi.StringPtrInput // The resource name of the phrase set. Name pulumi.StringPtrInput // The ID to use for the phrase set, which will become the final component of the phrase set's resource name. This value should be 4-63 characters, and valid characters are /a-z-/. PhraseSetId pulumi.StringInput // A list of word and phrases. Phrases PhraseArrayInput Project pulumi.StringPtrInput } func (PhraseSetArgs) ElementType() reflect.Type { return reflect.TypeOf((*phraseSetArgs)(nil)).Elem() } type PhraseSetInput interface { pulumi.Input ToPhraseSetOutput() PhraseSetOutput ToPhraseSetOutputWithContext(ctx context.Context) PhraseSetOutput } func (*PhraseSet) ElementType() reflect.Type { return reflect.TypeOf((**PhraseSet)(nil)).Elem() } func (i *PhraseSet) ToPhraseSetOutput() PhraseSetOutput { return i.ToPhraseSetOutputWithContext(context.Background()) } func (i *PhraseSet) ToPhraseSetOutputWithContext(ctx context.Context) PhraseSetOutput { return pulumi.ToOutputWithContext(ctx, i).(PhraseSetOutput) } type PhraseSetOutput struct{ *pulumi.OutputState } func (PhraseSetOutput) ElementType() reflect.Type { return reflect.TypeOf((**PhraseSet)(nil)).Elem() } func (o PhraseSetOutput) ToPhraseSetOutput() PhraseSetOutput { return o } func (o PhraseSetOutput) ToPhraseSetOutputWithContext(ctx context.Context) PhraseSetOutput { return o } func init() { pulumi.RegisterInputType(reflect.TypeOf((*PhraseSetInput)(nil)).Elem(), &PhraseSet{}) pulumi.RegisterOutputType(PhraseSetOutput{}) }
sdk/go/google/speech/v1/phraseSet.go
0.779825
0.42662
phraseSet.go
starcoder
Package goutils provides utility functions to manipulate strings in various ways. The code snippets below show examples of how to use goutils. Some functions return errors while others do not, so usage would vary as a result. Example: package main import ( "fmt" "github.com/aokoli/goutils" ) func main() { // EXAMPLE 1: A goutils function which returns no errors fmt.Println (goutils.Initials("<NAME>")) // Prints out "JDF" // EXAMPLE 2: A goutils function which returns an error rand1, err1 := goutils.Random (-1, 0, 0, true, true) if err1 != nil { fmt.Println(err1) // Prints out error message because -1 was entered as the first parameter in goutils.Random(...) } else { fmt.Println(rand1) } } */ package goutils import ( "bytes" "strings" "unicode" ) // VERSION indicates the current version of goutils const VERSION = "1.0.0" /* Wrap wraps a single line of text, identifying words by ' '. New lines will be separated by '\n'. Very long words, such as URLs will not be wrapped. Leading spaces on a new line are stripped. Trailing spaces are not stripped. Parameters: str - the string to be word wrapped wrapLength - the column (a column can fit only one character) to wrap the words at, less than 1 is treated as 1 Returns: a line with newlines inserted */ func Wrap(str string, wrapLength int) string { return WrapCustom(str, wrapLength, "", false) } /* WrapCustom wraps a single line of text, identifying words by ' '. Leading spaces on a new line are stripped. Trailing spaces are not stripped. Parameters: str - the string to be word wrapped wrapLength - the column number (a column can fit only one character) to wrap the words at, less than 1 is treated as 1 newLineStr - the string to insert for a new line, "" uses '\n' wrapLongWords - true if long words (such as URLs) should be wrapped Returns: a line with newlines inserted */ func WrapCustom(str string, wrapLength int, newLineStr string, wrapLongWords bool) string { if str == "" { return "" } if newLineStr == "" { newLineStr = "\n" // TODO Assumes "\n" is seperator. Explore SystemUtils.LINE_SEPARATOR from Apache Commons } if wrapLength < 1 { wrapLength = 1 } inputLineLength := len(str) offset := 0 var wrappedLine bytes.Buffer for inputLineLength-offset > wrapLength { if rune(str[offset]) == ' ' { offset++ continue } end := wrapLength + offset + 1 spaceToWrapAt := strings.LastIndex(str[offset:end], " ") + offset if spaceToWrapAt >= offset { // normal word (not longer than wrapLength) wrappedLine.WriteString(str[offset:spaceToWrapAt]) wrappedLine.WriteString(newLineStr) offset = spaceToWrapAt + 1 } else { // long word or URL if wrapLongWords { end := wrapLength + offset // long words are wrapped one line at a time wrappedLine.WriteString(str[offset:end]) wrappedLine.WriteString(newLineStr) offset += wrapLength } else { // long words aren't wrapped, just extended beyond limit end := wrapLength + offset index := strings.IndexRune(str[end:len(str)], ' ') if index == -1 { wrappedLine.WriteString(str[offset:len(str)]) offset = inputLineLength } else { spaceToWrapAt = index + end wrappedLine.WriteString(str[offset:spaceToWrapAt]) wrappedLine.WriteString(newLineStr) offset = spaceToWrapAt + 1 } } } } wrappedLine.WriteString(str[offset:len(str)]) return wrappedLine.String() } /* Capitalize capitalizes all the delimiter separated words in a string. Only the first letter of each word is changed. To convert the rest of each word to lowercase at the same time, use CapitalizeFully(str string, delimiters ...rune). The delimiters represent a set of characters understood to separate words. The first string character and the first non-delimiter character after a delimiter will be capitalized. A "" input string returns "". Capitalization uses the Unicode title case, normally equivalent to upper case. Parameters: str - the string to capitalize delimiters - set of characters to determine capitalization, exclusion of this parameter means whitespace would be delimeter Returns: capitalized string */ func Capitalize(str string, delimiters ...rune) string { var delimLen int if delimiters == nil { delimLen = -1 } else { delimLen = len(delimiters) } if str == "" || delimLen == 0 { return str } buffer := []rune(str) capitalizeNext := true for i := 0; i < len(buffer); i++ { ch := buffer[i] if isDelimiter(ch, delimiters...) { capitalizeNext = true } else if capitalizeNext { buffer[i] = unicode.ToTitle(ch) capitalizeNext = false } } return string(buffer) } /* CapitalizeFully converts all the delimiter separated words in a string into capitalized words, that is each word is made up of a titlecase character and then a series of lowercase characters. The delimiters represent a set of characters understood to separate words. The first string character and the first non-delimiter character after a delimiter will be capitalized. Capitalization uses the Unicode title case, normally equivalent to upper case. Parameters: str - the string to capitalize fully delimiters - set of characters to determine capitalization, exclusion of this parameter means whitespace would be delimeter Returns: capitalized string */ func CapitalizeFully(str string, delimiters ...rune) string { var delimLen int if delimiters == nil { delimLen = -1 } else { delimLen = len(delimiters) } if str == "" || delimLen == 0 { return str } str = strings.ToLower(str) return Capitalize(str, delimiters...) } /* Uncapitalize uncapitalizes all the whitespace separated words in a string. Only the first letter of each word is changed. The delimiters represent a set of characters understood to separate words. The first string character and the first non-delimiter character after a delimiter will be uncapitalized. Whitespace is defined by unicode.IsSpace(char). Parameters: str - the string to uncapitalize fully delimiters - set of characters to determine capitalization, exclusion of this parameter means whitespace would be delimeter Returns: uncapitalized string */ func Uncapitalize(str string, delimiters ...rune) string { var delimLen int if delimiters == nil { delimLen = -1 } else { delimLen = len(delimiters) } if str == "" || delimLen == 0 { return str } buffer := []rune(str) uncapitalizeNext := true // TODO Always makes capitalize/un apply to first char. for i := 0; i < len(buffer); i++ { ch := buffer[i] if isDelimiter(ch, delimiters...) { uncapitalizeNext = true } else if uncapitalizeNext { buffer[i] = unicode.ToLower(ch) uncapitalizeNext = false } } return string(buffer) } /* SwapCase swaps the case of a string using a word based algorithm. Conversion algorithm: Upper case character converts to Lower case Title case character converts to Lower case Lower case character after Whitespace or at start converts to Title case Other Lower case character converts to Upper case Whitespace is defined by unicode.IsSpace(char). Parameters: str - the string to swap case Returns: the changed string */ func SwapCase(str string) string { if str == "" { return str } buffer := []rune(str) whitespace := true for i := 0; i < len(buffer); i++ { ch := buffer[i] if unicode.IsUpper(ch) { buffer[i] = unicode.ToLower(ch) whitespace = false } else if unicode.IsTitle(ch) { buffer[i] = unicode.ToLower(ch) whitespace = false } else if unicode.IsLower(ch) { if whitespace { buffer[i] = unicode.ToTitle(ch) whitespace = false } else { buffer[i] = unicode.ToUpper(ch) } } else { whitespace = unicode.IsSpace(ch) } } return string(buffer) } /* Initials extracts the initial letters from each word in the string. The first letter of the string and all first letters after the defined delimiters are returned as a new string. Their case is not changed. If the delimiters parameter is excluded, then Whitespace is used. Whitespace is defined by unicode.IsSpacea(char). An empty delimiter array returns an empty string. Parameters: str - the string to get initials from delimiters - set of characters to determine words, exclusion of this parameter means whitespace would be delimeter Returns: string of initial letters */ func Initials(str string, delimiters ...rune) string { if str == "" { return str } if delimiters != nil && len(delimiters) == 0 { return "" } strLen := len(str) var buf bytes.Buffer lastWasGap := true for i := 0; i < strLen; i++ { ch := rune(str[i]) if isDelimiter(ch, delimiters...) { lastWasGap = true } else if lastWasGap { buf.WriteRune(ch) lastWasGap = false } } return buf.String() } // private function (lower case func name) func isDelimiter(ch rune, delimiters ...rune) bool { if delimiters == nil { return unicode.IsSpace(ch) } for _, delimiter := range delimiters { if ch == delimiter { return true } } return false }
vendor/github.com/Masterminds/goutils/wordutils.go
0.644225
0.514217
wordutils.go
starcoder
package iocap import ( "io" "time" ) const ( _ = (1 << (10 * iota)) / 8 Kb // Kilobit Mb // Megabit Gb // Gigabit ) var ( // The zero-value of RateOpts is used to indicate that no rate limit // should be applied to read/write operations. Unlimited = RateOpts{0, 0} ) // Reader implements the io.Reader interface and limits the rate at which // bytes come off of the underlying source reader. type Reader struct { src io.Reader bucket *bucket } // NewReader wraps src in a new rate limited reader. func NewReader(src io.Reader, opts RateOpts) *Reader { return &Reader{ src: src, bucket: newBucket(opts), } } // Read reads bytes off of the underlying source reader onto p with rate // limiting. Reads until EOF or until p is filled. func (r *Reader) Read(p []byte) (n int, err error) { for n < len(p) { // Ask for enough space to fit all remaining bytes v := r.bucket.insert(len(p) - n) // Read from src into the byte range in p v, err = r.src.Read(p[n : n+v]) // Count the actual number of bytes read. n += v // Return any errors from the underlying reader. Preserves the // underlying implementation's functionality. if err != nil { return } } return } // SetRate is used to dynamically set the rate options on the reader. func (r *Reader) SetRate(opts RateOpts) { r.bucket.setRate(opts) } // Writer implements the io.Writer interface and limits the rate at which // bytes are written to the underlying writer. type Writer struct { dst io.Writer bucket *bucket } // NewWriter wraps dst in a new rate limited writer. func NewWriter(dst io.Writer, opts RateOpts) *Writer { return &Writer{ dst: dst, bucket: newBucket(opts), } } // Write writes len(p) bytes onto the underlying io.Writer, respecting the // configured rate limit options. func (w *Writer) Write(p []byte) (n int, err error) { for n < len(p) { // Ask for enough space to write p completely. v := w.bucket.insert(len(p) - n) // Write from the byte offset on p into the writer. v, err = w.dst.Write(p[n : n+v]) // Count the actual bytes written. n += v // Return any errors from the underlying writer. Preserves the // underlying implementation's functionality. if err != nil { return } } return } // SetRate is used to dynamically set the rate options on the writer. func (w *Writer) SetRate(opts RateOpts) { w.bucket.setRate(opts) } // RateOpts is used to encapsulate rate limiting options. type RateOpts struct { // Interval is the time period of the rate Interval time.Duration // Size is the number of bytes per interval Size int } // perSecond is an internal helper to calculate rates. func perSecond(n, base float64) RateOpts { return RateOpts{ Interval: time.Second, Size: int(n * base), } } // Kbps returns a RateOpts configured for n kilobits per second. func Kbps(n float64) RateOpts { return perSecond(n, Kb) } // Mbps returns a RateOpts configured for n megabits per second. func Mbps(n float64) RateOpts { return perSecond(n, Mb) } // Gbps returns a RateOpts configured for n gigabits per second. func Gbps(n float64) RateOpts { return perSecond(n, Gb) } // Group is used to group multiple readers and/or writers onto the same bucket, // thus enforcing the rate limit across multiple independent processes. type Group struct { bucket *bucket } // NewGroup creates a new rate limiting group with the specific rate. func NewGroup(opts RateOpts) *Group { return &Group{newBucket(opts)} } // SetRate is used to dynamically update the rate options of the group. func (g *Group) SetRate(opts RateOpts) { g.bucket.setRate(opts) } // NewWriter creates and returns a new writer in the group. func (g *Group) NewWriter(dst io.Writer) *Writer { return &Writer{ dst: dst, bucket: g.bucket, } } // NewReader creates and returns a new reader in the group. func (g *Group) NewReader(src io.Reader) *Reader { return &Reader{ src: src, bucket: g.bucket, } }
iocap.go
0.709724
0.414484
iocap.go
starcoder
package grapho import "sort" // uint64Slice attaches the methods of sort.Interface to []uint64, sorting in increasing order. type uint64Slice []uint64 func (p uint64Slice) Len() int { return len(p) } func (p uint64Slice) Less(i, j int) bool { return p[i] < p[j] } func (p uint64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } // Attr is a set of attributes associated to a node/edge. // Keys are strings. Values can be anything. type Attr map[string]interface{} // NewAttr creates an empty set of attributes. func NewAttr() Attr { return make(Attr) } // Edge represents a relationship between two nodes. type Edge struct { Weight int // Edge weight (cost) Attr Attr // Edge attribute set } func NewEdge(weight int, attr Attr) *Edge { if attr == nil { attr = NewAttr() } return &Edge{weight, attr} } // Graph implementation. Each pair of nodes can only // hold one edge between them (no parallel edges). type Graph struct { directed bool // true to represent a Digraph, false for Undirected Graphs nodes map[uint64]Attr // Nodes present in the Graph, with their attributes edges map[uint64]map[uint64]*Edge // Adjacency list of edges, with their attributes } // NewGraph creates an empty Graph. func NewGraph(directed bool) *Graph { return &Graph{ directed: directed, nodes: make(map[uint64]Attr), edges: make(map[uint64]map[uint64]*Edge), } } // Len returns the number of nodes in the Graph func (g *Graph) Len() int { return len(g.nodes) } // IsDirected returns whether the Graph is directed or not. func (g *Graph) IsDirected() bool { return g.directed } // AddNode adds the given node to the Graph. If the node // already exists, it will override its attributes. func (g *Graph) AddNode(node uint64, attr Attr) { if attr == nil { attr = NewAttr() } g.nodes[node] = attr g.edges[node] = make(map[uint64]*Edge) } // DeleteNode removes a node entry from the Graph. // Any edge associated with it will be removed too. func (g *Graph) DeleteNode(node uint64) { // Remove incident edges for k := range g.edges[node] { delete(g.edges[k], node) } delete(g.edges, node) delete(g.nodes, node) } // AddEdge adds an edge (with its attributes) between nodes u and v // If the nodes don't exist, they will be automatically created. // If an u-v edge already existed, its attributes will be overridden. func (g *Graph) AddEdge(u, v uint64, weight int, attr Attr) { // Add nodes if necessary if _, ok := g.nodes[u]; !ok { g.AddNode(u, nil) } if _, ok := g.nodes[v]; !ok { g.AddNode(v, nil) } edge := NewEdge(weight, attr) g.edges[u][v] = edge if !g.directed { g.edges[v][u] = edge } } // DeleteEdge removes the u-v edge, if exists. // If any of the nodes don't exist, nothing happens. func (g *Graph) DeleteEdge(u, v uint64) { if _, ok := g.Node(u); ok { if _, ok := g.Node(v); ok { delete(g.edges[u], v) if !g.directed { delete(g.edges[v], u) } } } } // Nodes returns the list of nodes in the Graph (unsorted). func (g *Graph) Nodes() []uint64 { nodes := make([]uint64, len(g.nodes)) n := 0 for k := range g.nodes { nodes[n] = k n++ } return nodes } // Node returns the attributes associated with a given node, and // a bool flag set to true if the node was found, false otherwise. func (g *Graph) Node(node uint64) (Attr, bool) { attr, ok := g.nodes[node] return attr, ok } // Neighbors returns the list of nodes containing edges between the // given node and them, ordered by ascending node uint64 value // An extra bool flag determines whether the node was found. func (g *Graph) Neighbors(node uint64) ([]uint64, bool) { if edges, ok := g.edges[node]; ok { nodes := make([]uint64, len(edges)) n := 0 for k := range edges { nodes[n] = k n++ } sort.Sort(uint64Slice(nodes)) // order by node uint64 value return nodes, true } return nil, false } // Edge returns the Edge associated with the u-v node pair. // An extra bool flag determines whether the edge was found. // In undirected graphs, the edge u-v is be the same as v-u. func (g *Graph) Edge(u, v uint64) (*Edge, bool) { if _, ok := g.Node(u); ok { if _, ok := g.Node(v); ok { edge, ok := g.edges[u][v] return edge, ok } } return nil, false }
graph.go
0.781997
0.518059
graph.go
starcoder
package utils import ( "image" "image/draw" _ "image/gif" _ "image/jpeg" _ "image/png" "runtime" "sync" ) func Rotate270(i image.Image) image.Image { src := ConvertToRGBA(i) b := src.Bounds() dst := image.NewRGBA(image.Rectangle{ Min: image.Point{ X: b.Min.Y, Y: b.Min.X, }, Max: image.Point{ X: b.Max.Y, Y: b.Max.X, }, }) for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { s := y*src.Stride + x*4 d := (b.Max.X-x-1)*dst.Stride + y*4 copy(dst.Pix[d:d+4], src.Pix[s:s+4]) } } return dst } func Rotate180(i image.Image) image.Image { src := ConvertToRGBA(i) b := src.Bounds() dst := image.NewRGBA(image.Rectangle{ Min: image.Point{ X: b.Min.Y, Y: b.Min.X, }, Max: image.Point{ X: b.Max.Y, Y: b.Max.X, }, }) for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { s := y*src.Stride + x*4 d := (b.Max.X-x-1)*dst.Stride + (b.Max.Y-y-1)*4 copy(dst.Pix[d:d+4], src.Pix[s:s+4]) } } return src } func Rotate90(i image.Image) image.Image { src := ConvertToRGBA(i) b := src.Bounds() dst := image.NewRGBA(image.Rectangle{ Min: image.Point{ X: b.Min.Y, Y: b.Min.X, }, Max: image.Point{ X: b.Max.Y, Y: b.Max.X, }, }) for y := b.Min.Y; y < b.Max.Y; y++ { for x := b.Min.X; x < b.Max.X; x++ { s := y*src.Stride + x*4 d := x*dst.Stride + (b.Max.Y-y-1)*4 copy(dst.Pix[d:d+4], src.Pix[s:s+4]) } } return dst } func ConvertToRGBA(src image.Image) (dst *image.RGBA) { rgba, ok := src.(*image.RGBA) if !ok { rgba = image.NewRGBA(src.Bounds()) draw.Draw(rgba, src.Bounds(), src, src.Bounds().Min, draw.Src) } return rgba } func Line(ls, le int, f func(s, e int)) { p := runtime.GOMAXPROCS(0) ll := le - ls ps := ll / p if p <= 1 || ps <= p { f(0, ll) return } wg := sync.WaitGroup{} pn := ll for pn > 0 { s := ls + pn - ps if s < 0 { s = 0 } e := s + pn if e > le { e = le } pn -= ps wg.Add(1) go func() { defer wg.Done() f(s, e) }() } wg.Wait() }
pkg/utils/utils.go
0.569494
0.453141
utils.go
starcoder
package fp func (l BoolList) GroupByBool(f func(bool) bool) map[bool]BoolList { m := make(map[bool]BoolList) l.Foreach(func(e bool) { key := f(e) var group BoolList if value, found := m[key]; found { group = value } else { group = NilBoolList } group = group.Cons(e) m[key] = group }) return m } func (l StringList) GroupByString(f func(string) string) map[string]StringList { m := make(map[string]StringList) l.Foreach(func(e string) { key := f(e) var group StringList if value, found := m[key]; found { group = value } else { group = NilStringList } group = group.Cons(e) m[key] = group }) return m } func (l IntList) GroupByInt(f func(int) int) map[int]IntList { m := make(map[int]IntList) l.Foreach(func(e int) { key := f(e) var group IntList if value, found := m[key]; found { group = value } else { group = NilIntList } group = group.Cons(e) m[key] = group }) return m } func (l Int64List) GroupByInt64(f func(int64) int64) map[int64]Int64List { m := make(map[int64]Int64List) l.Foreach(func(e int64) { key := f(e) var group Int64List if value, found := m[key]; found { group = value } else { group = NilInt64List } group = group.Cons(e) m[key] = group }) return m } func (l ByteList) GroupByByte(f func(byte) byte) map[byte]ByteList { m := make(map[byte]ByteList) l.Foreach(func(e byte) { key := f(e) var group ByteList if value, found := m[key]; found { group = value } else { group = NilByteList } group = group.Cons(e) m[key] = group }) return m } func (l RuneList) GroupByRune(f func(rune) rune) map[rune]RuneList { m := make(map[rune]RuneList) l.Foreach(func(e rune) { key := f(e) var group RuneList if value, found := m[key]; found { group = value } else { group = NilRuneList } group = group.Cons(e) m[key] = group }) return m } func (l Float32List) GroupByFloat32(f func(float32) float32) map[float32]Float32List { m := make(map[float32]Float32List) l.Foreach(func(e float32) { key := f(e) var group Float32List if value, found := m[key]; found { group = value } else { group = NilFloat32List } group = group.Cons(e) m[key] = group }) return m } func (l Float64List) GroupByFloat64(f func(float64) float64) map[float64]Float64List { m := make(map[float64]Float64List) l.Foreach(func(e float64) { key := f(e) var group Float64List if value, found := m[key]; found { group = value } else { group = NilFloat64List } group = group.Cons(e) m[key] = group }) return m } func (l AnyList) GroupByAny(f func(Any) Any) map[Any]AnyList { m := make(map[Any]AnyList) l.Foreach(func(e Any) { key := f(e) var group AnyList if value, found := m[key]; found { group = value } else { group = NilAnyList } group = group.Cons(e) m[key] = group }) return m } func (l Tuple2List) GroupByTuple2(f func(Tuple2) Tuple2) map[Tuple2]Tuple2List { m := make(map[Tuple2]Tuple2List) l.Foreach(func(e Tuple2) { key := f(e) var group Tuple2List if value, found := m[key]; found { group = value } else { group = NilTuple2List } group = group.Cons(e) m[key] = group }) return m } func (l BoolOptionList) GroupByBoolOption(f func(BoolOption) BoolOption) map[BoolOption]BoolOptionList { m := make(map[BoolOption]BoolOptionList) l.Foreach(func(e BoolOption) { key := f(e) var group BoolOptionList if value, found := m[key]; found { group = value } else { group = NilBoolOptionList } group = group.Cons(e) m[key] = group }) return m } func (l StringOptionList) GroupByStringOption(f func(StringOption) StringOption) map[StringOption]StringOptionList { m := make(map[StringOption]StringOptionList) l.Foreach(func(e StringOption) { key := f(e) var group StringOptionList if value, found := m[key]; found { group = value } else { group = NilStringOptionList } group = group.Cons(e) m[key] = group }) return m } func (l IntOptionList) GroupByIntOption(f func(IntOption) IntOption) map[IntOption]IntOptionList { m := make(map[IntOption]IntOptionList) l.Foreach(func(e IntOption) { key := f(e) var group IntOptionList if value, found := m[key]; found { group = value } else { group = NilIntOptionList } group = group.Cons(e) m[key] = group }) return m } func (l Int64OptionList) GroupByInt64Option(f func(Int64Option) Int64Option) map[Int64Option]Int64OptionList { m := make(map[Int64Option]Int64OptionList) l.Foreach(func(e Int64Option) { key := f(e) var group Int64OptionList if value, found := m[key]; found { group = value } else { group = NilInt64OptionList } group = group.Cons(e) m[key] = group }) return m } func (l ByteOptionList) GroupByByteOption(f func(ByteOption) ByteOption) map[ByteOption]ByteOptionList { m := make(map[ByteOption]ByteOptionList) l.Foreach(func(e ByteOption) { key := f(e) var group ByteOptionList if value, found := m[key]; found { group = value } else { group = NilByteOptionList } group = group.Cons(e) m[key] = group }) return m } func (l RuneOptionList) GroupByRuneOption(f func(RuneOption) RuneOption) map[RuneOption]RuneOptionList { m := make(map[RuneOption]RuneOptionList) l.Foreach(func(e RuneOption) { key := f(e) var group RuneOptionList if value, found := m[key]; found { group = value } else { group = NilRuneOptionList } group = group.Cons(e) m[key] = group }) return m } func (l Float32OptionList) GroupByFloat32Option(f func(Float32Option) Float32Option) map[Float32Option]Float32OptionList { m := make(map[Float32Option]Float32OptionList) l.Foreach(func(e Float32Option) { key := f(e) var group Float32OptionList if value, found := m[key]; found { group = value } else { group = NilFloat32OptionList } group = group.Cons(e) m[key] = group }) return m } func (l Float64OptionList) GroupByFloat64Option(f func(Float64Option) Float64Option) map[Float64Option]Float64OptionList { m := make(map[Float64Option]Float64OptionList) l.Foreach(func(e Float64Option) { key := f(e) var group Float64OptionList if value, found := m[key]; found { group = value } else { group = NilFloat64OptionList } group = group.Cons(e) m[key] = group }) return m } func (l AnyOptionList) GroupByAnyOption(f func(AnyOption) AnyOption) map[AnyOption]AnyOptionList { m := make(map[AnyOption]AnyOptionList) l.Foreach(func(e AnyOption) { key := f(e) var group AnyOptionList if value, found := m[key]; found { group = value } else { group = NilAnyOptionList } group = group.Cons(e) m[key] = group }) return m } func (l Tuple2OptionList) GroupByTuple2Option(f func(Tuple2Option) Tuple2Option) map[Tuple2Option]Tuple2OptionList { m := make(map[Tuple2Option]Tuple2OptionList) l.Foreach(func(e Tuple2Option) { key := f(e) var group Tuple2OptionList if value, found := m[key]; found { group = value } else { group = NilTuple2OptionList } group = group.Cons(e) m[key] = group }) return m } func (l BoolListList) GroupByBoolList(f func(BoolList) BoolList) map[BoolList]BoolListList { m := make(map[BoolList]BoolListList) l.Foreach(func(e BoolList) { key := f(e) var group BoolListList if value, found := m[key]; found { group = value } else { group = NilBoolListList } group = group.Cons(e) m[key] = group }) return m } func (l StringListList) GroupByStringList(f func(StringList) StringList) map[StringList]StringListList { m := make(map[StringList]StringListList) l.Foreach(func(e StringList) { key := f(e) var group StringListList if value, found := m[key]; found { group = value } else { group = NilStringListList } group = group.Cons(e) m[key] = group }) return m } func (l IntListList) GroupByIntList(f func(IntList) IntList) map[IntList]IntListList { m := make(map[IntList]IntListList) l.Foreach(func(e IntList) { key := f(e) var group IntListList if value, found := m[key]; found { group = value } else { group = NilIntListList } group = group.Cons(e) m[key] = group }) return m } func (l Int64ListList) GroupByInt64List(f func(Int64List) Int64List) map[Int64List]Int64ListList { m := make(map[Int64List]Int64ListList) l.Foreach(func(e Int64List) { key := f(e) var group Int64ListList if value, found := m[key]; found { group = value } else { group = NilInt64ListList } group = group.Cons(e) m[key] = group }) return m } func (l ByteListList) GroupByByteList(f func(ByteList) ByteList) map[ByteList]ByteListList { m := make(map[ByteList]ByteListList) l.Foreach(func(e ByteList) { key := f(e) var group ByteListList if value, found := m[key]; found { group = value } else { group = NilByteListList } group = group.Cons(e) m[key] = group }) return m } func (l RuneListList) GroupByRuneList(f func(RuneList) RuneList) map[RuneList]RuneListList { m := make(map[RuneList]RuneListList) l.Foreach(func(e RuneList) { key := f(e) var group RuneListList if value, found := m[key]; found { group = value } else { group = NilRuneListList } group = group.Cons(e) m[key] = group }) return m } func (l Float32ListList) GroupByFloat32List(f func(Float32List) Float32List) map[Float32List]Float32ListList { m := make(map[Float32List]Float32ListList) l.Foreach(func(e Float32List) { key := f(e) var group Float32ListList if value, found := m[key]; found { group = value } else { group = NilFloat32ListList } group = group.Cons(e) m[key] = group }) return m } func (l Float64ListList) GroupByFloat64List(f func(Float64List) Float64List) map[Float64List]Float64ListList { m := make(map[Float64List]Float64ListList) l.Foreach(func(e Float64List) { key := f(e) var group Float64ListList if value, found := m[key]; found { group = value } else { group = NilFloat64ListList } group = group.Cons(e) m[key] = group }) return m } func (l AnyListList) GroupByAnyList(f func(AnyList) AnyList) map[AnyList]AnyListList { m := make(map[AnyList]AnyListList) l.Foreach(func(e AnyList) { key := f(e) var group AnyListList if value, found := m[key]; found { group = value } else { group = NilAnyListList } group = group.Cons(e) m[key] = group }) return m } func (l Tuple2ListList) GroupByTuple2List(f func(Tuple2List) Tuple2List) map[Tuple2List]Tuple2ListList { m := make(map[Tuple2List]Tuple2ListList) l.Foreach(func(e Tuple2List) { key := f(e) var group Tuple2ListList if value, found := m[key]; found { group = value } else { group = NilTuple2ListList } group = group.Cons(e) m[key] = group }) return m }
fp/bootstrap_list_groupby.go
0.575588
0.402568
bootstrap_list_groupby.go
starcoder
package main import ( "bufio" "fmt" "math" "os" ) type position struct { x, y int } func (p *position) dist(to position) int { return int(math.Abs(float64(p.x-to.x)) + math.Abs(float64(p.y-to.y))) } func (p *position) closest(positions []*position) (*position, int, bool) { var closestPosition *position lowestDistance := math.MaxInt32 distances := map[int]int{} for _, pos := range positions { dist := p.dist(*pos) distances[dist]++ if dist < lowestDistance { lowestDistance = dist closestPosition = pos } } return closestPosition, lowestDistance, distances[lowestDistance] > 1 } func main() { file, _ := os.Open("input.txt") fileScanner := bufio.NewScanner(file) defer file.Close() var positions []*position for fileScanner.Scan() { var x, y int fmt.Sscanf(fileScanner.Text(), "%d, %d", &x, &y) positions = append(positions, &position{x: x, y: y}) } minBoundingPosition, maxBoundingPosition := getBoundingPositions(positions) grid := map[position]*position{} area := map[*position][]*position{} for y := minBoundingPosition.y; y <= maxBoundingPosition.y; y++ { for x := minBoundingPosition.x; x <= maxBoundingPosition.x; x++ { pos := &position{x: x, y: y} closestPosition, _, hasTwoOrMoreClosestPositions := pos.closest(positions) if hasTwoOrMoreClosestPositions { continue } area[closestPosition] = append(area[closestPosition], pos) grid[*pos] = closestPosition } } // Loops through border to check infinite areas infiniteAreaPositions := map[*position]bool{} for y := minBoundingPosition.y; y <= maxBoundingPosition.y; y++ { isBetweenTopOrBottom := y > minBoundingPosition.y && y < maxBoundingPosition.y for x := minBoundingPosition.x; x <= maxBoundingPosition.x; x++ { pos := grid[position{x: x, y: y}] if _, exists := infiniteAreaPositions[pos]; pos != nil && !exists { infiniteAreaPositions[pos] = true } if isBetweenTopOrBottom { x += maxBoundingPosition.x - minBoundingPosition.x - 1 continue } } } largestFiniteAreaSize := 0 for pos, areaPositions := range area { if infiniteAreaPositions[pos] { continue } if areaSize := len(areaPositions); areaSize > largestFiniteAreaSize { largestFiniteAreaSize = areaSize } } safeAreaSize := 0 for y := minBoundingPosition.y; y <= maxBoundingPosition.y; y++ { for x := minBoundingPosition.x; x <= maxBoundingPosition.x; x++ { gridPos := &position{x: x, y: y} sumDistance := 0 for _, pos := range positions { sumDistance += gridPos.dist(*pos) } if sumDistance < 10000 { safeAreaSize++ } } } fmt.Println("Part 1: ", largestFiniteAreaSize) fmt.Println("Part 2: ", safeAreaSize) } func getBoundingPositions(positions []*position) (position, position) { minBoundingPosition := position{math.MaxInt32, math.MaxInt32} maxBoundingPosition := position{0, 0} for _, pos := range positions { if pos.x > maxBoundingPosition.x { maxBoundingPosition.x = pos.x } if pos.y > maxBoundingPosition.y { maxBoundingPosition.y = pos.y } if pos.x < minBoundingPosition.x { minBoundingPosition.x = pos.x } if pos.y < minBoundingPosition.y { minBoundingPosition.y = pos.y } } return minBoundingPosition, maxBoundingPosition }
2018/06/main.go
0.666171
0.5
main.go
starcoder
package physics import ( "github.com/roeldev/go-sdl2-experiments/pkg/sdlkit/geom" ) type HitTester interface { // HitTest returns true when the x and y values are within the HitTester. HitTest(x, y float64) bool HitTestXY(xy geom.XYGetter) bool } func HitTestCircle(x, y float64, circle geom.Circle) bool { dx, dy := circle.X-x, circle.Y-y return ((dx * dx) + (dy * dy)) < (circle.Radius * circle.Radius) } // HitTest returns true when position [x y] is inside the Circle. It calculates // the squared distance between [x y] and the Circle's center X Y and compares // this with the squared Radius. func (cc *CircleCollider) HitTest(x, y float64) bool { dx, dy := cc.shape.X-x, cc.shape.Y-y return ((dx * dx) + (dy * dy)) < (cc.shape.Radius * cc.shape.Radius) } func HitTestEllipse(x, y float64, ellipse geom.Ellipse) bool { return ((x-ellipse.X)*(x-ellipse.X)/(ellipse.RadiusX*ellipse.RadiusX))+ ((y-ellipse.Y)*(y-ellipse.Y)/(ellipse.RadiusY*ellipse.RadiusY)) <= 1 } // HitTest returns true when position [x y] is inside the EllipseCollider's // geom.Ellipse shape. // https://math.stackexchange.com/questions/76457/check-if-a-point-is-within-an-ellipse func (ec *EllipseCollider) HitTest(x, y float64) bool { return ((x-ec.shape.X)*(x-ec.shape.X)/(ec.shape.RadiusX*ec.shape.RadiusX))+ ((y-ec.shape.Y)*(y-ec.shape.Y)/(ec.shape.RadiusY*ec.shape.RadiusY)) <= 1 } func HitTestRect(x, y float64, rect geom.Rect) bool { w, h := rect.W/2, rect.H/2 return (x >= rect.X-w) && (x < rect.X+w) && (y >= rect.Y-h) && (y < rect.Y+h) } // HitTest returns true when the x and y values are within the Rect. func (rc *RectCollider) HitTest(x, y float64) bool { w, h := rc.shape.W/2, rc.shape.H/2 return (x >= rc.shape.X-w) && (x < rc.shape.X+w) && (y >= rc.shape.Y-h) && (y < rc.shape.Y+h) } // // https://wrf.ecse.rpi.edu/Research/Short_Notes/pnpoly.html func HitTestPolygon(x, y float64, vertices []geom.Point) (hit bool) { n := len(vertices) for i, j := 0, n-1; i < n; i++ { u, v := vertices[i], vertices[j] if ((u.Y > y) != (v.Y > y)) && (x < ((v.X-u.X)*(y-u.Y))/(v.Y-u.Y)+u.X) { hit = !hit } j = i } return hit }
pkg/sdlkit/physics/hittest.go
0.849722
0.553686
hittest.go
starcoder
package runtime import ( "fmt" "sort" "github.com/onflow/cadence" "github.com/onflow/cadence/runtime/common" "github.com/onflow/cadence/runtime/sema" ) // exportType converts a runtime type to its corresponding Go representation. func exportType(typ sema.Type) cadence.Type { switch t := typ.(type) { case *sema.AnyStructType: return cadence.AnyStructType{} case *sema.VoidType: return cadence.VoidType{} case *sema.OptionalType: return exportOptionalType(t) case *sema.BoolType: return cadence.BoolType{} case *sema.StringType: return cadence.StringType{} case *sema.IntType: return cadence.IntType{} case *sema.Int8Type: return cadence.Int8Type{} case *sema.Int16Type: return cadence.Int16Type{} case *sema.Int32Type: return cadence.Int32Type{} case *sema.Int64Type: return cadence.Int64Type{} case *sema.Int128Type: return cadence.Int128Type{} case *sema.Int256Type: return cadence.Int256Type{} case *sema.UIntType: return cadence.UIntType{} case *sema.UInt8Type: return cadence.UInt8Type{} case *sema.UInt16Type: return cadence.UInt16Type{} case *sema.UInt32Type: return cadence.UInt32Type{} case *sema.UInt64Type: return cadence.UInt64Type{} case *sema.UInt128Type: return cadence.UInt128Type{} case *sema.UInt256Type: return cadence.UInt256Type{} case *sema.Word8Type: return cadence.Word8Type{} case *sema.Word16Type: return cadence.Word16Type{} case *sema.Word32Type: return cadence.Word32Type{} case *sema.Word64Type: return cadence.Word64Type{} case *sema.Fix64Type: return cadence.Fix64Type{} case *sema.UFix64Type: return cadence.UFix64Type{} case *sema.VariableSizedType: return exportVariableSizedType(t) case *sema.ConstantSizedType: return exportConstantSizedType(t) case *sema.CompositeType: return exportCompositeType(t) case *sema.DictionaryType: return exportDictionaryType(t) case *sema.FunctionType: return exportFunctionType(t) case *sema.AddressType: return cadence.AddressType{} } panic(fmt.Sprintf("cannot convert type of type %T", typ)) } func exportOptionalType(t *sema.OptionalType) cadence.Type { convertedType := exportType(t.Type) return cadence.OptionalType{Type: convertedType} } func exportVariableSizedType(t *sema.VariableSizedType) cadence.Type { convertedElement := exportType(t.Type) return cadence.VariableSizedArrayType{ElementType: convertedElement} } func exportConstantSizedType(t *sema.ConstantSizedType) cadence.Type { convertedElement := exportType(t.Type) return cadence.ConstantSizedArrayType{ Size: uint(t.Size), ElementType: convertedElement, } } func exportCompositeType(t *sema.CompositeType) cadence.Type { fields := make([]cadence.Field, 0, len(t.Members)) // TODO: do not sort fields before export, store in order declared fieldNames := make([]string, 0, len(t.Members)) for identifier, member := range t.Members { if member.IgnoreInSerialization { continue } fieldNames = append(fieldNames, identifier) } // sort field names in lexicographical order sort.Strings(fieldNames) for _, identifier := range fieldNames { field := t.Members[identifier] convertedFieldType := exportType(field.TypeAnnotation.Type) fields = append(fields, cadence.Field{ Identifier: identifier, Type: convertedFieldType, }) } id := string(t.ID()) switch t.Kind { case common.CompositeKindStructure: return cadence.StructType{ TypeID: id, Identifier: t.Identifier, Fields: fields, } case common.CompositeKindResource: return cadence.ResourceType{ TypeID: id, Identifier: t.Identifier, Fields: fields, } case common.CompositeKindEvent: return cadence.EventType{ TypeID: id, Identifier: t.Identifier, Fields: fields, } } panic(fmt.Sprintf("cannot convert type %v of unknown kind %v", t, t.Kind)) } func exportDictionaryType(t *sema.DictionaryType) cadence.Type { convertedKeyType := exportType(t.KeyType) convertedElementType := exportType(t.ValueType) return cadence.DictionaryType{ KeyType: convertedKeyType, ElementType: convertedElementType, } } func exportFunctionType(t *sema.FunctionType) cadence.Type { convertedReturnType := exportType(t.ReturnTypeAnnotation.Type) parameters := make([]cadence.Parameter, len(t.Parameters)) for i, parameter := range t.Parameters { convertedParameterType := exportType(parameter.TypeAnnotation.Type) parameters[i] = cadence.Parameter{ Label: parameter.Label, Identifier: parameter.Identifier, Type: convertedParameterType, } } return cadence.Function{ Parameters: parameters, ReturnType: convertedReturnType, }.WithID(string(t.ID())) }
runtime/convertTypes.go
0.587588
0.413063
convertTypes.go
starcoder
package sun import ( "errors" "math" "time" ) // Error values if sun not rises or sets at speciefied date and location var ( ErrNoRise = errors.New("the sun never rises on this location (on the specified date)") ErrNoSet = errors.New("the sun never sets on this location (on the specified date)") ) func rad(deg float64) float64 { return deg * math.Pi / 180.0 } func deg(rad float64) float64 { return rad * 180.0 / math.Pi } func calc(t time.Time, lat, lon, zen float64, rising bool) (time.Time, error) { // 1. first calculate the day of the year N := float64(t.YearDay()) // 2. convert the longitude to hour value and calculate an approximate time if rising { N += (6.0 - lon/15.0) / 24.0 } else { N += (18.0 - lon/15.0) / 24.0 } // 3. calculate the Sun's mean anomaly M := 0.9856*N - 3.289 // 4. calculate the Sun's true longitude L := M + 1.916*math.Sin(rad(M)) + 0.020*math.Sin(2*rad(M)) + 282.634 // 5a. calculate the Sun's right ascension RA := deg(math.Atan(0.91764 * math.Tan(rad(L)))) // 5b. right ascension value needs to be in the same quadrant as L RA += math.Floor(L/90.0)*90.0 - math.Floor(RA/90.0)*90.0 // 5c. right ascension value needs to be converted into hours RA /= 15.0 // 6. calculate the Sun's declination sinDec := 0.39782 * math.Sin(rad(L)) cosDec := math.Cos(math.Asin(sinDec)) // 7a. calculate the Sun's local hour angle cosH := (math.Cos(rad(zen)) - sinDec*math.Sin(rad(lat))) / (cosDec * math.Cos(rad(lat))) switch { case cosH > 1.0: return time.Time{}, ErrNoRise case cosH < -1.0: return time.Time{}, ErrNoSet } // 7b. finish calculating H and convert into hours H := deg(math.Acos(cosH)) / 15.0 if rising { H = -H } // 8. calculate local mean time of rising/setting T := math.Mod(H+RA-0.06571*N-6.622, 24.0) // 9. adjust back to UTC UT := (T - lon/15.0) * float64(time.Hour) // 10. convert UT value to local time zone of latitude/longitude return t.Truncate(24 * time.Hour).Add(time.Duration(UT)), nil } // Zenith for sunrise/sunset (degree) type Zenith float64 // Sun's zenith for sunrise/sunset const ( Official Zenith = 90.0 + 50.0/60.0 Civil Zenith = 96.0 Nautical Zenith = 102.0 Astronomical Zenith = 108.0 ) // Rise returns a sunrise time at given time and location on given zenith func (z Zenith) Rise(t time.Time, lat, lon float64) (time.Time, error) { return calc(t, lat, lon, float64(z), true) } // Set returns a sunset time at given time and location on given zenith func (z Zenith) Set(t time.Time, lat, lon float64) (time.Time, error) { return calc(t, lat, lon, float64(z), false) } // Day duration at given time and location on given zenith func (z Zenith) Day(t time.Time, lat, lon float64) time.Duration { rise, err := z.Rise(t, lat, lon) if err == ErrNoRise { return 0 } set, err := z.Set(t, lat, lon) if err == ErrNoSet { return time.Hour * 24 } return set.Sub(rise) } // Rise returns a sunrise time at given time and location on official zenith func Rise(t time.Time, lat, lon float64) (time.Time, error) { return Official.Rise(t, lat, lon) } // Set returns a sunset time at given time and location on official zenith func Set(t time.Time, lat, lon float64) (time.Time, error) { return Official.Set(t, lat, lon) } // Day duration at given time and location on official zenith func Day(t time.Time, lat, lon float64) time.Duration { return Official.Day(t, lat, lon) }
sun.go
0.792304
0.508727
sun.go
starcoder
package main import ( "time" ) func BeginningOfYear(t time.Time) time.Time { return time.Date(t.Year(), 1, 1, 0, 0, 0, 0, t.Location()) } func EndOfYear(t time.Time) time.Time { return BeginningOfYear(t).AddDate(1, 0, 0).AddDate(0, 0, -1) } func BeginningOfMonth(t time.Time) time.Time { return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location()) } func EndOfMonth(t time.Time) time.Time { return BeginningOfMonth(t).AddDate(0, 1, 0).AddDate(0, 0, -1) } func BeginningOfDay(t time.Time) time.Time { return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()) } func NextDayOfWeek(t time.Time, w time.Weekday) time.Time { diff := w - t.Weekday() if diff < 0 { diff = diff + 7 } return BeginningOfDay(t.AddDate(0, 0, int(diff))) } func PreviousDayOfWeek(t time.Time, w time.Weekday) time.Time { diff := w - t.Weekday() if diff > 0 { diff = diff - 7 } return BeginningOfDay(t.AddDate(0, 0, int(diff))) } func NextMonth(t time.Time) time.Time { return t.AddDate(0, 1, 0) } func PreviousMonth(t time.Time) time.Time { return t.AddDate(0, -1, 0) } func NextDay(t time.Time) time.Time { return t.AddDate(0, 0, 1) } func PreviousDay(t time.Time) time.Time { return t.AddDate(0, 0, -1) } func NextWeek(t time.Time) time.Time { return t.AddDate(0, 0, 7) } func PreviousWeek(t time.Time) time.Time { return t.AddDate(0, 0, -7) } func NextMonthOfYear(t time.Time, m time.Month) time.Time { diff := m - t.Month() if diff < 0 { diff = diff + 12 } return BeginningOfMonth(t.AddDate(0, int(diff), 0)) } func PreviousMonthOfYear(t time.Time, m time.Month) time.Time { diff := m - t.Month() if diff > 0 { diff = diff - 12 } return BeginningOfMonth(t.AddDate(0, int(diff), 0)) } func NextYear(t time.Time) time.Time { return t.AddDate(1, 0, 0) } func PreviousYear(t time.Time) time.Time { return t.AddDate(-1, 0, 0) } func YearsSince(t time.Time, years int) time.Time { return t.AddDate(years, 0, 0) } func YearsAgo(t time.Time, years int) time.Time { return t.AddDate(-years, 0, 0) } func WeeksSince(t time.Time, weeks int) time.Time { return t.AddDate(0, 0, 7*weeks) } func WeeksAgo(t time.Time, weeks int) time.Time { return t.AddDate(0, 0, -7*weeks) }
carbon.go
0.73848
0.691317
carbon.go
starcoder
// go build // ./exercise1 // Sample program to show how to cache data from an API, and then // use that data in analyzing a dataset. package main import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "time" cache "github.com/patrickmn/go-cache" ) const ( // statusURL provides an explanation of Citibike station statuses. statusURL = "https://feeds.citibikenyc.com/stations/status.json" // currentStatusURL provides the current Citibike station statuses. currentStatusURL = "https://feeds.citibikenyc.com/stations/stations.json" ) // stationData is used to unmarshal the JSON document returned form citiBikeURL. type stationData struct { ExecutionTime string `json:"executionTime"` StationBeanList []station `json:"stationBeanList"` } // station is used to unmarshal each of the station documents in stationData. type station struct { ID int `json:"id"` StationName string `json:"stationName"` StatusKey int `json:"statusKey"` } func main() { // Get the JSON status codes from the statusURL. response, err := http.Get(statusURL) if err != nil { log.Fatal(err) } // Read the body of the response into []byte. body, err := ioutil.ReadAll(response.Body) if err != nil { log.Fatal(err) } // Unmarshal the JSON data into a map. Here the keys are the // status codes and the values are the meanings of the codes. var statuses map[string]string if err := json.Unmarshal(body, &statuses); err != nil { log.Fatal(err) return } // Create a cache with a default expiration time of 5 minutes, and which // purges expired items every 30 seconds c := cache.New(5*time.Minute, 30*time.Second) // Put the status codes and meanings into the cache. for k, v := range statuses { c.Set(k, v, cache.DefaultExpiration) } // Get the current CitiBike station statuses. response, err = http.Get(currentStatusURL) if err != nil { log.Fatal(err) } // Read the body of the response into []byte. body, err = ioutil.ReadAll(response.Body) if err != nil { log.Fatal(err) } // Declare a variable of type stationData. var sd stationData // Unmarshal the JSON data into the variable. if err := json.Unmarshal(body, &sd); err != nil { log.Fatal(err) return } // Determine which stations are not in service. for _, station := range sd.StationBeanList { // Get the respective code from the Cache. v, found := c.Get(string(station.StatusKey)) if found && v == "Not In Service" { fmt.Printf("%s station not in service\n", station.StationName) } } }
topics/data_science/caching/exercises/exercise1/exercise1.go
0.569972
0.403361
exercise1.go
starcoder
package world import ( "github.com/df-mc/dragonfly/server/block/cube" "time" ) var ( // Overworld is the Dimension implementation of a normal overworld. It has a blue sky under normal circumstances and // has a sun, clouds, stars and a moon. Overworld has a building range of [-64, 320]. Overworld overworld // Nether is a Dimension implementation with a lower base light level and a darker sky without sun/moon. It has a // building range of [0, 256]. Nether nether // End is a Dimension implementation with a dark sky. It has a building range of [0, 256]. End end ) type ( // Dimension is a dimension of a World. It influences a variety of properties of a World such as the building range, // the sky colour and the behaviour of liquid blocks. Dimension interface { Range() cube.Range EncodeDimension() int WaterEvaporates() bool LavaSpreadDuration() time.Duration WeatherCycle() bool TimeCycle() bool } overworld struct{} nether struct{} end struct{} ) func (overworld) Range() cube.Range { return cube.Range{-64, 320} } func (overworld) EncodeDimension() int { return 0 } func (overworld) WaterEvaporates() bool { return false } func (overworld) LavaSpreadDuration() time.Duration { return time.Second * 3 / 2 } func (overworld) WeatherCycle() bool { return true } func (overworld) TimeCycle() bool { return true } func (overworld) String() string { return "Overworld" } func (nether) Range() cube.Range { return cube.Range{0, 256} } func (nether) EncodeDimension() int { return 1 } func (nether) WaterEvaporates() bool { return true } func (nether) LavaSpreadDuration() time.Duration { return time.Second / 4 } func (nether) WeatherCycle() bool { return false } func (nether) TimeCycle() bool { return false } func (nether) String() string { return "Nether" } func (end) Range() cube.Range { return cube.Range{0, 256} } func (end) EncodeDimension() int { return 2 } func (end) WaterEvaporates() bool { return false } func (end) LavaSpreadDuration() time.Duration { return time.Second * 3 / 2 } func (end) WeatherCycle() bool { return false } func (end) TimeCycle() bool { return false } func (end) String() string { return "End" }
server/world/dimension.go
0.700178
0.569494
dimension.go
starcoder
&compiler.Module{ Pos: Position{Filename: "", Offset: 0, Line: 1, Column: 1}, Name: "main", Enums: []*compiler.Enum{ &compiler.Enum{ Pos: Position{Filename: "", Offset: 13, Line: 3, Column: 1}, Name: "Direction", Value: []string{ "Left", "Right", }, }, &compiler.Enum{ Pos: Position{Filename: "", Offset: 48, Line: 8, Column: 1}, Name: "Position", Value: []string{ "Top", "Bottom", }, }, }, Types: []*compiler.Type{ &compiler.Type{ Pos: Position{Filename: "", Offset: 82, Line: 13, Column: 1}, Name: "User", Fields: []compiler.TypeField{ compiler.TypeField{ Pos: Position{Filename: "", Offset: 96, Line: 14, Column: 3}, Name: "name", Value: "string", }, compiler.TypeField{ Pos: Position{Filename: "", Offset: 110, Line: 15, Column: 3}, Name: "age", Value: "string", }, compiler.TypeField{ Pos: Position{Filename: "", Offset: 123, Line: 16, Column: 3}, Name: "gender", Value: "string", }, compiler.TypeField{ Pos: Position{Filename: "", Offset: 139, Line: 17, Column: 3}, Name: "address", Value: "string", }, compiler.TypeField{ Pos: Position{Filename: "", Offset: 156, Line: 18, Column: 3}, Name: "createdAt", Value: "string", }, compiler.TypeField{ Pos: Position{Filename: "", Offset: 175, Line: 19, Column: 3}, Name: "updatedAt", Value: "string", }, compiler.TypeField{ Pos: Position{Filename: "", Offset: 194, Line: 20, Column: 3}, Name: "deletedAt", Value: "string", }, }, }, }, Functions: []*compiler.Function{ &compiler.Function{ Pos: Position{Filename: "", Offset: 214, Line: 23, Column: 1}, Type: "method", Name: "fullName", Parameters: []compiler.TypeField{ compiler.TypeField{ Pos: Position{Filename: "", Offset: 230, Line: 23, Column: 17}, Name: "u", Value: "User", }, }, ReturnType: &compiler.ReturnType{ Pos: Position{Filename: "", Offset: 239, Line: 23, Column: 26}, Name: "string", }, Statements: []*compiler.Statement{ &compiler.Statement{ Pos: Position{Filename: "", Offset: 251, Line: 24, Column: 3}, Assignment: &compiler.AssignmentStatement{ Pos: Position{Filename: "", Offset: 251, Line: 24, Column: 3}, Name: "name", Expression: u.name map := return u.name + " " + u.age, }, }, }, }, &compiler.Function{ Pos: Position{Filename: "", Offset: 392, Line: 35, Column: 1}, Type: "proc", Name: "Counter", Parameters: []compiler.TypeField{ compiler.TypeField{ Pos: Position{Filename: "", Offset: 405, Line: 35, Column: 14}, Name: "a", Value: "int", }, compiler.TypeField{ Pos: Position{Filename: "", Offset: 412, Line: 35, Column: 21}, Name: "b", Value: "int", }, }, ReturnType: &compiler.ReturnType{ Pos: Position{Filename: "", Offset: 419, Line: 35, Column: 28}, Name: "int", }, Statements: []*compiler.Statement{ &compiler.Statement{ Pos: Position{Filename: "", Offset: 428, Line: 36, Column: 3}, FuncCall: &compiler.FuncCallStatement{ Pos: Position{Filename: "", Offset: 428, Line: 36, Column: 3}, Name: "return", Values: []*compiler.Literal{ React.createElement( View, {}, React.createElement( View, {}, React.createElement( Text, {}, ) , ) , React.createElement( View, {}, React.createElement( Text, {}, ) , ) , ) , }, }, }, }, }, &compiler.Function{ Pos: Position{Filename: "", Offset: 611, Line: 52, Column: 1}, Type: "proc", Name: "adder", Parameters: []compiler.TypeField{ compiler.TypeField{ Pos: Position{Filename: "", Offset: 622, Line: 52, Column: 12}, Name: "a", Value: "int", }, compiler.TypeField{ Pos: Position{Filename: "", Offset: 629, Line: 52, Column: 19}, Name: "b", Value: "int", }, }, ReturnType: &compiler.ReturnType{ Pos: Position{Filename: "", Offset: 637, Line: 52, Column: 27}, Name: "int", }, Statements: []*compiler.Statement{ &compiler.Statement{ Pos: Position{Filename: "", Offset: 646, Line: 53, Column: 3}, If: &compiler.IfStatement{ Pos: Position{Filename: "", Offset: 646, Line: 53, Column: 3}, Condition: []*compiler.Expression{ a < b, }, Result: []*compiler.Statement{ &compiler.Statement{ Pos: Position{Filename: "", Offset: 661, Line: 54, Column: 5}, ReturnStatement: &compiler.ReturnStatement{ Pos: Position{Filename: "", Offset: 661, Line: 54, Column: 5}, Expression: a - b + b, }, }, }, }, }, &compiler.Statement{ Pos: Position{Filename: "", Offset: 684, Line: 56, Column: 3}, ReturnStatement: &compiler.ReturnStatement{ Pos: Position{Filename: "", Offset: 684, Line: 56, Column: 3}, Expression: a + b, }, }, }, }, }, Tests: []*compiler.Test{ &compiler.Test{ Pos: Position{Filename: "", Offset: 700, Line: 59, Column: 1}, Name: "for equal or not equal", Statements: []*compiler.Statement{ &compiler.Statement{ Pos: Position{Filename: "", Offset: 734, Line: 60, Column: 3}, AssertStatement: &compiler.AssertStatement{ Pos: Position{Filename: "", Offset: 734, Line: 60, Column: 3}, Expression: 1 == 1, }, }, &compiler.Statement{ Pos: Position{Filename: "", Offset: 751, Line: 61, Column: 3}, AssertStatement: &compiler.AssertStatement{ Pos: Position{Filename: "", Offset: 751, Line: 61, Column: 3}, Expression: 2 == 2, }, }, &compiler.Statement{ Pos: Position{Filename: "", Offset: 768, Line: 62, Column: 3}, AssertStatement: &compiler.AssertStatement{ Pos: Position{Filename: "", Offset: 768, Line: 62, Column: 3}, Expression: 4 == 4, }, }, &compiler.Statement{ Pos: Position{Filename: "", Offset: 785, Line: 63, Column: 3}, AssertStatement: &compiler.AssertStatement{ Pos: Position{Filename: "", Offset: 785, Line: 63, Column: 3}, Expression: 3 != 13, }, }, }, }, }, }
compiler/.snapshots/arithmetic.go
0.54698
0.627152
arithmetic.go
starcoder
package ast import ( "fmt" "github.com/michaelquigley/pfxlog" "reflect" "github.com/pkg/errors" ) func transformTypes(s SymbolTypes, nodes ...*Node) error { for _, node := range nodes { if sp, ok := (*node).(TypeTransformable); ok { transformed, err := sp.TypeTransform(s) if err != nil { return err } *node = transformed } if sp, ok := (*node).(BoolTypeTransformable); ok { transformed, err := sp.TypeTransformBool(s) if err != nil { return err } *node = transformed } } return nil } func toInt64Nodes(nodes ...Node) ([]Int64Node, bool) { var result []Int64Node for _, node := range nodes { if int64Node, ok := node.(Int64Node); ok { result = append(result, int64Node) } else { return nil, false } } return result, true } func toFloat64Nodes(nodes ...Node) ([]Float64Node, bool) { var result []Float64Node for _, node := range nodes { if int64Node, ok := node.(Int64Node); ok { result = append(result, int64Node.ToFloat64()) } else if float64Node, ok := node.(Float64Node); ok { result = append(result, float64Node) } else { return nil, false } } return result, true } type boolBinaryOp int const ( AndOp boolBinaryOp = iota OrOp ) type BooleanLogicExprNode struct { left Node right Node op boolBinaryOp } func (node *BooleanLogicExprNode) Accept(visitor Visitor) { visitor.VisitBooleanLogicExprNodeStart(node) node.left.Accept(visitor) node.right.Accept(visitor) visitor.VisitBooleanLogicExprNodeEnd(node) } func (node *BooleanLogicExprNode) GetType() NodeType { return NodeTypeBool } func (node *BooleanLogicExprNode) EvalBool(_ Symbols) bool { pfxlog.Logger().Errorf("cannot evaluate transitory binary bool op node %v", node) return false } func (node *BooleanLogicExprNode) String() string { opName := "AND" if node.op == OrOp { opName = "OR" } return fmt.Sprintf("%v %v %v", node.left, opName, node.right) } func (node *BooleanLogicExprNode) TypeTransformBool(s SymbolTypes) (BoolNode, error) { if err := transformTypes(s, &node.left, &node.right); err != nil { return node, err } left, ok := node.left.(BoolNode) if !ok { return node, errors.Errorf("boolean logic expression LHS is of type %v, not bool", reflect.TypeOf(node.left)) } right, ok := node.right.(BoolNode) if !ok { return node, errors.Errorf("boolean logic expression RHS is of type %v, not bool", reflect.TypeOf(node.right)) } if node.op == AndOp { return &AndExprNode{left, right}, nil } if node.op == OrOp { return &OrExprNode{left, right}, nil } return node, errors.Errorf("unsupported boolean logic expression operation %v", node.op) } func (node *BooleanLogicExprNode) IsConst() bool { return false } type BinaryExprNode struct { left Node right Node op BinaryOp } func (node *BinaryExprNode) Accept(visitor Visitor) { visitor.VisitBinaryExprNodeStart(node) node.left.Accept(visitor) node.right.Accept(visitor) visitor.VisitBinaryExprNodeEnd(node) } func (node *BinaryExprNode) GetType() NodeType { return NodeTypeBool } func (node *BinaryExprNode) EvalBool(_ Symbols) bool { pfxlog.Logger().Errorf("cannot evaluate transitory binary op node %v", node) return false } func (node *BinaryExprNode) TypeTransformBool(s SymbolTypes) (BoolNode, error) { if err := transformTypes(s, &node.left, &node.right); err != nil { return node, err } setFunction, isSetFunction := node.left.(*SetFunctionNode) if isSetFunction && setFunction.IsCompare() { node.left = setFunction.symbol } typedExpr, err := node.getTypedExpr() if err != nil { return nil, err } if isSetFunction && setFunction.IsCompare() { return setFunction.MoveUpTree(typedExpr) } return typedExpr, nil } func (node *BinaryExprNode) getTypedExpr() (BoolNode, error) { if _, isNull := node.right.(NullConstNode); isNull { return node.handleIsNullOps() } if node.op == BinaryOpContains || node.op == BinaryOpNotContains { return node.handleStringOps() } // use symbol type to drive operation type selection, unless type is any nodeType := node.left.GetType() if nodeType == NodeTypeAnyType { nodeType = node.right.GetType() } if nodeType == NodeTypeBool { return node.handleBoolOps() } if nodeType == NodeTypeDatetime { return node.handleDatetimeOps() } if nodeType == NodeTypeFloat64 { return node.handleFloat64Ops() } if nodeType == NodeTypeInt64 { return node.handleInt64Ops() } if nodeType == NodeTypeString { return node.handleStringOps() } return node.invalidOpTypes() } func (node *BinaryExprNode) handleIsNullOps() (BoolNode, error) { symbolNode, isSymbol := node.left.(SymbolNode) if isSymbol && (node.op == BinaryOpEQ || node.op == BinaryOpNEQ) { return &IsNilExprNode{ symbol: symbolNode, op: node.op, }, nil } return node.invalidOpTypes() } func (node *BinaryExprNode) handleBoolOps() (BoolNode, error) { if node.right.GetType() == NodeTypeBool && (node.op == BinaryOpEQ || node.op == BinaryOpNEQ) { return &BinaryBoolExprNode{ left: node.left.(BoolNode), right: node.right.(BoolNode), op: node.op, }, nil } return node.invalidOpTypes() } func (node *BinaryExprNode) handleStringOps() (BoolNode, error) { left, ok := node.left.(StringNode) if ok { right, ok := node.right.(StringNode) if ok { return &BinaryStringExprNode{ left: left, right: right, op: node.op, }, nil } } return node.invalidOpTypes() } func (node *BinaryExprNode) handleInt64Ops() (BoolNode, error) { left := node.left.(Int64Node) if node.right.GetType() == NodeTypeInt64 { return &BinaryInt64ExprNode{ left: left, right: node.right.(Int64Node), op: node.op, }, nil } if node.right.GetType() == NodeTypeFloat64 { return &BinaryFloat64ExprNode{ left: left.ToFloat64(), right: node.right.(Float64Node), op: node.op, }, nil } return node.invalidOpTypes() } func (node *BinaryExprNode) handleFloat64Ops() (BoolNode, error) { left := node.left.(Float64Node) if node.right.GetType() == NodeTypeFloat64 { return &BinaryFloat64ExprNode{ left: left, right: node.right.(Float64Node), op: node.op, }, nil } if node.right.GetType() == NodeTypeInt64 { right := node.right.(Int64Node) return &BinaryFloat64ExprNode{ left: left, right: right.ToFloat64(), op: node.op, }, nil } return node.invalidOpTypes() } func (node *BinaryExprNode) handleDatetimeOps() (BoolNode, error) { left := node.left.(DatetimeNode) if node.right.GetType() == NodeTypeDatetime { return &BinaryDatetimeExprNode{ left: left, right: node.right.(DatetimeNode), op: node.op, }, nil } return node.invalidOpTypes() } func (node *BinaryExprNode) invalidOpTypes() (BoolNode, error) { return node, errors.Errorf("operation %v is not supported with operands types %v, %v", node, nodeTypeNames[node.left.GetType()], nodeTypeNames[node.right.GetType()]) } func (node *BinaryExprNode) String() string { return fmt.Sprintf("%v %v %v", node.left, binaryOpNames[node.op], node.right) } func (node *BinaryExprNode) IsConst() bool { return false } type Int64ToFloat64Node struct { wrapped Int64Node } func (node *Int64ToFloat64Node) GetType() NodeType { return NodeTypeFloat64 } func (node *Int64ToFloat64Node) Accept(visitor Visitor) { visitor.VisitInt64ToFloat64NodeStart(node) node.wrapped.Accept(visitor) visitor.VisitInt64ToFloat64NodeEnd(node) } func (node *Int64ToFloat64Node) EvalFloat64(s Symbols) *float64 { result := node.wrapped.EvalInt64(s) if result == nil { return nil } floatResult := float64(*result) return &floatResult } func (node *Int64ToFloat64Node) EvalString(s Symbols) *string { return node.wrapped.EvalString(s) } func (node *Int64ToFloat64Node) String() string { return fmt.Sprintf("float64(%v)", node.wrapped) } func (node *Int64ToFloat64Node) IsConst() bool { return node.wrapped.IsConst() } func NewInArrayExprNode(left, right Node) *InArrayExprNode { return &InArrayExprNode{ left: left, right: right, } } // InArrayExprNode is transitory node that handles conversion from untyped to typed IN nodes type InArrayExprNode struct { left Node right Node } func (node *InArrayExprNode) Accept(visitor Visitor) { visitor.VisitInArrayExprNodeStart(node) node.left.Accept(visitor) node.right.Accept(visitor) visitor.VisitInArrayExprNodeEnd(node) } func (node *InArrayExprNode) String() string { return fmt.Sprintf("%v in %v", node.left, node.right) } func (*InArrayExprNode) GetType() NodeType { return NodeTypeBool } func (node *InArrayExprNode) EvalBool(_ Symbols) bool { pfxlog.Logger().Errorf("cannot evaluate transitory in node %v", node) return false } func (node *InArrayExprNode) TypeTransformBool(s SymbolTypes) (BoolNode, error) { if err := transformTypes(s, &node.left, &node.right); err != nil { return node, err } setFunction, isSetFunction := node.left.(*SetFunctionNode) if isSetFunction { node.left = setFunction.symbol } typedExpr, err := node.getTypedExpr() if err != nil { return nil, err } if isSetFunction { return setFunction.MoveUpTree(typedExpr) } return typedExpr, nil } func (node *InArrayExprNode) getTypedExpr() (BoolNode, error) { if leftDatetime, ok := node.left.(DatetimeNode); ok { if rightDatetimeArray, ok := node.right.(*DatetimeArrayNode); ok { return &InDatetimeArrayExprNode{left: leftDatetime, right: rightDatetimeArray}, nil } } if leftInt, ok := node.left.(Int64Node); ok { if rightIntArr, ok := node.right.(*Int64ArrayNode); ok { return &InInt64ArrayExprNode{left: leftInt, right: rightIntArr}, nil } leftFloat := leftInt.ToFloat64() if rightFloatArr, ok := node.right.(*Float64ArrayNode); ok { return &InFloat64ArrayExprNode{left: leftFloat, right: rightFloatArr}, nil } } if leftFloat, ok := node.left.(Float64Node); ok { if rightIntArr, ok := node.right.(*Int64ArrayNode); ok { return &InFloat64ArrayExprNode{left: leftFloat, right: rightIntArr.ToFloat64ArrayNode()}, nil } if rightFloatArr, ok := node.right.(*Float64ArrayNode); ok { return &InFloat64ArrayExprNode{left: leftFloat, right: rightFloatArr}, nil } } if leftStr, ok := node.left.(StringNode); ok { if rightStrArray, ok := node.right.(AsStringArrayable); ok { return &InStringArrayExprNode{left: leftStr, right: rightStrArray.AsStringArray()}, nil } } return node, errors.Errorf("operation %v is not supported with operands types %v, %v", node, nodeTypeNames[node.left.GetType()], nodeTypeNames[node.right.GetType()]) } func (node *InArrayExprNode) IsConst() bool { return false } // BetweenExprNode is transitory node that handles conversion from untyped to typed BETWEEN nodes type BetweenExprNode struct { left Node lower Node upper Node } func (node *BetweenExprNode) Accept(visitor Visitor) { visitor.VisitBetweenExprNodeStart(node) node.left.Accept(visitor) node.lower.Accept(visitor) node.upper.Accept(visitor) visitor.VisitBetweenExprNodeEnd(node) } func (node *BetweenExprNode) String() string { return fmt.Sprintf("%v between %v and %v", node.left, node.lower, node.upper) } func (*BetweenExprNode) GetType() NodeType { return NodeTypeBool } func (node *BetweenExprNode) EvalBool(_ Symbols) bool { pfxlog.Logger().Errorf("cannot evaluate transitory between node %v", node) return false } func (node *BetweenExprNode) TypeTransformBool(s SymbolTypes) (BoolNode, error) { if err := transformTypes(s, &node.left, &node.lower, &node.upper); err != nil { return node, err } setFunction, isSetFunction := node.left.(*SetFunctionNode) if isSetFunction { node.left = setFunction.symbol } typedExpr, err := node.getTypedExpr() if err != nil { return nil, err } if isSetFunction { return setFunction.MoveUpTree(typedExpr) } return typedExpr, nil } func (node *BetweenExprNode) getTypedExpr() (BoolNode, error) { if leftDatetime, ok := node.left.(DatetimeNode); ok { lowerDatetime := node.lower.(DatetimeNode) upperDatetime := node.upper.(DatetimeNode) return &DatetimeBetweenExprNode{left: leftDatetime, lower: lowerDatetime, upper: upperDatetime}, nil } if int64Nodes, ok := toInt64Nodes(node.left, node.lower, node.upper); ok { return NewInt64BetweenOp(int64Nodes) } if float64Nodes, ok := toFloat64Nodes(node.left, node.lower, node.upper); ok { return NewFloat64BetweenOp(float64Nodes) } return node, errors.Errorf("operation between is not supported with operands types %v, %v, %v", reflect.TypeOf(node.left), reflect.TypeOf(node.lower), reflect.TypeOf(node.lower)) } func (node *BetweenExprNode) IsConst() bool { return false } type SetFunctionNode struct { setFunction SetFunction symbol SymbolNode } func (node *SetFunctionNode) Accept(visitor Visitor) { visitor.VisitSetFunctionNodeStart(node) node.symbol.Accept(visitor) visitor.VisitSetFunctionNodeEnd(node) } func (node *SetFunctionNode) TypeTransform(s SymbolTypes) (Node, error) { var symbolNode Node = node.symbol err := transformTypes(s, &symbolNode) if err != nil { return node, err } newSymbolNode, ok := symbolNode.(SymbolNode) if !ok { return node, errors.Errorf("identifier symbol %v was transformed to non-identifier node: %v", node.symbol.Symbol(), reflect.TypeOf(symbolNode)) } node.symbol = newSymbolNode if !node.IsCompare() { symbol := node.symbol var query Query subQuery, ok := symbol.(*subQueryNode) if ok { symbol = subQuery.symbol query = subQuery.query } if node.setFunction == SetFunctionCount { return &CountSetExprNode{ symbol: symbol, }, nil } if node.setFunction == SetFunctionIsEmpty { return &IsEmptySetExprNode{ symbol: symbol, query: query, }, nil } } return node, nil } func (node *SetFunctionNode) String() string { return fmt.Sprintf("%v(%v)", node.setFunction, node.symbol) } func (node *SetFunctionNode) GetType() NodeType { switch node.setFunction { case SetFunctionCount: return NodeTypeInt64 case SetFunctionIsEmpty: return NodeTypeBool default: return node.symbol.GetType() } } func (node *SetFunctionNode) IsCompare() bool { switch node.setFunction { case SetFunctionAllOf, SetFunctionAnyOf: return true default: return false } } func (node *SetFunctionNode) MoveUpTree(boolNode BoolNode) (BoolNode, error) { switch node.setFunction { case SetFunctionAllOf: return &AllOfSetExprNode{name: node.symbol.Symbol(), predicate: boolNode}, nil case SetFunctionAnyOf: return node.specializeSetAnyOf(boolNode) default: return nil, errors.Errorf("unhandled set function %v", node.setFunction) } } func (node *SetFunctionNode) specializeSetAnyOf(boolNode BoolNode) (BoolNode, error) { if seekOptimizable, ok := boolNode.(SeekOptimizableBoolNode); ok && seekOptimizable.IsSeekable() { return &AnyOfSetExprNode{ name: node.symbol.Symbol(), predicate: boolNode, seekablePredicate: seekOptimizable, }, nil } return &AnyOfSetExprNode{name: node.symbol.Symbol(), predicate: boolNode}, nil } func (node *SetFunctionNode) IsConst() bool { return false } type UntypedNotExprNode struct { expr Node } func (node *UntypedNotExprNode) String() string { return fmt.Sprintf("not (%v)", node.expr.String()) } func (node *UntypedNotExprNode) Accept(visitor Visitor) { visitor.VisitUntypedNotExprStart(node) node.expr.Accept(visitor) visitor.VisitUntypedNotExprEnd(node) } func (node *UntypedNotExprNode) GetType() NodeType { return NodeTypeBool } func (node *UntypedNotExprNode) EvalBool(_ Symbols) bool { pfxlog.Logger().Errorf("cannot evaluate transitory untyped not node %v", node) return false } func (node *UntypedNotExprNode) TypeTransformBool(s SymbolTypes) (BoolNode, error) { if err := transformTypes(s, &node.expr); err != nil { return node, err } boolNode, ok := node.expr.(BoolNode) if !ok { return node, errors.Errorf("not expr must wrap bool expr. contains %v", reflect.TypeOf(node.expr)) } return &NotExprNode{expr: boolNode}, nil } func (node *UntypedNotExprNode) IsConst() bool { return node.expr.IsConst() }
storage/ast/node_convert.go
0.650467
0.509276
node_convert.go
starcoder
package eve // DL provides a convenient way to write Display List commands. type DL struct { Writer } // DL wraps W to return Display List writer. See W for more information. func (d *Driver) DL(addr int) DL { return DL{d.W(addr)} } // AlphaFunc sets the alpha test function. func (dl *DL) AlphaFunc(fun, ref byte) { dl.restart(4) dl.wr32(ALPHA_FUNC | uint32(fun)<<8 | uint32(ref)) } // Begin begins drawing a graphics primitive. func (dl *DL) Begin(prim byte) { dl.restart(4) dl.wr32(BEGIN | uint32(prim)) } // BitmapHandle selscts the bitmap handle. func (dl *DL) BitmapHandle(handle byte) { dl.restart(4) dl.wr32(BITMAP_HANDLE | uint32(handle)) } // BitmapLayout sets the bitmap memory format and layout for the current handle. func (dl *DL) BitmapLayout(format byte, linestride, height int) { l := uint32(linestride) & 1023 h := uint32(height) & 511 dl.restart(4) dl.wr32(BITMAP_LAYOUT | uint32(format)<<19 | l<<9 | h) if dl.d.mmap != &eve1 { l = uint32(linestride) >> 10 & 3 h = uint32(height) >> 9 & 3 dl.addrAdd(4) dl.wr32(BITMAP_LAYOUT_H | l<<2 | h) } } // BitmapSize sets the screen drawing of bitmaps for the current handle. func (dl *DL) BitmapSize(options byte, width, height int) { w := uint32(width) & 511 h := uint32(height) & 511 dl.restart(4) dl.wr32(BITMAP_SIZE | uint32(options)<<18 | w<<9 | h) if dl.d.mmap != &eve1 { w = uint32(width) >> 9 & 3 h = uint32(height) >> 9 & 3 dl.addrAdd(4) dl.wr32(BITMAP_SIZE_H | w<<2 | h) } } // BitmapSource sets the source address of bitmap data in graphics memory RAM_G. func (dl *DL) BitmapSource(addr int) { dl.restart(4) dl.wr32(BITMAP_SOURCE | uint32(addr)&0x3FFFFF) } // BitmapTransA sets the A coefficient of the bitmap transform matrix. func (dl *DL) BitmapTransformA(a int) { dl.restart(4) dl.wr32(BITMAP_TRANSFORM_A | uint32(a)&0x1FFFF) } // BitmapTransformB sets the B coefficient of the bitmap transform matrix. func (dl *DL) BitmapTransformB(b int) { dl.restart(4) dl.wr32(BITMAP_TRANSFORM_B | uint32(b)&0x1FFFF) } // BitmapTransformC sets the C coefficient of the bitmap transform matrix. func (dl *DL) BitmapTransformC(c int) { dl.restart(4) dl.wr32(BITMAP_TRANSFORM_C | uint32(c)&0x1FFFF) } // BitmapTransformD sets the D coefficient of the bitmap transform matrix. func (dl *DL) BitmapTransformD(d int) { dl.restart(4) dl.wr32(BITMAP_TRANSFORM_D | uint32(d)&0x1FFFF) } // BitmapTransformE sets the E coefficient of the bitmap transform matrix. func (dl *DL) BitmapTransformE(e int) { dl.restart(4) dl.wr32(BITMAP_TRANSFORM_E | uint32(e)&0x1FFFF) } // BitmapTransformF sets the F coefficient of the bitmap transform matrix. func (dl *DL) BitmapTransformF(f int) { dl.restart(4) dl.wr32(BITMAP_TRANSFORM_F | uint32(f)&0x1FFFF) } // BlendFunc configures pixel arithmetic. func (dl *DL) BlendFunc(src, dst byte) { dl.restart(4) dl.wr32(BLEND_FUNC | uint32(src)<<3 | uint32(dst)) } // Call executes a sequence of commands at another location in the display list. func (dl *DL) Call(dest int) { dl.restart(4) dl.wr32(CALL | uint32(dest)&0xFFFF) } // Cell sets the bitmap cell number for the Vertex2F command. func (dl *DL) Cell(cell byte) { dl.restart(4) dl.wr32(CELL | uint32(cell)) } // Clear clears buffers to preset values. func (dl *DL) Clear(cst byte) { dl.restart(4) dl.wr32(CLEAR | uint32(cst)) } // ClearColorA sets the clear value for the alpha channel. func (dl *DL) ClearColorA(alpha byte) { dl.restart(4) dl.wr32(CLEAR_COLOR_A | uint32(alpha)) } // ClearColorRGB sets the clear values for red, green and blue channels. func (dl *DL) ClearColorRGB(rgb uint32) { dl.restart(4) dl.wr32(CLEAR_COLOR_RGB | rgb) } // ClearStencil sets the clear value for the stencil buffer. func (dl *DL) ClearStencil(s byte) { dl.restart(4) dl.wr32(CLEAR_STENCIL | uint32(s)) } // ClearTag sets the clear value for the stencil buffer. func (dl *DL) ClearTag(t int) { dl.restart(4) dl.wr32(CLEAR_TAG | uint32(uint16(t))) } // ColorA sets the current color alpha. func (dl *DL) ColorA(alpha byte) { dl.restart(4) dl.wr32(COLOR_A | uint32(alpha)) } // ColorMask enables or disables writing of color components. func (dl *DL) ColorMask(rgba byte) { dl.restart(4) dl.wr32(COLOR_MASK | uint32(rgba)) } // ColorRGB sets the current color red, green and blue. func (dl *DL) ColorRGB(rgb uint32) { dl.restart(4) dl.wr32(COLOR_RGB | rgb) } // Display ends the display list (following command will be ignored). func (dl *DL) Display() { dl.restart(4) dl.wr32(DISPLAY) } // End ends drawing a graphics primitive. func (dl *DL) End() { dl.restart(4) dl.wr32(END) } // Jump executes commands at another location in the display list. Dest is the // command number in display list (address = RAM_DL + dest*4). func (dl *DL) Jump(dest int) { dl.restart(4) dl.wr32(JUMP | uint32(dest)&0xFFFF) } // LineWidth sets the width of lines to be drawn with primitive LINES in 1/16 // pixel precision. func (dl *DL) LineWidth(width int) { dl.restart(4) dl.wr32(LINE_WIDTH | uint32(width)&0xFFF) } // Macro executes a single command from a macro register. func (dl *DL) Macro(m int) { dl.restart(4) dl.wr32(MACRO | uint32(m&1)) } // Nop does nothing. func (dl *DL) Nop() { dl.restart(4) dl.wr32(NOP) } // PaletteSource sets the base address of the palette (EVE2). func (dl *DL) PaletteSource(addr int) { dl.restart(4) dl.wr32(PALETTE_SOURCE | uint32(addr)&0x3FFFFF) } // PointSize sets the radius of points. func (dl *DL) PointSize(size int) { dl.restart(4) dl.wr32(POINT_SIZE | uint32(size)&0x1FFF) } // RestoreContext restores the current graphics context from the context stack. func (dl *DL) RestoreContext() { dl.restart(4) dl.wr32(RESTORE_CONTEXT) } // Return returns from a previous CALL command. func (dl *DL) Return() { dl.restart(4) dl.wr32(RETURN) } // SaveContext pushes the current graphics context on the context stack. func (dl *DL) SaveContext() { dl.restart(4) dl.wr32(SAVE_CONTEXT) } // ScissorSize sets the size of the scissor clip rectangle. func (dl *DL) ScissorSize(width, height int) { dl.restart(4) dl.wr32(SCISSOR_SIZE | uint32(width)&0xFFF<<12 | uint32(height)&0xFFF) } // ScissorXY sets the size of the scissor clip rectangle. func (dl *DL) ScissorXY(x, y int) { dl.restart(4) dl.wr32(SCISSOR_XY | uint32(x)&0x7FF<<11 | uint32(y)&0x7FF) } // StencilFunc sets function and reference value for stencil testing. func (dl *DL) StencilFunc(fun, ref, mask byte) { dl.restart(4) dl.wr32(STENCIL_FUNC | uint32(fun)<<16 | uint32(ref)<<8 | uint32(mask)) } // StencilMask controls the writing of individual bits in the stencil planes. func (dl *DL) StencilMask(mask byte) { dl.restart(4) dl.wr32(STENCIL_MASK | uint32(mask)) } // StencilOp sets stencil test actions. func (dl *DL) StencilOp(sfail, spass byte) { dl.restart(4) dl.wr32(STENCIL_OP | uint32(sfail)<<3 | uint32(spass)) } // Tag attaches the tag value for the following graphics objects drawn on the // screen. The initial tag buffer value is 255. func (dl *DL) Tag(t int) { dl.restart(4) dl.wr32(TAG | uint32(uint16(t))) } // TagMask controls the writing of the tag buffer. func (dl *DL) TagMask(mask byte) { dl.restart(4) dl.wr32(TAG_MASK | uint32(mask)) } // Vertex2f starts the operation of graphics primitives at the specified screen // coordinate, in the pixel precision set by VertexFormat (default: 1/16 pixel). func (dl *DL) Vertex2f(x, y int) { dl.restart(4) dl.wr32(VERTEX2F | uint32(x)&0x7FFF<<15 | uint32(y)&0x7FFF) } // Vertex2II starts the operation of graphics primitive at the specified // coordinates in pixel precision. func (dl *DL) Vertex2ii(x, y int, handle, cell byte) { dl.restart(4) dl.wr32(VERTEX2II | uint32(x)&511<<21 | uint32(y)&511<<12 | uint32(handle)<<7 | uint32(cell)) } // VertexFormat sets the precision of Vertex2F coordinates (EVE2). func (dl *DL) VertexFormat(frac uint) { dl.restart(4) dl.wr32(VERTEX_FORMAT | uint32(frac)&7) }
egpath/src/display/eve/dl.go
0.758958
0.498474
dl.go
starcoder
package grob type Config struct { // Autosizable boolean Determines whether the graphs are plotted with respect to layout.autosize:true and infer its container size. Autosizable Bool `json:"autosizable,omitempty"` // DisplayModeBar enumerated Determines the mode bar display mode. If *true*, the mode bar is always visible. If *false*, the mode bar is always hidden. If *hover*, the mode bar is visible while the mouse cursor is on the graph container. DisplayModeBar ConfigDisplaymodebar `json:"displayModeBar,omitempty"` // Displaylogo boolean Determines whether or not the plotly logo is displayed on the end of the mode bar. Displaylogo Bool `json:"displaylogo,omitempty"` // DoubleClick enumerated Sets the double click interaction mode. Has an effect only in cartesian plots. If *false*, double click is disable. If *reset*, double click resets the axis ranges to their initial values. If *autosize*, double click set the axis ranges to their autorange values. If *reset+autosize*, the odd double clicks resets the axis ranges to their initial values and even double clicks set the axis ranges to their autorange values. DoubleClick ConfigDoubleclick `json:"doubleClick,omitempty"` // DoubleClickDelay number Sets the delay for registering a double-click in ms. This is the time interval (in ms) between first mousedown and 2nd mouseup to constitute a double-click. This setting propagates to all on-subplot double clicks (except for geo and mapbox) and on-legend double clicks. DoubleClickDelay float64 `json:"doubleClickDelay,omitempty"` // Editable boolean Determines whether the graph is editable or not. Sets all pieces of `edits` unless a separate `edits` config item overrides individual parts. Editable Bool `json:"editable,omitempty"` // Edits <no value> <no value> Edits *ConfigEdits `json:"edits,omitempty"` // FillFrame boolean When `layout.autosize` is turned on, determines whether the graph fills the container (the default) or the screen (if set to *true*). FillFrame Bool `json:"fillFrame,omitempty"` // FrameMargins number When `layout.autosize` is turned on, set the frame margins in fraction of the graph size. FrameMargins float64 `json:"frameMargins,omitempty"` // GlobalTransforms any Set global transform to be applied to all traces with no specification needed GlobalTransforms interface{} `json:"globalTransforms,omitempty"` // LinkText string Sets the text appearing in the `showLink` link. LinkText String `json:"linkText,omitempty"` // Locale string Which localization should we use? Should be a string like 'en' or 'en-US'. Locale String `json:"locale,omitempty"` // Locales any Localization definitions Locales can be provided either here (specific to one chart) or globally by registering them as modules. Should be an object of objects {locale: {dictionary: {...}, format: {...}}} { da: { dictionary: {'Reset axes': 'Nulstil aksler', ...}, format: {months: [...], shortMonths: [...]} }, ... } All parts are optional. When looking for translation or format fields, we look first for an exact match in a config locale, then in a registered module. If those fail, we strip off any regionalization ('en-US' -> 'en') and try each (config, registry) again. The final fallback for translation is untranslated (which is US English) and for formats is the base English (the only consequence being the last fallback date format %x is DD/MM/YYYY instead of MM/DD/YYYY). Currently `grouping` and `currency` are ignored for our automatic number formatting, but can be used in custom formats. Locales interface{} `json:"locales,omitempty"` // Logging integer Turn all console logging on or off (errors will be thrown) This should ONLY be set via Plotly.setPlotConfig Available levels: 0: no logs 1: warnings and errors, but not informational messages 2: verbose logs Logging int64 `json:"logging,omitempty"` // MapboxAccessToken string Mapbox access token (required to plot mapbox trace types) If using an Mapbox Atlas server, set this option to '' so that plotly.js won't attempt to authenticate to the public Mapbox server. MapboxAccessToken String `json:"mapboxAccessToken,omitempty"` // ModeBarButtons any Define fully custom mode bar buttons as nested array, where the outer arrays represents button groups, and the inner arrays have buttons config objects or names of default buttons See ./components/modebar/buttons.js for more info. ModeBarButtons interface{} `json:"modeBarButtons,omitempty"` // ModeBarButtonsToAdd any Add mode bar button using config objects See ./components/modebar/buttons.js for list of arguments. ModeBarButtonsToAdd interface{} `json:"modeBarButtonsToAdd,omitempty"` // ModeBarButtonsToRemove any Remove mode bar buttons by name. See ./components/modebar/buttons.js for the list of names. ModeBarButtonsToRemove interface{} `json:"modeBarButtonsToRemove,omitempty"` // NotifyOnLogging integer Set on-graph logging (notifier) level This should ONLY be set via Plotly.setPlotConfig Available levels: 0: no on-graph logs 1: warnings and errors, but not informational messages 2: verbose logs NotifyOnLogging int64 `json:"notifyOnLogging,omitempty"` // PlotGlPixelRatio number Set the pixel ratio during WebGL image export. This config option was formerly named `plot3dPixelRatio` which is now deprecated. PlotGlPixelRatio float64 `json:"plotGlPixelRatio,omitempty"` // PlotlyServerURL string When set it determines base URL for the 'Edit in Chart Studio' `showEditInChartStudio`/`showSendToCloud` mode bar button and the showLink/sendData on-graph link. To enable sending your data to Chart Studio Cloud, you need to set both `plotlyServerURL` to 'https://chart-studio.plotly.com' and also set `showSendToCloud` to true. PlotlyServerURL String `json:"plotlyServerURL,omitempty"` // QueueLength integer Sets the length of the undo/redo queue. QueueLength int64 `json:"queueLength,omitempty"` // Responsive boolean Determines whether to change the layout size when window is resized. In v2, this option will be removed and will always be true. Responsive Bool `json:"responsive,omitempty"` // ScrollZoom flaglist Determines whether mouse wheel or two-finger scroll zooms is enable. Turned on by default for gl3d, geo and mapbox subplots (as these subplot types do not have zoombox via pan), but turned off by default for cartesian subplots. Set `scrollZoom` to *false* to disable scrolling for all subplots. ScrollZoom ConfigScrollzoom `json:"scrollZoom,omitempty"` // SendData boolean If *showLink* is true, does it contain data just link to a Chart Studio Cloud file? SendData Bool `json:"sendData,omitempty"` // SetBackground any Set function to add the background color (i.e. `layout.paper_color`) to a different container. This function take the graph div as first argument and the current background color as second argument. Alternatively, set to string *opaque* to ensure there is white behind it. SetBackground interface{} `json:"setBackground,omitempty"` // ShowAxisDragHandles boolean Set to *false* to omit cartesian axis pan/zoom drag handles. ShowAxisDragHandles Bool `json:"showAxisDragHandles,omitempty"` // ShowAxisRangeEntryBoxes boolean Set to *false* to omit direct range entry at the pan/zoom drag points, note that `showAxisDragHandles` must be enabled to have an effect. ShowAxisRangeEntryBoxes Bool `json:"showAxisRangeEntryBoxes,omitempty"` // ShowEditInChartStudio boolean Same as `showSendToCloud`, but use a pencil icon instead of a floppy-disk. Note that if both `showSendToCloud` and `showEditInChartStudio` are turned, only `showEditInChartStudio` will be honored. ShowEditInChartStudio Bool `json:"showEditInChartStudio,omitempty"` // ShowLink boolean Determines whether a link to Chart Studio Cloud is displayed at the bottom right corner of resulting graphs. Use with `sendData` and `linkText`. ShowLink Bool `json:"showLink,omitempty"` // ShowSendToCloud boolean Should we include a ModeBar button, labeled "Edit in Chart Studio", that sends this chart to chart-studio.plotly.com (formerly plot.ly) or another plotly server as specified by `plotlyServerURL` for editing, export, etc? Prior to version 1.43.0 this button was included by default, now it is opt-in using this flag. Note that this button can (depending on `plotlyServerURL` being set) send your data to an external server. However that server does not persist your data until you arrive at the Chart Studio and explicitly click "Save". ShowSendToCloud Bool `json:"showSendToCloud,omitempty"` // ShowSources any Adds a source-displaying function to show sources on the resulting graphs. ShowSources interface{} `json:"showSources,omitempty"` // ShowTips boolean Determines whether or not tips are shown while interacting with the resulting graphs. ShowTips Bool `json:"showTips,omitempty"` // StaticPlot boolean Determines whether the graphs are interactive or not. If *false*, no interactivity, for export or image generation. StaticPlot Bool `json:"staticPlot,omitempty"` // ToImageButtonOptions any Statically override options for toImage modebar button allowed keys are format, filename, width, height, scale see ../components/modebar/buttons.js ToImageButtonOptions interface{} `json:"toImageButtonOptions,omitempty"` // TopojsonURL string Set the URL to topojson used in geo charts. By default, the topojson files are fetched from cdn.plot.ly. For example, set this option to: <path-to-plotly.js>/dist/topojson/ to render geographical feature using the topojson files that ship with the plotly.js module. TopojsonURL String `json:"topojsonURL,omitempty"` // Watermark boolean watermark the images with the company's logo Watermark Bool `json:"watermark,omitempty"` }
graph_objects/auto_config.go
0.884975
0.548674
auto_config.go
starcoder
package geometry import ( "github.com/g3n/engine/gls" "github.com/g3n/engine/math32" "math" ) // Circle represents the geometry of a filled circle (i.e. a disk) // The center of the circle is at the origin, and theta runs counter-clockwise // on the XY plane, starting at (x,y,z)=(1,0,0). type Circle struct { Geometry Radius float64 Segments int // >= 3 ThetaStart float64 ThetaLength float64 } // NewCircle creates a new circle geometry with the specified radius // and number of radial segments/triangles (minimum 3). func NewCircle(radius float64, segments int) *Circle { return NewCircleSector(radius, segments, 0, 2*math.Pi) } // NewCircleSector creates a new circle or circular sector geometry with the specified radius, // number of radial segments/triangles (minimum 3), sector start angle in radians (thetaStart), // and sector size angle in radians (thetaLength). This is the Circle constructor with most tunable parameters. func NewCircleSector(radius float64, segments int, thetaStart, thetaLength float64) *Circle { circ := new(Circle) circ.Geometry.Init() // Validate arguments if segments < 3 { panic("Invalid argument: segments. The number of segments needs to be greater or equal to 3.") } circ.Radius = radius circ.Segments = segments circ.ThetaStart = thetaStart circ.ThetaLength = thetaLength // Create buffers positions := math32.NewArrayF32(0, 16) normals := math32.NewArrayF32(0, 16) uvs := math32.NewArrayF32(0, 16) indices := math32.NewArrayU32(0, 16) // Append circle center position center := math32.NewVector3(0, 0, 0) positions.AppendVector3(center) // Append circle center normal var normal math32.Vector3 normal.Z = 1 normals.AppendVector3(&normal) // Append circle center uv coordinate centerUV := math32.NewVector2(0.5, 0.5) uvs.AppendVector2(centerUV) // Generate the segments for i := 0; i <= segments; i++ { segment := thetaStart + float64(i)/float64(segments)*thetaLength vx := float32(radius * math.Cos(segment)) vy := float32(radius * math.Sin(segment)) // Appends vertex position, normal and uv coordinates positions.Append(vx, vy, 0) normals.AppendVector3(&normal) uvs.Append((vx/float32(radius)+1)/2, (vy/float32(radius)+1)/2) } for i := 1; i <= segments; i++ { indices.Append(uint32(i), uint32(i)+1, 0) } circ.SetIndices(indices) circ.AddVBO(gls.NewVBO().AddAttrib("VertexPosition", 3).SetBuffer(positions)) circ.AddVBO(gls.NewVBO().AddAttrib("VertexNormal", 3).SetBuffer(normals)) circ.AddVBO(gls.NewVBO().AddAttrib("VertexTexcoord", 2).SetBuffer(uvs)) //circ.BoundingSphere = math32.NewSphere(math32.NewVector3(0,0,0), float32(radius)) return circ }
geometry/circle.go
0.85558
0.632162
circle.go
starcoder
package ent import ( "fmt" "strings" "entgo.io/ent/dialect/sql" "github.com/efectn/go-orm-benchmarks/benchs/ent/model" ) // Model is the model entity for the Model schema. type Model struct { config `json:"-"` // ID of the ent. ID int `json:"id,omitempty"` // Name holds the value of the "name" field. Name string `json:"name,omitempty"` // Title holds the value of the "title" field. Title string `json:"title,omitempty"` // Fax holds the value of the "fax" field. Fax string `json:"fax,omitempty"` // Web holds the value of the "web" field. Web string `json:"web,omitempty"` // Age holds the value of the "age" field. Age int `json:"age,omitempty"` // Right holds the value of the "right" field. Right bool `json:"right,omitempty"` // Counter holds the value of the "counter" field. Counter int64 `json:"counter,omitempty"` } // scanValues returns the types for scanning values from sql.Rows. func (*Model) scanValues(columns []string) ([]interface{}, error) { values := make([]interface{}, len(columns)) for i := range columns { switch columns[i] { case model.FieldRight: values[i] = new(sql.NullBool) case model.FieldID, model.FieldAge, model.FieldCounter: values[i] = new(sql.NullInt64) case model.FieldName, model.FieldTitle, model.FieldFax, model.FieldWeb: values[i] = new(sql.NullString) default: return nil, fmt.Errorf("unexpected column %q for type Model", columns[i]) } } return values, nil } // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Model fields. func (m *Model) 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 model.FieldID: value, ok := values[i].(*sql.NullInt64) if !ok { return fmt.Errorf("unexpected type %T for field id", value) } m.ID = int(value.Int64) case model.FieldName: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field name", values[i]) } else if value.Valid { m.Name = value.String } case model.FieldTitle: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field title", values[i]) } else if value.Valid { m.Title = value.String } case model.FieldFax: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field fax", values[i]) } else if value.Valid { m.Fax = value.String } case model.FieldWeb: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field web", values[i]) } else if value.Valid { m.Web = value.String } case model.FieldAge: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field age", values[i]) } else if value.Valid { m.Age = int(value.Int64) } case model.FieldRight: if value, ok := values[i].(*sql.NullBool); !ok { return fmt.Errorf("unexpected type %T for field right", values[i]) } else if value.Valid { m.Right = value.Bool } case model.FieldCounter: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field counter", values[i]) } else if value.Valid { m.Counter = value.Int64 } } } return nil } // Update returns a builder for updating this Model. // Note that you need to call Model.Unwrap() before calling this method if this Model // was returned from a transaction, and the transaction was committed or rolled back. func (m *Model) Update() *ModelUpdateOne { return (&ModelClient{config: m.config}).UpdateOne(m) } // Unwrap unwraps the Model 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 (m *Model) Unwrap() *Model { tx, ok := m.config.driver.(*txDriver) if !ok { panic("ent: Model is not a transactional entity") } m.config.driver = tx.drv return m } // String implements the fmt.Stringer. func (m *Model) String() string { var builder strings.Builder builder.WriteString("Model(") builder.WriteString(fmt.Sprintf("id=%v", m.ID)) builder.WriteString(", name=") builder.WriteString(m.Name) builder.WriteString(", title=") builder.WriteString(m.Title) builder.WriteString(", fax=") builder.WriteString(m.Fax) builder.WriteString(", web=") builder.WriteString(m.Web) builder.WriteString(", age=") builder.WriteString(fmt.Sprintf("%v", m.Age)) builder.WriteString(", right=") builder.WriteString(fmt.Sprintf("%v", m.Right)) builder.WriteString(", counter=") builder.WriteString(fmt.Sprintf("%v", m.Counter)) builder.WriteByte(')') return builder.String() } // Models is a parsable slice of Model. type Models []*Model func (m Models) config(cfg config) { for _i := range m { m[_i].config = cfg } }
benchs/ent/model.go
0.691081
0.401864
model.go
starcoder
package models // Interface defining a potential object that has a spike of a given type type HasSpike interface { // Whether the object has the potential for a Big Spike pattern Has() bool } // Interface defining a potential object that has a hasSpikeAny range type HasSpikeRange interface { HasSpike // The first price period a big hasSpikeAny could occur. Start() PricePeriod // The last price period a big hasSpikeAny could occur (inclusive). End() PricePeriod } // Implementation of HasSpike type Spike struct { // Whether this is a big or small hasSpikeAny. has bool } // Whether the object has the potential for a Big Spike pattern func (spike *Spike) Has() bool { return spike.has } // Implementation of HasSpikeRange type SpikeRange struct { Spike start PricePeriod end PricePeriod } // The first price period any spike pattern could occur. func (spike *SpikeRange) Start() PricePeriod { return spike.start } // The last price period any spike pattern could occur. func (spike *SpikeRange) End() PricePeriod { return spike.end } func (spike *SpikeRange) updateSpikeFromPeriod(period PricePeriod, info HasSpike) { if !info.Has() { return } if !spike.Has() || period < spike.start { spike.start = period } if period > spike.end { spike.end = period } spike.has = true } func (spike *SpikeRange) updateFromRange(info HasSpikeRange) { if !info.Has() { return } if !spike.has || info.Start() < spike.start { spike.start = info.Start() } if info.End() > spike.end { spike.end = info.End() } spike.has = true } type SpikeHasAll struct { big *Spike small *Spike any *Spike } func (spikes *SpikeHasAll) Big() HasSpike { return spikes.big } func (spikes *SpikeHasAll) Small() HasSpike { return spikes.small } func (spikes *SpikeHasAll) Any() HasSpike { return spikes.any } type SpikeRangeAll struct { big *SpikeRange small *SpikeRange any *SpikeRange } func (spike *SpikeRangeAll) Big() HasSpikeRange { return spike.big } func (spike *SpikeRangeAll) Small() HasSpikeRange { return spike.small } func (spike *SpikeRangeAll) Any() HasSpikeRange { return spike.any } func (spike *SpikeRangeAll) updateSpikeFromPeriod( period PricePeriod, info *SpikeHasAll, ) { spike.any.updateSpikeFromPeriod(period, info.Any()) spike.big.updateSpikeFromPeriod(period, info.Big()) spike.small.updateSpikeFromPeriod(period, info.Small()) } // Update From Range func (spike *SpikeRangeAll) updateSpikeFromRange(info *SpikeRangeAll) { spike.big.updateFromRange(info.Big()) spike.small.updateFromRange(info.Small()) spike.any.updateFromRange(info.Any()) }
models/spikeInfo.go
0.856122
0.580025
spikeInfo.go
starcoder
package diffq import ( "strings" "github.com/google/go-cmp/cmp" "github.com/pkg/errors" "github.com/r3labs/diff" ) // Changes and Change are abstracted to eliminate tight-coupling with underlying // diff library. // Change represents a single change identified by the differential. Change is // intentionally abstracted from the r3labs/diff library to avoid tight coupling // to the dependancy. type Change struct { // Type indicates the change type: create, delete or update. Type string // Path is an array of field names representing the path to the field in // question from the outer struct. Path []string // From contains the original value of the field. From interface{} // To contains the new value of the field. To interface{} } // Changes represents a list of changes identified by the differential process. type Changes []Change // Diff represents the differential of two arbitrary structs and is used to // evaluate statements against it. type Diff struct { // Changed indicates the presence of any changes between two objects. Changed bool // Changes holds the complete list of changes identified by the diff // process. Changes Changes // ChangeLogMap maps the field identifiers of the changed values to the // change. ChangeLogMap map[string]Change // Original holds the original struct value Original interface{} // New holds the new struct value New interface{} } // Differential calculates the differential of a and b returning an initialized // Diff and an error if encountered. func Differential(a, b interface{}) (*Diff, error) { // calculate diff using r3labs/diff changes, err := diff.Diff(a, b) if err != nil { return nil, err } result := &Diff{ ChangeLogMap: make(map[string]Change), Original: a, New: b, } // map changes to internal change type and build lookup map for _, c := range changes { nc := Change{ Type: c.Type, Path: c.Path, To: c.To, From: c.From, } result.Changes = append(result.Changes, nc) ident := strings.Join(c.Path, ".") result.ChangeLogMap[ident] = nc } if len(changes) > 0 { result.Changed = true } return result, nil } // HumanDifferential calculates the differential between Original and New fields // on Diff, d, and returns a human readable string representing the diff. func (d *Diff) HumanDifferential() string { diff := cmp.Diff(d.Original, d.New) return diff } // EvaluateStatement executes statement provided against Diff, d, and returns // the validity of the statement relative to the calculated diff and any errors // encountered. func (d *Diff) EvaluateStatement(statement string) (bool, error) { err := validate(statement) if err != nil { return false, err } result, err := evaluate(statement, d) if err != nil { return false, errors.Wrap(err, "error: failed to evaluate") } return result, nil }
diff.go
0.730001
0.449453
diff.go
starcoder
package schedule import ( "bytes" _ "embed" "fmt" "github.com/PuerkitoBio/goquery" "github.com/fogleman/gg" "github.com/golang/freetype/truetype" "github.com/ulstu-schedule/parser/types" "golang.org/x/text/encoding/charmap" "image" "io" "log" "math/rand" "net/http" "strconv" "strings" "sync" "time" ) const ( imgWidth = 1722 imgHeight = 1104 defaultScheduleFontSize = 19 cellWidth = 200 cellHeight = 150 ) //go:embed assets/Arial.ttf var font []byte // weekDays represents string values of the days of week. var weekDays = [7]string{"Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота", "Воскресенье"} // getDocFromURL returns goquery document representation of the page with the schedule. func getDocFromURL(URL string) (*goquery.Document, error) { response, err := http.Get(URL) if err != nil { return nil, err } defer func(Body io.ReadCloser) { err = Body.Close() if err != nil { log.Printf("error occured while closing response body: %s", err.Error()) } }(response.Body) if response.StatusCode > 299 { return nil, &types.StatusCodeError{StatusCode: response.StatusCode, StatusText: http.StatusText(response.StatusCode)} } // convert from windows-1251 to utf-8 decoder := charmap.Windows1251.NewDecoder() reader := decoder.Reader(response.Body) return goquery.NewDocumentFromReader(reader) } // determineLessonType returns types.LessonType representation of a string. func determineLessonType(lessonType string) types.LessonType { lessonType = strings.ToLower(lessonType) switch lessonType { case "лек": return types.Lecture case "пр": return types.Practice default: return types.Laboratory } } // GetWeekAndWeekDayNumbersByDate returns the number of the school week (0 or 1) and the number of the day of the // school week (0, ..., 6) by the string representation of the date. func GetWeekAndWeekDayNumbersByDate(date string) (weekNum int, weekDayNum int, err error) { dateTime, err := getDateTime(date) if err != nil { return } weekNum, weekDayNum = getWeekAndWeekDayNumbersByTime(dateTime) return } // GetWeekAndWeekDayNumbersByWeekDay returns the numbers of the selected day of the week in the current week and the current week number. func GetWeekAndWeekDayNumbersByWeekDay(weekDay string) (int, int) { currWeekNum, _ := GetWeekAndWeekDayNumbers(0) weekDayNum := convertWeekDayToWeekDayIdx(weekDay) return currWeekNum, weekDayNum } // GetWeekAndWeekDayNumbers increases the current time by daysDelta days and returns the numbers of the school week and day of the week. func GetWeekAndWeekDayNumbers(additionalDays int) (int, int) { // getting the current time and adding additionalDays days to it currTimeWithDelta := time.Now().AddDate(0, 0, additionalDays) return getWeekAndWeekDayNumbersByTime(currTimeWithDelta) } // getDateStr increases the current time by daysDelta days and returns the string representation of the new date. func getDateStr(additionalDays int) string { timeWithDelta := time.Now().AddDate(0, 0, additionalDays) return timeWithDelta.Format("02.01.2006") } // convertWeekDayToWeekDayIdx converts the string representation of the day of the week to its index in the array. func convertWeekDayToWeekDayIdx(weekDay string) int { switch strings.ToLower(weekDay) { case "понедельник": return 0 case "вторник": return 1 case "среда": return 2 case "четверг": return 3 case "пятница": return 4 case "суббота": return 5 default: return 6 } } // getWeekAndWeekDayNumbersByTime returns the number of the school week (0 or 1) and the number of the day of the // school week (0, ..., 6) by time. func getWeekAndWeekDayNumbersByTime(time time.Time) (weekNum int, weekDayNum int) { weekDayNum = int(time.Weekday()) - 1 if weekDayNum == -1 { weekDayNum = 6 } _, currWeekNumWithDelta := time.ISOWeek() weekNum = (currWeekNumWithDelta + 1) % 2 return } // getDateTime returns time.Time object from the string representation of the date. func getDateTime(date string) (time.Time, error) { day, month, year, err := getDayMonthYearByDate(date) if err != nil { return time.Time{}, err } return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.Local), nil } // getDayMonthYearByDate returns the day, month, and year extracted from the string representation of the date (Date // format: dd.mm). The year is considered equal to the current one. func getDayMonthYearByDate(date string) (day int, month int, year int, err error) { year = time.Now().Year() dateWithYear := fmt.Sprintf("%s.%d", date, year) if isDateExist(dateWithYear) { dateArray := strings.Split(date, ".") day, _ = strconv.Atoi(dateArray[0]) month, _ = strconv.Atoi(dateArray[1]) } else { err = &types.IncorrectDateError{Date: date} } return } // isDateExist checks if the date matches the format "dd.mm" and exists. func isDateExist(date string) bool { if _, err := time.Parse("02.01.2006", date); err != nil { return false } return true } // IsWeekScheduleEmpty returns true if the week schedule is empty, otherwise - false. func IsWeekScheduleEmpty(week types.Week) bool { for _, d := range week.Days { for _, l := range d.Lessons { if l.SubLessons != nil { return false } } } return true } // IsFullScheduleEmpty returns true if the full schedule is empty, otherwise - false. func IsFullScheduleEmpty(s *types.Schedule) bool { wg := &sync.WaitGroup{} inResultsEmptyCheck := make(chan bool, 2) for i := 0; i < 2; i++ { wg.Add(1) go func(weekNum int, wg *sync.WaitGroup, out chan bool) { defer wg.Done() out <- IsWeekScheduleEmpty(s.Weeks[weekNum]) }(i, wg, inResultsEmptyCheck) } wg.Wait() return <-inResultsEmptyCheck && <-inResultsEmptyCheck } // getRandInt returns a non-negative pseudo-random int. func getRandInt() int { rand.Seed(time.Now().UTC().UnixNano()) return rand.Int() } // highlightRow highlights the row in the table in blue. func highlightRow(row int, dc *gg.Context) { dc.DrawRectangle(4, float64(row-cellHeight), imgWidth-4, cellHeight) dc.SetRGBA255(25, 89, 209, 30) dc.Fill() setDefaultSettings(dc) } // setDefaultSettings sets the default drawing settings. func setDefaultSettings(dc *gg.Context) { dc.Stroke() dc.SetRGB255(0, 0, 0) setFont(defaultScheduleFontSize, dc) } // setFontSize sets the font's size depending on the number of lesson parts (lines) in the table cell. func setFontSize(lessonPartsNum int, dc *gg.Context) { switch { case lessonPartsNum == 6: setFont(16.5, dc) case lessonPartsNum == 7: setFont(16, dc) case lessonPartsNum == 8: setFont(15, dc) case lessonPartsNum == 9: setFont(14, dc) case lessonPartsNum == 10: setFont(13.5, dc) default: setFont(12.5, dc) } } // getWeekScheduleTmplImg returns image.Image based on a byte slice of the embedding png templates. func getWeekScheduleTmplImg(embeddingTmpl []byte) image.Image { weekScheduleTmpl, _, _ := image.Decode(bytes.NewReader(embeddingTmpl)) return weekScheduleTmpl } func setFont(fontSize float64, dc *gg.Context) { fnt, _ := truetype.Parse(font) face := truetype.NewFace(fnt, &truetype.Options{ Size: fontSize, }) dc.SetFontFace(face) }
schedule/utils.go
0.599016
0.430506
utils.go
starcoder
package period import ( "fmt" "math" "strings" ) // used for stages in arithmetic type period64 struct { // always positive values years, months, days, hours, minutes, seconds int64 // true if the period is negative neg bool input string } func (period Period) toPeriod64(input string) *period64 { if period.IsNegative() { return &period64{ years: int64(-period.years), months: int64(-period.months), days: int64(-period.days), hours: int64(-period.hours), minutes: int64(-period.minutes), seconds: int64(-period.seconds), neg: true, input: input, } } return &period64{ years: int64(period.years), months: int64(period.months), days: int64(period.days), hours: int64(period.hours), minutes: int64(period.minutes), seconds: int64(period.seconds), input: input, } } func (p64 *period64) toPeriod() (Period, error) { var f []string if p64.years > math.MaxInt32 { f = append(f, "years") } if p64.months > math.MaxInt32 { f = append(f, "months") } if p64.days > math.MaxInt32 { f = append(f, "days") } if p64.hours > math.MaxInt32 { f = append(f, "hours") } if p64.minutes > math.MaxInt32 { f = append(f, "minutes") } if p64.seconds > math.MaxInt32 { f = append(f, "seconds") } if len(f) > 0 { if p64.input == "" { p64.input = p64.String() } return Period{}, fmt.Errorf("%s: integer overflow occurred in %s", p64.input, strings.Join(f, ",")) } if p64.neg { return Period{ int32(-p64.years), int32(-p64.months), int32(-p64.days), int32(-p64.hours), int32(-p64.minutes), int32(-p64.seconds), }, nil } return Period{ int32(p64.years), int32(p64.months), int32(p64.days), int32(p64.hours), int32(p64.minutes), int32(p64.seconds), }, nil } func (p64 *period64) normalise64(precise bool) *period64 { return p64.rippleUp(precise).moveFractionToRight() } func (p64 *period64) rippleUp(precise bool) *period64 { // remember that the fields are all fixed-point 1E1 p64.minutes += (p64.seconds / 600) * 10 p64.seconds = p64.seconds % 600 p64.hours += (p64.minutes / 600) * 10 p64.minutes = p64.minutes % 600 // 32670-(32670/60)-(32670/3600) = 32760 - 546 - 9.1 = 32204.9 if !precise || p64.hours > 32204 { p64.days += (p64.hours / 240) * 10 p64.hours = p64.hours % 240 } if !precise || p64.days > 32760 { dE6 := p64.days * oneE5 p64.months += (dE6 / daysPerMonthE6) * 10 p64.days = (dE6 % daysPerMonthE6) / oneE5 } p64.years += (p64.months / 120) * 10 p64.months = p64.months % 120 return p64 } // moveFractionToRight attempts to remove fractions in higher-order fields by moving their value to the // next-lower-order field. For example, fractional years become months. func (p64 *period64) moveFractionToRight() *period64 { // remember that the fields are all fixed-point 1E1 y10 := p64.years % 10 if y10 != 0 && (p64.months != 0 || p64.days != 0 || p64.hours != 0 || p64.minutes != 0 || p64.seconds != 0) { p64.months += y10 * 12 p64.years = (p64.years / 10) * 10 } m10 := p64.months % 10 if m10 != 0 && (p64.days != 0 || p64.hours != 0 || p64.minutes != 0 || p64.seconds != 0) { p64.days += (m10 * daysPerMonthE6) / oneE6 p64.months = (p64.months / 10) * 10 } d10 := p64.days % 10 if d10 != 0 && (p64.hours != 0 || p64.minutes != 0 || p64.seconds != 0) { p64.hours += d10 * 24 p64.days = (p64.days / 10) * 10 } hh10 := p64.hours % 10 if hh10 != 0 && (p64.minutes != 0 || p64.seconds != 0) { p64.minutes += hh10 * 60 p64.hours = (p64.hours / 10) * 10 } mm10 := p64.minutes % 10 if mm10 != 0 && p64.seconds != 0 { p64.seconds += mm10 * 60 p64.minutes = (p64.minutes / 10) * 10 } return p64 }
period/period64.go
0.71103
0.634798
period64.go
starcoder
package gocassa import ( "fmt" "reflect" ) func builtinLessThan(k1, k2 interface{}) (bool, error) { if reflect.TypeOf(k1) != reflect.TypeOf(k2) { return false, fmt.Errorf("skiplist/BuiltinLessThan: k1.(%s) and k2.(%s) have different types", reflect.TypeOf(k1).Name(), reflect.TypeOf(k2).Name()) } switch k1 := k1.(type) { case string: return k1 < k2.(string), nil case int64: return k1 < k2.(int64), nil case int32: return k1 < k2.(int32), nil case int16: return k1 < k2.(int16), nil case int8: return k1 < k2.(int8), nil case int: return k1 < k2.(int), nil case float32: return k1 < k2.(float32), nil case float64: return k1 < k2.(float64), nil case uint: return k1 < k2.(uint), nil case uint8: return k1 < k2.(uint8), nil case uint16: return k1 < k2.(uint16), nil case uint32: return k1 < k2.(uint32), nil case uint64: return k1 < k2.(uint64), nil case uintptr: return k1 < k2.(uintptr), nil } return false, fmt.Errorf("skiplist/BuiltinLessThan: unsupported types for k1.(%s) and k2.(%s)", reflect.TypeOf(k1).Name(), reflect.TypeOf(k2).Name()) } func builtinGreaterThan(k1, k2 interface{}) (bool, error) { if reflect.TypeOf(k1) != reflect.TypeOf(k2) { return false, fmt.Errorf("skiplist/BuiltinGreaterThan: k1.(%s) and k2.(%s) have different types", reflect.TypeOf(k1).Name(), reflect.TypeOf(k2).Name()) } switch k1 := k1.(type) { case string: return k1 > k2.(string), nil case int64: return k1 > k2.(int64), nil case int32: return k1 > k2.(int32), nil case int16: return k1 > k2.(int16), nil case int8: return k1 > k2.(int8), nil case int: return k1 > k2.(int), nil case float32: return k1 > k2.(float32), nil case float64: return k1 > k2.(float64), nil case uint: return k1 > k2.(uint), nil case uint8: return k1 > k2.(uint8), nil case uint16: return k1 > k2.(uint16), nil case uint32: return k1 > k2.(uint32), nil case uint64: return k1 > k2.(uint64), nil case uintptr: return k1 > k2.(uintptr), nil } return false, fmt.Errorf("skiplist/BuiltinGreaterThan: unsupported types for k1.(%s) and k2.(%s)", reflect.TypeOf(k1).Name(), reflect.TypeOf(k2).Name()) }
compare.go
0.523177
0.513181
compare.go
starcoder
package glmatrix import ( "fmt" "math" "math/rand" ) // NewVec4 creates a new, empty Vec4 func NewVec4() []float64 { return []float64{0., 0., 0., 0.} } // Vec4Create creates a new Vec4 initialized with values from an existing vector func Vec4Create() []float64 { return NewVec4() } // Vec4Clone creates a new Vec4 initialized with the given values func Vec4Clone(a []float64) []float64 { return []float64{a[0], a[1], a[2], a[3]} } // Vec4FromValues creates a new Vec4 initialized with the given values func Vec4FromValues(x, y, z, w float64) []float64 { return []float64{x, y, z, w} } // Vec4Copy copy the values from one Vec4 to another func Vec4Copy(out, a []float64) []float64 { out[0] = a[0] out[1] = a[1] out[2] = a[2] out[3] = a[3] return out } // Vec4Set set the components of a vec4 to the given values func Vec4Set(out []float64, x, y, z, w float64) []float64 { out[0] = x out[1] = y out[2] = z out[3] = w return out } // Vec4Add adds two Vec4's func Vec4Add(out, a, b []float64) []float64 { out[0] = a[0] + b[0] out[1] = a[1] + b[1] out[2] = a[2] + b[2] out[3] = a[3] + b[3] return out } // Vec4Subtract subtracts vector b from vector a func Vec4Subtract(out, a, b []float64) []float64 { out[0] = a[0] - b[0] out[1] = a[1] - b[1] out[2] = a[2] - b[2] out[3] = a[3] - b[3] return out } // Vec4Multiply multiplies two Vec4's func Vec4Multiply(out, a, b []float64) []float64 { out[0] = a[0] * b[0] out[1] = a[1] * b[1] out[2] = a[2] * b[2] out[3] = a[3] * b[3] return out } // Vec4Divide divides two Vec4's func Vec4Divide(out, a, b []float64) []float64 { out[0] = a[0] / b[0] out[1] = a[1] / b[1] out[2] = a[2] / b[2] out[3] = a[3] / b[3] return out } // Vec4Ceil math.ceil the components of a vec4 func Vec4Ceil(out, a []float64) []float64 { out[0] = math.Ceil(a[0]) out[1] = math.Ceil(a[1]) out[2] = math.Ceil(a[2]) out[3] = math.Ceil(a[3]) return out } // Vec4Floor math.floor the components of a vec4 func Vec4Floor(out, a []float64) []float64 { out[0] = math.Floor(a[0]) out[1] = math.Floor(a[1]) out[2] = math.Floor(a[2]) out[3] = math.Floor(a[3]) return out } // Vec4Min returns the minimum of two Vec4's func Vec4Min(out, a, b []float64) []float64 { out[0] = math.Min(a[0], b[0]) out[1] = math.Min(a[1], b[1]) out[2] = math.Min(a[2], b[2]) out[3] = math.Min(a[3], b[3]) return out } // Vec4Max returns the maximum of two Vec4's func Vec4Max(out, a, b []float64) []float64 { out[0] = math.Max(a[0], b[0]) out[1] = math.Max(a[1], b[1]) out[2] = math.Max(a[2], b[2]) out[3] = math.Max(a[3], b[3]) return out } // Vec4Round math.round the components of a vec4 func Vec4Round(out, a []float64) []float64 { out[0] = math.Round(a[0]) out[1] = math.Round(a[1]) out[2] = math.Round(a[2]) out[3] = math.Round(a[3]) return out } // Vec4Scale scales a vec4 by a scalar number func Vec4Scale(out, a []float64, scale float64) []float64 { out[0] = a[0] * scale out[1] = a[1] * scale out[2] = a[2] * scale out[3] = a[3] * scale return out } // Vec4ScaleAndAdd adds two Vec4's after scaling the second operand by a scalar value func Vec4ScaleAndAdd(out, a, b []float64, scale float64) []float64 { out[0] = a[0] + b[0]*scale out[1] = a[1] + b[1]*scale out[2] = a[2] + b[2]*scale out[3] = a[3] + b[3]*scale return out } // Vec4Distance calculates the euclidian distance between two Vec4's func Vec4Distance(a, b []float64) float64 { x := b[0] - a[0] y := b[1] - a[1] z := b[2] - a[2] w := b[3] - a[3] return hypot(x, y, z, w) } // Vec4SquaredDistance calculates the squared euclidian distance between two Vec4's func Vec4SquaredDistance(a, b []float64) float64 { x := b[0] - a[0] y := b[1] - a[1] z := b[2] - a[2] w := b[3] - a[3] return x*x + y*y + z*z + w*w } // Vec4Length calculates the length of a vec4 func Vec4Length(out []float64) float64 { x := out[0] y := out[1] z := out[2] w := out[3] return hypot(x, y, z, w) } // Vec4SquaredLength calculates the squared length of a vec4 func Vec4SquaredLength(out []float64) float64 { x := out[0] y := out[1] z := out[2] w := out[3] return x*x + y*y + z*z + w*w } // Vec4Negate negates the components of a vec4 func Vec4Negate(out, a []float64) []float64 { out[0] = -a[0] out[1] = -a[1] out[2] = -a[2] out[3] = -a[3] return out } // Vec4Inverse returns the inverse of the components of a vec4 func Vec4Inverse(out, a []float64) []float64 { out[0] = 1. / a[0] out[1] = 1. / a[1] out[2] = 1. / a[2] out[3] = 1. / a[3] return out } // Vec4Normalize normalize a vec4 func Vec4Normalize(out, a []float64) []float64 { x := a[0] y := a[1] z := a[2] w := a[3] len := x*x + y*y + z*z + w*w if 0 < len { len = 1. / math.Sqrt(len) } out[0] = a[0] * len out[1] = a[1] * len out[2] = a[2] * len out[3] = a[3] * len return out } // Vec4Dot calculates the dot product of two Vec4's func Vec4Dot(a, b []float64) float64 { return a[0]*b[0] + a[1]*b[1] + a[2]*b[2] + a[3]*b[3] } // Vec4Cross computes the cross product of two Vec4's func Vec4Cross(out, u, v, w []float64) []float64 { A := v[0]*w[1] - v[1]*w[0] B := v[0]*w[2] - v[2]*w[0] C := v[0]*w[3] - v[3]*w[0] D := v[1]*w[2] - v[2]*w[1] E := v[1]*w[3] - v[3]*w[1] F := v[2]*w[3] - v[3]*w[2] G := u[0] H := u[1] I := u[2] J := u[3] out[0] = H*F - I*E + J*D out[1] = -(G * F) + I*C - J*B out[2] = G*E - H*C + J*A out[3] = -(G * D) + H*B - I*A return out } // Vec4Lerp performs a linear interpolation between two Vec4's func Vec4Lerp(out, a, b []float64, t float64) []float64 { ax := a[0] ay := a[1] az := a[2] aw := a[3] out[0] = ax + t*(b[0]-ax) out[1] = ay + t*(b[1]-ay) out[2] = az + t*(b[2]-az) out[3] = aw + t*(b[3]-aw) return out } // Vec4Random generates a random vector with the given scale func Vec4Random(out []float64, scale float64) []float64 { if scale == 0. { scale = 1. } var v1, v2, v3, v4, s1, s2 float64 for { v1 = rand.Float64()*2 - 1 v2 = rand.Float64()*2 - 1 s1 = v1*v1 + v2*v2 if s1 < 1 { break } } for { v3 = rand.Float64()*2 - 1 v4 = rand.Float64()*2 - 1 s2 = v3*v3 + v4*v4 if s2 < 1 { break } } d := math.Sqrt((1 - s1) / s2) out[0] = scale * v1 out[1] = scale * v2 out[2] = scale * v3 * d out[3] = scale * v4 * d return out } // Vec4TransformMat4 transforms the vec4 with a mat4 func Vec4TransformMat4(out, a, m []float64) []float64 { x := a[0] y := a[1] z := a[2] w := a[3] out[0] = (m[0]*x + m[4]*y + m[8]*z + m[12]) / w out[1] = (m[1]*x + m[5]*y + m[9]*z + m[13]) / w out[2] = (m[2]*x + m[6]*y + m[10]*z + m[14]) / w out[3] = (m[3]*x + m[7]*y + m[11]*z + m[15]) / w return out } // Vec4TransformQuat transforms the vec4 with a quat func Vec4TransformQuat(out, a, q []float64) []float64 { qx := q[0] qy := q[1] qz := q[2] qw := q[3] x := a[0] y := a[1] z := a[2] ix := qw*x + qy*z - qz*y iy := qw*y + qy*x - qz*z iz := qw*z + qy*y - qz*x iw := -qw*x - qy*y - qz*z out[0] = ix*qw + iw*-qx + iy*-qz - iz*-qy out[1] = iy*qw + iw*-qy + iz*-qx - ix*-qz out[2] = iz*qw + iw*-qz + ix*-qy - iy*-qx out[3] = a[3] return out } // Vec4Zero set the components of a vec4 to zero func Vec4Zero(out []float64) []float64 { out[0] = 0. out[1] = 0. out[2] = 0. out[3] = 0. return out } // Vec4Str returns a string representation of a vector func Vec4Str(a []float64) string { return fmt.Sprintf("vec4(%v, %v, %v, %v)", a[0], a[1], a[2], a[3]) } // Vec4ExactEquals returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) func Vec4ExactEquals(a, b []float64) bool { return a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3] } // Vec4Equals returns whether or not the vectors have approximately the same elements in the same position. func Vec4Equals(a, b []float64) bool { return equals(a[0], b[0]) && equals(a[1], b[1]) && equals(a[2], b[2]) && equals(a[3], b[3]) } // Vec4Len alias for Vec4Length var Vec4Len = Vec4Length // Vec4Sub alias for Vec4Subtract var Vec4Sub = Vec4Subtract // Vec4Mul alias for Vec4Multiply var Vec4Mul = Vec4Multiply // Vec4Div alias for Vec4Divide var Vec4Div = Vec4Divide // Vec4Dist alias for Vec4Distance var Vec4Dist = Vec4Distance // Vec4SqrDist alias for Vec4SquaredDistance var Vec4SqrDist = Vec4SquaredDistance // Vec4SqrLen alias for Vec4SquaredLength var Vec4SqrLen = Vec4SquaredLength // Vec4ForEach perform some operation over an array of Vec4s. func Vec4ForEach(a []float64, stride, offset, count int, fn func([]float64, []float64, []float64), arg []float64) []float64 { if stride <= 0 { stride = 4 } if offset <= 0 { offset = 0 } var l int if 0 < count { l = int(math.Min(float64(count*stride+offset), float64(len(a)))) } else { l = len(a) } for i := offset; i < l; i += stride { vec := []float64{a[i], a[i+1], a[i+2], a[i+3]} fn(vec, vec, arg) a[i] = vec[0] a[i+1] = vec[1] a[i+2] = vec[2] a[i+3] = vec[3] } return a }
vec4.go
0.854779
0.705441
vec4.go
starcoder
package fantree import ( "fmt" "sync" ) //TreeNode is the node Of tree. type TreeNode struct { Name string //Name of TreeNode should equal to the node Value *Node //Value of TreeNode is a pointer to the Node Previous []*TreeNode // A TreeNode may have many previous Next []*TreeNode // A TreeNode may have many next too. } //NewTreeNode construct a TreeNode based on 1 node pointer func NewTreeNode(nd *Node) *TreeNode { treeNode := new(TreeNode) treeNode.Name = nd.Name treeNode.Value = nd treeNode.Previous = []*TreeNode{} treeNode.Next = []*TreeNode{} return treeNode } func findTreeNodeInList(node *TreeNode, treeNodeList []*TreeNode) bool { for _, n := range treeNodeList { if node == n { return true } } return false } //Forest is structure to store a forest type Forest struct { NodePool map[string]*TreeNode //NodePool store all TreeNodes of forest in a map Roots []*TreeNode //Roots is slice pointers to mark the roots in forest. } //NewForest construct a new forest based on a list of Node func NewForest(nodes []*Node) (forest *Forest, err error) { forest = new(Forest) forest.setupForestNodePool(nodes) err = forest.setupForest() return forest, err } func (frt *Forest) setupForestNodePool(nodeList []*Node) { frt.NodePool = make(map[string]*TreeNode) //store all node in a map for _, node := range nodeList { frt.NodePool[node.Name] = NewTreeNode(node) } } func (frt *Forest) setupForest() error { //setup the tree for _, treeNode := range frt.NodePool { pre := treeNode.Value.PreName next := treeNode.Value.NextName if preNode, ok := frt.NodePool[pre]; ok { if !findTreeNodeInList(preNode, treeNode.Previous) { treeNode.Previous = append(treeNode.Previous, preNode) } if !findTreeNodeInList(treeNode, preNode.Next) { preNode.Next = append(preNode.Next, treeNode) } } if nextNode, ok := frt.NodePool[next]; ok { if !findTreeNodeInList(nextNode, treeNode.Next) { treeNode.Next = append(treeNode.Next, nextNode) } if !findTreeNodeInList(treeNode, nextNode.Previous) { nextNode.Previous = append(nextNode.Previous, treeNode) } } } return frt.findRoots() } func (frt *Forest) findRoots() error { hCount := 0 for _, node := range frt.NodePool { if len(node.Previous) == 0 { hCount++ frt.Roots = append(frt.Roots, node) } } if hCount == 0 { return fmt.Errorf("Do not find a root!") } else { return nil } } func printForest(roots []*TreeNode) { for _, root := range roots { fmt.Println("Name:", root.Name) if len(root.Next) > 0 { printForest(root.Next) } } } //Print will print the node name of forest func (frt *Forest) Print() { if len(frt.Roots) == 0 { fmt.Println("There is still no tree in forest") return } printForest(frt.Roots) } //GetTrees return all roots in the forest func (frt *Forest) GetTrees() []*TreeNode { return frt.Roots } //GetTree return the specified tree(through the name of root node) in the forest. // If there isn't a tree with the name in the forest an error will be returned. func (frt *Forest) GetTree(name string) (root *TreeNode, err error) { for _, root = range frt.Roots { if root.Name == name { return root, nil } } return nil, fmt.Errorf("Do not find the tree with a root which name is:[%s]", name) } // Pipeline launch goroutines for every nodes in the forest to execute the node's handler concurrently. // It will Set up a wait group to sync the execution of all nodes. func (frt *Forest) Pipeline(metadata interface{}) error { var wg sync.WaitGroup for _, tp := range frt.NodePool { node := tp.Value wg.Add(1) //fan-in the previous channels for the nodes inC := make(chan chan interface{}, len(tp.Previous)) if len(tp.Previous) > 0 { for _, pre := range tp.Previous { inC <- pre.Value.OutC } } close(inC) //start the goroutine to execute node handler go func() { node.Cmd.Handler(node, inC, node.OutC) wg.Done() }() } //wait all goroutine done // TODO: right now just implement the way to sync data and semaphore between goroutines, need a way to // notify the downstream goroutines cancel when errors happened on upstream. wg.Wait() return nil } func treeToLink(root *TreeNode) (head *LinkNode, err error) { if root == nil || root.Value == nil { return nil, fmt.Errorf("Found a bad node[%v]", *root) } link := NewLinkNode(root.Value) if len(root.Next) > 0 { next, err := forestToLink(root.Next) if err != nil { return nil, err } link.Next = next } return link, nil } func forestToLink(roots []*TreeNode) (head *LinkNode, err error) { links := []*LinkNode{} for _, root := range roots { link, err := treeToLink(root) if err != nil { return nil, err } links = append(links, link) } if len(links) == 0 { return nil, fmt.Errorf("Empty link") } return MergeLink(links) } //ToLink will convert a forest to a single link. // The rules of conversion include: //1. Forest and Tree will be unfolded to multiple links at first //2. The final link is merged from links. func (frt *Forest) ToLink() (head *LinkNode, err error) { return forestToLink(frt.Roots) }
forest.go
0.551332
0.520192
forest.go
starcoder
package trader import ( "errors" "fmt" "strings" "github.com/processout/decimal" ) // CurrencyCode represents a currency code in the norm ISO 4217 type CurrencyCode string // format sets the CurrencyCode to the right format func (c CurrencyCode) format() CurrencyCode { return CurrencyCode(strings.ToUpper(string(c))) } // String to implement Stringer interface func (c CurrencyCode) String() string { return string(c.format()) } // Currency represents a currency and its value relative to the dollar type Currency struct { // Code is the ISO 4217 code of the currency Code CurrencyCode `json:"code"` // Value is the value of the currency, relative to the base currency Value decimal.Decimal `json:"value"` } // emptyCurrency represents an empty currency var emptyCurrency = Currency{} // NewCurrency creates a new Currency structure, but returns an error if the // currency code is not part of ISO 4217 func NewCurrency(code CurrencyCode, v decimal.Decimal) (Currency, error) { // Verify code: if ok := code.Verify(); !ok { return emptyCurrency, errors.New("Currency `" + code.String() + "' does not exist") } return Currency{ Code: code.format(), Value: v, }, nil } // Currencies represents a slice of Currencies type Currencies []Currency // Find finds a Currency within the Currencies slice from the given // currency code, or returns an error if the currency code was not found func (c Currencies) Find(code CurrencyCode) (Currency, error) { for _, v := range c { if v.Is(code) { return v, nil } } return emptyCurrency, fmt.Errorf("The currency code %s could not be found.", code) } // Is returns true if the given code is the code of the Currency, false // otherwise func (c Currency) Is(code CurrencyCode) bool { return c.Code == code.format() } // DecimalPlaces returns the number of decimal places a currency has // e.g. for USD there are 2 ($12.25), for JPY there are 0 (5412) func (c Currency) DecimalPlaces() int { // Here we just test for the currencies that don't have 2 decimal places return c.Code.Information().Places }
currency.go
0.845177
0.415907
currency.go
starcoder
package mom // MedianOfMedians is used as a pivot selection in the quickselect algorithm func MedianOfMedians(data []int, left, right, nTh, groupSize int) int { for { // get median pivot pivoIndex := getMedianPivot(data, left, right, groupSize) // do partitioning pivoIndex = partition(data, left, right-1, pivoIndex) if nTh == pivoIndex { return nTh // find the position of nTh element } else if nTh < pivoIndex { right = pivoIndex // now, find left side } else { left = pivoIndex + 1 // now, find right side } } } // get median of medians pivot by iteration func getMedianPivot(data []int, left, right, groupSize int) int { for { size := right - left if size < groupSize { return partitionN(data, left, right, groupSize) } // index is increased by a group size for index := left; index < right; index += groupSize { subRight := index + groupSize // check boundary if subRight > right { subRight = right } // get median median := partitionN(data, index, subRight, groupSize) // move each median to the front of container data[median], data[left+(index-left)/groupSize] = data[left+(index-left)/groupSize], data[median] } // update the end of medians right = left + (right-left)/groupSize } } // partiton data into two parts (left, right), those less than a certain element func partition(data []int, left, right, pivotIndex int) int { pivotValue := data[pivotIndex] // move pivot to end data[pivotIndex], data[right] = data[right], data[pivotIndex] // partition lowindex := left for highIndex := left; highIndex < right; highIndex++ { if data[highIndex] < pivotValue { data[highIndex], data[lowindex] = data[lowindex], data[highIndex] lowindex++ } } // move pivot to its final place data[lowindex], data[right] = data[right], data[lowindex] return lowindex } // sort if data is lower than group size (generally 5) func partitionN(data []int, left, right, groupSize int) int { // insertion sort for standardIndex := left + 1; standardIndex < right; standardIndex++ { for comparedIndex := standardIndex - 1; comparedIndex >= left; comparedIndex-- { if data[comparedIndex+1] < data[comparedIndex] { data[comparedIndex+1], data[comparedIndex] = data[comparedIndex], data[comparedIndex+1] } } } // get median index medianindex := left + groupSize/2 // check rightside boundary if medianindex >= right { medianindex = right - 1 } return medianindex }
codes/mom/mom.go
0.751375
0.644896
mom.go
starcoder
package mat64 import ( "bitbucket.org/zombiezen/math3/vec64" "fmt" "math" ) // Matrix holds a 4x4 matrix. Each vector is a column of the matrix. type Matrix [4]vec64.Vector // Identity can be multiplied by another matrix to produce the same matrix. var Identity = Matrix{ {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}, } func (m Matrix) String() string { var result string for i, row := range m.Transpose() { format := "| %5.2f %5.2f %5.2f %5.2f |\n" switch i { case 0: format = "/ %5.2f %5.2f %5.2f %5.2f \\\n" case len(m) - 1: format = "\\ %5.2f %5.2f %5.2f %5.2f /" } result += fmt.Sprintf(format, row[0], row[1], row[2], row[3]) } return result } // Transpose performs a matrix transposition. func (m Matrix) Transpose() Matrix { for i := 0; i < 3; i++ { for j := i + 1; j < 4; j++ { m[i][j], m[j][i] = m[j][i], m[i][j] } } return m } // Translate post-multiplies a translation by v and returns the result. func (m Matrix) Translate(v vec64.Vector) Matrix { return Mul(m, Matrix{ {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {v[0], v[1], v[2], 1}, }) } // Rotate post-multiplies a rotation around an axis. The angle is in radians and // the axis will be normalized. func (m Matrix) Rotate(angle float64, axis vec64.Vector) Matrix { axis = axis.Normalize() x, y, z := axis[0], axis[1], axis[2] sin, cos := math.Sin(angle), math.Cos(angle) return Mul(m, Matrix{ {cos + x*x*(1-cos), y*x*(1-cos) + z*sin, z*x*(1-cos) - y*sin, 0}, {x*y*(1-cos) - z*sin, cos + y*y*(1-cos), z*y*(1-cos) + x*sin, 0}, {x*z*(1-cos) + y*sin, y*z*(1-cos) - x*sin, cos + z*z*(1-cos), 0}, {0, 0, 0, 1}, }) } // Scale post-multiplies a scale and returns the result. func (m Matrix) Scale(scale vec64.Vector) Matrix { return Mul(m, Matrix{ {scale[0], 0, 0, 0}, {0, scale[1], 0, 0}, {0, 0, scale[2], 0}, {0, 0, 0, 1}, }) } // Mul multiplies m1 by m2. func Mul(m1, m2 Matrix) Matrix { var result Matrix m1 = m1.Transpose() for i := 0; i < 4; i++ { for j := 0; j < 4; j++ { result[i][j] = vec64.Dot(m1[j], m2[i]) } } return result } // Transform multiplies m by u. func (m Matrix) Transform(u vec64.Vector) (v vec64.Vector) { for i := range v { for j := range u { v[i] += m[i][j] * u[j] } } return }
mat64/matrix.go
0.791297
0.658884
matrix.go
starcoder
// The image package implements a basic 2-D image library. package image // An Image is a rectangular grid of Colors drawn from a ColorModel. type Image interface { ColorModel() ColorModel; Width() int; Height() int; // At(0, 0) returns the upper-left pixel of the grid. // At(Width()-1, Height()-1) returns the lower-right pixel. At(x, y int) Color; } // An RGBA is an in-memory image backed by a 2-D slice of RGBAColor values. type RGBA struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. Pixel [][]RGBAColor; } func (p *RGBA) ColorModel() ColorModel { return RGBAColorModel; } func (p *RGBA) Width() int { if len(p.Pixel) == 0 { return 0; } return len(p.Pixel[0]); } func (p *RGBA) Height() int { return len(p.Pixel); } func (p *RGBA) At(x, y int) Color { return p.Pixel[y][x]; } func (p *RGBA) Set(x, y int, c Color) { p.Pixel[y][x] = toRGBAColor(c).(RGBAColor); } // NewRGBA returns a new RGBA with the given width and height. func NewRGBA(w, h int) *RGBA { pixel := make([][]RGBAColor, h); for y := 0; y < int(h); y++ { pixel[y] = make([]RGBAColor, w); } return &RGBA{pixel}; } // An RGBA64 is an in-memory image backed by a 2-D slice of RGBA64Color values. type RGBA64 struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. Pixel [][]RGBA64Color; } func (p *RGBA64) ColorModel() ColorModel { return RGBA64ColorModel; } func (p *RGBA64) Width() int { if len(p.Pixel) == 0 { return 0; } return len(p.Pixel[0]); } func (p *RGBA64) Height() int { return len(p.Pixel); } func (p *RGBA64) At(x, y int) Color { return p.Pixel[y][x]; } func (p *RGBA64) Set(x, y int, c Color) { p.Pixel[y][x] = toRGBA64Color(c).(RGBA64Color); } // NewRGBA64 returns a new RGBA64 with the given width and height. func NewRGBA64(w, h int) *RGBA64 { pixel := make([][]RGBA64Color, h); for y := 0; y < int(h); y++ { pixel[y] = make([]RGBA64Color, w); } return &RGBA64{pixel}; } // A NRGBA is an in-memory image backed by a 2-D slice of NRGBAColor values. type NRGBA struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. Pixel [][]NRGBAColor; } func (p *NRGBA) ColorModel() ColorModel { return NRGBAColorModel; } func (p *NRGBA) Width() int { if len(p.Pixel) == 0 { return 0; } return len(p.Pixel[0]); } func (p *NRGBA) Height() int { return len(p.Pixel); } func (p *NRGBA) At(x, y int) Color { return p.Pixel[y][x]; } func (p *NRGBA) Set(x, y int, c Color) { p.Pixel[y][x] = toNRGBAColor(c).(NRGBAColor); } // NewNRGBA returns a new NRGBA with the given width and height. func NewNRGBA(w, h int) *NRGBA { pixel := make([][]NRGBAColor, h); for y := 0; y < int(h); y++ { pixel[y] = make([]NRGBAColor, w); } return &NRGBA{pixel}; } // A NRGBA64 is an in-memory image backed by a 2-D slice of NRGBA64Color values. type NRGBA64 struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. Pixel [][]NRGBA64Color; } func (p *NRGBA64) ColorModel() ColorModel { return NRGBA64ColorModel; } func (p *NRGBA64) Width() int { if len(p.Pixel) == 0 { return 0; } return len(p.Pixel[0]); } func (p *NRGBA64) Height() int { return len(p.Pixel); } func (p *NRGBA64) At(x, y int) Color { return p.Pixel[y][x]; } func (p *NRGBA64) Set(x, y int, c Color) { p.Pixel[y][x] = toNRGBA64Color(c).(NRGBA64Color); } // NewNRGBA64 returns a new NRGBA64 with the given width and height. func NewNRGBA64(w, h int) *NRGBA64 { pixel := make([][]NRGBA64Color, h); for y := 0; y < int(h); y++ { pixel[y] = make([]NRGBA64Color, w); } return &NRGBA64{pixel}; } // A PalettedColorModel represents a fixed palette of colors. type PalettedColorModel []Color func diff(a, b uint32) uint32 { if a > b { return a-b; } return b-a; } // Convert returns the palette color closest to c in Euclidean R,G,B space. func (p PalettedColorModel) Convert(c Color) Color { if len(p) == 0 { return nil; } // TODO(nigeltao): Revisit the "pick the palette color which minimizes sum-squared-difference" // algorithm when the premultiplied vs unpremultiplied issue is resolved. // Currently, we only compare the R, G and B values, and ignore A. cr, cg, cb, _ := c.RGBA(); // Shift by 17 bits to avoid potential uint32 overflow in sum-squared-difference. cr >>= 17; cg >>= 17; cb >>= 17; result := Color(nil); bestSSD := uint32(1<<32 - 1); for _, v := range p { vr, vg, vb, _ := v.RGBA(); vr >>= 17; vg >>= 17; vb >>= 17; dr, dg, db := diff(cr, vr), diff(cg, vg), diff(cb, vb); ssd := (dr*dr)+(dg*dg)+(db*db); if ssd < bestSSD { bestSSD = ssd; result = v; } } return result; } // A Paletted is an in-memory image backed by a 2-D slice of uint8 values and a PalettedColorModel. type Paletted struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Palette[Pixel[y][x]]. Pixel [][]uint8; Palette PalettedColorModel; } func (p *Paletted) ColorModel() ColorModel { return p.Palette; } func (p *Paletted) Width() int { if len(p.Pixel) == 0 { return 0; } return len(p.Pixel[0]); } func (p *Paletted) Height() int { return len(p.Pixel); } func (p *Paletted) At(x, y int) Color { return p.Palette[p.Pixel[y][x]]; } func (p *Paletted) ColorIndexAt(x, y int) uint8 { return p.Pixel[y][x]; } func (p *Paletted) SetColorIndex(x, y int, index uint8) { p.Pixel[y][x] = index; } // NewPaletted returns a new Paletted with the given width, height and palette. func NewPaletted(w, h int, m PalettedColorModel) *Paletted { pixel := make([][]uint8, h); for y := 0; y < int(h); y++ { pixel[y] = make([]uint8, w); } return &Paletted{pixel, m}; }
src/pkg/image/image.go
0.888451
0.717358
image.go
starcoder
package bitbucket import ( "time" ) // GetDownloadCount returns the DownloadCount field if it's non-nil, zero value otherwise. func (a *Artifact) GetDownloadCount() int64 { if a == nil || a.DownloadCount == nil { return 0 } return *a.DownloadCount } // GetLinks returns the Links field. func (a *Artifact) GetLinks() *ArtifactFileLinks { if a == nil { return nil } return a.Links } // GetName returns the Name field if it's non-nil, zero value otherwise. func (a *Artifact) GetName() string { if a == nil || a.Name == nil { return "" } return *a.Name } // GetSize returns the Size field if it's non-nil, zero value otherwise. func (a *Artifact) GetSize() int64 { if a == nil || a.Size == nil { return 0 } return *a.Size } // GetType returns the Type field if it's non-nil, zero value otherwise. func (a *Artifact) GetType() string { if a == nil || a.Type == nil { return "" } return *a.Type } // GetUser returns the User field. func (a *Artifact) GetUser() *User { if a == nil { return nil } return a.User } // GetSelf returns the Self field. func (a *ArtifactFileLinks) GetSelf() *Link { if a == nil { return nil } return a.Self } // HasValues checks if Artifacts has any Values. func (a *Artifacts) HasValues() bool { if a == nil || a.Values == nil { return false } if len(a.Values) == 0 { return false } return true } // GetBranch returns the Branch field. func (b *BMBranch) GetBranch() *Ref { if b == nil { return nil } return b.Branch } // GetIsValid returns the IsValid field if it's non-nil, zero value otherwise. func (b *BMBranch) GetIsValid() bool { if b == nil || b.IsValid == nil { return false } return *b.IsValid } // GetName returns the Name field if it's non-nil, zero value otherwise. func (b *BMBranch) GetName() string { if b == nil || b.Name == nil { return "" } return *b.Name } // GetUseMainbranch returns the UseMainbranch field if it's non-nil, zero value otherwise. func (b *BMBranch) GetUseMainbranch() bool { if b == nil || b.UseMainbranch == nil { return false } return *b.UseMainbranch } // GetEnabled returns the Enabled field if it's non-nil, zero value otherwise. func (b *BMBranchType) GetEnabled() bool { if b == nil || b.Enabled == nil { return false } return *b.Enabled } // GetKind returns the Kind field if it's non-nil, zero value otherwise. func (b *BMBranchType) GetKind() string { if b == nil || b.Kind == nil { return "" } return *b.Kind } // GetPrefix returns the Prefix field if it's non-nil, zero value otherwise. func (b *BMBranchType) GetPrefix() string { if b == nil || b.Prefix == nil { return "" } return *b.Prefix } // GetEnabled returns the Enabled field if it's non-nil, zero value otherwise. func (b *BMBranchUpdateOpts) GetEnabled() bool { if b == nil || b.Enabled == nil { return false } return *b.Enabled } // GetName returns the Name field if it's non-nil, zero value otherwise. func (b *BMBranchUpdateOpts) GetName() string { if b == nil || b.Name == nil { return "" } return *b.Name } // GetUseMainbranch returns the UseMainbranch field if it's non-nil, zero value otherwise. func (b *BMBranchUpdateOpts) GetUseMainbranch() bool { if b == nil || b.UseMainbranch == nil { return false } return *b.UseMainbranch } // GetSelf returns the Self field. func (b *BMLinks) GetSelf() *Link { if b == nil { return nil } return b.Self } // HasBranchTypes checks if BMRequest has any BranchTypes. func (b *BMRequest) HasBranchTypes() bool { if b == nil || b.BranchTypes == nil { return false } if len(b.BranchTypes) == 0 { return false } return true } // GetDevelopment returns the Development field. func (b *BMRequest) GetDevelopment() *BMBranchUpdateOpts { if b == nil { return nil } return b.Development } // GetProduction returns the Production field. func (b *BMRequest) GetProduction() *BMBranchUpdateOpts { if b == nil { return nil } return b.Production } // GetName returns the Name field if it's non-nil, zero value otherwise. func (b *Branch) GetName() string { if b == nil || b.Name == nil { return "" } return *b.Name } // HasBranchTypes checks if BranchingModel has any BranchTypes. func (b *BranchingModel) HasBranchTypes() bool { if b == nil || b.BranchTypes == nil { return false } if len(b.BranchTypes) == 0 { return false } return true } // GetDevelopment returns the Development field. func (b *BranchingModel) GetDevelopment() *BMBranch { if b == nil { return nil } return b.Development } // GetLinks returns the Links field. func (b *BranchingModel) GetLinks() *BMLinks { if b == nil { return nil } return b.Links } // GetProduction returns the Production field. func (b *BranchingModel) GetProduction() *BMBranch { if b == nil { return nil } return b.Production } // GetType returns the Type field if it's non-nil, zero value otherwise. func (b *BranchingModel) GetType() string { if b == nil || b.Type == nil { return "" } return *b.Type } // GetBranchMatchKind returns the BranchMatchKind field if it's non-nil, zero value otherwise. func (b *BranchRestriction) GetBranchMatchKind() string { if b == nil || b.BranchMatchKind == nil { return "" } return *b.BranchMatchKind } // GetID returns the ID field if it's non-nil, zero value otherwise. func (b *BranchRestriction) GetID() int64 { if b == nil || b.ID == nil { return 0 } return *b.ID } // GetKind returns the Kind field if it's non-nil, zero value otherwise. func (b *BranchRestriction) GetKind() string { if b == nil || b.Kind == nil { return "" } return *b.Kind } // GetLinks returns the Links field. func (b *BranchRestriction) GetLinks() *BRLinks { if b == nil { return nil } return b.Links } // GetPattern returns the Pattern field if it's non-nil, zero value otherwise. func (b *BranchRestriction) GetPattern() string { if b == nil || b.Pattern == nil { return "" } return *b.Pattern } // GetType returns the Type field if it's non-nil, zero value otherwise. func (b *BranchRestriction) GetType() string { if b == nil || b.Type == nil { return "" } return *b.Type } // HasUsers checks if BranchRestriction has any Users. func (b *BranchRestriction) HasUsers() bool { if b == nil || b.Users == nil { return false } if len(b.Users) == 0 { return false } return true } // GetValue returns the Value field if it's non-nil, zero value otherwise. func (b *BranchRestriction) GetValue() int64 { if b == nil || b.Value == nil { return 0 } return *b.Value } // HasValues checks if BranchRestrictions has any Values. func (b *BranchRestrictions) HasValues() bool { if b == nil || b.Values == nil { return false } if len(b.Values) == 0 { return false } return true } // GetSelf returns the Self field. func (b *BRLinks) GetSelf() *Link { if b == nil { return nil } return b.Self } // GetBranchMatchKind returns the BranchMatchKind field if it's non-nil, zero value otherwise. func (b *BRRequest) GetBranchMatchKind() string { if b == nil || b.BranchMatchKind == nil { return "" } return *b.BranchMatchKind } // GetBranchType returns the BranchType field if it's non-nil, zero value otherwise. func (b *BRRequest) GetBranchType() string { if b == nil || b.BranchType == nil { return "" } return *b.BranchType } // GetKind returns the Kind field if it's non-nil, zero value otherwise. func (b *BRRequest) GetKind() string { if b == nil || b.Kind == nil { return "" } return *b.Kind } // GetPattern returns the Pattern field if it's non-nil, zero value otherwise. func (b *BRRequest) GetPattern() string { if b == nil || b.Pattern == nil { return "" } return *b.Pattern } // GetHTML returns the HTML field. func (c *CCLinks) GetHTML() *Link { if c == nil { return nil } return c.HTML } // GetSelf returns the Self field. func (c *CCLinks) GetSelf() *Link { if c == nil { return nil } return c.Self } // GetLinks returns the Links field. func (c *CodeFile) GetLinks() *SearchCodeFileLinks { if c == nil { return nil } return c.Links } // GetPath returns the Path field if it's non-nil, zero value otherwise. func (c *CodeFile) GetPath() string { if c == nil || c.Path == nil { return "" } return *c.Path } // GetType returns the Type field if it's non-nil, zero value otherwise. func (c *CodeFile) GetType() string { if c == nil || c.Type == nil { return "" } return *c.Type } // GetContent returns the Content field. func (c *Comment) GetContent() *Content { if c == nil { return nil } return c.Content } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (c *Comment) GetCreatedOn() time.Time { if c == nil || c.CreatedOn == nil { return time.Time{} } return *c.CreatedOn } // GetID returns the ID field if it's non-nil, zero value otherwise. func (c *Comment) GetID() int64 { if c == nil || c.ID == nil { return 0 } return *c.ID } // GetLinks returns the Links field. func (c *Comment) GetLinks() *CommentLinks { if c == nil { return nil } return c.Links } // GetType returns the Type field if it's non-nil, zero value otherwise. func (c *Comment) GetType() string { if c == nil || c.Type == nil { return "" } return *c.Type } // GetUpdatedOn returns the UpdatedOn field if it's non-nil, zero value otherwise. func (c *Comment) GetUpdatedOn() time.Time { if c == nil || c.UpdatedOn == nil { return time.Time{} } return *c.UpdatedOn } // GetUser returns the User field. func (c *Comment) GetUser() *User { if c == nil { return nil } return c.User } // GetHTML returns the HTML field. func (c *CommentLinks) GetHTML() *Link { if c == nil { return nil } return c.HTML } // GetSelf returns the Self field. func (c *CommentLinks) GetSelf() *Link { if c == nil { return nil } return c.Self } // GetAuthor returns the Author field. func (c *Commit) GetAuthor() *User { if c == nil { return nil } return c.Author } // GetDate returns the Date field if it's non-nil, zero value otherwise. func (c *Commit) GetDate() time.Time { if c == nil || c.Date == nil { return time.Time{} } return *c.Date } // GetHash returns the Hash field if it's non-nil, zero value otherwise. func (c *Commit) GetHash() string { if c == nil || c.Hash == nil { return "" } return *c.Hash } // GetLinks returns the Links field. func (c *Commit) GetLinks() *CommitLinks { if c == nil { return nil } return c.Links } // GetMessage returns the Message field if it's non-nil, zero value otherwise. func (c *Commit) GetMessage() string { if c == nil || c.Message == nil { return "" } return *c.Message } // HasParents checks if Commit has any Parents. func (c *Commit) HasParents() bool { if c == nil || c.Parents == nil { return false } if len(c.Parents) == 0 { return false } return true } // HasParticipants checks if Commit has any Participants. func (c *Commit) HasParticipants() bool { if c == nil || c.Participants == nil { return false } if len(c.Participants) == 0 { return false } return true } // GetRendered returns the Rendered field. func (c *Commit) GetRendered() *CommitMessageContent { if c == nil { return nil } return c.Rendered } // GetRepository returns the Repository field. func (c *Commit) GetRepository() *Repository { if c == nil { return nil } return c.Repository } // GetSummary returns the Summary field. func (c *Commit) GetSummary() *Content { if c == nil { return nil } return c.Summary } // GetType returns the Type field if it's non-nil, zero value otherwise. func (c *Commit) GetType() string { if c == nil || c.Type == nil { return "" } return *c.Type } // GetCommit returns the Commit field. func (c *CommitComment) GetCommit() *Commit { if c == nil { return nil } return c.Commit } // GetContent returns the Content field. func (c *CommitComment) GetContent() *Content { if c == nil { return nil } return c.Content } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (c *CommitComment) GetCreatedOn() time.Time { if c == nil || c.CreatedOn == nil { return time.Time{} } return *c.CreatedOn } // GetDeleted returns the Deleted field if it's non-nil, zero value otherwise. func (c *CommitComment) GetDeleted() bool { if c == nil || c.Deleted == nil { return false } return *c.Deleted } // GetID returns the ID field if it's non-nil, zero value otherwise. func (c *CommitComment) GetID() int64 { if c == nil || c.ID == nil { return 0 } return *c.ID } // GetLinks returns the Links field. func (c *CommitComment) GetLinks() *CCLinks { if c == nil { return nil } return c.Links } // GetParent returns the Parent field. func (c *CommitComment) GetParent() *CommitComment { if c == nil { return nil } return c.Parent } // GetType returns the Type field if it's non-nil, zero value otherwise. func (c *CommitComment) GetType() string { if c == nil || c.Type == nil { return "" } return *c.Type } // GetUpdatedOn returns the UpdatedOn field if it's non-nil, zero value otherwise. func (c *CommitComment) GetUpdatedOn() time.Time { if c == nil || c.UpdatedOn == nil { return time.Time{} } return *c.UpdatedOn } // GetUser returns the User field. func (c *CommitComment) GetUser() *User { if c == nil { return nil } return c.User } // GetContent returns the Content field. func (c *CommitCommentRequest) GetContent() *Content { if c == nil { return nil } return c.Content } // GetParentComment returns the ParentComment field. func (c *CommitCommentRequest) GetParentComment() *CommitComment { if c == nil { return nil } return c.ParentComment } // HasValues checks if CommitComments has any Values. func (c *CommitComments) HasValues() bool { if c == nil || c.Values == nil { return false } if len(c.Values) == 0 { return false } return true } // GetApprove returns the Approve field. func (c *CommitLinks) GetApprove() *Link { if c == nil { return nil } return c.Approve } // GetComment returns the Comment field. func (c *CommitLinks) GetComment() *Link { if c == nil { return nil } return c.Comment } // GetDiff returns the Diff field. func (c *CommitLinks) GetDiff() *Link { if c == nil { return nil } return c.Diff } // GetHTML returns the HTML field. func (c *CommitLinks) GetHTML() *Link { if c == nil { return nil } return c.HTML } // GetSelf returns the Self field. func (c *CommitLinks) GetSelf() *Link { if c == nil { return nil } return c.Self } // GetStatuses returns the Statuses field. func (c *CommitLinks) GetStatuses() *Link { if c == nil { return nil } return c.Statuses } // GetMessage returns the Message field. func (c *CommitMessageContent) GetMessage() *Content { if c == nil { return nil } return c.Message } // HasValues checks if Commits has any Values. func (c *Commits) HasValues() bool { if c == nil || c.Values == nil { return false } if len(c.Values) == 0 { return false } return true } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (c *CommitStatus) GetCreatedOn() time.Time { if c == nil || c.CreatedOn == nil { return time.Time{} } return *c.CreatedOn } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (c *CommitStatus) GetDescription() string { if c == nil || c.Description == nil { return "" } return *c.Description } // GetKey returns the Key field if it's non-nil, zero value otherwise. func (c *CommitStatus) GetKey() string { if c == nil || c.Key == nil { return "" } return *c.Key } // GetLinks returns the Links field. func (c *CommitStatus) GetLinks() *CSLinks { if c == nil { return nil } return c.Links } // GetName returns the Name field if it's non-nil, zero value otherwise. func (c *CommitStatus) GetName() string { if c == nil || c.Name == nil { return "" } return *c.Name } // GetRefname returns the Refname field if it's non-nil, zero value otherwise. func (c *CommitStatus) GetRefname() string { if c == nil || c.Refname == nil { return "" } return *c.Refname } // GetState returns the State field if it's non-nil, zero value otherwise. func (c *CommitStatus) GetState() string { if c == nil || c.State == nil { return "" } return *c.State } // GetUpdatedOn returns the UpdatedOn field if it's non-nil, zero value otherwise. func (c *CommitStatus) GetUpdatedOn() time.Time { if c == nil || c.UpdatedOn == nil { return time.Time{} } return *c.UpdatedOn } // GetURL returns the URL field if it's non-nil, zero value otherwise. func (c *CommitStatus) GetURL() string { if c == nil || c.URL == nil { return "" } return *c.URL } // GetUUID returns the UUID field if it's non-nil, zero value otherwise. func (c *CommitStatus) GetUUID() string { if c == nil || c.UUID == nil { return "" } return *c.UUID } // HasValues checks if CommitStatuses has any Values. func (c *CommitStatuses) HasValues() bool { if c == nil || c.Values == nil { return false } if len(c.Values) == 0 { return false } return true } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (c *CommitStatusRequest) GetDescription() string { if c == nil || c.Description == nil { return "" } return *c.Description } // GetKey returns the Key field if it's non-nil, zero value otherwise. func (c *CommitStatusRequest) GetKey() string { if c == nil || c.Key == nil { return "" } return *c.Key } // GetName returns the Name field if it's non-nil, zero value otherwise. func (c *CommitStatusRequest) GetName() string { if c == nil || c.Name == nil { return "" } return *c.Name } // GetRefname returns the Refname field if it's non-nil, zero value otherwise. func (c *CommitStatusRequest) GetRefname() string { if c == nil || c.Refname == nil { return "" } return *c.Refname } // GetState returns the State field if it's non-nil, zero value otherwise. func (c *CommitStatusRequest) GetState() string { if c == nil || c.State == nil { return "" } return *c.State } // GetURL returns the URL field if it's non-nil, zero value otherwise. func (c *CommitStatusRequest) GetURL() string { if c == nil || c.URL == nil { return "" } return *c.URL } // GetID returns the ID field if it's non-nil, zero value otherwise. func (c *Component) GetID() int64 { if c == nil || c.ID == nil { return 0 } return *c.ID } // GetLinks returns the Links field. func (c *Component) GetLinks() *ComponentLinks { if c == nil { return nil } return c.Links } // GetName returns the Name field if it's non-nil, zero value otherwise. func (c *Component) GetName() string { if c == nil || c.Name == nil { return "" } return *c.Name } // GetRepository returns the Repository field. func (c *Component) GetRepository() *Repository { if c == nil { return nil } return c.Repository } // GetType returns the Type field if it's non-nil, zero value otherwise. func (c *Component) GetType() string { if c == nil || c.Type == nil { return "" } return *c.Type } // GetSelf returns the Self field. func (c *ComponentLinks) GetSelf() *Link { if c == nil { return nil } return c.Self } // GetName returns the Name field if it's non-nil, zero value otherwise. func (c *ComponentRequest) GetName() string { if c == nil || c.Name == nil { return "" } return *c.Name } // HasValues checks if Components has any Values. func (c *Components) HasValues() bool { if c == nil || c.Values == nil { return false } if len(c.Values) == 0 { return false } return true } // GetHTML returns the HTML field if it's non-nil, zero value otherwise. func (c *Content) GetHTML() string { if c == nil || c.HTML == nil { return "" } return *c.HTML } // GetMarkup returns the Markup field if it's non-nil, zero value otherwise. func (c *Content) GetMarkup() string { if c == nil || c.Markup == nil { return "" } return *c.Markup } // GetRaw returns the Raw field if it's non-nil, zero value otherwise. func (c *Content) GetRaw() string { if c == nil || c.Raw == nil { return "" } return *c.Raw } // GetType returns the Type field if it's non-nil, zero value otherwise. func (c *Content) GetType() string { if c == nil || c.Type == nil { return "" } return *c.Type } // GetHTML returns the HTML field. func (c *CSLinks) GetHTML() *Link { if c == nil { return nil } return c.HTML } // GetSelf returns the Self field. func (c *CSLinks) GetSelf() *Link { if c == nil { return nil } return c.Self } // GetAddedOn returns the AddedOn field if it's non-nil, zero value otherwise. func (d *DeployKey) GetAddedOn() time.Time { if d == nil || d.AddedOn == nil { return time.Time{} } return *d.AddedOn } // GetComment returns the Comment field if it's non-nil, zero value otherwise. func (d *DeployKey) GetComment() string { if d == nil || d.Comment == nil { return "" } return *d.Comment } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (d *DeployKey) GetCreatedOn() time.Time { if d == nil || d.CreatedOn == nil { return time.Time{} } return *d.CreatedOn } // GetID returns the ID field if it's non-nil, zero value otherwise. func (d *DeployKey) GetID() int64 { if d == nil || d.ID == nil { return 0 } return *d.ID } // GetKey returns the Key field if it's non-nil, zero value otherwise. func (d *DeployKey) GetKey() string { if d == nil || d.Key == nil { return "" } return *d.Key } // GetLabel returns the Label field if it's non-nil, zero value otherwise. func (d *DeployKey) GetLabel() string { if d == nil || d.Label == nil { return "" } return *d.Label } // GetLastUsed returns the LastUsed field if it's non-nil, zero value otherwise. func (d *DeployKey) GetLastUsed() time.Time { if d == nil || d.LastUsed == nil { return time.Time{} } return *d.LastUsed } // GetLinks returns the Links field. func (d *DeployKey) GetLinks() *DeployKeyLinks { if d == nil { return nil } return d.Links } // GetRepository returns the Repository field. func (d *DeployKey) GetRepository() *Repository { if d == nil { return nil } return d.Repository } // GetType returns the Type field if it's non-nil, zero value otherwise. func (d *DeployKey) GetType() string { if d == nil || d.Type == nil { return "" } return *d.Type } // GetSelf returns the Self field. func (d *DeployKeyLinks) GetSelf() *Link { if d == nil { return nil } return d.Self } // GetKey returns the Key field if it's non-nil, zero value otherwise. func (d *DeployKeyRequest) GetKey() string { if d == nil || d.Key == nil { return "" } return *d.Key } // GetLabel returns the Label field if it's non-nil, zero value otherwise. func (d *DeployKeyRequest) GetLabel() string { if d == nil || d.Label == nil { return "" } return *d.Label } // HasValues checks if DeployKeys has any Values. func (d *DeployKeys) HasValues() bool { if d == nil || d.Values == nil { return false } if len(d.Values) == 0 { return false } return true } // GetLinesAdded returns the LinesAdded field if it's non-nil, zero value otherwise. func (d *Diff) GetLinesAdded() int64 { if d == nil || d.LinesAdded == nil { return 0 } return *d.LinesAdded } // GetLinesRemoved returns the LinesRemoved field if it's non-nil, zero value otherwise. func (d *Diff) GetLinesRemoved() int64 { if d == nil || d.LinesRemoved == nil { return 0 } return *d.LinesRemoved } // GetNew returns the New field. func (d *Diff) GetNew() *CodeFile { if d == nil { return nil } return d.New } // GetOld returns the Old field. func (d *Diff) GetOld() *CodeFile { if d == nil { return nil } return d.Old } // GetStatus returns the Status field if it's non-nil, zero value otherwise. func (d *Diff) GetStatus() string { if d == nil || d.Status == nil { return "" } return *d.Status } // GetType returns the Type field if it's non-nil, zero value otherwise. func (d *Diff) GetType() string { if d == nil || d.Type == nil { return "" } return *d.Type } // GetBinary returns the Binary field if it's non-nil, zero value otherwise. func (d *DiffGetOpts) GetBinary() string { if d == nil || d.Binary == nil { return "" } return *d.Binary } // GetContext returns the Context field if it's non-nil, zero value otherwise. func (d *DiffGetOpts) GetContext() int { if d == nil || d.Context == nil { return 0 } return *d.Context } // GetIgnoreWhitespace returns the IgnoreWhitespace field if it's non-nil, zero value otherwise. func (d *DiffGetOpts) GetIgnoreWhitespace() string { if d == nil || d.IgnoreWhitespace == nil { return "" } return *d.IgnoreWhitespace } // GetPath returns the Path field if it's non-nil, zero value otherwise. func (d *DiffGetOpts) GetPath() string { if d == nil || d.Path == nil { return "" } return *d.Path } // HasValues checks if Diffs has any Values. func (d *Diffs) HasValues() bool { if d == nil || d.Values == nil { return false } if len(d.Values) == 0 { return false } return true } // HasBody checks if ErrorResponse has any Body. func (e *ErrorResponse) HasBody() bool { if e == nil || e.Body == nil { return false } if len(e.Body) == 0 { return false } return true } // HasValues checks if FileHistory has any Values. func (f *FileHistory) HasValues() bool { if f == nil || f.Values == nil { return false } if len(f.Values) == 0 { return false } return true } // GetHistory returns the History field. func (f *FileHistoryLinks) GetHistory() *Link { if f == nil { return nil } return f.History } // GetMeta returns the Meta field. func (f *FileHistoryLinks) GetMeta() *Link { if f == nil { return nil } return f.Meta } // GetSelf returns the Self field. func (f *FileHistoryLinks) GetSelf() *Link { if f == nil { return nil } return f.Self } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (f *ForkRequest) GetDescription() string { if f == nil || f.Description == nil { return "" } return *f.Description } // GetForkPolicy returns the ForkPolicy field if it's non-nil, zero value otherwise. func (f *ForkRequest) GetForkPolicy() string { if f == nil || f.ForkPolicy == nil { return "" } return *f.ForkPolicy } // GetHasIssues returns the HasIssues field if it's non-nil, zero value otherwise. func (f *ForkRequest) GetHasIssues() string { if f == nil || f.HasIssues == nil { return "" } return *f.HasIssues } // GetHasWiki returns the HasWiki field if it's non-nil, zero value otherwise. func (f *ForkRequest) GetHasWiki() bool { if f == nil || f.HasWiki == nil { return false } return *f.HasWiki } // GetIsPrivate returns the IsPrivate field if it's non-nil, zero value otherwise. func (f *ForkRequest) GetIsPrivate() bool { if f == nil || f.IsPrivate == nil { return false } return *f.IsPrivate } // GetLanguage returns the Language field if it's non-nil, zero value otherwise. func (f *ForkRequest) GetLanguage() string { if f == nil || f.Language == nil { return "" } return *f.Language } // GetMainBranch returns the MainBranch field. func (f *ForkRequest) GetMainBranch() *RepositoryMainBranch { if f == nil { return nil } return f.MainBranch } // GetName returns the Name field if it's non-nil, zero value otherwise. func (f *ForkRequest) GetName() string { if f == nil || f.Name == nil { return "" } return *f.Name } // GetOwner returns the Owner field. func (f *ForkRequest) GetOwner() *User { if f == nil { return nil } return f.Owner } // GetParent returns the Parent field. func (f *ForkRequest) GetParent() *Repository { if f == nil { return nil } return f.Parent } // GetSCM returns the SCM field if it's non-nil, zero value otherwise. func (f *ForkRequest) GetSCM() string { if f == nil || f.SCM == nil { return "" } return *f.SCM } // GetCategory returns the Category field if it's non-nil, zero value otherwise. func (h *HookEvent) GetCategory() string { if h == nil || h.Category == nil { return "" } return *h.Category } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (h *HookEvent) GetDescription() string { if h == nil || h.Description == nil { return "" } return *h.Description } // GetEvent returns the Event field if it's non-nil, zero value otherwise. func (h *HookEvent) GetEvent() string { if h == nil || h.Event == nil { return "" } return *h.Event } // GetLabel returns the Label field if it's non-nil, zero value otherwise. func (h *HookEvent) GetLabel() string { if h == nil || h.Label == nil { return "" } return *h.Label } // HasValues checks if HookEvents has any Values. func (h *HookEvents) HasValues() bool { if h == nil || h.Values == nil { return false } if len(h.Values) == 0 { return false } return true } // GetRepository returns the Repository field. func (h *HookEventTypes) GetRepository() *HookEventTypesLinks { if h == nil { return nil } return h.Repository } // GetTeam returns the Team field. func (h *HookEventTypes) GetTeam() *HookEventTypesLinks { if h == nil { return nil } return h.Team } // GetUser returns the User field. func (h *HookEventTypes) GetUser() *HookEventTypesLinks { if h == nil { return nil } return h.User } // GetEvents returns the Events field. func (h *HookEventTypesLinks) GetEvents() *Link { if h == nil { return nil } return h.Events } // GetAssignee returns the Assignee field. func (i *Issue) GetAssignee() *User { if i == nil { return nil } return i.Assignee } // GetComponent returns the Component field. func (i *Issue) GetComponent() *Component { if i == nil { return nil } return i.Component } // GetContent returns the Content field. func (i *Issue) GetContent() *IssueContent { if i == nil { return nil } return i.Content } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (i *Issue) GetCreatedOn() time.Time { if i == nil || i.CreatedOn == nil { return time.Time{} } return *i.CreatedOn } // GetEditedOn returns the EditedOn field if it's non-nil, zero value otherwise. func (i *Issue) GetEditedOn() time.Time { if i == nil || i.EditedOn == nil { return time.Time{} } return *i.EditedOn } // GetID returns the ID field if it's non-nil, zero value otherwise. func (i *Issue) GetID() int64 { if i == nil || i.ID == nil { return 0 } return *i.ID } // GetKind returns the Kind field if it's non-nil, zero value otherwise. func (i *Issue) GetKind() string { if i == nil || i.Kind == nil { return "" } return *i.Kind } // GetLinks returns the Links field. func (i *Issue) GetLinks() *IssueLinks { if i == nil { return nil } return i.Links } // GetMilestone returns the Milestone field. func (i *Issue) GetMilestone() *Milestone { if i == nil { return nil } return i.Milestone } // GetPriority returns the Priority field if it's non-nil, zero value otherwise. func (i *Issue) GetPriority() string { if i == nil || i.Priority == nil { return "" } return *i.Priority } // GetReporter returns the Reporter field. func (i *Issue) GetReporter() *User { if i == nil { return nil } return i.Reporter } // GetRepository returns the Repository field. func (i *Issue) GetRepository() *Repository { if i == nil { return nil } return i.Repository } // GetState returns the State field if it's non-nil, zero value otherwise. func (i *Issue) GetState() string { if i == nil || i.State == nil { return "" } return *i.State } // GetTitle returns the Title field if it's non-nil, zero value otherwise. func (i *Issue) GetTitle() string { if i == nil || i.Title == nil { return "" } return *i.Title } // GetType returns the Type field if it's non-nil, zero value otherwise. func (i *Issue) GetType() string { if i == nil || i.Type == nil { return "" } return *i.Type } // GetUpdatedOn returns the UpdatedOn field if it's non-nil, zero value otherwise. func (i *Issue) GetUpdatedOn() time.Time { if i == nil || i.UpdatedOn == nil { return time.Time{} } return *i.UpdatedOn } // GetVersion returns the Version field. func (i *Issue) GetVersion() *Version { if i == nil { return nil } return i.Version } // GetVotes returns the Votes field if it's non-nil, zero value otherwise. func (i *Issue) GetVotes() int { if i == nil || i.Votes == nil { return 0 } return *i.Votes } // GetWatches returns the Watches field if it's non-nil, zero value otherwise. func (i *Issue) GetWatches() int { if i == nil || i.Watches == nil { return 0 } return *i.Watches } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (i *IssueChange) GetCreatedOn() time.Time { if i == nil || i.CreatedOn == nil { return time.Time{} } return *i.CreatedOn } // GetID returns the ID field if it's non-nil, zero value otherwise. func (i *IssueChange) GetID() int64 { if i == nil || i.ID == nil { return 0 } return *i.ID } // GetIssue returns the Issue field. func (i *IssueChange) GetIssue() *Issue { if i == nil { return nil } return i.Issue } // GetLinks returns the Links field. func (i *IssueChange) GetLinks() *IssueChangeLinks { if i == nil { return nil } return i.Links } // GetMessage returns the Message field. func (i *IssueChange) GetMessage() *Content { if i == nil { return nil } return i.Message } // GetType returns the Type field if it's non-nil, zero value otherwise. func (i *IssueChange) GetType() string { if i == nil || i.Type == nil { return "" } return *i.Type } // GetUser returns the User field. func (i *IssueChange) GetUser() *User { if i == nil { return nil } return i.User } // GetHTML returns the HTML field. func (i *IssueChangeLinks) GetHTML() *Link { if i == nil { return nil } return i.HTML } // GetSelf returns the Self field. func (i *IssueChangeLinks) GetSelf() *Link { if i == nil { return nil } return i.Self } // GetAssigneeAccountID returns the AssigneeAccountID field if it's non-nil, zero value otherwise. func (i *IssueChangeRequest) GetAssigneeAccountID() string { if i == nil || i.AssigneeAccountID == nil { return "" } return *i.AssigneeAccountID } // GetComponent returns the Component field if it's non-nil, zero value otherwise. func (i *IssueChangeRequest) GetComponent() string { if i == nil || i.Component == nil { return "" } return *i.Component } // GetContent returns the Content field if it's non-nil, zero value otherwise. func (i *IssueChangeRequest) GetContent() string { if i == nil || i.Content == nil { return "" } return *i.Content } // GetKind returns the Kind field if it's non-nil, zero value otherwise. func (i *IssueChangeRequest) GetKind() string { if i == nil || i.Kind == nil { return "" } return *i.Kind } // GetMessage returns the Message field if it's non-nil, zero value otherwise. func (i *IssueChangeRequest) GetMessage() string { if i == nil || i.Message == nil { return "" } return *i.Message } // GetMilestone returns the Milestone field if it's non-nil, zero value otherwise. func (i *IssueChangeRequest) GetMilestone() string { if i == nil || i.Milestone == nil { return "" } return *i.Milestone } // GetPriority returns the Priority field if it's non-nil, zero value otherwise. func (i *IssueChangeRequest) GetPriority() string { if i == nil || i.Priority == nil { return "" } return *i.Priority } // GetVersion returns the Version field if it's non-nil, zero value otherwise. func (i *IssueChangeRequest) GetVersion() string { if i == nil || i.Version == nil { return "" } return *i.Version } // HasValues checks if IssueChanges has any Values. func (i *IssueChanges) HasValues() bool { if i == nil || i.Values == nil { return false } if len(i.Values) == 0 { return false } return true } // GetContent returns the Content field. func (i *IssueComment) GetContent() *Content { if i == nil { return nil } return i.Content } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (i *IssueComment) GetCreatedOn() time.Time { if i == nil || i.CreatedOn == nil { return time.Time{} } return *i.CreatedOn } // GetID returns the ID field if it's non-nil, zero value otherwise. func (i *IssueComment) GetID() int64 { if i == nil || i.ID == nil { return 0 } return *i.ID } // GetIssue returns the Issue field. func (i *IssueComment) GetIssue() *Issue { if i == nil { return nil } return i.Issue } // GetLinks returns the Links field. func (i *IssueComment) GetLinks() *IssueCommentLinks { if i == nil { return nil } return i.Links } // GetType returns the Type field if it's non-nil, zero value otherwise. func (i *IssueComment) GetType() string { if i == nil || i.Type == nil { return "" } return *i.Type } // GetUpdatedOn returns the UpdatedOn field if it's non-nil, zero value otherwise. func (i *IssueComment) GetUpdatedOn() time.Time { if i == nil || i.UpdatedOn == nil { return time.Time{} } return *i.UpdatedOn } // GetUser returns the User field. func (i *IssueComment) GetUser() *User { if i == nil { return nil } return i.User } // GetHTML returns the HTML field. func (i *IssueCommentLinks) GetHTML() *Link { if i == nil { return nil } return i.HTML } // GetSelf returns the Self field. func (i *IssueCommentLinks) GetSelf() *Link { if i == nil { return nil } return i.Self } // GetContent returns the Content field. func (i *IssueCommentRequest) GetContent() *Content { if i == nil { return nil } return i.Content } // HasValues checks if IssueComments has any Values. func (i *IssueComments) HasValues() bool { if i == nil || i.Values == nil { return false } if len(i.Values) == 0 { return false } return true } // GetHTML returns the HTML field if it's non-nil, zero value otherwise. func (i *IssueContent) GetHTML() string { if i == nil || i.HTML == nil { return "" } return *i.HTML } // GetMarkup returns the Markup field if it's non-nil, zero value otherwise. func (i *IssueContent) GetMarkup() string { if i == nil || i.Markup == nil { return "" } return *i.Markup } // GetRaw returns the Raw field if it's non-nil, zero value otherwise. func (i *IssueContent) GetRaw() string { if i == nil || i.Raw == nil { return "" } return *i.Raw } // GetType returns the Type field if it's non-nil, zero value otherwise. func (i *IssueContent) GetType() string { if i == nil || i.Type == nil { return "" } return *i.Type } // GetAttachments returns the Attachments field. func (i *IssueLinks) GetAttachments() *Link { if i == nil { return nil } return i.Attachments } // GetComments returns the Comments field. func (i *IssueLinks) GetComments() *Link { if i == nil { return nil } return i.Comments } // GetHTML returns the HTML field. func (i *IssueLinks) GetHTML() *Link { if i == nil { return nil } return i.HTML } // GetSelf returns the Self field. func (i *IssueLinks) GetSelf() *Link { if i == nil { return nil } return i.Self } // GetVote returns the Vote field. func (i *IssueLinks) GetVote() *Link { if i == nil { return nil } return i.Vote } // GetWatch returns the Watch field. func (i *IssueLinks) GetWatch() *Link { if i == nil { return nil } return i.Watch } // GetAssignee returns the Assignee field. func (i *IssueRequest) GetAssignee() *IssueRequestAssigneeOpts { if i == nil { return nil } return i.Assignee } // GetComponent returns the Component field. func (i *IssueRequest) GetComponent() *ComponentRequest { if i == nil { return nil } return i.Component } // GetContent returns the Content field. func (i *IssueRequest) GetContent() *IssueRequestContentOpts { if i == nil { return nil } return i.Content } // GetKind returns the Kind field if it's non-nil, zero value otherwise. func (i *IssueRequest) GetKind() string { if i == nil || i.Kind == nil { return "" } return *i.Kind } // GetMilestone returns the Milestone field. func (i *IssueRequest) GetMilestone() *MilestoneRequest { if i == nil { return nil } return i.Milestone } // GetPriority returns the Priority field if it's non-nil, zero value otherwise. func (i *IssueRequest) GetPriority() string { if i == nil || i.Priority == nil { return "" } return *i.Priority } // GetTitle returns the Title field if it's non-nil, zero value otherwise. func (i *IssueRequest) GetTitle() string { if i == nil || i.Title == nil { return "" } return *i.Title } // GetVersion returns the Version field. func (i *IssueRequest) GetVersion() *VersionRequest { if i == nil { return nil } return i.Version } // GetUsername returns the Username field if it's non-nil, zero value otherwise. func (i *IssueRequestAssigneeOpts) GetUsername() string { if i == nil || i.Username == nil { return "" } return *i.Username } // GetHTML returns the HTML field if it's non-nil, zero value otherwise. func (i *IssueRequestContentOpts) GetHTML() string { if i == nil || i.HTML == nil { return "" } return *i.HTML } // GetRaw returns the Raw field if it's non-nil, zero value otherwise. func (i *IssueRequestContentOpts) GetRaw() string { if i == nil || i.Raw == nil { return "" } return *i.Raw } // HasValues checks if Issues has any Values. func (i *Issues) HasValues() bool { if i == nil || i.Values == nil { return false } if len(i.Values) == 0 { return false } return true } // GetHRef returns the HRef field if it's non-nil, zero value otherwise. func (l *Link) GetHRef() string { if l == nil || l.HRef == nil { return "" } return *l.HRef } // GetName returns the Name field if it's non-nil, zero value otherwise. func (l *Link) GetName() string { if l == nil || l.Name == nil { return "" } return *l.Name } // GetID returns the ID field if it's non-nil, zero value otherwise. func (m *Milestone) GetID() int64 { if m == nil || m.ID == nil { return 0 } return *m.ID } // GetLinks returns the Links field. func (m *Milestone) GetLinks() *MilestoneLinks { if m == nil { return nil } return m.Links } // GetName returns the Name field if it's non-nil, zero value otherwise. func (m *Milestone) GetName() string { if m == nil || m.Name == nil { return "" } return *m.Name } // GetRepository returns the Repository field. func (m *Milestone) GetRepository() *Repository { if m == nil { return nil } return m.Repository } // GetType returns the Type field if it's non-nil, zero value otherwise. func (m *Milestone) GetType() string { if m == nil || m.Type == nil { return "" } return *m.Type } // GetSelf returns the Self field. func (m *MilestoneLinks) GetSelf() *Link { if m == nil { return nil } return m.Self } // GetName returns the Name field if it's non-nil, zero value otherwise. func (m *MilestoneRequest) GetName() string { if m == nil || m.Name == nil { return "" } return *m.Name } // HasValues checks if Milestones has any Values. func (m *Milestones) HasValues() bool { if m == nil || m.Values == nil { return false } if len(m.Values) == 0 { return false } return true } // GetNext returns the Next field if it's non-nil, zero value otherwise. func (p *PaginationInfo) GetNext() string { if p == nil || p.Next == nil { return "" } return *p.Next } // GetPage returns the Page field if it's non-nil, zero value otherwise. func (p *PaginationInfo) GetPage() int64 { if p == nil || p.Page == nil { return 0 } return *p.Page } // GetPagelen returns the Pagelen field if it's non-nil, zero value otherwise. func (p *PaginationInfo) GetPagelen() int64 { if p == nil || p.Pagelen == nil { return 0 } return *p.Pagelen } // GetPrevious returns the Previous field if it's non-nil, zero value otherwise. func (p *PaginationInfo) GetPrevious() string { if p == nil || p.Previous == nil { return "" } return *p.Previous } // GetSize returns the Size field if it's non-nil, zero value otherwise. func (p *PaginationInfo) GetSize() int64 { if p == nil || p.Size == nil { return 0 } return *p.Size } // GetApproved returns the Approved field if it's non-nil, zero value otherwise. func (p *Participant) GetApproved() bool { if p == nil || p.Approved == nil { return false } return *p.Approved } // GetParticipatedOn returns the ParticipatedOn field if it's non-nil, zero value otherwise. func (p *Participant) GetParticipatedOn() time.Time { if p == nil || p.ParticipatedOn == nil { return time.Time{} } return *p.ParticipatedOn } // GetRole returns the Role field if it's non-nil, zero value otherwise. func (p *Participant) GetRole() string { if p == nil || p.Role == nil { return "" } return *p.Role } // GetType returns the Type field if it's non-nil, zero value otherwise. func (p *Participant) GetType() string { if p == nil || p.Type == nil { return "" } return *p.Type } // GetUser returns the User field. func (p *Participant) GetUser() *User { if p == nil { return nil } return p.User } // HasValues checks if PRActivities has any Values. func (p *PRActivities) HasValues() bool { if p == nil || p.Values == nil { return false } if len(p.Values) == 0 { return false } return true } // GetApproval returns the Approval field. func (p *PRActivity) GetApproval() *PRApprovalActivity { if p == nil { return nil } return p.Approval } // GetPullRequest returns the PullRequest field. func (p *PRActivity) GetPullRequest() *PullRequest { if p == nil { return nil } return p.PullRequest } // GetUpdate returns the Update field. func (p *PRActivity) GetUpdate() *PRUpdateActivity { if p == nil { return nil } return p.Update } // GetDate returns the Date field if it's non-nil, zero value otherwise. func (p *PRApprovalActivity) GetDate() time.Time { if p == nil || p.Date == nil { return time.Time{} } return *p.Date } // GetPullRequest returns the PullRequest field. func (p *PRApprovalActivity) GetPullRequest() *PullRequest { if p == nil { return nil } return p.PullRequest } // GetUser returns the User field. func (p *PRApprovalActivity) GetUser() *User { if p == nil { return nil } return p.User } // GetDeleted returns the Deleted field if it's non-nil, zero value otherwise. func (p *PRComment) GetDeleted() bool { if p == nil || p.Deleted == nil { return false } return *p.Deleted } // GetPullRequest returns the PullRequest field. func (p *PRComment) GetPullRequest() *PullRequest { if p == nil { return nil } return p.PullRequest } // GetContent returns the Content field. func (p *PRCommentRequest) GetContent() *Content { if p == nil { return nil } return p.Content } // HasValues checks if PRComments has any Values. func (p *PRComments) HasValues() bool { if p == nil || p.Values == nil { return false } if len(p.Values) == 0 { return false } return true } // GetCloseSourceBranch returns the CloseSourceBranch field if it's non-nil, zero value otherwise. func (p *PRRequest) GetCloseSourceBranch() bool { if p == nil || p.CloseSourceBranch == nil { return false } return *p.CloseSourceBranch } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (p *PRRequest) GetDescription() string { if p == nil || p.Description == nil { return "" } return *p.Description } // GetDestination returns the Destination field. func (p *PRRequest) GetDestination() *PRRequestDestinationOpts { if p == nil { return nil } return p.Destination } // HasReviewers checks if PRRequest has any Reviewers. func (p *PRRequest) HasReviewers() bool { if p == nil || p.Reviewers == nil { return false } if len(p.Reviewers) == 0 { return false } return true } // GetSource returns the Source field. func (p *PRRequest) GetSource() *PRRequestSourceOpts { if p == nil { return nil } return p.Source } // GetTitle returns the Title field if it's non-nil, zero value otherwise. func (p *PRRequest) GetTitle() string { if p == nil || p.Title == nil { return "" } return *p.Title } // GetBranch returns the Branch field. func (p *PRRequestDestinationOpts) GetBranch() *Branch { if p == nil { return nil } return p.Branch } // GetUUID returns the UUID field if it's non-nil, zero value otherwise. func (p *PRRequestReviewerOpts) GetUUID() string { if p == nil || p.UUID == nil { return "" } return *p.UUID } // GetBranch returns the Branch field. func (p *PRRequestSourceOpts) GetBranch() *Branch { if p == nil { return nil } return p.Branch } // GetAuthor returns the Author field. func (p *PRUpdateActivity) GetAuthor() *User { if p == nil { return nil } return p.Author } // GetDate returns the Date field if it's non-nil, zero value otherwise. func (p *PRUpdateActivity) GetDate() time.Time { if p == nil || p.Date == nil { return time.Time{} } return *p.Date } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (p *PRUpdateActivity) GetDescription() string { if p == nil || p.Description == nil { return "" } return *p.Description } // GetDestination returns the Destination field. func (p *PRUpdateActivity) GetDestination() *PullRequestBranch { if p == nil { return nil } return p.Destination } // GetReason returns the Reason field if it's non-nil, zero value otherwise. func (p *PRUpdateActivity) GetReason() string { if p == nil || p.Reason == nil { return "" } return *p.Reason } // GetSource returns the Source field. func (p *PRUpdateActivity) GetSource() *PullRequestBranch { if p == nil { return nil } return p.Source } // GetState returns the State field if it's non-nil, zero value otherwise. func (p *PRUpdateActivity) GetState() string { if p == nil || p.State == nil { return "" } return *p.State } // GetTitle returns the Title field if it's non-nil, zero value otherwise. func (p *PRUpdateActivity) GetTitle() string { if p == nil || p.Title == nil { return "" } return *p.Title } // GetAuthor returns the Author field. func (p *PullRequest) GetAuthor() *User { if p == nil { return nil } return p.Author } // GetBody returns the Body field. func (p *PullRequest) GetBody() *PullRequestBody { if p == nil { return nil } return p.Body } // GetClosedBy returns the ClosedBy field. func (p *PullRequest) GetClosedBy() *User { if p == nil { return nil } return p.ClosedBy } // GetCloseSourceBranch returns the CloseSourceBranch field if it's non-nil, zero value otherwise. func (p *PullRequest) GetCloseSourceBranch() bool { if p == nil || p.CloseSourceBranch == nil { return false } return *p.CloseSourceBranch } // GetCommentCount returns the CommentCount field if it's non-nil, zero value otherwise. func (p *PullRequest) GetCommentCount() int64 { if p == nil || p.CommentCount == nil { return 0 } return *p.CommentCount } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (p *PullRequest) GetCreatedOn() time.Time { if p == nil || p.CreatedOn == nil { return time.Time{} } return *p.CreatedOn } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (p *PullRequest) GetDescription() string { if p == nil || p.Description == nil { return "" } return *p.Description } // GetDestination returns the Destination field. func (p *PullRequest) GetDestination() *PullRequestBranch { if p == nil { return nil } return p.Destination } // GetID returns the ID field if it's non-nil, zero value otherwise. func (p *PullRequest) GetID() int64 { if p == nil || p.ID == nil { return 0 } return *p.ID } // GetLinks returns the Links field. func (p *PullRequest) GetLinks() *PullRequestLinks { if p == nil { return nil } return p.Links } // GetMergeCommit returns the MergeCommit field if it's non-nil, zero value otherwise. func (p *PullRequest) GetMergeCommit() string { if p == nil || p.MergeCommit == nil { return "" } return *p.MergeCommit } // HasParticipants checks if PullRequest has any Participants. func (p *PullRequest) HasParticipants() bool { if p == nil || p.Participants == nil { return false } if len(p.Participants) == 0 { return false } return true } // GetReason returns the Reason field if it's non-nil, zero value otherwise. func (p *PullRequest) GetReason() string { if p == nil || p.Reason == nil { return "" } return *p.Reason } // HasReviewers checks if PullRequest has any Reviewers. func (p *PullRequest) HasReviewers() bool { if p == nil || p.Reviewers == nil { return false } if len(p.Reviewers) == 0 { return false } return true } // GetSource returns the Source field. func (p *PullRequest) GetSource() *PullRequestBranch { if p == nil { return nil } return p.Source } // GetState returns the State field if it's non-nil, zero value otherwise. func (p *PullRequest) GetState() string { if p == nil || p.State == nil { return "" } return *p.State } // GetSummary returns the Summary field. func (p *PullRequest) GetSummary() *Content { if p == nil { return nil } return p.Summary } // GetTaskCount returns the TaskCount field if it's non-nil, zero value otherwise. func (p *PullRequest) GetTaskCount() int64 { if p == nil || p.TaskCount == nil { return 0 } return *p.TaskCount } // GetTitle returns the Title field if it's non-nil, zero value otherwise. func (p *PullRequest) GetTitle() string { if p == nil || p.Title == nil { return "" } return *p.Title } // GetType returns the Type field if it's non-nil, zero value otherwise. func (p *PullRequest) GetType() string { if p == nil || p.Type == nil { return "" } return *p.Type } // GetUpdatedOn returns the UpdatedOn field if it's non-nil, zero value otherwise. func (p *PullRequest) GetUpdatedOn() string { if p == nil || p.UpdatedOn == nil { return "" } return *p.UpdatedOn } // GetDescription returns the Description field. func (p *PullRequestBody) GetDescription() *Content { if p == nil { return nil } return p.Description } // GetTitle returns the Title field. func (p *PullRequestBody) GetTitle() *Content { if p == nil { return nil } return p.Title } // GetBranch returns the Branch field. func (p *PullRequestBranch) GetBranch() *Branch { if p == nil { return nil } return p.Branch } // GetCommit returns the Commit field. func (p *PullRequestBranch) GetCommit() *Commit { if p == nil { return nil } return p.Commit } // GetRepository returns the Repository field. func (p *PullRequestBranch) GetRepository() *Repository { if p == nil { return nil } return p.Repository } // GetActivity returns the Activity field. func (p *PullRequestLinks) GetActivity() *Link { if p == nil { return nil } return p.Activity } // GetApprove returns the Approve field. func (p *PullRequestLinks) GetApprove() *Link { if p == nil { return nil } return p.Approve } // GetComments returns the Comments field. func (p *PullRequestLinks) GetComments() *Link { if p == nil { return nil } return p.Comments } // GetCommits returns the Commits field. func (p *PullRequestLinks) GetCommits() *Link { if p == nil { return nil } return p.Commits } // GetDecline returns the Decline field. func (p *PullRequestLinks) GetDecline() *Link { if p == nil { return nil } return p.Decline } // GetDiff returns the Diff field. func (p *PullRequestLinks) GetDiff() *Link { if p == nil { return nil } return p.Diff } // GetHTML returns the HTML field. func (p *PullRequestLinks) GetHTML() *Link { if p == nil { return nil } return p.HTML } // GetMerge returns the Merge field. func (p *PullRequestLinks) GetMerge() *Link { if p == nil { return nil } return p.Merge } // GetSelf returns the Self field. func (p *PullRequestLinks) GetSelf() *Link { if p == nil { return nil } return p.Self } // GetStatuses returns the Statuses field. func (p *PullRequestLinks) GetStatuses() *Link { if p == nil { return nil } return p.Statuses } // HasState checks if PullRequestListOpts has any State. func (p *PullRequestListOpts) HasState() bool { if p == nil || p.State == nil { return false } if len(p.State) == 0 { return false } return true } // HasValues checks if PullRequests has any Values. func (p *PullRequests) HasValues() bool { if p == nil || p.Values == nil { return false } if len(p.Values) == 0 { return false } return true } // GetDate returns the Date field if it's non-nil, zero value otherwise. func (r *Ref) GetDate() time.Time { if r == nil || r.Date == nil { return time.Time{} } return *r.Date } // GetDefaultMergeStrategy returns the DefaultMergeStrategy field if it's non-nil, zero value otherwise. func (r *Ref) GetDefaultMergeStrategy() string { if r == nil || r.DefaultMergeStrategy == nil { return "" } return *r.DefaultMergeStrategy } // HasHeads checks if Ref has any Heads. func (r *Ref) HasHeads() bool { if r == nil || r.Heads == nil { return false } if len(r.Heads) == 0 { return false } return true } // GetLinks returns the Links field. func (r *Ref) GetLinks() *RefLinks { if r == nil { return nil } return r.Links } // HasMergeStrategies checks if Ref has any MergeStrategies. func (r *Ref) HasMergeStrategies() bool { if r == nil || r.MergeStrategies == nil { return false } if len(r.MergeStrategies) == 0 { return false } return true } // GetMessage returns the Message field if it's non-nil, zero value otherwise. func (r *Ref) GetMessage() string { if r == nil || r.Message == nil { return "" } return *r.Message } // GetName returns the Name field if it's non-nil, zero value otherwise. func (r *Ref) GetName() string { if r == nil || r.Name == nil { return "" } return *r.Name } // GetTarget returns the Target field. func (r *Ref) GetTarget() *Commit { if r == nil { return nil } return r.Target } // GetType returns the Type field if it's non-nil, zero value otherwise. func (r *Ref) GetType() string { if r == nil || r.Type == nil { return "" } return *r.Type } // GetCommits returns the Commits field. func (r *RefLinks) GetCommits() *Link { if r == nil { return nil } return r.Commits } // GetHTML returns the HTML field. func (r *RefLinks) GetHTML() *Link { if r == nil { return nil } return r.HTML } // GetSelf returns the Self field. func (r *RefLinks) GetSelf() *Link { if r == nil { return nil } return r.Self } // GetName returns the Name field if it's non-nil, zero value otherwise. func (r *RefRequest) GetName() string { if r == nil || r.Name == nil { return "" } return *r.Name } // HasValues checks if Refs has any Values. func (r *Refs) HasValues() bool { if r == nil || r.Values == nil { return false } if len(r.Values) == 0 { return false } return true } // HasValues checks if Repositories has any Values. func (r *Repositories) HasValues() bool { if r == nil || r.Values == nil { return false } if len(r.Values) == 0 { return false } return true } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (r *Repository) GetCreatedOn() time.Time { if r == nil || r.CreatedOn == nil { return time.Time{} } return *r.CreatedOn } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (r *Repository) GetDescription() string { if r == nil || r.Description == nil { return "" } return *r.Description } // GetForkPolicy returns the ForkPolicy field if it's non-nil, zero value otherwise. func (r *Repository) GetForkPolicy() string { if r == nil || r.ForkPolicy == nil { return "" } return *r.ForkPolicy } // GetFullName returns the FullName field if it's non-nil, zero value otherwise. func (r *Repository) GetFullName() string { if r == nil || r.FullName == nil { return "" } return *r.FullName } // GetHasIssues returns the HasIssues field if it's non-nil, zero value otherwise. func (r *Repository) GetHasIssues() bool { if r == nil || r.HasIssues == nil { return false } return *r.HasIssues } // GetHasWiki returns the HasWiki field if it's non-nil, zero value otherwise. func (r *Repository) GetHasWiki() bool { if r == nil || r.HasWiki == nil { return false } return *r.HasWiki } // GetIsPrivate returns the IsPrivate field if it's non-nil, zero value otherwise. func (r *Repository) GetIsPrivate() bool { if r == nil || r.IsPrivate == nil { return false } return *r.IsPrivate } // GetLanguage returns the Language field if it's non-nil, zero value otherwise. func (r *Repository) GetLanguage() string { if r == nil || r.Language == nil { return "" } return *r.Language } // GetLinks returns the Links field. func (r *Repository) GetLinks() *RepositoryLinks { if r == nil { return nil } return r.Links } // GetMainBranch returns the MainBranch field. func (r *Repository) GetMainBranch() *RepositoryMainBranch { if r == nil { return nil } return r.MainBranch } // GetName returns the Name field if it's non-nil, zero value otherwise. func (r *Repository) GetName() string { if r == nil || r.Name == nil { return "" } return *r.Name } // GetOwner returns the Owner field. func (r *Repository) GetOwner() *User { if r == nil { return nil } return r.Owner } // GetParent returns the Parent field. func (r *Repository) GetParent() *Repository { if r == nil { return nil } return r.Parent } // GetSCM returns the SCM field if it's non-nil, zero value otherwise. func (r *Repository) GetSCM() string { if r == nil || r.SCM == nil { return "" } return *r.SCM } // GetSize returns the Size field if it's non-nil, zero value otherwise. func (r *Repository) GetSize() int64 { if r == nil || r.Size == nil { return 0 } return *r.Size } // GetSlug returns the Slug field if it's non-nil, zero value otherwise. func (r *Repository) GetSlug() string { if r == nil || r.Slug == nil { return "" } return *r.Slug } // GetType returns the Type field if it's non-nil, zero value otherwise. func (r *Repository) GetType() string { if r == nil || r.Type == nil { return "" } return *r.Type } // GetUpdatedOn returns the UpdatedOn field if it's non-nil, zero value otherwise. func (r *Repository) GetUpdatedOn() time.Time { if r == nil || r.UpdatedOn == nil { return time.Time{} } return *r.UpdatedOn } // GetUUID returns the UUID field if it's non-nil, zero value otherwise. func (r *Repository) GetUUID() string { if r == nil || r.UUID == nil { return "" } return *r.UUID } // GetWebsite returns the Website field if it's non-nil, zero value otherwise. func (r *Repository) GetWebsite() string { if r == nil || r.Website == nil { return "" } return *r.Website } // GetActive returns the Active field if it's non-nil, zero value otherwise. func (r *RepositoryHook) GetActive() bool { if r == nil || r.Active == nil { return false } return *r.Active } // GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. func (r *RepositoryHook) GetCreatedAt() time.Time { if r == nil || r.CreatedAt == nil { return time.Time{} } return *r.CreatedAt } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (r *RepositoryHook) GetDescription() string { if r == nil || r.Description == nil { return "" } return *r.Description } // HasEvents checks if RepositoryHook has any Events. func (r *RepositoryHook) HasEvents() bool { if r == nil || r.Events == nil { return false } if len(r.Events) == 0 { return false } return true } // HasSubjectType checks if RepositoryHook has any SubjectType. func (r *RepositoryHook) HasSubjectType() bool { if r == nil || r.SubjectType == nil { return false } if len(r.SubjectType) == 0 { return false } return true } // GetURL returns the URL field if it's non-nil, zero value otherwise. func (r *RepositoryHook) GetURL() string { if r == nil || r.URL == nil { return "" } return *r.URL } // GetUUID returns the UUID field if it's non-nil, zero value otherwise. func (r *RepositoryHook) GetUUID() string { if r == nil || r.UUID == nil { return "" } return *r.UUID } // GetActive returns the Active field if it's non-nil, zero value otherwise. func (r *RepositoryHookRequest) GetActive() bool { if r == nil || r.Active == nil { return false } return *r.Active } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (r *RepositoryHookRequest) GetDescription() string { if r == nil || r.Description == nil { return "" } return *r.Description } // HasEvents checks if RepositoryHookRequest has any Events. func (r *RepositoryHookRequest) HasEvents() bool { if r == nil || r.Events == nil { return false } if len(r.Events) == 0 { return false } return true } // GetURL returns the URL field if it's non-nil, zero value otherwise. func (r *RepositoryHookRequest) GetURL() string { if r == nil || r.URL == nil { return "" } return *r.URL } // HasValues checks if RepositoryHooks has any Values. func (r *RepositoryHooks) HasValues() bool { if r == nil || r.Values == nil { return false } if len(r.Values) == 0 { return false } return true } // GetAvatar returns the Avatar field. func (r *RepositoryLinks) GetAvatar() *Link { if r == nil { return nil } return r.Avatar } // GetBranches returns the Branches field. func (r *RepositoryLinks) GetBranches() *Link { if r == nil { return nil } return r.Branches } // HasClone checks if RepositoryLinks has any Clone. func (r *RepositoryLinks) HasClone() bool { if r == nil || r.Clone == nil { return false } if len(r.Clone) == 0 { return false } return true } // GetCommits returns the Commits field. func (r *RepositoryLinks) GetCommits() *Link { if r == nil { return nil } return r.Commits } // GetDownloads returns the Downloads field. func (r *RepositoryLinks) GetDownloads() *Link { if r == nil { return nil } return r.Downloads } // GetForks returns the Forks field. func (r *RepositoryLinks) GetForks() *Link { if r == nil { return nil } return r.Forks } // GetHTML returns the HTML field. func (r *RepositoryLinks) GetHTML() *Link { if r == nil { return nil } return r.HTML } // GetPullRequests returns the PullRequests field. func (r *RepositoryLinks) GetPullRequests() *Link { if r == nil { return nil } return r.PullRequests } // GetSelf returns the Self field. func (r *RepositoryLinks) GetSelf() *Link { if r == nil { return nil } return r.Self } // GetSource returns the Source field. func (r *RepositoryLinks) GetSource() *Link { if r == nil { return nil } return r.Source } // GetTags returns the Tags field. func (r *RepositoryLinks) GetTags() *Link { if r == nil { return nil } return r.Tags } // GetWatchers returns the Watchers field. func (r *RepositoryLinks) GetWatchers() *Link { if r == nil { return nil } return r.Watchers } // GetName returns the Name field if it's non-nil, zero value otherwise. func (r *RepositoryMainBranch) GetName() string { if r == nil || r.Name == nil { return "" } return *r.Name } // GetType returns the Type field if it's non-nil, zero value otherwise. func (r *RepositoryMainBranch) GetType() string { if r == nil || r.Type == nil { return "" } return *r.Type } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (r *RepositoryRequest) GetDescription() string { if r == nil || r.Description == nil { return "" } return *r.Description } // GetForkPolicy returns the ForkPolicy field if it's non-nil, zero value otherwise. func (r *RepositoryRequest) GetForkPolicy() string { if r == nil || r.ForkPolicy == nil { return "" } return *r.ForkPolicy } // GetHasIssues returns the HasIssues field if it's non-nil, zero value otherwise. func (r *RepositoryRequest) GetHasIssues() bool { if r == nil || r.HasIssues == nil { return false } return *r.HasIssues } // GetHasWiki returns the HasWiki field if it's non-nil, zero value otherwise. func (r *RepositoryRequest) GetHasWiki() bool { if r == nil || r.HasWiki == nil { return false } return *r.HasWiki } // GetName returns the Name field if it's non-nil, zero value otherwise. func (r *RepositoryRequest) GetName() string { if r == nil || r.Name == nil { return "" } return *r.Name } // GetSCM returns the SCM field if it's non-nil, zero value otherwise. func (r *RepositoryRequest) GetSCM() string { if r == nil || r.SCM == nil { return "" } return *r.SCM } // GetRepositories returns the Repositories field. func (s *SearchCodeFileLinks) GetRepositories() *Link { if s == nil { return nil } return s.Repositories } // GetSelf returns the Self field. func (s *SearchCodeFileLinks) GetSelf() *Link { if s == nil { return nil } return s.Self } // GetContentMatchCount returns the ContentMatchCount field if it's non-nil, zero value otherwise. func (s *SearchCodeResult) GetContentMatchCount() int64 { if s == nil || s.ContentMatchCount == nil { return 0 } return *s.ContentMatchCount } // HasContentMatches checks if SearchCodeResult has any ContentMatches. func (s *SearchCodeResult) HasContentMatches() bool { if s == nil || s.ContentMatches == nil { return false } if len(s.ContentMatches) == 0 { return false } return true } // GetFile returns the File field. func (s *SearchCodeResult) GetFile() *CodeFile { if s == nil { return nil } return s.File } // HasPathMatches checks if SearchCodeResult has any PathMatches. func (s *SearchCodeResult) HasPathMatches() bool { if s == nil || s.PathMatches == nil { return false } if len(s.PathMatches) == 0 { return false } return true } // GetType returns the Type field if it's non-nil, zero value otherwise. func (s *SearchCodeResult) GetType() string { if s == nil || s.Type == nil { return "" } return *s.Type } // GetQuerySubstituted returns the QuerySubstituted field if it's non-nil, zero value otherwise. func (s *SearchCodeResults) GetQuerySubstituted() bool { if s == nil || s.QuerySubstituted == nil { return false } return *s.QuerySubstituted } // GetValues returns the Values field. func (s *SearchCodeResults) GetValues() *SearchCodeResult { if s == nil { return nil } return s.Values } // GetLines returns the Lines field. func (s *SearchContentMatch) GetLines() *SearchContentMatchLine { if s == nil { return nil } return s.Lines } // GetLine returns the Line field if it's non-nil, zero value otherwise. func (s *SearchContentMatchLine) GetLine() int64 { if s == nil || s.Line == nil { return 0 } return *s.Line } // HasSegments checks if SearchContentMatchLine has any Segments. func (s *SearchContentMatchLine) HasSegments() bool { if s == nil || s.Segments == nil { return false } if len(s.Segments) == 0 { return false } return true } // GetMatch returns the Match field if it's non-nil, zero value otherwise. func (s *SearchMatch) GetMatch() bool { if s == nil || s.Match == nil { return false } return *s.Match } // GetText returns the Text field if it's non-nil, zero value otherwise. func (s *SearchMatch) GetText() string { if s == nil || s.Text == nil { return "" } return *s.Text } // HasAttributes checks if SRCMetadata has any Attributes. func (s *SRCMetadata) HasAttributes() bool { if s == nil || s.Attributes == nil { return false } if len(s.Attributes) == 0 { return false } return true } // GetCommit returns the Commit field. func (s *SRCMetadata) GetCommit() *Commit { if s == nil { return nil } return s.Commit } // GetLinks returns the Links field. func (s *SRCMetadata) GetLinks() *FileHistoryLinks { if s == nil { return nil } return s.Links } // GetMimetype returns the Mimetype field if it's non-nil, zero value otherwise. func (s *SRCMetadata) GetMimetype() string { if s == nil || s.Mimetype == nil { return "" } return *s.Mimetype } // GetPath returns the Path field if it's non-nil, zero value otherwise. func (s *SRCMetadata) GetPath() string { if s == nil || s.Path == nil { return "" } return *s.Path } // GetSize returns the Size field if it's non-nil, zero value otherwise. func (s *SRCMetadata) GetSize() int64 { if s == nil || s.Size == nil { return 0 } return *s.Size } // GetType returns the Type field if it's non-nil, zero value otherwise. func (s *SRCMetadata) GetType() string { if s == nil || s.Type == nil { return "" } return *s.Type } // GetKey returns the Key field if it's non-nil, zero value otherwise. func (s *SSHKeyAddRequest) GetKey() string { if s == nil || s.Key == nil { return "" } return *s.Key } // GetLabel returns the Label field if it's non-nil, zero value otherwise. func (s *SSHKeyAddRequest) GetLabel() string { if s == nil || s.Label == nil { return "" } return *s.Label } // GetAccountStatus returns the AccountStatus field if it's non-nil, zero value otherwise. func (t *Team) GetAccountStatus() string { if t == nil || t.AccountStatus == nil { return "" } return *t.AccountStatus } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (t *Team) GetCreatedOn() time.Time { if t == nil || t.CreatedOn == nil { return time.Time{} } return *t.CreatedOn } // GetDisplayName returns the DisplayName field if it's non-nil, zero value otherwise. func (t *Team) GetDisplayName() string { if t == nil || t.DisplayName == nil { return "" } return *t.DisplayName } // GetHas2FAEnabled returns the Has2FAEnabled field if it's non-nil, zero value otherwise. func (t *Team) GetHas2FAEnabled() string { if t == nil || t.Has2FAEnabled == nil { return "" } return *t.Has2FAEnabled } // GetLinks returns the Links field. func (t *Team) GetLinks() *TeamLinks { if t == nil { return nil } return t.Links } // GetNickname returns the Nickname field if it's non-nil, zero value otherwise. func (t *Team) GetNickname() string { if t == nil || t.Nickname == nil { return "" } return *t.Nickname } // GetUsername returns the Username field if it's non-nil, zero value otherwise. func (t *Team) GetUsername() string { if t == nil || t.Username == nil { return "" } return *t.Username } // GetUUID returns the UUID field if it's non-nil, zero value otherwise. func (t *Team) GetUUID() string { if t == nil || t.UUID == nil { return "" } return *t.UUID } // GetWebsite returns the Website field if it's non-nil, zero value otherwise. func (t *Team) GetWebsite() string { if t == nil || t.Website == nil { return "" } return *t.Website } // GetAvatar returns the Avatar field. func (t *TeamLinks) GetAvatar() *Link { if t == nil { return nil } return t.Avatar } // GetFollowers returns the Followers field. func (t *TeamLinks) GetFollowers() *Link { if t == nil { return nil } return t.Followers } // GetFollowing returns the Following field. func (t *TeamLinks) GetFollowing() *Link { if t == nil { return nil } return t.Following } // GetHooks returns the Hooks field. func (t *TeamLinks) GetHooks() *Link { if t == nil { return nil } return t.Hooks } // GetHTML returns the HTML field. func (t *TeamLinks) GetHTML() *Link { if t == nil { return nil } return t.HTML } // GetMembers returns the Members field. func (t *TeamLinks) GetMembers() *Link { if t == nil { return nil } return t.Members } // GetProjects returns the Projects field. func (t *TeamLinks) GetProjects() *Link { if t == nil { return nil } return t.Projects } // GetRepositories returns the Repositories field. func (t *TeamLinks) GetRepositories() *Link { if t == nil { return nil } return t.Repositories } // GetSelf returns the Self field. func (t *TeamLinks) GetSelf() *Link { if t == nil { return nil } return t.Self } // GetSnippets returns the Snippets field. func (t *TeamLinks) GetSnippets() *Link { if t == nil { return nil } return t.Snippets } // GetPermission returns the Permission field if it's non-nil, zero value otherwise. func (t *TeamPermission) GetPermission() string { if t == nil || t.Permission == nil { return "" } return *t.Permission } // GetTeam returns the Team field. func (t *TeamPermission) GetTeam() *Team { if t == nil { return nil } return t.Team } // GetType returns the Type field if it's non-nil, zero value otherwise. func (t *TeamPermission) GetType() string { if t == nil || t.Type == nil { return "" } return *t.Type } // GetUser returns the User field. func (t *TeamPermission) GetUser() *User { if t == nil { return nil } return t.User } // HasValues checks if TeamPermissions has any Values. func (t *TeamPermissions) HasValues() bool { if t == nil || t.Values == nil { return false } if len(t.Values) == 0 { return false } return true } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (t *TeamProject) GetCreatedOn() time.Time { if t == nil || t.CreatedOn == nil { return time.Time{} } return *t.CreatedOn } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (t *TeamProject) GetDescription() string { if t == nil || t.Description == nil { return "" } return *t.Description } // GetIsPrivate returns the IsPrivate field if it's non-nil, zero value otherwise. func (t *TeamProject) GetIsPrivate() bool { if t == nil || t.IsPrivate == nil { return false } return *t.IsPrivate } // GetKey returns the Key field if it's non-nil, zero value otherwise. func (t *TeamProject) GetKey() string { if t == nil || t.Key == nil { return "" } return *t.Key } // GetLinks returns the Links field. func (t *TeamProject) GetLinks() *TeamProjectLinks { if t == nil { return nil } return t.Links } // GetName returns the Name field if it's non-nil, zero value otherwise. func (t *TeamProject) GetName() string { if t == nil || t.Name == nil { return "" } return *t.Name } // GetOwner returns the Owner field. func (t *TeamProject) GetOwner() *User { if t == nil { return nil } return t.Owner } // GetType returns the Type field if it's non-nil, zero value otherwise. func (t *TeamProject) GetType() string { if t == nil || t.Type == nil { return "" } return *t.Type } // GetUpdatedOn returns the UpdatedOn field if it's non-nil, zero value otherwise. func (t *TeamProject) GetUpdatedOn() time.Time { if t == nil || t.UpdatedOn == nil { return time.Time{} } return *t.UpdatedOn } // GetUUID returns the UUID field if it's non-nil, zero value otherwise. func (t *TeamProject) GetUUID() string { if t == nil || t.UUID == nil { return "" } return *t.UUID } // GetAvatar returns the Avatar field. func (t *TeamProjectLinks) GetAvatar() *Link { if t == nil { return nil } return t.Avatar } // GetHTML returns the HTML field. func (t *TeamProjectLinks) GetHTML() *Link { if t == nil { return nil } return t.HTML } // GetSelf returns the Self field. func (t *TeamProjectLinks) GetSelf() *Link { if t == nil { return nil } return t.Self } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (t *TeamProjectRequest) GetDescription() string { if t == nil || t.Description == nil { return "" } return *t.Description } // GetIsPrivate returns the IsPrivate field if it's non-nil, zero value otherwise. func (t *TeamProjectRequest) GetIsPrivate() bool { if t == nil || t.IsPrivate == nil { return false } return *t.IsPrivate } // GetKey returns the Key field if it's non-nil, zero value otherwise. func (t *TeamProjectRequest) GetKey() string { if t == nil || t.Key == nil { return "" } return *t.Key } // GetName returns the Name field if it's non-nil, zero value otherwise. func (t *TeamProjectRequest) GetName() string { if t == nil || t.Name == nil { return "" } return *t.Name } // HasValues checks if TeamProjects has any Values. func (t *TeamProjects) HasValues() bool { if t == nil || t.Values == nil { return false } if len(t.Values) == 0 { return false } return true } // GetPermission returns the Permission field if it's non-nil, zero value otherwise. func (t *TeamRepoPermission) GetPermission() string { if t == nil || t.Permission == nil { return "" } return *t.Permission } // GetRepository returns the Repository field. func (t *TeamRepoPermission) GetRepository() *Repository { if t == nil { return nil } return t.Repository } // GetType returns the Type field if it's non-nil, zero value otherwise. func (t *TeamRepoPermission) GetType() string { if t == nil || t.Type == nil { return "" } return *t.Type } // GetUser returns the User field. func (t *TeamRepoPermission) GetUser() *User { if t == nil { return nil } return t.User } // HasValues checks if TeamRepoPermissions has any Values. func (t *TeamRepoPermissions) HasValues() bool { if t == nil || t.Values == nil { return false } if len(t.Values) == 0 { return false } return true } // HasValues checks if Teams has any Values. func (t *Teams) HasValues() bool { if t == nil || t.Values == nil { return false } if len(t.Values) == 0 { return false } return true } // GetAccountID returns the AccountID field if it's non-nil, zero value otherwise. func (u *User) GetAccountID() string { if u == nil || u.AccountID == nil { return "" } return *u.AccountID } // GetAccountStatus returns the AccountStatus field if it's non-nil, zero value otherwise. func (u *User) GetAccountStatus() string { if u == nil || u.AccountStatus == nil { return "" } return *u.AccountStatus } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (u *User) GetCreatedOn() time.Time { if u == nil || u.CreatedOn == nil { return time.Time{} } return *u.CreatedOn } // GetDisplayName returns the DisplayName field if it's non-nil, zero value otherwise. func (u *User) GetDisplayName() string { if u == nil || u.DisplayName == nil { return "" } return *u.DisplayName } // GetIsStaff returns the IsStaff field if it's non-nil, zero value otherwise. func (u *User) GetIsStaff() bool { if u == nil || u.IsStaff == nil { return false } return *u.IsStaff } // GetLinks returns the Links field. func (u *User) GetLinks() *UserLinks { if u == nil { return nil } return u.Links } // GetLocation returns the Location field if it's non-nil, zero value otherwise. func (u *User) GetLocation() string { if u == nil || u.Location == nil { return "" } return *u.Location } // GetNickname returns the Nickname field if it's non-nil, zero value otherwise. func (u *User) GetNickname() string { if u == nil || u.Nickname == nil { return "" } return *u.Nickname } // GetType returns the Type field if it's non-nil, zero value otherwise. func (u *User) GetType() string { if u == nil || u.Type == nil { return "" } return *u.Type } // GetUsername returns the Username field if it's non-nil, zero value otherwise. func (u *User) GetUsername() string { if u == nil || u.Username == nil { return "" } return *u.Username } // GetUUID returns the UUID field if it's non-nil, zero value otherwise. func (u *User) GetUUID() string { if u == nil || u.UUID == nil { return "" } return *u.UUID } // GetWebsite returns the Website field if it's non-nil, zero value otherwise. func (u *User) GetWebsite() string { if u == nil || u.Website == nil { return "" } return *u.Website } // GetEmail returns the Email field if it's non-nil, zero value otherwise. func (u *UserEmail) GetEmail() string { if u == nil || u.Email == nil { return "" } return *u.Email } // GetIsConfirmed returns the IsConfirmed field if it's non-nil, zero value otherwise. func (u *UserEmail) GetIsConfirmed() bool { if u == nil || u.IsConfirmed == nil { return false } return *u.IsConfirmed } // GetIsPrimary returns the IsPrimary field if it's non-nil, zero value otherwise. func (u *UserEmail) GetIsPrimary() bool { if u == nil || u.IsPrimary == nil { return false } return *u.IsPrimary } // GetLinks returns the Links field. func (u *UserEmail) GetLinks() *UserEmailLinks { if u == nil { return nil } return u.Links } // GetType returns the Type field if it's non-nil, zero value otherwise. func (u *UserEmail) GetType() string { if u == nil || u.Type == nil { return "" } return *u.Type } // GetSelf returns the Self field. func (u *UserEmailLinks) GetSelf() *Link { if u == nil { return nil } return u.Self } // HasValues checks if UserEmails has any Values. func (u *UserEmails) HasValues() bool { if u == nil || u.Values == nil { return false } if len(u.Values) == 0 { return false } return true } // GetActive returns the Active field if it's non-nil, zero value otherwise. func (u *UserHook) GetActive() bool { if u == nil || u.Active == nil { return false } return *u.Active } // GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. func (u *UserHook) GetCreatedAt() time.Time { if u == nil || u.CreatedAt == nil { return time.Time{} } return *u.CreatedAt } // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (u *UserHook) GetDescription() string { if u == nil || u.Description == nil { return "" } return *u.Description } // HasEvents checks if UserHook has any Events. func (u *UserHook) HasEvents() bool { if u == nil || u.Events == nil { return false } if len(u.Events) == 0 { return false } return true } // GetSubjectType returns the SubjectType field if it's non-nil, zero value otherwise. func (u *UserHook) GetSubjectType() string { if u == nil || u.SubjectType == nil { return "" } return *u.SubjectType } // GetURL returns the URL field if it's non-nil, zero value otherwise. func (u *UserHook) GetURL() string { if u == nil || u.URL == nil { return "" } return *u.URL } // GetUUID returns the UUID field if it's non-nil, zero value otherwise. func (u *UserHook) GetUUID() string { if u == nil || u.UUID == nil { return "" } return *u.UUID } // HasValues checks if UserHooks has any Values. func (u *UserHooks) HasValues() bool { if u == nil || u.Values == nil { return false } if len(u.Values) == 0 { return false } return true } // GetAvatar returns the Avatar field. func (u *UserLinks) GetAvatar() *Link { if u == nil { return nil } return u.Avatar } // GetFollowers returns the Followers field. func (u *UserLinks) GetFollowers() *Link { if u == nil { return nil } return u.Followers } // GetFollowing returns the Following field. func (u *UserLinks) GetFollowing() *Link { if u == nil { return nil } return u.Following } // GetHooks returns the Hooks field. func (u *UserLinks) GetHooks() *Link { if u == nil { return nil } return u.Hooks } // GetHTML returns the HTML field. func (u *UserLinks) GetHTML() *Link { if u == nil { return nil } return u.HTML } // GetRepositories returns the Repositories field. func (u *UserLinks) GetRepositories() *Link { if u == nil { return nil } return u.Repositories } // GetSelf returns the Self field. func (u *UserLinks) GetSelf() *Link { if u == nil { return nil } return u.Self } // GetSnippets returns the Snippets field. func (u *UserLinks) GetSnippets() *Link { if u == nil { return nil } return u.Snippets } // GetPermission returns the Permission field if it's non-nil, zero value otherwise. func (u *UserRepositoriesPermission) GetPermission() string { if u == nil || u.Permission == nil { return "" } return *u.Permission } // GetRepository returns the Repository field. func (u *UserRepositoriesPermission) GetRepository() *Repository { if u == nil { return nil } return u.Repository } // GetType returns the Type field if it's non-nil, zero value otherwise. func (u *UserRepositoriesPermission) GetType() string { if u == nil || u.Type == nil { return "" } return *u.Type } // GetUser returns the User field. func (u *UserRepositoriesPermission) GetUser() *User { if u == nil { return nil } return u.User } // HasValues checks if UserRepositoriesPermissions has any Values. func (u *UserRepositoriesPermissions) HasValues() bool { if u == nil || u.Values == nil { return false } if len(u.Values) == 0 { return false } return true } // HasValues checks if Users has any Values. func (u *Users) HasValues() bool { if u == nil || u.Values == nil { return false } if len(u.Values) == 0 { return false } return true } // GetComment returns the Comment field if it's non-nil, zero value otherwise. func (u *UsersSSHKey) GetComment() string { if u == nil || u.Comment == nil { return "" } return *u.Comment } // GetCreatedOn returns the CreatedOn field if it's non-nil, zero value otherwise. func (u *UsersSSHKey) GetCreatedOn() time.Time { if u == nil || u.CreatedOn == nil { return time.Time{} } return *u.CreatedOn } // GetKey returns the Key field if it's non-nil, zero value otherwise. func (u *UsersSSHKey) GetKey() string { if u == nil || u.Key == nil { return "" } return *u.Key } // GetLabel returns the Label field if it's non-nil, zero value otherwise. func (u *UsersSSHKey) GetLabel() string { if u == nil || u.Label == nil { return "" } return *u.Label } // GetLastUsed returns the LastUsed field if it's non-nil, zero value otherwise. func (u *UsersSSHKey) GetLastUsed() time.Time { if u == nil || u.LastUsed == nil { return time.Time{} } return *u.LastUsed } // GetLinks returns the Links field. func (u *UsersSSHKey) GetLinks() *UsersSSHKeyLinks { if u == nil { return nil } return u.Links } // GetOwner returns the Owner field. func (u *UsersSSHKey) GetOwner() *User { if u == nil { return nil } return u.Owner } // GetType returns the Type field if it's non-nil, zero value otherwise. func (u *UsersSSHKey) GetType() string { if u == nil || u.Type == nil { return "" } return *u.Type } // GetUUID returns the UUID field if it's non-nil, zero value otherwise. func (u *UsersSSHKey) GetUUID() string { if u == nil || u.UUID == nil { return "" } return *u.UUID } // GetSelf returns the Self field. func (u *UsersSSHKeyLinks) GetSelf() *Link { if u == nil { return nil } return u.Self } // HasValues checks if UsersSSHKeys has any Values. func (u *UsersSSHKeys) HasValues() bool { if u == nil || u.Values == nil { return false } if len(u.Values) == 0 { return false } return true } // GetPermission returns the Permission field if it's non-nil, zero value otherwise. func (u *UserTeamsPermission) GetPermission() string { if u == nil || u.Permission == nil { return "" } return *u.Permission } // GetTeam returns the Team field. func (u *UserTeamsPermission) GetTeam() *Team { if u == nil { return nil } return u.Team } // GetType returns the Type field if it's non-nil, zero value otherwise. func (u *UserTeamsPermission) GetType() string { if u == nil || u.Type == nil { return "" } return *u.Type } // GetUser returns the User field. func (u *UserTeamsPermission) GetUser() *User { if u == nil { return nil } return u.User } // HasValues checks if UserTeamsPermissions has any Values. func (u *UserTeamsPermissions) HasValues() bool { if u == nil || u.Values == nil { return false } if len(u.Values) == 0 { return false } return true } // GetID returns the ID field if it's non-nil, zero value otherwise. func (v *Version) GetID() int64 { if v == nil || v.ID == nil { return 0 } return *v.ID } // GetLinks returns the Links field. func (v *Version) GetLinks() *VersionLinks { if v == nil { return nil } return v.Links } // GetName returns the Name field if it's non-nil, zero value otherwise. func (v *Version) GetName() string { if v == nil || v.Name == nil { return "" } return *v.Name } // GetRepository returns the Repository field. func (v *Version) GetRepository() *Repository { if v == nil { return nil } return v.Repository } // GetType returns the Type field if it's non-nil, zero value otherwise. func (v *Version) GetType() string { if v == nil || v.Type == nil { return "" } return *v.Type } // GetSelf returns the Self field. func (v *VersionLinks) GetSelf() *Link { if v == nil { return nil } return v.Self } // GetName returns the Name field if it's non-nil, zero value otherwise. func (v *VersionRequest) GetName() string { if v == nil || v.Name == nil { return "" } return *v.Name } // HasValues checks if Versions has any Values. func (v *Versions) HasValues() bool { if v == nil || v.Values == nil { return false } if len(v.Values) == 0 { return false } return true }
bitbucket/bitbucket-accessors.go
0.802207
0.442396
bitbucket-accessors.go
starcoder
package design_compressed_string_iterator /* 对于一个压缩字符串,设计一个数据结构,它支持如下两种操作: next 和 hasNext。 给定的压缩字符串格式为:每个字母后面紧跟一个正整数,这个整数表示该字母在解压后的字符串里连续出现的次数。 next() - 如果压缩字符串仍然有字母未被解压,则返回下一个字母,否则返回一个空格。 hasNext() - 判断是否还有字母仍然没被解压。 注意: 请记得将你的类在 StringIterator 中 初始化 ,因为静态变量或类变量在多组测试数据中不会被自动清空。更多细节请访问 这里 。 示例: StringIterator iterator = new StringIterator("L1e2t1C1o1d1e1"); iterator.next(); // 返回 'L' iterator.next(); // 返回 'e' iterator.next(); // 返回 'e' iterator.next(); // 返回 't' iterator.next(); // 返回 'C' iterator.next(); // 返回 'o' iterator.next(); // 返回 'd' iterator.hasNext(); // 返回 true iterator.next(); // 返回 'e' iterator.hasNext(); // 返回 false iterator.next(); // 返回 ' ' 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/design-compressed-string-iterator 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ /* 1 最朴素对实现是在初始化时还原字符串,不过这样可能内存占用太大 2 可用chars和nums两个数组记录原字符串里的字符及每个字符的出现次数 ``` type StringIterator struct { chars []byte nums []int index int } func Constructor(compressedString string) StringIterator { r := StringIterator{} i := 0 for i < len(compressedString) { ch := compressedString[i] r.chars = append(r.chars, ch) i ++ num := 0 for i< len(compressedString) && compressedString[i] >= '0' && compressedString[i] <= '9' { num = 10 * num + int(compressedString[i]-'0') i ++ } r.nums = append(r.nums, num) } return r } func (si *StringIterator) Next() byte { if si.HasNext() { r := si.chars[si.index] si.nums[si.index] -- if si.nums[si.index] == 0 { si.index ++ } return r } return ' ' } func (si *StringIterator) HasNext() bool { return len(si.chars) > si.index } ``` */ /* 3 不对原字符串做处理;在实际对操作里处理 */ type StringIterator struct { s string num int ch byte index int } func Constructor(compressedString string) StringIterator { return StringIterator{s: compressedString} } func (si *StringIterator) Next() byte { if !si.HasNext() { return ' ' } if si.num == 0 { si.ch = si.s[si.index] si.index++ for si.index < len(si.s) && si.s[si.index] >= '0' && si.s[si.index] <= '9' { si.num = 10*si.num + int(si.s[si.index]-'0') si.index++ } } si.num-- return si.ch } func (si *StringIterator) HasNext() bool { return len(si.s) > si.index || si.num > 0 }
solutions/design-compressed-string-iterator/d.go
0.572245
0.786664
d.go
starcoder
package cpi import ( "sort" "time" ) // timeSeries stores data and sort them by timestamp type timeSeries struct { timeline []int64 data map[int64]float64 } func newTimeSeries() *timeSeries { return &timeSeries{ data: make(map[int64]float64), } } func (t *timeSeries) add(value float64, timestamp time.Time) { t.data[timestamp.UnixNano()] = value t.timeline = append(t.timeline, timestamp.UnixNano()) sort.Sort(int64Asc(t.timeline)) } func (t *timeSeries) getByUnixNano(nano int64) (float64, bool) { v, ok := t.data[nano] return v, ok } // rangeSearch output data series between the start and end timestamp func (t *timeSeries) rangeSearch(start, end time.Time) *timeSeries { if end.Before(start) { return nil } startIndex := sort.Search(len(t.timeline), func(i int) bool { return t.timeline[i] >= start.UnixNano() }) if startIndex == len(t.timeline) { return nil } endIndex := sort.Search(len(t.timeline), func(i int) bool { return t.timeline[i] >= end.UnixNano() }) if endIndex < len(t.timeline) && t.timeline[endIndex] == end.UnixNano() { endIndex++ } timeRange := t.timeline[startIndex:endIndex] ret := newTimeSeries() for _, ts := range timeRange { v, ok := t.data[ts] if !ok { continue } ret.add(v, time.Unix(0, ts)) } return ret } // normalize normalize the data value to 1 func (t timeSeries) normalize() *timeSeries { var sum float64 for _, v := range t.data { sum += v } ret := newTimeSeries() for tl, v := range t.data { ret.add(v/sum, time.Unix(0, tl)) } return ret } // expire delete expired data func (t *timeSeries) expire(before time.Time) { i := sort.Search(len(t.timeline), func(i int) bool { return t.timeline[i] >= before.UnixNano() }) expired := t.timeline[:i] if i == len(t.timeline) { t.timeline = []int64{} } else { t.timeline = t.timeline[i:] } for _, e := range expired { delete(t.data, e) } } type int64Asc []int64 // Len returns slice length func (i64 int64Asc) Len() int { return len(i64) } // Less compares slice elements func (i64 int64Asc) Less(i, j int) bool { return i64[i] < i64[j] } // Swap swaps slice elements func (i64 int64Asc) Swap(i, j int) { i64[i], i64[j] = i64[j], i64[i] }
pkg/caelus/cpi/time_series.go
0.723407
0.400808
time_series.go
starcoder
package gosthopper func DoEncrypt(block [16]uint8, rkeys [10][16]uint8) [16]uint8 { // This is a spare, SLOW Go implementation of cipher. This code // should be only compiled for target platforms different from amd64. var r [16]uint8 ct := block // Encryption process follows. for i := 0; i < 9; i++ { // We have nine basic rounds. for k := range ct { ct[k] = ct[k] ^ rkeys[i][k] // XOR with current round key. } for k := range r { r[k] = LSEncLookup[0][ct[0]][k] // Prepare for lookup. } for j := 1; j <= 15; j++ { // There are 15 values from lookup table to XOR. // Calculate XOR with lookup table elements. Each element corresponds // to particular value of byte at current block position (ct[j]). for k := range r { r[k] = r[k] ^ LSEncLookup[j][ct[j]][k] } } ct = r } for k := range ct { ct[k] = ct[k] ^ rkeys[9][k] } // XOR with the last round key. return ct } func DoEncryptCounter(nonce [16]uint8, block [16]uint8, rkeys [10][16]uint8) [16]uint8 { // Routine for counter mode. Almost the same as DoEncrypt(). var r [16]uint8 ct := nonce // Encryption process follows. for i := 0; i < 9; i++ { // We have nine basic rounds. for k := range ct { ct[k] = ct[k] ^ rkeys[i][k] // XOR with current round key. } for k := range r { r[k] = LSEncLookup[0][ct[0]][k] // Prepare for lookup. } for j := 1; j <= 15; j++ { // There are 15 values from lookup table to XOR. // Calculate XOR with lookup table elements. Each element corresponds // to particular value of byte at current block position (ct[j]). for k := range r { r[k] = r[k] ^ LSEncLookup[j][ct[j]][k] } } ct = r } for k := range ct { ct[k] = ct[k] ^ rkeys[9][k] } // XOR with the last round key. for k := range ct { ct[k] = ct[k] ^ block[k] } // XOR with plain text. return ct } func DoDecrypt(block [16]uint8, rkeys [10][16]uint8) [16]uint8 { // This is a spare, SLOW Go implementation of cipher. This code // should be only compiled for target platforms different from amd64. var r [16]uint8 pt := block // First - apply inverse L using lookup table. for k := range r { r[k] = LInvLookup[0][pt[0]][k] } for j := 1; j <= 15; j++ { for k := range r { r[k] = r[k] ^ LInvLookup[j][pt[j]][k] } } pt = r for i := 9; i > 1; i-- { // XOR with current round key (inversed). for k := range pt { pt[k] = pt[k] ^ rkeys[i][k] } // Apply SL transformations using lookup table. for k := range r { r[k] = SLDecLookup[0][pt[0]][k] } for j := 1; j <= 15; j++ { for k := range r { r[k] = r[k] ^ SLDecLookup[j][pt[j]][k] } } pt = r } for k := range pt { pt[k] = pt[k] ^ rkeys[1][k] // XOR with K_2 pt[k] = PiInverseTable[pt[k]] // Inverse Pi pt[k] = pt[k] ^ rkeys[0][k] // XOR with K_1 } return pt // Plain text. }
crypto/gosthopper/docipher.go
0.681621
0.416025
docipher.go
starcoder
package framework import "fmt" // RecordEvidence records evidence for the compliance check active in the given context. func RecordEvidence(ctx ComplianceContext, status Status, msg string) { ctx.RecordEvidence(status, msg) } // RecordEvidencef records evidence for the compliance check active in the given context. func RecordEvidencef(ctx ComplianceContext, status Status, format string, args ...interface{}) { ctx.RecordEvidence(status, fmt.Sprintf(format, args...)) } // Pass records "pass" evidence for the compliance check active in the given context. func Pass(ctx ComplianceContext, msg string) { RecordEvidence(ctx, PassStatus, msg) } // Passf records "pass" evidence for the compliance check active in the given context. func Passf(ctx ComplianceContext, format string, args ...interface{}) { Pass(ctx, fmt.Sprintf(format, args...)) } // PassNow records "pass" evidence for the compliance check active in the given context, and terminates the check. func PassNow(ctx ComplianceContext, msg string) { Pass(ctx, msg) Abort(ctx, nil) } // PassNowf records "pass" evidence for the compliance check active in the given context, and terminates the check. func PassNowf(ctx ComplianceContext, format string, args ...interface{}) { Passf(ctx, format, args...) Abort(ctx, nil) } // Fail records "fail" evidence for the compliance check active in the given context. func Fail(ctx ComplianceContext, msg string) { RecordEvidence(ctx, FailStatus, msg) } // Failf records "fail" evidence for the compliance check active in the given context. func Failf(ctx ComplianceContext, format string, args ...interface{}) { Fail(ctx, fmt.Sprintf(format, args...)) } // FailNow records "fail" evidence for the compliance check active in the given context, and terminates the check. func FailNow(ctx ComplianceContext, msg string) { Fail(ctx, msg) Abort(ctx, nil) } // FailNowf records "fail" evidence for the compliance check active in the given context, and terminates the check. func FailNowf(ctx ComplianceContext, format string, args ...interface{}) { Failf(ctx, format, args...) Abort(ctx, nil) } // Skip records "skip" evidence for the compliance check active in the given context. func Skip(ctx ComplianceContext, msg string) { RecordEvidence(ctx, SkipStatus, msg) } // Skipf records "skip" evidence for the compliance check active in the given context. func Skipf(ctx ComplianceContext, format string, args ...interface{}) { Skip(ctx, fmt.Sprintf(format, args...)) } // SkipNow records "skip" evidence for the compliance check active in the given context, and terminates the check. func SkipNow(ctx ComplianceContext, msg string) { Skip(ctx, msg) Abort(ctx, nil) } // SkipNowf records "skip" evidence for the compliance check active in the given context, and terminates the check. func SkipNowf(ctx ComplianceContext, format string, args ...interface{}) { Skipf(ctx, format, args...) Abort(ctx, nil) } // Abortf aborts with an error created from the given format and args via `fmt.Errorf`. func Abortf(ctx ComplianceContext, format string, args ...interface{}) { Abort(ctx, fmt.Errorf(format, args...)) } // Note records "note" evidence for the compliance check active in the given context. func Note(ctx ComplianceContext, msg string) { RecordEvidence(ctx, NoteStatus, msg) } // Notef records "note" evidence for the compliance check active in the given context. func Notef(ctx ComplianceContext, format string, args ...interface{}) { Note(ctx, fmt.Sprintf(format, args...)) } // NoteNow records "note" evidence for the compliance check active in the given context, and terminates the check. func NoteNow(ctx ComplianceContext, msg string) { Note(ctx, msg) Abort(ctx, nil) } // NoteNowf records "note" evidence for the compliance check active in the given context, and terminates the check. func NoteNowf(ctx ComplianceContext, format string, args ...interface{}) { Notef(ctx, format, args...) Abort(ctx, nil) }
central/compliance/framework/control_helpers.go
0.621081
0.473109
control_helpers.go
starcoder
package repo import ( "errors" "fmt" "math" "math/big" "strconv" ) const ( CurrencyCodeValidMinimumLength = 3 CurrencyCodeValidMaximumLength = 4 ) var ( ErrCurrencyValueInsufficientPrecision = errors.New("unable to accurately represent value as int64") ErrCurrencyValueNegativeRate = errors.New("conversion rate must be greater than zero") ErrCurrencyValueAmountInvalid = errors.New("invalid amount") ErrCurrencyValueDefinitionInvalid = errors.New("invalid currency definition") ) // CurrencyValue represents the amount and variety of currency type CurrencyValue struct { Amount *big.Int Currency *CurrencyDefinition } // NewCurrencyValueFromInt is a convenience function which converts an int64 // into a string and passes the arguments to NewCurrencyValue func NewCurrencyValueFromInt(amount int64, currency *CurrencyDefinition) (*CurrencyValue, error) { return NewCurrencyValue(strconv.FormatInt(amount, 10), currency) } // NewCurrencyValueFromUint is a convenience function which converts an int64 // into a string and passes the arguments to NewCurrencyValue func NewCurrencyValueFromUint(amount uint64, currency *CurrencyDefinition) (*CurrencyValue, error) { return NewCurrencyValue(strconv.FormatUint(amount, 10), currency) } // NewCurrencyValue accepts string amounts and currency codes, and creates // a valid CurrencyValue func NewCurrencyValue(amount string, currency *CurrencyDefinition) (*CurrencyValue, error) { var ( i = new(big.Int) ok bool ) if _, ok = i.SetString(amount, 0); !ok { return nil, ErrCurrencyValueAmountInvalid } return &CurrencyValue{Amount: i, Currency: currency}, nil } // AmountInt64 returns a valid int64 or an error func (v *CurrencyValue) AmountInt64() (int64, error) { if !v.Amount.IsInt64() { return 0, ErrCurrencyValueInsufficientPrecision } return v.Amount.Int64(), nil } // AmountUint64 returns a valid int64 or an error func (v *CurrencyValue) AmountUint64() (uint64, error) { if !v.Amount.IsUint64() { return 0, ErrCurrencyValueInsufficientPrecision } return v.Amount.Uint64(), nil } // String returns a string representation of a CurrencyValue func (v *CurrencyValue) String() string { return fmt.Sprintf("%s %s", v.Amount.String(), v.Currency.String()) } // Valid returns an error if the CurrencyValue is invalid func (v *CurrencyValue) Valid() error { if v.Amount == nil { return ErrCurrencyValueAmountInvalid } if err := v.Currency.Valid(); err != nil { return err } return nil } // Equal indicates if the amount and variety of currency is equivalent func (v *CurrencyValue) Equal(other *CurrencyValue) bool { if v == nil || other == nil { return false } if !v.Currency.Equal(other.Currency) { return false } return v.Amount.Cmp(other.Amount) == 0 } // ConvertTo will perform the following math given its arguments are valid: // v.Amount * exchangeRate * (final.Currency.Divisibility/v.Currency.Divisibility) // where v is the receiver, exchangeRate is the ratio of (1 final.Currency/v.Currency) // v and final must both be Valid() and exchangeRate must not be zero. func (v *CurrencyValue) ConvertTo(final *CurrencyDefinition, exchangeRate float64) (*CurrencyValue, error) { if err := v.Valid(); err != nil { return nil, fmt.Errorf("cannot convert invalid value: %s", err.Error()) } if err := final.Valid(); err != nil { return nil, fmt.Errorf("cannot convert to invalid currency: %s", err.Error()) } if exchangeRate <= 0 { return nil, ErrCurrencyValueNegativeRate } var ( j = new(big.Float) currencyRate = new(big.Float) divisibilityRate = new(big.Float) divRateFloat = math.Pow10(int(final.Divisibility)) / math.Pow10(int(v.Currency.Divisibility)) ) currencyRate.SetFloat64(exchangeRate) divisibilityRate.SetFloat64(divRateFloat) j.SetInt(v.Amount) j.Mul(j, currencyRate) j.Mul(j, divisibilityRate) result, _ := j.Int(nil) return &CurrencyValue{Amount: result, Currency: final}, nil }
repo/currency.go
0.831143
0.484136
currency.go
starcoder
package spdy /* Internals documentation The goroutines, lifetimes and channels of this package is a bit involved, so here's a quick overview. Once a connection has been established, there are 3 main goroutines. - The session goroutine - The stream goroutine - The outFramer goroutine Session goroutine: The session goroutine keeps the internal state of the session and receives events from the client. Whenever a stream is created, the session goroutine adds the stream to it's internal data structure and starts a stream goroutine. It also muxes events from the client connection to the appropriate stream goroutine. For example, it adjusts the window size, sends resets to the proper goroutine and fills the buffers of a stream when receiving data frames. interfaces: - closemsgch: send a message to this channel to request that the entire session shut down. This is usually used when there's a network or spdy protocol error. -closech: This channel is closed when the session is going away. If you intend to block for some event, receive from this channel in your select to be notified when the session is closing - finch: Send on this channel to request that a stream be removed from the session data structures. Note that it's the reposibility of the clients using this interface to send out reset messages and data frames with the fin flag set. Stream goroutine: For each request on a session, a stream goroutine is spawned. The handler is run inside this goroutine and it's responsible for sending out the syn stream frame, the data frames and closing frame. interfaces: - reset: this channel is closed when the stream is either reset or the session is going away. If you're blocking on a select, listen to this channel to be notified. - recvData: this channel acts as a flag, telling the stream goroutine that there is new data to be read. Do a non-blocking send to this channel to notify the stream goroutine. - windowUpdate: this channel acts as a flag, telling the stream that there the send window has been updated and it can continue sending frames again. Do a non blocking select on this channel to notify the stream goroutine. the outFramer goroutine: The outFramer is the arbiter of access to the outgoing connection. Broadly speaking, it implements a prioritized mutex, where the session is prioritized highest and the streams are prioritized according to their SPDY session priority. The interface to this goroutine is the helper functions. They handle the mutex locking and avoid allocation by using the internal buffers that the outframer has. */
doc.go
0.665519
0.605012
doc.go
starcoder
package hbook import "math" // Dist0D is a 0-dim distribution. type Dist0D struct { N int64 // number of entries SumW float64 // sum of weights SumW2 float64 // sum of squared weights } func (d Dist0D) clone() Dist0D { return d } // Rank returns the number of dimensions of the distribution. func (*Dist0D) Rank() int { return 1 } // Entries returns the number of entries in the distribution. func (d *Dist0D) Entries() int64 { return d.N } // EffEntries returns the number of weighted entries, such as: // (\sum w)^2 / \sum w^2 func (d *Dist0D) EffEntries() float64 { if d.SumW2 == 0 { return 0 } return d.SumW * d.SumW / d.SumW2 } // errW returns the absolute error on sumW() func (d *Dist0D) errW() float64 { return math.Sqrt(d.SumW2) } // relErrW returns the relative error on sumW() func (d *Dist0D) relErrW() float64 { // FIXME(sbinet) check for low stats ? return d.errW() / d.SumW } func (d *Dist0D) fill(w float64) { d.N++ d.SumW += w d.SumW2 += w * w } func (d *Dist0D) addScaled(a, a2 float64, o Dist0D) { d.N += o.N d.SumW += a * o.SumW d.SumW2 += a2 * o.SumW2 } func (d *Dist0D) scaleW(f float64) { d.SumW *= f d.SumW2 *= f * f } // Dist1D is a 1-dim distribution. type Dist1D struct { Dist Dist0D // weight moments Stats struct { SumWX float64 // 1st order weighted x moment SumWX2 float64 // 2nd order weighted x moment } } func (d Dist1D) clone() Dist1D { return Dist1D{ Dist: d.Dist.clone(), Stats: d.Stats, } } // Rank returns the number of dimensions of the distribution. func (*Dist1D) Rank() int { return 1 } // Entries returns the number of entries in the distribution. func (d *Dist1D) Entries() int64 { return d.Dist.Entries() } // EffEntries returns the effective number of entries in the distribution. func (d *Dist1D) EffEntries() float64 { return d.Dist.EffEntries() } // SumW returns the sum of weights of the distribution. func (d *Dist1D) SumW() float64 { return d.Dist.SumW } // SumW2 returns the sum of squared weights of the distribution. func (d *Dist1D) SumW2() float64 { return d.Dist.SumW2 } // SumWX returns the 1st order weighted x moment. func (d *Dist1D) SumWX() float64 { return d.Stats.SumWX } // SumWX2 returns the 2nd order weighted x moment. func (d *Dist1D) SumWX2() float64 { return d.Stats.SumWX2 } // errW returns the absolute error on sumW() func (d *Dist1D) errW() float64 { return d.Dist.errW() } // relErrW returns the relative error on sumW() func (d *Dist1D) relErrW() float64 { return d.Dist.relErrW() } // mean returns the weighted mean of the distribution func (d *Dist1D) mean() float64 { // FIXME(sbinet): check for low stats? return d.SumWX() / d.SumW() } // variance returns the weighted variance of the distribution, defined as: // sig2 = ( \sum(wx^2) * \sum(w) - \sum(wx)^2 ) / ( \sum(w)^2 - \sum(w^2) ) // see: https://en.wikipedia.org/wiki/Weighted_arithmetic_mean func (d *Dist1D) variance() float64 { // FIXME(sbinet): check for low stats? sumw := d.SumW() num := d.SumWX2()*sumw - d.SumWX()*d.SumWX() den := sumw*sumw - d.SumW2() v := num / den return math.Abs(v) } // stdDev returns the weighted standard deviation of the distribution func (d *Dist1D) stdDev() float64 { return math.Sqrt(d.variance()) } // stdErr returns the weighted standard error of the distribution func (d *Dist1D) stdErr() float64 { // FIXME(sbinet): check for low stats? // TODO(sbinet): unbiased should check that Neff>1 and divide by N-1? return math.Sqrt(d.variance() / d.EffEntries()) } // rms returns the weighted RMS of the distribution, defined as: // rms = \sqrt{\sum{w . x^2} / \sum{w}} func (d *Dist1D) rms() float64 { // FIXME(sbinet): check for low stats? meansq := d.SumWX2() / d.SumW() return math.Sqrt(meansq) } func (d *Dist1D) fill(x, w float64) { d.Dist.fill(w) d.Stats.SumWX += w * x d.Stats.SumWX2 += w * x * x } func (d *Dist1D) addScaled(a, a2 float64, o Dist1D) { d.Dist.addScaled(a, a2, o.Dist) d.Stats.SumWX += a * o.Stats.SumWX d.Stats.SumWX2 += a * o.Stats.SumWX2 } func (d *Dist1D) scaleW(f float64) { d.Dist.scaleW(f) d.Stats.SumWX *= f d.Stats.SumWX2 *= f } func (d *Dist1D) scaleX(f float64) { d.Stats.SumWX *= f d.Stats.SumWX2 *= f * f } // Dist2D is a 2-dim distribution. type Dist2D struct { X Dist1D // x moments Y Dist1D // y moments Stats struct { SumWXY float64 // 2nd-order cross-term } } // Rank returns the number of dimensions of the distribution. func (*Dist2D) Rank() int { return 2 } // Entries returns the number of entries in the distribution. func (d *Dist2D) Entries() int64 { return d.X.Entries() } // EffEntries returns the effective number of entries in the distribution. func (d *Dist2D) EffEntries() float64 { return d.X.EffEntries() } // SumW returns the sum of weights of the distribution. func (d *Dist2D) SumW() float64 { return d.X.SumW() } // SumW2 returns the sum of squared weights of the distribution. func (d *Dist2D) SumW2() float64 { return d.X.SumW2() } // SumWX returns the 1st order weighted x moment func (d *Dist2D) SumWX() float64 { return d.X.SumWX() } // SumWX2 returns the 2nd order weighted x moment func (d *Dist2D) SumWX2() float64 { return d.X.SumWX2() } // SumWY returns the 1st order weighted y moment func (d *Dist2D) SumWY() float64 { return d.Y.SumWX() } // SumWY2 returns the 2nd order weighted y moment func (d *Dist2D) SumWY2() float64 { return d.Y.SumWX2() } // SumWXY returns the 2nd-order cross-term. func (d *Dist2D) SumWXY() float64 { return d.Stats.SumWXY } // errW returns the absolute error on sumW() func (d *Dist2D) errW() float64 { return d.X.errW() } // relErrW returns the relative error on sumW() func (d *Dist2D) relErrW() float64 { return d.X.relErrW() } // xMean returns the weighted mean of the distribution func (d *Dist2D) xMean() float64 { return d.X.mean() } // yMean returns the weighted mean of the distribution func (d *Dist2D) yMean() float64 { return d.Y.mean() } // xVariance returns the weighted variance of the distribution func (d *Dist2D) xVariance() float64 { return d.X.variance() } // yVariance returns the weighted variance of the distribution func (d *Dist2D) yVariance() float64 { return d.Y.variance() } // xStdDev returns the weighted standard deviation of the distribution func (d *Dist2D) xStdDev() float64 { return d.X.stdDev() } // yStdDev returns the weighted standard deviation of the distribution func (d *Dist2D) yStdDev() float64 { return d.Y.stdDev() } // xStdErr returns the weighted standard error of the distribution func (d *Dist2D) xStdErr() float64 { return d.X.stdErr() } // yStdErr returns the weighted standard error of the distribution func (d *Dist2D) yStdErr() float64 { return d.Y.stdErr() } // xRMS returns the weighted RMS of the distribution func (d *Dist2D) xRMS() float64 { return d.X.rms() } // yRMS returns the weighted RMS of the distribution func (d *Dist2D) yRMS() float64 { return d.Y.rms() } func (d *Dist2D) fill(x, y, w float64) { d.X.fill(x, w) d.Y.fill(y, w) d.Stats.SumWXY += w * x * y } func (d *Dist2D) scaleW(f float64) { d.X.scaleW(f) d.Y.scaleW(f) d.Stats.SumWXY *= f } func (d *Dist2D) scaleX(f float64) { d.X.scaleX(f) d.Stats.SumWXY *= f } func (d *Dist2D) scaleY(f float64) { d.Y.scaleX(f) d.Stats.SumWXY *= f } func (d *Dist2D) scaleXY(fx, fy float64) { d.scaleX(fx) d.scaleY(fy) }
hbook/dist.go
0.810816
0.579311
dist.go
starcoder
// API for: // 1) gonum/mat mat.VecDense and mat.Dense structures; // 2) float64 arrays. // Reading: https://en.wikipedia.org/wiki/Distance package distance import ( "fmt" "gonum.org/v1/gonum/mat" "math" ) type dimError struct { err string firstDim int secondDim int } func (e *dimError) Error() string { return fmt.Sprintf("%s: first dimension: %d, second dimension: %d", e.err, e.firstDim, e.secondDim) } // VecEuclidean calculates Euclidean (L2) distance between // mat.VecDence vector instances. // Reading: https://en.wikipedia.org/wiki/Euclidean_distance // General form: d(p, q) = sqrt(pow(q1-p1, 2) + pow(q2-p2, 2) + ...) func VecEuclidean(v, u *mat.VecDense) (dist float64) { if err := checkDim(v, u); err != nil { panic(err) } vr, _ := v.Dims() for i := 0; i < vr; i++ { dist += math.Pow(v.AtVec(i)-u.AtVec(i), 2) } return math.Sqrt(dist) } // VecL1 calculates taxicab distance (L1) between // mat.VecDence vector instances. // Reading: https://en.wikipedia.org/wiki/Taxicab_geometry // General form: d(p, q) = ||q - p||1 = sum(|pi - qi|, 1, n) func VecL1(v, u *mat.VecDense) (dist float64) { if err := checkDim(v, u); err != nil { panic(err) } vr, _ := v.Dims() for i := 0; i < vr; i++ { dist += math.Abs(v.AtVec(i) - u.AtVec(i)) } return } // VecCanberra calculates canberra distance between // mat.VecDence vector instances. // Reading: https://en.wikipedia.org/wiki/Canberra_distance // General form: d(p, q) = sum((|pi - qi|/|pi|+|qi|) ,1, n) func VecCanberra(v, u *mat.VecDense) (dist float64) { if err := checkDim(v, u); err != nil { panic(err) } vr, _ := v.Dims() for i := 0; i < vr; i++ { numerator := math.Abs(v.AtVec(i) - u.AtVec(i)) denominator := math.Abs(v.AtVec(i)) + math.Abs(u.AtVec(i)) dist += numerator / denominator } return } // VecChebyshev calculates Chebyshev distance (Linf) between // mat.VecDence vector instances. // Reading: https://en.wikipedia.org/wiki/Chebyshev_distance // General form: d(p, q) = max(|xi - yi|, i) // whitch equal to: lim(sum(|xi - yi|^p, 1, n)^1/p, p -> inf) func VecChebyshev(v, u *mat.VecDense) (dist float64) { if err := checkDim(v, u); err != nil { panic(err) } vr, _ := v.Dims() for i := 0; i < vr; i++ { dist = math.Max(dist, math.Abs(v.AtVec(i)-u.AtVec(i))) } return } func checkDim(N, M mat.Matrix) (err error){ Nr, Nc := N.Dims() Mr, Mc := M.Dims() switch { case Nc == 1 && Mc == 1: if Nr != Mr { return &dimError{"Vectors dimension mismatch", Nr, Mr} } default: if Nc != Mr { return &dimError{"Matrices dimension mismatch", Nc, Mr} } } return nil }
linalg/distance/distance.go
0.67854
0.54056
distance.go
starcoder
package util import ( "fmt" "math" ) // PairType defines a two-dimensional coordianate. type PairType struct { X, Y float64 } // Cluster breaks apart pairs into zero or more slices that each contain at // least minPts pairs and have gaps between X values no greater than gapX. // Elements in pairs must be ordered from low X value to high. func Cluster(pairs []PairType, minPts int, gapX float64) [][]PairType { var ln int var clList [][]PairType var list []PairType list = make([]PairType, 0, 32) place := func() { // list has contiguous points; discard if fewer than minPts if len(list) >= minPts { clList = append(clList, list) } list = make([]PairType, 0, 32) } for _, pr := range pairs { ln = len(list) switch { case ln == 0: list = append(list, pr) case pr.X < list[ln-1].X+gapX: list = append(list, pr) default: place() list = append(list, pr) } } place() return clList } // BoundingBox returns the smallest and greatest values of X and Y in the // specified slice of coordinates. func BoundingBox(pairs []PairType) (lf, rt, tp, bt float64) { var xr, yr RangeType for j, pr := range pairs { xr.Set(pr.X, j == 0) yr.Set(pr.Y, j == 0) } return xr.Min, xr.Max, yr.Max, yr.Min } // RangeType holds the minimum and maximum values of a range. type RangeType struct { Min, Max float64 } // Set adjusts the fields Min and Max such that Min holds the smallest value // encountered and Max the largest. If init is true, val is assigned to both // Min and Max. If init is false, val is assigned to Min only if it is smaller, // and val is assigned to Max only if it is greater. func (r *RangeType) Set(val float64, init bool) { if init { r.Min = val r.Max = val } else { if val < r.Min { r.Min = val } if val > r.Max { r.Max = val } } } // LinearEquationType describes a line with its slope and intercept type LinearEquationType struct { Slope, Intercept float64 } // String implements the fmt Stringer interface func (eq LinearEquationType) String() string { var op string switch math.Signbit(eq.Intercept) { case true: op = "-" eq.Intercept = -eq.Intercept default: op = "+" } return fmt.Sprintf("y = %f x %s %f", eq.Slope, op, eq.Intercept) } // Perpendicular returns an equation that is perpendicular to eq and intersects // it at x. func (eq LinearEquationType) Perpendicular(x float64) (p LinearEquationType) { if eq.Slope != 0 { p.Slope = -1 / eq.Slope p.Intercept = (eq.Slope*x + eq.Intercept) - p.Slope*x } return } // PerpendicularPoint returns an equation that is perpendicular to eq and // includes the point specified by x and y. func (eq LinearEquationType) PerpendicularPoint(x, y float64) (p LinearEquationType) { if eq.Slope != 0 { p.Slope = -1 / eq.Slope p.Intercept = y - p.Slope*x } return } // DistanceToPoint returns the shortest distance from the specified point to // eq. func (eq LinearEquationType) DistanceToPoint(x, y float64) (d float64) { if eq.Slope != 0 { p := eq.PerpendicularPoint(x, y) xi := (eq.Intercept - p.Intercept) / (p.Slope - eq.Slope) yi := eq.Slope*xi + eq.Intercept dx := xi - x dy := yi - y d = math.Sqrt(dx*dx + dy*dy) } else { d = math.Abs(y - eq.Intercept) } return } // LinearY returns the value of the linear function defined by intercept and // slope at the specified x value. func LinearY(slope, intercept, x float64) (y float64) { y = slope*x + intercept return } // Linear returns the y-intercept and slope of the straight line joining the // two specified points. For scaling purposes, associate the arguments as // follows: x1: observed low value, y1: desired low value, x2: observed high // value, y2: desired high value. func Linear(x1, y1, x2, y2 float64) (eq LinearEquationType) { if x2 != x1 { eq.Slope = (y2 - y1) / (x2 - x1) eq.Intercept = y2 - x2*eq.Slope } return } // LinearPointSlope returns the y-intercept of the straight line joining the // specified arbitrary point (not necessarily an intercept) and the line's // slope. func LinearPointSlope(x, y, slope float64) (intercept float64) { intercept = y - slope*x return } // AverageType manages the calculation of a running average type AverageType struct { weight float64 value float64 } // Add adds a value to a running average. weight is quietly constrained to the // range [0, 1]. func (avg *AverageType) Add(val, weight float64) { if weight > 0 { if weight > 1 { weight = 1 } oldWeight := avg.weight avg.weight += weight avg.value = (avg.value*oldWeight + val*weight) / avg.weight } } // Value returns the current average of submitted values func (avg AverageType) Value() float64 { return avg.value } // RootMeanSquareLinear returns the RMS value for the specified regression // variables. func RootMeanSquareLinear(xList, yList []float64, intercept, slope float64) (rms float64) { count := len(xList) if count > 0 && count == len(yList) { for j := 0; j < count; j++ { yEst := xList[j]*slope + intercept diff := yEst - yList[j] rms += diff * diff } rms = math.Sqrt(rms / float64(count)) } return } // RootMeanSquare returns the RMS value for the specified slice of values. From // https://en.wikipedia.org/wiki/Root_mean_square: In Estimation theory, the // root mean square error of an estimator is a measure of the imperfection of // the fit of the estimator to the data. func RootMeanSquare(list []float64) (rms float64) { count := len(list) if count > 0 { for _, val := range list { rms += val * val } rms = math.Sqrt(rms / float64(count)) } return } // GeometricMean returns the nth root of the product of the n values in list. func GeometricMean(list []float64) (mean float64) { count := len(list) if count > 0 { mean = 1 for _, val := range list { mean *= val } if count > 1 { mean = math.Pow(mean, float64(1)/float64(count)) } } return } // ArithmeticMean returns the sum of the values in list divided by the number // of values. func ArithmeticMean(list []float64) (mean float64) { count := len(list) if count > 0 { for _, val := range list { mean += val } if count > 1 { mean /= float64(count) } } return }
go/util/mth.go
0.850562
0.602149
mth.go
starcoder
package graph type Graph struct { key string superstep int vertices map[string]*vertex } type vertex struct { value interface{} mutableValue interface{} edges map[string]*edge } type edge struct { value interface{} mutableValue interface{} } func NewGraph(capacity int) *Graph { return &Graph{vertices: make(map[string]*vertex, capacity)} } func (g *Graph) setVertexMutableValue(id string, value interface{}) { v := g.ensureVertex(id) v.mutableValue = value } func (g *Graph) setVertexValue(id string, value interface{}) { v := g.ensureVertex(id) v.value = value } func (g *Graph) setEdgeValue(from string, to string, value interface{}) { e := g.ensureEdge(from, to) e.value = value } func (g *Graph) setEdgeMutableValue(from string, to string, value interface{}) { e := g.ensureEdge(from, to) e.mutableValue = value } func (g *Graph) removeVertex(id string) { _, ok := g.vertices[id] if !ok { return } delete(g.vertices, id) for _, v := range g.vertices { delete(v.edges, id) } } func (g *Graph) removeEdge(from string, to string) { v, ok := g.vertices[from] if !ok { return } delete(v.edges, to) } func (g *Graph) VertexValue(id string) (interface{}, bool) { v, ok := g.vertices[id] if !ok { return nil, false } return v.value, true } func (g *Graph) VertexMutableValue(id string) (interface{}, bool) { v, ok := g.vertices[id] if !ok { return nil, false } return v.mutableValue, true } func (g *Graph) HasVertex(id string) bool { _, ok := g.VertexValue(id) return ok } func (g *Graph) EdgeValue(from string, to string) (interface{}, bool) { v, ok := g.vertices[from] if !ok { return nil, false } e, ok := v.edges[to] if !ok { return nil, false } return e.value, true } func (g *Graph) EdgeMutableValue(from string, to string) (interface{}, bool) { v, ok := g.vertices[from] if !ok { return nil, false } e, ok := v.edges[to] if !ok { return nil, false } return e.mutableValue, true } func (g *Graph) HasEdge(from string, to string) bool { _, ok := g.EdgeValue(from, to) return ok } func (g *Graph) Vertices() []string { result := make([]string, len(g.vertices)) i := 0 for k := range g.vertices { result[i] = k i++ } return result } func (g *Graph) EdgesFrom(id string) []string { v, ok := g.vertices[id] if !ok { return make([]string, 0) } result := make([]string, len(v.edges)) i := 0 for k := range v.edges { result[i] = k i++ } return result } func (g *Graph) ensureVertex(id string) *vertex { v, ok := g.vertices[id] if !ok { v = &vertex{edges: make(map[string]*edge)} g.vertices[id] = v } return v } func (g *Graph) ensureEdge(from string, to string) *edge { v := g.ensureVertex(from) e, ok := v.edges[to] if !ok { e = &edge{} v.edges[to] = e } return e }
executor/graph/graph.go
0.63409
0.400486
graph.go
starcoder
Package cloudevents provides a CloudEvents library focused on target component requirements and on how responses should be composed. Basics The package provides a Replier object that should be instantiated as a singleton, and a set of pubic functions that are further divided into Knative managed and Custom managed responses. Knative managed responses contain no payload, they just log and report ACK or NACK to the interacting channel. Custom managed responses on the other hand provide information through payload. In the case of successful responses the payload is provided by the target, but when an error occurs, a custom managed response includes an EventError payload. type EventError struct { Code string // short string to identify error nature Description string // description from the error object Fields interface{} // additional information } Replier The Replier constructor can be customized by passing an array of ReplierOption objects, being that customization applied to all responses. Customization choices are: responseType how to compose the outgoing response event type. responseContentType which content-type header to choose. responseSource how to compose the outgoing event source. responseErrorType in case of error, same as responseType. responseErrorContentType in case of error, same as responseContentType. payloadPolicy if payload replies should be sent or not. Knative Managed Functions Ack() (*cloudevents.Event, cloudevents.Result) Is the function to use when we want Knative to acknoledge that the message was delivered and no reponse payload is being returned. ErrorKnativeManaged(event *cloudevents.Event, err error) (*cloudevents.Event, cloudevents.Result) Sends a non properly delivered message back to the channel, which will decide if it should be retried, sent to the DLQ or forgotten. A summary of the incoming event that led to the error is added to the error message returned. Custom Managed Functions Ok(in *cloudevents.Event, payload interface{}, opts ...EventResponseOption) (*cloudevents.Event, cloudevents.Result) Replies acknowledging the delivery of the message and providing a payload for further use. The incoming event is passed to help composing header fields for the response. EventResponseOptions will be sequentially processed and can be used to modify the response before sending out. Ok responses will have a "category" header set to "success". ErrorWithFields(in *cloudevents.Event, code string, reportedErr error, details interface{}, opts ...EventResponseOption) (*cloudevents.Event, cloudevents.Result) Replies acknowledging the delivery of the message, which means Knative will consider the message as succeeded and wont retry nor send to the DLQ. The code parameter values are suggested at the package but can be provided by the target, being recommended that cardinality is kept low to make log analysis easy. If response options for type and content-type are not explicitly set the ones for the Ok response will be used. Error responses will have a "category" header set to "error". */ package cloudevents /* Usage: // Create replier that will add bridge header to custom responses and // will only reply payloads when an error occurs. replier, err := targetce.New(env.Component, logger.Named("replier"), targetce.ReplierWithStatefulHeaders(bridgeIdentifier), targetce.ReplierWithPayloadPolicy(targetce.PayloadPolicyErrors)) ... // Create replier that will use a different static type response // depending on the incoming type. mt = map[string]string{ "search.snowball.io": "list.snowball.io", "update.snowball.io": "product.snowball.io", } replier, err := targetce.New(env.Component, logger.Named("replier"), targetce.ReplierWithMappedResponseType(mt)) ... // Returning a custom success response that uses the title variable as subject replier.Ok(inEvent, bJson, targetce.ResponseWithSubject(title)) ... // Returning a custom error from the dispatcher, not being // able to parse the response from a third party service. return a.replier.Error(&event, targetce.ErrorCodeParseResponse, err, nil) */
pkg/targets/adapter/cloudevents/doc.go
0.708213
0.807195
doc.go
starcoder
package nn type HiddenLayer struct { *Layer biasNeuron *BiasNeuron prevLayer ILayer withBias bool weights [][]float64 biasWeights []float64 activationDerivativeFunction ActivationDerivativeFunction learningRate float64 moment float64 } func NewHiddenLayer(numberOfNeurons int, prevLayer ILayer, withBias bool, weights [][]float64, biasWeights []float64, activationDerivativeFunction ActivationDerivativeFunction, learningRate, moment float64) *HiddenLayer { l := new(HiddenLayer) l.Layer = NewLayer(LayerTypeHidden, numberOfNeurons) l.prevLayer = prevLayer l.withBias = withBias l.weights = weights l.biasWeights = biasWeights l.activationDerivativeFunction = activationDerivativeFunction l.learningRate = learningRate l.moment = moment l.build() return l } func (hiddenLayer *HiddenLayer) build() { var neurons []INeuron biasNeuron := NewBiasNeuron() for i := 0; i < hiddenLayer.numberOfNeurons; i++ { hiddenNeuron := NewHiddenNeuron() var neuronWeights []float64 if hiddenLayer.weights != nil && i < len(hiddenLayer.weights) { neuronWeights = hiddenLayer.weights[i] } for prevLayerNeuronIndex, prevLayerNeuron := range hiddenLayer.prevLayer.GetNeurons() { synapse := NewSynapse(hiddenLayer.learningRate, hiddenLayer.moment) if neuronWeights != nil && prevLayerNeuronIndex < len(neuronWeights) { synapse.Weight = neuronWeights[prevLayerNeuronIndex] } hiddenNeuron.AddSynapse(synapse, SynapseTypeIn) prevLayerNeuron.AddSynapse(synapse, SynapseTypeOut) synapse.InNeuron = prevLayerNeuron synapse.OutNeuron = hiddenNeuron } if hiddenLayer.withBias { synapse := NewSynapse(hiddenLayer.learningRate, hiddenLayer.moment) if hiddenLayer.biasWeights != nil && i < len(hiddenLayer.biasWeights) { synapse.Weight = hiddenLayer.biasWeights[i] } hiddenNeuron.AddSynapse(synapse, SynapseTypeIn) biasNeuron.AddSynapse(synapse, SynapseTypeOut) synapse.InNeuron = biasNeuron synapse.OutNeuron = hiddenNeuron } neurons = append(neurons, hiddenNeuron) } if hiddenLayer.withBias { hiddenLayer.biasNeuron = biasNeuron } hiddenLayer.neurons = neurons } func (hiddenLayer *HiddenLayer) UpdateDelta() { for _, neuron := range hiddenLayer.neurons { neuron.(*HiddenNeuron).UpdateDelta(hiddenLayer.activationDerivativeFunction) } } func (hiddenLayer *HiddenLayer) UpdateWeight() { for _, neuron := range hiddenLayer.neurons { for _, synapse := range neuron.GetInSynapses() { if synapse.InNeuron.GetNeuronType() == NeuronTypeBias { continue } synapse.UpdateGradient() synapse.UpdateWeight() } } } func (hiddenLayer *HiddenLayer) GetBiasWeights() []float64 { var layerBiasWeights []float64 if hiddenLayer.withBias { for _, synapse := range hiddenLayer.biasNeuron.outSynapses { layerBiasWeights = append(layerBiasWeights, synapse.Weight) } } return layerBiasWeights }
src/nn/layer_hidden.go
0.716318
0.546859
layer_hidden.go
starcoder
package be import ( cir "github.com/hoijui/escher/circuit" ) // *Spirit gates emit the residue of the enclosing circuit itself var SpiritVerb = cir.NewVerbAddress("*", "Spirit") // create all links before materializing gates func createLinks(design cir.Circuit) map[cir.Name]Reflex { // create all links before materializing gates gates := make(map[cir.Name]Reflex) gates[cir.Super] = make(Reflex) for name, view := range design.Flow { if gates[name] == nil { gates[name] = make(Reflex) } for vlv, vec := range view { if gates[name][vlv] != nil { continue } if gates[vec.Gate] == nil { gates[vec.Gate] = make(Reflex) } gates[name][vlv], gates[vec.Gate][vec.Valve] = NewSynapse() } } return gates } func calcResidue(matter cir.Circuit, design cir.Circuit, gates map[cir.Name]Reflex) (cir.Circuit, map[cir.Name]interface{}) { residue := cir.New() spirit := make(map[cir.Name]interface{}) // channel to pass circuit residue back to spirit gates inside the circuit for g := range design.Gate { if g == cir.Super { panicWithMatter(matter, "Circuit design overwrites the empty-string gate, in design %v\n", design) } gSyntax := design.At(g) var gResidue interface{} // Compute view of gate within circuit view := cir.New() for vlv, vec := range design.Flow[g] { view.Grow(vlv, design.Gate[vec.Gate]) } if cir.Same(gSyntax, SpiritVerb) { gResidue, spirit[g] = MaterializeInstance(gates[g], newSubMatterView(matter, view), &Future{}) } else { if gCir, ok := gSyntax.(cir.Circuit); ok && !cir.IsVerb(gCir) { gResidue = materializeNoun(gates[g], newSubMatterView(matter, view).Grow("Noun", gCir)) } else { gResidue = route(gSyntax, gates[g], newSubMatterView(matter, view)) } } residue.Gate[g] = gResidue } return residue, spirit } // connect boundary synapses func connect(given Reflex, matter cir.Circuit, design cir.Circuit, gates map[cir.Name]Reflex) { for vlv, s := range given { t, ok := gates[cir.Super][vlv] if !ok { panicWithMatter(matter, "connected valve %v is not connected within circuit design %v", vlv, design) } delete(gates[cir.Super], vlv) go Link(s, t) go Link(t, s) } } // send residue of this circuit to all escher.Spirit reflexes func distributeResidue(residue cir.Circuit, spirit map[cir.Name]interface{}) cir.Circuit { res := CleanUp(residue) go func() { for _, f := range spirit { f.(*Future).Charge(res) } }() return res } // Required matter: Index, View, Circuit func materializeCircuit(given Reflex, matter cir.Circuit) interface{} { design := matter.CircuitAt("Circuit") gates := createLinks(design) // materialize gates residue, spirit := calcResidue(matter, design, gates) connect(given, matter, design, gates) res := distributeResidue(residue, spirit) if len(gates[cir.Super]) > 0 { panicWithMatter(matter, "circuit valves left unconnected") } return res } func newSubMatterView(matter cir.Circuit, view cir.Circuit) cir.Circuit { r := newSubMatter(matter) r.Include("View", view) return r } // CleanUp removes nil-valued gates and their incident edges. // CleanUp never returns nil. func CleanUp(u cir.Circuit) cir.Circuit { for n, g := range u.Gate { if g != nil { continue } delete(u.Gate, n) for vlv, vec := range u.Flow[n] { u.Unlink(cir.Vector{Gate: n, Valve: vlv}, vec) } } return u }
be/be-circuit.go
0.712632
0.408926
be-circuit.go
starcoder
package tree import ( "fmt" "log" json "github.com/rwxrob/json/pkg" "github.com/rwxrob/structs/types" ) // E ("tree-e") is an encapsulating struct to contain the Root Node and // all possible Types for any Node. Most users of a tree will make // direct use of E.Root (which has a type of 1 by convention). Tree // implements custom methods for MarshalJSON and UnmarshalJSON as // minimal JSON array types to facilitate storage, transfer, and // documentation but includes longer forms that use strings instead of // integer types and indentation. type E[T any] struct { types.Types Root *Node[T] `json:",omitempty"` } // New creates a new tree initialized with the given types and returns. func New[T any](types ...string) *E[T] { t := new(E[T]) t.Init(types) return t } // Init initializes a tree creating its Root Node reference and // assigning it the conventional type of 1 (0 is reserved for UNKNOWN). // The first type string name passed should coincide with the name for // the root type of 1 (ex: "Grammar", "Document"). Init creates and // indexes the Types by passing them to Types.Set. func (t *E[T]) Init(types []string) *E[T] { t.Types.Set(types...) t.Root = new(Node[T]) t.Root.T = 1 t.Root.Tree = t return t } // Node returns new detached Node initialized for this same tree. func (t *E[T]) Node(typ int, val T) *Node[T] { node := new(Node[T]) node.T = typ node.V = val node.Tree = t return node } // ---------------------------- marshaling ---------------------------- type jstree[T any] struct { types.Types Root *Node[T] `json:",omitempty"` } // MarshalJSON implements encoding/json.Marshaler without the broken, // unnecessary HTML escapes. func (s E[T]) MarshalJSON() ([]byte, error) { t := new(jstree[T]) t.Types = s.Types t.Root = s.Root return json.Marshal(t) } // JSONL implements rwxrob/json.AsJSON. func (s *E[T]) JSON() ([]byte, error) { return json.Marshal(s) } // JSONL implements rwxrob/json.AsJSON. func (s *E[T]) JSONL() ([]byte, error) { return json.MarshalIndent(s, " ", " ") } // String implements rwxrob/json.Stringer and fmt.Stringer. func (s E[T]) String() string { byt, err := s.JSON() if err != nil { log.Print(err) } return string(byt) } // StringLong implements rwxrob/json.Stringer. func (s E[T]) StringLong() string { byt, err := s.JSONL() if err != nil { log.Print(err) } return string(byt) } // String implements rwxrob/json.Printer. func (s *E[T]) Print() { fmt.Println(s.String()) } // PrintLong implements rwxrob/json.Printer. func (s *E[T]) PrintLong() { fmt.Println(s.StringLong()) } // Log implements rwxrob/json.Logger. func (s E[T]) Log() { log.Print(s.String()) }
tree/tree.go
0.763836
0.460471
tree.go
starcoder
package ml import ( "github.com/cpmech/gosl/fun" "github.com/cpmech/gosl/fun/dbf" "github.com/cpmech/gosl/la" "github.com/cpmech/gosl/opt" ) // LogRegMulti implements a logistic regression model for multiple classes (Observer of data) type LogRegMulti struct { // input data *Data // X-y data // access nClass int // number of classes // internal dataB []*Data // [nClass] reference to X-y data but with binary y-vector models []*LogReg // [nClass] one-versus-all models } // NewLogRegMulti returns a new object // NOTE: the y-vector in data must have values in [0, nClass-1] func NewLogRegMulti(data *Data) (o *LogRegMulti) { o = new(LogRegMulti) o.data = data o.data.AddObserver(o) o.nClass = int(data.Y.Max()) + 1 o.dataB = make([]*Data, o.nClass) o.models = make([]*LogReg, o.nClass) useY := true allocate := false for k := 0; k < o.nClass; k++ { o.dataB[k] = NewData(data.Nsamples, data.Nfeatures, useY, allocate) } o.Update() return } // Update perform updates after data has been changed (as an Observer) func (o *LogRegMulti) Update() { for k := 0; k < o.nClass; k++ { o.dataB[k].X = o.data.X if len(o.dataB[k].Y) != o.data.Nsamples { o.dataB[k].Y = la.NewVector(o.data.Nsamples) } for i := 0; i < o.data.Nsamples; i++ { if int(o.data.Y[i]) == k { o.dataB[k].Y[i] = 1.0 } else { o.dataB[k].Y[i] = 0.0 } } if o.models[k] == nil { o.models[k] = NewLogReg(o.dataB[k]) } else { o.models[k].Update() } } } // Nclasses returns the number of classes func (o *LogRegMulti) Nclasses() int { return o.nClass } // SetLambda sets the regularization parameter func (o *LogRegMulti) SetLambda(lambda float64) { for k := 0; k < o.nClass; k++ { o.models[k].SetLambda(lambda) } } // Predict returns the model evaluation @ {x;θ,b} // Input: // x -- vector of features // Output: // class -- class with the highest probability // probs -- probabilities func (o *LogRegMulti) Predict(x la.Vector) (class int, probs []float64) { pMax := 0.0 probs = make([]float64, o.nClass) for k := 0; k < o.nClass; k++ { probs[k] = o.models[k].Predict(x) if probs[k] > pMax { pMax = probs[k] class = k } } return } // Train finds the parameters using Newton's method func (o *LogRegMulti) Train() { for k := 0; k < o.nClass; k++ { o.models[k].Train() } } // TrainNumerical trains model using numerical optimizer // method -- method/kind of numerical solver. e.g. conjgrad, powel, graddesc // saveHist -- save history // control -- parameters to numerical solver. See package 'opt' func (o *LogRegMulti) TrainNumerical(method string, saveHist bool, control dbf.Params) (minCosts []float64, hists []*opt.History) { minCosts = make([]float64, o.nClass) if saveHist { hists = make([]*opt.History, o.nClass) } for k := 0; k < o.nClass; k++ { θini := la.NewVector(o.data.Nfeatures) bini := 0.0 c, h := o.models[k].TrainNumerical(θini, bini, method, saveHist, control) minCosts[k] = c if saveHist { hists[k] = h } } return } // GetFunctionsForPlotting returns functions for plotting func (o *LogRegMulti) GetFunctionsForPlotting() (ffcn fun.Sv, ffcns []fun.Sv) { ffcn = func(x la.Vector) float64 { class, _ := o.Predict(x) return float64(class) } ffcns = []fun.Sv{ o.models[0].Predict, o.models[1].Predict, o.models[2].Predict, } return }
ml/logregmulti.go
0.613237
0.402157
logregmulti.go
starcoder
package network import ( "encoding/json" "fmt" "testing" "github.com/ingrammicro/cio/api/types" "github.com/ingrammicro/cio/utils" "github.com/stretchr/testify/assert" ) // ListDomainsMocked test mocked function func ListDomainsMocked(t *testing.T, domainsIn []*types.Domain) []*types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(domainsIn) assert.Nil(err, "Domains test data corrupted") // call service cs.On("Get", APIPathNetworkDnsDomains).Return(dIn, 200, nil) domainsOut, err := ds.ListDomains() assert.Nil(err, "Error getting domains") assert.Equal(domainsIn, domainsOut, "ListDomains returned different domains") return domainsOut } // ListDomainsFailErrMocked test mocked function func ListDomainsFailErrMocked(t *testing.T, domainsIn []*types.Domain) []*types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(domainsIn) assert.Nil(err, "Domains test data corrupted") // call service cs.On("Get", APIPathNetworkDnsDomains).Return(dIn, 200, fmt.Errorf("mocked error")) domainsOut, err := ds.ListDomains() assert.NotNil(err, "We are expecting an error") assert.Nil(domainsOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return domainsOut } // ListDomainsFailStatusMocked test mocked function func ListDomainsFailStatusMocked(t *testing.T, domainsIn []*types.Domain) []*types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(domainsIn) assert.Nil(err, "Domains test data corrupted") // call service cs.On("Get", APIPathNetworkDnsDomains).Return(dIn, 499, nil) domainsOut, err := ds.ListDomains() assert.NotNil(err, "We are expecting an status code error") assert.Nil(domainsOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return domainsOut } // ListDomainsFailJSONMocked test mocked function func ListDomainsFailJSONMocked(t *testing.T, domainsIn []*types.Domain) []*types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Get", APIPathNetworkDnsDomains).Return(dIn, 200, nil) domainsOut, err := ds.ListDomains() assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(domainsOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return domainsOut } // GetDomainMocked test mocked function func GetDomainMocked(t *testing.T, domainIn *types.Domain) *types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(domainIn) assert.Nil(err, "Domain test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathNetworkDnsDomain, domainIn.ID)).Return(dIn, 200, nil) domainOut, err := ds.GetDomain(domainIn.ID) assert.Nil(err, "Error getting domain") assert.Equal(*domainIn, *domainOut, "GetDomain returned different domain") return domainOut } // GetDomainFailErrMocked test mocked function func GetDomainFailErrMocked(t *testing.T, domainIn *types.Domain) *types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(domainIn) assert.Nil(err, "Domain test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathNetworkDnsDomain, domainIn.ID)).Return(dIn, 200, fmt.Errorf("mocked error")) domainOut, err := ds.GetDomain(domainIn.ID) assert.NotNil(err, "We are expecting an error") assert.Nil(domainOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return domainOut } // GetDomainFailStatusMocked test mocked function func GetDomainFailStatusMocked(t *testing.T, domainIn *types.Domain) *types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(domainIn) assert.Nil(err, "Domain test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathNetworkDnsDomain, domainIn.ID)).Return(dIn, 499, nil) domainOut, err := ds.GetDomain(domainIn.ID) assert.NotNil(err, "We are expecting an status code error") assert.Nil(domainOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return domainOut } // GetDomainFailJSONMocked test mocked function func GetDomainFailJSONMocked(t *testing.T, domainIn *types.Domain) *types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Get", fmt.Sprintf(APIPathNetworkDnsDomain, domainIn.ID)).Return(dIn, 200, nil) domainOut, err := ds.GetDomain(domainIn.ID) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(domainOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return domainOut } // CreateDomainMocked test mocked function func CreateDomainMocked(t *testing.T, domainIn *types.Domain) *types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*domainIn) assert.Nil(err, "Domain test data corrupted") // to json dOut, err := json.Marshal(domainIn) assert.Nil(err, "Domain test data corrupted") // call service cs.On("Post", APIPathNetworkDnsDomains, mapIn).Return(dOut, 200, nil) domainOut, err := ds.CreateDomain(mapIn) assert.Nil(err, "Error creating domain") assert.Equal(domainIn, domainOut, "CreateDomain returned different domain") return domainOut } // CreateDomainFailErrMocked test mocked function func CreateDomainFailErrMocked(t *testing.T, domainIn *types.Domain) *types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*domainIn) assert.Nil(err, "Domain test data corrupted") // to json dOut, err := json.Marshal(domainIn) assert.Nil(err, "Domain test data corrupted") // call service cs.On("Post", APIPathNetworkDnsDomains, mapIn).Return(dOut, 200, fmt.Errorf("mocked error")) domainOut, err := ds.CreateDomain(mapIn) assert.NotNil(err, "We are expecting an error") assert.Nil(domainOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return domainOut } // CreateDomainFailStatusMocked test mocked function func CreateDomainFailStatusMocked(t *testing.T, domainIn *types.Domain) *types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*domainIn) assert.Nil(err, "Domain test data corrupted") // to json dOut, err := json.Marshal(domainIn) assert.Nil(err, "Domain test data corrupted") // call service cs.On("Post", APIPathNetworkDnsDomains, mapIn).Return(dOut, 499, nil) domainOut, err := ds.CreateDomain(mapIn) assert.NotNil(err, "We are expecting an status code error") assert.Nil(domainOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return domainOut } // CreateDomainFailJSONMocked test mocked function func CreateDomainFailJSONMocked(t *testing.T, domainIn *types.Domain) *types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*domainIn) assert.Nil(err, "Domain test data corrupted") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Post", APIPathNetworkDnsDomains, mapIn).Return(dIn, 200, nil) domainOut, err := ds.CreateDomain(mapIn) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(domainOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return domainOut } // DeleteDomainMocked test mocked function func DeleteDomainMocked(t *testing.T, domainIn *types.Domain) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(domainIn) assert.Nil(err, "Domain test data corrupted") // call service cs.On("Delete", fmt.Sprintf(APIPathNetworkDnsDomain, domainIn.ID)).Return(dIn, 200, nil) domainOut, err := ds.DeleteDomain(domainIn.ID) assert.Nil(err, "Error deleting domain") assert.Equal(domainIn, domainOut, "DeleteDomain returned different domain") } // DeleteDomainFailErrMocked test mocked function func DeleteDomainFailErrMocked(t *testing.T, domainIn *types.Domain) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(domainIn) assert.Nil(err, "Domain test data corrupted") // call service cs.On("Delete", fmt.Sprintf(APIPathNetworkDnsDomain, domainIn.ID)).Return(dIn, 200, fmt.Errorf("mocked error")) domainOut, err := ds.DeleteDomain(domainIn.ID) assert.NotNil(err, "We are expecting an error") assert.Nil(domainOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") } // DeleteDomainFailStatusMocked test mocked function func DeleteDomainFailStatusMocked(t *testing.T, domainIn *types.Domain) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(domainIn) assert.Nil(err, "Domain test data corrupted") // call service cs.On("Delete", fmt.Sprintf(APIPathNetworkDnsDomain, domainIn.ID)).Return(dIn, 499, nil) domainOut, err := ds.DeleteDomain(domainIn.ID) assert.NotNil(err, "We are expecting an status code error") assert.Nil(domainOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") } // DeleteDomainFailJSONMocked test mocked function func DeleteDomainFailJSONMocked(t *testing.T, domainIn *types.Domain) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Delete", fmt.Sprintf(APIPathNetworkDnsDomain, domainIn.ID)).Return(dIn, 200, nil) domainOut, err := ds.DeleteDomain(domainIn.ID) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(domainOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") } // RetryDomainMocked test mocked function func RetryDomainMocked(t *testing.T, domainIn *types.Domain) *types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") mapIn := new(map[string]interface{}) // to json dOut, err := json.Marshal(domainIn) assert.Nil(err, "Domain test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathNetworkDnsDomainRetry, domainIn.ID), mapIn).Return(dOut, 200, nil) domainOut, err := ds.RetryDomain(domainIn.ID) assert.Nil(err, "Error retrying domain") assert.Equal(domainIn, domainOut, "RetryDomain returned different domain") return domainOut } // RetryDomainFailErrMocked test mocked function func RetryDomainFailErrMocked(t *testing.T, domainIn *types.Domain) *types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") mapIn := new(map[string]interface{}) // to json dOut, err := json.Marshal(domainIn) assert.Nil(err, "Domain test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathNetworkDnsDomainRetry, domainIn.ID), mapIn). Return(dOut, 200, fmt.Errorf("mocked error")) domainOut, err := ds.RetryDomain(domainIn.ID) assert.NotNil(err, "We are expecting an error") assert.Nil(domainOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return domainOut } // RetryDomainFailStatusMocked test mocked function func RetryDomainFailStatusMocked(t *testing.T, domainIn *types.Domain) *types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") mapIn := new(map[string]interface{}) // to json dOut, err := json.Marshal(domainIn) assert.Nil(err, "Domain test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathNetworkDnsDomainRetry, domainIn.ID), mapIn).Return(dOut, 499, nil) domainOut, err := ds.RetryDomain(domainIn.ID) assert.NotNil(err, "We are expecting an status code error") assert.Nil(domainOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return domainOut } // RetryDomainFailJSONMocked test mocked function func RetryDomainFailJSONMocked(t *testing.T, domainIn *types.Domain) *types.Domain { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") mapIn := new(map[string]interface{}) // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Put", fmt.Sprintf(APIPathNetworkDnsDomainRetry, domainIn.ID), mapIn).Return(dIn, 200, nil) domainOut, err := ds.RetryDomain(domainIn.ID) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(domainOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return domainOut } // ListRecordsMocked test mocked function func ListRecordsMocked(t *testing.T, domainID string, recordsIn []*types.Record) []*types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(recordsIn) assert.Nil(err, "Records test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathNetworkDnsDomainRecords, domainID)).Return(dIn, 200, nil) recordsOut, err := ds.ListRecords(domainID) assert.Nil(err, "Error getting records") assert.Equal(recordsIn, recordsOut, "ListRecords returned different records") return recordsOut } // ListRecordsFailErrMocked test mocked function func ListRecordsFailErrMocked(t *testing.T, domainID string, recordsIn []*types.Record) []*types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(recordsIn) assert.Nil(err, "Records test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathNetworkDnsDomainRecords, domainID)).Return(dIn, 200, fmt.Errorf("mocked error")) recordsOut, err := ds.ListRecords(domainID) assert.NotNil(err, "We are expecting an error") assert.Nil(recordsOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return recordsOut } // ListRecordsFailStatusMocked test mocked function func ListRecordsFailStatusMocked(t *testing.T, domainID string, recordsIn []*types.Record) []*types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(recordsIn) assert.Nil(err, "Records test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathNetworkDnsDomainRecords, domainID)).Return(dIn, 499, nil) recordsOut, err := ds.ListRecords(domainID) assert.NotNil(err, "We are expecting an status code error") assert.Nil(recordsOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return recordsOut } // ListRecordsFailJSONMocked test mocked function func ListRecordsFailJSONMocked(t *testing.T, domainID string, recordsIn []*types.Record) []*types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Get", fmt.Sprintf(APIPathNetworkDnsDomainRecords, domainID)).Return(dIn, 200, nil) recordsOut, err := ds.ListRecords(domainID) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(recordsOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return recordsOut } // GetRecordMocked test mocked function func GetRecordMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathNetworkDnsRecord, recordIn.ID)).Return(dIn, 200, nil) recordOut, err := ds.GetRecord(recordIn.ID) assert.Nil(err, "Error getting record") assert.Equal(recordIn, recordOut, "GetRecord returned different record") return recordOut } // GetRecordFailErrMocked test mocked function func GetRecordFailErrMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathNetworkDnsRecord, recordIn.ID)).Return(dIn, 200, fmt.Errorf("mocked error")) recordOut, err := ds.GetRecord(recordIn.ID) assert.NotNil(err, "We are expecting an error") assert.Nil(recordOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return recordOut } // GetRecordFailStatusMocked test mocked function func GetRecordFailStatusMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Get", fmt.Sprintf(APIPathNetworkDnsRecord, recordIn.ID)).Return(dIn, 499, nil) recordOut, err := ds.GetRecord(recordIn.ID) assert.NotNil(err, "We are expecting an status code error") assert.Nil(recordOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return recordOut } // GetRecordFailJSONMocked test mocked function func GetRecordFailJSONMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Get", fmt.Sprintf(APIPathNetworkDnsRecord, recordIn.ID)).Return(dIn, 200, nil) recordOut, err := ds.GetRecord(recordIn.ID) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(recordOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return recordOut } // CreateRecordMocked test mocked function func CreateRecordMocked(t *testing.T, domainID string, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*recordIn) assert.Nil(err, "Record test data corrupted") // to json dOut, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Post", fmt.Sprintf(APIPathNetworkDnsDomainRecords, domainID), mapIn).Return(dOut, 200, nil) recordOut, err := ds.CreateRecord(domainID, mapIn) assert.Nil(err, "Error creating record") assert.Equal(recordIn, recordOut, "CreateRecord returned different record") return recordOut } // CreateRecordFailErrMocked test mocked function func CreateRecordFailErrMocked(t *testing.T, domainID string, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*recordIn) assert.Nil(err, "Record test data corrupted") // to json dOut, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Post", fmt.Sprintf(APIPathNetworkDnsDomainRecords, domainID), mapIn). Return(dOut, 200, fmt.Errorf("mocked error")) recordOut, err := ds.CreateRecord(domainID, mapIn) assert.NotNil(err, "We are expecting an error") assert.Nil(recordOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return recordOut } // CreateRecordFailStatusMocked test mocked function func CreateRecordFailStatusMocked(t *testing.T, domainID string, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*recordIn) assert.Nil(err, "Record test data corrupted") // to json dOut, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Post", fmt.Sprintf(APIPathNetworkDnsDomainRecords, domainID), mapIn).Return(dOut, 499, nil) recordOut, err := ds.CreateRecord(domainID, mapIn) assert.NotNil(err, "We are expecting an status code error") assert.Nil(recordOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return recordOut } // CreateRecordFailJSONMocked test mocked function func CreateRecordFailJSONMocked(t *testing.T, domainID string, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*recordIn) assert.Nil(err, "Record test data corrupted") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Post", fmt.Sprintf(APIPathNetworkDnsDomainRecords, domainID), mapIn).Return(dIn, 200, nil) recordOut, err := ds.CreateRecord(domainID, mapIn) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(recordOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return recordOut } // UpdateRecordMocked test mocked function func UpdateRecordMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*recordIn) assert.Nil(err, "Record test data corrupted") // to json dOut, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathNetworkDnsRecord, recordIn.ID), mapIn).Return(dOut, 200, nil) recordOut, err := ds.UpdateRecord(recordIn.ID, mapIn) assert.Nil(err, "Error updating record") assert.Equal(recordIn, recordOut, "UpdateRecord returned different record") return recordOut } // UpdateRecordFailErrMocked test mocked function func UpdateRecordFailErrMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*recordIn) assert.Nil(err, "Record test data corrupted") // to json dOut, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathNetworkDnsRecord, recordIn.ID), mapIn). Return(dOut, 200, fmt.Errorf("mocked error")) recordOut, err := ds.UpdateRecord(recordIn.ID, mapIn) assert.NotNil(err, "We are expecting an error") assert.Nil(recordOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return recordOut } // UpdateRecordFailStatusMocked test mocked function func UpdateRecordFailStatusMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*recordIn) assert.Nil(err, "Record test data corrupted") // to json dOut, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathNetworkDnsRecord, recordIn.ID), mapIn).Return(dOut, 499, nil) recordOut, err := ds.UpdateRecord(recordIn.ID, mapIn) assert.NotNil(err, "We are expecting an status code error") assert.Nil(recordOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return recordOut } // UpdateRecordFailJSONMocked test mocked function func UpdateRecordFailJSONMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*recordIn) assert.Nil(err, "Record test data corrupted") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Put", fmt.Sprintf(APIPathNetworkDnsRecord, recordIn.ID), mapIn).Return(dIn, 200, nil) recordOut, err := ds.UpdateRecord(recordIn.ID, mapIn) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(recordOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return recordOut } // DeleteRecordMocked test mocked function func DeleteRecordMocked(t *testing.T, recordIn *types.Record) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Delete", fmt.Sprintf(APIPathNetworkDnsRecord, recordIn.ID)).Return(dIn, 200, nil) recordOut, err := ds.DeleteRecord(recordIn.ID) assert.Nil(err, "Error deleting record") assert.Equal(recordIn, recordOut, "DeleteRecord returned different record") } // DeleteRecordFailErrMocked test mocked function func DeleteRecordFailErrMocked(t *testing.T, recordIn *types.Record) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Delete", fmt.Sprintf(APIPathNetworkDnsRecord, recordIn.ID)).Return(dIn, 200, fmt.Errorf("mocked error")) recordOut, err := ds.DeleteRecord(recordIn.ID) assert.NotNil(err, "We are expecting an error") assert.Nil(recordOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") } // DeleteRecordFailStatusMocked test mocked function func DeleteRecordFailStatusMocked(t *testing.T, recordIn *types.Record) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // to json dIn, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Delete", fmt.Sprintf(APIPathNetworkDnsRecord, recordIn.ID)).Return(dIn, 499, nil) recordOut, err := ds.DeleteRecord(recordIn.ID) assert.NotNil(err, "We are expecting an status code error") assert.Nil(recordOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") } // DeleteRecordFailJSONMocked test mocked function func DeleteRecordFailJSONMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Delete", fmt.Sprintf(APIPathNetworkDnsRecord, recordIn.ID)).Return(dIn, 200, nil) recordOut, err := ds.DeleteRecord(recordIn.ID) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(recordOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return recordOut } // RetryRecordMocked test mocked function func RetryRecordMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") mapIn := new(map[string]interface{}) // to json dOut, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathNetworkDnsRecordRetry, recordIn.ID), mapIn).Return(dOut, 200, nil) recordOut, err := ds.RetryRecord(recordIn.ID) assert.Nil(err, "Error retrying record") assert.Equal(recordIn, recordOut, "RetryRecord returned different record") return recordOut } // RetryRecordFailErrMocked test mocked function func RetryRecordFailErrMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") mapIn := new(map[string]interface{}) // to json dOut, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathNetworkDnsRecordRetry, recordIn.ID), mapIn). Return(dOut, 200, fmt.Errorf("mocked error")) recordOut, err := ds.RetryRecord(recordIn.ID) assert.NotNil(err, "We are expecting an error") assert.Nil(recordOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return recordOut } // RetryRecordFailStatusMocked test mocked function func RetryRecordFailStatusMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") mapIn := new(map[string]interface{}) // to json dOut, err := json.Marshal(recordIn) assert.Nil(err, "Record test data corrupted") // call service cs.On("Put", fmt.Sprintf(APIPathNetworkDnsRecordRetry, recordIn.ID), mapIn).Return(dOut, 499, nil) recordOut, err := ds.RetryRecord(recordIn.ID) assert.NotNil(err, "We are expecting an status code error") assert.Nil(recordOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return recordOut } // RetryRecordFailJSONMocked test mocked function func RetryRecordFailJSONMocked(t *testing.T, recordIn *types.Record) *types.Record { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewDomainService(cs) assert.Nil(err, "Couldn't load domain service") assert.NotNil(ds, "Domain service not instanced") mapIn := new(map[string]interface{}) // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Put", fmt.Sprintf(APIPathNetworkDnsRecordRetry, recordIn.ID), mapIn).Return(dIn, 200, nil) recordOut, err := ds.RetryRecord(recordIn.ID) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(recordOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return recordOut }
api/network/domains_api_mocked.go
0.693784
0.497559
domains_api_mocked.go
starcoder
package resize import ( "image" "image/color" "math" ) // restrict an input float32 to the // range of uint16 values func clampToUint16(x float32) (y uint16) { y = uint16(x) if x < 0 { y = 0 } else if x > float32(0xfffe) { // "else if x > float32(0xffff)" will cause overflows! y = 0xffff } return } type filterModel struct { converter factor [2]float32 kernel func(float32) float32 tempRow, tempCol []colorArray } func (f *filterModel) convolution1d(x float32, p []colorArray, isRow bool) colorArray { var k float32 var sum float32 = 0 c := colorArray{0.0, 0.0, 0.0, 0.0} var index uint if isRow { index = 0 } else { index = 1 } for j := range p { k = f.kernel((x - float32(j)) / f.factor[index]) sum += k for i := range c { c[i] += p[j][i] * k } } // normalize values for i := range c { c[i] = c[i] / sum } return c } func (f *filterModel) Interpolate(x, y float32) color.RGBA64 { xf, yf := int(x)-len(f.tempRow)/2+1, int(y)-len(f.tempCol)/2+1 x -= float32(xf) y -= float32(yf) for i := 0; i < len(f.tempCol); i++ { for j := 0; j < len(f.tempRow); j++ { f.tempRow[j] = f.at(xf+j, yf+i) } f.tempCol[i] = f.convolution1d(x, f.tempRow, true) } c := f.convolution1d(y, f.tempCol, false) return color.RGBA64{ clampToUint16(c[0]), clampToUint16(c[1]), clampToUint16(c[2]), clampToUint16(c[3]), } } // createFilter tries to find an optimized converter for the given input image // and initializes all filterModel members to their defaults func createFilter(img image.Image, factor [2]float32, size int, kernel func(float32) float32) (f Filter) { sizeX := size * (int(math.Ceil(float64(factor[0])))) sizeY := size * (int(math.Ceil(float64(factor[1])))) switch img.(type) { default: f = &filterModel{ &genericConverter{img}, factor, kernel, make([]colorArray, sizeX), make([]colorArray, sizeY), } case *image.RGBA: f = &filterModel{ &rgbaConverter{img.(*image.RGBA)}, factor, kernel, make([]colorArray, sizeX), make([]colorArray, sizeY), } case *image.RGBA64: f = &filterModel{ &rgba64Converter{img.(*image.RGBA64)}, factor, kernel, make([]colorArray, sizeX), make([]colorArray, sizeY), } case *image.Gray: f = &filterModel{ &grayConverter{img.(*image.Gray)}, factor, kernel, make([]colorArray, sizeX), make([]colorArray, sizeY), } case *image.Gray16: f = &filterModel{ &gray16Converter{img.(*image.Gray16)}, factor, kernel, make([]colorArray, sizeX), make([]colorArray, sizeY), } case *image.YCbCr: f = &filterModel{ &ycbcrConverter{img.(*image.YCbCr)}, factor, kernel, make([]colorArray, sizeX), make([]colorArray, sizeY), } } return } // Nearest-neighbor interpolation func NearestNeighbor(img image.Image, factor [2]float32) Filter { return createFilter(img, factor, 2, func(x float32) (y float32) { if x >= -0.5 && x < 0.5 { y = 1 } else { y = 0 } return }) } // Bilinear interpolation func Bilinear(img image.Image, factor [2]float32) Filter { return createFilter(img, factor, 2, func(x float32) (y float32) { absX := float32(math.Abs(float64(x))) if absX <= 1 { y = 1 - absX } else { y = 0 } return }) } // Bicubic interpolation (with cubic hermite spline) func Bicubic(img image.Image, factor [2]float32) Filter { return createFilter(img, factor, 4, func(x float32) (y float32) { absX := float32(math.Abs(float64(x))) if absX <= 1 { y = absX*absX*(1.5*absX-2.5) + 1 } else if absX <= 2 { y = absX*(absX*(2.5-0.5*absX)-4) + 2 } else { y = 0 } return }) } // Mitchell-Netravali interpolation func MitchellNetravali(img image.Image, factor [2]float32) Filter { return createFilter(img, factor, 4, func(x float32) (y float32) { absX := float32(math.Abs(float64(x))) if absX <= 1 { y = absX*absX*(7*absX-12) + 16.0/3 } else if absX <= 2 { y = -(absX - 2) * (absX - 2) / 3 * (7*absX - 8) } else { y = 0 } return }) } func lanczosKernel(a uint) func(float32) float32 { return func(x float32) (y float32) { if x > -float32(a) && x < float32(a) { y = float32(Sinc(float64(x))) * float32(Sinc(float64(x/float32(a)))) } else { y = 0 } return } } // Lanczos interpolation (a=2) func Lanczos2(img image.Image, factor [2]float32) Filter { return createFilter(img, factor, 4, lanczosKernel(2)) } // Lanczos interpolation (a=3) func Lanczos3(img image.Image, factor [2]float32) Filter { return createFilter(img, factor, 6, lanczosKernel(3)) }
imaging/resize/filters.go
0.657209
0.481759
filters.go
starcoder
package main import ( "bytes" "fmt" "math" "strconv" "github.com/mjibson/go-dsp/spectral" "github.com/wayneashleyberry/terminal-dimensions" ) // Rasterizer fills one or more buffers with discreet audio samples type Rasterizer func([][]float64) // RenderMono rasterizes a TFunc into a mono Portaudio channel func RenderMono(tfunc TFunc) Rasterizer { var t uint64 return func(out [][]float64) { for i := range out[0] { var tc = Timecode(t + uint64(i)) out[0][i] = float64(tfunc(tc)) } t = t + uint64(len(out[0])) } } // RenderStereo rasterizes two TFuncs into a stereo Portaudio channel func RenderStereo(left TFunc, right TFunc) Rasterizer { var t uint64 return func(out [][]float64) { for i := range out[0] { var tc = Timecode(t + uint64(i)) out[0][i] = float64(left(tc)) out[1][i] = float64(right(tc)) } t = t + uint64(len(out[0])) } } // Visualize renders a Rasterizer's power spectral density to the screen func Visualize(sampleRate Frequency, colormap Colormap, inner Rasterizer) Rasterizer { termWidth := termWidth() segmentLength := termWidth*2 - 2 // FFT results in segmentLength/2+1 output samples // stores the rendered output lineQueueDepth := 8 lineQueue := make(chan []float64, lineQueueDepth) go printer(lineQueue, segmentLength, colormap) options := newOptions(segmentLength) return func(out [][]float64) { // adjust PSD options if they are too agressive for the input data if segmentLength > len(out[0]) { options = newOptions(len(out[0])) } // compute raster values from the inner rasterizer inner(out) // divide the rasterized sound into [segmentLength] sample segments var segments [][]float64 for _, chanBuf := range out { chanSegs := spectral.Segment(chanBuf, options.NFFT, options.Noverlap) segments = append(segments, chanSegs...) } // subtract the mean of each segment from each segment's sample // https://www.mathworks.com/matlabcentral/answers/267658-why-am-i-getting-huge-values-on-low-frequencies-of-my-psd#comment_342452 for i := range segments { segment := segments[i] var avg float64 for j := range segment { avg += segment[j] } avg /= float64(len(segment)) for j := range segment { segment[j] -= avg } } // compute the averge PSD for all segments psd := make([]float64, options.Pad/2+1) // output of FFT is len(time domain)/2+1 var freqs []float64 for _, seg := range segments { var pxx []float64 // compute the PSD for each segment pxx, freqs = spectral.Pwelch(seg, float64(sampleRate), options) for i := range pxx { psd[i] += pxx[i] } // println() } // normalize the PSD for i := range psd { // divide by number of segments to get average psd[i] /= float64(len(segments)) // linearize the PSD. power is expressed in relationship to the square root of the frequency psd[i] *= math.Sqrt(freqs[i]) // plot data intensity on a logarithmic scale between zero and 1 psd[i] = math.Log10(psd[i] + 1) } // skip line rendering if there are too many lines waiting to be rendered if len(lineQueue) < lineQueueDepth { lineQueue <- psd } } } func newOptions(segmentLength int) *spectral.PwelchOptions { overlap := segmentLength / 2 options := new(spectral.PwelchOptions) options.Scale_off = true options.Noverlap = overlap options.NFFT = segmentLength options.Pad = segmentLength return options } // Renders printed lines from a queue func printer(lineQueue chan []float64, segmentLength int, colormap Colormap) { outLine := bytes.NewBuffer(make([]byte, 30*segmentLength, 30*segmentLength)) for { psd := <-lineQueue outLine.Reset() for i := range psd { r, g, b := colormap(psd[i]) outLine.WriteString("\x1b[48;2;") outLine.WriteString(strconv.Itoa(int(r))) outLine.WriteString(";") outLine.WriteString(strconv.Itoa(int(g))) outLine.WriteString(";") outLine.WriteString(strconv.Itoa(int(b))) outLine.WriteString("m \x1b[0m") } fmt.Println(outLine.String()) } } // get the width of the terminal - always even func termWidth() int { w, e := terminaldimensions.Width() if e != nil { return 80 } // make w even if w%2 != 0 { w-- } return int(w) }
raster.go
0.696062
0.411052
raster.go
starcoder
package arrays //The efficiency of this algorithm is O(N) but it reverses the list. Use FoldLeft instead if you don't want this. func FoldRight[T1, T2 any](as []T1, z T2, f func(T1, T2) T2) T2 { if len(as) > 1 { //Slice has a head and a tail. h, t := as[0], as[1:len(as)] return f(h, FoldRight(t, z, f)) } else if len(as) == 1 { //Slice has a head and an empty tail. h := as[0] return f(h, FoldRight(Zero[T1](), z, f)) } return z } //The efficiency of this algorithm is O(N) and it does not reverse the list like FoldRight does. //TODO Make this function tail-recursive func FoldLeft[T1, T2 any](as []T1, z T2, f func(T2, T1) T2) T2 { if len(as) > 1 { //Slice has a head and a tail. h, t := as[0], as[1:len(as)] return FoldLeft(t, f(z, h), f) } else if len(as) == 1 { //Slice has a head and an empty tail. h := as[0] return FoldLeft(Zero[T1](), f(z, h), f) } return z } func Appender[T any](s T, as []T) []T { gss := append(as, s) return gss } func Zero[T any]() []T { return []T{} } //The efficiency of this algorithm is O(N) func Reverse[T1 any](xs []T1) []T1 { f := Appender[T1] return FoldRight(xs, Zero[T1](), f) } // A structure-preserving Functor on the given array of T. //The efficiency of this algorithm is O(N) func Map[T1, T2 any](as []T1, f func(T1) T2) []T2 { g := func(as []T2, s T1) []T2 { gss := append(as, f(s)) return gss } xs := FoldLeft(as, Zero[T2](), g) return xs } //The efficiency of this algorithm is O(N) func Concat[A any](l [][]A) []A { g := func(s []A, as []A) []A { gss := append(as, s...) return gss } return FoldLeft(l, Zero[A](), g) } // Similar to Map in that it takes an array of T1 and applies a function to each element. // But FlatMap is more powerful than map. We can use flatMap to generate a collection that is either larger or smaller than the original input. //The efficiency of this algorithm is O(N squared) func FlatMap[T1, T2 any](as []T1, f func(T1) []T2) []T2 { return Concat(Map(as, f)) } //The efficiency of this algorithm is O(N) func Filter[T any](as []T, p func(T) bool) []T { var g = func(accum []T, h T) []T { if p(h) { return append(accum, h) } else { return accum } } return FoldLeft(as, []T{}, g) } //The efficiency of this algorithm is O(N) func Append[T any](as1, as2 []T) []T { var g = func(h T, accum []T) []T { return append(accum, h) } return FoldRight(as1, as2, g) } //The efficiency of this algorithm is O(N) func Contains[T any](source []T, contains T, equality func(l, r T) bool) bool { p := func(s T) bool { if equality(s, contains) { return true } else { return false } } r := Filter(source, p) if len(r) > 0 { return true } else { return false } } //The efficiency of this algorithm is O(N) func ContainsAllOf[T any](source []T, contains []T, equality func(l, r T) bool) bool { for _, v := range contains { if !Contains(source, v, equality) { return false } } return true } //The efficiency of this algorithm is O(N) func SetEquality[T any](aa []T, bb []T, equality func(l, r T) bool) bool { return (aa == nil && bb == nil) || (len(aa) == 0 && bb == nil) || (aa == nil && len(bb) == 0) || (len(aa) == 0 && len(bb) == 0) || (ContainsAllOf(aa, bb, equality) && ContainsAllOf(bb, aa, equality)) } // Returns the set 'a' minus set 'b' //The efficiency of this algorithm is O(N) func SetMinus[T any](a []T, b []T, equality func(l, r T) bool) []T { var result []T for _, v := range a { if !Contains(b, v, equality) { result = append(result, v) } } return result } // Returns the intersection of set 'a' and 'b' //The efficiency of this algorithm is O(5 * N) func SetIntersection[T any](a []T, b []T, equality func(l, r T) bool) []T { ma := SetMinus(a, b, equality) mb := SetMinus(b, a, equality) return SetMinus(SetUnion(a, b), SetUnion(ma, mb), equality) } // Returns the set union of set 'a' and 'b' //The efficiency of this algorithm is O(N) func SetUnion[T any](a []T, b []T) []T { return Append(a, b) }
arrays/arrays.go
0.561696
0.636763
arrays.go
starcoder
package nakamura import "strings" type Nakamura struct { date, format string } // NewDate creates a new nakamura object to perform //various date formatting and manipulations n func NewDate(date, format string) Nakamura { if len(strings.TrimSpace(date)) == 0 { return Nakamura{Today(), "YYYY-MM-DD"} } return Nakamura{strings.Split(date, " ")[0], format} } // IsDateValid checks for the validity of a nakamura date object func (date Nakamura) IsDateValid() bool { return IsDateValid(date.date, date.format) } // Normalise corrects any errors in the date object, such as // overflowing days or months by normalising func (date Nakamura) Normalise() Nakamura { return Nakamura{Normalise(date.date, date.format), date.format} } // Humanise converts a nakamura date object into readable format func (date Nakamura) Humanise() string { return Humanise(date.date, date.format) } // IsWeekEnd Checks if a given date input is a weekend func (date Nakamura) IsWeekEnd() bool { return IsWeekend(date.date, date.format) } // IsLeapYear checks if the year in a nakamura date object is a leap year func (date Nakamura) IsLeapYear() bool { return IsLeapYear(date.date, date.format) } // GreaterThan checks if firstDate is greater than secondDate func (firstDate Nakamura) GreaterThan(secondDate Nakamura) bool { return GreaterThan(firstDate, secondDate, secondDate.format) } // LessThan checks if firstDate is Less than secondDate func (firstDate Nakamura) LessThan(secondDate Nakamura) bool { return LessThan(firstDate, secondDate, secondDate.format) } // Check if firstDate is between secondDate and thirdDate func (firstDate Nakamura) Between(secondDate, thirdDate Nakamura) bool { return firstDate.GreaterThan(secondDate) && firstDate.LessThan(thirdDate) || firstDate.Equal(secondDate) || firstDate.Equal(thirdDate) } // Check if a nakamura object is in the future func (date Nakamura) IsFuture() bool { return date.GreaterThan(NewDate("", date.format)) } // Check if a nakamura object is in the past func (date Nakamura) IsPast() bool { return date.LessThan(NewDate("", date.format)) } // Add adds a given value to either year/month/day func (date Nakamura) Add(value int, format string) Nakamura { return Add(date, value, format) } // Subtract subtracts a given value from year/month/day func (date Nakamura) Subtract(value int, format string) Nakamura { return Add(date, -value, format) } // Equal checks if a given pair of date objects are equal func (firstDate Nakamura) Equal(secondDate Nakamura) bool { return Equal(firstDate, secondDate, secondDate.format) } // Weekday checks if a given date falls on a weekday func (date Nakamura) Weekday() string { return Weekday(date.date, date.format) } // Month returns the Month of a given date func (date Nakamura) Month() string { return Month(date.date, date.format) } func (date Nakamura) MonthDays() (int, error) { return DaysInMonth(date.date, date.format) } func Max(dates ...Nakamura) Nakamura { return GetMax(dates...) } func Min(dates ...Nakamura) Nakamura { return GetMin(dates...) }
nakamura.go
0.852383
0.630728
nakamura.go
starcoder
// Package polynomial provides interfaces for polynomial and polynomial commitment schemes defined in gnark-crypto/ecc/.../fr. package polynomial import "io" var ( ErrVerifyOpeningProof = "error verifying opening proof" ErrVerifyBatchOpeningSinglePoint = "error verifying batch opening proof at single point" ) // Polynomial interface that a polynomial should implement type Polynomial interface { Degree() uint64 Eval(v interface{}) interface{} } // Digest interface that a polynomial commitment should implement type Digest interface { io.WriterTo io.ReaderFrom Bytes() []byte } // OpeningProof interface that an opening proof // should implement. type OpeningProof interface { io.WriterTo io.ReaderFrom } // BatchOpeningProofSinglePoint interface that a bacth opening proof (single point) // should implement. type BatchOpeningProofSinglePoint interface { io.WriterTo io.ReaderFrom } // CommitmentScheme interface for an additively homomorphic // polynomial commitment scheme. // The function BatchOpenSinglePoint is proper to an additively // homomorphic commitment scheme. type CommitmentScheme interface { io.WriterTo io.ReaderFrom Commit(p Polynomial) Digest Open(val interface{}, p Polynomial) OpeningProof // Verify verifies an opening proof of commitment at point Verify(point interface{}, commitment Digest, proof OpeningProof) error // BatchOpenSinglePoint creates a batch opening proof at _val of a list of polynomials. // It's an interactive protocol, made non interactive using Fiat Shamir. BatchOpenSinglePoint(point interface{}, polynomials interface{}) BatchOpeningProofSinglePoint // BatchVerifySinglePoint verifies a batched opening proof at a single point of a list of polynomials. // point: point at which the polynomials are evaluated // claimedValues: claimed values of the polynomials at _val // commitments: list of commitments to the polynomials which are opened // batchOpeningProof: the batched opening proof at a single point of the polynomials. BatchVerifySinglePoint( point interface{}, claimedValues interface{}, commitments interface{}, batchOpeningProof BatchOpeningProofSinglePoint) error }
polynomial/commitment.go
0.648689
0.51879
commitment.go
starcoder
package simple var docS1000 = `Use plain channel send or receive Select statements with a single case can be replaced with a simple send or receive. Before: select { case x := <-ch: fmt.Println(x) } After: x := <-ch fmt.Println(x) Available since 2017.1 ` var docS1001 = `Replace with copy() Use copy() for copying elements from one slice to another. Before: for i, x := range src { dst[i] = x } After: copy(dst, src) Available since 2017.1 ` var docS1002 = `Omit comparison with boolean constant Before: if x == true {} After: if x {} Available since 2017.1 ` var docS1003 = `Replace with strings.Contains Before: if strings.Index(x, y) != -1 {} After: if strings.Contains(x, y) {} Available since 2017.1 ` var docS1004 = `Replace with bytes.Equal Before: if bytes.Compare(x, y) == 0 {} After: if bytes.Equal(x, y) {} Available since 2017.1 ` var docS1005 = `Drop unnecessary use of the blank identifier In many cases, assigning to the blank identifier is unnecessary. Before: for _ = range s {} x, _ = someMap[key] _ = <-ch After: for range s{} x = someMap[key] <-ch Available since 2017.1 ` var docS1006 = `Replace with for { ... } For infinite loops, using for { ... } is the most idiomatic choice. Available since 2017.1 ` var docS1007 = `Simplify regular expression by using raw string literal Raw string literals use ` + "`" + ` instead of " and do not support any escape sequences. This means that the backslash (\) can be used freely, without the need of escaping. Since regular expressions have their own escape sequences, raw strings can improve their readability. Before: regexp.Compile("\\A(\\w+) profile: total \\d+\\n\\z") After: regexp.Compile(` + "`" + `\A(\w+) profile: total \d+\n\z` + "`" + `) Available since 2017.1 ` var docS1008 = `Simplify returning boolean expression Before: if <expr> { return true } return false After: return <expr> Available since 2017.1 ` var docS1009 = `Omit redundant nil check on slices The len function is defined for all slices, even nil ones, which have a length of zero. It is not necessary to check if a slice is not nil before checking that its length is not zero. Before: if x != nil && len(x) != 0 {} After: if len(x) != 0 {} Available since 2017.1 ` var docS1010 = `Omit default slice index When slicing, the second index defaults to the length of the value, making s[n:len(s)] and s[n:] equivalent. Available since 2017.1 ` var docS1011 = `Use a single append to concatenate two slices Before: for _, e := range y { x = append(x, e) } After: x = append(x, y...) Available since 2017.1 ` var docS1012 = `Replace with time.Since(x) The time.Since helper has the same effect as using time.Now().Sub(x) but is easier to read. Before: time.Now().Sub(x) After: time.Since(x) Available since 2017.1 ` var docS1016 = `Use a type conversion Two struct types with identical fields can be converted between each other. In older versions of Go, the fields had to have identical struct tags. Since Go 1.8, however, struct tags are ignored during conversions. It is thus not necessary to manually copy every field individually. Before: var x T1 y := T2{ Field1: x.Field1, Field2: x.Field2, } After: var x T1 y := T2(x) Available since 2017.1 ` var docS1017 = `Replace with strings.TrimPrefix Instead of using strings.HasPrefix and manual slicing, use the strings.TrimPrefix function. If the string doesn't start with the prefix, the original string will be returned. Using strings.TrimPrefix reduces complexity, and avoids common bugs, such as off-by-one mistakes. Before: if strings.HasPrefix(str, prefix) { str = str[len(prefix):] } After: str = strings.TrimPrefix(str, prefix) Available since 2017.1 ` var docS1018 = `Replace with copy() copy() permits using the same source and destination slice, even with overlapping ranges. This makes it ideal for sliding elements in a slice. Before: for i := 0; i < n; i++ { bs[i] = bs[offset+i] } After: copy(bs[:n], bs[offset:]) Available since 2017.1 ` var docS1019 = `Simplify make call The make function has default values for the length and capacity arguments. For channels and maps, the length defaults to zero. Additionally, for slices the capacity defaults to the length. Available since 2017.1 ` var docS1020 = `Omit redundant nil check in type assertion Before: if _, ok := i.(T); ok && i != nil {} After: if _, ok := i.(T); ok {} Available since 2017.1 ` var docS1021 = `Merge variable declaration and assignment Before: var x uint x = 1 After: var x uint = 1 Available since 2017.1 ` var docS1023 = `Omit redundant control flow Functions that have no return value do not need a return statement as the final statement of the function. Switches in Go do not have automatic fallthrough, unlike languages like C. It is not necessary to have a break statement as the final statement in a case block. Available since 2017.1 ` var docS1024 = `Replace with time.Until(x) The time.Until helper has the same effect as using x.Sub(time.Now()) but is easier to read. Before: x.Sub(time.Now()) After: time.Until(x) Available since 2017.1 ` var docS1025 = `Don't use fmt.Sprintf("%s", x) unnecessarily In many instances, there are easier and more efficient ways of getting a value's string representation. Whenever a value's underlying type is a string already, or the type has a String method, they should be used directly. Given the following shared definitions type T1 string type T2 int func (T2) String() string { return "Hello, world" } var x string var y T1 var z T2 we can simplify the following fmt.Sprintf("%s", x) fmt.Sprintf("%s", y) fmt.Sprintf("%s", z) to x string(y) z.String() Available since 2017.1 ` var docS1028 = `replace with fmt.Errorf Before: errors.New(fmt.Sprintf(...)) After: fmt.Errorf(...) Available since 2017.1 ` var docS1029 = `Range over the string Ranging over a string will yield byte offsets and runes. If the offset isn't used, this is functionally equivalent to converting the string to a slice of runes and ranging over that. Ranging directly over the string will be more performant, however, as it avoids allocating a new slice, the size of which depends on the length of the string. Before: for _, r := range []rune(s) {} After: for _, r := range s {} Available since 2017.1 ` var docS1030 = `Use bytes.Buffer.String or bytes.Buffer.Bytes bytes.Buffer has both a String and a Bytes method. It is never necessary to use string(buf.Bytes()) or []byte(buf.String()) – simply use the other method. Available since 2017.1 ` var docS1031 = `Omit redundant nil check around loop You can use range on nil slices and maps, the loop will simply never execute. This makes an additional nil check around the loop unnecessary. Before: if s != nil { for _, x := range s { ... } } After: for _, x := range s { ... } Available since 2017.1 ` var docS1032 = `Replace with sort.Ints(x), sort.Float64s(x), sort.Strings(x) The sort.Ints, sort.Float64s and sort.Strings functions are easier to read than sort.Sort(sort.IntSlice(x)), sort.Sort(sort.Float64Slice(x)) and sort.Sort(sort.StringSlice(x)). Before: sort.Sort(sort.StringSlice(x)) After: sort.Strings(x) Available since 2019.1 `
vendor/honnef.co/go/tools/simple/doc.go
0.774754
0.503479
doc.go
starcoder
package sm import ( "context" "fmt" "github.com/Jim3Things/CloudChamber/simulation/internal/common" "github.com/Jim3Things/CloudChamber/simulation/internal/tracing" ) // StateIndex denotes that the value is used as an index into the state machine // action states. type StateIndex interface { fmt.Stringer } type invalidIndexType int32 func (s invalidIndexType) String() string { return "invalid" } const invalidIndex invalidIndexType = 0 // SM defines a simplified state machine structure. It assumes that the issues // of concurrency and lifecycle management are handled by some external logic. type SM struct { common.Guarded // CurrentIndex holds the index to the current state CurrentIndex StateIndex // Current is a pointer to the current state Current State // FirstState is the index to the starting state FirstState StateIndex // States holds the map of known state index values to state implementations States map[StateIndex]State // Parent points to the structure that holds this state machine, and likely // holds global context that the state actions need. Parent interface{} // Terminated is true if the state machine has reached its final state. Terminated bool // EnteredAt is the simulated time tick when the current state was entered. EnteredAt int64 // Name is the string that can be used to identify this particular instance. Name string // Saver is the function responsible for saving the state machine state to // an external store at the completion of an operation. Saver SaveHandler } // SaveHandler defines the function signature expected from a state machine // save handler. type SaveHandler func(ctx context.Context, machine *SM, starting bool) error // NullSaver is a function that provides the 'no-save' (or null) save handler // support for state machines that do not save state to an external store. func NullSaver(ctx context.Context, machine *SM, starting bool) error { tracing.Debug(ctx, "NullSaver: save (%v) signaled for %v", starting, machine) return nil } // StateDecl defines the type expected for a state declaration decorator when // creating a new SM instance type StateDecl func() (bool, StateIndex, State) // WithState is a decorator that defines a state in the state machine func WithState( name StateIndex, onEnter EnterFunc, actions []ActionEntry, other ActionFunc, onLeave LeaveFunc) StateDecl { return func() (bool, StateIndex, State) { return false, name, NewActionState(actions, other, onEnter, onLeave) } } // WithFirstState is a decorator that defines the starting state for the state // machine func WithFirstState( name StateIndex, onEnter EnterFunc, actions []ActionEntry, other ActionFunc, onLeave LeaveFunc) StateDecl { return func() (bool, StateIndex, State) { return true, name, NewActionState(actions, other, onEnter, onLeave) } } // NewSM creates a new state machine instance with the associated // parent instance reference, as well as the state declarations. func NewSM(parent interface{}, name string, saver SaveHandler, decls ...StateDecl) *SM { states := make(map[StateIndex]State) var firstState StateIndex = invalidIndex for _, decl := range decls { first, name, instance := decl() states[name] = instance if first { firstState = name } } return &SM{ CurrentIndex: firstState, Current: states[firstState], FirstState: firstState, States: states, Parent: parent, Terminated: false, EnteredAt: 0, Name: name, Saver: saver, } } // ChangeState changes the current state. Leave the old state, try to // enter the new state, and declare that state as current if successful. func (sm *SM) ChangeState(ctx context.Context, newState StateIndex) error { tracing.Info( ctx, "Change state from %q to %q in state machine %q", sm.CurrentIndex, newState, sm.Name) cur := sm.Current cur.Leave(ctx, sm, newState) cur = sm.States[newState] sm.CurrentIndex = newState sm.Current = cur tick := common.TickFromContext(ctx) sm.EnteredAt = tick sm.AdvanceGuard(tick) if err := cur.Enter(ctx, sm); err != nil { return tracing.Error(ctx, err) } return nil } // Receive processes an incoming message by routing it to the active state // handler. func (sm *SM) Receive(ctx context.Context, msg Envelope) { sm.Current.Receive(ctx, sm, msg) if err := sm.Saver(ctx, sm, false); err != nil { tracing.Fatal(ctx, err) } } // Start sets the state machine to its first (starting) state func (sm *SM) Start(ctx context.Context) error { cur := sm.States[sm.FirstState] sm.CurrentIndex = sm.FirstState sm.Current = cur if err := cur.Enter(ctx, sm); err != nil { return tracing.Error(ctx, err) } if err := sm.Saver(ctx, sm, true); err != nil { return tracing.Error(ctx, err) } return nil } // Savable returns the SM state that can be usefully saved off and later // restored as part of implementing a persistent state machine. func (sm *SM) Savable() (StateIndex, int64, bool, int64) { return sm.CurrentIndex, sm.EnteredAt, sm.Terminated, sm.Guarded.Guard }
simulation/internal/sm/sm.go
0.738386
0.606207
sm.go
starcoder
package nifi import ( "encoding/json" ) // ClusterSummaryDTO struct for ClusterSummaryDTO type ClusterSummaryDTO struct { // When clustered, reports the number of nodes connected vs the number of nodes in the cluster. ConnectedNodes *string `json:"connectedNodes,omitempty"` // The number of nodes that are currently connected to the cluster ConnectedNodeCount *int32 `json:"connectedNodeCount,omitempty"` // The number of nodes in the cluster, regardless of whether or not they are connected TotalNodeCount *int32 `json:"totalNodeCount,omitempty"` // Whether this NiFi instance is connected to a cluster. ConnectedToCluster *bool `json:"connectedToCluster,omitempty"` // Whether this NiFi instance is clustered. Clustered *bool `json:"clustered,omitempty"` } // NewClusterSummaryDTO instantiates a new ClusterSummaryDTO 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 NewClusterSummaryDTO() *ClusterSummaryDTO { this := ClusterSummaryDTO{} return &this } // NewClusterSummaryDTOWithDefaults instantiates a new ClusterSummaryDTO 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 NewClusterSummaryDTOWithDefaults() *ClusterSummaryDTO { this := ClusterSummaryDTO{} return &this } // GetConnectedNodes returns the ConnectedNodes field value if set, zero value otherwise. func (o *ClusterSummaryDTO) GetConnectedNodes() string { if o == nil || o.ConnectedNodes == nil { var ret string return ret } return *o.ConnectedNodes } // GetConnectedNodesOk returns a tuple with the ConnectedNodes field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ClusterSummaryDTO) GetConnectedNodesOk() (*string, bool) { if o == nil || o.ConnectedNodes == nil { return nil, false } return o.ConnectedNodes, true } // HasConnectedNodes returns a boolean if a field has been set. func (o *ClusterSummaryDTO) HasConnectedNodes() bool { if o != nil && o.ConnectedNodes != nil { return true } return false } // SetConnectedNodes gets a reference to the given string and assigns it to the ConnectedNodes field. func (o *ClusterSummaryDTO) SetConnectedNodes(v string) { o.ConnectedNodes = &v } // GetConnectedNodeCount returns the ConnectedNodeCount field value if set, zero value otherwise. func (o *ClusterSummaryDTO) GetConnectedNodeCount() int32 { if o == nil || o.ConnectedNodeCount == nil { var ret int32 return ret } return *o.ConnectedNodeCount } // GetConnectedNodeCountOk returns a tuple with the ConnectedNodeCount field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ClusterSummaryDTO) GetConnectedNodeCountOk() (*int32, bool) { if o == nil || o.ConnectedNodeCount == nil { return nil, false } return o.ConnectedNodeCount, true } // HasConnectedNodeCount returns a boolean if a field has been set. func (o *ClusterSummaryDTO) HasConnectedNodeCount() bool { if o != nil && o.ConnectedNodeCount != nil { return true } return false } // SetConnectedNodeCount gets a reference to the given int32 and assigns it to the ConnectedNodeCount field. func (o *ClusterSummaryDTO) SetConnectedNodeCount(v int32) { o.ConnectedNodeCount = &v } // GetTotalNodeCount returns the TotalNodeCount field value if set, zero value otherwise. func (o *ClusterSummaryDTO) GetTotalNodeCount() int32 { if o == nil || o.TotalNodeCount == nil { var ret int32 return ret } return *o.TotalNodeCount } // GetTotalNodeCountOk returns a tuple with the TotalNodeCount field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ClusterSummaryDTO) GetTotalNodeCountOk() (*int32, bool) { if o == nil || o.TotalNodeCount == nil { return nil, false } return o.TotalNodeCount, true } // HasTotalNodeCount returns a boolean if a field has been set. func (o *ClusterSummaryDTO) HasTotalNodeCount() bool { if o != nil && o.TotalNodeCount != nil { return true } return false } // SetTotalNodeCount gets a reference to the given int32 and assigns it to the TotalNodeCount field. func (o *ClusterSummaryDTO) SetTotalNodeCount(v int32) { o.TotalNodeCount = &v } // GetConnectedToCluster returns the ConnectedToCluster field value if set, zero value otherwise. func (o *ClusterSummaryDTO) GetConnectedToCluster() bool { if o == nil || o.ConnectedToCluster == nil { var ret bool return ret } return *o.ConnectedToCluster } // GetConnectedToClusterOk returns a tuple with the ConnectedToCluster field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ClusterSummaryDTO) GetConnectedToClusterOk() (*bool, bool) { if o == nil || o.ConnectedToCluster == nil { return nil, false } return o.ConnectedToCluster, true } // HasConnectedToCluster returns a boolean if a field has been set. func (o *ClusterSummaryDTO) HasConnectedToCluster() bool { if o != nil && o.ConnectedToCluster != nil { return true } return false } // SetConnectedToCluster gets a reference to the given bool and assigns it to the ConnectedToCluster field. func (o *ClusterSummaryDTO) SetConnectedToCluster(v bool) { o.ConnectedToCluster = &v } // GetClustered returns the Clustered field value if set, zero value otherwise. func (o *ClusterSummaryDTO) GetClustered() bool { if o == nil || o.Clustered == nil { var ret bool return ret } return *o.Clustered } // GetClusteredOk returns a tuple with the Clustered field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ClusterSummaryDTO) GetClusteredOk() (*bool, bool) { if o == nil || o.Clustered == nil { return nil, false } return o.Clustered, true } // HasClustered returns a boolean if a field has been set. func (o *ClusterSummaryDTO) HasClustered() bool { if o != nil && o.Clustered != nil { return true } return false } // SetClustered gets a reference to the given bool and assigns it to the Clustered field. func (o *ClusterSummaryDTO) SetClustered(v bool) { o.Clustered = &v } func (o ClusterSummaryDTO) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.ConnectedNodes != nil { toSerialize["connectedNodes"] = o.ConnectedNodes } if o.ConnectedNodeCount != nil { toSerialize["connectedNodeCount"] = o.ConnectedNodeCount } if o.TotalNodeCount != nil { toSerialize["totalNodeCount"] = o.TotalNodeCount } if o.ConnectedToCluster != nil { toSerialize["connectedToCluster"] = o.ConnectedToCluster } if o.Clustered != nil { toSerialize["clustered"] = o.Clustered } return json.Marshal(toSerialize) } type NullableClusterSummaryDTO struct { value *ClusterSummaryDTO isSet bool } func (v NullableClusterSummaryDTO) Get() *ClusterSummaryDTO { return v.value } func (v *NullableClusterSummaryDTO) Set(val *ClusterSummaryDTO) { v.value = val v.isSet = true } func (v NullableClusterSummaryDTO) IsSet() bool { return v.isSet } func (v *NullableClusterSummaryDTO) Unset() { v.value = nil v.isSet = false } func NewNullableClusterSummaryDTO(val *ClusterSummaryDTO) *NullableClusterSummaryDTO { return &NullableClusterSummaryDTO{value: val, isSet: true} } func (v NullableClusterSummaryDTO) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableClusterSummaryDTO) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
model_cluster_summary_dto.go
0.7659
0.565419
model_cluster_summary_dto.go
starcoder