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 quicksort import "math/rand" func insertionSort(a []int) { n := len(a) if n <= 1 { return; } for i := 0; i < n - 1; i++ { j := i + 1 key := a[j] for ;j > 0 && key < a[j-1]; j-- { a[j] = a[j - 1] } a[j] = key } } func min(a, b int) int { if a < b { return a } else { return b } } func partition(a[] int) int { n := len(a) a[0], a[n/2] = a[n/2], a[0] i := 0 x := a[0] for j := 1; j < n; j++ { if a[j] <= x { i++ a[i], a[j] = a[j], a[i] } } a[0], a[i] = a[i], a[0] return i } func hpartitionInternal(k int, a[] int) (int, int) { i, j := 0, len(a) - 1 for { for k < a[j] { j-- } for a[i] < k { i++ } if i < j { a[i], a[j] = a[j], a[i] i++ j-- } else { return i, j } } } func hpartition(a []int) (int, int) { return hpartitionInternal(a[len(a)/2], a) } func median(x, y, z int) int { if x > y { x, y = y, x } if y > z { y, z = z, y } if x > y { return x } else { return y; } } func mpartition(a []int) (int, int) { n := len(a) m := n / 2 return hpartitionInternal(median(a[0], a[m], a[n-1]), a) } func rpartition(r *rand.Rand, a[] int) (int, int) { k := r.Intn(len(a)) return hpartitionInternal(a[k], a) } func fpartitionInternal(k int, v []int) (int, int) { a, b := 0, 0 c, d := len(v)-1, len(v)-1 // v[0, a) == k // v[a, b) < k // v(d, n) == k // v(c, d] > k // b <= c for { for b <= c && v[b] <= k { if k == v[b] { v[a], v[b] = v[b], v[a] a++ } b++ } for b <= c && k <= v[c] { if k == v[c] { v[d], v[c] = v[c], v[d] d-- } c-- } if b > c { break } v[b], v[c] = v[c], v[b] b++ c-- } s := min(a, b-a) lo, hi := 0, c for i := 0; i < s; i++ { v[i], v[hi - i] = v[hi - i], v[i] } s = min(d-c, len(v)-d-1) lo, hi = b, len(v) - 1 for i := 0; i < s; i++ { v[lo + i], v[hi - i] = v[hi - i], v[lo + i] } return b - a, len(v) - d + c } func fpartition(a []int) (int, int) { y := a[len(a) / 2] // n := len(a) // m := n / 2 // y := median(a[0], a[m], a[n-1]) return fpartitionInternal(y, a) } const sizeThreshold = 32 func Quicksort(a []int) { for len(a) > sizeThreshold { m := partition(a) if m > len(a) / 2 { Quicksort(a[m+1:]) a = a[:m] } else { Quicksort(a[:m]) a = a[m+1:] } } insertionSort(a) } func QuicksortH(a []int) { for len(a) > sizeThreshold { i, j := hpartition(a) if i > len(a) - j - 1 { QuicksortH(a[j+1:]) a = a[:i] } else { QuicksortH(a[:i]) a = a[j+1:] } } insertionSort(a) } func QuicksortM(a []int) { for len(a) > sizeThreshold { i, j := mpartition(a) if i > len(a) - j - 1 { QuicksortM(a[j+1:]) a = a[:i] } else { QuicksortM(a[:i]) a = a[j+1:] } } insertionSort(a) } func quicksortR(r *rand.Rand, a []int) { for len(a) > sizeThreshold { i, j := rpartition(r, a) if i > len(a) - j - 1 { quicksortR(r, a[j+1:]) a = a[:i] } else { quicksortR(r, a[:i]) a = a[j+1:] } } insertionSort(a) } func QuicksortR(a []int) { r := rand.New(rand.NewSource(1)) quicksortR(r, a) } func QuicksortF(a []int) { for len(a) > sizeThreshold { i, j := fpartition(a) if i > len(a) - j { QuicksortF(a[j:]) a = a[:i] } else { QuicksortF(a[:i]) a = a[j:] } } insertionSort(a) }
Lecture 04- Quicksort/src/quicksort/quicksort.go
0.573678
0.428951
quicksort.go
starcoder
package linkedlist import ( "errors" "fmt" ) type node struct { Data interface{} Next *node } // linkedList is the actual linked list of nodes. type linkedList struct { Length int Head *node } // InitList initializes and returns the reference to a new linkedlist. func InitList() *linkedList { return &linkedList{} } // Size returns the size/length of the Linked List. func (ll *linkedList) Size() int { return ll.Length } // AddAtHead adds a node at the beginning(head) of the Linked List func (ll *linkedList) AddAtHead(data interface{}) bool { node := &node{ Data: data, } if ll.Head == nil { ll.Head = node ll.Length++ return true } node.Next = ll.Head ll.Head = node ll.Length++ return true } // AddAtTail adds an element at the end(tail) of the list. func (ll *linkedList) AddAtTail(data interface{}) bool { node := &node{ Data: data, } if ll.Head == nil { ll.Head = node ll.Length++ return true } current := ll.Head for current.Next != nil { current = current.Next } current.Next = node ll.Length++ return true } // AddAtIndex adds a node at given index in the Linked List. Returns an error if the index is invalid. //Note: The list is zero indexed. Therefore the provided index must fall in the range 0 <= index <= SizeOfList. func (ll *linkedList) AddAtIndex(index int, data interface{}) error { node := &node{ Data: data, } if ll.Head == nil { // ll.Head = node return errors.New("invalid index. List is empty") } if index > ll.Size() || index < 0 { return errors.New("invalid index. index must be a number between 0 and list.Size()") } if index == 0 { ll.AddAtHead(data) return nil } if index == ll.Size() { ll.AddAtTail(data) return nil } previousNode := ll.Head for index > 1 { previousNode = previousNode.Next index-- } node.Next = previousNode.Next previousNode.Next = node ll.Length++ return nil } // Find searches for the specified item in the list. If found, returns the index of the item, else returns an error. In case of duplicates, returns the index of the first occurence. func (ll *linkedList) Find(data interface{}) (int, error) { if ll.Head == nil { return 0, errors.New("item not found. List is empty") } index := 0 currentItem := ll.Head if data == currentItem.Data { return 0, nil } for currentItem.Next != nil { currentItem = currentItem.Next index++ if data == currentItem.Data { return index, nil } } return 0, errors.New("item not found") } // Get returns the value at the specified index. Returns an error if the list is empty or the index is invalid. func (ll *linkedList) Get(index int) (interface{}, error) { if ll.Head == nil { return nil, errors.New("list is empty") } if index < 0 || index >= ll.Length { return nil, errors.New("invalid index") } if index == 0 { return ll.Head.Data, nil } current := ll.Head for index > 0 { current = current.Next index-- } return current.Data, nil } // Print iterates through the list and prints each element. Returns an error if the list is empty. func (ll *linkedList) Print() error { if ll.Head == nil { return errors.New("list is empty") } currentItem := ll.Head fmt.Printf("\n") fmt.Printf("%v ", currentItem.Data) for currentItem.Next != nil { currentItem = currentItem.Next fmt.Printf("%v ", currentItem.Data) } fmt.Printf("\n") return nil } // RemoveFromHead deletes the first element(Head) from the list. Returns an error if the list is empty. func (ll *linkedList) RemoveFromHead() (interface{}, error) { if ll.Head == nil { return nil, errors.New("list is empty") } currentItem := ll.Head ll.Head = ll.Head.Next currentItem.Next = nil ll.Length-- return currentItem.Data, nil } // RemoveFromIndex deletes the item present at specified index in the list. Return an error if the index is invalid. // Note: List is zero indexed. Provided index must be in the range 0 <= index < SizeOfList. func (ll *linkedList) RemoveFromIndex(index int) (interface{}, error) { if ll.Head == nil { return nil, errors.New("list is empty") } if index < 0 || index >= ll.Size() { return nil, errors.New("invalid index") } currentItem := ll.Head if index == 0 { ll.Head = currentItem.Next currentItem.Next = nil ll.Length-- return currentItem.Data, nil } // Traverse to index in the list and remove that item. previousItem := ll.Head for index > 0 { currentItem, previousItem = currentItem.Next, currentItem index-- } if currentItem.Next == nil { previousItem.Next = nil } else { previousItem.Next = currentItem.Next } //currentItem.Next = nil ll.Length-- return currentItem.Data, nil } // RemoveItem deletes first occurence of the given item from the list. Returns an error if the list is empty or the item was not found. func (ll *linkedList) RemoveItem(data interface{}) error { if ll.Head == nil { return errors.New("list is empty") } if data == ll.Head.Data { ll.Head = ll.Head.Next ll.Length-- return nil } currentItem := ll.Head previousItem := ll.Head for currentItem.Next != nil { previousItem = currentItem currentItem = currentItem.Next if currentItem.Data == data { if currentItem.Next == nil { previousItem.Next = nil } else { previousItem.Next = currentItem.Next } ll.Length-- return nil } } return errors.New("item not found") }
DataStructures/linkedList/singlyLinkedList.go
0.660063
0.411229
singlyLinkedList.go
starcoder
package bitmap import ( "unsafe" ) // Range iterates over all of the bits set to one in this bitmap. func (dst Bitmap) Range(fn func(x uint32)) { for blkAt := 0; blkAt < len(dst); blkAt++ { blk := (dst)[blkAt] if blk == 0x0 { continue // Skip the empty page } // Iterate in a 4-bit chunks so we can reduce the number of function calls and skip // the bits for which we should not call our range function. offset := uint32(blkAt << 6) for ; blk > 0; blk = blk >> 4 { switch blk & 0b1111 { case 0b0001: fn(offset + 0) case 0b0010: fn(offset + 1) case 0b0011: fn(offset + 0) fn(offset + 1) case 0b0100: fn(offset + 2) case 0b0101: fn(offset + 0) fn(offset + 2) case 0b0110: fn(offset + 1) fn(offset + 2) case 0b0111: fn(offset + 0) fn(offset + 1) fn(offset + 2) case 0b1000: fn(offset + 3) case 0b1001: fn(offset + 0) fn(offset + 3) case 0b1010: fn(offset + 1) fn(offset + 3) case 0b1011: fn(offset + 0) fn(offset + 1) fn(offset + 3) case 0b1100: fn(offset + 2) fn(offset + 3) case 0b1101: fn(offset + 0) fn(offset + 2) fn(offset + 3) case 0b1110: fn(offset + 1) fn(offset + 2) fn(offset + 3) case 0b1111: fn(offset + 0) fn(offset + 1) fn(offset + 2) fn(offset + 3) } offset += 4 } } } // Filter predicate type predicate = func(x uint32) byte // Filter iterates over the bitmap elements and calls a predicate provided for each // containing element. If the predicate returns false, the bitmap at the element's // position is set to zero. func (dst *Bitmap) Filter(f func(x uint32) bool) { fn := *(*predicate)(unsafe.Pointer(&f)) for blkAt := 0; blkAt < len(*dst); blkAt++ { blk := (*dst)[blkAt] if blk == 0x0 { continue // Skip the empty page } offset := uint32(blkAt << 6) var mask uint64 var i uint32 // Iterate in a 4-bit chunks so we can reduce the number of function calls and skip // the bits for which we should not call our filter function. for ; blk > 0; blk = blk >> 4 { switch blk & 0b1111 { case 0b0001: mask |= uint64(fn(offset)) << i case 0b0010: mask |= uint64(fn(offset+1)<<1) << i case 0b0011: mask |= uint64(fn(offset)|(fn(offset+1)<<1)) << i case 0b0100: mask |= uint64(fn(offset+2)<<2) << i case 0b0101: mask |= uint64(fn(offset)|fn(offset+2)<<2) << i case 0b0110: mask |= uint64((fn(offset+1)<<1)|(fn(offset+2)<<2)) << i case 0b0111: mask |= uint64(fn(offset)|(fn(offset+1)<<1)|(fn(offset+2)<<2)) << i case 0b1000: mask |= uint64(fn(offset+3)<<3) << i case 0b1001: mask |= uint64(fn(offset)|(fn(offset+3)<<3)) << i case 0b1010: mask |= uint64((fn(offset+1)<<1)|(fn(offset+3)<<3)) << i case 0b1011: mask |= uint64(fn(offset)|(fn(offset+1)<<1)|(fn(offset+3)<<3)) << i case 0b1100: mask |= uint64((fn(offset+2)<<2)|(fn(offset+3)<<3)) << i case 0b1101: mask |= uint64(fn(offset)|(fn(offset+2)<<2)|(fn(offset+3)<<3)) << i case 0b1110: mask |= uint64((fn(offset+1)<<1)|(fn(offset+2)<<2)|(fn(offset+3)<<3)) << i case 0b1111: mask |= uint64(fn(offset)|(fn(offset+1)<<1)|(fn(offset+2)<<2)|(fn(offset+3)<<3)) << i } i += 4 offset += 4 } // Apply the mask (*dst)[blkAt] &= mask } }
range.go
0.519034
0.506713
range.go
starcoder
package v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // FeatureReference refers to a Feature resource and specifies its intended activation state. type FeatureReference struct { // Name is the name of the Feature resource, which represents a feature the system offers. // +kubebuilder:validation:Required Name string `json:"name"` // Activate indicates the activation intent for the feature. Activate bool `json:"activate,omitempty"` } // FeatureGateSpec defines the desired state of FeatureGate type FeatureGateSpec struct { // NamespaceSelector is a selector to specify namespaces for which this feature gate applies. // Use an empty LabelSelector to match all namespaces. NamespaceSelector metav1.LabelSelector `json:"namespaceSelector"` // Features is a slice of FeatureReference to gate features. // The Feature resource specified may or may not be present in the system. If the Feature is present, the // FeatureGate controller and webhook sets the specified activation state only if the Feature is discoverable and // its immutability constraint is satisfied. If the Feature is not present, the activation intent is applied when // the Feature resource appears in the system. The actual activation state of the Feature is reported in the status. // +listType=map // +listMapKey=name Features []FeatureReference `json:"features,omitempty"` } // FeatureGateStatus defines the observed state of FeatureGate type FeatureGateStatus struct { // Namespaces lists the existing namespaces for which this feature gate applies. This is obtained from listing all // namespaces and applying the NamespaceSelector specified in spec. Namespaces []string `json:"namespaces,omitempty"` // ActivatedFeatures lists the discovered features that are activated for the namespaces specified in the spec. // This can include features that are not explicitly gated in the spec, but are already available in the system as // Feature resources. ActivatedFeatures []string `json:"activatedFeatures,omitempty"` // DeactivatedFeatures lists the discovered features that are deactivated for the namespaces specified in the spec. // This can include features that are not explicitly gated in the spec, but are already available in the system as // Feature resources. DeactivatedFeatures []string `json:"deactivatedFeatures,omitempty"` // UnavailableFeatures lists the features that are gated in the spec, but are not available in the system as // Feature resources. UnavailableFeatures []string `json:"unavailableFeatures,omitempty"` } //+kubebuilder:object:root=true //+kubebuilder:subresource:status //+kubebuilder:resource:scope=Cluster // FeatureGate is the Schema for the featuregates API type FeatureGate struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` // Spec is the specification for gating features. Spec FeatureGateSpec `json:"spec,omitempty"` // Status reports activation state and availability of features in the system. Status FeatureGateStatus `json:"status,omitempty"` } //+kubebuilder:object:root=true // FeatureGateList contains a list of FeatureGate type FeatureGateList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []FeatureGate `json:"items"` } func init() { SchemeBuilder.Register(&FeatureGate{}, &FeatureGateList{}) }
apis/config/v1alpha1/featuregate_types.go
0.76454
0.401629
featuregate_types.go
starcoder
package intset import ( "encoding/json" "sort" ) type Set struct{ items []int } // New creates a set with a given cap func New(size int) *Set { return &Set{items: make([]int, 0, size)} } // Use turns a slice into a set, re-using the underlying slice // WARNING: this function is destructive and will mutate the passed slice func Use(vv ...int) *Set { sort.Ints(vv) return &Set{items: vv} } // Len returns the set length func (s Set) Len() int { return len(s.items) } // Add adds an item to the set func (s *Set) Add(v int) bool { if pos := sort.SearchInts(s.items, v); pos < len(s.items) { if s.items[pos] == v { return false } s.items = append(s.items, 0) copy(s.items[pos+1:], s.items[pos:]) s.items[pos] = v } else { s.items = append(s.items, v) } return true } // Remove removes an item from the set func (s *Set) Remove(v int) bool { if pos := sort.SearchInts(s.items, v); pos < len(s.items) && s.items[pos] == v { s.items = s.items[:pos+copy(s.items[pos:], s.items[pos+1:])] return true } return false } // Exists checks the existence func (s *Set) Exists(v int) bool { pos := sort.SearchInts(s.items, v) return pos < len(s.items) && s.items[pos] == v } // Intersects checks if intersectable func (s *Set) Intersects(t *Set) bool { ls, lt := len(s.items), len(t.items) if lt < ls { ls, lt = lt, ls s, t = t, s } if ls == 0 || s.items[0] > t.items[lt-1] || t.items[0] > s.items[ls-1] { return false } offset := 0 for _, v := range s.items { pos, ok := index(t.items, v, offset) if ok { return true } else if pos >= lt { return false } offset = pos } return false } // Slice returns the int slice func (s *Set) Slice() []int { return s.items } // MarshalJSON encodes the set as JSON func (s *Set) MarshalJSON() ([]byte, error) { return json.Marshal(s.items) } // UnmarshalJSON decodes JSON into a set func (s *Set) UnmarshalJSON(data []byte) error { var vv []int if err := json.Unmarshal(data, &vv); err != nil { return err } *s = *Use(vv...) return nil } func index(vs []int, v int, offset int) (int, bool) { pos := sort.SearchInts(vs[offset:], v) + offset return pos, pos < len(vs) && vs[pos] == v }
intset.go
0.732879
0.417212
intset.go
starcoder
package main import ( "errors" "fmt" ) // Orientation is a type that indicates in which direction the piece is moved. type Orientation int // Location is a type that represents a 2 dimensional coordinate. type Location struct { x int y int } // Direction constants. const ( Up Orientation = iota Right Down Left ) // Goal - The "win" situation of the board. type Goal struct { Piece *Piece X, Y int } // Board is a structure that represents the puzzle board. type Board struct { // Width contains the width of the puzzle board. Width int // Height contains the height of the puzzle board. Height int Goal *Goal slots [][]*Piece pieces map[*Piece]Location } // NewBoard constructs a new empty puzzle board. func NewBoard(width, height int) (*Board, error) { if width < 1 { return nil, errors.New("Cannot create a board with a width that is less than 1.") } if height < 1 { return nil, errors.New("Cannot create a board with a height that is less than 1.") } slotsValue := make([][]*Piece, width) for i := range slotsValue { slotsValue[i] = make([]*Piece, height) } return &Board{ Width: width, Height: height, slots: slotsValue, pieces: make(map[*Piece]Location), }, nil } // AddPiece adds a Piece instance at the specified location. If the piece // would overlap with an existing piece, it is not placed and an error is // returned. func (p *Board) AddPiece(piece *Piece, x, y int) error { // Validate location inputs if x < 0 || x > p.Width-piece.Width || y < 0 || y > p.Height-piece.Height { return fmt.Errorf("Piece %d cannot be added at %d, %d because it would not fit within the board.", piece.ID, x, y) } for i := 0; i < piece.Width; i++ { for j := 0; j < piece.Height; j++ { slotPiece := p.slots[x+i][y+j] if slotPiece != nil { return fmt.Errorf("Piece %d overlaps piece %d at %d, %d\n", piece.ID, slotPiece, x+i, y+j) } } } p.pieces[piece] = Location{ x: x, y: y, } for i := 0; i < piece.Width; i++ { for j := 0; j < piece.Height; j++ { p.slots[x+i][y+j] = piece } } return nil } // SetGoal sets the goal layout of the puzzle, which piece needs to be in which position for the puzzle to be solved. func (p *Board) SetGoal(piece *Piece, x, y int) error { if piece == nil { return errors.New("goal cannot have nil piece") } if _, ok := p.pieces[piece]; !ok { return fmt.Errorf("invalid piece for goal, piece %d is not present in the puzzle", piece.ID) } if p.PieceFitsOnBoardAtPosition(piece, x, y) { return fmt.Errorf("Invalid position for goal (%d, %d), x must be positive and smaller than %d, y must be positive and smaller than %d", x, y, p.Width, p.Height) } p.Goal = &Goal{ X: x, Y: y, Piece: piece, } return nil } // MovePiece moves the specified piece by 1 square in the given direction. func (p *Board) MovePiece(piece *Piece, orientation Orientation) error { // Check if the piece can be moved. l := p.pieces[piece] x := l.x y := l.y switch orientation { case Up: y-- break case Right: x++ break case Down: y++ break case Left: x-- break } if p.PieceFitsOnBoardAtPosition(piece, x, y) { return fmt.Errorf("Moving piece %d (%d, %d - %d, %d) would put it outside the bounds of the puzzle board (0, 0 - %d, %d)", piece.ID, x, y, x+piece.Width, y+piece.Height, p.Width, p.Height) } for i := 0; i < piece.Width; i++ { for j := 0; j < piece.Height; j++ { slotPiece := p.slots[x+i][y+j] if slotPiece != nil && slotPiece != piece { return fmt.Errorf("Moving piece %d would cause it to overlap piece %d", piece.ID, slotPiece.ID) } } } p.RemovePiece(piece) p.AddPiece(piece, x, y) return nil } // PieceFitsOnBoardAtPosition checks whether a piece would fit on the board at the position func (p *Board) PieceFitsOnBoardAtPosition(piece *Piece, x, y int) bool { return x < 0 || x+piece.Width > p.Width || y < 0 || y+piece.Height > p.Height } // RemovePiece removes a Piece instance from the puzzle board. func (p *Board) RemovePiece(piece *Piece) { if l, ok := p.pieces[piece]; ok { for x := 0; x < piece.Width; x++ { for y := 0; y < piece.Height; y++ { p.slots[x+l.x][y+l.y] = nil } } delete(p.pieces, piece) } } // GetPieceAt returns the Piece instance that occupies the specified location. func (p *Board) GetPieceAt(x, y int) (*Piece, error) { if x < 0 || x >= p.Width { return nil, fmt.Errorf("The specified x coordinate %d is invalid.", x) } if y < 0 || y >= p.Height { return nil, fmt.Errorf("The specified y coordinate %d is invalid.", y) } return p.slots[x][y], nil } // IsSolved verifies whether the puzzle is in the solved state base on the goal set by SetGoal func (p *Board) IsSolved() bool { // a puzzle with no goal is always solved! ;) if p.Goal == nil { return true } pieceInPos, err := p.GetPieceAt(p.Goal.X, p.Goal.Y) if err != nil { panic(fmt.Sprintf("Got an error while checking if solved: %v", err)) } if pieceInPos == nil { // no piece occupying the goal return false } location, ok := p.pieces[pieceInPos] if !ok { panic(fmt.Sprintf("Got an error while checking if solved: %v", err)) } if pieceInPos.ID == p.Goal.Piece.ID && location.x == p.Goal.X && location.y == p.Goal.Y { return true } return false }
board.go
0.787319
0.523847
board.go
starcoder
package part2 import "strings" type P struct { W int X int Y int Z int } func (p P) Neighbors2d() (all []P) { return append(all, p.North(), p.South(), p.East(), p.West(), p.NorthWest(), p.NorthEast(), p.SouthWest(), p.SouthEast(), ) } func (p P) Neighbors3d() (all []P) { all = append(all, p.Neighbors2d()...) all = append(all, p.Above()) all = append(all, p.Above().Neighbors2d()...) all = append(all, p.Below()) all = append(all, p.Below().Neighbors2d()...) return all } func (p P) Neighbors4d() (all []P) { all = append(all, p.Neighbors3d()...) all = append(all, p.Above4d()) all = append(all, p.Above4d().Neighbors3d()...) all = append(all, p.Below4d()) all = append(all, p.Below4d().Neighbors3d()...) return all } func (p P) Above() P { return Point(p.W, p.X, p.Y, p.Z+1) } func (p P) Below() P { return Point(p.W, p.X, p.Y, p.Z-1) } func (p P) North() P { return Point(p.W, p.X, p.Y+1, p.Z) } func (p P) South() P { return Point(p.W, p.X, p.Y-1, p.Z) } func (p P) East() P { return Point(p.W, p.X-1, p.Y, p.Z) } func (p P) West() P { return Point(p.W, p.X+1, p.Y, p.Z) } func (p P) NorthWest() P { return Point(p.W, p.X-1, p.Y+1, p.Z) } func (p P) NorthEast() P { return Point(p.W, p.X+1, p.Y+1, p.Z) } func (p P) SouthWest() P { return Point(p.W, p.X-1, p.Y-1, p.Z) } func (p P) SouthEast() P { return Point(p.W, p.X+1, p.Y-1, p.Z) } func (p P) Above4d() P { return Point(p.W+1, p.X, p.Y, p.Z) } func (p P) Below4d() P { return Point(p.W-1, p.X, p.Y, p.Z) } func Point(w, x, y, z int) P { return P{ W: w, X: x, Y: y, Z: z, } } type World map[P]struct{} func ParseInitialWorld(s string) World { world := make(World) for y, line := range strings.Fields(s) { for x, char := range line { if char == '#' { world.Set(Point(0, x, y, 0), true) } } } return world } func (this World) Set(p P, activate bool) { if activate { this[p] = struct{}{} } else { delete(this, p) } } func (this World) IsActive(p P) int { _, found := this[p] if found { return 1 } return 0 } func (this World) Boot() { for x := 0; x < 6; x++ { this.Cycle() } } func (this World) Cycle() { // Establish upper/lower bounds of active world state. var wMin, xMin, yMin, zMin int var wMax, xMax, yMax, zMax int for p := range this { if p.W < wMin { wMin = p.W } else if p.W > wMax { wMax = p.W } if p.X < xMin { xMin = p.X } else if p.X > xMax { xMax = p.X } if p.Y < yMin { yMin = p.Y } else if p.Y > yMax { yMax = p.Y } if p.Z < zMin { zMin = p.Z } else if p.Z > zMax { zMax = p.Z } } // Determine upcoming state of all points within bounds. // The inspection must be extended to just beyond the bounds. upcoming := make(map[P]bool) for w := wMin - 1; w <= wMax+1; w++ { for x := xMin - 1; x <= xMax+1; x++ { for y := yMin - 1; y <= yMax+1; y++ { for z := zMin - 1; z <= zMax+1; z++ { p := Point(w, x, y, z) active := this.countActiveNeighbors(p) if this.IsActive(p) > 0 { upcoming[p] = active == 2 || active == 3 } else { upcoming[p] = active == 3 } } } } } // Deactivate and activate cells according to calculations. for p, state := range upcoming { this.Set(p, state) } } func (this World) countActiveNeighbors(p P) (active int) { for _, neighbor := range p.Neighbors4d() { active += this.IsActive(neighbor) } return active }
go/2020/day17/part2/part2.go
0.547948
0.454291
part2.go
starcoder
package rely import ( "math" ) // sequenceBuffer is a generic store for sent and received packets, as well as fragments of packets. // The entry data is the actual custom packet data that the user is trying to send type sequenceBuffer struct { Sequence uint16 NumEntries int EntrySequence []uint32 } const available = 0xFFFFFFFF // newSequenceBuffer creates a sequence buffer with specified entries and stride (size of each packet's data) func newSequenceBuffer(numEntries int) *sequenceBuffer { sb := &sequenceBuffer{ NumEntries: numEntries, EntrySequence: make([]uint32, numEntries), } sb.Reset() return sb } // Reset starts the sequence buffer from scratch func (sb *sequenceBuffer) Reset() { sb.Sequence = 0 for i := 0; i < sb.NumEntries; i++ { sb.EntrySequence[i] = math.MaxUint32 } } // RemoveEntries removes old entries from start sequence to finish sequence (inclusive) func (sb *sequenceBuffer) RemoveEntries(start, finish int) { if finish < start { finish += 65536 } if finish - start < sb.NumEntries { for sequence := start; sequence <= finish; sequence++ { // cleanup? sb.EntrySequence[sequence%sb.NumEntries] = available } } else { for i := 0; i < sb.NumEntries; i++ { sb.EntrySequence[i] = available } } } // TestInsert checks to see if the sequence can be inserted func (sb *sequenceBuffer) TestInsert(sequence uint16) bool { if lessThan(sequence, sb.Sequence - uint16(sb.NumEntries)) { return false } return true } func (sb *sequenceBuffer) Remove(sequence uint16) { sb.EntrySequence[int(sequence)%sb.NumEntries] = available } func (sb *sequenceBuffer) Available(sequence uint16) bool { return sb.EntrySequence[int(sequence)] == available } func (sb *sequenceBuffer) Exists(sequence uint16) bool { return sb.EntrySequence[int(sequence)%sb.NumEntries] == uint32(sequence) } func (sb *sequenceBuffer) GenerateAckBits(ack *uint16, ackBits *uint32) { *ack = sb.Sequence-1 *ackBits = 0 var mask uint32 = 1 for i:=0; i<32; i++ { sequence := *ack - uint16(i) if sb.Exists(sequence) { *ackBits |= mask } mask <<= 1 } } type sentPacketSequenceBuffer struct { *sequenceBuffer EntryData []sentPacketData } func newSentPacketSequenceBuffer(numEntries int) *sentPacketSequenceBuffer { return &sentPacketSequenceBuffer{ sequenceBuffer: newSequenceBuffer(numEntries), EntryData: make([]sentPacketData, numEntries), } } // Insert marks the sequence as used and returns an address to the buffer, or nil if insertion is invalid func (sb *sentPacketSequenceBuffer) Insert(sequence uint16) *sentPacketData { if lessThan(sequence, sb.Sequence-uint16(sb.NumEntries)) { // sequence is too low return nil } if greaterThan(sequence + 1, sb.Sequence) { // move the sequence forward, drop old entries sb.RemoveEntries(int(sb.Sequence), int(sequence)) sb.Sequence = sequence + 1 } index := int(sequence) % sb.NumEntries sb.EntrySequence[index] = uint32(sequence) return &sb.EntryData[index] } // Find returns the entry data for the sequence, or nil if there is none func (sb *sentPacketSequenceBuffer) Find(sequence uint16) *sentPacketData { index := int(sequence) % sb.NumEntries if sb.EntrySequence[index] == uint32(sequence) { return &sb.EntryData[index] } else { return nil } } func (sb *sentPacketSequenceBuffer) AtIndex(index int) *sentPacketData { if sb.EntrySequence[index] != available { return &sb.EntryData[index] } else { return nil } } type receivedPacketSequenceBuffer struct { *sequenceBuffer EntryData []receivedPacketData } func newReceivedPacketSequenceBuffer(numEntries int) *receivedPacketSequenceBuffer { return &receivedPacketSequenceBuffer{ sequenceBuffer: newSequenceBuffer(numEntries), EntryData: make([]receivedPacketData, numEntries), } } // Insert marks the sequence as used and returns an address to the buffer, or nil if insertion is invalid func (sb *receivedPacketSequenceBuffer) Insert(sequence uint16) *receivedPacketData { if lessThan(sequence, sb.Sequence-uint16(sb.NumEntries)) { // sequence is too low return nil } if greaterThan(sequence + 1, sb.Sequence) { // move the sequence forward, drop old entries sb.RemoveEntries(int(sb.Sequence), int(sequence)) sb.Sequence = sequence + 1 } index := int(sequence) % sb.NumEntries sb.EntrySequence[index] = uint32(sequence) return &sb.EntryData[index] } // Find returns the entry data for the sequence, or nil if there is none func (sb *receivedPacketSequenceBuffer) Find(sequence uint16) *receivedPacketData { index := int(sequence) % sb.NumEntries if sb.EntrySequence[index] == uint32(sequence) { return &sb.EntryData[index] } else { return nil } } func (sb *receivedPacketSequenceBuffer) AtIndex(index int) *receivedPacketData { if sb.EntrySequence[index] != available { return &sb.EntryData[index] } else { return nil } } type fragmentSequenceBuffer struct { *sequenceBuffer EntryData []fragmentReassemblyData } func newFragmentSequenceBuffer(numEntries int) *fragmentSequenceBuffer { return &fragmentSequenceBuffer{ sequenceBuffer: newSequenceBuffer(numEntries), EntryData: make([]fragmentReassemblyData, numEntries), } } // Insert marks the sequence as used and returns an address to the buffer, or nil if insertion is invalid func (sb *fragmentSequenceBuffer) Insert(sequence uint16) *fragmentReassemblyData { if lessThan(sequence, sb.Sequence-uint16(sb.NumEntries)) { // sequence is too low return nil } if greaterThan(sequence + 1, sb.Sequence) { // move the sequence forward, drop old entries sb.RemoveEntries(int(sb.Sequence), int(sequence)) sb.Sequence = sequence + 1 } index := int(sequence) % sb.NumEntries sb.EntrySequence[index] = uint32(sequence) return &sb.EntryData[index] } // Find returns the entry data for the sequence, or nil if there is none func (sb *fragmentSequenceBuffer) Find(sequence uint16) *fragmentReassemblyData { index := int(sequence) % sb.NumEntries if sb.EntrySequence[index] == uint32(sequence) { return &sb.EntryData[index] } else { return nil } } func (sb *fragmentSequenceBuffer) AtIndex(index int) *fragmentReassemblyData { if sb.EntrySequence[index] != available { return &sb.EntryData[index] } else { return nil } }
seqbuf.go
0.751101
0.469277
seqbuf.go
starcoder
package env import ( "fmt" "reflect" "strconv" "strings" "time" ) // setField determines a field's type and parses the given value // accordingly. An error will be returned if the field is unexported. func setBuiltInField(fieldValue reflect.Value, value string) (err error) { switch fieldValue.Kind() { case reflect.Bool: return setBool(fieldValue, value) case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return setInt(fieldValue, value) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return setUint(fieldValue, value) case reflect.Float32, reflect.Float64: return setFloat(fieldValue, value) case reflect.String: return setString(fieldValue, value) default: return fmt.Errorf("%s is not supported", fieldValue.Kind()) } } func setBool(fieldValue reflect.Value, value string) (err error) { var b bool if b, err = strconv.ParseBool(value); err != nil { return err } fieldValue.SetBool(b) return } func setInt(fieldValue reflect.Value, value string) (err error) { if fieldValue.Type() == reflect.TypeOf((*time.Duration)(nil)).Elem() { return setDuration(fieldValue, value) } var i int64 if i, err = strconv.ParseInt(value, 0, 64); err != nil { return err } fieldValue.SetInt(int64(i)) return } func setUint(fieldValue reflect.Value, value string) (err error) { var i uint64 if i, err = strconv.ParseUint(value, 0, 64); err != nil { return err } fieldValue.SetUint(uint64(i)) return } func setFloat(fieldValue reflect.Value, value string) (err error) { var f float64 if f, err = strconv.ParseFloat(value, 64); err != nil { return err } fieldValue.SetFloat(f) return } func setDuration(fieldValue reflect.Value, value string) (err error) { var d time.Duration if d, err = time.ParseDuration(value); err != nil { return err } fieldValue.SetInt(d.Nanoseconds()) return } func setString(fieldValue reflect.Value, value string) (err error) { fieldValue.SetString(value) return } func setSlice(t reflect.StructField, v reflect.Value, value string) (err error) { // allow the user to provide their own delimiter, falling back to a // comma if one isn't provided. delimiter := getDelimiter(t) rawValues := split(value, delimiter) sliceValue, err := makeSlice(v, len(rawValues)) if err != nil { return } populateSlice(sliceValue, rawValues) v.Set(sliceValue) return } func makeSlice(v reflect.Value, n int) (slice reflect.Value, err error) { switch v.Type() { case reflect.TypeOf([]string{}): slice = reflect.MakeSlice(reflect.TypeOf([]string{}), n, n) case reflect.TypeOf([]bool{}): slice = reflect.MakeSlice(reflect.TypeOf([]bool{}), n, n) case reflect.TypeOf([]int{}): slice = reflect.MakeSlice(reflect.TypeOf([]int{}), n, n) case reflect.TypeOf([]int8{}): slice = reflect.MakeSlice(reflect.TypeOf([]int8{}), n, n) case reflect.TypeOf([]int16{}): slice = reflect.MakeSlice(reflect.TypeOf([]int16{}), n, n) case reflect.TypeOf([]int32{}): slice = reflect.MakeSlice(reflect.TypeOf([]int32{}), n, n) case reflect.TypeOf([]int64{}): slice = reflect.MakeSlice(reflect.TypeOf([]int64{}), n, n) case reflect.TypeOf([]uint{}): slice = reflect.MakeSlice(reflect.TypeOf([]uint{}), n, n) case reflect.TypeOf([]uint8{}): slice = reflect.MakeSlice(reflect.TypeOf([]uint8{}), n, n) case reflect.TypeOf([]uint16{}): slice = reflect.MakeSlice(reflect.TypeOf([]uint16{}), n, n) case reflect.TypeOf([]uint32{}): slice = reflect.MakeSlice(reflect.TypeOf([]uint32{}), n, n) case reflect.TypeOf([]uint64{}): slice = reflect.MakeSlice(reflect.TypeOf([]uint64{}), n, n) case reflect.TypeOf([]float32{}): slice = reflect.MakeSlice(reflect.TypeOf([]float32{}), n, n) case reflect.TypeOf([]float64{}): slice = reflect.MakeSlice(reflect.TypeOf([]float64{}), n, n) case reflect.TypeOf([]time.Duration{}): slice = reflect.MakeSlice(reflect.TypeOf([]time.Duration{}), n, n) default: err = fmt.Errorf("%v is not supported", v.Type()) } return } func populateSlice(sliceValue reflect.Value, rawItems []string) { for i, item := range rawItems { setBuiltInField(sliceValue.Index(i), item) } } func split(value string, delimeter string) (out []string) { out = strings.Split(value, delimeter) for i, s := range out { out[i] = strings.Trim(s, " ") } return } func getDelimiter(t reflect.StructField) (d string) { if d, ok := t.Tag.Lookup("delimiter"); ok { return d } return "," }
vendor/github.com/codingconcepts/env/setter.go
0.61057
0.467393
setter.go
starcoder
package wkttoorb import ( "fmt" "strconv" "github.com/paulmach/orb" "github.com/pkg/errors" ) type Parser struct { *Lexer } func (p *Parser) Parse() (orb.Geometry, error) { t, err := p.scanToken() if err != nil { return nil, err } switch t.ttype { case Point: return p.parsePoint() case Linestring: return p.parseLineString() case Polygon: return p.parsePolygon() case Multipoint: line, err := p.parseLineString() return orb.MultiPoint(line), err case MultilineString: poly, err := p.parsePolygon() multiline := make(orb.MultiLineString, 0, len(poly)) for _, ring := range poly { multiline = append(multiline, orb.LineString(ring)) } return multiline, err case MultiPolygon: return p.parseMultiPolygon() default: return nil, fmt.Errorf("Parse unexpected token %s on pos %d expected geometry type", t.lexeme, t.pos) } } func (p *Parser) parsePoint() (point orb.Point, err error) { t, err := p.scanToken() if err != nil { return point, err } switch t.ttype { case Empty: point = orb.Point{0, 0} case Z, M, ZM: t1, err := p.scanToken() if err != nil { return point, err } if t1.ttype == Empty { point = orb.Point{0, 0} break } if t1.ttype != LeftParen { return point, fmt.Errorf("parse point unexpected token %s on pos %d", t.lexeme, t.pos) } fallthrough case LeftParen: switch t.ttype { // reswitch on the type because of the fallthrough case Z, M: point, err = p.parseCoordDrop1() case ZM: point, err = p.parseCoordDrop2() default: point, err = p.parseCoord() } if err != nil { return point, err } t, err = p.scanToken() if err != nil { return point, err } if t.ttype != RightParen { return point, fmt.Errorf("parse point unexpected token %s on pos %d expected )", t.lexeme, t.pos) } default: return point, fmt.Errorf("parse point unexpected token %s on pos %d", t.lexeme, t.pos) } t, err = p.scanToken() if err != nil { return point, err } if t.ttype != Eof { return point, fmt.Errorf("parse point unexpected token %s on pos %d", t.lexeme, t.pos) } return point, nil } func (p *Parser) parseLineString() (line orb.LineString, err error) { line = make([]orb.Point, 0) t, err := p.scanToken() if err != nil { return nil, err } switch t.ttype { case Empty: case Z, M, ZM: t1, err := p.scanToken() if err != nil { return line, err } if t1.ttype == Empty { break } if t1.ttype != LeftParen { return line, fmt.Errorf("unexpected token %s on pos %d expected '('", t.lexeme, t.pos) } fallthrough case LeftParen: line, err = p.parseLineStringText(t.ttype) if err != nil { return line, err } default: return line, fmt.Errorf("unexpected token %s on pos %d", t.lexeme, t.pos) } t, err = p.scanToken() if err != nil { return line, err } if t.ttype != Eof { return line, fmt.Errorf("unexpected token %s on pos %d, expected Eof", t.lexeme, t.pos) } return line, nil } func (p *Parser) parseLineStringText(ttype tokenType) (line orb.LineString, err error) { line = make([]orb.Point, 0) for { var point orb.Point switch ttype { case Z, M: point, err = p.parseCoordDrop1() case ZM: point, err = p.parseCoordDrop2() default: point, err = p.parseCoord() } if err != nil { return line, err } line = append(line, point) t, err := p.scanToken() if err != nil { return line, err } if t.ttype == RightParen { break } else if t.ttype != Comma { return line, fmt.Errorf("unexpected token %s on pos %d expected ','", t.lexeme, t.pos) } } return line, nil } func (p *Parser) parsePolygon() (poly orb.Polygon, err error) { poly = make([]orb.Ring, 0) t, err := p.scanToken() if err != nil { return poly, err } switch t.ttype { case Empty: case Z, M, ZM: t1, err := p.scanToken() if err != nil { return poly, err } if t1.ttype == Empty { break } if t1.ttype != LeftParen { return poly, fmt.Errorf("unexpected token %s on pos %d expected '('", t.lexeme, t.pos) } fallthrough case LeftParen: poly, err = p.parsePolygonText(t.ttype) if err != nil { return poly, err } default: return poly, fmt.Errorf("unexpected token %s on pos %d", t.lexeme, t.pos) } t, err = p.scanToken() if err != nil { return poly, err } if t.ttype != Eof { return poly, fmt.Errorf("unexpected token %s on pos %d, expected Eof", t.lexeme, t.pos) } return poly, nil } func (p *Parser) parsePolygonText(ttype tokenType) (poly orb.Polygon, err error) { poly = make([]orb.Ring, 0) for { var line orb.LineString t, err := p.scanToken() if err != nil { return poly, err } if t.ttype != LeftParen { return poly, fmt.Errorf("unexpected token %s on pos %d expected '('", t.lexeme, t.pos) } line, err = p.parseLineStringText(ttype) if err != nil { return poly, err } poly = append(poly, orb.Ring(line)) t, err = p.scanToken() if err != nil { return poly, err } if t.ttype == RightParen { break } else if t.ttype != Comma { return poly, fmt.Errorf("unexpected token %s on pos %d expected ','", t.lexeme, t.pos) } } return poly, nil } func (p *Parser) parseMultiPolygon() (multi orb.MultiPolygon, err error) { multi = make([]orb.Polygon, 0) t, err := p.scanToken() if err != nil { return multi, err } switch t.ttype { case Empty: case Z, M, ZM: t1, err := p.scanToken() if err != nil { return multi, err } if t1.ttype == Empty { break } if t1.ttype != LeftParen { return multi, fmt.Errorf("unexpected token %s on pos %d expected '('", t.lexeme, t.pos) } fallthrough case LeftParen: multi, err = p.parseMultiPolygonText(t.ttype) if err != nil { return multi, err } default: return multi, fmt.Errorf("unexpected token %s on pos %d", t.lexeme, t.pos) } t, err = p.scanToken() if err != nil { return multi, err } if t.ttype != Eof { return multi, fmt.Errorf("unexpected token %s on pos %d, expected Eof", t.lexeme, t.pos) } return multi, nil } func (p *Parser) parseMultiPolygonText(ttype tokenType) (multi orb.MultiPolygon, err error) { multi = make([]orb.Polygon, 0) for { var poly orb.Polygon t, err := p.scanToken() if err != nil { return multi, err } if t.ttype != LeftParen { return multi, fmt.Errorf("unexpected token %s on pos %d expected '('", t.lexeme, t.pos) } poly, err = p.parsePolygonText(ttype) if err != nil { return multi, err } multi = append(multi, poly) t, err = p.scanToken() if err != nil { return multi, err } if t.ttype == RightParen { break } else if t.ttype != Comma { return multi, fmt.Errorf("unexpected token %s on pos %d expected ','", t.lexeme, t.pos) } } return multi, nil } func (p *Parser) parseCoord() (point orb.Point, err error) { t1, err := p.scanToken() if err != nil { return point, err } if t1.ttype != Float { return point, fmt.Errorf("parse coordinates unexpected token %s on pos %d", t1.lexeme, t1.pos) } t2, err := p.scanToken() if err != nil { return point, err } if t2.ttype != Float { return point, fmt.Errorf("parse coordinates unexpected token %s on pos %d", t1.lexeme, t2.pos) } c1, err := strconv.ParseFloat(t1.lexeme, 64) if err != nil { return point, errors.Wrap(err, fmt.Sprintf("invalid lexeme %s for token on pos %d", t1.lexeme, t1.pos)) } c2, err := strconv.ParseFloat(t2.lexeme, 64) if err != nil { return point, errors.Wrap(err, fmt.Sprintf("invalid lexeme %s for token on pos %d", t2.lexeme, t2.pos)) } return orb.Point{c1, c2}, nil } func (p *Parser) parseCoordDrop1() (point orb.Point, err error) { point, err = p.parseCoord() if err != nil { return point, err } // drop the last value Z or M coordinates are not really supported t, err := p.scanToken() if err != nil { return point, err } if t.ttype != Float { return point, fmt.Errorf("parseCoordDrop1 unexpected token %s on pos %d expected Float", t.lexeme, t.pos) } return point, nil } func (p *Parser) parseCoordDrop2() (point orb.Point, err error) { point, err = p.parseCoord() if err != nil { return point, err } // drop the last value M values // and Z coordinates are not really supported for i := 0; i < 2; i++ { t, err := p.scanToken() if err != nil { return point, err } if t.ttype != Float { return point, fmt.Errorf("parseCoordDrop2 unexpected token %s on pos %d expected Float", t.lexeme, t.pos) } } return point, nil }
parser.go
0.690559
0.522263
parser.go
starcoder
package main import ( "flag" "fmt" "math" "os" ) // R is an ideal gas constant const R = 0.0831 // Temperature represents gas temperature type Temperature float64 // GasVolume is the amount of gas in liters type GasVolume float64 // CylinderVolume is cylinder size in liters type CylinderVolume float64 // GasWeight is the amount of of gas in kilograms (kg) type GasWeight float64 // PressureBar represents pressure (in bar) type PressureBar float64 // AtomicWeight is an atomic weight for an element type AtomicWeight float64 // PressureFromVolumes returns a new PressureBar instance from gas volume and cylinder volume. func PressureFromVolumes(gasVolume GasVolume, totalVolume CylinderVolume) PressureBar { return PressureBar(float64(gasVolume) / float64(totalVolume)) } // PartialPressure returns a new partial pressure object from pressure and multiplier. func (p PressureBar) PartialPressure(pp float64) PressureBar { return PressureBar(float64(p) * pp) } // GasWeightFromMole calculates gas weight based on the mole count and atomic weight. func GasWeightFromMole(moleCount MoleCount, atomicWeight AtomicWeight) GasWeight { return GasWeight(float64(moleCount) * float64(atomicWeight)) } // MoleCount represents number of atoms type MoleCount float64 // GasSystem is the system used to calculate amount of the gas. type GasSystem int const ( // IdealGas uses ideal gas equations which do not compensate for pressure and temperature IdealGas GasSystem = iota // VanDerWaals uses Van Der Waals equations to compensate for temperature and pressure. VanDerWaals ) // Gas represents various gases cylinders may contain. type Gas int // Available gases const ( Helium Gas = iota Oxygen Nitrogen Argon Neon Hydrogen ) // VanDerWaalsConstant represents Van der Waals equation constants type VanDerWaalsConstant struct { A float64 B float64 } // AtomicWeightLookup is the weight of a single mole in grams. var AtomicWeightLookup = map[Gas]AtomicWeight{ Argon: 14.0067, Helium: 4.002602, Hydrogen: 1.00784, Neon: 20.1797, Nitrogen: 14.0067, Oxygen: 15.999, } // VanDerWaalsConstants holds Van der Waals constants for gases. var VanDerWaalsConstants = map[Gas]VanDerWaalsConstant{ Argon: {A: 1.355, B: 0.03201}, Helium: {A: 0.0346, B: 0.0238}, Hydrogen: {A: 0.2476, B: 0.02661}, Neon: {A: 0.2135, B: 0.01709}, Nitrogen: {A: 1.370, B: 0.0387}, Oxygen: {A: 1.382, B: 0.03186}, } // GasComposition stores information about gases currently being processed type GasComposition map[Gas]float64 // Equalize equalizes all input cylinders func Equalize(cylinders []*Cylinder, gasSystem GasSystem, gasComposition GasComposition, temperature Temperature, verbose bool, debug bool) { var totalVolume CylinderVolume var pressureAfterEqualize PressureBar if gasSystem == IdealGas { var totalGasVolume GasVolume for i := range cylinders { totalGasVolume += cylinders[i].GasVolume(gasSystem, gasComposition, temperature) totalVolume += cylinders[i].CylinderVolume } pressureAfterEqualize = PressureFromVolumes(totalGasVolume, totalVolume) } else { var totalMoles MoleCount for i := range cylinders { moles := cylinders[i].Moles(temperature, gasComposition) if debug { fmt.Println("Cylinder", cylinders[i], "moles", moles) } totalMoles += moles totalVolume += cylinders[i].CylinderVolume } pressureAfterEqualize = cylinderMolesToPressure(totalVolume, totalMoles, temperature, gasComposition) if debug { fmt.Println("Moles:", totalMoles, "Pressure after equalize:", pressureAfterEqualize) } } for i := range cylinders { cylinders[i].Pressure = pressureAfterEqualize } } // CylinderConfiguration holds information about available cylinders and cylinder configuration, such as manifolds type CylinderConfiguration struct { DestinationCylinderIsTwinset bool DestinationCylinderPressure PressureBar DestinationCylinderVolume CylinderVolume SourceCylinderIsTwinset bool SourceCylinderPressure PressureBar SourceCylinderVolume CylinderVolume } // Cylinder represents a single cylinder and gas it contains type Cylinder struct { Description string CylinderVolume CylinderVolume Pressure PressureBar } // GasVolume returns amount of gas in the cylinder func (c1 Cylinder) GasVolume(gasSystem GasSystem, gasComposition GasComposition, temperature Temperature) GasVolume { if gasSystem == IdealGas { return GasVolume(float64(c1.CylinderVolume) * float64(c1.Pressure)) } return GasVolume(gasCompositionToMoles(c1.CylinderVolume, c1.Pressure, temperature, gasComposition) * 22.4) } // Equalize equalizes two cylinders func (c1 *Cylinder) Equalize(c2 *Cylinder, gasSystem GasSystem, gasComposition GasComposition, temperature Temperature, verbose bool, debug bool) { listOfCylinders := []*Cylinder{c1, c2} Equalize(listOfCylinders, gasSystem, gasComposition, temperature, verbose, debug) } // Moles returns number of atoms (in mole) inside a cylinder func (c1 *Cylinder) Moles(temperature Temperature, gasComposition GasComposition) MoleCount { return gasCompositionToMoles(c1.CylinderVolume, c1.Pressure, temperature, gasComposition) } func gasCompositionToMoles(cylinderVolume CylinderVolume, cylinderPressure PressureBar, temperature Temperature, gasComposition GasComposition) MoleCount { var moles MoleCount for gasType, gasInfo := range gasComposition { moles += GasToMoles(cylinderVolume, cylinderPressure.PartialPressure(gasInfo), VanDerWaalsConstants[gasType], temperature) } return moles } // GasToMoles calculates number of atoms in given cylinder func GasToMoles(cylinderVolume CylinderVolume, cylinderPressure PressureBar, vdwConstants VanDerWaalsConstant, temperature Temperature) MoleCount { a := vdwConstants.A b := vdwConstants.B P := float64(cylinderPressure) a2 := math.Pow(a, 2.0) a3 := math.Pow(a, 3.0) b2 := math.Pow(b, 2.0) V := float64(cylinderVolume) V2 := math.Pow(V, 2.0) V3 := math.Pow(V, 3.0) T := float64(temperature) subterm1 := 2*a3*V3 + 18*a2*b2*P*V3 - 9*a2*b*R*T*V3 subterm2 := 3*a*b*(b*P*V2+R*T*V2) - a2*V2 subterm3 := math.Pow( (subterm1 + math.Sqrt(4*math.Pow(subterm2, 3.0)+math.Pow(subterm1, 2.0))), (1 / 3.0)) term1 := 0.26457 * subterm3 term2 := a * b * subterm3 term3 := 0.41997 * subterm2 return MoleCount(term1/(a*b) - term3/term2 + (0.33333*V)/b) } // GasWeight returns weight of the gas stored inside the cylinder func (c1 Cylinder) GasWeight(gasComposition GasComposition, temperature Temperature) GasWeight { var weightSum GasWeight for gasType, gasInfo := range gasComposition { moleCount := GasToMoles(c1.CylinderVolume, c1.Pressure.PartialPressure(gasInfo), VanDerWaalsConstants[gasType], temperature) gasWeight := GasWeightFromMole(moleCount, AtomicWeightLookup[gasType]) weightSum += gasWeight } return weightSum } func cylinderMolesToPressure(cylinderVolume CylinderVolume, n MoleCount, temperature Temperature, gasComposition GasComposition) PressureBar { var pressureSum PressureBar for gasType, gasInfo := range gasComposition { pressureSum += MolesToPressure(cylinderVolume, MoleCount(float64(n)*gasInfo), temperature, VanDerWaalsConstants[gasType]) } return pressureSum } // MolesToPressure returns pressure based on the volume, atomic count and gas composition. func MolesToPressure(cylinderVolume CylinderVolume, moleCount MoleCount, T Temperature, vdwConstants VanDerWaalsConstant) PressureBar { V := float64(cylinderVolume) a := vdwConstants.A b := vdwConstants.B n := float64(moleCount) V2 := math.Pow(V, 2.0) return PressureBar(n * (-(a*n)/V2 - (R*float64(T))/(b*n-V))) } // CylinderList is a list of cylinders type CylinderList []Cylinder // TotalVolume returns total cylinder volume for all listed cylinders func (cl CylinderList) TotalVolume() CylinderVolume { var totalVolume CylinderVolume for _, cylinder := range cl { totalVolume += cylinder.CylinderVolume } return totalVolume } // TotalGasWeight calculates the weight of the gas for all cylinders in cylinder list. func (cl CylinderList) TotalGasWeight(gasComposition GasComposition, temperature Temperature) GasWeight { var weightSum GasWeight for _, cylinder := range cl { weightSum += cylinder.GasWeight(gasComposition, temperature) } return weightSum } // TotalGasVolume returns total gas volume for all listed cylinders func (cl CylinderList) TotalGasVolume(gasSystem GasSystem, gasComposition GasComposition, temperature Temperature) GasVolume { var totalGasVolume GasVolume for _, cylinder := range cl { totalGasVolume += cylinder.GasVolume(gasSystem, gasComposition, temperature) } return totalGasVolume } func initializeCylinders(cylinderConfiguration CylinderConfiguration, sourceCylinders *CylinderList, destinationCylinders *CylinderList) { if cylinderConfiguration.SourceCylinderIsTwinset { *sourceCylinders = []Cylinder{ { Description: "left", CylinderVolume: CylinderVolume(cylinderConfiguration.SourceCylinderVolume / 2), Pressure: cylinderConfiguration.SourceCylinderPressure, }, { Description: "right", CylinderVolume: CylinderVolume(cylinderConfiguration.SourceCylinderVolume / 2), Pressure: cylinderConfiguration.SourceCylinderPressure, }, } } else { *sourceCylinders = []Cylinder{ { Description: "source", CylinderVolume: CylinderVolume(cylinderConfiguration.SourceCylinderVolume), Pressure: cylinderConfiguration.SourceCylinderPressure, }, } } if cylinderConfiguration.DestinationCylinderIsTwinset { *destinationCylinders = []Cylinder{ { Description: "left", CylinderVolume: CylinderVolume(cylinderConfiguration.DestinationCylinderVolume / 2), Pressure: cylinderConfiguration.DestinationCylinderPressure, }, { Description: "right", CylinderVolume: CylinderVolume(cylinderConfiguration.DestinationCylinderVolume / 2), Pressure: cylinderConfiguration.DestinationCylinderPressure, }, } } else { *destinationCylinders = []Cylinder{ { Description: "destination", CylinderVolume: CylinderVolume(cylinderConfiguration.DestinationCylinderVolume), Pressure: cylinderConfiguration.DestinationCylinderPressure, }, } } } // CylinderSummary has information about the end result of gas transfers type CylinderSummary struct { Description string DestinationCylinderGasVolume GasVolume DestinationCylinderGasWeight GasWeight DestinationCylinderPressure PressureBar SourceCylinderGasVolume GasVolume SourceCylinderPressure PressureBar SourceCylinderGasWeight GasWeight } func equalizeAndReport(cylinderConfiguration CylinderConfiguration, gasSystem GasSystem, gasComposition GasComposition, temperature Temperature, verbose bool, debug bool, printSourceSummary bool) CylinderSummary { var sourceCylinders CylinderList var destinationCylinders CylinderList initializeCylinders(cylinderConfiguration, &sourceCylinders, &destinationCylinders) if printSourceSummary { sourceCylinderGasVolume := sourceCylinders.TotalGasVolume(gasSystem, gasComposition, temperature) destinationCylinderGasVolume := destinationCylinders.TotalGasVolume(gasSystem, gasComposition, temperature) if verbose { fmt.Println("Before any transfers:") fmt.Println("Source cylinders:", sourceCylinderGasVolume, "l of gas, pressure", cylinderConfiguration.SourceCylinderPressure, "bar") fmt.Println("Destination cylinders:", destinationCylinderGasVolume, "l of gas, pressure", cylinderConfiguration.DestinationCylinderPressure, "bar") fmt.Println() } } var description string if cylinderConfiguration.DestinationCylinderIsTwinset && cylinderConfiguration.SourceCylinderIsTwinset { description = "both manifolds closed" } else if cylinderConfiguration.DestinationCylinderIsTwinset { description = "destination manifold closed" } else if cylinderConfiguration.SourceCylinderIsTwinset { description = "source manifold closed" } else { description = "all manifolds open" } fmt.Println("Equalizing with", description) stepI := 0 for sourceI := range sourceCylinders { for destinationI := range destinationCylinders { stepI++ destinationCylinderGasVolumeBefore := destinationCylinders[destinationI].GasVolume(gasSystem, gasComposition, temperature) destinationCylinders[destinationI].Equalize(&sourceCylinders[sourceI], gasSystem, gasComposition, temperature, verbose, debug) if verbose { fmt.Printf("Step %d: from %s to %s; transferred %.0fl of gas\n", stepI, sourceCylinders[sourceI].Description, destinationCylinders[destinationI].Description, destinationCylinders[destinationI].GasVolume(gasSystem, gasComposition, temperature)-destinationCylinderGasVolumeBefore) } } } destinationCylinderPointers := make([]*Cylinder, len(destinationCylinders)) for destinationI := range destinationCylinders { destinationCylinderPointers[destinationI] = &destinationCylinders[destinationI] } Equalize(destinationCylinderPointers, gasSystem, gasComposition, temperature, verbose, debug) if debug { fmt.Println("Source cylinders gas volume:", sourceCylinders.TotalGasVolume(gasSystem, gasComposition, temperature)) fmt.Println("Destination cylinders gas volume:", destinationCylinders.TotalGasVolume(gasSystem, gasComposition, temperature)) } sourceCylinderGasVolume := sourceCylinders.TotalGasVolume(gasSystem, gasComposition, temperature) sourceCylinderPressure := PressureFromVolumes(sourceCylinderGasVolume, sourceCylinders.TotalVolume()) destinationCylinderGasVolume := destinationCylinders.TotalGasVolume(gasSystem, gasComposition, temperature) destinationCylinderPressure := PressureFromVolumes(destinationCylinderGasVolume, destinationCylinders.TotalVolume()) fmt.Printf("Source cylinders: %.0fl, %.0fbar\n", sourceCylinderGasVolume, sourceCylinderPressure) fmt.Printf("Destination cylinders: %.0fl, %.0fbar\n", destinationCylinderGasVolume, destinationCylinderPressure) fmt.Println() return CylinderSummary{ Description: description, DestinationCylinderGasVolume: destinationCylinderGasVolume, DestinationCylinderGasWeight: destinationCylinders.TotalGasWeight(gasComposition, temperature), DestinationCylinderPressure: destinationCylinderPressure, SourceCylinderGasVolume: sourceCylinderGasVolume, SourceCylinderGasWeight: sourceCylinders.TotalGasWeight(gasComposition, temperature), SourceCylinderPressure: sourceCylinderPressure, } } func printSummaries(cylinderSummaries []CylinderSummary, verbose bool) { var worstDestinationPressure PressureBar for _, cylinderSummary := range cylinderSummaries { if cylinderSummary.DestinationCylinderPressure < worstDestinationPressure || worstDestinationPressure == 0 { worstDestinationPressure = cylinderSummary.DestinationCylinderPressure } } fmt.Printf("%30s src bar src l dst bar dst l improvement\n", "") for _, cylinderSummary := range cylinderSummaries { if cylinderSummary.Description == "" { continue } fmt.Printf("%30s %7.0f %6.0f %8.0f %6.0f %10.2f%%\n", cylinderSummary.Description, cylinderSummary.SourceCylinderPressure, cylinderSummary.SourceCylinderGasVolume, cylinderSummary.DestinationCylinderPressure, cylinderSummary.DestinationCylinderGasVolume, 100*(cylinderSummary.DestinationCylinderPressure-worstDestinationPressure)/worstDestinationPressure) if verbose { fmt.Printf(" Gas weight %6.0fg %6.0fg\n", cylinderSummary.SourceCylinderGasWeight, cylinderSummary.DestinationCylinderGasWeight) } } } func main() { var verboseFlag = flag.Bool("verbose", false, "Print detailed information") var debugFlag = flag.Bool("debug", false, "Print debug information") var sourceCylinderVolumeFlag = flag.Float64("source-cylinder-volume", 24, "Source cylinder volume in liters") var useIdealGasFlag = flag.Bool("use-ideal-gas", false, "Use ideal gas equations instead of Van der Waals") var destinationCylinderVolumeFlag = flag.Float64("destination-cylinder-volume", 24, "Destination cylinder volume in liters") var sourceCylinderPressureFlag = flag.Float64("source-cylinder-pressure", 232, "Source cylinder pressure in bar") var destinationCylinderPressureFlag = flag.Float64("destination-cylinder-pressure", 100, "Destination cylinder pressure") var sourceCylinderIsTwinsetFlag = flag.Bool("source-cylinder-twinset", false, "Source cylinder is a twinset with a closeable manifold") var destinationCylinderIsTwinsetFlag = flag.Bool("destination-cylinder-twinset", false, "Destination cylinder is a twinset with a closeable manifold") var temperatureFlag = flag.Float64("temperature", 20.0, "Gas temperature for Van der Waals equation (celsius)") var heliumPercentFlag = flag.Float64("helium", 0.0, "Percentage of helium") var oxygenPercentFlag = flag.Float64("oxygen", 0.21, "Percentage of oxygen") var neonPercentFlag = flag.Float64("neon", 0, "Percentage of neon") var argonPercentFlag = flag.Float64("argon", 0, "Percentage of argon") var hydrogenPercentFlag = flag.Float64("hydrogen", 0, "Percentage of hydrogen") flag.Parse() if *temperatureFlag < -30 || *temperatureFlag > 80 { println("Invalid temperature. Must be >-30 and <80") os.Exit(1) } gasSum := *heliumPercentFlag + *oxygenPercentFlag + *neonPercentFlag + *argonPercentFlag + *hydrogenPercentFlag if gasSum > 1.0 { println("Defined gases must not exceed 100% (1.0)") os.Exit(11) } nitrogenPercent := 1.0 - gasSum gasComposition := GasComposition{ Argon: *argonPercentFlag, Helium: *heliumPercentFlag, Hydrogen: *hydrogenPercentFlag, Neon: *neonPercentFlag, Nitrogen: nitrogenPercent, Oxygen: *oxygenPercentFlag, } if *destinationCylinderPressureFlag > 350 || *destinationCylinderPressureFlag < 0 { println("Invalid destination cylinder pressure; must be >= 0 and <=350") os.Exit(1) } if *sourceCylinderPressureFlag > 350 || *sourceCylinderPressureFlag <= 0 { println("Invalid source cylinder pressure; must be > 0 and <=350") os.Exit(1) } if *sourceCylinderPressureFlag < *destinationCylinderPressureFlag { println("Source pressure must be higher than destination pressure") os.Exit(1) } if *destinationCylinderVolumeFlag <= 0 || *destinationCylinderVolumeFlag > 1000 { println("Destination cylinder volume size must be greater than 0 and less than 1000") os.Exit(1) } if *sourceCylinderVolumeFlag <= 0 || *sourceCylinderVolumeFlag > 1000 { println("Source cylinder volume size must be greater than 0 and less than 1000") os.Exit(1) } temperature := Temperature(*temperatureFlag + 273.15) var gasSystem GasSystem if *useIdealGasFlag { gasSystem = IdealGas } else { gasSystem = VanDerWaals } cylinderConfiguration := CylinderConfiguration{ DestinationCylinderIsTwinset: *destinationCylinderIsTwinsetFlag, DestinationCylinderPressure: PressureBar(*destinationCylinderPressureFlag), DestinationCylinderVolume: CylinderVolume(*destinationCylinderVolumeFlag), SourceCylinderIsTwinset: *sourceCylinderIsTwinsetFlag, SourceCylinderPressure: PressureBar(*sourceCylinderPressureFlag), SourceCylinderVolume: CylinderVolume(*sourceCylinderVolumeFlag), } cylinderSummaries := make([]CylinderSummary, 4) a := 0 cylinderSummaries[a] = equalizeAndReport(cylinderConfiguration, gasSystem, gasComposition, temperature, *verboseFlag, *debugFlag, true) a++ if *sourceCylinderIsTwinsetFlag { cylinderConfiguration.SourceCylinderIsTwinset = false cylinderSummaries[a] = equalizeAndReport(cylinderConfiguration, gasSystem, gasComposition, temperature, *verboseFlag, *debugFlag, true) a++ cylinderConfiguration.SourceCylinderIsTwinset = true } if *destinationCylinderIsTwinsetFlag { cylinderConfiguration.DestinationCylinderIsTwinset = false cylinderSummaries[a] = equalizeAndReport(cylinderConfiguration, gasSystem, gasComposition, temperature, *verboseFlag, *debugFlag, true) a++ cylinderConfiguration.DestinationCylinderIsTwinset = true } if *destinationCylinderIsTwinsetFlag || *sourceCylinderIsTwinsetFlag { cylinderConfiguration.DestinationCylinderIsTwinset = false cylinderConfiguration.SourceCylinderIsTwinset = false cylinderSummaries[a] = equalizeAndReport(cylinderConfiguration, gasSystem, gasComposition, temperature, *verboseFlag, *debugFlag, true) a++ } printSummaries(cylinderSummaries, *verboseFlag) }
app.go
0.824356
0.58439
app.go
starcoder
package polygon import ( "fmt" ) var ErrNoData = fmt.Errorf("polygon: no data") // Polygon represents and enclosed area given a set of coordinates type Polygon struct { data []Point // these store the min/max of our points minLat, maxLat, minLon, maxLon float64 isMinMaxComputed bool } // Point represent a single coordinate type Point struct { Lat, Lon float64 } // NewPolygonAsPoints retuns a Polygon given a variadic list of points. // If the list is even, the method will automatically close the polygon // by using the starting point as the last point. func NewPolygonAsPoints(points ...Point) (*Polygon, error) { var mustClose bool polygon := Polygon{} if len(points) == 0 { return nil, ErrNoData } if len(points)%2 == 0 { mustClose = true } for _, p := range points { polygon.data = append(polygon.data, p) } if mustClose { polygon.data = append(polygon.data, polygon.data[0]) } return &polygon, nil } // NewPolygonAsSlice retuns a Polygon given a slice of points. // If slice is even, the method will automatically close the polygon // by using the starting point as the last point. func NewPolygonAsSlice(points []Point) (*Polygon, error) { return NewPolygonAsPoints(points...) } // Contains returns true if the given point lies within the boundary // of the polygon. // Based on: https://stackoverflow.com/questions/217578/how-can-i-determine-whether-a-2d-point-is-within-a-polygon func (p *Polygon) Contains(point Point) bool { if p.data == nil { return false } // this will effciently determine if a point is NOT inside the polygon if !p.isMinMaxComputed { p.computeMinMax() } if point.Lat < p.minLat || point.Lat > p.maxLat || point.Lon < p.minLon || point.Lon > p.maxLon { return false } // now check if the point is inside var inside bool for i, j := 0, len(p.data)-1; i < len(p.data) && j < len(p.data); j = i { i++ if i == len(p.data) { break } if j == len(p.data) { break } if (p.data[i].Lon > point.Lon) != (p.data[j].Lon > point.Lon) && point.Lat < (p.data[j].Lat-p.data[i].Lat)*(point.Lon-p.data[i].Lon)/ (p.data[j].Lon-p.data[i].Lon)+p.data[i].Lat { inside = !inside break } } return inside } func (p *Polygon) computeMinMax() { p.isMinMaxComputed = true for i, point := range p.data { if i == 0 { p.minLat, p.minLon = point.Lat, point.Lon p.maxLat, p.maxLon = point.Lat, point.Lon continue } if p.minLat > point.Lat { p.minLat = point.Lat } if p.minLon > point.Lon { p.minLon = point.Lon } if p.maxLat < point.Lat { p.maxLat = point.Lat } if p.maxLon < point.Lon { p.maxLon = point.Lon } } }
polygon.go
0.793306
0.52074
polygon.go
starcoder
package jumble // FrameOval sets the frame shape to // oval (default is rectangle) func FrameOval(val bool) func(f *Frame) { return func(fr *Frame) { fr.oval = val } } // FrameColor sets the frame color func FrameColor(hex string) func(f *Frame) { return func(fr *Frame) { fr.color = hex } } // FrameStroke enables the frame stroke func FrameStroke(val bool) func(f *Frame) { return func(fr *Frame) { fr.stroke = val } } // FrameDashes sets the frame dashes func FrameDashes(val float64) func(f *Frame) { return func(fr *Frame) { fr.dashes = val } } // FrameStrokeWidth sets the stroke width func FrameStrokeWidth(val float64) func(f *Frame) { return func(fr *Frame) { fr.strokeWidth = val } } // Frame represents a frame on the grid. type Frame struct { Left int Top int Right int Bottom int dashes float64 color string stroke bool strokeWidth float64 oval bool } // NewFrame returns a new frame func NewFrame(l, t int, r, b int, opts ...func(*Frame)) Frame { res := Frame{ Left: l, Top: t, Right: r, Bottom: b, oval: false, color: "#000000", stroke: true, strokeWidth: 1, dashes: 5, } for _, opt := range opts { opt(&res) } return res } // Location returns the grid position (row, col) func (fr *Frame) Location() (int, int) { return fr.Left, fr.Right } // Plot draws a frame accross the specified cells func (fr *Frame) Plot(g *Grid) error { if err := g.VerifyInBounds(fr.Left, fr.Top); err != nil { return err } p1 := g.CellCenter(fr.Left, fr.Top) p2 := g.CellCenter(fr.Right, fr.Bottom) dx, dy := p2.X-p1.X, p2.Y-p1.Y dc := g.Context() dc.Push() if fr.dashes > 0 { dc.SetDash(fr.dashes) } else { dc.SetDash() } dc.SetLineWidth(fr.strokeWidth) dc.SetHexColor(fr.color) if fr.oval { rx, ry := 0.5*dx, 0.5*dy cx, cy := p1.X+rx, p1.Y+ry dc.DrawEllipse(cx, cy, rx, ry) } else { dc.DrawRectangle(p1.X, p1.Y, dx, dy) } if fr.stroke { dc.Stroke() } else { dc.Fill() } dc.Pop() return nil }
frame.go
0.878151
0.402598
frame.go
starcoder
package omgo import ( "encoding/json" "time" ) type ForecastJSON struct { Latitude float64 Longitude float64 Elevation float64 GenerationTime float64 `json:"generationtime_ms"` CurrentWeather CurrentWeather `json:"current_weather"` HourlyUnits map[string]string `json:"hourly_units"` HourlyMetrics map[string]json.RawMessage `json:"hourly"` // Parsed later, the API returns both Time and floats here DailyUnits map[string]string `json:"daily_units"` DailyMetrics map[string]json.RawMessage `json:"daily"` // Parsed later, the API returns both Time and floats here } type Forecast struct { Latitude float64 Longitude float64 Elevation float64 GenerationTime float64 CurrentWeather CurrentWeather HourlyUnits map[string]string HourlyMetrics map[string][]float64 // Parsed from ForecastJSON.HourlyMetrics HourlyTimes []time.Time // Parsed from ForecastJSON.HourlyMetrics DailyUnits map[string]string DailyMetrics map[string][]float64 // Parsed from ForecastJSON.DailyMetrics DailyTimes []time.Time // Parsed from ForecastJSON.DailyMetrics } type CurrentWeather struct { Temperature float64 Time ApiTime WeatherCode int WindDirection int WindSpeed float64 } // ParseBody converts the API response body into a Forecast struct // Rationale: The API returns a map with both times as well as floats, this function // unmarshalls in 2 steps in order to not return a map[string][]interface{} func ParseBody(body []byte) (*Forecast, error) { f := &ForecastJSON{} err := json.Unmarshal(body, f) if err != nil { return nil, err } fc := &Forecast{ Latitude: f.Latitude, Longitude: f.Longitude, Elevation: f.Elevation, GenerationTime: f.GenerationTime, CurrentWeather: f.CurrentWeather, HourlyUnits: f.HourlyUnits, HourlyTimes: []time.Time{}, HourlyMetrics: make(map[string][]float64), DailyUnits: f.DailyUnits, DailyTimes: []time.Time{}, DailyMetrics: make(map[string][]float64), } for k, v := range f.HourlyMetrics { if k == "time" { // We unmarshal into an ApiTime array because of the custom formatting // of the timestamp in the API response target := []ApiTime{} err := json.Unmarshal(v, &target) if err != nil { return nil, err } for _, at := range target { fc.HourlyTimes = append(fc.HourlyTimes, at.Time) } continue } target := []float64{} err := json.Unmarshal(v, &target) if err != nil { return nil, err } fc.HourlyMetrics[k] = target } for k, v := range f.DailyMetrics { if k == "time" { // We unmarshal into an ApiTime array because of the custom formatting // of the timestamp in the API response target := []ApiDate{} err := json.Unmarshal(v, &target) if err != nil { return nil, err } for _, at := range target { fc.DailyTimes = append(fc.DailyTimes, at.Time) } continue } target := []float64{} err := json.Unmarshal(v, &target) if err != nil { return nil, err } fc.DailyMetrics[k] = target } return fc, nil }
parsing.go
0.700997
0.424949
parsing.go
starcoder
package main // The width and height of the individual boards and the game board as a whole. // This value must be odd, and values of 3 or 5 are recommended. const XY int = 5 // The coorindates of the central cell of the board. Since the board arrays are // zero-indexed, it is one less than expected. const CENTRE int = (XY - 1) / 2 type cell interface { Owner() *player } type board interface { cell SelectCell(x int, y int, p *player) *cell } type singlecell struct { owner *player } func (c *singlecell) Owner() *player { return c.owner } type miniboard struct { contents [XY][XY]cell owner *player } // Func Owner() calculates if there is a winner of the miniboard. The results // of this function are undefined for a board layout with more than one winner. func (brd *miniboard) Owner() *player { // First check to see for a cached winner. if brd.owner != nil { return brd.owner } var winner *player // Check for horizontal wins. for y := 0; y < XY; y++ { tempwinner := brd.contents[0][y].Owner() for x := 1; x < XY; x++ { if brd.contents[x][y].Owner() != tempwinner { tempwinner = nil } } if tempwinner != nil { winner = tempwinner } } // Check for vertical wins. for x := 0; x < XY; x++ { tempwinner := brd.contents[x][0].Owner() for y := 1; y < XY; y++ { if brd.contents[x][y].Owner() != tempwinner { tempwinner = nil } } if tempwinner != nil { winner = tempwinner } } // Check for diagonal wins. // There is no diagonal win without occupying the centre. if brd.contents[CENTRE][CENTRE].Owner() == nil { return nil } tempwinner := brd.contents[0][0].Owner() for x := 1; x < XY; x++ { if brd.contents[x][x].Owner() != tempwinner { tempwinner = nil } } if tempwinner != nil { winner = tempwinner } tempwinner = brd.contents[0][XY-1].Owner() for x := 1; x < XY; x++ { if brd.contents[x][(XY-1)-x].Owner() != tempwinner { tempwinner = nil } } if tempwinner != nil { winner = tempwinner } brd.owner = winner return winner } type gameboard struct { contents [XY][XY]miniboard owner *player } // Func Owner() calculates if there is a winner of the gameboard. The results // of this function are undefined for a board layout with more than one winner. func (brd *gameboard) Owner() *player { // First check to see for a cached winner. if brd.owner != nil { return brd.owner } var winner *player // Check for horizontal wins. for y := 0; y < XY; y++ { tempwinner := brd.contents[0][y].Owner() for x := 1; x < XY; x++ { if brd.contents[x][y].Owner() != tempwinner { tempwinner = nil } } if tempwinner != nil { winner = tempwinner } } // Check for vertical wins. for x := 0; x < XY; x++ { tempwinner := brd.contents[x][0].Owner() for y := 1; y < XY; y++ { if brd.contents[x][y].Owner() != tempwinner { tempwinner = nil } } if tempwinner != nil { winner = tempwinner } } // Check for diagonal wins. // There is no diagonal win without occupying the centre. if brd.contents[CENTRE][CENTRE].Owner() == nil { return nil } tempwinner := brd.contents[0][0].Owner() for x := 1; x < XY; x++ { if brd.contents[x][x].Owner() != tempwinner { tempwinner = nil } } if tempwinner != nil { winner = tempwinner } tempwinner = brd.contents[0][XY-1].Owner() for x := 1; x < XY; x++ { if brd.contents[x][(XY-1)-x].Owner() != tempwinner { tempwinner = nil } } if tempwinner != nil { winner = tempwinner } brd.owner = winner return winner }
board.go
0.676299
0.536738
board.go
starcoder
package tsplot import ( "gonum.org/v1/plot" "gonum.org/v1/plot/plotter" "image/color" ) // PlotOption defines the type used to configure the underlying *plot.Plot. // A function that returns PlotOption can be used to set options on the *plot.Plot. type PlotOption func(p *plot.Plot) // WithForeground sets the foreground colors of the *plot.Plot to the provided color. func WithForeground(color color.Color) PlotOption { return func(p *plot.Plot) { p.Title.TextStyle.Color = color p.X.Color = color p.X.Label.TextStyle.Color = color p.X.Tick.Color = color p.X.Tick.Label.Color = color p.Y.Tick.Label.Color = color p.Y.Color = color p.Y.Label.TextStyle.Color = color p.Y.Tick.Color = color p.Y.Tick.Label.Color = color } } // WithBackground sets the background color on the *plot.Plot. func WithBackground(color color.Color) PlotOption { return func(p *plot.Plot) { p.BackgroundColor = color } } // WithTitle configures the title text of the *plot.Plot. func WithTitle(title string) PlotOption { return func(p *plot.Plot) { p.Title.Text = title } } // WithGrid adds a grid to the *plot.Plot and sets the color. func WithGrid(color color.Color) PlotOption { return func(p *plot.Plot) { grid := plotter.NewGrid() grid.Horizontal.Color = color grid.Vertical.Color = color p.Add(grid) } } // WithLegend sets the text color of the legend. func WithLegend(color color.Color) PlotOption { return func(p *plot.Plot) { p.Legend.TextStyle.Color = color } } // WithXAxisName sets the name of the X Axis. func WithXAxisName(name string) PlotOption { return func(p *plot.Plot) { p.X.Label.Text = name } } // WithYAxisName sets the name of the Y Axis. func WithYAxisName(name string) PlotOption { return func(p *plot.Plot) { p.Y.Label.Text = name } } // WithXTimeTicks configures the format for the tick marks on the X Axis. func WithXTimeTicks(format string) PlotOption { return func(p *plot.Plot) { p.X.Tick.Marker = plot.TimeTicks{ Format: format, } } } // ApplyDefaultHighContrast applies the default high contrast color scheme to the *plot.Plot. func ApplyDefaultHighContrast(p *plot.Plot) { opts := []PlotOption{ WithBackground(DefaultColors_HighContrast.Background), WithForeground(DefaultColors_HighContrast.Foreground), WithLegend(DefaultColors_HighContrast.Foreground), } for _, opt := range opts { opt(p) } }
tsplot/options.go
0.851907
0.468851
options.go
starcoder
package grid import ( "math" aocmath "github.com/bewuethr/advent-of-code/go/math" ) // Vec2 represents a 2d vector with integer components. type Vec2 struct { x, y int } // Special 2d vectors var ( Origin = Vec2{0, 0} // Origin of the grid Ux = Vec2{1, 0} // Horizontal unit vector Uy = Vec2{0, 1} // Vertical unit vector ) // NewVec2 creates a new vector with components x and y. func NewVec2(x, y int) Vec2 { return Vec2{ x: x, y: y, } } // X returns the x component of v. func (v Vec2) X() int { return v.x } // Y returns the y component of v. func (v Vec2) Y() int { return v.y } // Norm returns the length of v. func (v Vec2) Norm() float64 { return math.Sqrt(math.Pow(float64(v.x), 2) + math.Pow(float64(v.y), 2)) } // Azimuth returns the polar angle of v, normalized to the range [0, 2π). func (v Vec2) Azimuth() float64 { return math.Mod(math.Atan2(float64(v.y), float64(v.x))+math.Pi*2, math.Pi*2) } // Add returns the sum of vectors v and w. func (v Vec2) Add(w Vec2) Vec2 { return NewVec2(v.x+w.x, v.y+w.y) } // Subtract returns the difference of vectors v and w. func (v Vec2) Subtract(w Vec2) Vec2 { return NewVec2(v.x-w.x, v.y-w.y) } // ScalarMult is the result of multiplying v by n. func (v Vec2) ScalarMult(n int) Vec2 { return NewVec2(v.x*n, v.y*n) } // ScalarDiv reuturns a Vec2 with components of v divided by n. func (v Vec2) ScalarDiv(n int) Vec2 { return NewVec2(v.x/n, v.y/n) } // ManhattanDistance is the Manhattan distance between v and w. func (v Vec2) ManhattanDistance(w Vec2) int { return aocmath.IntAbs(v.x-w.x) + aocmath.IntAbs(v.y-w.y) } // ManhattanDistanceOrigin is the Manhattan distance from v to the origin. func (v Vec2) ManhattanDistanceOrigin() int { return v.ManhattanDistance(Origin) } // RotCCW returns v rotated counterclockwise by 90 degrees (assuming the y axis // pointing down). func (v Vec2) RotCCW() Vec2 { return NewVec2(v.y, -v.x) } // RotCW returns v rotated clockwise by 90 degrees (assuming the y axis pointing // down). func (v Vec2) RotCW() Vec2 { return NewVec2(-v.y, v.x) }
go/grid/vec2.go
0.927009
0.634671
vec2.go
starcoder
package docs import ( "bytes" "encoding/json" "strings" "github.com/alecthomas/template" "github.com/swaggo/swag" ) var doc = `{ "schemes": {{ marshal .Schemes }}, "swagger": "2.0", "info": { "description": "{{.Description}}", "title": "{{.Title}}", "contact": {}, "version": "{{.Version}}" }, "host": "{{.Host}}", "basePath": "{{.BasePath}}", "paths": { "/regist/logic": { "get": { "description": "get logics list", "produces": [ "application/json" ], "tags": [ "logic" ], "summary": "List logics info", "responses": { "200": { "description": "return all logics info.", "schema": { "type": "array", "items": { "$ref": "#/definitions/model.Logic" } } } } }, "post": { "description": "Add logic info", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "logic" ], "summary": "Add logic info", "parameters": [ { "description": "logic_name, elems", "name": "logic", "in": "body", "required": true, "schema": { "$ref": "#/definitions/adapter.Logic" } } ], "responses": { "200": { "description": "include sensor info", "schema": { "$ref": "#/definitions/adapter.Logic" } } } }, "delete": { "description": "Delete logic", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "logic" ], "summary": "Delete logic", "parameters": [ { "type": "integer", "description": "logic's id", "name": "id", "in": "path", "required": true } ], "responses": { "200": { "description": "include sensor info", "schema": { "$ref": "#/definitions/model.Logic" } } } } }, "/regist/logic-service": { "get": { "description": "get LogicServices list", "produces": [ "application/json" ], "tags": [ "LogicService" ], "summary": "List LogicServices info", "responses": { "200": { "description": "return all logics info.", "schema": { "type": "array", "items": { "$ref": "#/definitions/model.LogicService" } } } } }, "delete": { "description": "Delete LogicService", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "logicService" ], "summary": "Delete LogicService", "parameters": [ { "type": "integer", "description": "logicSerivce's id", "name": "id", "in": "path", "required": true } ], "responses": { "200": { "description": "include topic info", "schema": { "$ref": "#/definitions/model.Logic" } } } } }, "/regist/node": { "get": { "description": "get nodes list", "produces": [ "application/json" ], "tags": [ "node" ], "summary": "List sensor node", "parameters": [ { "type": "integer", "description": "page num", "name": "page", "in": "query" }, { "type": "integer", "description": "page size(row)", "name": "size", "in": "query" }, { "type": "integer", "description": "sink filter", "name": "sink", "in": "query" }, { "type": "number", "description": "location(longitude) filter", "name": "left", "in": "query" }, { "type": "number", "description": "location(longitude) filter", "name": "right", "in": "query" }, { "type": "number", "description": "location(Latitude) filter", "name": "up", "in": "query" }, { "type": "number", "description": "location(Latitude) filter", "name": "down", "in": "query" } ], "responses": { "200": { "description": "default, return all nodes. if location query is exist, return location filter result(square).", "schema": { "type": "array", "items": { "$ref": "#/definitions/model.Node" } } }, "201": { "description": "if page query is exist, return pagenation result. pages only valid when page is 1.", "schema": { "$ref": "#/definitions/adapter.NodePage" } } } }, "post": { "description": "Add sensor node", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "node" ], "summary": "Add sensor node", "parameters": [ { "description": "name, lat, lng, sink_id", "name": "node", "in": "body", "required": true, "schema": { "$ref": "#/definitions/model.Node" } } ], "responses": { "200": { "description": "include sink, sink.topic, sensors, sensors.logics info", "schema": { "$ref": "#/definitions/model.Node" } } } }, "delete": { "description": "Delete sensor node", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "node" ], "summary": "Delete sensor node", "parameters": [ { "type": "integer", "description": "node's id", "name": "id", "in": "path", "required": true } ], "responses": { "200": { "description": "include sink, sink.topic info", "schema": { "$ref": "#/definitions/model.Node" } } } } }, "/regist/sensor": { "get": { "description": "get sensors list", "produces": [ "application/json" ], "tags": [ "sensor" ], "summary": "List sensor info", "parameters": [ { "type": "integer", "description": "page num", "name": "page", "in": "query" }, { "type": "integer", "description": "page size(row)", "name": "size", "in": "query" } ], "responses": { "200": { "description": "default, return all sensors.", "schema": { "type": "array", "items": { "$ref": "#/definitions/model.Sensor" } } }, "201": { "description": "if page query is exist, return pagenation result. pages only valid when page is 1.", "schema": { "$ref": "#/definitions/adapter.SensorPage" } } } }, "post": { "description": "Add sensor info", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "sensor" ], "summary": "Add sensor info", "parameters": [ { "description": "name, sensorValues(only value name)", "name": "sensor", "in": "body", "required": true, "schema": { "$ref": "#/definitions/model.Sensor" } } ], "responses": { "200": { "description": "include sensorValues info", "schema": { "$ref": "#/definitions/model.Node" } } } }, "delete": { "description": "Delete sensor", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "sensor" ], "summary": "Delete sensor", "parameters": [ { "type": "integer", "description": "sensor's id", "name": "id", "in": "path", "required": true } ], "responses": { "200": { "description": "include logics info", "schema": { "$ref": "#/definitions/model.Sensor" } } } } }, "/regist/sink": { "get": { "description": "get sinks list", "produces": [ "application/json" ], "tags": [ "sink" ], "summary": "List sink node(raspi info)", "parameters": [ { "type": "integer", "description": "page num", "name": "page", "in": "query" }, { "type": "integer", "description": "page size(row)", "name": "size", "in": "query" } ], "responses": { "200": { "description": "default, return all sinks.", "schema": { "type": "array", "items": { "$ref": "#/definitions/model.Sink" } } }, "201": { "description": "if page query is exist, return pagenation result. pages only valid when page is 1.", "schema": { "$ref": "#/definitions/adapter.SinkPage" } } } }, "post": { "description": "Add sink node", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "sink" ], "summary": "Add sink node(raspi info)", "parameters": [ { "description": "name, address(only ip address, don't include port)", "name": "sink", "in": "body", "required": true, "schema": { "$ref": "#/definitions/model.Sink" } } ], "responses": { "200": { "description": "include topic info", "schema": { "$ref": "#/definitions/model.Sink" } } } }, "delete": { "description": "Delete sink node", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "sink" ], "summary": "Delete sink node(raspi info)", "parameters": [ { "type": "integer", "description": "sink's id", "name": "id", "in": "path", "required": true } ], "responses": { "200": { "description": "include topic, nodes info", "schema": { "$ref": "#/definitions/model.Sink" } } } } }, "/regist/topic": { "get": { "description": "get topics list", "produces": [ "application/json" ], "tags": [ "topic" ], "summary": "List topics info", "responses": { "200": { "description": "return all topics info.", "schema": { "type": "array", "items": { "$ref": "#/definitions/model.Topic" } } } } }, "post": { "description": "Add topic info", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "topic" ], "summary": "Add topic info", "parameters": [ { "description": "name, partitions, replications", "name": "logic", "in": "body", "required": true, "schema": { "$ref": "#/definitions/model.Logic" } } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/model.Topic" } } } }, "delete": { "description": "Delete topic(kafka topic for logicservices)", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "topic" ], "summary": "Delete topic(kafka topic for logicservices)", "parameters": [ { "type": "integer", "description": "topic's id", "name": "id", "in": "path", "required": true } ], "responses": { "200": { "description": "include logicService info", "schema": { "$ref": "#/definitions/model.Topic" } } } } } }, "definitions": { "adapter.Element": { "type": "object", "properties": { "arg": { "type": "object", "additionalProperties": true }, "elem": { "type": "string" } } }, "adapter.Logic": { "type": "object", "properties": { "elems": { "type": "array", "items": { "$ref": "#/definitions/adapter.Element" } }, "id": { "type": "integer" }, "logic_name": { "type": "string" }, "sensor": { "$ref": "#/definitions/model.Sensor" }, "sensor_id": { "type": "integer" } } }, "adapter.NodePage": { "type": "object", "properties": { "nodes": { "type": "array", "items": { "$ref": "#/definitions/model.Node" } }, "pages": { "type": "integer" } } }, "adapter.SensorPage": { "type": "object", "properties": { "pages": { "type": "integer" }, "sensors": { "type": "array", "items": { "$ref": "#/definitions/model.Sensor" } } } }, "adapter.SinkPage": { "type": "object", "properties": { "pages": { "type": "integer" }, "sinks": { "type": "array", "items": { "$ref": "#/definitions/model.Sink" } } } }, "model.Logic": { "type": "object", "properties": { "elems": { "type": "string" }, "id": { "type": "integer" }, "name": { "type": "string" }, "sensor": { "$ref": "#/definitions/model.Sensor" }, "sensor_id": { "type": "integer" } } }, "model.LogicService": { "type": "object", "properties": { "addr": { "type": "string" }, "id": { "type": "integer" }, "topic": { "$ref": "#/definitions/model.Topic" }, "topic_id": { "type": "integer" } } }, "model.Node": { "type": "object", "properties": { "id": { "type": "integer" }, "lat": { "type": "number" }, "lng": { "type": "number" }, "name": { "type": "string" }, "sensors": { "type": "array", "items": { "$ref": "#/definitions/model.Sensor" } }, "sink": { "$ref": "#/definitions/model.Sink" }, "sink_id": { "type": "integer" } } }, "model.Sensor": { "type": "object", "properties": { "id": { "type": "integer" }, "logics": { "type": "array", "items": { "$ref": "#/definitions/model.Logic" } }, "name": { "type": "string" }, "nodes": { "type": "array", "items": { "$ref": "#/definitions/model.Node" } }, "sensor_values": { "type": "array", "items": { "$ref": "#/definitions/model.SensorValue" } } } }, "model.SensorValue": { "type": "object", "properties": { "index": { "type": "integer" }, "sensor_id": { "type": "integer" }, "value_name": { "type": "string" } } }, "model.Sink": { "type": "object", "properties": { "addr": { "type": "string" }, "id": { "type": "integer" }, "name": { "type": "string" }, "nodes": { "type": "array", "items": { "$ref": "#/definitions/model.Node" } }, "topic": { "$ref": "#/definitions/model.Topic" }, "topic_id": { "type": "integer" } } }, "model.Topic": { "type": "object", "properties": { "id": { "type": "integer" }, "logic_services": { "type": "array", "items": { "$ref": "#/definitions/model.LogicService" } }, "name": { "type": "string" }, "partitions": { "type": "integer" }, "replications": { "type": "integer" }, "sinks": { "type": "array", "items": { "$ref": "#/definitions/model.Sink" } } } } } }` type swaggerInfo struct { Version string Host string BasePath string Schemes []string Title string Description string } // SwaggerInfo holds exported Swagger Info so clients can modify it var SwaggerInfo = swaggerInfo{ Version: "", Host: "", BasePath: "", Schemes: []string{}, Title: "", Description: "", } type s struct{} func (s *s) ReadDoc() string { sInfo := SwaggerInfo sInfo.Description = strings.Replace(sInfo.Description, "\n", "\\n", -1) t, err := template.New("swagger_info").Funcs(template.FuncMap{ "marshal": func(v interface{}) string { a, _ := json.Marshal(v) return string(a) }, }).Parse(doc) if err != nil { return doc } var tpl bytes.Buffer if err := t.Execute(&tpl, sInfo); err != nil { return doc } return tpl.String() } func init() { swag.Register(swag.Name, &s{}) }
application/docs/docs.go
0.548915
0.412708
docs.go
starcoder
package color import ( "errors" "math" colorful "github.com/lucasb-eyer/go-colorful" ) var colorMap map[string]colorful.Color var clusterMap map[string]colorful.Color func init() { colorMap = make(map[string]colorful.Color, len(colors)) for name, color := range colors { colorMap[name], _ = colorful.Hex(color) } clusterMap = make(map[string]colorful.Color) for name, color := range clusters { clusterMap[name], _ = colorful.Hex(color) } } func Find(name string) (string, error) { if result, ok := clusters[name]; ok { return result, nil } return "", errors.New("color not found") } // Cluster resolves the closest "cluster" or bucket of colors // For example, "rose" would map to "red" or "sky blue" would map to "blue" // This is useful for generalizing about what basic color a particular hue // may be, especially for faceting. func Cluster(input colorful.Color) (string, float64) { closest := "" distance := 999999.0 for name, color := range clusterMap { d := input.DistanceCIE94(color) distance = math.Min(d, distance) if d != distance { closest = name } } return closest, distance } // Match the input against the closest known color func Match(input colorful.Color) (string, float64) { closest := "" distance := 999999.0 for name, color := range colorMap { d := input.DistanceLab(color) if d < distance { closest = name distance = d } } return closest, distance } // List of common color names that we can use to cluster together hues var clusters = map[string]string{ "beige": "#f5f5dc", "black": "#000000", "blue": "#0000ff", "brown": "#8b4513", "gold": "#ffd700", "gray": "#808080", "green": "#008000", "navy": "#000080", "off-white": "#f5f5f5", "orange": "#ffa500", "pink": "#ffc0cb", "purple": "#800080", "red": "#ff0000", "silver": "#c0c0c0", "white": "#ffffff", "yellow": "#ffff00", } // List of known color names to hex values. Feel free to add to this list. var colors = map[string]string{ "black": "#000000", "navy": "#000080", "darkblue": "#00008b", "mediumblue": "#0000cd", "blue": "#0000ff", "darkgreen": "#006400", "green": "#008000", "teal": "#008080", "darkcyan": "#008b8b", "deepskyblue": "#00bfff", "darkturquoise": "#00ced1", "mediumspringgreen": "#00fa9a", "lime": "#00ff00", "springgreen": "#00ff7f", "cyan": "#00ffff", "midnightblue": "#191970", "dodgerblue": "#1e90ff", "lightseagreen": "#20b2aa", "forestgreen": "#228b22", "seagreen": "#2e8b57", "darkslategray": "#2f4f4f", "limegreen": "#32cd32", "mediumseagreen": "#3cb371", "turquoise": "#40e0d0", "royalblue": "#4169e1", "steelblue": "#4682b4", "darkslateblue": "#483d8b", "mediumturquoise": "#48d1cc", "indigo": "#4b0082", "darkolivegreen": "#556b2f", "cadetblue": "#5f9ea0", "cornflowerblue": "#6495ed", "mediumaquamarine": "#66cdaa", "dimgray": "#696969", "slateblue": "#6a5acd", "olivedrab": "#6b8e23", "slategray": "#708090", "lightslategray": "#778899", "mediumslateblue": "#7b68ee", "lawngreen": "#7cfc00", "chartreuse": "#7fff00", "aquamarine": "#7fffd4", "maroon": "#800000", "purple": "#800080", "olive": "#808000", "gray": "#808080", "skyblue": "#87ceeb", "lightskyblue": "#87cefa", "blueviolet": "#8a2be2", "darkred": "#8b0000", "darkmagenta": "#8b008b", "saddlebrown": "#8b4513", "darkseagreen": "#8fbc8f", "lightgreen": "#90ee90", "mediumpurple": "#9370db", "darkviolet": "#9400d3", "palegreen": "#98fb98", "darkorchid": "#9932cc", "yellowgreen": "#9acd32", "sienna": "#a0522d", "brown": "#a52a2a", "darkgray": "#a9a9a9", "lightblue": "#add8e6", "greenyellow": "#adff2f", "paleturquoise": "#afeeee", "lightsteelblue": "#b0c4de", "powderblue": "#b0e0e6", "firebrick": "#b22222", "darkgoldenrod": "#b8860b", "mediumorchid": "#ba55d3", "rosybrown": "#bc8f8f", "darkkhaki": "#bdb76b", "silver": "#c0c0c0", "mediumvioletred": "#c71585", "peru": "#cd853f", "chocolate": "#d2691e", "tan": "#d2b48c", "lightgrey": "#d3d3d3", "thistle": "#d8bfd8", "orchid": "#da70d6", "goldenrod": "#daa520", "palevioletred": "#db7093", "crimson": "#dc143c", "gainsboro": "#dcdcdc", "plum": "#dda0dd", "burlywood": "#deb887", "lightcyan": "#e0ffff", "lavender": "#e6e6fa", "darksalmon": "#e9967a", "violet": "#ee82ee", "palegoldenrod": "#eee8aa", "lightcoral": "#f08080", "khaki": "#f0e68c", "aliceblue": "#f0f8ff", "honeydew": "#f0fff0", "azure": "#f0ffff", "sandybrown": "#f4a460", "wheat": "#f5deb3", "beige": "#f5f5dc", "whitesmoke": "#f5f5f5", "mintcream": "#f5fffa", "ghostwhite": "#f8f8ff", "salmon": "#fa8072", "antiquewhite": "#faebd7", "linen": "#faf0e6", "lightgoldenrodyellow": "#fafad2", "oldlace": "#fdf5e6", "red": "#ff0000", "magenta": "#ff00ff", "deeppink": "#ff1493", "orangered": "#ff4500", "tomato": "#ff6347", "hotpink": "#ff69b4", "coral": "#ff7f50", "darkorange": "#ff8c00", "lightsalmon": "#ffa07a", "orange": "#ffa500", "lightpink": "#ffb6c1", "pink": "#ffc0cb", "gold": "#ffd700", "peachpuff": "#ffdab9", "navajowhite": "#ffdead", "moccasin": "#ffe4b5", "bisque": "#ffe4c4", "mistyrose": "#ffe4e1", "blanchedalmond": "#ffebcd", "papayawhip": "#ffefd5", "lavenderblush": "#fff0f5", "seashell": "#fff5ee", "cornsilk": "#fff8dc", "lemonchiffon": "#fffacd", "floralwhite": "#fffaf0", "snow": "#fffafa", "yellow": "#ffff00", "lightyellow": "#ffffe0", "ivory": "#fffff0", "white": "#ffffff", "air force blue": "#5d8aa8", "alice blue": "#f0f8ff", "alizarin crimson": "#e32636", "almond": "#efdecd", "amaranth": "#e52b50", "amber": "#ffbf00", "american rose": "#ff033e", "amethyst": "#9966cc", "android green": "#a4c639", "anti flash white": "#f2f3f4", "antique brass": "#cd9575", "antique fuchsia": "#915c83", "antique white": "#faebd7", "ao": "#008000", "apple green": "#8db600", "apricot": "#fbceb1", "aqua": "#00ffff", "army green": "#4b5320", "arsenic": "#3b444b", "arylide yellow": "#e9d66b", "ash gray": "#b2beb5", "asparagus": "#87a96b", "atomic tangerine": "#ff9966", "auburn": "#a52a2a", "aureolin": "#fdee00", "aurometalsaurus": "#6e7f80", "awesome": "#ff2052", "azure mist": "#f0ffff", "baby blue": "#89cff0", "baby blue eyes": "#a1caf1", "baby pink": "#f4c2c2", "ball blue": "#21abcd", "banana mania": "#fae7b5", "banana yellow": "#ffe135", "battleship gray": "#848482", "bazaar": "#98777b", "beau blue": "#bcd4e6", "beaver": "#9f8170", "bistre": "#3d2b1f", "bittersweet": "#fe6f5e", "blanched almond": "#ffebcd", "bleu de france": "#318ce7", "blizzard blue": "#ace5ee", "blond": "#faf0be", "blue bell": "#a2a2d0", "blue gray": "#6699cc", "blue green": "#00dddd", "blue violet": "#8a2be2", "blush": "#de5d83", "bole": "#79443b", "bondi blue": "#0095b6", "boston university red": "#cc0000", "brandeis blue": "#0070ff", "brass": "#b5a642", "brick red": "#cb4154", "bright cerulean": "#1dacd6", "bright green": "#66ff00", "bright lavender": "#bf94e4", "bright maroon": "#c32148", "bright pink": "#ff007f", "bright turquoise": "#08e8de", "bright ube": "#d19fe8", "brilliant lavender": "#f4bbff", "brilliant rose": "#ff55a3", "brink pink": "#fb607f", "british racing green": "#004225", "bronze": "#cd7f32", "bubble gum": "#ffc1cc", "bubbles": "#e7feff", "buff": "#f0dc82", "bulgarian rose": "#480607", "burgundy": "#800020", "burnt orange": "#cc5500", "burnt sienna": "#e97451", "burnt umber": "#8a3324", "byzantine": "#bd33a4", "byzantium": "#702963", "cadet": "#536872", "cadet blue": "#5f9ea0", "cadet gray": "#91a3b0", "cadmium green": "#006b3c", "cadmium orange": "#ed872d", "cadmium red": "#e30022", "cadmium yellow": "#fff600", "cal poly pomona green": "#1e4d2b", "cambridge blue": "#a3c1ad", "camel": "#c19a6b", "camouflage green": "#78866b", "canary yellow": "#ffef00", "candy apple red": "#ff0800", "candy pink": "#e4717a", "capri": "#00bfff", "caput mortuum": "#592720", "cardinal": "#c41e3a", "caribbean green": "#00cc99", "carmine": "#960018", "carmine pink": "#eb4c42", "carmine red": "#ff0038", "carnation pink": "#ffa6c9", "carnelian": "#b31b1b", "carolina blue": "#99badd", "carrot orange": "#ed9121", "ceil": "#92a1cf", "celadon": "#ace1af", "celestial blue": "#4997d0", "cerise": "#de3163", "cerise pink": "#ec3b83", "cerulean": "#007ba7", "cerulean blue": "#2a52be", "cg blue": "#007aa5", "cg red": "#e03c31", "chamoisee": "#a0785a", "champagne": "#f7e7ce", "charcoal": "#36454f", "cherry blossom pink": "#ffb7c5", "chestnut": "#cd5c5c", "chrome yellow": "#ffa700", "cinereous": "#98817b", "cinnabar": "#e34234", "cinnamon": "#d2691e", "citrine": "#e4d00a", "classic rose": "#fbcce7", "cobalt": "#0047ab", "coffee": "#c86428", "columbia blue": "#9bddff", "cool black": "#002e63", "cool gray": "#8c92ac", "copper": "#b87333", "copper rose": "#996666", "coquelicot": "#ff3800", "coral pink": "#f88379", "coral red": "#ff4040", "cordovan": "#893f45", "corn": "#fbec5d", "cornflower blue": "#6495ed", "cosmic latte": "#fff8e7", "cotton candy": "#ffbcd9", "cream": "#fffdd0", "crimson glory": "#be0032", "daffodil": "#ffff31", "dandelion": "#f0e130", "dark blue": "#00008b", "dark brown": "#654321", "dark byzantium": "#5d3954", "dark candy apple red": "#a40000", "dark cerulean": "#08457e", "dark champagne": "#c2b280", "dark chestnut": "#986960", "dark coral": "#cd5b45", "dark cyan": "#008b8b", "dark electric blue": "#536878", "dark goldenrod": "#b8860b", "dark gray": "#a9a9a9", "dark green": "#013220", "dark jungle green": "#1a2421", "dark khaki": "#bdb76b", "dark lava": "#483c32", "dark lavender": "#734f96", "dark magenta": "#8b008b", "dark midnight blue": "#003366", "dark olive green": "#556b2f", "dark orange": "#ff8c00", "dark orchid": "#9932cc", "dark pastel blue": "#779ecb", "dark pastel green": "#03c03c", "dark pastel purple": "#966fd6", "dark pastel red": "#c23b22", "dark pink": "#e75480", "dark powder blue": "#003399", "dark raspberry": "#872657", "dark red": "#8b0000", "dark salmon": "#e9967a", "dark scarlet": "#560319", "dark sea green": "#8fbc8f", "dark sienna": "#3c1414", "dark slate blue": "#483d8b", "dark slate gray": "#2f4f4f", "dark spring green": "#177245", "dark tan": "#918151", "dark tangerine": "#ffa812", "dark terra cotta": "#cc4e5c", "dark turquoise": "#00ced1", "dark violet": "#9400d3", "dartmouth green": "#00693e", "davy's gray": "#555555", "debian red": "#d70a53", "deep carmine": "#a9203e", "deep carmine pink": "#ef3038", "deep carrot orange": "#e9692c", "deep cerise": "#da3287", "deep champagne": "#fad6a5", "deep chestnut": "#b94e48", "deep fuchsia": "#c154c1", "deep jungle green": "#004b49", "deep lilac": "#9955bb", "deep magenta": "#cc00cc", "deep peach": "#ffcba4", "deep pink": "#ff1493", "deep saffron": "#ff9933", "denim": "#1560bd", "desert sand": "#edc9af", "dim gray": "#696969", "dodger blue": "#1e90ff", "dogwood rose": "#d71868", "dollar bill": "#85bb65", "drab": "#967117", "duke blue": "#00009c", "earth yellow": "#e1a95f", "eggplant": "#614051", "eggshell": "#f0ead6", "egyptian blue": "#1034a6", "electric blue": "#7df9ff", "electric crimson": "#ff003f", "electric green": "#00fe00", "electric indigo": "#6f00ff", "electric lime": "#ccff00", "electric purple": "#bf00ff", "electric ultramarine": "#3f00ff", "electric violet": "#8f00ff", "electric yellow": "#fffe00", "emerald": "#50c878", "eton blue": "#96c8a2", "falu red": "#801818", "fandango": "#b53389", "fashion fuchsia": "#f400a1", "fawn": "#e5aa70", "feldgrau": "#4d5d53", "fern green": "#4f7942", "ferrari red": "#ff2800", "field drab": "#6c541e", "fire engine red": "#ce2029", "flame": "#e25822", "flamingo pink": "#fc8eac", "flavescent": "#f7e98e", "flax": "#eedc82", "floral white": "#fffaf0", "folly": "#ff004f", "forest green": "#014421", "french beige": "#a67b5b", "french blue": "#0072bb", "french lilac": "#86608e", "french rose": "#f64a8a", "fuchsia": "#ff00ff", "fuchsia pink": "#ff77ff", "fulvous": "#e48400", "fuzzy wuzzy": "#cc6666", "gamboge": "#e49b0f", "ghost white": "#f8f8ff", "ginger": "#b06500", "glaucous": "#6082b6", "golden brown": "#996515", "golden poppy": "#fcc200", "golden yellow": "#ffdf00", "granny smith apple": "#a8e4a0", "gray asparagus": "#465945", "green yellow": "#adff2f", "grullo": "#a99a86", "guppie green": "#00ff7f", "halaya ube": "#663854", "han blue": "#446ccf", "han purple": "#5218fa", "harlequin": "#3fff00", "harvard crimson": "#c90016", "harvest gold": "#da9100", "heliotrope": "#df73ff", "hooker's green": "#007000", "hot magenta": "#ff1dce", "hot pink": "#ff69b4", "hunter green": "#355e3b", "iceberg": "#71a6d2", "icterine": "#fcf75e", "inchworm": "#b2ec5d", "india green": "#138808", "indian yellow": "#e3a857", "international klein blue": "#002fa7", "international orange": "#ff4f00", "iris": "#5a4fcf", "isabelline": "#f4f0ec", "islamic green": "#009000", "jade": "#00a86b", "jasmine": "#f8de7e", "jasper": "#d73b3e", "jazzberry jam": "#a50b5e", "jonquil": "#fada5e", "june bud": "#bdda57", "jungle green": "#29ab87", "kelly green": "#4cbb17", "ku crimson": "#e8000d", "languid lavender": "#d6cadd", "lapis lazuli": "#26619c", "la salle green": "#087830", "laser lemon": "#fefe22", "lava": "#cf1020", "lavender blue": "#ccccff", "lavender blush": "#fff0f5", "lavender gray": "#c4c3d0", "lavender indigo": "#9457eb", "lavender magenta": "#ee82ee", "lavender mist": "#e6e6fa", "lavender pink": "#fbaed2", "lavender purple": "#967bb6", "lavender rose": "#fba0e3", "lawn green": "#7cfc00", "lemon": "#fff700", "lemon chiffon": "#fffacd", "light apricot": "#fdd5b1", "light blue": "#add8e6", "light brown": "#b5651d", "light carmine pink": "#e66771", "light coral": "#f08080", "light cornflower blue": "#93ccea", "light crimson": "#f56991", "light cyan": "#e0ffff", "light fuchsia pink": "#f984ef", "light goldenrod yellow": "#fafad2", "light gray": "#d3d3d3", "light green": "#90ee90", "light khaki": "#f0e68c", "light mauve": "#dcd0ff", "light pastel purple": "#b19cd9", "light pink": "#ffb6c1", "light salmon": "#ffa07a", "light salmon pink": "#ff9999", "light sea green": "#20b2aa", "light sky blue": "#87cefa", "light slate gray": "#778899", "light taupe": "#b38b6d", "light thulian pink": "#e68fac", "light yellow": "#ffffed", "lilac": "#c8a2c8", "lime green": "#32cd32", "lincoln green": "#195905", "liver": "#534b4f", "lust": "#e62020", "magic mint": "#aaf0d1", "magnolia": "#f8f4ff", "mahogany": "#c04000", "majorelle blue": "#6050dc", "malachite": "#0bda51", "manatee": "#979aaa", "mango tango": "#ff8243", "mauve": "#e0b0ff", "mauvelous": "#ef98aa", "mauve taupe": "#915f6d", "maya blue": "#73c2fb", "meat brown": "#e5b73b", "medium aquamarine": "#66ddaa", "medium blue": "#0000cd", "medium candy apple red": "#e2062c", "medium carmine": "#af4035", "medium champagne": "#f3e5ab", "medium electric blue": "#035096", "medium jungle green": "#1c352d", "medium lavender magenta": "#dda0dd", "medium orchid": "#ba55d3", "medium persian blue": "#0067a5", "medium purple": "#9370db", "medium red violet": "#bb3385", "medium sea green": "#3cb371", "medium slate blue": "#7b68ee", "medium spring bud": "#c9dc87", "medium spring green": "#00fa9a", "medium taupe": "#674c47", "medium teal blue": "#0054b4", "medium turquoise": "#48d1cc", "medium violet red": "#c71585", "melon": "#fdbcb4", "midnight blue": "#191970", "midnight green": "#004953", "mikado yellow": "#ffc40c", "mint": "#3eb489", "mint cream": "#f5fffa", "mint green": "#98ff98", "misty rose": "#ffe4e1", "moonstone blue": "#73a9c2", "mordant red 19": "#ae0c00", "moss green": "#addfad", "mountain meadow": "#30ba8f", "mountbatten pink": "#997a8d", "msu green": "#18453b", "mulberry": "#c54b8c", "mustard": "#ffdb58", "myrtle": "#21421e", "nadeshiko pink": "#f6adc6", "napier green": "#2a8000", "navajo white": "#ffdead", "neon carrot": "#ffa343", "neon fuchsia": "#fe59c2", "neon green": "#39ff14", "non photo blue": "#a4dded", "ocean boat blue": "#0077be", "ochre": "#cc7722", "old gold": "#cfb53b", "old lace": "#fdf5e6", "old lavender": "#796878", "old mauve": "#673147", "old rose": "#c08081", "olive drab": "#6b8e23", "olive drab 7": "#3c341f", "olivine": "#9ab973", "onyx": "#0f0f0f", "opera mauve": "#b784a7", "orange peel": "#ff9f00", "orange red": "#ff4500", "ou crimson red": "#990000", "outer space": "#414a4c", "outrageous orange": "#ff6e4a", "oxford blue": "#002147", "pakistan green": "#006600", "palatinate blue": "#273be2", "palatinate purple": "#682860", "pale blue": "#afeeee", "pale brown": "#987654", "pale cerulean": "#9bc4e2", "pale chestnut": "#ddadaf", "pale copper": "#da8a67", "pale cornflower blue": "#abcdef", "pale gold": "#e6be8a", "pale goldenrod": "#eee8aa", "pale green": "#98fb98", "pale magenta": "#f984e5", "pale pink": "#fadadd", "pale red violet": "#db7093", "pale robin egg blue": "#96ded1", "pale silver": "#c9c0bb", "pale spring bud": "#ecebbd", "pale taupe": "#bc987e", "pansy purple": "#78184a", "papaya whip": "#ffefd5", "pastel blue": "#aec6cf", "pastel brown": "#836953", "pastel gray": "#cfcfc4", "pastel green": "#77dd77", "pastel magenta": "#f49ac2", "pastel orange": "#ffb347", "pastel pink": "#ffd1dc", "pastel purple": "#b39eb5", "pastel red": "#ff6961", "pastel violet": "#cb99c9", "pastel yellow": "#fdfd96", "patriarch": "#800080", "payne's gray": "#40404f", "peach": "#ffe5b4", "peach orange": "#ffcc99", "peach puff": "#ffdab9", "peach yellow": "#fadfad", "pear": "#d1e231", "pearl aqua": "#88d8c0", "peridot": "#e6e200", "persian blue": "#1c39bb", "persian green": "#00a693", "persian indigo": "#32127a", "persian orange": "#d99058", "persian pink": "#f77fbe", "persian plum": "#701c1c", "persian red": "#cc3333", "persian rose": "#fe28a2", "persimmon": "#ec5800", "phlox": "#df00ff", "phthalo blue": "#000f89", "phthalo green": "#123524", "piggy pink": "#fddde6", "pine green": "#01796f", "pink pearl": "#e7accf", "pink sherbet": "#f78fa7", "pistachio": "#93c572", "platinum": "#e5e4e2", "portland orange": "#ff5a36", "powder blue": "#b0e0e6", "princeton orange": "#ff8f00", "prussian blue": "#003153", "puce": "#cc8899", "pumpkin": "#ff7518", "purple heart": "#69359c", "purple mountain majesty": "#9678b6", "purple pizzazz": "#fe4eda", "purple taupe": "#50404d", "quartz": "#51484f", "radical red": "#ff355e", "raspberry": "#e30b5d", "raspberry pink": "#e25098", "raspberry rose": "#b3446c", "raw umber": "#826644", "razzle dazzle rose": "#ff33cc", "razzmatazz": "#e3256b", "redwood": "#ab4e52", "regalia": "#522d80", "rich black": "#004040", "rich brilliant lavender": "#f1a7fe", "rich carmine": "#d70040", "rich electric blue": "#0892d0", "rich lavender": "#a76bcf", "rich lilac": "#b666d2", "rich maroon": "#b03060", "rifle green": "#414833", "robin egg blue": "#00cccc", "rose bonbon": "#f9429e", "rose ebony": "#674846", "rose gold": "#b76e79", "rose pink": "#ff66cc", "rose quartz": "#aa98a9", "rose taupe": "#905d5d", "rosewood": "#65000b", "rosso corsa": "#d40000", "rosy brown": "#bc8f8f", "royal azure": "#0038a8", "royal blue": "#002366", "royal fuchsia": "#ca2c92", "royal purple": "#7851a9", "ruby": "#e0115f", "ruddy": "#ff0028", "ruddy brown": "#bb6528", "ruddy pink": "#e18e96", "rufous": "#a81c07", "russet": "#80461b", "rust": "#b7410e", "sacramento state green": "#00563f", "saddle brown": "#8b4513", "safety orange": "#ff6700", "saffron": "#f4c430", "salmon pink": "#ff91a4", "sandstorm": "#ecd540", "sandy brown": "#f4a460", "sangria": "#92000a", "sap green": "#507d2a", "sapphire": "#082567", "satin sheen gold": "#cba135", "scarlet": "#ff2400", "school bus yellow": "#ffd800", "screamin' green": "#76ff7a", "sea green": "#2e8b57", "seal brown": "#321414", "selective yellow": "#ffba00", "sepia": "#704214", "shadow": "#8a795d", "shamrock green": "#009e60", "shocking pink": "#fc0fc0", "sinopia": "#cb410b", "skobeloff": "#007474", "sky blue": "#87ceeb", "sky magenta": "#cf71af", "slate blue": "#6a5acd", "slate gray": "#708090", "smokey topaz": "#933d41", "smoky black": "#100c08", "spiro disco ball": "#0fc0fc", "splashed white": "#fefdff", "spring bud": "#a7fc00", "steel blue": "#4682b4", "st. patrick's blue": "#23297a", "straw": "#e4d96f", "sunglow": "#ffcc33", "tangelo": "#f94d00", "tangerine": "#f28500", "tangerine yellow": "#ffcc00", "taupe gray": "#8b8589", "tea green": "#d0f0c0", "teal blue": "#367588", "teal green": "#006d5b", "tenné": "#cd5700", "terra cotta": "#e2725b", "thulian pink": "#de6fa1", "tickle me pink": "#fc89ac", "tiffany blue": "#0abab5", "tiger's eye": "#e08d3c", "timberwolf": "#dbd7d2", "titanium yellow": "#eee600", "toolbox": "#746cc0", "topaz": "#ffc87c", "tractor red": "#fd0e35", "tropical rain forest": "#00755e", "true blue": "#0073cf", "tufts blue": "#417dc1", "tumbleweed": "#deaa88", "turkish rose": "#b57281", "turquoise blue": "#00ffef", "turquoise green": "#a0d6b4", "tuscan red": "#66424d", "twilight lavender": "#8a496b", "tyrian purple": "#66023c", "ua blue": "#0033aa", "ua red": "#d9004c", "ube": "#8878c3", "ucla blue": "#536895", "ucla gold": "#ffb300", "ufo green": "#3cd070", "ultramarine": "#120a8f", "ultramarine blue": "#4166f5", "ultra pink": "#ff6fff", "umber": "#635147", "united nations blue": "#5b92e5", "university of california gold": "#b78727", "unmellow yellow": "#ffff66", "up maroon": "#7b1113", "upsdell red": "#ae2029", "urobilin": "#e1ad21", "utah crimson": "#d3003f", "vegas gold": "#c5b358", "venetian red": "#c80815", "verdigris": "#43b3ae", "veronica": "#a020f0", "viridian": "#40826d", "vivid auburn": "#922724", "vivid burgundy": "#9f1d35", "vivid cerise": "#da1d81", "vivid tangerine": "#ffa089", "vivid violet": "#9f00ff", "warm black": "#004242", "wenge": "#645452", "white smoke": "#f5f5f5", "wild blue yonder": "#a2add0", "wild strawberry": "#ff43a4", "wild watermelon": "#fc6c85", "wine": "#722f37", "wisteria": "#c9a0dc", "xanadu": "#738678", "yale blue": "#0f4d92", "yellow green": "#9acd32", "yellow orange": "#ffef02", "zaffre": "#0014a8", "zinnwaldite brown": "#2c1608", }
color/color.go
0.597608
0.431105
color.go
starcoder
package reflectx import ( "reflect" ) // IsSlice returns true if the given instance is a slice. func IsSlice(instance interface{}) bool { value, ok := instance.(reflect.Value) if !ok { value = reflect.ValueOf(instance) } return GetIndirectType(value.Type()).Kind() == reflect.Slice } // GetSliceType returns the type of a slice. func GetSliceType(instance interface{}) reflect.Type { return GetIndirectType(instance).Elem() } // GetIndirectSliceType returns the indirect type of a slice. func GetIndirectSliceType(instance interface{}) reflect.Type { t := GetSliceType(instance) for t.Kind() == reflect.Ptr { t = t.Elem() } return t } // NewSliceValue creates a new value for slice type. func NewSliceValue(instance interface{}) interface{} { t := GetSliceType(instance) if t.Kind() == reflect.Ptr { t = t.Elem() } return reflect.New(t).Interface() } // NewReflectSlice creates a new slice for type and returns it's pointer. func NewReflectSlice(instance interface{}) reflect.Value { t, ok := instance.(reflect.Type) if !ok { v, ok := instance.(reflect.Value) if ok { t = v.Type() } else { t = reflect.TypeOf(instance) } } return reflect.New(reflect.SliceOf(t)) } // AppendReflectSlice will append given element to reflect slice. func AppendReflectSlice(list reflect.Value, value interface{}) { target := list if list.Kind() == reflect.Ptr { target = list.Elem() } elem := target.Type().Elem() val, ok := value.(reflect.Value) if !ok { val = reflect.ValueOf(value) } for elem.Kind() != reflect.Ptr && val.Kind() == reflect.Ptr { val = val.Elem() } if elem.Kind() == reflect.Ptr && val.Kind() == reflect.Struct { val = MakeReflectPointer(val) } target.Set(reflect.Append(target, val)) } // SetReflectSlice will attach given reflect slice to the destination value. func SetReflectSlice(dest interface{}, list reflect.Value) { val, ok := dest.(reflect.Value) if !ok { val = reflect.ValueOf(dest) } for val.Kind() == reflect.Ptr { val = val.Elem() } for list.Kind() == reflect.Ptr { list = list.Elem() } val.Set(list) }
reflectx/slice.go
0.796886
0.459015
slice.go
starcoder
package pe import ( "bytes" "encoding/binary" ) const ( // DansSignature ('DanS' as dword) is where the rich header struct starts. DansSignature = 0x536E6144 // RichSignature ('0x68636952' as dword) is where the rich header struct ends. RichSignature = "Rich" // AnoDansSigNotFound is reported when rich header signature was found, but AnoDansSigNotFound = "Rich Header found, but could not locate DanS " + "signature" // AnoPaddingDwordNotZero is repoted when rich header signature leading // padding DWORDs are not equal to 0. AnoPaddingDwordNotZero = "Rich header found: 3 leading padding DWORDs " + "not found after DanS signature" ) // CompID represents the `@comp.id` structure. type CompID struct { // The minor version information for the compiler used when building the product. MinorCV uint16 // Provides information about the identity or type of the objects used to // build the PE32. ProdID uint16 // Indicates how often the object identified by the former two fields is // referenced by this PE32 file. Count uint32 // The raw @comp.id structure (unmasked). Unmasked uint32 } // RichHeader is a structure that is written right after the MZ DOS header. // It consists of pairs of 4-byte integers. And it is also // encrypted using a simple XOR operation using the checksum as the key. // The data between the magic values encodes the ‘bill of materials’ that were // collected by the linker to produce the binary. type RichHeader struct { XorKey uint32 CompIDs []CompID DansOffset int Raw []byte } // ParseRichHeader parses the rich header struct. func (pe *File) ParseRichHeader() error { rh := RichHeader{} ntHeaderOffset := pe.DosHeader.AddressOfNewEXEHeader richSigOffset := bytes.Index(pe.data[:ntHeaderOffset], []byte(RichSignature)) // For example, .NET executable files do not use the MSVC linker and these // executables do not contain a detectable Rich Header. if richSigOffset < 0 { return nil } // The DWORD following the "Rich" sequence is the XOR key stored by and // calculated by the linker. It is actually a checksum of the DOS header with // the e_lfanew zeroed out, and additionally includes the values of the // unencrypted "Rich" array. Using a checksum with encryption will not only // obfuscate the values, but it also serves as a rudimentary digital // signature. If the checksum is calculated from scratch once the values // have been decrypted, but doesn't match the stored key, it can be assumed // the structure had been tampered with. For those that go the extra step to // recalculate the checksum/key, this simple protection mechanism can be bypassed. rh.XorKey = binary.LittleEndian.Uint32(pe.data[richSigOffset+4:]) // To decrypt the array, start with the DWORD just prior to the `Rich` sequence // and XOR it with the key. Continue the loop backwards, 4 bytes at a time, // until the sequence `DanS` is decrypted. var decRichHeader []uint32 dansSigOffset := -1 estimatedBeginDans := richSigOffset - 4 - binary.Size(ImageDosHeader{}) for it := 0; it < estimatedBeginDans; it += 4 { buff := binary.LittleEndian.Uint32(pe.data[richSigOffset-4-it:]) res := buff ^ rh.XorKey if res == DansSignature { dansSigOffset = richSigOffset - it - 4 break } decRichHeader = append(decRichHeader, res) } // Probe we successfuly found the `DanS` magic. if dansSigOffset == -1 { pe.Anomalies = append(pe.Anomalies, AnoDansSigNotFound) return nil } // Anomaly check: dansSigOffset is usually found in offset 0x80. if dansSigOffset != 0x80 { pe.Anomalies = append(pe.Anomalies, AnoDanSMagicOffset) } rh.DansOffset = dansSigOffset rh.Raw = pe.data[dansSigOffset : richSigOffset+8] // Reverse the decrypted rich header for i, j := 0, len(decRichHeader)-1; i < j; i, j = i+1, j-1 { decRichHeader[i], decRichHeader[j] = decRichHeader[j], decRichHeader[i] } // After the `DanS` signature, there are some zero-padded In practice, // Microsoft seems to have wanted the entries to begin on a 16-byte // (paragraph) boundary, so the 3 leading padding DWORDs can be safely // skipped as not belonging to the data. if decRichHeader[0] != 0 || decRichHeader[1] != 0 || decRichHeader[2] != 0 { pe.Anomalies = append(pe.Anomalies, AnoPaddingDwordNotZero) } // The array stores entries that are 8-bytes each, broken into 3 members. // Each entry represents either a tool that was employed as part of building // the executable or a statistic. // The @compid struct should be multiple of 8 (bytes), some malformed pe // files have incorrect number of entries. var lenCompIDs int if (len(decRichHeader)-3)%2 != 0 { lenCompIDs = len(decRichHeader) - 1 } else { lenCompIDs = len(decRichHeader) } for i := 3; i < lenCompIDs; i += 2 { cid := CompID{} compid := make([]byte, binary.Size(cid)) binary.LittleEndian.PutUint32(compid, decRichHeader[i]) binary.LittleEndian.PutUint32(compid[4:], decRichHeader[i+1]) buf := bytes.NewReader(compid) err := binary.Read(buf, binary.LittleEndian, &cid) if err != nil { return err } cid.Unmasked = binary.LittleEndian.Uint32(compid) rh.CompIDs = append(rh.CompIDs, cid) } pe.RichHeader = &rh checksum := pe.RichHeaderChecksum() if checksum != rh.XorKey { pe.Anomalies = append(pe.Anomalies, "Invalid rich header checksum") } return nil } // RichHeaderChecksum calculate the Rich Header checksum. func (pe *File) RichHeaderChecksum() uint32 { checksum := uint32(pe.RichHeader.DansOffset) // First, calculate the sum of the DOS header bytes each rotated left the // number of times their position relative to the start of the DOS header e.g. // second byte is rotated left 2x using rol operation. for i := 0; i < pe.RichHeader.DansOffset; i++ { // skip over dos e_lfanew field at offset 0x3C if i >= 0x3C && i < 0x40 { continue } b := uint32(pe.data[i]) checksum += ((b << (i % 32)) | (b>>(32-(i%32)))&0xff) checksum &= 0xFFFFFFFF } // Next, take summation of each Rich header entry by combining its ProductId // and BuildNumber into a single 32 bit number and rotating by its count. for _, compid := range pe.RichHeader.CompIDs { checksum += (compid.Unmasked<<(compid.Count%32) | compid.Unmasked>>(32-(compid.Count%32))) checksum &= 0xFFFFFFFF } return checksum } // ProdIDtoStr mapps product ids to MS internal names. // list from: https://github.com/kirschju/richheader func ProdIDtoStr(prodID uint16) string { switch prodID { case 0x0000: return "Unknown" case 0x0001: return "Import0" case 0x0002: return "Linker510" case 0x0003: return "Cvtomf510" case 0x0004: return "Linker600" case 0x0005: return "Cvtomf600" case 0x0006: return "Cvtres500" case 0x0007: return "Utc11_Basic" case 0x0008: return "Utc11_C" case 0x0009: return "Utc12_Basic" case 0x000a: return "Utc12_C" case 0x000b: return "Utc12_CPP" case 0x000c: return "AliasObj60" case 0x000d: return "VisualBasic60" case 0x000e: return "Masm613" case 0x000f: return "Masm710" case 0x0010: return "Linker511" case 0x0011: return "Cvtomf511" case 0x0012: return "Masm614" case 0x0013: return "Linker512" case 0x0014: return "Cvtomf512" case 0x0015: return "Utc12_C_Std" case 0x0016: return "Utc12_CPP_Std" case 0x0017: return "Utc12_C_Book" case 0x0018: return "Utc12_CPP_Book" case 0x0019: return "Implib700" case 0x001a: return "Cvtomf700" case 0x001b: return "Utc13_Basic" case 0x001c: return "Utc13_C" case 0x001d: return "Utc13_CPP" case 0x001e: return "Linker610" case 0x001f: return "Cvtomf610" case 0x0020: return "Linker601" case 0x0021: return "Cvtomf601" case 0x0022: return "Utc12_1_Basic" case 0x0023: return "Utc12_1_C" case 0x0024: return "Utc12_1_CPP" case 0x0025: return "Linker620" case 0x0026: return "Cvtomf620" case 0x0027: return "AliasObj70" case 0x0028: return "Linker621" case 0x0029: return "Cvtomf621" case 0x002a: return "Masm615" case 0x002b: return "Utc13_LTCG_C" case 0x002c: return "Utc13_LTCG_CPP" case 0x002d: return "Masm620" case 0x002e: return "ILAsm100" case 0x002f: return "Utc12_2_Basic" case 0x0030: return "Utc12_2_C" case 0x0031: return "Utc12_2_CPP" case 0x0032: return "Utc12_2_C_Std" case 0x0033: return "Utc12_2_CPP_Std" case 0x0034: return "Utc12_2_C_Book" case 0x0035: return "Utc12_2_CPP_Book" case 0x0036: return "Implib622" case 0x0037: return "Cvtomf622" case 0x0038: return "Cvtres501" case 0x0039: return "Utc13_C_Std" case 0x003a: return "Utc13_CPP_Std" case 0x003b: return "Cvtpgd1300" case 0x003c: return "Linker622" case 0x003d: return "Linker700" case 0x003e: return "Export622" case 0x003f: return "Export700" case 0x0040: return "Masm700" case 0x0041: return "Utc13_POGO_I_C" case 0x0042: return "Utc13_POGO_I_CPP" case 0x0043: return "Utc13_POGO_O_C" case 0x0044: return "Utc13_POGO_O_CPP" case 0x0045: return "Cvtres700" case 0x0046: return "Cvtres710p" case 0x0047: return "Linker710p" case 0x0048: return "Cvtomf710p" case 0x0049: return "Export710p" case 0x004a: return "Implib710p" case 0x004b: return "Masm710p" case 0x004c: return "Utc1310p_C" case 0x004d: return "Utc1310p_CPP" case 0x004e: return "Utc1310p_C_Std" case 0x004f: return "Utc1310p_CPP_Std" case 0x0050: return "Utc1310p_LTCG_C" case 0x0051: return "Utc1310p_LTCG_CPP" case 0x0052: return "Utc1310p_POGO_I_C" case 0x0053: return "Utc1310p_POGO_I_CPP" case 0x0054: return "Utc1310p_POGO_O_C" case 0x0055: return "Utc1310p_POGO_O_CPP" case 0x0056: return "Linker624" case 0x0057: return "Cvtomf624" case 0x0058: return "Export624" case 0x0059: return "Implib624" case 0x005a: return "Linker710" case 0x005b: return "Cvtomf710" case 0x005c: return "Export710" case 0x005d: return "Implib710" case 0x005e: return "Cvtres710" case 0x005f: return "Utc1310_C" case 0x0060: return "Utc1310_CPP" case 0x0061: return "Utc1310_C_Std" case 0x0062: return "Utc1310_CPP_Std" case 0x0063: return "Utc1310_LTCG_C" case 0x0064: return "Utc1310_LTCG_CPP" case 0x0065: return "Utc1310_POGO_I_C" case 0x0066: return "Utc1310_POGO_I_CPP" case 0x0067: return "Utc1310_POGO_O_C" case 0x0068: return "Utc1310_POGO_O_CPP" case 0x0069: return "AliasObj710" case 0x006a: return "AliasObj710p" case 0x006b: return "Cvtpgd1310" case 0x006c: return "Cvtpgd1310p" case 0x006d: return "Utc1400_C" case 0x006e: return "Utc1400_CPP" case 0x006f: return "Utc1400_C_Std" case 0x0070: return "Utc1400_CPP_Std" case 0x0071: return "Utc1400_LTCG_C" case 0x0072: return "Utc1400_LTCG_CPP" case 0x0073: return "Utc1400_POGO_I_C" case 0x0074: return "Utc1400_POGO_I_CPP" case 0x0075: return "Utc1400_POGO_O_C" case 0x0076: return "Utc1400_POGO_O_CPP" case 0x0077: return "Cvtpgd1400" case 0x0078: return "Linker800" case 0x0079: return "Cvtomf800" case 0x007a: return "Export800" case 0x007b: return "Implib800" case 0x007c: return "Cvtres800" case 0x007d: return "Masm800" case 0x007e: return "AliasObj800" case 0x007f: return "PhoenixPrerelease" case 0x0080: return "Utc1400_CVTCIL_C" case 0x0081: return "Utc1400_CVTCIL_CPP" case 0x0082: return "Utc1400_LTCG_MSIL" case 0x0083: return "Utc1500_C" case 0x0084: return "Utc1500_CPP" case 0x0085: return "Utc1500_C_Std" case 0x0086: return "Utc1500_CPP_Std" case 0x0087: return "Utc1500_CVTCIL_C" case 0x0088: return "Utc1500_CVTCIL_CPP" case 0x0089: return "Utc1500_LTCG_C" case 0x008a: return "Utc1500_LTCG_CPP" case 0x008b: return "Utc1500_LTCG_MSIL" case 0x008c: return "Utc1500_POGO_I_C" case 0x008d: return "Utc1500_POGO_I_CPP" case 0x008e: return "Utc1500_POGO_O_C" case 0x008f: return "Utc1500_POGO_O_CPP" case 0x0090: return "Cvtpgd1500" case 0x0091: return "Linker900" case 0x0092: return "Export900" case 0x0093: return "Implib900" case 0x0094: return "Cvtres900" case 0x0095: return "Masm900" case 0x0096: return "AliasObj900" case 0x0097: return "Resource" case 0x0098: return "AliasObj1000" case 0x0099: return "Cvtpgd1600" case 0x009a: return "Cvtres1000" case 0x009b: return "Export1000" case 0x009c: return "Implib1000" case 0x009d: return "Linker1000" case 0x009e: return "Masm1000" case 0x009f: return "Phx1600_C" case 0x00a0: return "Phx1600_CPP" case 0x00a1: return "Phx1600_CVTCIL_C" case 0x00a2: return "Phx1600_CVTCIL_CPP" case 0x00a3: return "Phx1600_LTCG_C" case 0x00a4: return "Phx1600_LTCG_CPP" case 0x00a5: return "Phx1600_LTCG_MSIL" case 0x00a6: return "Phx1600_POGO_I_C" case 0x00a7: return "Phx1600_POGO_I_CPP" case 0x00a8: return "Phx1600_POGO_O_C" case 0x00a9: return "Phx1600_POGO_O_CPP" case 0x00aa: return "Utc1600_C" case 0x00ab: return "Utc1600_CPP" case 0x00ac: return "Utc1600_CVTCIL_C" case 0x00ad: return "Utc1600_CVTCIL_CPP" case 0x00ae: return "Utc1600_LTCG_C" case 0x00af: return "Utc1600_LTCG_CPP" case 0x00b0: return "Utc1600_LTCG_MSIL" case 0x00b1: return "Utc1600_POGO_I_C" case 0x00b2: return "Utc1600_POGO_I_CPP" case 0x00b3: return "Utc1600_POGO_O_C" case 0x00b4: return "Utc1600_POGO_O_CPP" case 0x00b5: return "AliasObj1010" case 0x00b6: return "Cvtpgd1610" case 0x00b7: return "Cvtres1010" case 0x00b8: return "Export1010" case 0x00b9: return "Implib1010" case 0x00ba: return "Linker1010" case 0x00bb: return "Masm1010" case 0x00bc: return "Utc1610_C" case 0x00bd: return "Utc1610_CPP" case 0x00be: return "Utc1610_CVTCIL_C" case 0x00bf: return "Utc1610_CVTCIL_CPP" case 0x00c0: return "Utc1610_LTCG_C" case 0x00c1: return "Utc1610_LTCG_CPP" case 0x00c2: return "Utc1610_LTCG_MSIL" case 0x00c3: return "Utc1610_POGO_I_C" case 0x00c4: return "Utc1610_POGO_I_CPP" case 0x00c5: return "Utc1610_POGO_O_C" case 0x00c6: return "Utc1610_POGO_O_CPP" case 0x00c7: return "AliasObj1100" case 0x00c8: return "Cvtpgd1700" case 0x00c9: return "Cvtres1100" case 0x00ca: return "Export1100" case 0x00cb: return "Implib1100" case 0x00cc: return "Linker1100" case 0x00cd: return "Masm1100" case 0x00ce: return "Utc1700_C" case 0x00cf: return "Utc1700_CPP" case 0x00d0: return "Utc1700_CVTCIL_C" case 0x00d1: return "Utc1700_CVTCIL_CPP" case 0x00d2: return "Utc1700_LTCG_C" case 0x00d3: return "Utc1700_LTCG_CPP" case 0x00d4: return "Utc1700_LTCG_MSIL" case 0x00d5: return "Utc1700_POGO_I_C" case 0x00d6: return "Utc1700_POGO_I_CPP" case 0x00d7: return "Utc1700_POGO_O_C" case 0x00d8: return "Utc1700_POGO_O_CPP" case 0x00d9: return "AliasObj1200" case 0x00da: return "Cvtpgd1800" case 0x00db: return "Cvtres1200" case 0x00dc: return "Export1200" case 0x00dd: return "Implib1200" case 0x00de: return "Linker1200" case 0x00df: return "Masm1200" case 0x00e0: return "Utc1800_C" case 0x00e1: return "Utc1800_CPP" case 0x00e2: return "Utc1800_CVTCIL_C" case 0x00e3: return "Utc1800_CVTCIL_CPP" case 0x00e4: return "Utc1800_LTCG_C" case 0x00e5: return "Utc1800_LTCG_CPP" case 0x00e6: return "Utc1800_LTCG_MSIL" case 0x00e7: return "Utc1800_POGO_I_C" case 0x00e8: return "Utc1800_POGO_I_CPP" case 0x00e9: return "Utc1800_POGO_O_C" case 0x00ea: return "Utc1800_POGO_O_CPP" case 0x00eb: return "AliasObj1210" case 0x00ec: return "Cvtpgd1810" case 0x00ed: return "Cvtres1210" case 0x00ee: return "Export1210" case 0x00ef: return "Implib1210" case 0x00f0: return "Linker1210" case 0x00f1: return "Masm1210" case 0x00f2: return "Utc1810_C" case 0x00f3: return "Utc1810_CPP" case 0x00f4: return "Utc1810_CVTCIL_C" case 0x00f5: return "Utc1810_CVTCIL_CPP" case 0x00f6: return "Utc1810_LTCG_C" case 0x00f7: return "Utc1810_LTCG_CPP" case 0x00f8: return "Utc1810_LTCG_MSIL" case 0x00f9: return "Utc1810_POGO_I_C" case 0x00fa: return "Utc1810_POGO_I_CPP" case 0x00fb: return "Utc1810_POGO_O_C" case 0x00fc: return "Utc1810_POGO_O_CPP" case 0x00fd: return "AliasObj1400" case 0x00fe: return "Cvtpgd1900" case 0x00ff: return "Cvtres1400" case 0x0100: return "Export1400" case 0x0101: return "Implib1400" case 0x0102: return "Linker1400" case 0x0103: return "Masm1400" case 0x0104: return "Utc1900_C" case 0x0105: return "Utc1900_CPP" case 0x0106: return "Utc1900_CVTCIL_C" case 0x0107: return "Utc1900_CVTCIL_CPP" case 0x0108: return "Utc1900_LTCG_C" case 0x0109: return "Utc1900_LTCG_CPP" case 0x010a: return "Utc1900_LTCG_MSIL" case 0x010b: return ": 'Utc1900_POGO_I_C" case 0x010c: return "Utc1900_POGO_I_CPP" case 0x010d: return "Utc1900_POGO_O_C" case 0x010e: return "Utc1900_POGO_O_CPP" } return "?" } // ProdIDtoVSversion retrieves the Visual Studio version from product id. // list from: https://github.com/kirschju/richheader func ProdIDtoVSversion(prodID uint16) string { if prodID > 0x010e || prodID < 0 { return "" } if prodID >= 0x00fd && prodID < (0x010e+1) { return "Visual Studio 2015 14.00" } if prodID >= 0x00eb && prodID < 0x00fd { return "Visual Studio 2013 12.10" } if prodID >= 0x00d9 && prodID < 0x00eb { return "Visual Studio 2013 12.00" } if prodID >= 0x00c7 && prodID < 0x00d9 { return "Visual Studio 2012 11.00" } if prodID >= 0x00b5 && prodID < 0x00c7 { return "Visual Studio 2010 10.10" } if prodID >= 0x0098 && prodID < 0x00b5 { return "Visual Studio 2010 10.00" } if prodID >= 0x0083 && prodID < 0x0098 { return "Visual Studio 2008 09.00" } if prodID >= 0x006d && prodID < 0x0083 { return "Visual Studio 2005 08.00" } if prodID >= 0x005a && prodID < 0x006d { return "Visual Studio 2003 07.10" } if prodID == 1 { return "Visual Studio" } return "" }
richheader.go
0.713631
0.405566
richheader.go
starcoder
package main import ( "math" "math/rand" "github.com/hajimehoshi/ebiten" vec "github.com/woodywood117/vector" ) type Particle struct { pos, vel *vec.Vec color *ebiten.Image history []vec.Vec } // Create a particle with a random starting position/color. // Particles created by this function have no starting velocity func NewParticle() *Particle { p := &Particle{ pos: vec.New( Scale(rand.Float64(), 0, WINDOW_X, 0, 1), Scale(rand.Float64(), 0, WINDOW_Y, 0, 1), ), vel: vec.Zero(), color: sprites[rand.Intn(len(sprites))], } return p } func (p *Particle) Update(grid [][]*Node) { width := int(WINDOW_X / SCALE) height := int(WINDOW_Y / SCALE) p.Move() x := math.Floor(p.pos.X / SCALE) y := math.Floor(p.pos.Y / SCALE) if int(x) < width && int(y) < height && int(x) >= 0 && int(y) >= 0 { p.Accelerate(grid[int(x)][int(y)].accl) } } // Move a particle based on it's current velocity. func (p *Particle) Move() { if DRAW_TRAIL { p.history = append(p.history, *p.pos) if len(p.history) > MAX_TRAIL_LEN { p.history = p.history[1:] } } p.pos.Add(p.vel) // Wrap around if necessary if p.pos.X > WINDOW_X { diff := p.pos.X - WINDOW_X p.pos.X = diff } if p.pos.X < 0 { p.pos.X = WINDOW_X + p.pos.X } if p.pos.Y > WINDOW_Y { diff := p.pos.Y - WINDOW_Y p.pos.Y = diff } if p.pos.Y < 0 { p.pos.Y = WINDOW_Y + p.pos.Y } } // Accelerate the velocity of a particle with a given acceleration vector. func (p *Particle) Accelerate(accl *vec.Vec) { p.vel.Add(accl) l := p.vel.Magnitude() // Cap velocity to MAX_VELOCITY if l > MAX_VELOCITY { angle := p.vel.Angle() p.vel = vec.New(1, 0) p.vel.Rotate(angle) p.vel.Multiply(MAX_VELOCITY) } } // Draw a particle to the screen func (p *Particle) Draw(screen *ebiten.Image) { // Draw the trail if DRAW_TRAIL { op := &ebiten.DrawImageOptions{} op.GeoM.Scale(PARTICLE_WIDTH, PARTICLE_WIDTH) for trail := len(p.history) - 1; trail > -1; trail-- { op.ColorM.Scale(1, 1, 1, 0.85) op.GeoM.Translate(p.history[trail].X, p.history[trail].Y) screen.DrawImage(p.color, op) op.GeoM.Translate(-p.history[trail].X, -p.history[trail].Y) } } // Draw the particle itself op := &ebiten.DrawImageOptions{} op.GeoM.Scale(PARTICLE_WIDTH, PARTICLE_WIDTH) op.GeoM.Translate(p.pos.X, p.pos.Y) screen.DrawImage(p.color, op) }
particle.go
0.653901
0.413004
particle.go
starcoder
package simplecsv // countIndexesInSlices counts how many times an integrer shows up in one or more slices func countIndexesInSlices(indexes [][]int) map[int]int { valuesMap := map[int]int{} var valueExists bool for _, toCount := range indexes { for _, v := range toCount { _, valueExists = valuesMap[v] if valueExists != true { valuesMap[v] = 1 } else { valuesMap[v]++ } } } return valuesMap } // showsMoreThanTimes returns an array of ints they show more than the min time func showsMoreThanTimes(valuesMap map[int]int, min int) []int { result := []int{} for k, v := range valuesMap { if v >= min { result = append(result, k) } } return result } // contains checks if a number exits in a slice func contains(s []int, e int) bool { for _, a := range s { if a == e { return true } } return false } // OrIndex operates an OR operator in the indexes func OrIndex(indexes ...[]int) []int { minTimes := 1 base := [][]int{} for _, index := range indexes { base = append(base, index) } valuesMap := countIndexesInSlices(base) result := showsMoreThanTimes(valuesMap, minTimes) return result } // AndIndex operates an AND operator in the indexes func AndIndex(indexes ...[]int) []int { minTimes := len(indexes) base := [][]int{} for _, index := range indexes { base = append(base, index) } valuesMap := countIndexesInSlices(base) result := showsMoreThanTimes(valuesMap, minTimes) return result } // NotIndex negates the index between a min value and a max value // The min value tipically is either 0 or 1 (without and with headers) // The max value tipically is the csv length - 1 (number of rows -1). // A table with a header and 2 rows (length = 3) can have indexes with values of 1 and 2 func NotIndex(index []int, min, max int) []int { counter := make(map[int]bool) for i := min; i <= max; i++ { counter[i] = false } for _, v := range index { counter[v] = true } negativeIndex := []int{} for i := min; i <= max; i++ { if counter[i] == false { negativeIndex = append(negativeIndex, i) } } return negativeIndex }
logic.go
0.743634
0.557845
logic.go
starcoder
package blokus import "fmt" // BasicState is a quite inefficient way of storing the game state type BasicState struct { board [20][20]boardValue notPlayedPieces [4][]Piece lastMoveMono [4]bool startPiece Piece isPlayerTwoFirst bool // stored inverted, so initial state is correct isColorInvalid [4]bool // stored inverted, so initial state is correct currentColor Color } func (b *BasicState) At(x, y uint8) (c Color, hasPiece bool) { if x > 19 || y > 19 { return } bv := b.board[x][y] c = bv.color hasPiece = bv.hasPiece return } func (b *BasicState) ensureNotPlayedPieces() { if b.notPlayedPieces[0] == nil { for c := Color(0); c < 4; c++ { b.notPlayedPieces[c] = make([]Piece, NumPieces) copy(b.notPlayedPieces[c], AllPieces[:]) } } } func (b *BasicState) NotPlayedPiecesFor(c Color) []Piece { b.ensureNotPlayedPieces() return b.notPlayedPieces[c] } func (b *BasicState) IsPiecePlayed(c Color, p Piece) bool { b.ensureNotPlayedPieces() for _, pp := range b.notPlayedPieces[c] { if pp == p { return false } } return true } func (b *BasicState) IsLastMoveMono(c Color) bool { return b.lastMoveMono[c] } func (b *BasicState) HasPlayed(c Color) bool { b.ensureNotPlayedPieces() return len(b.notPlayedPieces[c]) < NumPieces } func (b *BasicState) Reset() { b.startPiece = PieceMono for x := 0; x < 20; x++ { for y := 0; y < 20; y++ { b.board[x][y] = boardValue{} } } for c := ColorBlue; c < 4; c++ { b.notPlayedPieces[c] = make([]Piece, NumPieces) copy(b.notPlayedPieces[c], AllPieces[:]) b.lastMoveMono[c] = false } } func (b *BasicState) Set(x, y uint8, c Color, hasPiece bool) { if x > 19 || y > 19 { panic(fmt.Errorf("trying to set (color=%s, hasPiece=%v) at invalid coordinates x=%d y%d", c.String(), hasPiece, x, y)) } b.board[x][y] = boardValue{ color: c, hasPiece: hasPiece, } } func (b *BasicState) SetNotPlayedPiecesFor(c Color, pieces []Piece) { b.ensureNotPlayedPieces() b.notPlayedPieces[c] = b.notPlayedPieces[c][0:0] for _, p := range pieces { b.notPlayedPieces[c] = append(b.notPlayedPieces[c], p) } } func (b *BasicState) SetPiecePlayed(c Color, p Piece, isPlayed bool) { b.ensureNotPlayedPieces() l := len(b.notPlayedPieces[c]) insertI := 0 for i, pi := range b.notPlayedPieces[c] { if pi == p { if isPlayed { if (i + 1) < l { copy(b.notPlayedPieces[c][i:l-1], b.notPlayedPieces[c][i+1:l]) } b.notPlayedPieces[c] = b.notPlayedPieces[c][0 : l-1] } return } if p.NumPoints() > pi.NumPoints() { insertI = i } } if isPlayed { return } b.notPlayedPieces[c] = append(b.notPlayedPieces[c], p) copy(b.notPlayedPieces[c][insertI+1:], b.notPlayedPieces[c][insertI:l]) b.notPlayedPieces[c][insertI] = p } func (b *BasicState) SetLastMoveMono(c Color, isLastMoveMono bool) { b.lastMoveMono[c] = isLastMoveMono } type boardValue struct { color Color hasPiece bool } func (b *BasicState) SetStartPiece(piece Piece) { b.startPiece = piece } func (b *BasicState) StartPiece() Piece { return b.startPiece } func (b *BasicState) IsPlayerOneFirst() bool { return !b.isPlayerTwoFirst } func (b *BasicState) IsColorValid(c Color) bool { return !b.isColorInvalid[c] } func (b *BasicState) CurrentColor() Color { return b.currentColor } func (b *BasicState) SetPlayerOneFirst(isPlayerOneFirst bool) { b.isPlayerTwoFirst = !isPlayerOneFirst } func (b *BasicState) SetColorValid(c Color, isValid bool) { b.isColorInvalid[c] = !isValid } func (b *BasicState) SetCurrentColor(c Color) { b.currentColor = c }
2021/blokus/basic_state.go
0.692538
0.403508
basic_state.go
starcoder
package main import ( "bufio" "fmt" "os" "strconv" "strings" "github.com/dowlandaiello/word_search/types" "github.com/gookit/color" ) // main is the main word search solver function. func main() { var grid *types.Grid // Declare grid buffer reader := bufio.NewReader(os.Stdin) // Initialize reader if len(os.Args) == 1 { // Check invalid params panic("Make sure to pass in word search width and height!") // Panic } else if len(os.Args) == 2 { // Check import grid grid = importGrid(os.Args[1]) // Import grid } else { gridWidth, err := strconv.Atoi(os.Args[1]) // Parse width if err != nil { // Check for errors panic(err) // Panic } gridHeight, err := strconv.Atoi(os.Args[2]) // Parse height if err != nil { // Check for errors panic(err) // Panic } grid = types.NewGrid(uint64(gridWidth), uint64(gridHeight)) // Initialize grid for i := 0; i < gridHeight; i++ { // Do until made all rows fmt.Printf("Row %d: ", i) // Log input row input, err := reader.ReadString('\n') // Read up to \n if err != nil { // Check for errors panic(err) // Panic } input = strings.Replace(input, "\n", "", -1) // Remove \n grid.Rows[i].Letters = input // Set letters } } for { fmt.Print("Word to find: ") // Print prompt wordToFind, err := reader.ReadString('\n') // Read up to \n if err != nil { // Check for errors panic(err) // Panic } wordToFind = strings.Replace(wordToFind, "\n", "", -1) // Remove \n xCoords, yCoords := grid.FindString(wordToFind) // Find word if len(xCoords) == 0 || len(yCoords) == 0 { // Check couldn't find a match color.Red.Println("Couldn't find a match!") // Log err continue // Continue } for y, row := range grid.Rows { // Iterate through rows var rowStr string // Init row buffer for x, char := range row.Letters { // Iterate through characters if index := indexOf(xCoords, uint64(x)); index != -1 && yCoords[index] == uint64(y) { // Check matching coordinates rowStr = rowStr + color.Yellow.Sprintf("%c", char) // Append char } else { rowStr = rowStr + string(char) // Append char } } fmt.Println(rowStr) // Log row } } } // importGrid imports a grid. func importGrid(fileName string) *types.Grid { file, err := os.Open(fileName) // Open file if err != nil { // Check for errors panic(err) // Panic } defer file.Close() // Close file scanner := bufio.NewScanner(file) // Initialize scanner var grid types.Grid // Initialize grid buffer for scanner.Scan() { // Read entire file line := scanner.Text() // Get line grid.Rows = append(grid.Rows, types.NewRow(line)) // Set row } return &grid // Return read grid } // indexOf fetches the index of a value in a uint64 slice. func indexOf(s []uint64, v uint64) int { for i, val := range s { // Iterate through values if val == v { // Check match return i // Valid } } return -1 // Invalid }
main.go
0.563858
0.416322
main.go
starcoder
package gerber import ( "fmt" "io" "math" "github.com/gmlewis/go3d/float64/vec2" ) const ( sf = 1e6 // scale factor maxPts = 10000 ) // Shape represents the type of shape the apertures use. type Shape string const ( // RectShape uses rectangles for the aperture. RectShape Shape = "R" // CircleShape uses circles for the aperture. CircleShape Shape = "C" ) // Primitive is a Gerber primitive. type Primitive interface { WriteGerber(w io.Writer, apertureIndex int) error Aperture() *Aperture // MBB returns the minimum bounding box in millimeters. MBB() MBB } // Aperture represents the nature of the primitive // and satisfies the Primitive interface. type Aperture struct { Shape Shape Size float64 } func (a *Aperture) MBB() MBB { return MBB{} } // WriteGerber writes the aperture to the Gerber file. func (a *Aperture) WriteGerber(w io.Writer, apertureIndex int) error { if a.Shape == CircleShape { fmt.Fprintf(w, "%%ADD%vC,%0.5f*%%\n", apertureIndex, a.Size) return nil } fmt.Fprintf(w, "%%ADD%vR,%0.5fX%0.5f*%%\n", apertureIndex, a.Size, a.Size) return nil } // Aperture is defined to implement the Primitive interface. func (a *Aperture) Aperture() *Aperture { return a } // ID returns a unique ID for the Aperture. func (a *Aperture) ID() string { if a == nil { return "default" } return fmt.Sprintf("%v%0.5f", a.Shape, sf*a.Size) } // Pt represents a 2D Point. type Pt = vec2.T // MBB represents a minimum bounding box. type MBB = vec2.Rect // Point is a simple convenience function that keeps the code easy to read. // All dimensions are in millimeters. func Point(x, y float64) Pt { return Pt{x, y} } // ArcT represents an arc and satisfies the Primitive interface. type ArcT struct { Center Pt Radius float64 Shape Shape XScale float64 YScale float64 StartAngle float64 EndAngle float64 Thickness float64 mbb *MBB // cached minimum bounding box } // Arc returns an arc primitive. // All dimensions are in millimeters. // Angles are specified in degrees (and stored as radians). func Arc( center Pt, radius float64, shape Shape, xScale, yScale, startAngle, endAngle float64, thickness float64) *ArcT { if startAngle > endAngle { startAngle, endAngle = endAngle, startAngle } return &ArcT{ Center: center, Radius: radius, Shape: shape, XScale: math.Abs(xScale), YScale: math.Abs(yScale), StartAngle: math.Pi * startAngle / 180.0, EndAngle: math.Pi * endAngle / 180.0, Thickness: thickness, } } // WriteGerber writes the primitive to the Gerber file. func (a *ArcT) WriteGerber(w io.Writer, apertureIndex int) error { delta := a.EndAngle - a.StartAngle length := delta * a.Radius // Resolution of segments is 0.1mm segments := int(0.5+length*10.0) + 1 delta /= float64(segments) angle := float64(a.StartAngle) for i := 0; i < segments; i++ { x1 := a.Center[0] + a.XScale*math.Cos(angle)*a.Radius y1 := a.Center[1] + a.YScale*math.Sin(angle)*a.Radius angle += delta x2 := a.Center[0] + a.XScale*math.Cos(angle)*a.Radius y2 := a.Center[1] + a.YScale*math.Sin(angle)*a.Radius line := Line(x1, y1, x2, y2, a.Shape, a.Thickness) line.WriteGerber(w, apertureIndex) } return nil } // Aperture returns the primitive's desired aperture. func (a *ArcT) Aperture() *Aperture { return &Aperture{ Shape: a.Shape, Size: a.Thickness, } } func (a *ArcT) MBB() MBB { if a.mbb != nil { return *a.mbb } delta := a.EndAngle - a.StartAngle length := delta * a.Radius // Resolution of segments is 0.1mm segments := int(0.5+length*10.0) + 1 delta /= float64(segments) angle := float64(a.StartAngle) for i := 0; i < segments; i++ { x1 := a.Center[0] + a.XScale*math.Cos(angle)*a.Radius y1 := a.Center[1] + a.YScale*math.Sin(angle)*a.Radius angle += delta x2 := a.Center[0] + a.XScale*math.Cos(angle)*a.Radius y2 := a.Center[1] + a.YScale*math.Sin(angle)*a.Radius line := Line(x1, y1, x2, y2, a.Shape, a.Thickness) mbb := line.MBB() if a.mbb == nil { a.mbb = &mbb } else { a.mbb.Join(&mbb) } } return *a.mbb } // CircleT represents a circle and satisfies the Primitive interface. type CircleT struct { pt Pt thickness float64 mbb *MBB // cached minimum bounding box } // Circle returns a circle primitive. // All dimensions are in millimeters. func Circle(center Pt, thickness float64) *CircleT { return &CircleT{ pt: center, thickness: thickness, } } // WriteGerber writes the primitive to the Gerber file. func (c *CircleT) WriteGerber(w io.Writer, apertureIndex int) error { fmt.Fprintf(w, "G54D%d*\n", apertureIndex) fmt.Fprintf(w, "X%06dY%06dD02*\n", int(0.5+sf*(c.pt[0])), int(0.5+sf*(c.pt[1]))) fmt.Fprintf(w, "X%06dY%06dD01*\n", int(0.5+sf*(c.pt[0])), int(0.5+sf*(c.pt[1]))) return nil } // Aperture returns the primitive's desired aperture. func (c *CircleT) Aperture() *Aperture { return &Aperture{ Shape: CircleShape, Size: c.thickness, } } func (c *CircleT) MBB() MBB { if c.mbb != nil { return *c.mbb } r := 0.5 * c.thickness ll := Pt{c.pt[0] - r, c.pt[1] - r} ur := Pt{c.pt[0] + r, c.pt[1] + r} c.mbb = &MBB{Min: ll, Max: ur} return *c.mbb } // LineT represents a line and satisfies the Primitive interface. type LineT struct { P1, P2 Pt Shape Shape Thickness float64 mbb *MBB // cached minimum bounding box } // Line returns a line primitive. // All dimensions are in millimeters. func Line(x1, y1, x2, y2 float64, shape Shape, thickness float64) *LineT { p1 := Pt{x1, y1} p2 := Pt{x2, y2} return &LineT{ P1: p1, P2: p2, Shape: shape, Thickness: thickness, } } // WriteGerber writes the primitive to the Gerber file. func (l *LineT) WriteGerber(w io.Writer, apertureIndex int) error { fmt.Fprintf(w, "G54D%d*\n", apertureIndex) fmt.Fprintf(w, "X%06dY%06dD02*\n", int(0.5+sf*(l.P1[0])), int(0.5+sf*(l.P1[1]))) fmt.Fprintf(w, "X%06dY%06dD01*\n", int(0.5+sf*(l.P2[0])), int(0.5+sf*(l.P2[1]))) return nil } // Aperture returns the primitive's desired aperture. func (l *LineT) Aperture() *Aperture { return &Aperture{ Shape: l.Shape, Size: l.Thickness, } } func (l *LineT) MBB() MBB { if l.mbb != nil { return *l.mbb } l.mbb = &MBB{Min: l.P1, Max: l.P1} l.mbb.Join(&MBB{Min: l.P2, Max: l.P2}) l.mbb.Min[0] -= 0.5 * l.Thickness l.mbb.Min[1] -= 0.5 * l.Thickness l.mbb.Max[0] += 0.5 * l.Thickness l.mbb.Max[1] += 0.5 * l.Thickness return *l.mbb } // PolygonT represents a polygon and satisfies the Primitive interface. type PolygonT struct { Offset Pt Points []Pt mbb *MBB // cached minimum bounding box } // Polygon returns a polygon primitive. // All dimensions are in millimeters. func Polygon(offset Pt, filled bool, points []Pt, thickness float64) *PolygonT { return &PolygonT{ Offset: offset, Points: points, } } // WriteGerber writes the primitive to the Gerber file. func (p *PolygonT) WriteGerber(w io.Writer, apertureIndex int) error { io.WriteString(w, "G54D11*\n") io.WriteString(w, "G36*\n") for i, pt := range p.Points { if i == 0 { fmt.Fprintf(w, "X%06dY%06dD02*\n", int(0.5+sf*(pt[0]+p.Offset[0])), int(0.5+sf*(pt[1]+p.Offset[1]))) continue } fmt.Fprintf(w, "X%06dY%06dD01*\n", int(0.5+sf*(pt[0]+p.Offset[0])), int(0.5+sf*(pt[1]+p.Offset[1]))) } fmt.Fprintf(w, "X%06dY%06dD02*\n", int(0.5+sf*(p.Points[0][0]+p.Offset[0])), int(0.5+sf*(p.Points[0][1]+p.Offset[1]))) io.WriteString(w, "G37*\n") return nil } // Aperture returns nil for PolygonT because it uses the default aperture. func (p *PolygonT) Aperture() *Aperture { return nil } func (p *PolygonT) MBB() MBB { if p.mbb != nil { return *p.mbb } for i, pt := range p.Points { newPt := Pt{pt[0] + p.Offset[0], pt[1] + p.Offset[1]} v := &MBB{Min: newPt, Max: newPt} if i == 0 { p.mbb = v continue } p.mbb.Join(v) } return *p.mbb }
gerber/primitives.go
0.82251
0.488649
primitives.go
starcoder
package parser import ( "fmt" "io" "strconv" "strings" "github.com/zoncoen/query-go/ast" "github.com/zoncoen/query-go/token" ) // Parser represents a parser. type Parser struct { s *scanner pos int tok token.Token lit string errors Errors } // NewParser returns a new parser. func NewParser(r io.Reader) *Parser { return &Parser{s: newScanner(r)} } // Parse parses the query string and returns the corresponding ast.Node. func (p *Parser) Parse() (ast.Node, error) { return p.parse(), p.errors.Err() } func (p *Parser) next() { p.pos, p.tok, p.lit = p.s.scan() } func (p *Parser) parse() ast.Node { node := p.parseFirst() if node == nil { return nil } L: for { switch p.tok { case token.PERIOD: pos := p.pos p.next() node = &ast.Selector{ ValuePos: pos, X: node, Sel: p.lit, } p.next() case token.LBRACK: node = p.parseIndex(node) case token.EOF: break L default: p.expect(token.PERIOD, token.LBRACK) } } return node } func (p *Parser) parseFirst() ast.Node { p.next() var node ast.Node switch p.tok { case token.STRING: node = &ast.Selector{ ValuePos: p.pos, Sel: p.lit, } p.next() case token.PERIOD: pos := p.pos p.next() node = &ast.Selector{ ValuePos: pos, X: node, Sel: p.lit, } p.next() case token.LBRACK: node = p.parseIndex(nil) case token.EOF: return nil default: p.expect(token.STRING, token.LBRACK) } return node } func (p *Parser) parseIndex(x ast.Node) ast.Node { pos := p.pos p.next() var node ast.Node switch p.tok { case token.STRING: node = &ast.Selector{ ValuePos: pos, X: x, Sel: p.lit, } p.next() case token.INT: node = &ast.Index{ ValuePos: pos, X: x, Index: p.parseInt(), } default: p.expect(token.STRING, token.INT) } p.expect(token.RBRACK) return node } func (p *Parser) parseInt() int { pos, lit := p.pos, p.lit p.next() i, err := strconv.Atoi(lit) if err != nil { p.error(pos, fmt.Sprintf("%s is not an integer", lit)) return 0 } return i } func (p *Parser) error(pos int, msg string) { p.errors.Append(pos, msg) } func (p *Parser) expect(toks ...token.Token) { var ok bool strs := make([]string, len(toks)) for i, tok := range toks { if p.tok == tok { ok = true break } strs[i] = fmt.Sprintf(`"%s"`, tok) } if !ok { p.error(p.pos, fmt.Sprintf(`expected %s but found "%s"`, strings.Join(strs, " or "), p.tok)) } p.next() // make progress }
parser/parser.go
0.620162
0.421552
parser.go
starcoder
package lattice import ( "errors" "fmt" "github.com/arbori/population.git/population/space" ) type Lattice struct { Dimention int Limits []int lines []interface{} } func New(dim ...int) (Lattice, error) { return NewWithValue(nil, dim...) } func NewWithValue(value interface{}, dim ...int) (Lattice, error) { if len(dim) <= 0 { return Lattice{}, errors.New("Wrong dimention") } dimention := len(dim) result := Lattice{ Dimention: dimention, Limits: dim, lines: makeLine(value, dim...), } return result, nil } func (l Lattice) At(x ...int) interface{} { if len(x) != l.Dimention { panic(fmt.Sprintf("Dimention out of bounds: The X's dimention %d is diferent than lattice's dimention %d.", len(x), l.Dimention)) } cell := get(x, l.lines) return (*cell) } func (l Lattice) Set(value interface{}, x ...int) { if len(x) != l.Dimention { panic(fmt.Sprintf("Dimention out of bounds: The X's dimention %d is diferent than lattice's dimention %d.", len(x), l.Dimention)) } cell := get(x, l.lines) (*cell) = value } func (l Lattice) Enclose(to space.Point) space.Point { if to == nil || l.Dimention != len(to) { return space.Point{} } point := make([]int, l.Dimention) for c := 0; c < l.Dimention; c += 1 { point[c] = to[c] if point[c] < 0 { point[c] = (-point[c] + l.Limits[c]) % l.Limits[c] } else if point[c] >= l.Limits[c] { point[c] = point[c] % l.Limits[c] } } return point } func makeLine(value interface{}, dim ...int) []interface{} { var rows []interface{} = make([]interface{}, dim[0]) for i := 0; i < dim[0]; i += 1 { fillLine(value, &rows[i], dim[1:]) } return rows } func fillLine(value interface{}, cell *interface{}, dim []int) { if len(dim) < 1 { (*cell) = value return } *cell = make([]interface{}, dim[0]) size := dim[0] if len(dim) == 1 { for i := 0; i < size; i += 1 { (*cell).([]interface{})[i] = value } } else { for i := 0; i < size; i += 1 { fillLine(value, &(*cell).([]interface{})[i], dim[1:]) } } } func get(x []int, row []interface{}) *interface{} { if x[0] < 0 || x[0] >= len(row) { panic(fmt.Sprintf("Index out of bounds: %d is out of [0, %d).", x[0], len(row))) } if len(x) == 1 { return &row[x[0]] } return get(x[1:], row[x[0]].([]interface{})) }
lattice/lattice.go
0.582135
0.492615
lattice.go
starcoder
package it import "fmt" type KeyType int64 const ( maxKey = KeyType(0x7fffffffffffffff) minKey = -maxKey - 1 ) const ( Red = 0 Black = 1 ) type Node struct { Low, High KeyType Upper KeyType Parent, Left, Right *Node Color uint8 } type Tree struct { Root, Nil *Node sentinel Node } func New() *Tree { var t Tree t.sentinel.Color = Black t.Nil = &t.sentinel t.Root = t.Nil return &t } func (t *Tree) makeNode(low, high KeyType) *Node { return &Node{Low: low, High: high, Upper: high, Parent: t.Nil, Left: t.Nil, Right: t.Nil, Color: Red} } func (t *Tree) Insert(low, high KeyType) { y := t.Nil x := t.Root for x != t.Nil { if x.Upper < high { x.Upper = high } y = x if low <= x.Low { x = x.Left } else { x = x.Right } } z := t.makeNode(low, high) z.Parent = y if y == t.Nil { t.Root = z } else if low <= y.Low { y.Left = z } else { y.Right = z } t.insertFixup(z) } func (t *Tree) insertFixup(z *Node) { for z.Parent.Color == Red { y := z.Parent.Parent if z.Parent == y.Left { if y.Right.Color == Red { // Case 1: recolor y.Color = Red y.Left.Color = Black y.Right.Color = Black z = y } else { // y.Right.Color == Black if z == z.Parent.Right { // Case 2: straighten z = z.Parent t.leftRotate(z) } // Case 3: rotate/balance z.Parent.Color = Black y.Color = Red t.rightRotate(y) } } else { // z.Parent == y.Right if y.Left.Color == Red { // Case 1: recolor y.Color = Red y.Left.Color = Black y.Right.Color = Black z = y } else { // y.Left.Color == Black if z == z.Parent.Left { // Case 2: straighten z = z.Parent t.rightRotate(z) } // Case 3: rotate/balance z.Parent.Color = Black y.Color = Red t.leftRotate(y) } } } t.Root.Color = Black } func (t *Tree) Delete(low, high KeyType) { z := t.Root for z != t.Nil && (low != z.Low || high != z.High) { if low <= z.Low { z = z.Left } else { z = z.Right } } var x *Node color := z.Color switch { case z == t.Nil: return // Key not found. case z.Left == t.Nil: // Node to delete has at most a right child. x = z.Right t.transplant(z, x) case z.Right == t.Nil: // Node to delete has only a left child x = z.Left t.transplant(z, x) default: // Node to delete has two children y := t.min(z.Right) color = y.Color x = y.Right if y.Parent == z { x.Parent = y } else { t.transplant(y, y.Right) y.Right = z.Right y.Right.Parent = y } t.transplant(z, y) y.Left = z.Left y.Left.Parent = y y.Color = z.Color } t.updateUpper(x.Parent) if color == Black { t.deleteFixup(x) } } func (t *Tree) deleteFixup(x *Node) { for x != t.Root && x.Color == Black { if x == x.Parent.Left { w := x.Parent.Right if w.Color == Red { // Case 1: make the sibling black t.leftRotate(x.Parent) w.Color = Black x.Parent.Color = Red w = x.Parent.Right } if w.Left.Color == Black && w.Right.Color == Black { // Case 2: push the double blackness up w.Color = Red x = x.Parent } else { // Case 3: if w.Left.Color == Red && w.Right.Color == Black { w.Color = Red w.Left.Color = Black t.rightRotate(w) w = x.Parent.Right } // Case 4: remove the double blackness; end w.Color = x.Parent.Color w.Right.Color = Black x.Parent.Color = Black t.leftRotate(x.Parent) x = t.Root } } else { // x == x.Parent.Right w := x.Parent.Left if w.Color == Red { // Case 1: make the sibling black t.rightRotate(x.Parent) w.Color = Black x.Parent.Color = Red w = x.Parent.Left } if w.Left.Color == Black && w.Right.Color == Black { // Case 2: push the double blackness up w.Color = Red x = x.Parent } else { // Case 3: if w.Left.Color == Black && w.Right.Color == Red { w.Color = Red w.Right.Color = Black t.leftRotate(w) w = x.Parent.Left } // Case 4: remove the double blackness; end w.Color = x.Parent.Color w.Left.Color = Black x.Parent.Color = Black t.rightRotate(x.Parent) x = t.Root } } } x.Color = Black } func (t *Tree) Search(low, high KeyType) (KeyType, KeyType, bool) { x := t.Root for x != t.Nil && (low > x.High || high < x.Low) { if x.Left != t.Nil && x.Left.Upper >= low { x = x.Left } else { x = x.Right } } if x == t.Nil { return 0, 0, false } else { return x.Low, x.High, true } } func (t *Tree) leftRotate(x *Node) { y := x.Right y.Parent = x.Parent y.Upper = x.Upper if x == t.Root { t.Root = y } else { if x == x.Parent.Left { x.Parent.Left = y } else { x.Parent.Right = y } } x.Right = y.Left if y.Left != t.Nil { y.Left.Parent = x } y.Left = x x.Parent = y x.Upper = t.upper(x) } func (t *Tree) rightRotate(y *Node) { x := y.Left x.Parent = y.Parent x.Upper = y.Upper if y == t.Root { t.Root = x } else { if y == y.Parent.Left { y.Parent.Left = x } else { y.Parent.Right = x } } y.Left = x.Right if x.Right != t.Nil { x.Right.Parent = y } x.Right = y y.Parent = x y.Upper = t.upper(y) } func (t *Tree) transplant(u, v *Node) { if u.Parent == t.Nil { t.Root = v } else if u == u.Parent.Left { u.Parent.Left = v } else { u.Parent.Right = v } v.Parent = u.Parent } func (t *Tree) min(u *Node) *Node { for u.Left != t.Nil { u = u.Left } return u } func (t *Tree) upper(x *Node) KeyType { u := x.High if x.Left != t.Nil && u < x.Left.Upper { u = x.Left.Upper } if x.Right != t.Nil && u < x.Right.Upper { u = x.Right.Upper } return u } func (t *Tree) updateUpper(x *Node) { for x != t.Nil { x.Upper = t.upper(x) x = x.Parent } } func (t *Tree) verifyTreeUpper() bool { return t.verifyUpper(t.Root) } func (t *Tree) verifyUpper(x *Node) bool { if x == t.Nil { return true } if ok := t.verifyUpper(x.Left); !ok { return false } if ok := t.verifyUpper(x.Right); !ok { return false } return x.Upper == t.upper(x) } func (t *Tree) WriteDot() string { var sn, se string _, sn = t.writeDotNodes(1, t.Root) _, se = t.writeDotEdges(1, t.Root) return "digraph RBTree {\n" + sn + se + "}\n" } const leafString = "[shape=point]" func (t *Tree) writeDotNodes(n uint, nd *Node) (uint, string) { if nd == t.Nil { return n + 1, fmt.Sprintf("n%d%s\n", n, leafString) } var color string if nd.Color == Red { color = "red" } else { color = "black" } var s, sl, sr string s = fmt.Sprintf("n%d[label=\"[%d, %d | %d]\", color=%s]\n", n, int64(nd.Low), int64(nd.High), int64(nd.Upper), color) n, sl = t.writeDotNodes(n+1, nd.Left) n, sr = t.writeDotNodes(n, nd.Right) return n, s + sl + sr } func (t *Tree) writeDotEdges(n uint, nd *Node) (uint, string) { if nd == t.Nil { return n + 1, "" } nl, sl := t.writeDotEdges(n+1, nd.Left) nr, sr := t.writeDotEdges(nl, nd.Right) s := fmt.Sprintf("n%d -> n%d[arrowhead=none]\n", n, n+1) s += fmt.Sprintf("n%d -> n%d[arrowhead=none]\n", n, nl) return nr, s + sl + sr }
Lecture 11- Augmenting data structures/src/it/it.go
0.559531
0.442817
it.go
starcoder
package mysql_nodejs import ( . "github.com/gocircuit/circuit/gocircuit.org/render" ) func RenderImage() string { return RenderHtml("Prepare host images", Render(imageBody, nil)) } const imageBody = ` <h1>Prepare host images</h1> <p>We are going to describe here a sequence of steps that will result in creating a new Amazon Machine Image (AMI), preloaded with software needed for this tutorial. <p>Start a fresh EC2 instance with an Ubuntu Linux base image. The plan is to install the needed software in a few simple manual steps and then save the state of the machine into the resulting image. <h3>Install a few generic tools</h3> <p>Begin by updating the packaging system and installing a few handy generic tools: <pre> # sudo apt-get update # sudo apt-get install vim curl git </pre> <h3>Install the circuit</h3> <p>Installing the Go compiler: <pre> # sudo apt-get install golang </pre> <p>Next, we need to create a directory for building the circuit. This directory will serve as the <a href="https://golang.org/doc/code.html">GOPATH</a> directory that points the Go compiler to a source tree. <pre> # mkdir -p $HOME/0/src # echo "declare -x GOPATH=$HOME/0" >> ~/.bash_profile # source ~/.bash_profile </pre> <p>Fetch and build the circuit, then place the circuit executable in the system path: <pre> # go get github.com/gocircuit/circuit/cmd/circuit # cp $GOPATH/bin/circuit /usr/local/bin </pre> <p>Make sure the installation succeeded by running <code>circuit start</code>, to start the circuit daemon, and then simply kill it with Control-C. <p>Finally, prepare a scratch directory which we will later use for the circuit daemon to write logging and other such information. <pre> # mkdir /var/circuit </pre> <h3>Install MySQL server</h3> <p>Install MySQL using the default packaged distribution. The installation will prompt you for a root user password — feel free to use the empty string to simplify the tutorial: <pre> # sudo apt-get install mysql-server </pre> <p>As a side-effect, the installer will put MySQL in the boot sequence of this machine. We would like to disable that as we plan to manage (start/stop) the service through our circuit application. Thus, disable the automatic boot startup of MySQL using: <pre> # echo manual | sudo tee /etc/init/mysql.override </pre> <h3>Install node.js and the tutorial node.js app</h3> <p>Last, we need to install Node.js as well as the example Node.js app that we have prepared for this tutorial, to serve as a RESTful HTTP API front-end for the key/value store, backed by MySQL. <p>Install Node.js with: <pre> # sudo apt-get install nodejs npm </pre> <p>The Node.js app for this tutorial is located in the circuit's source tree. We already have a local clone of the source tree (as a result of the <code>go get</code> command earlier). We are simply going to copy it out of the source tree and place it nearby for convenience: <pre> # cd $HOME # cp -R $GOPATH/src/github.com/gocircuit/circuit/tutorial/nodejs-using-mysql/nodejs-app . </pre> <p>And prepare the Node.js app for execution by fetching its Node.js package dependencies: <pre> # cd $HOME # cd nodejs-app # npm install </pre> <h3>Save the image</h3> <p>We are done installing. It is best to now “stop” (rather than “terminate”) the Amazon host instance. Once the instance has stopped, use your Amazon EC2 console to save its current state to a new machine image. `
gocircuit.org/tutorial/mysql-nodejs/image.go
0.547464
0.499084
image.go
starcoder
package game import ( "math" "github.com/faiface/pixel" ) const ( bulletSizeX = int64(1) bulletSizeY = int64(2) ) type bullet struct { sprite pixel.Sprite direction Direction x, y int64 size [2]int64 state State tank *tank } func (g *game) loadBullet(x int64, y int64, direction Direction, state State, tank *tank) *bullet { sprite := g.sprites.bullet b := &bullet{ sprite: *sprite, direction: direction, x: x, y: y, size: [2]int64{bulletSizeX, bulletSizeY}, state: state, tank: tank, } return b } func (t *tank) fire(g *game) { if t.bullet != nil { return } x, y := t.x, t.y switch t.direction { case right: x += 5 case left: x -= 5 case up: y += 5 case down: y -= 5 } t.bullet = g.loadBullet(x, y, t.direction, active, t) } func (b *bullet) draw(target pixel.Target) { mat := pixel.IM switch b.direction { case left: mat = mat.Rotated(pixel.ZV, math.Pi/2) case down: mat = mat.Rotated(pixel.ZV, math.Pi) case right: mat = mat.Rotated(pixel.ZV, 3*math.Pi/2) } mat = mat.Moved(pixel.V(float64(b.x), float64(b.y))) b.sprite.Draw(target, mat) } func (b *bullet) checkTankDestroyed(g *game, playerTank *tank) bool { bulletSpriteRect := b.sprite.Frame() bulletV := pixel.V(float64(b.x), float64(b.y)).Sub(bulletSpriteRect.Min) bulletRect := bulletSpriteRect.Moved(bulletV) for _, player := range g.players { if player == nil { continue } t := player.tank if t == playerTank { continue } if t.bullet != nil { anotherBulletV := pixel.V(float64(t.bullet.x), float64(t.bullet.y)).Sub(bulletSpriteRect.Min) anotherBulletRect := bulletSpriteRect.Moved(anotherBulletV) if bulletRect.Intersects(anotherBulletRect) { playerTank.bullet = nil t.bullet = nil return true } } tankRect := t.sprite.Frame() tankV := pixel.V(float64(t.x), float64(t.y)).Sub(tankRect.Min) tankRect = tankRect.Moved(tankV) if !bulletRect.Intersects(tankRect) && !rectContains(tankRect, bulletRect) { continue } if t.state != active { continue } b.state = removed t.state = explodingS + 1 t.bullet = nil g.incrementScore(g.players[playerTank.number]) return true } return false } func (b *bullet) checkBlockingTile(g *game) { checkXLeft, checkYBottom := b.x-b.size[0], b.y-b.size[1] checkXRight, checkYTop := b.x-b.size[0], b.y+b.size[1] closestTilesCenters := [12]int64{ checkXLeft - (checkXLeft % 4), // leftCenterX checkXLeft + 4 - (checkXLeft % 4), // leftCenterX checkXRight - (checkXRight % 4), // rightCenterX checkXRight + 4 - (checkXRight % 4), b.x - (b.x % 4), // rightCenterX b.x + 4 - (b.x % 4), // rightCenterX checkYBottom - (checkYBottom % 4), // bottomCenterY checkYBottom + 4 - (checkYBottom % 4), // topCenterY checkYTop - (checkYTop % 4), // bottomCenterY checkYTop + 4 - (checkYTop % 4), b.y - (b.y % 4), b.y + 4 - (b.y % 4), } bulletRect := b.sprite.Frame() bulletV := pixel.V(float64(b.x), float64(b.y)).Sub(bulletRect.Min) bulletRect = bulletRect.Moved(bulletV) for i := 0; i < 6; i++ { for j := 6; j < 12; j++ { x := closestTilesCenters[i] y := closestTilesCenters[j] yMap, xMap := tileWorldMapByPixel(x, y) if (xMap == 26) || (yMap == 26) || (xMap == -1) || (yMap == -1) || g.world.worldMap[xMap][yMap] == tileEmpty { continue } tileRect := g.sprites.tiles[g.world.worldMap[xMap][yMap]].Frame() tileV := pixel.V(float64(x), float64(y)).Sub(tileRect.Min) tileRect = tileRect.Moved(tileV) switch g.world.worldMap[xMap][yMap] { case tileWater: continue case tileGrass: continue } if !bulletRect.Intersects(tileRect) && !rectContains(tileRect, bulletRect) { continue } b.state = explodingS if g.world.worldMap[xMap][yMap] == tileSteel { continue } if g.port == b.tank.name { g.world.worldMap[xMap][yMap] = tileEmpty } } } } func (b *bullet) moveBullet(g *game, t *tank) { movedPixels := int64(8) if b.direction == right { if b.x+movedPixels >= gameH { b.x = gameH - 1 b.state = explodingS return } b.x = b.x + movedPixels } if b.direction == left { if b.x-movedPixels <= 0 { b.x = 0 b.state = explodingS return } b.x = b.x - movedPixels } if b.direction == up { if b.y+movedPixels >= gameH { b.y = gameH - 1 b.state = explodingS return } b.y = b.y + movedPixels } if b.direction == down { if b.y-movedPixels <= 0 { b.y = 0 b.state = explodingS return } b.y = b.y - movedPixels } if b.checkTankDestroyed(g, t) { return } b.checkBlockingTile(g) } func (t *tank) updateBullet(g *game) { b := t.bullet if b.state == active { b.moveBullet(g, t) } b.checkTankDestroyed(g, t) switch b.state { case explodingS: b.state = explodingM b.sprite = *g.sprites.explosions[0] case explodingM: t.bullet = nil b.sprite = *g.sprites.explosions[1] case removed: t.bullet = nil } b.draw(g.canvas) }
game/bullet.go
0.590779
0.485844
bullet.go
starcoder
package model import ( "encoding/binary" "fmt" "math" ) // Used to down size the frequences to a 9 bit ints // XXX: we could also use 10.7Hz directly const freqStep = MaxFreq / float64(1<<9) // Used to down size the delta times to 14 bit ints (we use 16s as the max duration) const deltaTimeStep = 16 / float64(1<<14) // TableValueSize represents the TableValueSize when encoded in bytes const TableValueSize = 8 // AnchorKey represents a anchor key type AnchorKey struct { // Frequency of the anchor point for the given point's target zone AnchorFreq float64 // Frequency of the given point PointFreq float64 // Delta time between the anchor point and the given point DeltaT float64 } // EncodedKey represents an encoded key type EncodedKey uint32 // NewAnchorKey creates a new anchor key from the given anchor and the given point func NewAnchorKey(anchor, point ConstellationPoint) *AnchorKey { return &AnchorKey{ AnchorFreq: anchor.Freq, PointFreq: point.Freq, // Use absolute just in case anchor is after the target zone DeltaT: math.Abs(point.Time - anchor.Time), } } // Bytes encodes the key in bytes func (ek EncodedKey) Bytes() []byte { // uint32 is 4 bytes bk := make([]byte, 4) binary.LittleEndian.PutUint32(bk, uint32(ek)) return bk } // Encode encodes the anchor key using: // 9 bits for the “frequency of the anchor”: fa // 9 bits for the ” frequency of the point”: fp // 14 bits for the ”delta time between the anchor and the point”: dt // The result is then dt | fa | fp // XXX: this only works if frequencies are coded in 9 bits or less (if we used a 1024 samples FFT, it will be the case) func (tk *AnchorKey) Encode() EncodedKey { // down size params fp := uint32(tk.PointFreq / freqStep) fa := uint32(tk.AnchorFreq / freqStep) dt := uint32(tk.DeltaT / deltaTimeStep) res := fp res |= fa << 9 res |= dt << 23 return EncodedKey(res) } // TableValue represents a table value type TableValue struct { // AnchorTimeMs is the time of the anchor in the related song in milliseconds AnchorTimeMs uint32 // SongID is an ID representing the related song SongID uint32 } // NewTableValue creates a new table value from the given song ID and anchor point func NewTableValue(song uint32, anchor ConstellationPoint) *TableValue { return &TableValue{ AnchorTimeMs: uint32(anchor.Time * 1000), SongID: song, } } // Bytes encodes the given table value in bytes func (tv *TableValue) Bytes() []byte { // Use a uint64 (8 bytes) b := make([]byte, TableValueSize) binary.LittleEndian.PutUint32(b[:4], tv.AnchorTimeMs) binary.LittleEndian.PutUint32(b[4:], tv.SongID) return b } // ValuesFromBytes decodes a list of table values from the given byte array func ValuesFromBytes(b []byte) ([]TableValue, error) { if len(b)%TableValueSize != 0 { return nil, fmt.Errorf("error wrong size for value: %d (got: %v) expected a multiple of %d", len(b), b, TableValueSize) } N := len(b) / TableValueSize res := make([]TableValue, 0, N) for i := 0; i < N; i++ { tv := TableValue{} tv.AnchorTimeMs = binary.LittleEndian.Uint32(b[i*8 : i*8+4]) tv.SongID = binary.LittleEndian.Uint32(b[i*8+4 : (i+1)*8]) res = append(res, tv) } return res, nil } // String returns a string representation of a TableValue func (tv TableValue) String() string { return fmt.Sprintf("(anchor_time_ms: %d, song_id: %d)", tv.AnchorTimeMs, tv.SongID) }
internal/pkg/model/table.go
0.712532
0.546678
table.go
starcoder
package list import "strings" // Head returns the FIRST item in a string-based-list func Head(value string, delimiter string) string { index := strings.Index(value, delimiter) if index == -1 { return value } return value[:index] } // Tail returns any values in the string-based-list AFTER the first item func Tail(value string, delimiter string) string { index := strings.Index(value, delimiter) if index == -1 { return "" } return value[index+1:] } // RemoveLast returns the full list, with the last element removed. func RemoveLast(value string, delimiter string) string { index := strings.LastIndex(value, delimiter) if index == -1 { return "" } return value[:index] } // Last returns the LAST item in a string-based-list func Last(value string, delimiter string) string { index := strings.LastIndex(value, delimiter) if index == -1 { return value } return value[index+len(delimiter):] } // LastDelim returns the LAST item in a string-based-list func LastDelim(value string, delimiter string) string { index := strings.LastIndex(value, delimiter) if index == -1 { return value } return value[index:] } // Split returns the FIRST element, and the REST element in one function call func Split(value string, delimiter string) (string, string) { index := strings.Index(value, delimiter) if index == -1 { return value, "" } return value[:index], value[index+len(delimiter):] } // SplitTail behaves like Split, but splits the beginning of the list from the last item in the list. So, the list "a,b,c" => "a,b", "c" func SplitTail(value string, delimiter string) (string, string) { index := strings.LastIndex(value, delimiter) if index == -1 { return value, "" } return value[:index], value[index+len(delimiter):] } // At returns the list vaue at a particular index func At(value string, delimiter string, index int) string { if index == 0 { return Head(value, delimiter) } tail := Tail(value, delimiter) if tail == "" { return "" } return At(tail, delimiter, index-1) } // PushHead adds a new item to the beginning of the list func PushHead(value string, newValue string, delimiter string) string { if len(value) == 0 { return newValue } return newValue + delimiter + value } // PushTail adds a new item to the end of the list func PushTail(value string, newValue string, delimiter string) string { if len(value) == 0 { return newValue } return value + delimiter + newValue }
list.go
0.766992
0.524029
list.go
starcoder
package runtime import ( "math" "sort" "sync" "github.com/rcrowley/go-metrics" ) // Initial slice capacity for the values stored in a ResettingHistogram const InitialResettingHistogramSliceCap = 10 // newResettingHistogram constructs a new StandardResettingHistogram func newResettingHistogram() Histogram { if metrics.UseNilMetrics { return nilResettingHistogram{} } return &standardResettingHistogram{ values: make([]int64, 0, InitialResettingHistogramSliceCap), } } // nilResettingHistogram is a no-op ResettingHistogram. type nilResettingHistogram struct { } // Values is a no-op. func (nilResettingHistogram) Values() []int64 { return nil } // Snapshot is a no-op. func (nilResettingHistogram) Snapshot() Histogram { return &resettingHistogramSnapshot{ values: []int64{}, } } // Update is a no-op. func (nilResettingHistogram) Update(int64) {} // Clear is a no-op. func (nilResettingHistogram) Clear() {} func (nilResettingHistogram) Count() int64 { return 0 } func (nilResettingHistogram) Variance() float64 { return 0.0 } func (nilResettingHistogram) Min() int64 { return 0 } func (nilResettingHistogram) Max() int64 { return 0 } func (nilResettingHistogram) Sum() int64 { return 0 } func (nilResettingHistogram) StdDev() float64 { return 0.0 } func (nilResettingHistogram) Sample() Sample { return metrics.NilSample{} } func (nilResettingHistogram) Percentiles([]float64) []float64 { return nil } func (nilResettingHistogram) Percentile(float64) float64 { return 0.0 } func (nilResettingHistogram) Mean() float64 { return 0.0 } // standardResettingHistogram is used for storing aggregated values for timers, which are reset on every flush interval. type standardResettingHistogram struct { values []int64 mutex sync.Mutex } func (t *standardResettingHistogram) Count() int64 { panic("Count called on a resetting histogram; capture a snapshot first") } func (t *standardResettingHistogram) Max() int64 { panic("Max called on a resetting histogram; capture a snapshot first") } func (t *standardResettingHistogram) Min() int64 { panic("Min called on a resetting histogram; capture a snapshot first") } func (t *standardResettingHistogram) StdDev() float64 { panic("StdDev called on a resetting histogram; capture a snapshot first") } func (t *standardResettingHistogram) Variance() float64 { panic("Variance called on a resetting histogram; capture a snapshot first") } func (t *standardResettingHistogram) Sum() int64 { panic("Sum called on a resetting histogram; capture a snapshot first") } func (t *standardResettingHistogram) Sample() Sample { panic("Sample called on a resetting histogram; capture a snapshot first") } func (t *standardResettingHistogram) Percentiles([]float64) []float64 { panic("Percentiles called on a resetting histogram; capture a snapshot first") } func (t *standardResettingHistogram) Percentile(float64) float64 { panic("Percentile called on a resetting histogram; capture a snapshot first") } func (t *standardResettingHistogram) Mean() float64 { panic("Mean called on a resetting histogram; capture a snapshot first") } // Values returns a slice with all measurements. func (t *standardResettingHistogram) Values() []int64 { return t.values } // Snapshot resets the timer and returns a read-only copy of its sorted contents. func (t *standardResettingHistogram) Snapshot() Histogram { t.mutex.Lock() defer t.mutex.Unlock() currentValues := t.values t.values = make([]int64, 0, InitialResettingHistogramSliceCap) sort.Slice(currentValues, func(i, j int) bool { return currentValues[i] < currentValues[j] }) return &resettingHistogramSnapshot{ values: currentValues, } } func (t *standardResettingHistogram) Clear() { t.mutex.Lock() defer t.mutex.Unlock() t.values = t.values[:0] } // Record the duration of an event. func (t *standardResettingHistogram) Update(d int64) { t.mutex.Lock() defer t.mutex.Unlock() t.values = append(t.values, d) } // resettingHistogramSnapshot is a point-in-time copy of another resettingHistogram. type resettingHistogramSnapshot struct { sync.Mutex values []int64 mean float64 calculated bool } // resettingHistogramSnapshot returns the snapshot. func (t *resettingHistogramSnapshot) Snapshot() Histogram { return t } func (*resettingHistogramSnapshot) Update(int64) { panic("Update called on a resetting histogram snapshot") } func (t *resettingHistogramSnapshot) Clear() { panic("Clear called on a resetting histogram snapshot") } func (t *resettingHistogramSnapshot) Sample() Sample { panic("Sample called on a resetting histogram snapshot") } func (t *resettingHistogramSnapshot) Count() int64 { t.Lock() defer t.Unlock() return int64(len(t.values)) } // Values returns all values from snapshot. func (t *resettingHistogramSnapshot) Values() []int64 { t.Lock() defer t.Unlock() return t.values } func (t *resettingHistogramSnapshot) Min() int64 { t.Lock() defer t.Unlock() if len(t.values) > 0 { return t.values[0] } return 0 } func (t *resettingHistogramSnapshot) Variance() float64 { t.Lock() defer t.Unlock() if len(t.values) == 0 { return 0.0 } m := t._mean() var sum float64 for _, v := range t.values { d := float64(v) - m sum += d * d } return sum / float64(len(t.values)) } func (t *resettingHistogramSnapshot) Max() int64 { t.Lock() defer t.Unlock() if len(t.values) > 0 { return t.values[len(t.values)-1] } return 0 } func (t *resettingHistogramSnapshot) StdDev() float64 { return math.Sqrt(t.Variance()) } func (t *resettingHistogramSnapshot) Sum() int64 { t.Lock() defer t.Unlock() var sum int64 for _, v := range t.values { sum += v } return sum } // Percentile returns the boundaries for the input percentiles. func (t *resettingHistogramSnapshot) Percentile(percentile float64) float64 { t.Lock() defer t.Unlock() tb := t.calc([]float64{percentile}) return tb[0] } // Percentiles returns the boundaries for the input percentiles. func (t *resettingHistogramSnapshot) Percentiles(percentiles []float64) []float64 { t.Lock() defer t.Unlock() tb := t.calc(percentiles) return tb } // Mean returns the mean of the snapshotted values func (t *resettingHistogramSnapshot) Mean() float64 { t.Lock() defer t.Unlock() return t._mean() } func (t *resettingHistogramSnapshot) _mean() float64 { if !t.calculated { _ = t.calc([]float64{}) } return t.mean } func (t *resettingHistogramSnapshot) calc(percentiles []float64) (thresholdBoundaries []float64) { count := len(t.values) if count == 0 { thresholdBoundaries = make([]float64, len(percentiles)) t.mean = 0 t.calculated = true return } min := t.values[0] max := t.values[count-1] cumulativeValues := make([]int64, count) cumulativeValues[0] = min for i := 1; i < count; i++ { cumulativeValues[i] = t.values[i] + cumulativeValues[i-1] } thresholdBoundaries = make([]float64, len(percentiles)) thresholdBoundary := max for i, pct := range percentiles { if count > 1 { var abs float64 if pct >= 0 { abs = pct } else { abs = 100 + pct } // poor man's math.Round(x): // math.Floor(x + 0.5) indexOfPerc := int(math.Floor(((abs / 100.0) * float64(count)) + 0.5)) if pct >= 0 && indexOfPerc > 0 { indexOfPerc -= 1 // index offset=0 } thresholdBoundary = t.values[indexOfPerc] } thresholdBoundaries[i] = float64(thresholdBoundary) } sum := cumulativeValues[count-1] t.mean = float64(sum) / float64(count) t.calculated = true return }
runtime/resetting_histogram.go
0.848941
0.71144
resetting_histogram.go
starcoder
package main import ( "fmt" "math" ) type MatrixPoint [2]uint64 //--------------------------------------------------------------------------------------- const ROW = 1000 //--------------------------------------------------------------------------------------- type GeoMatrixData struct { polygon Polygon data float64 } //--------------------------------------------------------------------------------------- const ( GeoMatrixAccuracyHigh = 0 GeoMatrixAccuracyMedium = 1 GeoMatrixAccuracyLow = 2 ) //--------------------------------------------------------------------------------------- type GeoMatrix struct { bBox Rectangle pMap map[MatrixPoint][]*GeoMatrixData items []GeoMatrixData } //--------------------------------------------------------------------------------------- func (thisPt *GeoMatrix) GetMultiPolygonWKT(point MatrixPoint, extPoint *Point) string { polyList := thisPt.pMap[point] if polyList == nil { return "" } out := "GEOMETRYCOLLECTION(" for i, p := range polyList { if i > 0 { out += "," } out += p.polygon.GetWKTString() } if extPoint != nil { out += "," + extPoint.GetWKTString() } out += ")" return out } //--------------------------------------------------------------------------------------- func (thisPt *GeoMatrix) GetPointMosaic(point MatrixPoint) string { polyList := thisPt.pMap[point] if polyList == nil { return "" } tmpMap := make(map[MatrixPoint]bool) for _, p := range polyList { rect := p.polygon.GetBoundingBox() start := thisPt.GetMatrixPoint(&rect.start) end := thisPt.GetMatrixPoint(&rect.end) for x := start[0]; x <= end[0]; x++ { for y := start[1]; y <= end[1]; y++ { tmpMap[MatrixPoint{x, y}] = true } } } cnt := 0 out := "GEOMETRYCOLLECTION(" for k, _ := range tmpMap { if cnt > 0 { out += "," } cnt++ rect := thisPt.GetCellLatLong(k) out += rect.GetWKTString() } out += ")" return out } //--------------------------------------------------------------------------------------- func (thisPt *GeoMatrix) GetMatrixPoint(in *Point) MatrixPoint { ext := thisPt.bBox.GetLength() slotX := (ext.GetX() / ROW) slotY := (ext.GetY() / ROW) x := ((in.GetX() - thisPt.bBox.GetStart().GetX()) / slotX) y := ((in.GetY() - thisPt.bBox.GetStart().GetY()) / slotY) x = math.Min(x, ROW-1) y = math.Min(y, ROW-1) return MatrixPoint{uint64(x), uint64(y)} } //--------------------------------------------------------------------------------------- func (thisPt *GeoMatrix) CoverArea(start MatrixPoint, end MatrixPoint, itemInfo *GeoMatrixData) { for x := start[0]; x <= end[0]; x++ { for y := start[1]; y <= end[1]; y++ { point := MatrixPoint{x, y} thisPt.pMap[point] = append(thisPt.pMap[point], itemInfo) } } } //--------------------------------------------------------------------------------------- func (thisPt *GeoMatrix) Add(poly Polygon, data float64) { rect := poly.GetBoundingBox() if len(thisPt.items) == 0 { thisPt.bBox = *rect } else { thisPt.bBox.Add(rect) } thisPt.items = append(thisPt.items, GeoMatrixData{poly, data}) } //--------------------------------------------------------------------------------------- func (thisPt *GeoMatrix) Build() { for i := range thisPt.items { rect := thisPt.items[i].polygon.GetBoundingBox() start := thisPt.GetMatrixPoint(rect.GetStart()) end := thisPt.GetMatrixPoint(rect.GetEnd()) thisPt.CoverArea(start, end, &thisPt.items[i]) } } //--------------------------------------------------------------------------------------- func (thisPt *GeoMatrix) Query(point *Point, acc int, maxCount int) []float64 { mPoint := thisPt.GetMatrixPoint(point) items := thisPt.pMap[mPoint] out := []float64{} if items == nil { return nil } if len(items) == 1 { out = append(out, items[0].data) return out } for i := range items { if len(out) == maxCount { return out } switch acc { case GeoMatrixAccuracyHigh: { if items[i].polygon.PointIsInside(point) { out = append(out, items[i].data) return out } } case GeoMatrixAccuracyMedium: { if items[i].polygon.GetBoundingBox().PointInside(point) { out = append(out, items[i].data) } } default: { out = append(out, items[i].data) } } } return out } //--------------------------------------------------------------------------------------- func (thisPt *GeoMatrix) GetCellLatLong(cell MatrixPoint) Rectangle { ext := thisPt.bBox.GetLength() slotX := (ext.GetX() / ROW) slotY := (ext.GetY() / ROW) start := Point{thisPt.bBox.start.x + (float64(cell[0]) * slotX), thisPt.bBox.start.y + (float64(cell[1]) * slotY)} end := Point{start.GetX() + slotX, start.GetY() + slotY} return Rectangle{start, end} } //--------------------------------------------------------------------------------------- func (thisPt *GeoMatrix) DumpStat() { maxPoint := MatrixPoint{} sampleO1Point := MatrixPoint{} maxLen := 0 oOnePoints := 0 //extract some info for k, p := range thisPt.pMap { if len(p) > maxLen { maxPoint = k maxLen = len(p) } if len(p) == 1 { oOnePoints++ sampleO1Point = k } } maxRect := thisPt.GetCellLatLong(maxPoint) o1Rect := thisPt.GetCellLatLong(sampleO1Point) oOnePoints += (ROW * ROW) - len(thisPt.pMap) data := ` Total Cell : %d Max M : %d POL Max Cell Info : %s Max Cell Pol : %s Max Cell Mosaic : %s O(1) : %d Sample O(1) Rect : %s Sample O(1) Pol : %s Sample O(1) Mosaic : %s ` fmt.Printf(data, len(thisPt.pMap), maxLen, maxRect.GetWKTString(), thisPt.GetMultiPolygonWKT(maxPoint, nil), thisPt.GetPointMosaic(maxPoint), oOnePoints, o1Rect.GetWKTString(), thisPt.GetMultiPolygonWKT(sampleO1Point, nil), thisPt.GetPointMosaic(sampleO1Point), ) } //--------------------------------------------------------------------------------------- func (thisPt *GeoMatrix) GetResultWKT(pt *Point, acc int) string { mPoint := thisPt.GetMatrixPoint(pt) items := thisPt.pMap[mPoint] matchList := []Polygon{} if items == nil { return "" } for i := range items { item := items[i] if acc == GeoMatrixAccuracyHigh { if item.polygon.PointIsInside(pt) { matchList = append(matchList, item.polygon) break } } else if acc == GeoMatrixAccuracyMedium { if item.polygon.GetBoundingBox().PointInside(pt) { matchList = append(matchList, item.polygon) } } else { matchList = append(matchList, item.polygon) } } out := "GEOMETRYCOLLECTION(" for i, p := range matchList { if i > 0 { out += "," } out += p.GetWKTString() } out += "," + pt.GetWKTString() out += ")" return out } //--------------------------------------------------------------------------------------- func CreateMatrix() *GeoMatrix { matrix := new(GeoMatrix) matrix.pMap = make(map[MatrixPoint][]*GeoMatrixData) return matrix }
go/GeoMatrix.go
0.503906
0.472014
GeoMatrix.go
starcoder
// Package slicer provides an easy API to slice a stream of bytes using a custom slice of indicies. package slicer import ( "fmt" ) // Slicer provides an easy API to slice a stream of bytes. type Slicer struct { indicies []int strict bool // strict mode } // New returns a new slicer that slices an input stream of bytes using the given indicies. // If strict is false, then any data contained entirely within the given bounds is returned, rather than an error. func New(strict bool, indicies ...int) (*Slicer, error) { if len(indicies) > 2 { return nil, fmt.Errorf("invalid number of indicies %d", len(indicies)) } return &Slicer{strict: strict, indicies: indicies}, nil } func (s Slicer) strictSliceString(in string) (string, error) { if len(s.indicies) == 2 { start := s.indicies[0] if start < 0 { start = len(in) + start } if start < 0 { return "", fmt.Errorf("when in strict mode, start index %d (%d) must be greater than or equal to zero", s.indicies[0], start) } end := s.indicies[1] if end < 0 { end = len(in) + end } if end < start { return "", fmt.Errorf("start index %d (%d) must be before end index %d (%d)", s.indicies[0], start, s.indicies[1], end) } if end > len(in) { return "", fmt.Errorf("when in strict mode, end index %d (%d) cannot be greater than the length of the input string %q (%d)", s.indicies[1], end, in, len(in)) } return in[start:end], nil } if len(s.indicies) == 1 { start := s.indicies[0] if start < 0 { return "", fmt.Errorf("when in strict mode, start index %d (%d) must be greater than or equal to zero", s.indicies[0], start) } if start > len(in)-1 { return "", fmt.Errorf("when in strict mode, start index %d (%d) cannot be greater than the length of the input string %q (%d) minus 1", s.indicies[0], start, in, len(in)) } return in[start:], nil } return in[:], nil } func (s Slicer) looseSliceString(in string) (string, error) { if len(s.indicies) == 2 { start := s.indicies[0] if start < 0 { start = len(in) + start } end := s.indicies[1] if end < 0 { end = len(in) + end } if end < start { return "", fmt.Errorf("start index %d (%d) must be before end index %d (%d)", s.indicies[0], start, s.indicies[1], end) } if start < 0 { start = 0 } if start > len(in) { return "", nil } if end < 0 { return "", nil } if end > len(in) { return in[start:], nil } return in[start:end], nil } if len(s.indicies) == 1 { start := s.indicies[0] if start < 0 { start = len(in) + start } if start < 0 { start = 0 } if start > len(in)-1 { return "", nil } return in[start:], nil } return in[:], nil } // SliceString returns the sliced version of the given string. func (s Slicer) SliceString(in string) (string, error) { if s.strict { return s.strictSliceString(in) } return s.looseSliceString(in) } // MustSliceString returns the sliced version of the given string and panics if there is an error. func (s Slicer) MustSliceString(in string) string { out, err := s.SliceString(in) if err != nil { panic(err) } return out } func (s Slicer) strictSliceBytes(in []byte) ([]byte, error) { if len(s.indicies) == 2 { start := s.indicies[0] if start < 0 { start = len(in) + start } if start < 0 { return make([]byte, 0), fmt.Errorf("when in strict mode, start index %d (%d) must be greater than or equal to zero", s.indicies[0], start) } end := s.indicies[1] if end < 0 { end = len(in) + end } if end < start { return make([]byte, 0), fmt.Errorf("start index %d (%d) must be before end index %d (%d)", s.indicies[0], start, s.indicies[1], end) } if end > len(in) { return make([]byte, 0), fmt.Errorf("when in strict mode, end index %d (%d) cannot be greater than the length of the input bytes %q (%d)", s.indicies[1], end, in, len(in)) } return in[start:end], nil } if len(s.indicies) == 1 { start := s.indicies[0] if start < 0 { start = len(in) + start } if start < 0 { return make([]byte, 0), fmt.Errorf("when in strict mode, start index %d (%d) must be greater than or equal to zero", s.indicies[0], start) } if start > len(in)-1 { return make([]byte, 0), fmt.Errorf("when in strict mode, start index %d (%d) cannot be greater than the length of the input bytes %q (%d) minus 1", s.indicies[0], start, in, len(in)) } return in[start:], nil } return in[:], nil } func (s Slicer) looseSliceBytes(in []byte) ([]byte, error) { if len(s.indicies) == 2 { start := s.indicies[0] if start < 0 { start = len(in) + start } end := s.indicies[1] if end < 0 { end = len(in) + end } if end < start { return make([]byte, 0), fmt.Errorf("start index %d (%d) must be before end index %d (%d)", s.indicies[0], start, s.indicies[1], end) } if start > len(in) { return make([]byte, 0), nil } if end < 0 { return make([]byte, 0), nil } if start < 0 { start = 0 } if end > len(in) { return in[start:], nil } return in[start:end], nil } if len(s.indicies) == 1 { start := s.indicies[0] if start < 0 { start = len(in) + start } if start < 0 { start = 0 } if start > len(in)-1 { return make([]byte, 0), nil } return in[start:], nil } return in[:], nil } // SliceBytes returns the sliced version of the given slice of bytes. func (s Slicer) SliceBytes(in []byte) ([]byte, error) { if s.strict { return s.strictSliceBytes(in) } return s.looseSliceBytes(in) } // MustSliceBytes returns the sliced version of the given slice of bytes and panics if there is an error. func (s Slicer) MustSliceBytes(in []byte) []byte { out, err := s.SliceBytes(in) if err != nil { panic(err) } return out } // Slice returns the sliced version of the given slice of bytes. func (s Slicer) Slice(in interface{}) (interface{}, error) { switch x := in.(type) { case string: return s.SliceString(x) case *string: return s.SliceString(*x) case []byte: return s.SliceBytes(x) case *[]byte: return s.SliceBytes(*x) } return nil, fmt.Errorf("unknown type %T", in) } // MustSlice returns the sliced version of the given slice of bytes and panics if there is an error. func (s Slicer) MustSlice(in interface{}) interface{} { switch x := in.(type) { case string: return s.MustSliceString(x) case *string: return s.MustSliceString(*x) case []byte: return s.MustSliceBytes(x) case *[]byte: return s.MustSliceBytes(*x) } panic(fmt.Errorf("unknown type %T", in)) }
pkg/slicer/Slicer.go
0.751101
0.672091
Slicer.go
starcoder
package gofuncs import ( "fmt" "math/big" "math/cmplx" "reflect" ) const ( indexOfErrorMsg = "slc must be a slice" valueOfKeyErrorMsg = "mp must be a map" filterErrorMsg = "fn must be a non-nil function of one argument of any type that returns bool" lessThanErrorMsg = "val must be a lessable type" mapErrorMsg = "fn must be a non-nil function of one argument of any type that returns one value of any type" mapToErrorMsg = "fn must be a non-nil function of one argument of any type that returns one value convertible to type %s" supplierErrorMsg = "fn must be a non-nil function of no arguments or a single variadic argument that returns one value of any type" supplierOfErrorMsg = "fn must be a non-nil function of no arguments or a single variadic argument that returns one value convertible to type %s" consumerErrorMsg = "fn must be a non-nil funciton of one argument of any type and no return values" sortErrorMsg = "fn must be a non-nil function of two arguments of the same type and return bool" ) // IndexOf returns the first of the following given an array or slice, index, and optional default value: // 1. slice[index] if the array or slice length > index // 2. default value if provided, converted to array or slice element type // 3. zero value of array or slice element type // Panics if arrslc is not an array or slice. // Panics if the default value is not convertible to the array or slice element type, even if it is not needed. func IndexOf(arrslc interface{}, index uint, defalt ...interface{}) interface{} { rv := reflect.ValueOf(arrslc) switch rv.Kind() { case reflect.Array: case reflect.Slice: default: panic(indexOfErrorMsg) } elementTyp := rv.Type().Elem() // Always ensure if default is provided that it is convertible to slice element type var rdf reflect.Value if len(defalt) > 0 { rdf = reflect.ValueOf(defalt[0]).Convert(elementTyp) } // Return index if it exists idx := int(index) if rv.Len() > idx { return rv.Index(idx).Interface() } // Else return default if provided if rdf.IsValid() { return rdf.Interface() } // Else return zero value of array or slice element type return reflect.Zero(elementTyp).Interface() } // ValueOfKey returns the first of the following: // 1. map[key] if the key exists in the map // 2. default if provided // 3. zero value of map value type // Panics if mp is not a map. // Panics if the default value is not convertible to map value type, even if it is not needed. func ValueOfKey(mp interface{}, key interface{}, defalt ...interface{}) interface{} { rv := reflect.ValueOf(mp) if rv.Kind() != reflect.Map { panic(valueOfKeyErrorMsg) } elementTyp := rv.Type().Elem() // Always ensure if default is provided that it is convertible to map value type var rdf reflect.Value if len(defalt) > 0 { rdf = reflect.ValueOf(defalt[0]).Convert(elementTyp) } // Return key value if it exists for mr := rv.MapRange(); mr.Next(); { if mr.Key().Interface() == key { return mr.Value().Interface() } } // Else return default if provided if rdf.IsValid() { return rdf.Interface() } // Else return zero value of map value type return reflect.Zero(elementTyp).Interface() } // Filter (fn) adapts a func(any) bool into a func(interface{}) bool. // If fn happens to be a func(interface{}) bool, it is returned as is. // Otherwise, each invocation converts the arg passed to the type the func receives. func Filter(fn interface{}) func(interface{}) bool { // Return fn as is if it is desired type if res, isa := fn.(func(interface{}) bool); isa { return res } vfn := reflect.ValueOf(fn) if (vfn.Kind() != reflect.Func) || vfn.IsNil() { panic(filterErrorMsg) } typ := vfn.Type() if (typ.NumIn() != 1) || (typ.NumOut() != 1) || (typ.Out(0).Kind() != reflect.Bool) { panic(filterErrorMsg) } argTyp := typ.In(0) return func(arg interface{}) bool { var ( argVal = reflect.ValueOf(arg).Convert(argTyp) resVal = vfn.Call([]reflect.Value{argVal})[0].Bool() ) return resVal } } // FilterAll (fns) adapts any number of func(any) bool into a slice of func(interface{}) bool. // Each func passed is separately adapted using Filter into the corresponding slice element of the result. // FIlterAll is the basis for composing multiple logic functions into a single logic function. // Note that when calling the provided set of logic functions, the argument type must be compatible with all of them. // The most likely failure case is mixing funcs that accept interface{} that type assert the argument with funcs that accept a specific type. func FilterAll(fns ...interface{}) []func(interface{}) bool { // Create adapters adaptedFns := make([]func(interface{}) bool, len(fns)) for i, fn := range fns { adaptedFns[i] = Filter(fn) } return adaptedFns } // And (fns) any number of func(any)bool into the conjunction of all the funcs. // Short-circuit logic will return false on the first function that returns false. func And(fns ...interface{}) func(interface{}) bool { adaptedFns := FilterAll(fns...) return func(val interface{}) bool { for _, fn := range adaptedFns { if !fn(val) { return false } } return true } } // Or (fns) any number of func(any)bool into the disjunction of all the funcs. // Short-circuit logic will return true on the first function that returns true. func Or(fns ...interface{}) func(interface{}) bool { adaptedFns := FilterAll(fns...) return func(val interface{}) bool { for _, fn := range adaptedFns { if fn(val) { return true } } return false } } // Not (fn) adapts a func(any) bool to the negation of the func. func Not(fn interface{}) func(interface{}) bool { adaptedFn := Filter(fn) return func(val interface{}) bool { return !adaptedFn(val) } } // EqualTo (val) returns a func(interface{}) bool that returns true if the func arg is equal to val. // The arg is converted to the type of val first, then compared. // If val is nil, then the arg type must be convertible to the type of val. // If val is an untyped nil, then the arg must be an untyped nil. // Comparison is made using == operator. // If val is not comparable using == (eg, slices are not comparable), the result will be true if val and arg have the same address. func EqualTo(val interface{}) func(interface{}) bool { var ( valIsNil = IsNil(val) valTyp = reflect.TypeOf(val) ) return func(arg interface{}) bool { argTyp := reflect.TypeOf(arg) if valTyp == nil { // val is an untyped nil return argTyp == nil } // Remaining comparisons require arg to be convertible to val type if (argTyp == nil) || (!argTyp.ConvertibleTo(valTyp)) { return false } if valIsNil { // val is a typed nil, and arg is a convertible type return IsNil(arg) } if !valTyp.Comparable() { // val cannot be compared using == return fmt.Sprintf("%p", val) == fmt.Sprintf("%p", arg) } // val is non-nil, and arg is a possibly nil value of a convertible type return (!IsNil(arg)) && (val == reflect.ValueOf(arg).Convert(valTyp).Interface()) } } // DeepEqualTo (val) returns a func(interface{}) bool that returns true if the func arg is deep equal to val. // The arg is converted to the type of val first, then compared. // If val is nil, then the arg type must be convertible to the type of val. // If val is an untyped nil, then the arg must be an untyped nil. // Comparison is made using reflect.DeepEqual. func DeepEqualTo(val interface{}) func(interface{}) bool { var ( valIsNil = IsNil(val) valTyp = reflect.TypeOf(val) ) return func(arg interface{}) bool { argTyp := reflect.TypeOf(arg) if valTyp == nil { // val is an untyped nil return argTyp == nil } // Remaining comparisons require arg to be convertible to val type if (argTyp == nil) || (!argTyp.ConvertibleTo(valTyp)) { return false } if valIsNil { // val is a typed nil, and arg is a convertible type return IsNil(arg) } // val is non-nil, and arg is a possibly nil value of a convertible type return (!IsNil(arg)) && reflect.DeepEqual(val, reflect.ValueOf(arg).Convert(valTyp).Interface()) } } // IsLessableKind returns if if kind represents any numeric type or string func IsLessableKind(kind reflect.Kind) bool { return ((kind >= reflect.Int) && (kind <= reflect.Float64) || (kind == reflect.String)) } // LessThan (val) returns a func(val1, val2 interface{}) bool that returns true if val1 < val2. // The args are converted to the type of val first, then compared. // Panics if val is nil or IsLessableKind(kind of val) is false. func LessThan(val interface{}) func(val1, val2 interface{}) bool { if IsNil(val) { panic(lessThanErrorMsg) } kind := reflect.ValueOf(val).Kind() if !IsLessableKind(kind) { panic(lessThanErrorMsg) } switch kind { case reflect.Int: fallthrough case reflect.Int8: fallthrough case reflect.Int16: fallthrough case reflect.Int32: fallthrough case reflect.Int64: typ := reflect.TypeOf(int64(0)) return func(val1, val2 interface{}) bool { return reflect.ValueOf(val1).Convert(typ).Int() < reflect.ValueOf(val2).Convert(typ).Int() } case reflect.Uint: fallthrough case reflect.Uint8: fallthrough case reflect.Uint16: fallthrough case reflect.Uint32: fallthrough case reflect.Uint64: typ := reflect.TypeOf(uint64(0)) return func(val1, val2 interface{}) bool { return reflect.ValueOf(val1).Convert(typ).Uint() < reflect.ValueOf(val2).Convert(typ).Uint() } case reflect.Float32: fallthrough case reflect.Float64: typ := reflect.TypeOf(float64(0.0)) return func(val1, val2 interface{}) bool { return reflect.ValueOf(val1).Convert(typ).Float() < reflect.ValueOf(val2).Convert(typ).Float() } // Must be string default: typ := reflect.TypeOf("") return func(val1, val2 interface{}) bool { return fmt.Sprintf("%s", reflect.ValueOf(val1).Convert(typ)) < fmt.Sprintf("%s", reflect.ValueOf(val2).Convert(typ)) } } } // IsLessThan returns a func(arg interface{}) bool that returns true if arg < val func IsLessThan(val interface{}) func(interface{}) bool { lt := LessThan(val) return func(arg interface{}) bool { return lt(arg, val) } } // LessThanEquals (val) returns a func(val1, val2 interface{}) bool that returns true if val1 <= val2. // The args are converted to the type of val first, then compared. // Panics if val is nil or IsLessableKind(kind of val) is false. func LessThanEquals(val interface{}) func(val1, val2 interface{}) bool { if IsNil(val) { panic(lessThanErrorMsg) } kind := reflect.ValueOf(val).Kind() if !IsLessableKind(kind) { panic(lessThanErrorMsg) } switch kind { case reflect.Int: fallthrough case reflect.Int8: fallthrough case reflect.Int16: fallthrough case reflect.Int32: fallthrough case reflect.Int64: typ := reflect.TypeOf(int64(0)) return func(val1, val2 interface{}) bool { return reflect.ValueOf(val1).Convert(typ).Int() <= reflect.ValueOf(val2).Convert(typ).Int() } case reflect.Uint: fallthrough case reflect.Uint8: fallthrough case reflect.Uint16: fallthrough case reflect.Uint32: fallthrough case reflect.Uint64: typ := reflect.TypeOf(uint64(0)) return func(val1, val2 interface{}) bool { return reflect.ValueOf(val1).Convert(typ).Uint() <= reflect.ValueOf(val2).Convert(typ).Uint() } case reflect.Float32: fallthrough case reflect.Float64: typ := reflect.TypeOf(float64(0.0)) return func(val1, val2 interface{}) bool { return reflect.ValueOf(val1).Convert(typ).Float() <= reflect.ValueOf(val2).Convert(typ).Float() } // Must be string default: typ := reflect.TypeOf("") return func(val1, val2 interface{}) bool { return fmt.Sprintf("%s", reflect.ValueOf(val1).Convert(typ)) <= fmt.Sprintf("%s", reflect.ValueOf(val2).Convert(typ)) } } } // IsLessThanEquals returns a func(arg interface{}) bool that returns true if arg <= val func IsLessThanEquals(val interface{}) func(interface{}) bool { lte := LessThanEquals(val) return func(arg interface{}) bool { return lte(arg, val) } } // GreaterThan (val) returns a func(val1, val2 interface{}) bool that returns true if val1 > val2. // The args are converted to the type of val first, then compared. // Panics if val is nil or IsLessableKind(kind of val) is false. func GreaterThan(val interface{}) func(val1, val2 interface{}) bool { lte := LessThanEquals(val) return func(val1, val2 interface{}) bool { return !lte(val1, val2) } } // IsGreaterThan returns a func(arg interface{}) bool that returns true if arg > val func IsGreaterThan(val interface{}) func(interface{}) bool { gt := GreaterThan(val) return func(arg interface{}) bool { return gt(arg, val) } } // GreaterThanEquals (val) returns a func(val1, val2 interface{}) bool that returns true if val1 >= val2. // The args are converted to the type of val first, then compared. // Panics if val is nil or IsLessableKind(kind of val) is false. func GreaterThanEquals(val interface{}) func(val1, val2 interface{}) bool { lt := LessThan(val) return func(val1, val2 interface{}) bool { return !lt(val1, val2) } } // IsGreaterThanEquals returns a func(arg interface{}) bool that returns true if arg >= val func IsGreaterThanEquals(val interface{}) func(interface{}) bool { gte := GreaterThanEquals(val) return func(arg interface{}) bool { return gte(arg, val) } } // IsNegative (val) returns true if the val < 0 func IsNegative(val interface{}) bool { return LessThan(val)(val, 0) } // IsNonNegative (val) returns true if val >= 0 func IsNonNegative(val interface{}) bool { return GreaterThanEquals(val)(val, 0) } // IsPositive (val) returns true if val > 0 func IsPositive(val interface{}) bool { return GreaterThan(val)(val, 0) } // IsNil is a func(interface{}) bool that returns true if val is nil func IsNil(val interface{}) bool { if IsNilable(val) { rv := reflect.ValueOf(val) return (!rv.IsValid()) || rv.IsNil() } return false } // IsNilable is a func(interface{}) bool that returns true if val is nil or the type of val is a nilable type. // Returns true of the reflect.Kind of val is Chan, Func, Interface, Map, Ptr, or Slice. func IsNilable(val interface{}) bool { rv := reflect.ValueOf(val) if !rv.IsValid() { return true } k := rv.Type().Kind() return (k >= reflect.Chan) && (k <= reflect.Slice) } // Map (fn) adapts a func(any) any into a func(interface{}) interface{}. // If fn happens to be a func(interface{}) interface{}, it is returned as is. // Otherwise, each invocation converts the arg passed to the type the func receives. func Map(fn interface{}) func(interface{}) interface{} { // Return fn as is if it is desired type if res, isa := fn.(func(interface{}) interface{}); isa { return res } vfn := reflect.ValueOf(fn) if (vfn.Kind() != reflect.Func) || vfn.IsNil() { panic(mapErrorMsg) } typ := vfn.Type() if (typ.NumIn() != 1) || (typ.NumOut() != 1) { panic(mapErrorMsg) } argTyp := typ.In(0) return func(arg interface{}) interface{} { var ( argVal = reflect.ValueOf(arg).Convert(argTyp) resVal = vfn.Call([]reflect.Value{argVal})[0].Interface() ) return resVal } } // MapTo (fn, X) adapts a func(any) X' into a func(interface{}) X. // If fn happens to be a func(interface{}) X, it is returned as is. // Otherwise, each invocation converts the arg passed to the type the func receives, and type X' must be convertible to X. // The result will have to be type asserted by the caller. func MapTo(fn interface{}, val interface{}) interface{} { // val cannot be nil if IsNil(val) { panic("val cannot be nil") } // Verify val is a non-interface type var ( xval = reflect.ValueOf(val) xtyp = xval.Type() ) if xval.Kind() == reflect.Interface { panic("val cannot be an interface{} value") } // Verify fn has is a non-nil func of 1 parameter and 1 result var ( vfn = reflect.ValueOf(fn) errMsg = fmt.Sprintf(mapToErrorMsg, xtyp) ) if (vfn.Kind() != reflect.Func) || vfn.IsNil() { panic(errMsg) } // The func has to accept 1 arg and return 1 type typ := vfn.Type() if (typ.NumIn() != 1) || (typ.NumOut() != 1) { panic(errMsg) } var ( argTyp = typ.In(0) resTyp = typ.Out(0) ) // Return fn as is if it is desired type if (argTyp.Kind() == reflect.Interface) && (resTyp == xtyp) { return fn } // If fn returns any type convertible to X, then generate a function of interface{} to exactly X if !resTyp.ConvertibleTo(xtyp) { panic(errMsg) } return reflect.MakeFunc( reflect.FuncOf( []reflect.Type{reflect.TypeOf((*interface{})(nil)).Elem()}, []reflect.Type{xtyp}, false, ), func(args []reflect.Value) []reflect.Value { var ( argVal = reflect.ValueOf(args[0].Interface()).Convert(argTyp) resVal = vfn.Call([]reflect.Value{argVal})[0].Convert(xtyp) ) return []reflect.Value{resVal} }, ).Interface() } // ConvertTo generates a func(interface{}) interface{} that converts a value into the same type as the value passed. // Eg, ConvertTo(int8(0)) converts a func that converts a value into an int8. func ConvertTo(out interface{}) func(interface{}) interface{} { outTyp := reflect.TypeOf(out) return func(in interface{}) interface{} { return reflect.ValueOf(in).Convert(outTyp).Interface() } } // Supplier (fn) adapts a func() any into a func() interface{}. // If fn happens to be a func() interface{}, it is returned as is. // fn may have a single variadic argument. func Supplier(fn interface{}) func() interface{} { // Return fn as is if it is desired type if res, isa := fn.(func() interface{}); isa { return res } // Verify fn has is a non-nil func of 0 parameters and 1 result vfn := reflect.ValueOf(fn) if (vfn.Kind() != reflect.Func) || vfn.IsNil() { panic(supplierErrorMsg) } // The func has to accept no args or a single variadic arg and return 1 type typ := vfn.Type() if !(((typ.NumIn() == 0) || ((typ.NumIn() == 1) && (typ.IsVariadic()))) && (typ.NumOut() == 1)) { panic(supplierErrorMsg) } return func() interface{} { resVal := vfn.Call([]reflect.Value{})[0].Interface() return resVal } } // SupplierOf (fn, X) adapts a func() X' into a func() X. // If fn happens to be a func() X, it is returned as is. // Otherwise, type X' must be convertible to X. // The result will have to be type asserted by the caller. // fn may have a single variadic argument. func SupplierOf(fn interface{}, val interface{}) interface{} { // val cannot be nil if IsNil(val) { panic("val cannot be nil") } // Verify val is a non-interface type var ( xval = reflect.ValueOf(val) xtyp = xval.Type() ) if xval.Kind() == reflect.Interface { panic("val cannot be an interface{} value") } // Verify fn has is a non-nil func of 0 parameters and 1 result var ( vfn = reflect.ValueOf(fn) errMsg = fmt.Sprintf(supplierOfErrorMsg, xtyp) ) if (vfn.Kind() != reflect.Func) || vfn.IsNil() { panic(errMsg) } // The func has to accept no args or a single variadic arg and return 1 type typ := vfn.Type() if !(((typ.NumIn() == 0) || ((typ.NumIn() == 1) && (typ.IsVariadic()))) && (typ.NumOut() == 1)) { panic(errMsg) } resTyp := typ.Out(0) // Return fn as is if it is desired type if resTyp == xtyp { return fn } // If fn returns any type convertible to X, then generate a function that returns exactly X if !resTyp.ConvertibleTo(xtyp) { panic(errMsg) } return reflect.MakeFunc( reflect.FuncOf( []reflect.Type{}, []reflect.Type{xtyp}, false, ), func(args []reflect.Value) []reflect.Value { resVal := vfn.Call([]reflect.Value{})[0].Convert(xtyp) return []reflect.Value{resVal} }, ).Interface() } // Consumer (fn) adapts a func(any) into a func(interface{}) // If fn happens to be a func(interface{}), it is returned as is. // Otherwise, each invocation converts the arg passed to the type the func receives. func Consumer(fn interface{}) func(interface{}) { // Return fn as is if it is desired type if res, isa := fn.(func(interface{})); isa { return res } // Verify fn has is a non-nil func of 1 parameters and no result vfn := reflect.ValueOf(fn) if (vfn.Kind() != reflect.Func) || vfn.IsNil() { panic(consumerErrorMsg) } // The func has to accept one arg and return nothing typ := vfn.Type() if (typ.NumIn() != 1) || (typ.NumOut() != 0) { panic(consumerErrorMsg) } argTyp := typ.In(0) return func(arg interface{}) { argVal := reflect.ValueOf(arg).Convert(argTyp) vfn.Call([]reflect.Value{argVal}) } } // Ternary returns trueVal if expr is true, else it returns falseVal func Ternary(expr bool, trueVal, falseVal interface{}) interface{} { if expr { return trueVal } return falseVal } // TernaryOf returns trueVal() if expr is true, else it returns falseVal() // trueVal and falseVal must be func() any. func TernaryOf(expr bool, trueVal, falseVal interface{}) interface{} { if expr { return Supplier(trueVal)() } return Supplier(falseVal)() } // PanicE panics if err is non-nil func PanicE(err error) { if err != nil { panic(err.Error()) } } // PanicVE panics if err is non-nil, otherwise returns val func PanicVE(val interface{}, err error) interface{} { if err != nil { panic(err.Error()) } return val } // PanicBM panics with msg if valid is false func PanicBM(valid bool, msg string) { if !valid { panic(msg) } } // PanicVBM panics with msg if valid is false, else returns val func PanicVBM(val interface{}, valid bool, msg string) interface{} { if !valid { panic(msg) } return val } // SortFunc adapts a func(val1, val2 any) bool into a func(val1, val2 interface{}) bool. // If fn is already a func(val1, val2 interface{}) bool, it is returned as is. // The passed func must return true if and only if val1 < val2. // Panics if fn is nil, not a func, does not accept two args of the same type, or does not return a single bool value. func SortFunc(fn interface{}) func(val1, val2 interface{}) bool { PanicBM(!IsNil(fn), sortErrorMsg) // If fn is already the right signature, return it as is if f, isa := fn.(func(val1, val2 interface{}) bool); isa { return f } var ( vfn = reflect.ValueOf(fn) fnTyp = vfn.Type() ) if !((fnTyp.Kind() == reflect.Func) && (fnTyp.NumIn() == 2) && (fnTyp.NumOut() == 1) && (fnTyp.In(0) == fnTyp.In(1)) && (fnTyp.Out(0).Kind() == reflect.Bool)) { panic(sortErrorMsg) } valTyp := fnTyp.In(0) return func(val1, val2 interface{}) bool { return vfn.Call([]reflect.Value{ reflect.ValueOf(val1).Convert(valTyp), reflect.ValueOf(val2).Convert(valTyp), })[0].Bool() } } var ( // IntSortFunc returns true if int64 val1 < val2 IntSortFunc = SortFunc(func(val1, val2 int64) bool { return val1 < val2 }) // UintSortFunc returns true if uint64 val1 < val2 UintSortFunc = SortFunc(func(val1, val2 uint64) bool { return val1 < val2 }) // FloatSortFunc returns true if float64 val1 < val2 FloatSortFunc = SortFunc(func(val1, val2 float64) bool { return val1 < val2 }) // ComplexSortFunc returns true if abs(complex128 val1) < abs(complex128 val2) ComplexSortFunc = SortFunc(func(val1, val2 complex128) bool { return cmplx.Abs(val1) < cmplx.Abs(val2) }) // StringSortFunc returns true if string val1 < val2 StringSortFunc = SortFunc(func(val1, val2 string) bool { return val1 < val2 }) // BigIntSortFunc returns true if big.Int val1 < val2 BigIntSortFunc = SortFunc(func(val1, val2 *big.Int) bool { return val1.Cmp(val2) == -1 }) // BigRatSortFunc returns true if big.Rat val1 < val2 BigRatSortFunc = SortFunc(func(val1, val2 *big.Rat) bool { return val1.Cmp(val2) == -1 }) // BigFloatSortFunc returns true if big.Float val1 < val2 BigFloatSortFunc = SortFunc(func(val1, val2 *big.Float) bool { return val1.Cmp(val2) == -1 }) )
funcs.go
0.729712
0.423965
funcs.go
starcoder
package uuidnil import ( "log" "reflect" "github.com/google/uuid" ) // assignFunc assigns the from value to the to value. type assignFunc func(to reflect.Value, from reflect.Value) error // proxyArray returns a proxy type and assign function for the specified array // type. func proxyArray(typ reflect.Type, opts Option) (reflect.Type, assignFunc) { proxy, assign := proxyType(typ.Elem(), opts) return reflect.ArrayOf(typ.Len(), proxy), func(to reflect.Value, from reflect.Value) error { if opts.trace() { log.Printf("[TRACE] assign: %s => %s\n", from.Type(), to.Type()) } for i := 0; i < typ.Len(); i++ { if err := assign(to.Index(i), from.Index(i)); err != nil { return err } } return nil } } // proxyMap returns a proxy type and assign function for the specified map // type. func proxyMap(typ reflect.Type, opts Option) (reflect.Type, assignFunc) { proxyKey, assignKey := proxyType(typ.Key(), opts) proxyVal, assignVal := proxyType(typ.Elem(), opts) return reflect.MapOf(proxyKey, proxyVal), func(to reflect.Value, from reflect.Value) error { if opts.trace() { log.Printf("[TRACE] assign: %s => %s\n", from.Type(), to.Type()) } if from.IsNil() { to.Set(reflect.Zero(to.Type())) return nil } if to.IsNil() { to.Set(reflect.MakeMapWithSize(to.Type(), from.Len())) } iter := from.MapRange() for iter.Next() { key := reflect.Indirect(reflect.New(typ.Key())) if err := assignKey(key, iter.Key()); err != nil { return err } val := reflect.Indirect(reflect.New(typ.Elem())) if err := assignVal(val, iter.Value()); err != nil { return err } to.SetMapIndex(key, val) } return nil } } // proxyPtr returns a proxy type and assign function for the specified pointer // type. func proxyPtr(typ reflect.Type, opts Option) (reflect.Type, assignFunc) { proxy, assign := proxyType(typ.Elem(), opts) return reflect.PtrTo(proxy), func(to reflect.Value, from reflect.Value) error { if opts.trace() { log.Printf("[TRACE] assign: %s => %s\n", from.Type(), to.Type()) } if from.IsNil() { to.Set(reflect.Zero(to.Type())) return nil } if to.IsNil() { to.Set(reflect.New(to.Type().Elem())) } return assign(to.Elem(), from.Elem()) } } // proxySlice returns a proxy type and assign function for the specified slice // type. func proxySlice(typ reflect.Type, opts Option) (reflect.Type, assignFunc) { proxy, assign := proxyType(typ.Elem(), opts) return reflect.SliceOf(proxy), func(to reflect.Value, from reflect.Value) error { if opts.trace() { log.Printf("[TRACE] assign: %s => %s\n", from.Type(), to.Type()) } if from.IsNil() { to.Set(reflect.Zero(to.Type())) return nil } slice := reflect.MakeSlice(to.Type(), 0, from.Len()) for i := 0; i < from.Len(); i++ { elem := reflect.Indirect(reflect.New(to.Type().Elem())) if err := assign(elem, from.Index(i)); err != nil { return err } slice = reflect.Append(slice, elem) } to.Set(slice) return nil } } // proxyStruct returns a proxy type and assign function for the specified // struct type. func proxyStruct(typ reflect.Type, opts Option) (reflect.Type, assignFunc) { n := typ.NumField() proxies := make([]reflect.StructField, 0, n) assigns := make([]assignFunc, 0, n) for i := 0; i < n; i++ { field := typ.Field(i) proxy, assign := proxyType(field.Type, opts) proxies = append(proxies, reflect.StructField{ Name: field.Name, Type: proxy, Tag: field.Tag, Index: field.Index, Anonymous: false, }) assigns = append(assigns, assign) } return reflect.StructOf(proxies), func(to reflect.Value, from reflect.Value) error { if opts.trace() { log.Printf("[TRACE] assign: %s => %s\n", from.Type(), to.Type()) } for i := 0; i < n; i++ { if err := assigns[i](to.Field(i), from.Field(i)); err != nil { return err } } return nil } } // proxyUUID returns a proxy type (string) and assign function for the // specified UUID type. func proxyUUID(typ reflect.Type, opts Option) (reflect.Type, assignFunc) { return reflect.TypeOf(""), func(to reflect.Value, from reflect.Value) error { if opts.trace() { log.Printf("[TRACE] assign: %s => %s\n", from.Type(), to.Type()) } if from.Type().Kind() != reflect.String { id := from.Interface().(uuid.UUID) to.Set(reflect.ValueOf(id.String())) return nil } str := from.String() if str == "" && opts.empty() { to.Set(reflect.Zero(to.Type())) return nil } id, err := uuid.Parse(str) if err != nil && opts.invalid() { to.Set(reflect.Zero(to.Type())) return nil } if err != nil { return err } to.Set(reflect.ValueOf(id)) return nil } } // proxyType returns a proxy type and assign function for the specified type. func proxyType(typ reflect.Type, opts Option) (reflect.Type, assignFunc) { if opts.trace() { log.Printf("[TRACE] proxy: %s", typ) } // UUID type. if typ.PkgPath() == "github.com/google/uuid" && typ.Name() == "UUID" { return proxyUUID(typ, opts) } // Composite types. switch typ.Kind() { case reflect.Array: return proxyArray(typ, opts) case reflect.Map: return proxyMap(typ, opts) case reflect.Ptr: return proxyPtr(typ, opts) case reflect.Slice: return proxySlice(typ, opts) case reflect.Struct: return proxyStruct(typ, opts) } // Simple type. return typ, func(to reflect.Value, from reflect.Value) error { if opts.trace() { log.Printf("[TRACE] assign: %s => %s\n", from.Type(), to.Type()) } to.Set(from) return nil } } // proxyValue returns a proxy value and assign function for the specified // value. func proxyValue(value reflect.Value, opts Option) (reflect.Value, assignFunc) { proxy, assign := proxyType(value.Type().Elem(), opts) if opts.debug() { log.Printf("[DEBUG] value type: %s, proxy type: %s\n", value.Type().Elem(), proxy) } return reflect.New(proxy), assign }
proxy.go
0.706596
0.498352
proxy.go
starcoder
package milight import ( "net" "time" "github.com/lucasb-eyer/go-colorful" ) // Zone constants are used to declare the target zone const ( ZoneAll int = iota Zone1 Zone2 Zone3 Zone4 ) var ( trailer byte = 0x55 on = [][]byte{{0x42, 0x00}, {0x45, 0x00}, {0x47, 0x00}, {0x49, 0x00}, {0x4B, 0x00}} off = [][]byte{{0x41, 0x00}, {0x46, 0x00}, {0x48, 0x00}, {0x4A, 0x00}, {0x4C, 0x00}} night = [][]byte{{0xC1, 0x00}, {0xC6, 0x00}, {0xC8, 0x00}, {0xCA, 0x00}, {0xCC, 0x00}} white = [][]byte{{0xC2, 0x00}, {0xC5, 0x00}, {0xC7, 0x00}, {0xC9, 0x00}, {0xCB, 0x00}} discoModeOn = []byte{0x4D, 0x00} discoModeFaster = []byte{0x44, 0x00} discoModeSlower = []byte{0x43, 0x00} brightnessPrefix byte = 0x4E brightnessValueMin byte = 0x02 brightnessValueMax byte = 0x1B colorPrefix byte = 0x40 ) // Send sends the command to the light controller func Send(addr string, values ...[]byte) error { a, err := net.ResolveUDPAddr("udp", addr) if err != nil { return err } conn, err := net.DialUDP("udp", nil, a) if err != nil { return err } defer conn.Close() for i1, value := range values { for i := 0; i < len(value); i += 2 { if i+i1 > 0 { time.Sleep(200 * time.Millisecond) } _, err = conn.Write([]byte{value[i], value[i+1], trailer}) if err != nil { return err } } } return nil } // TurnOff turns off the lights in the selected zone and selects this zone for future actions func TurnOff(zone int) []byte { return off[zone] } // TurnOn turns on the lights in the selected zone without changing their in-bulb values and selects this zone for future actions func TurnOn(zone int) []byte { return on[zone] } // SetWhite sets the lights in the selected zone to full white and selects this zone for future actions func SetWhite(zone int) []byte { return append(white[zone], white[zone]...) // apparently have to turn the bulb on first before setting WHITE } // SetNight sets the lights in the selected zone to night mode and selects this zone for future actions func SetNight(zone int) []byte { return append(night[zone], night[zone]...) // apparently have to turn the bulb on first before setting WHITE, so we'll do it for night too } // SetBrightness sets the brightness for the lights in the currently selected zone func SetBrightness(brightness float64) []byte { value := byte(brightness*float64(brightnessValueMax-brightnessValueMin)) + brightnessValueMin return []byte{brightnessPrefix, value} } // SetColorRGB sets the color using int 0-255 as the RGB values for lights in the currently selected zone func SetColorRGB(r, g, b int) []byte { return SetColorRGBFloat(float64(r)/255, float64(g)/255, float64(b)/255) } // SetColorRGBHex sets the color using #000000 as the RGB values for lights in the currently selected zone func SetColorRGBHex(rgb string) []byte { hex, _ := colorful.Hex(rgb) return setColor(hex) } // SetColorRGBFloat sets the color using float64 0..1 as the RGB values for lights in the currently selected zone func SetColorRGBFloat(r, g, b float64) []byte { return setColor(colorful.Color{r, g, b}) } func setColor(color colorful.Color) []byte { hue, _, _ := color.Hsv() value := byte(int(256+176-(hue/360*255)) % 256) // math stolen from https://goo.gl/rMwABR return []byte{colorPrefix, value} } // DiscoMode turns on disco mode for lights in the currently selected zone. Running this more than once will cycle to the next disco mode, of which there are many (built into the bulbs, apparently). func DiscoMode() []byte { return discoModeOn } // DiscoModeFaster makes disco mode run faster on lights in the currently selected zone. func DiscoModeFaster() []byte { return discoModeFaster } // DiscoModeSlower makes disco mode run slower on lights in the currently selected zone. func DiscoModeSlower() []byte { return discoModeSlower }
milight.go
0.659953
0.403802
milight.go
starcoder
package main import ( "fmt" "os" "strconv" "time" rpio "github.com/stianeikeland/go-rpio" ) var timeout = 100000 // SignalPair is a pair of values that show the state of the ir receiver type SignalPair struct { state rpio.State // State of the ir receiver (0 = pulse, 1 = gap) time int64 // Time the ir receiver is in the state } func main() { if len(os.Args) < 2 { fmt.Printf("Please specify the input pin for the signal of the ir sensor\n") return } inputPin, err := strconv.Atoi(os.Args[1]) if err != nil { fmt.Printf("Invalid input pin number\n") return } rawSignal := decodeSignal(inputPin) gapValues, pulseValues := parseSignal(rawSignal) gapBinaryString := parseGapValues(gapValues, rawSignal) pulseBinaryString := parsePulseValues(pulseValues, rawSignal) fmt.Printf("Binary from gaps = %v\n", gapBinaryString) fmt.Printf("Binary from pulses = %v\n", pulseBinaryString) } func decodeSignal(inPin int) []SignalPair { err := rpio.Open() if err != nil { fmt.Printf("Error when opening rpio: %v", err) } pin := rpio.Pin(inPin) pin.Input() currentState := rpio.State(rpio.High) var command []SignalPair // Loop until we see a low state fmt.Printf("Waiting for ir signal...\n") for currentState == rpio.State(rpio.High) { currentState = pin.Read() } startTime := time.Now() highCounter := 0 previousState := rpio.State(rpio.Low) for { if currentState != previousState { // The state has changed, so calculate the length of this run now := time.Now() elapsed := now.Sub(startTime) startTime = now var mySignalPair SignalPair mySignalPair.state = previousState mySignalPair.time = elapsed.Nanoseconds() command = append(command, mySignalPair) } if currentState == rpio.State(rpio.High) { highCounter++ } else { highCounter = 0 } // timout (global variable) is arbitrary, adjust as nessesary if highCounter > timeout { break } previousState = currentState currentState = pin.Read() } return command } func parseSignal(inputSignal []SignalPair) ([][]int64, [][]int64) { var gapValues [][]int64 var pulseValues [][]int64 for _, pair := range inputSignal { // If the state is a gap if pair.state == rpio.State(rpio.High) { fmt.Printf("Gap time: %v\n", pair.time) gapValues = addOrFindPulseGap(pair, gapValues) } else if pair.state == rpio.State(rpio.Low) { fmt.Printf("Pulse time: %v\n", pair.time) pulseValues = addOrFindPulseGap(pair, pulseValues) } } return gapValues, pulseValues } func addOrFindPulseGap(inputPair SignalPair, GapOrPulseValues [][]int64) [][]int64 { var foundAverageCategory bool // If GapOrPulseValues is totally empty if GapOrPulseValues == nil { s := []int64{inputPair.time} GapOrPulseValues = append(GapOrPulseValues, s) } else { // Get averages of the slices within GapOrPulseValues and see if the pair time fits somewhere foundAverageCategory = false var averages []int64 for _, timeCategory := range GapOrPulseValues { averages = append(averages, averageOfSlice(timeCategory)) } for index, average := range averages { if inputPair.time <= (average+250000) && inputPair.time >= (average-250000) && !foundAverageCategory { GapOrPulseValues[index] = append(GapOrPulseValues[index], inputPair.time) foundAverageCategory = true fmt.Printf("Found category. Inserting: %v into category: %v\n", inputPair.time, average) } } // If the pair time doesn't fit somewhere, create a new category for it if !foundAverageCategory { fmt.Printf("Category was not found. Adding %v to new category\n", inputPair.time) s := []int64{inputPair.time} GapOrPulseValues = append(GapOrPulseValues, s) } } return GapOrPulseValues } func parseGapValues(inputGapValues [][]int64, inputSignal []SignalPair) string { var binarySlice []byte var finalGapValues []int64 var smallestGapIndex int for _, gapSlice := range inputGapValues { finalGapValues = append(finalGapValues, averageOfSlice(gapSlice)) } fmt.Printf("Final gap values: \n") for _, value := range finalGapValues { if index == 0 { fmt.Printf("Leading gap duration: %v", value) } else { fmt.Println(value) } } fmt.Printf("Calculating binary string...\n") for _, pair := range inputSignal { if pair.state == rpio.State(rpio.High) { smallestGapIndex = indexOfSmallest(finalGapValues) if pair.time > finalGapValues[smallestGapIndex]+300000 { fmt.Printf("%v gapTime: %v = 1\n", finalGapValues[smallestGapIndex], pair.time) binarySlice = append(binarySlice, '1') } else { fmt.Printf("%v gapTime: %v = 0\n", finalGapValues[smallestGapIndex], pair.time) binarySlice = append(binarySlice, '0') } } } //remove first character because it's the leading bit binarySlice = binarySlice[1:] return string(binarySlice) } func parsePulseValues(inputPulseValues [][]int64, inputSignal []SignalPair) string { var binarySlice []byte var finalPulseValues []int64 var smallestPulseIndex int for _, pulseSlice := range inputPulseValues { finalPulseValues = append(finalPulseValues, averageOfSlice(pulseSlice)) } fmt.Printf("Final pulse values: \n") for index, value := range finalPulseValues { if index == 0 { fmt.Printf("Leading pulse duration: %v", value) } else { fmt.Println(value) } } fmt.Printf("Calculating binary string...\n") for _, pair := range inputSignal { if pair.state == rpio.State(rpio.High) { smallestPulseIndex = indexOfSmallest(finalPulseValues) if pair.time > finalPulseValues[smallestPulseIndex]+300000 { fmt.Printf("%v gapTime: %v = 1\n", finalPulseValues[smallestPulseIndex], pair.time) binarySlice = append(binarySlice, '1') } else { fmt.Printf("%v gapTime: %v = 0\n", finalPulseValues[smallestPulseIndex], pair.time) binarySlice = append(binarySlice, '0') } } } //remove first character because it's the leading bit binarySlice = binarySlice[1:] return string(binarySlice) } func averageOfSlice(input []int64) int64 { var sum int64 for _, value := range input { sum += value } return (sum / int64(len(input))) } //finds the index of the smallest value in a slice func indexOfSmallest(inputSlice []int64) int { var smallestValue int64 var smallestIndex int for index, value := range inputSlice { if smallestValue == 0 { smallestValue = value smallestIndex = index } else if value < smallestValue { smallestValue = value smallestIndex = index } } return smallestIndex }
decode.go
0.596081
0.413004
decode.go
starcoder
package coordinate import ( "math" "math/rand" "time" ) type Coordinate struct { Vec []float64 Error float64 Adjustment float64 Height float64 } const ( secondsToNanoseconds = 1.0e9 zeroThreshold = 1.0e-6 ) type DimensionalityConflictError struct{} func (e DimensionalityConflictError) Error() string { return "coordinate dimensionality does not match" } func NewCoordinate(config *Config) *Coordinate { return &Coordinate{ Vec: make([]float64, config.Dimensionality), Error: config.VivaldiErrorMax, Adjustment: 0.0, Height: config.HeightMin, } } func (c *Coordinate) Clone() *Coordinate { vec := make([]float64, len(c.Vec)) copy(vec, c.Vec) return &Coordinate{ Vec: vec, Error: c.Error, Adjustment: c.Adjustment, Height: c.Height, } } func componentIsValid(f float64) bool { return !math.IsInf(f, 0) && !math.IsNaN(f) } func (c *Coordinate) IsValid() bool { for i := range c.Vec { if !componentIsValid(c.Vec[i]) { return false } } return componentIsValid(c.Error) && componentIsValid(c.Adjustment) && componentIsValid(c.Height) } func (c *Coordinate) IsCompatibleWith(other *Coordinate) bool { return len(c.Vec) == len(other.Vec) } func (c *Coordinate) ApplyForce(config *Config, force float64, other *Coordinate) *Coordinate { if !c.IsCompatibleWith(other) { panic(DimensionalityConflictError{}) } ret := c.Clone() unit, mag := unitVectorAt(c.Vec, other.Vec) ret.Vec = add(ret.Vec, mul(unit, force)) if mag > zeroThreshold { ret.Height = (ret.Height+other.Height)*force/mag + ret.Height ret.Height = math.Max(ret.Height, config.HeightMin) } return ret } func (c *Coordinate) DistanceTo(other *Coordinate) time.Duration { if !c.IsCompatibleWith(other) { panic(DimensionalityConflictError{}) } dist := c.rawDistanceTo(other) adjustedDist := dist + c.Adjustment + other.Adjustment if adjustedDist > 0.0 { dist = adjustedDist } return time.Duration(dist * secondsToNanoseconds) } func (c *Coordinate) rawDistanceTo(other *Coordinate) float64 { return magnitude(diff(c.Vec, other.Vec)) + c.Height + other.Height } func add(vec1 []float64, vec2 []float64) []float64 { ret := make([]float64, len(vec1)) for i := range ret { ret[i] = vec1[i] + vec2[i] } return ret } func diff(vec1 []float64, vec2 []float64) []float64 { ret := make([]float64, len(vec1)) for i := range ret { ret[i] = vec1[i] - vec2[i] } return ret } func mul(vec []float64, factor float64) []float64 { ret := make([]float64, len(vec)) for i := range vec { ret[i] = vec[i] * factor } return ret } func magnitude(vec []float64) float64 { sum := 0.0 for i := range vec { sum += vec[i] * vec[i] } return math.Sqrt(sum) } func unitVectorAt(vec1 []float64, vec2 []float64) ([]float64, float64) { ret := diff(vec1, vec2) if mag := magnitude(ret); mag > zeroThreshold { return mul(ret, 1.0/mag), mag } for i := range ret { ret[i] = rand.Float64() - 0.5 } if mag := magnitude(ret); mag > zeroThreshold { return mul(ret, 1.0/mag), 0.0 } ret = make([]float64, len(ret)) ret[0] = 1.0 return ret, 0.0 }
hashicorp/serf/coordinate/coordinate.go
0.819749
0.450239
coordinate.go
starcoder
package client // ToBooler converts a redis value to a bool. // In case the conversion is not supported a ConversionError is returned. func (r *result) ToBool() (bool, error) { if err := r.wait(); err != nil { return false, err } return r.value.ToBool() } // ToFloat64 converts a redis value to a float64. // In case the conversion is not supported a ConversionError is returned. func (r *result) ToFloat64() (float64, error) { if err := r.wait(); err != nil { return 0, err } return r.value.ToFloat64() } // ToInt64 converts a redis value to an int64. // In case the conversion is not supported a ConversionError is returned. func (r *result) ToInt64() (int64, error) { if err := r.wait(); err != nil { return 0, err } return r.value.ToInt64() } // ToInt64Slice returns a slice with values of type int64. In case value conversion to []int64 is not possible // a ConversitionError is returned. func (r *result) ToInt64Slice() ([]int64, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToInt64Slice() } // ToIntfSlice returns a slice with values of type interface{}. func (r *result) ToIntfSlice() ([]interface{}, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToIntfSlice() } // ToInttSlice2 returns a slice with values of type []interface{}. In case value conversion to []interface{} is not possible // a ConversitionError is returned. func (r *result) ToIntfSlice2() ([][]interface{}, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToIntfSlice2() } // ToIntSlice3 returns a slice with values of type [][]interface{}. In case value conversion to [][]interface{} is not possible // a ConversitionError is returned. func (r *result) ToIntfSlice3() ([][][]interface{}, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToIntfSlice3() } // ToMap converts a redis value to a Map. // In case value conversion is not possible a ConversitionError is returned. func (r *result) ToMap() (Map, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToMap() } // ToSet converts a redis value to a Set. // In case value conversion is not possible a ConversitionError is returned. func (r *result) ToSet() (Set, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToSet() } // ToSlice converts a redis value to a Slice. // In case value conversion is not possible a ConversitionError is returned. func (r *result) ToSlice() (Slice, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToSlice() } // ToString converts a redis value to a string. // In case the conversion is not supported a ConversionError is returned. func (r *result) ToString() (string, error) { if err := r.wait(); err != nil { return "", err } return r.value.ToString() } // ToStringInt64Map returns a map with keys of type string and values of type int64. In case key or value conversion is not possible // a ConvertionError is returned. func (r *result) ToStringInt64Map() (map[string]int64, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToStringInt64Map() } // ToStringMap returns a map with keys of type string. In case key conversion to string is not possible // a ConvertionError is returned. func (r *result) ToStringMap() (map[string]interface{}, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToStringMap() } // ToStringMapSlice returns a slice with values of type map[string]interface{}. In case value conversion to map[string]interface{} is not possible // a ConversitionError is returned. func (r *result) ToStringMapSlice() ([]map[string]interface{}, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToStringMapSlice() } // ToStringSet returns a map with keys of type string and boolean true values. In case key conversion to string is not possible // a ConvertionError is returned. func (r *result) ToStringSet() (map[string]bool, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToStringSet() } // ToStringSlice returns a slice with values of type string. In case value conversion to []string is not possible // a ConversitionError is returned. func (r *result) ToStringSlice() ([]string, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToStringSlice() } // ToStringStringMap returns a map with keys and values of type string. In case key or value conversion to string is not possible // a ConvertionError is returned. func (r *result) ToStringStringMap() (map[string]string, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToStringStringMap() } // ToStringValueMap returns a map with keys of type string and values of type RedisValue. // In case key conversion to string is not possible a ConvertionError is returned. func (r *result) ToStringValueMap() (map[string]RedisValue, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToStringValueMap() } // ToTree returns a tree with nodes of type []interface{} and leaves of type interface{}. In case value conversion to []interface{} is not possible // a ConversitionError is returned. func (r *result) ToTree() ([]interface{}, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToTree() } // ToVerbatimString converts a redis value to a VerbatimString. // In case the conversion is not supported a ConversionError is returned. func (r *result) ToVerbatimString() (VerbatimString, error) { if err := r.wait(); err != nil { return "", err } return r.value.ToVerbatimString() } // ToXrange returns a slice with values of type XItem. In case the conversion is not possible // a ConversitionError is returned. func (r *result) ToXrange() ([]XItem, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToXrange() } // ToXread returns a map[string] with values of type XItem. In case the conversion is not possible // a ConversitionError is returned. func (r *result) ToXread() (map[string][]XItem, error) { if err := r.wait(); err != nil { return nil, err } return r.value.ToXread() }
client/result_gen.go
0.849753
0.459622
result_gen.go
starcoder
package main import ( "math/rand" "github.com/hajimehoshi/ebiten" "github.com/hajimehoshi/ebiten/inpututil" ) type Point struct { X, Y int } func LinePoints(x0, y0, x1, y1 int) []Point { var points []Point // implemented straight from WP pseudocode dx := x1 - x0 if dx < 0 { dx = -dx } dy := y1 - y0 if dy < 0 { dy = -dy } var sx, sy int if x0 < x1 { sx = 1 } else { sx = -1 } if y0 < y1 { sy = 1 } else { sy = -1 } err := dx - dy for { points = append(points, Point{X: x0, Y: y0}) if x0 == x1 && y0 == y1 { break } e2 := 2 * err if e2 > -dy { err -= dy x0 += sx } if e2 < dx { err += dx y0 += sy } } return points } func CirclePoints(x, y, r int) []Point { var points []Point if r < 0 { return nil } // Bresenham algorithm x1, y1, err := -r, 0, 2-2*r for { points = append(points, Point{X: x - x1, Y: y + y1}, Point{X: x - y1, Y: y - x1}, Point{X: x + x1, Y: y - y1}, Point{X: x + y1, Y: y + x1}, ) r = err if r > x1 { x1++ err += x1*2 + 1 } if r <= y1 { y1++ err += y1*2 + 1 } if x1 >= 0 { break } } return points } func CircleThickPoints(x, y, r int) (points []Point) { circle := CirclePoints(x, y, r) for _, cp := range circle { points = append(points, cp) points = append(points, CirclePoints(cp.X, cp.Y, 1)...) } return } func RectPoints(x1, y1, x2, y2 int) (points []Point) { for x := x1; x <= x2; x++ { points = append(points, Point{X: x, Y: y1}) points = append(points, Point{X: x, Y: y2}) } for y := y1; y <= y2; y++ { points = append(points, Point{X: x1, Y: y}) points = append(points, Point{X: x2, Y: y}) } return } // repeatingKeyPressed return true when key is pressed considering the repeat state. func repeatingKeyPressed(key ebiten.Key) bool { const ( delay = 30 interval = 3 ) d := inpututil.KeyPressDuration(key) if d == 1 { return true } if d >= delay && (d-delay)%interval == 0 { return true } return false } // RandIntRange returns a random int in the range [min, max]. func RandIntRange(min, max int) int { return rand.Intn(max+1-min) + min }
util.go
0.540196
0.465145
util.go
starcoder
package math32 // Line3 represents a 3D line segment defined by a start and an end point. type Line3 struct { start Vector3 end Vector3 } // NewLine3 creates and returns a pointer to a new Line3 with the // specified start and end points. func NewLine3(start, end *Vector3) *Line3 { l := new(Line3) l.Set(start, end) return l } // Set sets this line segment start and end points. // Returns pointer to this updated line segment. func (l *Line3) Set(start, end *Vector3) *Line3 { if start != nil { l.start = *start } if end != nil { l.end = *end } return l } // Copy copy other line segment to this one. // Returns pointer to this updated line segment. func (l *Line3) Copy(other *Line3) *Line3 { *l = *other return l } // Center calculates this line segment center point. // Store its pointer into optionalTarget, if not nil, and also returns it. func (l *Line3) Center(optionalTarget *Vector3) *Vector3 { var result *Vector3 if optionalTarget == nil { result = NewVector3(0, 0, 0) } else { result = optionalTarget } return result.AddVectors(&l.start, &l.end).MultiplyScalar(0.5) } // Delta calculates the vector from the start to end point of this line segment. // Store its pointer in optionalTarget, if not nil, and also returns it. func (l *Line3) Delta(optionalTarget *Vector3) *Vector3 { var result *Vector3 if optionalTarget == nil { result = NewVector3(0, 0, 0) } else { result = optionalTarget } return result.SubVectors(&l.end, &l.start) } // DistanceSq returns the square of the distance from the start point to the end point. func (l *Line3) DistanceSq() float32 { return l.start.DistanceTo(&l.end) } // Distance returns the distance from the start point to the end point. func (l *Line3) Distance() float32 { return l.start.DistanceTo(&l.end) } // DistanceToVec3 returns the shortest distance between the line and a vector func (l *Line3) DistanceToVec3(v *Vector3) float32 { d := l.Delta(nil) w1 := NewVec3().SubVectors(v, &l.start) d1 := w1.Dot(d) if d1 <= 0 { return v.DistanceTo(&l.start) } w2 := NewVec3().SubVectors(v, &l.end) d2 := w2.Dot(d) if d2 >= 0 { return v.DistanceTo(&l.end) } b := d1 / l.DistanceSq() pb := d.MultiplyScalar(b).Add(&l.start) return pb.DistanceTo(v) } // ApplyMatrix4 applies the specified matrix to this line segment start and end points. // Returns pointer to this updated line segment. func (l *Line3) ApplyMatrix4(matrix *Matrix4) *Line3 { l.start.ApplyMatrix4(matrix) l.end.ApplyMatrix4(matrix) return l } // Equals returns if this line segement is equal to other. func (l *Line3) Equals(other *Line3) bool { return other.start.Equals(&l.start) && other.end.Equals(&l.end) } // Clone creates and returns a pointer to a copy of this line segment. func (l *Line3) Clone() *Line3 { return NewLine3(&l.start, &l.end) } // Ray Converts the line to a ray and returns the new ray func (l *Line3) Ray() *Ray { return NewRay(&l.start, l.Delta(nil).Normalize()) }
math32/line3.go
0.920034
0.666629
line3.go
starcoder
package actions import ( "github.com/LindsayBradford/crem/internal/pkg/model/action" "github.com/LindsayBradford/crem/internal/pkg/model/planningunit" ) const HillSlopeRestorationType action.ManagementActionType = "HillSlopeRestoration" func NewHillSlopeRestoration() *HillSlopeRestoration { return new(HillSlopeRestoration).WithType(HillSlopeRestorationType) } type HillSlopeRestoration struct { action.SimpleManagementAction } func (h *HillSlopeRestoration) WithType(actionType action.ManagementActionType) *HillSlopeRestoration { h.SimpleManagementAction.WithType(actionType) return h } func (h *HillSlopeRestoration) WithPlanningUnit(planningUnit planningunit.Id) *HillSlopeRestoration { h.SimpleManagementAction.WithPlanningUnit(planningUnit) return h } const HillSlopeRestorationCost action.ModelVariableName = "HillSlopeRestorationCost" func (h *HillSlopeRestoration) WithImplementationCost(costInDollars float64) *HillSlopeRestoration { return h.WithVariable(HillSlopeRestorationCost, costInDollars) } const HillSlopeRestorationOpportunityCost action.ModelVariableName = "HillSlopeRestorationOpportunityCost" func (h *HillSlopeRestoration) WithOpportunityCost(costInDollars float64) *HillSlopeRestoration { return h.WithVariable(HillSlopeRestorationOpportunityCost, costInDollars) } func (h *HillSlopeRestoration) WithOriginalSedimentErosion(costInDollars float64) *HillSlopeRestoration { return h.WithVariable(HillSlopeErosionOriginalAttribute, costInDollars) } func (h *HillSlopeRestoration) WithActionedSedimentErosion(costInDollars float64) *HillSlopeRestoration { return h.WithVariable(HillSlopeErosionActionedAttribute, costInDollars) } func (h *HillSlopeRestoration) WithOriginalParticulateNitrogen(costInDollars float64) *HillSlopeRestoration { return h.WithVariable(ParticulateNitrogenOriginalAttribute, costInDollars) } func (h *HillSlopeRestoration) WithActionedParticulateNitrogen(costInDollars float64) *HillSlopeRestoration { return h.WithVariable(ParticulateNitrogenActionedAttribute, costInDollars) } func (h *HillSlopeRestoration) WithOriginalDissolvedNitrogen(costInDollars float64) *HillSlopeRestoration { return h.WithVariable(DissolvedNitrogenOriginalAttribute, costInDollars) } func (h *HillSlopeRestoration) WithActionedDissolvedNitrogen(costInDollars float64) *HillSlopeRestoration { return h.WithVariable(DissolvedNitrogenActionedAttribute, costInDollars) } func (h *HillSlopeRestoration) WithVariable(variableName action.ModelVariableName, value float64) *HillSlopeRestoration { h.SimpleManagementAction.WithVariable(variableName, value) return h }
internal/pkg/model/models/catchment/actions/HillSlopeRestoration.go
0.781664
0.544983
HillSlopeRestoration.go
starcoder
package idx import ( "github.com/reearth/reearth-cms/server/pkg/util" "golang.org/x/exp/slices" ) type List[T Type] []ID[T] type RefList[T Type] []*ID[T] func ListFrom[T Type](ids []string) (List[T], error) { return util.TryMap(ids, From[T]) } func MustList[T Type](ids []string) List[T] { return util.Must(ListFrom[T](ids)) } func (l List[T]) list() util.List[ID[T]] { return util.List[ID[T]](l) } func (l List[T]) Has(ids ...ID[T]) bool { return l.list().Has(ids...) } func (l List[T]) At(i int) *ID[T] { return l.list().At(i) } func (l List[T]) Index(id ID[T]) int { return l.list().Index(id) } func (l List[T]) Len() int { return l.list().Len() } func (l List[T]) Ref() *List[T] { return (*List[T])(l.list().Ref()) } func (l List[T]) Refs() RefList[T] { return l.list().Refs() } func (l List[T]) Delete(ids ...ID[T]) List[T] { return List[T](l.list().Delete(ids...)) } func (l List[T]) DeleteAt(i int) List[T] { return List[T](l.list().DeleteAt(i)) } func (l List[T]) Add(ids ...ID[T]) List[T] { return List[T](l.list().Add(ids...)) } func (l List[T]) AddUniq(ids ...ID[T]) List[T] { return List[T](l.list().AddUniq(ids...)) } func (l List[T]) Insert(i int, ids ...ID[T]) List[T] { return List[T](l.list().Insert(i, ids...)) } func (l List[T]) Move(e ID[T], to int) List[T] { return List[T](l.list().Move(e, to)) } func (l List[T]) MoveAt(from, to int) List[T] { return List[T](l.list().MoveAt(from, to)) } func (l List[T]) Reverse() List[T] { return List[T](l.list().Reverse()) } func (l List[T]) Concat(m List[T]) List[T] { return List[T](l.list().Concat(m)) } func (l List[T]) Intersect(m List[T]) List[T] { return List[T](l.list().Intersect(m)) } func (l List[T]) Strings() []string { return util.Map(l, func(id ID[T]) string { return id.String() }) } func (l List[T]) Clone() List[T] { return util.Map(l, func(id ID[T]) ID[T] { return id.Clone() }) } func (l List[T]) Sort() List[T] { m := l.list().Copy() slices.SortStableFunc(m, func(a, b ID[T]) bool { return a.Compare(b) <= 0 }) return List[T](m) } func (l RefList[T]) Deref() List[T] { return util.FilterMap(l, func(id *ID[T]) *ID[T] { if id != nil && !(*id).IsNil() { return id } return nil }) }
server/pkg/id/idx/list.go
0.501221
0.608681
list.go
starcoder
package evolution import ( "fmt" "math/rand" ) /** Selection is the stage of a genetic algorithm in which individual genomes are chosen from a population for later breeding (using the crossover operator). A generic selection procedure may be implemented as follows: 1. The Fitness function is evaluated for each individual, providing Fitness values, which are then normalized. Normalization means dividing the Fitness value of each individual by the sum of all Fitness values, so that the sum of all resulting Fitness values equals 1. 2. The population is sorted by descending Fitness values. 3. Accumulated normalized Fitness values are computed: the accumulated Fitness value of an individual is the sum of its own Fitness value plus the Fitness values of all the previous individuals; the accumulated Fitness of the last individual should be 1, otherwise something went wrong in the normalization step. 4. A random number R between 0 and 1 is chosen. 5. The selected individual is the last one whose accumulated normalized value is greater than or equal to R. For a large number of individuals the above algorithm might be computationally quite demanding. A simpler and faster alternative uses the so-called stochastic acceptance. //https://en.wikipedia.org/wiki/Selection_(genetic_algorithm) */ const ( ParentSelectionTournament = "ParentSelectionTournament" // ID for Tournament Selection ParentSelectionElitism = "ParentSelectionElitism" //ID for elitism ParentSelectionFitnessProportionate = 2 ) // TournamentSelection is a process whereby a random set of individuals from the population are selected, // and the best in that sample succeed onto the next Generation func TournamentSelection(population []*Individual, tournamentSize int) ([]*Individual, error) { if population == nil { return nil, fmt.Errorf("tournament population cannot be nil") } if len(population) < 1 { return nil, fmt.Errorf("tournament population cannot have len < 1") } if tournamentSize < 1 { return nil, fmt.Errorf("tournament size cannot be less than 1") } // do newPop := make([]*Individual, len(population)) for i := 0; i < len(population); i++ { randSelectedIndividuals := getNRandom(population, tournamentSize) fittest, err := tournamentSelect(randSelectedIndividuals) if err != nil { return nil, err } newPop[i] = fittest } return newPop, nil } // getNRandom selects a random group of individiduals equivalent to the tournamentSize func getNRandom(population []*Individual, tournamentSize int) []*Individual { newPop := make([]*Individual, tournamentSize) for i := 0; i < tournamentSize; i++ { randIndex := rand.Intn(len(population)) newPop[i] = population[randIndex] } return newPop } //tournamentSelect returns the fittest individual in a given tournament func tournamentSelect(selectedIndividuals []*Individual) (*Individual, error) { fittest := selectedIndividuals[0] for i := range selectedIndividuals { if selectedIndividuals[i].AverageFitness > fittest.AverageFitness { individual, err := selectedIndividuals[i].Clone() if err != nil { return nil, err } fittest = &individual } } return fittest, nil } // Elitism is an evolutionary process where only the top ( // n) individuals based on eliteCount are selected based on their Fitness. // In essence it ranks the individuals based on Fitness, then returns the top (n) func Elitism(population []*Individual, isMoreFitnessBetter bool) ([]*Individual, error) { return nil, nil } // Fitness Proportionate Selection is one of the most popular ways of parent selection. // In this every individual can become a parent with a probability which is proportional to its Fitness. // Therefore, fitter individuals have a higher chance of mating and propagating their features to the next Generation. // Therefore, such a selection Strategy applies a selection pressure to the more fit individuals in the population, evolving better individuals over time. func FitnessProportionateSelection(population []*Individual) ([]*Individual, error) { return nil, nil }
evolution/parentselection.go
0.81538
0.775052
parentselection.go
starcoder
package sudoku import ( "errors" ) // Take an unsolved Sudoku input and return a solved Sudoku output func solveSerial(sudokuIn Sudoku, iter ...int) (sudokuOut Sudoku, solved bool, iteration int, err error) { /* Solve the Sudoku puzzle as follows: 1) mapper: find out potential numbers that can be filled for each unfilled column in each row by looking at the unfilled column from the perspective of the corresponding row, column and the bounded box 2) reducer: scan through the row, column or bounding box and resolve the column value 3) repeat step 1 and 2 as long as the number of unfilled reduces in each iteration 4) If the unfilled Cells are not reducing anymore, do the following pick the Cell with the least number of potentials: fire multiple threads concurrently with each of these potentials filled in the Cell do this recursively. I.e. once a Cell is filled with a potential, a recursive call is made to solve function, which fills the next potential and so on. There can be only one of two outcomes at the top most level: (a) the Sudoku is solved (b) this combination is invalid, in which case, this guess is abandoned at intermediate levels, there can be one of two outcomes: (a) the Sudoku is partially solved, in which case, this guessing comtinues (b) this combination is invalid, in which case, this guess is abandoned */ sudokuOut = sudokuIn.Copy() UnfilledCount := 0 if iter != nil { iteration = iter[0] } else { iteration = 0 } // fmt.Println(iteration) for { // If the Sudoku is solved, exit out of the routine if sudokuOut.Solved() { //fmt.Println("Sudoku solved!") break } if iteration >= 10000000 { break } UnfilledCount = sudokuOut.UnfilledCount() // cMap := make(chan Cell) // cReduce := make(chan int) iteration++ //fmt.Println("<<<Iteration & unfilled>>>: ", iteration, sudokuOut.UnfilledCount()) // sudokuOut.Print(0 // call map function concurrently for all the Cells // mapResults = make([]Cell, 0) for rowID, row := range sudokuOut { for colID, col := range row { if col == 0 { _cell := sudokuOut.MapEligibleNumbers(rowID, colID) _result := sudokuOut.ReduceAndFillEligibleNumber(_cell) if _result == -1 { //fmt.Println("incorrect Sudoku. return to caller") return sudokuOut, sudokuOut.Solved(), iteration, errors.New("incorrect Sudoku") } } } } // If the Sudoku is solved, exit out of the routine if sudokuOut.Solved() { //fmt.Println("Sudoku solved!") break } // If no Cells have been reduced, there is no point in repeating, start brute force if sudokuOut.UnfilledCount() >= UnfilledCount { //fmt.Println("start brute force attack") potentials := make(map[int]Cell) for rowID, row := range sudokuOut { for colID, col := range row { if col == 0 { _cell := sudokuOut.MapEligibleNumbers(rowID, colID) _potentialsLen := len(_cell.EligibleNumbers.GetList()) potentials[_potentialsLen] = _cell } } } // var input string // fmt.Println(potentials) // fmt.Scanln(&input) // Walk through all Cells and group them by the number of potentials var cellToEvaluate Cell potentialsRange := []int{2, 3, 4, 5, 6, 7, 8, 9} for _, _potential := range potentialsRange { if _, ok := potentials[_potential]; ok { cellToEvaluate = potentials[_potential] break } } // Pick each eligible number, fill it and see if it works for eligNum, eligible := range cellToEvaluate.EligibleNumbers { if eligible { SudokuCopy := sudokuOut.Copy() sudokuOut.Fill(cellToEvaluate.RowID, cellToEvaluate.ColID, eligNum) _sudokuInter, _solved, _iteration, _err := solveSerial(sudokuOut, iteration) if _solved { // fmt.Println("solved. return to caller") return _sudokuInter, _solved, _iteration, _err } if _err.Error() == "incorrect Sudoku" { // This combination is invalid. rollback. try out the next option sudokuOut = SudokuCopy.Copy() } else { //fmt.Println("not solved, but the guess is correct. try from beginning") sudokuOut = _sudokuInter.Copy() sudokuOut.Print() break } } } } } //fmt.Println("finally going back") return sudokuOut, sudokuOut.Solved(), iteration, errors.New("done") }
sudoku/sudokusolveserial.go
0.513181
0.631552
sudokusolveserial.go
starcoder
package tart import ( "sort" ) // Developed by <NAME> in 1976 and featured in Stocks & Commodities // Magazine in 1985, the Ultimate Oscillator is a momentum oscillator designed // to capture momentum across three different timeframes. The multiple timeframe // objective seeks to avoid the pitfalls of other oscillators. Many momentum // oscillators surge at the beginning of a strong advance, only to form a bearish // divergence as the advance continues. This is because they are stuck with one // timeframe. The Ultimate Oscillator attempts to correct this fault by // incorporating longer timeframes into the basic formula. Williams identified // a buy signal a based on a bullish divergence and a sell signal based on a // bearish divergence. // https://school.stockcharts.com/doku.php?id=technical_indicators:ultimate_oscillator // https://www.investopedia.com/terms/u/ultimateoscillator.asp // https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/ultimate-oscillator type UltOsc struct { n1 int64 n2 int64 n3 int64 bp1 *Sum bp2 *Sum bp3 *Sum tr1 *Sum tr2 *Sum tr3 *Sum prevC float64 sz int64 } func NewUltOsc(n1, n2, n3 int64) *UltOsc { arr := []int64{n1, n2, n3} sort.Slice(arr, func(i, j int) bool { return arr[i] < arr[j] }) n1, n2, n3 = arr[0], arr[1], arr[2] return &UltOsc{ n1: n1, n2: n2, n3: n3, bp1: NewSum(n1), bp2: NewSum(n2), bp3: NewSum(n3), tr1: NewSum(n1), tr2: NewSum(n2), tr3: NewSum(n3), prevC: 0, sz: 0, } } func (u *UltOsc) Update(h, l, c float64) float64 { u.sz++ low := min(l, u.prevC) bp := c - low tr := max(h, u.prevC) - low u.prevC = c if u.sz == 1 { return 0 } bp1 := u.bp1.Update(bp) bp2 := u.bp2.Update(bp) bp3 := u.bp3.Update(bp) tr1 := u.tr1.Update(tr) tr2 := u.tr2.Update(tr) tr3 := u.tr3.Update(tr) if u.sz <= u.n3 { return 0 } d1 := bp1 / tr1 d2 := bp2 / tr2 d3 := bp3 / tr3 return (d1*4.0 + d2*2.0 + d3) / 7.0 * 100.0 } func (u *UltOsc) InitPeriod() int64 { return u.n3 } func (u *UltOsc) Valid() bool { return u.sz > u.InitPeriod() } // Developed by <NAME> in 1976 and featured in Stocks & Commodities // Magazine in 1985, the Ultimate Oscillator is a momentum oscillator designed // to capture momentum across three different timeframes. The multiple timeframe // objective seeks to avoid the pitfalls of other oscillators. Many momentum // oscillators surge at the beginning of a strong advance, only to form a bearish // divergence as the advance continues. This is because they are stuck with one // timeframe. The Ultimate Oscillator attempts to correct this fault by // incorporating longer timeframes into the basic formula. Williams identified // a buy signal a based on a bullish divergence and a sell signal based on a // bearish divergence. // https://school.stockcharts.com/doku.php?id=technical_indicators:ultimate_oscillator // https://www.investopedia.com/terms/u/ultimateoscillator.asp // https://www.fidelity.com/learning-center/trading-investing/technical-analysis/technical-indicator-guide/ultimate-oscillator func UltOscArr(h, l, c []float64, n1, n2, n3 int64) []float64 { out := make([]float64, len(c)) u := NewUltOsc(n1, n2, n3) for i := 0; i < len(c); i++ { out[i] = u.Update(h[i], l[i], c[i]) } return out }
ultosc.go
0.642993
0.442335
ultosc.go
starcoder
package ogame import "strconv" // MissionID represent a mission id type MissionID int func (m MissionID) String() string { switch m { case Attack: return "Attack" case GroupedAttack: return "GroupedAttack" case Transport: return "Transport" case Park: return "Park" case ParkInThatAlly: return "ParkInThatAlly" case Spy: return "Spy" case Colonize: return "Colonize" case RecycleDebrisField: return "RecycleDebrisField" case Destroy: return "Destroy" case MissileAttack: return "MissileAttack" case Expedition: return "Expedition" default: return strconv.FormatInt(int64(m), 10) } } // Speed represent a fleet speed type Speed float64 // Float64 returns a float64 value of the speed func (s Speed) Float64() float64 { return float64(s) } // Int64 returns an integer value of the speed func (s Speed) Int64() int64 { return int64(s) } // Int returns an integer value of the speed // Deprecated: backward compatibility func (s Speed) Int() int64 { return int64(s) } func (s Speed) String() string { switch s { case FivePercent: return "5%" case TenPercent: return "10%" case FifteenPercent: return "15%" case TwentyPercent: return "20%" case TwentyFivePercent: return "25%" case ThirtyPercent: return "30%" case ThirtyFivePercent: return "35%" case FourtyPercent: return "40%" case FourtyFivePercent: return "45%" case FiftyPercent: return "50%" case FiftyFivePercent: return "55%" case SixtyPercent: return "60%" case SixtyFivePercent: return "65%" case SeventyPercent: return "70%" case SeventyFivePercent: return "75%" case EightyPercent: return "80%" case EightyFivePercent: return "85%" case NinetyPercent: return "90%" case NinetyFivePercent: return "95%" case HundredPercent: return "100%" default: return strconv.FormatFloat(float64(s), 'f', 1, 64) } } // CelestialType destination type might be planet/moon/debris type CelestialType int64 func (d CelestialType) String() string { switch d { case PlanetType: return "planet" case MoonType: return "moon" case DebrisType: return "debris" default: return strconv.FormatInt(int64(d), 10) } } // Int64 returns an integer value of the CelestialType func (d CelestialType) Int64() int64 { return int64(d) } // Int returns an integer value of the CelestialType // Deprecated: backward compatibility func (d CelestialType) Int() int64 { return int64(d) } // AllianceClass ... type AllianceClass int64 // IsWarrior ... func (c AllianceClass) IsWarrior() bool { return c == Warrior } // IsTrader ... func (c AllianceClass) IsTrader() bool { return c == Trader } // IsResearcher ... func (c AllianceClass) IsResearcher() bool { return c == Researcher } // CharacterClass ... type CharacterClass int64 func (c CharacterClass) IsCollector() bool { return c == Collector } func (c CharacterClass) IsGeneral() bool { return c == General } func (c CharacterClass) IsDiscoverer() bool { return c == Discoverer } // OGame constants const ( NoClass CharacterClass = 0 Collector CharacterClass = 1 General CharacterClass = 2 Discoverer CharacterClass = 3 NoAllianceClass AllianceClass = 0 Warrior AllianceClass = 1 Trader AllianceClass = 2 Researcher AllianceClass = 3 PlanetType CelestialType = 1 DebrisType CelestialType = 2 MoonType CelestialType = 3 //Buildings MetalMineID ID = 1 CrystalMineID ID = 2 DeuteriumSynthesizerID ID = 3 SolarPlantID ID = 4 FusionReactorID ID = 12 MetalStorageID ID = 22 CrystalStorageID ID = 23 DeuteriumTankID ID = 24 ShieldedMetalDenID ID = 25 UndergroundCrystalDenID ID = 26 SeabedDeuteriumDenID ID = 27 AllianceDepotID ID = 34 // Facilities RoboticsFactoryID ID = 14 ShipyardID ID = 21 ResearchLabID ID = 31 MissileSiloID ID = 44 NaniteFactoryID ID = 15 TerraformerID ID = 33 SpaceDockID ID = 36 LunarBaseID ID = 41 // Moon facilities SensorPhalanxID ID = 42 JumpGateID ID = 43 RocketLauncherID ID = 401 // Defense LightLaserID ID = 402 HeavyLaserID ID = 403 GaussCannonID ID = 404 IonCannonID ID = 405 PlasmaTurretID ID = 406 SmallShieldDomeID ID = 407 LargeShieldDomeID ID = 408 AntiBallisticMissilesID ID = 502 InterplanetaryMissilesID ID = 503 SmallCargoID ID = 202 // Ships LargeCargoID ID = 203 LightFighterID ID = 204 HeavyFighterID ID = 205 CruiserID ID = 206 BattleshipID ID = 207 ColonyShipID ID = 208 RecyclerID ID = 209 EspionageProbeID ID = 210 BomberID ID = 211 SolarSatelliteID ID = 212 DestroyerID ID = 213 DeathstarID ID = 214 BattlecruiserID ID = 215 CrawlerID ID = 217 ReaperID ID = 218 PathfinderID ID = 219 EspionageTechnologyID ID = 106 // Research ComputerTechnologyID ID = 108 WeaponsTechnologyID ID = 109 ShieldingTechnologyID ID = 110 ArmourTechnologyID ID = 111 EnergyTechnologyID ID = 113 HyperspaceTechnologyID ID = 114 CombustionDriveID ID = 115 ImpulseDriveID ID = 117 HyperspaceDriveID ID = 118 LaserTechnologyID ID = 120 IonTechnologyID ID = 121 PlasmaTechnologyID ID = 122 IntergalacticResearchNetworkID ID = 123 AstrophysicsID ID = 124 GravitonTechnologyID ID = 199 // Missions Attack MissionID = 1 GroupedAttack MissionID = 2 Transport MissionID = 3 Park MissionID = 4 ParkInThatAlly MissionID = 5 Spy MissionID = 6 Colonize MissionID = 7 RecycleDebrisField MissionID = 8 Destroy MissionID = 9 MissileAttack MissionID = 10 Expedition MissionID = 15 // Speeds TenPercent Speed = 1 TwentyPercent Speed = 2 ThirtyPercent Speed = 3 FourtyPercent Speed = 4 FiftyPercent Speed = 5 SixtyPercent Speed = 6 SeventyPercent Speed = 7 EightyPercent Speed = 8 NinetyPercent Speed = 9 HundredPercent Speed = 10 FivePercent Speed = 0.5 // General class only detailed speeds FifteenPercent Speed = 1.5 TwentyFivePercent Speed = 2.5 ThirtyFivePercent Speed = 3.5 FourtyFivePercent Speed = 4.5 FiftyFivePercent Speed = 5.5 SixtyFivePercent Speed = 6.5 SeventyFivePercent Speed = 7.5 EightyFivePercent Speed = 8.5 NinetyFivePercent Speed = 9.5 )
constants.go
0.681303
0.401189
constants.go
starcoder
package typ import ( "fmt" "sort" ) // Vars is a sorted set of type variable kinds. type Vars []Kind func (vs Vars) Len() int { return len(vs) } func (vs Vars) Less(i, j int) bool { return vs[i] < vs[j] } func (vs Vars) Swap(i, j int) { vs[i], vs[j] = vs[j], vs[i] } // Copy returns a copy of vs func (vs Vars) Copy() Vars { return append(make(Vars, 0, len(vs)+8), vs...) } func (vs Vars) idx(v Kind) int { return sort.Search(len(vs), func(i int) bool { return vs[i] >= v }) } // Has returns whether vs contains type variable v. func (vs Vars) Has(v Kind) bool { i := vs.idx(v) return i < len(vs) && vs[i] == v } // Add inserts v into vs and returns the resulting set. func (vs Vars) Add(v Kind) Vars { i := vs.idx(v) if i >= len(vs) { vs = append(vs, v) } else if vs[i] != v { vs = append(vs[:i+1], vs[i:]...) vs[i] = v } return vs } // Del removes v from vs and returns the resulting set. func (vs Vars) Del(v Kind) Vars { i := vs.idx(v) if i < len(vs) && vs[i] == v { vs = append(vs[:i], vs[i+1:]...) } return vs } // Bind represents a type variable binding to another type type Bind struct { Var Kind Type } func (b Bind) String() string { return fmt.Sprintf("%s = %s", b.Var, b.Type) } // Binds is a sorted set of type variable bindings. type Binds []Bind func (bs Binds) Len() int { return len(bs) } func (bs Binds) Less(i, j int) bool { return bs[i].Var < bs[j].Var } func (bs Binds) Swap(i, j int) { bs[i], bs[j] = bs[j], bs[i] } // Copy returns a copy of bs. func (bs Binds) Copy() Binds { return append(make(Binds, 0, len(bs)+8), bs...) } func (bs Binds) idx(v Kind) int { return sort.Search(len(bs), func(i int) bool { return bs[i].Var >= v }) } // Get returns the type bound to v and a boolean indicating whether a binding was found. func (bs Binds) Get(v Kind) (Type, bool) { i := bs.idx(v) if i >= len(bs) || bs[i].Var != v { return Void, false } return bs[i].Type, true } // Set inserts a binding with v and t to bs and returns the resulting set. func (bs Binds) Set(v Kind, t Type) Binds { i := bs.idx(v) if i >= len(bs) { return append(bs, Bind{v, t}) } if bs[i].Var != v { bs = append(bs[:i+1], bs[i:]...) } bs[i] = Bind{v, t} return bs } // Del removes a binding with v from bs and returns the resulting set. func (bs Binds) Del(v Kind) Binds { i := bs.idx(v) if i < len(bs) && bs[i].Var == v { return append(bs[:i], bs[i+1:]...) } return bs }
typ/vars.go
0.713831
0.450118
vars.go
starcoder
package coldata // zeroedNulls is a zeroed out slice representing a bitmap of size BatchSize. // This is copied to efficiently clear a nulls slice. var zeroedNulls [(BatchSize-1)>>6 + 1]uint64 // filledNulls is a slice representing a bitmap of size BatchSize with every // single bit set. var filledNulls [(BatchSize-1)>>6 + 1]uint64 // onesMask is a max uint64, where every bit is set to 1. const onesMask = ^uint64(0) func init() { // Initializes filledNulls to the desired slice. for i := range filledNulls { filledNulls[i] = onesMask } } // Nulls represents a list of potentially nullable values. type Nulls struct { nulls []uint64 // hasNulls represents whether or not the memColumn has any null values set. hasNulls bool } // NewNulls returns a new nulls vector, initialized with a length. func NewNulls(len int) Nulls { if len > 0 { return Nulls{ nulls: make([]uint64, (len-1)>>6+1), } } return Nulls{ nulls: make([]uint64, 0), } } // HasNulls returns true if the column has any null values. func (n *Nulls) HasNulls() bool { return n.hasNulls } // NullAt returns true if the ith value of the column is null. func (n *Nulls) NullAt(i uint16) bool { return n.NullAt64(uint64(i)) } // SetNull sets the ith value of the column to null. func (n *Nulls) SetNull(i uint16) { n.SetNull64(uint64(i)) } // SetNullRange sets all the values in [start, end) to null. func (n *Nulls) SetNullRange(start uint64, end uint64) { if start >= end { return } n.hasNulls = true sIdx := start >> 6 eIdx := end >> 6 // Case where mask only spans one uint64. if sIdx == eIdx { mask := onesMask << (start % 64) mask = mask & (onesMask >> (64 - (end % 64))) n.nulls[sIdx] |= mask return } // Case where mask spans at least two uint64s. if sIdx < eIdx { mask := onesMask << (start % 64) n.nulls[sIdx] |= mask mask = onesMask >> (64 - (end % 64)) n.nulls[eIdx] |= mask for i := sIdx + 1; i < eIdx; i++ { n.nulls[i] |= onesMask } } } // UnsetNulls sets the column to have no null values. func (n *Nulls) UnsetNulls() { n.hasNulls = false startIdx := 0 for startIdx < len(n.nulls) { startIdx += copy(n.nulls[startIdx:], zeroedNulls[:]) } } // SetNulls sets the column to have only null values. func (n *Nulls) SetNulls() { n.hasNulls = true startIdx := 0 for startIdx < len(n.nulls) { startIdx += copy(n.nulls[startIdx:], filledNulls[:]) } } // NullAt64 returns true if the ith value of the column is null. func (n *Nulls) NullAt64(i uint64) bool { intIdx := i >> 6 return ((n.nulls[intIdx] >> (i % 64)) & 1) == 1 } // SetNull64 sets the ith value of the column to null. func (n *Nulls) SetNull64(i uint64) { n.hasNulls = true intIdx := i >> 6 n.nulls[intIdx] |= 1 << (i % 64) } // Extend extends the nulls vector with the next toAppend values from src, // starting at srcStartIdx. func (n *Nulls) Extend(src *Nulls, destStartIdx uint64, srcStartIdx uint16, toAppend uint16) { if toAppend == 0 { return } outputLen := destStartIdx + uint64(toAppend) // We will need ceil(outputLen/64) uint64s to encode the combined nulls. needed := (outputLen-1)/64 + 1 current := uint64(len(n.nulls)) if current < needed { n.nulls = append(n.nulls, make([]uint64, needed-current)...) } if src.HasNulls() { for i := uint16(0); i < toAppend; i++ { // TODO(yuzefovich): this can be done more efficiently with a bitwise OR: // like n.nulls[i] |= vec.nulls[i]. if src.NullAt(srcStartIdx + i) { n.SetNull64(destStartIdx + uint64(i)) } } } } // ExtendWithSel extends the nulls vector with the next toAppend values from // src, starting at srcStartIdx and using the provided selection vector. func (n *Nulls) ExtendWithSel( src *Nulls, destStartIdx uint64, srcStartIdx uint16, toAppend uint16, sel []uint16, ) { if toAppend == 0 { return } outputLen := destStartIdx + uint64(toAppend) // We will need ceil(outputLen/64) uint64s to encode the combined nulls. needed := (outputLen-1)/64 + 1 current := uint64(len(n.nulls)) if current < needed { n.nulls = append(n.nulls, make([]uint64, needed-current)...) } if src.HasNulls() { for i := uint16(0); i < toAppend; i++ { // TODO(yuzefovich): this can be done more efficiently with a bitwise OR: // like n.nulls[i] |= vec.nulls[i]. if src.NullAt(sel[srcStartIdx+i]) { n.SetNull64(destStartIdx + uint64(i)) } } } } // Slice returns a new Nulls representing a slice of the current Nulls from // [start, end). func (n *Nulls) Slice(start uint64, end uint64) Nulls { if !n.hasNulls { return NewNulls(int(end - start)) } mod := start % 64 startIdx := start >> 6 // end is exclusive, so translate that to an exclusive index in nulls by // figuring out which index the last accessible null should be in and add // 1. endIdx := (end-1)>>6 + 1 nulls := n.nulls[startIdx:endIdx] if mod != 0 { // If start is not a multiple of 64, we need to shift over the bitmap // to have the first index correspond. Allocate new null bitmap as we // want to keep the original bitmap safe for reuse. nulls = make([]uint64, len(nulls)) for i, j := startIdx, 0; i < endIdx-1; i, j = i+1, j+1 { // Bring the first null to the beginning. nulls[j] = n.nulls[i] >> mod // And now bitwise or the remaining bits with the bits we want to // bring over from the next index, note that we handle endIdx-1 // separately. nulls[j] |= (n.nulls[i+1] << (64 - mod)) } // Get the first bits to where we want them for endIdx-1. nulls[len(nulls)-1] = n.nulls[endIdx-1] >> mod } return Nulls{ nulls: nulls, hasNulls: true, } } // NullBitmap returns the null bitmap. func (n *Nulls) NullBitmap() []uint64 { return n.nulls } // SetNullBitmap sets the null bitmap. func (n *Nulls) SetNullBitmap(bm []uint64) { n.nulls = bm n.hasNulls = false for _, i := range bm { if i != 0 { n.hasNulls = true return } } }
pkg/sql/exec/coldata/nulls.go
0.712532
0.582075
nulls.go
starcoder
package pquerier import ( "encoding/binary" "math" "github.com/v3io/v3io-tsdb/pkg/aggregate" ) /* main query flow logic fire GetItems to all partitions and tables iterate over results from first to last partition hash lookup (over labels only w/o name) to find dataFrame if not found create new dataFrame based on hash dispatch work to one of the parallel collectors collectors convert raw/array data to series and aggregate or group once collectors are done (wg.done) return SeriesSet (prom compatible) or FrameSet (iguazio column interface) final aggregators (Avg, Stddav/var, ..) are formed from raw aggr in flight via iterators - Series: have a single name and optional aggregator per time series, values limited to Float64 - Frames: have index/time column(s) and multiple named/typed value columns (one per metric name * function) ** optionally can return SeriesSet (from dataFrames) to Prom immediately after we completed GetItems iterators and block (wg.done) the first time Prom tries to access the SeriesIter data (can lower latency) if result set needs to be ordered we can also sort the dataFrames based on Labels data (e.g. order-by username) in parallel to having all the time series data processed by the collectors */ /* collector logic: - get qryResults from chan - if raw query if first partition create series else append chunks to existing series - if vector query (results are bucketed over time or grouped by) if first partition create & init array per function (and per name) based on query metadata/results init child raw-chunk or attribute iterators iterate over data and fill bucketed arrays if missing time or data use interpolation - if got fin message and processed last item use sync waitgroup to signal the main that the go routines are done will allow main flow to continue and serve the results, no locks are required */ // Main collector which processes query results from a channel and then dispatches them according to query type. // Query types: raw data, server-side aggregates, client-side aggregates func mainCollector(ctx *selectQueryContext, responseChannel chan *qryResults) { defer ctx.wg.Done() lastTimePerMetric := make(map[string]int64, len(ctx.columnsSpecByMetric)) lastValuePerMetric := make(map[string]float64, len(ctx.columnsSpecByMetric)) for res := range responseChannel { if res.IsRawQuery() { rawCollector(ctx, res) } else { err := res.frame.addMetricIfNotExist(res.name, ctx.getResultBucketsSize(), res.IsServerAggregates()) if err != nil { ctx.logger.Error("problem adding new metric '%v', lset: %v, err:%v", res.name, res.frame.lset, err) ctx.errorChannel <- err return } if res.IsServerAggregates() { aggregateServerAggregates(ctx, res) } else if res.IsClientAggregates() { aggregateClientAggregates(ctx, res) } // It is possible to query an aggregate and down sample raw chunks in the same df. if res.IsDownsample() { lastTimePerMetric[res.name], lastValuePerMetric[res.name], err = downsampleRawData(ctx, res, lastTimePerMetric[res.name], lastValuePerMetric[res.name]) if err != nil { ctx.logger.Error("problem downsampling '%v', lset: %v, err:%v", res.name, res.frame.lset, err) ctx.errorChannel <- err return } } } } } func rawCollector(ctx *selectQueryContext, res *qryResults) { frameIndex, ok := res.frame.columnByName[res.name] if ok { res.frame.rawColumns[frameIndex].(*V3ioRawSeries).AddChunks(res) } else { series, err := NewRawSeries(res, ctx.logger.GetChild("v3ioRawSeries")) if err != nil { ctx.errorChannel <- err return } res.frame.rawColumns = append(res.frame.rawColumns, series) res.frame.columnByName[res.name] = len(res.frame.rawColumns) - 1 } } func aggregateClientAggregates(ctx *selectQueryContext, res *qryResults) { it := newRawChunkIterator(res, nil) for it.Next() { t, v := it.At() currentCell := (t - ctx.mint) / res.query.aggregationParams.Interval for _, col := range res.frame.columns { if col.GetColumnSpec().metric == res.name { col.SetDataAt(int(currentCell), v) } } } } func aggregateServerAggregates(ctx *selectQueryContext, res *qryResults) { partitionStartTime := res.query.partition.GetStartTime() rollupInterval := res.query.aggregationParams.GetRollupTime() for _, col := range res.frame.columns { if col.GetColumnSpec().metric == res.name && aggregate.HasAggregates(col.GetColumnSpec().function) && col.GetColumnSpec().isConcrete() { array, ok := res.fields[aggregate.ToAttrName(col.GetColumnSpec().function)] if !ok { ctx.logger.Warn("requested function %v was not found in response", col.GetColumnSpec().function) } else { // go over the byte array and convert each uint as we go to save memory allocation bytes := array.([]byte) for i := 16; i+8 <= len(bytes); i += 8 { val := binary.LittleEndian.Uint64(bytes[i : i+8]) currentValueIndex := (i - 16) / 8 currentValueTime := partitionStartTime + int64(currentValueIndex+1)*rollupInterval currentCell := (currentValueTime - ctx.mint) / res.query.aggregationParams.Interval var floatVal float64 if aggregate.IsCountAggregate(col.GetColumnSpec().function) { floatVal = float64(val) } else { floatVal = math.Float64frombits(val) } col.SetDataAt(int(currentCell), floatVal) } } } } } func downsampleRawData(ctx *selectQueryContext, res *qryResults, previousPartitionLastTime int64, previousPartitionLastValue float64) (int64, float64, error) { var lastT int64 var lastV float64 it := newRawChunkIterator(res, nil).(*rawChunkIterator) col, err := res.frame.Column(res.name) if err != nil { return previousPartitionLastTime, previousPartitionLastValue, err } for currBucket := 0; currBucket < col.Len(); currBucket++ { currBucketTime := int64(currBucket)*ctx.step + ctx.mint if it.Seek(currBucketTime) { t, v := it.At() tBucketIndex := (t - ctx.mint) / ctx.step if t == currBucketTime { col.SetDataAt(currBucket, v) } else if tBucketIndex == int64(currBucket) { prevT, prevV := it.PeakBack() // In case it's the first point in the partition use the last point of the previous partition for the interpolation if prevT == 0 { prevT = previousPartitionLastTime prevV = previousPartitionLastValue } // If previous point is too old for interpolation interpolateFunc, tolerance := col.GetInterpolationFunction() if prevT != 0 && t-prevT > tolerance { col.SetDataAt(currBucket, math.NaN()) } else { _, interpolatedV := interpolateFunc(prevT, t, currBucketTime, prevV, v) col.SetDataAt(currBucket, interpolatedV) } } else { col.SetDataAt(currBucket, math.NaN()) } } else { lastT, lastV = it.At() col.SetDataAt(currBucket, math.NaN()) } } return lastT, lastV, nil }
vendor/github.com/v3io/v3io-tsdb/pkg/pquerier/collector.go
0.566378
0.477676
collector.go
starcoder
package plaid import ( "encoding/json" ) // RecipientBACSNullable struct for RecipientBACSNullable type RecipientBACSNullable struct { // The account number of the account. Maximum of 10 characters. Account *string `json:"account,omitempty"` // The 6-character sort code of the account. SortCode *string `json:"sort_code,omitempty"` } // NewRecipientBACSNullable instantiates a new RecipientBACSNullable 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 NewRecipientBACSNullable() *RecipientBACSNullable { this := RecipientBACSNullable{} return &this } // NewRecipientBACSNullableWithDefaults instantiates a new RecipientBACSNullable 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 NewRecipientBACSNullableWithDefaults() *RecipientBACSNullable { this := RecipientBACSNullable{} return &this } // GetAccount returns the Account field value if set, zero value otherwise. func (o *RecipientBACSNullable) GetAccount() string { if o == nil || o.Account == nil { var ret string return ret } return *o.Account } // GetAccountOk returns a tuple with the Account field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *RecipientBACSNullable) GetAccountOk() (*string, bool) { if o == nil || o.Account == nil { return nil, false } return o.Account, true } // HasAccount returns a boolean if a field has been set. func (o *RecipientBACSNullable) HasAccount() bool { if o != nil && o.Account != nil { return true } return false } // SetAccount gets a reference to the given string and assigns it to the Account field. func (o *RecipientBACSNullable) SetAccount(v string) { o.Account = &v } // GetSortCode returns the SortCode field value if set, zero value otherwise. func (o *RecipientBACSNullable) GetSortCode() string { if o == nil || o.SortCode == nil { var ret string return ret } return *o.SortCode } // GetSortCodeOk returns a tuple with the SortCode field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *RecipientBACSNullable) GetSortCodeOk() (*string, bool) { if o == nil || o.SortCode == nil { return nil, false } return o.SortCode, true } // HasSortCode returns a boolean if a field has been set. func (o *RecipientBACSNullable) HasSortCode() bool { if o != nil && o.SortCode != nil { return true } return false } // SetSortCode gets a reference to the given string and assigns it to the SortCode field. func (o *RecipientBACSNullable) SetSortCode(v string) { o.SortCode = &v } func (o RecipientBACSNullable) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Account != nil { toSerialize["account"] = o.Account } if o.SortCode != nil { toSerialize["sort_code"] = o.SortCode } return json.Marshal(toSerialize) } type NullableRecipientBACSNullable struct { value *RecipientBACSNullable isSet bool } func (v NullableRecipientBACSNullable) Get() *RecipientBACSNullable { return v.value } func (v *NullableRecipientBACSNullable) Set(val *RecipientBACSNullable) { v.value = val v.isSet = true } func (v NullableRecipientBACSNullable) IsSet() bool { return v.isSet } func (v *NullableRecipientBACSNullable) Unset() { v.value = nil v.isSet = false } func NewNullableRecipientBACSNullable(val *RecipientBACSNullable) *NullableRecipientBACSNullable { return &NullableRecipientBACSNullable{value: val, isSet: true} } func (v NullableRecipientBACSNullable) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableRecipientBACSNullable) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
plaid/model_recipient_bacs_nullable.go
0.765067
0.606528
model_recipient_bacs_nullable.go
starcoder
package pair import ( "fmt" "math" "sort" ) type Point struct { x, y float64 } func NewPoint(x, y float64) *Point { return &Point{x, y} } func (p *Point) String() string { return fmt.Sprintf("P(%f,%f)", p.x, p.y) } func (p *Point) X() float64 { return p.x } func (p *Point) Y() float64 { return p.y } func (p *Point) Distance(p2 *Point) float64 { return math.Sqrt(math.Pow(p.x-p2.x, 2) + math.Pow(p.y-p2.y, 2)) } func Distance(p1, p2 *Point) float64 { return p1.Distance(p2) } type Points []*Point func NewPoints(ps []*Point) Points { return Points(ps) } func (ps Points) Len() int { return len(ps) } func (ps Points) Swap(i, j int) { ps[i], ps[j] = ps[j], ps[i] } type ByX struct { Points } func (ps ByX) Less(i, j int) bool { return ps.Points[i].x < ps.Points[j].x } type ByY struct { Points } func (ps ByY) Less(i, j int) bool { return ps.Points[i].y < ps.Points[j].y } type Indices struct { Indices []int sort.Interface } func NewIndices(underlying sort.Interface) Indices { indices := []int(nil) for i := 0; i < underlying.Len(); i++ { indices = append(indices, i) } return Indices{indices, underlying} } func (ids Indices) Swap(i, j int) { ids.Indices[i], ids.Indices[j] = ids.Indices[j], ids.Indices[i] } func (ids Indices) Less(i, j int) bool { return ids.Interface.Less(ids.Indices[i], ids.Indices[j]) } func ClosestPair(ps []*Point) (*Point, *Point, float64) { switch len(ps) { case 0, 1: return nil, nil, math.MaxFloat64 case 2: return ps[0], ps[1], Distance(ps[0], ps[1]) } pa := NewPoints(ps) sort.Sort(ByX{pa}) pyi := NewIndices(ByY{pa}) sort.Sort(pyi) return dccPair(ps, pyi.Indices, pa) } func dccPair(ps []*Point, pyi []int, pa Points) (*Point, *Point, float64) { switch len(ps) { case 2: return ps[0], ps[1], Distance(ps[0], ps[1]) case 3: d01 := Distance(ps[0], ps[1]) d02 := Distance(ps[0], ps[2]) d12 := Distance(ps[1], ps[2]) if d01 <= d02 { if d12 <= d01 { return ps[1], ps[2], d12 } return ps[0], ps[1], d01 } if d12 <= d02 { return ps[1], ps[2], d12 } return ps[0], ps[2], d02 } // TODO use goroutine pl1, pl2, dl := dccPair(ps[:len(ps)/2], pyi, pa) pr1, pr2, dr := dccPair(ps[len(ps)/2:], pyi, pa) d := math.Min(dl, dr) sp := []*Point(nil) px := ps[len(ps)/2] for i := 0; i < len(pyi); i++ { p := pa[pyi[i]] if math.Abs(p.x-px.x) <= d && math.Abs(p.y-px.y) <= d { sp = append(sp, p) } } ps1, ps2, ds := closestSplitPair(sp) if ds <= d { return ps1, ps2, ds } if dl <= dr { return pl1, pl2, dl } return pr1, pr2, dr } func closestSplitPair(ps []*Point) (ps1 *Point, ps2 *Point, d float64) { switch len(ps) { case 0, 1: return nil, nil, math.MaxFloat64 case 2: return ps[0], ps[1], Distance(ps[0], ps[1]) } d = math.MaxFloat64 n := int(math.Min(7, float64(len(ps)))) for i := 0; i <= len(ps)-n; i++ { for j := i + 1; j < n; j++ { ds := Distance(ps[i], ps[j]) if ds < d { ps1, ps2, d = ps[i], ps[j], ds } } } return }
pair/pair.go
0.611498
0.533701
pair.go
starcoder
package inmemory import ( "fmt" "regexp" "strings" "go.jlucktay.dev/arrowverse/pkg/models" ) type subexpressionName string func (s subexpressionName) String() string { return string(s) } const ( multiPartNumber subexpressionName = "mpn" multiPartTitle subexpressionName = "mpt" ) var ( rePart = regexp.MustCompile(`^(?P<` + multiPartTitle.String() + `>.*) Part (?P<` + multiPartNumber.String() + `>[0-9a-zA-Z]+)$`) numbers = strings.NewReplacer("One", "1", "Two", "2", "Three", "3", "Four", "4", "Five", "5", "Six", "6", "Seven", "7", "Eight", "8", "Nine", "9") airOrderByYear = map[int][]models.ShowName{ 2016: { models.DCsLegendsOfTomorrow, models.Vixen, }, 2017: { models.TheFlashTheCW, models.DCsLegendsOfTomorrow, }, 2018: { models.TheFlashTheCW, models.Supergirl, models.BlackLightning, models.Arrow, models.DCsLegendsOfTomorrow, }, 2019: { models.DCsLegendsOfTomorrow, models.TheFlashTheCW, models.Arrow, models.Batwoman, models.BlackLightning, models.Supergirl, }, 2020: { models.Batwoman, models.Supergirl, models.TheFlashTheCW, models.Arrow, models.DCsLegendsOfTomorrow, }, } ) // ByAirdate implements sort.Interface for []*models.Episode based on the Airdate field. type ByAirdate []models.Episode func (a ByAirdate) Len() int { return len(a) } func (a ByAirdate) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByAirdate) Less(i, j int) bool { // KISS; compare airdates first, and ONLY if they differ, go ahead with other logic if !a[i].Airdate.Equal(a[j].Airdate) { return a[i].Airdate.Before(a[j].Airdate) } // If the two episodes are from the same show, go by overall episode number if a[i].Season.Show.Name == a[j].Season.Show.Name { return a[i].EpisodeOverall < a[j].EpisodeOverall } // So now the two episodes aren't from the same show, but have the same airdate, and could be a multi-part/crossover if rePart.MatchString(a[i].Name) && rePart.MatchString(a[j].Name) { // At this point, both episode titles match the regex and contain '... Part ...', and are not from the same show iMatches := rePart.FindStringSubmatch(a[i].Name) jMatches := rePart.FindStringSubmatch(a[j].Name) titleIndex := rePart.SubexpIndex(multiPartTitle.String()) // True if the multi-part/crossover has the same title, e.g. 'Crisis on Infinite Earths' if iMatches[titleIndex] == jMatches[titleIndex] { partNumberIndex := rePart.SubexpIndex(multiPartNumber.String()) iPartNumber := numbers.Replace(iMatches[partNumberIndex]) jPartNumber := numbers.Replace(jMatches[partNumberIndex]) return iPartNumber < jPartNumber } } // If the previous block has not returned and flow has fallen through to this logic, at this point the two episodes // are not from the same show nor are they part of the same multi-part/crossover, but they did air on the same date // so we need to go through the air order, which is different in different years checkAirOrderYear := 0 for year := range airOrderByYear { if year == a[i].Airdate.Year() { checkAirOrderYear = year break } } if checkAirOrderYear == 0 { return a[i].Airdate.Before(a[j].Airdate) } for _, showname := range airOrderByYear[checkAirOrderYear] { if showname == a[i].Season.Show.Name { return true } if showname == a[j].Season.Show.Name { return false } } // Neither show name turned up in the air orderings, so ... TODO? panic(fmt.Sprintf("Not sure what to do with these two episodes at this point:\n%s\n%s\n", a[i], a[j])) }
pkg/collection/inmemory/sort.go
0.54698
0.407451
sort.go
starcoder
package copypasta import ( "math" "math/bits" ) /* FFT: fast Fourier transform 快速傅里叶变换 https://en.wikipedia.org/wiki/Fast_Fourier_transform 【推荐】一小时学会快速傅里叶变换 https://zhuanlan.zhihu.com/p/31584464 傅里叶变换学习笔记 https://www.luogu.com.cn/blog/command-block/fft-xue-xi-bi-ji 从多项式乘法到快速傅里叶变换 http://blog.miskcoo.com/2015/04/polynomial-multiplication-and-fast-fourier-transform 优化技巧 https://www.luogu.com.cn/blog/105254/qian-tan-fft-zong-ft-dao-fft https://codeforces.com/blog/entry/43499 https://codeforces.com/blog/entry/48798 https://oi-wiki.org/math/poly/fft/ https://cp-algorithms.com/algebra/fft.html https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/FFT.java.html https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/Polynomial.java.html 有关快速数论变换 (NTT) 以及多项式运算的内容见 math_ntt.go 模板题 https://www.luogu.com.cn/problem/P3803 todo 推式子 https://www.luogu.com.cn/problem/P3338 花絮 https://zhuanlan.zhihu.com/p/349249817 */ type fft struct { n int omega, omegaInv []complex128 } func newFFT(n int) *fft { omega := make([]complex128, n) omegaInv := make([]complex128, n) for i := range omega { sin, cos := math.Sincos(2 * math.Pi * float64(i) / float64(n)) omega[i] = complex(cos, sin) omegaInv[i] = complex(cos, -sin) } return &fft{n, omega, omegaInv} } // 注:下面 swap 的代码,另一种写法是初始化每个 i 对应的 j https://blog.csdn.net/Flag_z/article/details/99163939 func (t *fft) transform(a, omega []complex128) { for i, j := 0, 0; i < t.n; i++ { if i > j { a[i], a[j] = a[j], a[i] } for l := t.n >> 1; ; l >>= 1 { j ^= l if j >= l { break } } } for l := 2; l <= t.n; l <<= 1 { m := l >> 1 for st := 0; st < t.n; st += l { b := a[st:] for i := 0; i < m; i++ { d := omega[t.n/l*i] * b[m+i] b[m+i] = b[i] - d b[i] += d } } } } func (t *fft) dft(a []complex128) { t.transform(a, t.omega) } func (t *fft) idft(a []complex128) { t.transform(a, t.omegaInv) cn := complex(float64(t.n), 0) for i := range a { a[i] /= cn } } // 计算 A(x) 和 B(x) 的卷积 (convolution) // 入参出参都是次项从低到高的系数 // 建议全程用 int64 func polyConvFFT(a, b []int64) []int64 { n, m := len(a), len(b) limit := 1 << bits.Len(uint(n+m-1)) A := make([]complex128, limit) for i, v := range a { A[i] = complex(float64(v), 0) } B := make([]complex128, limit) for i, v := range b { B[i] = complex(float64(v), 0) } t := newFFT(limit) t.dft(A) t.dft(B) for i := range A { A[i] *= B[i] } t.idft(A) conv := make([]int64, n+m-1) for i := range conv { conv[i] = int64(math.Round(real(A[i]))) // % mod } return conv } // 计算多个多项式的卷积 // 入参出参都是次项从低到高的系数 // 可重集大小为 k 的不同子集个数 https://codeforces.com/contest/958/problem/F3 func polyConvFFTs(coefs [][]int64) []int64 { n := len(coefs) if n == 1 { return coefs[0] } return polyConvFFT(polyConvFFTs(coefs[:n/2]), polyConvFFTs(coefs[n/2:])) }
copypasta/math_fft.go
0.515864
0.473962
math_fft.go
starcoder
package transformation import ( "bytes" "encoding/binary" "errors" "fmt" "strings" "github.com/golang/protobuf/proto" equality "github.com/solo-io/protoc-gen-ext/pkg/equality" ) // ensure the imports are used var ( _ = errors.New("") _ = fmt.Print _ = binary.LittleEndian _ = bytes.Compare _ = strings.Compare _ = equality.Equalizer(nil) _ = proto.Message(nil) ) // Equal function func (m *FilterTransformations) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*FilterTransformations) if !ok { that2, ok := that.(FilterTransformations) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if len(m.GetTransformations()) != len(target.GetTransformations()) { return false } for idx, v := range m.GetTransformations() { if h, ok := interface{}(v).(equality.Equalizer); ok { if !h.Equal(target.GetTransformations()[idx]) { return false } } else { if !proto.Equal(v, target.GetTransformations()[idx]) { return false } } } if m.GetStage() != target.GetStage() { return false } return true } // Equal function func (m *TransformationRule) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*TransformationRule) if !ok { that2, ok := that.(TransformationRule) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if h, ok := interface{}(m.GetMatch()).(equality.Equalizer); ok { if !h.Equal(target.GetMatch()) { return false } } else { if !proto.Equal(m.GetMatch(), target.GetMatch()) { return false } } if h, ok := interface{}(m.GetRouteTransformations()).(equality.Equalizer); ok { if !h.Equal(target.GetRouteTransformations()) { return false } } else { if !proto.Equal(m.GetRouteTransformations(), target.GetRouteTransformations()) { return false } } return true } // Equal function func (m *RouteTransformations) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*RouteTransformations) if !ok { that2, ok := that.(RouteTransformations) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if h, ok := interface{}(m.GetRequestTransformation()).(equality.Equalizer); ok { if !h.Equal(target.GetRequestTransformation()) { return false } } else { if !proto.Equal(m.GetRequestTransformation(), target.GetRequestTransformation()) { return false } } if h, ok := interface{}(m.GetResponseTransformation()).(equality.Equalizer); ok { if !h.Equal(target.GetResponseTransformation()) { return false } } else { if !proto.Equal(m.GetResponseTransformation(), target.GetResponseTransformation()) { return false } } if m.GetClearRouteCache() != target.GetClearRouteCache() { return false } if len(m.GetTransformations()) != len(target.GetTransformations()) { return false } for idx, v := range m.GetTransformations() { if h, ok := interface{}(v).(equality.Equalizer); ok { if !h.Equal(target.GetTransformations()[idx]) { return false } } else { if !proto.Equal(v, target.GetTransformations()[idx]) { return false } } } return true } // Equal function func (m *ResponseMatcher) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*ResponseMatcher) if !ok { that2, ok := that.(ResponseMatcher) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if len(m.GetHeaders()) != len(target.GetHeaders()) { return false } for idx, v := range m.GetHeaders() { if h, ok := interface{}(v).(equality.Equalizer); ok { if !h.Equal(target.GetHeaders()[idx]) { return false } } else { if !proto.Equal(v, target.GetHeaders()[idx]) { return false } } } if h, ok := interface{}(m.GetResponseCodeDetails()).(equality.Equalizer); ok { if !h.Equal(target.GetResponseCodeDetails()) { return false } } else { if !proto.Equal(m.GetResponseCodeDetails(), target.GetResponseCodeDetails()) { return false } } return true } // Equal function func (m *ResponseTransformationRule) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*ResponseTransformationRule) if !ok { that2, ok := that.(ResponseTransformationRule) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if h, ok := interface{}(m.GetMatch()).(equality.Equalizer); ok { if !h.Equal(target.GetMatch()) { return false } } else { if !proto.Equal(m.GetMatch(), target.GetMatch()) { return false } } if h, ok := interface{}(m.GetResponseTransformation()).(equality.Equalizer); ok { if !h.Equal(target.GetResponseTransformation()) { return false } } else { if !proto.Equal(m.GetResponseTransformation(), target.GetResponseTransformation()) { return false } } return true } // Equal function func (m *Transformation) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*Transformation) if !ok { that2, ok := that.(Transformation) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } switch m.TransformationType.(type) { case *Transformation_TransformationTemplate: if _, ok := target.TransformationType.(*Transformation_TransformationTemplate); !ok { return false } if h, ok := interface{}(m.GetTransformationTemplate()).(equality.Equalizer); ok { if !h.Equal(target.GetTransformationTemplate()) { return false } } else { if !proto.Equal(m.GetTransformationTemplate(), target.GetTransformationTemplate()) { return false } } case *Transformation_HeaderBodyTransform: if _, ok := target.TransformationType.(*Transformation_HeaderBodyTransform); !ok { return false } if h, ok := interface{}(m.GetHeaderBodyTransform()).(equality.Equalizer); ok { if !h.Equal(target.GetHeaderBodyTransform()) { return false } } else { if !proto.Equal(m.GetHeaderBodyTransform(), target.GetHeaderBodyTransform()) { return false } } case *Transformation_TransformerConfig: if _, ok := target.TransformationType.(*Transformation_TransformerConfig); !ok { return false } if h, ok := interface{}(m.GetTransformerConfig()).(equality.Equalizer); ok { if !h.Equal(target.GetTransformerConfig()) { return false } } else { if !proto.Equal(m.GetTransformerConfig(), target.GetTransformerConfig()) { return false } } default: // m is nil but target is not nil if m.TransformationType != target.TransformationType { return false } } return true } // Equal function func (m *Extraction) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*Extraction) if !ok { that2, ok := that.(Extraction) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if strings.Compare(m.GetRegex(), target.GetRegex()) != 0 { return false } if m.GetSubgroup() != target.GetSubgroup() { return false } switch m.Source.(type) { case *Extraction_Header: if _, ok := target.Source.(*Extraction_Header); !ok { return false } if strings.Compare(m.GetHeader(), target.GetHeader()) != 0 { return false } case *Extraction_Body: if _, ok := target.Source.(*Extraction_Body); !ok { return false } if h, ok := interface{}(m.GetBody()).(equality.Equalizer); ok { if !h.Equal(target.GetBody()) { return false } } else { if !proto.Equal(m.GetBody(), target.GetBody()) { return false } } default: // m is nil but target is not nil if m.Source != target.Source { return false } } return true } // Equal function func (m *TransformationTemplate) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*TransformationTemplate) if !ok { that2, ok := that.(TransformationTemplate) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if m.GetAdvancedTemplates() != target.GetAdvancedTemplates() { return false } if len(m.GetExtractors()) != len(target.GetExtractors()) { return false } for k, v := range m.GetExtractors() { if h, ok := interface{}(v).(equality.Equalizer); ok { if !h.Equal(target.GetExtractors()[k]) { return false } } else { if !proto.Equal(v, target.GetExtractors()[k]) { return false } } } if len(m.GetHeaders()) != len(target.GetHeaders()) { return false } for k, v := range m.GetHeaders() { if h, ok := interface{}(v).(equality.Equalizer); ok { if !h.Equal(target.GetHeaders()[k]) { return false } } else { if !proto.Equal(v, target.GetHeaders()[k]) { return false } } } if len(m.GetHeadersToAppend()) != len(target.GetHeadersToAppend()) { return false } for idx, v := range m.GetHeadersToAppend() { if h, ok := interface{}(v).(equality.Equalizer); ok { if !h.Equal(target.GetHeadersToAppend()[idx]) { return false } } else { if !proto.Equal(v, target.GetHeadersToAppend()[idx]) { return false } } } if m.GetParseBodyBehavior() != target.GetParseBodyBehavior() { return false } if m.GetIgnoreErrorOnParse() != target.GetIgnoreErrorOnParse() { return false } if len(m.GetDynamicMetadataValues()) != len(target.GetDynamicMetadataValues()) { return false } for idx, v := range m.GetDynamicMetadataValues() { if h, ok := interface{}(v).(equality.Equalizer); ok { if !h.Equal(target.GetDynamicMetadataValues()[idx]) { return false } } else { if !proto.Equal(v, target.GetDynamicMetadataValues()[idx]) { return false } } } switch m.BodyTransformation.(type) { case *TransformationTemplate_Body: if _, ok := target.BodyTransformation.(*TransformationTemplate_Body); !ok { return false } if h, ok := interface{}(m.GetBody()).(equality.Equalizer); ok { if !h.Equal(target.GetBody()) { return false } } else { if !proto.Equal(m.GetBody(), target.GetBody()) { return false } } case *TransformationTemplate_Passthrough: if _, ok := target.BodyTransformation.(*TransformationTemplate_Passthrough); !ok { return false } if h, ok := interface{}(m.GetPassthrough()).(equality.Equalizer); ok { if !h.Equal(target.GetPassthrough()) { return false } } else { if !proto.Equal(m.GetPassthrough(), target.GetPassthrough()) { return false } } case *TransformationTemplate_MergeExtractorsToBody: if _, ok := target.BodyTransformation.(*TransformationTemplate_MergeExtractorsToBody); !ok { return false } if h, ok := interface{}(m.GetMergeExtractorsToBody()).(equality.Equalizer); ok { if !h.Equal(target.GetMergeExtractorsToBody()) { return false } } else { if !proto.Equal(m.GetMergeExtractorsToBody(), target.GetMergeExtractorsToBody()) { return false } } default: // m is nil but target is not nil if m.BodyTransformation != target.BodyTransformation { return false } } return true } // Equal function func (m *InjaTemplate) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*InjaTemplate) if !ok { that2, ok := that.(InjaTemplate) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if strings.Compare(m.GetText(), target.GetText()) != 0 { return false } return true } // Equal function func (m *Passthrough) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*Passthrough) if !ok { that2, ok := that.(Passthrough) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } return true } // Equal function func (m *MergeExtractorsToBody) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*MergeExtractorsToBody) if !ok { that2, ok := that.(MergeExtractorsToBody) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } return true } // Equal function func (m *HeaderBodyTransform) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*HeaderBodyTransform) if !ok { that2, ok := that.(HeaderBodyTransform) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } return true } // Equal function func (m *TransformationRule_Transformations) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*TransformationRule_Transformations) if !ok { that2, ok := that.(TransformationRule_Transformations) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if h, ok := interface{}(m.GetRequestTransformation()).(equality.Equalizer); ok { if !h.Equal(target.GetRequestTransformation()) { return false } } else { if !proto.Equal(m.GetRequestTransformation(), target.GetRequestTransformation()) { return false } } if m.GetClearRouteCache() != target.GetClearRouteCache() { return false } if h, ok := interface{}(m.GetResponseTransformation()).(equality.Equalizer); ok { if !h.Equal(target.GetResponseTransformation()) { return false } } else { if !proto.Equal(m.GetResponseTransformation(), target.GetResponseTransformation()) { return false } } if h, ok := interface{}(m.GetOnStreamCompletionTransformation()).(equality.Equalizer); ok { if !h.Equal(target.GetOnStreamCompletionTransformation()) { return false } } else { if !proto.Equal(m.GetOnStreamCompletionTransformation(), target.GetOnStreamCompletionTransformation()) { return false } } return true } // Equal function func (m *RouteTransformations_RouteTransformation) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*RouteTransformations_RouteTransformation) if !ok { that2, ok := that.(RouteTransformations_RouteTransformation) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if m.GetStage() != target.GetStage() { return false } switch m.Match.(type) { case *RouteTransformations_RouteTransformation_RequestMatch_: if _, ok := target.Match.(*RouteTransformations_RouteTransformation_RequestMatch_); !ok { return false } if h, ok := interface{}(m.GetRequestMatch()).(equality.Equalizer); ok { if !h.Equal(target.GetRequestMatch()) { return false } } else { if !proto.Equal(m.GetRequestMatch(), target.GetRequestMatch()) { return false } } case *RouteTransformations_RouteTransformation_ResponseMatch_: if _, ok := target.Match.(*RouteTransformations_RouteTransformation_ResponseMatch_); !ok { return false } if h, ok := interface{}(m.GetResponseMatch()).(equality.Equalizer); ok { if !h.Equal(target.GetResponseMatch()) { return false } } else { if !proto.Equal(m.GetResponseMatch(), target.GetResponseMatch()) { return false } } default: // m is nil but target is not nil if m.Match != target.Match { return false } } return true } // Equal function func (m *RouteTransformations_RouteTransformation_RequestMatch) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*RouteTransformations_RouteTransformation_RequestMatch) if !ok { that2, ok := that.(RouteTransformations_RouteTransformation_RequestMatch) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if h, ok := interface{}(m.GetMatch()).(equality.Equalizer); ok { if !h.Equal(target.GetMatch()) { return false } } else { if !proto.Equal(m.GetMatch(), target.GetMatch()) { return false } } if h, ok := interface{}(m.GetRequestTransformation()).(equality.Equalizer); ok { if !h.Equal(target.GetRequestTransformation()) { return false } } else { if !proto.Equal(m.GetRequestTransformation(), target.GetRequestTransformation()) { return false } } if h, ok := interface{}(m.GetResponseTransformation()).(equality.Equalizer); ok { if !h.Equal(target.GetResponseTransformation()) { return false } } else { if !proto.Equal(m.GetResponseTransformation(), target.GetResponseTransformation()) { return false } } if m.GetClearRouteCache() != target.GetClearRouteCache() { return false } return true } // Equal function func (m *RouteTransformations_RouteTransformation_ResponseMatch) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*RouteTransformations_RouteTransformation_ResponseMatch) if !ok { that2, ok := that.(RouteTransformations_RouteTransformation_ResponseMatch) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if h, ok := interface{}(m.GetMatch()).(equality.Equalizer); ok { if !h.Equal(target.GetMatch()) { return false } } else { if !proto.Equal(m.GetMatch(), target.GetMatch()) { return false } } if h, ok := interface{}(m.GetResponseTransformation()).(equality.Equalizer); ok { if !h.Equal(target.GetResponseTransformation()) { return false } } else { if !proto.Equal(m.GetResponseTransformation(), target.GetResponseTransformation()) { return false } } return true } // Equal function func (m *TransformationTemplate_HeaderToAppend) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*TransformationTemplate_HeaderToAppend) if !ok { that2, ok := that.(TransformationTemplate_HeaderToAppend) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if strings.Compare(m.GetKey(), target.GetKey()) != 0 { return false } if h, ok := interface{}(m.GetValue()).(equality.Equalizer); ok { if !h.Equal(target.GetValue()) { return false } } else { if !proto.Equal(m.GetValue(), target.GetValue()) { return false } } return true } // Equal function func (m *TransformationTemplate_DynamicMetadataValue) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*TransformationTemplate_DynamicMetadataValue) if !ok { that2, ok := that.(TransformationTemplate_DynamicMetadataValue) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if strings.Compare(m.GetMetadataNamespace(), target.GetMetadataNamespace()) != 0 { return false } if strings.Compare(m.GetKey(), target.GetKey()) != 0 { return false } if h, ok := interface{}(m.GetValue()).(equality.Equalizer); ok { if !h.Equal(target.GetValue()) { return false } } else { if !proto.Equal(m.GetValue(), target.GetValue()) { return false } } return true }
projects/gloo/pkg/api/external/envoy/extensions/transformation/transformation.pb.equal.go
0.632049
0.424412
transformation.pb.equal.go
starcoder
// Package jwtauth provides functions and structs that allowes the generation // and validation of JWTs package jwtauth import ( "errors" "time" jwt "github.com/dgrijalva/jwt-go" ) // JwtWrapper represents the wrapper that contains values of the JWT except for // the claims type JwtWrapper struct { SecretKey string Issuer string ExpirationSeconds int64 } // JwtClaim contains the claims that will issue the JWT. type JwtClaim struct { Email string jwt.StandardClaims } // GenerateToken creates a signed token with an email claim, identifying the user // Param email: Email identifying the user // Return signedToken: Signed JWT Token // Return err: Error, if any func (j *JwtWrapper) GenerateToken(email string) (signedToken string, err error) { claims := &JwtClaim{ Email: email, StandardClaims: jwt.StandardClaims{ ExpiresAt: time.Now().Local().Add(time.Second * time.Duration(j.ExpirationSeconds)).Unix(), Issuer: j.Issuer, }, } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) signedToken, err = token.SignedString([]byte(j.SecretKey)) return signedToken, err } // GetEmailToken returns the email associated with the jwt token func GetEmailToken(token string) (string, error) { var email string var err error tok, _ := jwt.ParseWithClaims( token, &JwtClaim{}, func(token *jwt.Token) (interface{}, error) { return []byte(token.Signature), nil }, ) if tok != nil { claims, ok := tok.Claims.(*JwtClaim) if !ok { err = errors.New("couldn't parse claims") return email, err } if claims.ExpiresAt < time.Now().Local().Unix() { err = errors.New("JWT is expired") return email, err } email = claims.Email } return email, err } // ValidateToken validates the token signedToken and returns the claims // Param signedToken: Token that will be validated // Return claims: *JwtClaim that the token is claiming // Return err: error if something is wrong or if validation is unsuccessful func (j *JwtWrapper) ValidateToken(signedToken string) (claims *JwtClaim, err error) { token, err := jwt.ParseWithClaims( signedToken, &JwtClaim{}, func(token *jwt.Token) (interface{}, error) { return []byte(j.SecretKey), nil }, ) //Para validar en realidad tendre que hacer nuevas funciones que //separen validacion de secreto de obtencion de claims if err != nil { return } claims, ok := token.Claims.(*JwtClaim) if !ok { err = errors.New("couldn't parse claims") return } if claims.ExpiresAt < time.Now().Local().Unix() { err = errors.New("JWT is expired") return } return }
BackEnd/jwtauth/jwtauth.go
0.672224
0.444625
jwtauth.go
starcoder
package vectormath import "fmt" const g_SLERP_TOL = 0.999 func V3Copy(result *Vector3, vec *Vector3) { result.X = vec.X result.Y = vec.Y result.Z = vec.Z } func V3MakeFromElems(result *Vector3, x, y, z float32) { result.X = x result.Y = y result.Z = z } func V3MakeFromP3(result *Vector3, pnt *Point3) { result.X = pnt.X result.Y = pnt.Y result.Z = pnt.Z } func V3MakeFromScalar(result *Vector3, scalar float32) { result.X = scalar result.Y = scalar result.Z = scalar } func V3MakeXAxis(result *Vector3) { V3MakeFromElems(result, 1.0, 0.0, 0.0) } func V3MakeYAxis(result *Vector3) { V3MakeFromElems(result, 0.0, 1.0, 0.0) } func V3MakeZAxis(result *Vector3) { V3MakeFromElems(result, 0.0, 0.0, 1.0) } func V3Lerp(result *Vector3, t float32, vec0, vec1 *Vector3) { var tmpV3_0, tmpV3_1 Vector3 V3Sub(&tmpV3_0, vec1, vec0) V3ScalarMul(&tmpV3_1, &tmpV3_0, t) V3Add(result, vec0, &tmpV3_1) } func V3Slerp(result *Vector3, t float32, unitVec0, unitVec1 *Vector3) { var tmpV3_0, tmpV3_1 Vector3 var scale0, scale1 float32 cosAngle := V3Dot(unitVec0, unitVec1) if cosAngle < g_SLERP_TOL { angle := acos(cosAngle) recipSinAngle := 1.0 / sin(angle) scale0 = (sin(((1.0 - t) * angle)) * recipSinAngle) scale1 = (sin((t * angle)) * recipSinAngle) } else { scale0 = 1.0 - t scale1 = t } V3ScalarMul(&tmpV3_0, unitVec0, scale0) V3ScalarMul(&tmpV3_1, unitVec1, scale1) V3Add(result, &tmpV3_0, &tmpV3_1) } func (v *Vector3) SetX(x float32) { v.X = x } func (v *Vector3) SetY(y float32) { v.Y = y } func (v *Vector3) SetZ(z float32) { v.Z = z } func (v *Vector3) SetElem(index int, value float32) { switch index { case 0: v.X = value case 1: v.Y = value case 2: v.Z = value } } func (v *Vector3) GetElem(index int) float32 { switch index { case 0: return v.X case 1: return v.Y case 2: return v.Z } return 0 } func V3Add(result, vec0, vec1 *Vector3) { result.X = vec0.X + vec1.X result.Y = vec0.Y + vec1.Y result.Z = vec0.Z + vec1.Z } func V3Sub(result, vec0, vec1 *Vector3) { result.X = vec0.X - vec1.X result.Y = vec0.Y - vec1.Y result.Z = vec0.Z - vec1.Z } func V3AddP3(result, vec0 *Vector3, pnt1 *Point3) { result.X = vec0.X + pnt1.X result.Y = vec0.Y + pnt1.Y result.Z = vec0.Z + pnt1.Z } func V3ScalarMul(result, vec *Vector3, scalar float32) { result.X = vec.X * scalar result.Y = vec.Y * scalar result.Z = vec.Z * scalar } func V3ScalarDiv(result, vec *Vector3, scalar float32) { result.X = vec.X / scalar result.Y = vec.Y / scalar result.Z = vec.Z / scalar } func V3Neg(result, vec *Vector3) { result.X = -vec.X result.Y = -vec.Y result.Z = -vec.Z } func V3MulPerElem(result, vec0, vec1 *Vector3) { result.X = vec0.X * vec1.X result.Y = vec0.Y * vec1.Y result.Z = vec0.Z * vec1.Z } func V3DivPerElem(result, vec0, vec1 *Vector3) { result.X = vec0.X / vec1.X result.Y = vec0.Y / vec1.Y result.Z = vec0.Z / vec1.Z } func V3RecipPerElem(result, vec *Vector3) { result.X = 1.0 / vec.X result.Y = 1.0 / vec.Y result.Z = 1.0 / vec.Z } func V3SqrtPerElem(result, vec *Vector3) { result.X = sqrt(vec.X) result.Y = sqrt(vec.Y) result.Z = sqrt(vec.Z) } func V3RsqrtPerElem(result, vec *Vector3) { result.X = 1.0 / sqrt(vec.X) result.Y = 1.0 / sqrt(vec.Y) result.Z = 1.0 / sqrt(vec.Z) } func V3AbsPerElem(result, vec *Vector3) { result.X = abs(vec.X) result.Y = abs(vec.Y) result.Z = abs(vec.Z) } func V3CopySignPerElem(result, vec0, vec1 *Vector3) { if vec1.X < 0.0 { result.X = -abs(vec0.X) } else { result.X = abs(vec0.X) } if vec1.Y < 0.0 { result.Y = -abs(vec0.Y) } else { result.Y = abs(vec0.Y) } if vec1.Z < 0.0 { result.Z = -abs(vec0.Z) } else { result.Z = abs(vec0.Z) } } func V3MaxPerElem(result, vec0, vec1 *Vector3) { result.X = max(vec0.X, vec1.X) result.Y = max(vec0.Y, vec1.Y) result.Z = max(vec0.Z, vec1.Z) } func (v *Vector3) MaxElem() float32 { var result float32 result = max(v.X, v.Y) result = max(v.Z, result) return result } func V3MinPerElem(result, vec0, vec1 *Vector3) { result.X = min(vec0.X, vec1.X) result.Y = min(vec0.Y, vec1.Y) result.Z = min(vec0.Z, vec1.Z) } func (v *Vector3) MinElem() float32 { var result float32 result = min(v.X, v.Y) result = min(v.Z, result) return result } func (v *Vector3) Sum() float32 { var result float32 result = v.X + v.Y + v.Z return result } func V3Dot(vec0, vec1 *Vector3) float32 { result := vec0.X * vec1.X result += vec0.Y * vec1.Y result += vec0.Z * vec1.Z return result } func (v *Vector3) Dot(vec1 *Vector3) float32 { result := v.X * vec1.X result += v.Y * vec1.Y result += v.Z * vec1.Z return result } func (v *Vector3) LengthSqr() float32 { result := v.X * v.X result += v.Y * v.Y result += v.Z * v.Z return result } func (v *Vector3) Length() float32 { return sqrt(v.LengthSqr()) } func V3Normalize(result, vec *Vector3) { lenSqr := vec.LengthSqr() lenInv := 1.0 / sqrt(lenSqr) result.X = vec.X * lenInv result.Y = vec.Y * lenInv result.Z = vec.Z * lenInv } func V3Cross(result, vec0, vec1 *Vector3) { tmpX := vec0.Y*vec1.Z - vec0.Z*vec1.Y tmpY := vec0.Z*vec1.X - vec0.X*vec1.Z tmpZ := vec0.X*vec1.Y - vec0.Y*vec1.X V3MakeFromElems(result, tmpX, tmpY, tmpZ) } func V3Select(result, vec0, vec1 *Vector3, select1 int) { if select1 != 0 { result.X = vec1.X result.Y = vec1.Y result.Z = vec1.Z } else { result.X = vec0.X result.Y = vec0.Y result.Z = vec0.Z } } func (v *Vector3) String() string { return fmt.Sprintf("( %f %f %f )\n", v.X, v.Y, v.Z) } /*******/ func V4Copy(result, vec *Vector4) { result.X = vec.X result.Y = vec.Y result.Z = vec.Z result.W = vec.W } func V4MakeFromElems(result *Vector4, x, y, z, w float32) { result.X = x result.Y = y result.Z = z result.W = w } func V4MakeFromV3Scalar(result *Vector4, xyz *Vector3, w float32) { result.SetXYZ(xyz) result.SetW(w) } func V4MakeFromV3(result *Vector4, vec *Vector3) { result.X = vec.X result.Y = vec.Y result.Z = vec.Z result.W = 0.0 } func V4MakeFromP3(result *Vector4, pnt *Point3) { result.X = pnt.X result.Y = pnt.Y result.Z = pnt.Z result.W = 1.0 } func V4MakeFromQ(result *Vector4, quat *Quat) { result.X = quat.X result.Y = quat.Y result.Z = quat.Z result.W = quat.W } func V4MakeFromScalar(result *Vector4, scalar float32) { result.X = scalar result.Y = scalar result.Z = scalar result.W = scalar } func V4MakeXAxis(result *Vector4) { V4MakeFromElems(result, 1.0, 0.0, 0.0, 0.0) } func V4MakeYAxis(result *Vector4) { V4MakeFromElems(result, 0.0, 1.0, 0.0, 0.0) } func V4MakeZAxis(result *Vector4) { V4MakeFromElems(result, 0.0, 0.0, 1.0, 0.0) } func V4MakeWAxis(result *Vector4) { V4MakeFromElems(result, 0.0, 0.0, 0.0, 1.0) } func V4Lerp(result *Vector4, t float32, vec0, vec1 *Vector4) { var tmpV4_0, tmpV4_1 Vector4 V4Sub(&tmpV4_0, vec1, vec0) V4ScalarMul(&tmpV4_1, &tmpV4_0, t) V4Add(result, vec0, &tmpV4_1) } func V4Slerp(result *Vector4, t float32, unitVec0, unitVec1 *Vector4) { var tmpV4_0, tmpV4_1 Vector4 var scale0, scale1 float32 cosAngle := V4Dot(unitVec0, unitVec1) if cosAngle < g_SLERP_TOL { angle := acos(cosAngle) recipSinAngle := (1.0 / sin(angle)) scale0 = (sin(((1.0 - t) * angle)) * recipSinAngle) scale1 = (sin((t * angle)) * recipSinAngle) } else { scale0 = (1.0 - t) scale1 = t } V4ScalarMul(&tmpV4_0, unitVec0, scale0) V4ScalarMul(&tmpV4_1, unitVec1, scale1) V4Add(result, &tmpV4_0, &tmpV4_1) } func (v *Vector4) SetXYZ(vec *Vector3) { v.X = vec.X v.Y = vec.Y v.Z = vec.Z } func V4GetXYZ(result *Vector3, vec *Vector4) { V3MakeFromElems(result, vec.X, vec.Y, vec.Z) } func (v *Vector4) SetX(x float32) { v.X = x } func (v *Vector4) SetY(y float32) { v.Y = y } func (v *Vector4) SetZ(z float32) { v.Z = z } func (v *Vector4) SetW(w float32) { v.W = w } func (v *Vector4) SetElem(index int, value float32) { switch index { case 0: v.X = value case 1: v.Y = value case 2: v.Z = value case 3: v.W = value } } func (v *Vector4) GetElem(index int) float32 { switch index { case 0: return v.X case 1: return v.Y case 2: return v.Z case 3: return v.W } return 0 } func V4Add(result, vec0, vec1 *Vector4) { result.X = vec0.X + vec1.X result.Y = vec0.Y + vec1.Y result.Z = vec0.Z + vec1.Z result.W = vec0.W + vec1.W } func V4Sub(result, vec0, vec1 *Vector4) { result.X = vec0.X - vec1.X result.Y = vec0.Y - vec1.Y result.Z = vec0.Z - vec1.Z result.W = vec0.W - vec1.W } func V4ScalarMul(result, vec *Vector4, scalar float32) { result.X = vec.X * scalar result.Y = vec.Y * scalar result.Z = vec.Z * scalar result.W = vec.W * scalar } func V4ScalarDiv(result, vec *Vector4, scalar float32) { result.X = vec.X / scalar result.Y = vec.Y / scalar result.Z = vec.Z / scalar result.W = vec.W / scalar } func V4Neg(result, vec *Vector4) { result.X = -vec.X result.Y = -vec.Y result.Z = -vec.Z result.W = -vec.W } func V4MulPerElem(result, vec0, vec1 *Vector4) { result.X = vec0.X * vec1.X result.Y = vec0.Y * vec1.Y result.Z = vec0.Z * vec1.Z result.W = vec0.W * vec1.W } func V4DivPerElem(result, vec0, vec1 *Vector4) { result.X = vec0.X / vec1.X result.Y = vec0.Y / vec1.Y result.Z = vec0.Z / vec1.Z result.W = vec0.W / vec1.W } func V4RecipPerElem(result, vec *Vector4) { result.X = 1.0 / vec.X result.Y = 1.0 / vec.Y result.Z = 1.0 / vec.Z result.W = 1.0 / vec.W } func V4SqrtPerElem(result, vec *Vector4) { result.X = sqrt(vec.X) result.Y = sqrt(vec.Y) result.Z = sqrt(vec.Z) result.W = sqrt(vec.W) } func V4RsqrtPerElem(result, vec *Vector4) { result.X = 1.0 / sqrt(vec.X) result.Y = 1.0 / sqrt(vec.Y) result.Z = 1.0 / sqrt(vec.Z) result.W = 1.0 / sqrt(vec.W) } func V4AbsPerElem(result, vec *Vector4) { result.X = abs(vec.X) result.Y = abs(vec.Y) result.Z = abs(vec.Z) result.W = abs(vec.W) } func V4CopySignPerElem(result, vec0, vec1 *Vector4) { if vec1.X < 0.0 { result.X = -abs(vec0.X) } else { result.X = abs(vec0.X) } if vec1.Y < 0.0 { result.Y = -abs(vec0.Y) } else { result.Y = abs(vec0.Y) } if vec1.Z < 0.0 { result.Z = -abs(vec0.Z) } else { result.Z = abs(vec0.Z) } if vec1.W < 0.0 { result.W = -abs(vec0.W) } else { result.W = abs(vec0.W) } } func V4MaxPerElem(result, vec0, vec1 *Vector4) { result.X = max(vec0.X, vec1.X) result.Y = max(vec0.Y, vec1.Y) result.Z = max(vec0.Z, vec1.Z) result.W = max(vec0.W, vec1.W) } func (v *Vector4) MaxElem() float32 { var result float32 result = max(v.X, v.Y) result = max(v.Z, result) result = max(v.W, result) return result } func V4MinPerElem(result, vec0, vec1 *Vector4) { result.X = min(vec0.X, vec1.X) result.Y = min(vec0.Y, vec1.Y) result.Z = min(vec0.Z, vec1.Z) result.W = min(vec0.W, vec1.W) } func (v *Vector4) MinElem() float32 { var result float32 result = min(v.X, v.Y) result = min(v.Z, result) result = min(v.W, result) return result } func (v *Vector4) Sum() float32 { var result float32 result = v.X + v.Y + v.Z + v.W return result } func V4Dot(vec0, vec1 *Vector4) float32 { result := vec0.X * vec1.X result += vec0.Y * vec1.Y result += vec0.Z * vec1.Z result += vec0.W * vec1.W return result } func (v *Vector4) Dot(vec1 *Vector4) float32 { result := v.X * vec1.X result += v.Y * vec1.Y result += v.Z * vec1.Z result += v.W * vec1.W return result } func (v *Vector4) LengthSqr() float32 { result := v.X * v.X result += v.Y * v.Y result += v.Z * v.Z result += v.W * v.W return result } func (v *Vector4) Length() float32 { return sqrt(v.LengthSqr()) } func V4Normalize(result, vec *Vector4) { lenSqr := vec.LengthSqr() lenInv := 1.0 / sqrt(lenSqr) result.X = vec.X * lenInv result.Y = vec.Y * lenInv result.Z = vec.Z * lenInv result.W = vec.W * lenInv } func V4Select(result, vec0, vec1 *Vector4, select1 int) { if select1 != 0 { result.X = vec1.X result.Y = vec1.Y result.Z = vec1.Z result.W = vec1.W } else { result.X = vec0.X result.Y = vec0.Y result.Z = vec0.Z result.W = vec0.W } } func (v *Vector4) String() string { return fmt.Sprintf("( %f %f %f %f )", v.X, v.Y, v.Z, v.W) } /*******/ func P3Copy(result, pnt *Point3) { result.X = pnt.X result.Y = pnt.Y result.Z = pnt.Z } func P3MakeFromElems(result *Point3, x, y, z float32) { result.X = x result.Y = y result.Z = z } func P3MakeFromV3(result *Point3, vec *Vector3) { result.X = vec.X result.Y = vec.Y result.Z = vec.Z } func P3MakeFromScalar(result *Point3, scalar float32) { result.X = scalar result.Y = scalar result.Z = scalar } func P3Lerp(result *Point3, t float32, pnt0, pnt1 *Point3) { var tmpV3_0, tmpV3_1 Vector3 P3Sub(&tmpV3_0, pnt1, pnt0) V3ScalarMul(&tmpV3_1, &tmpV3_0, t) P3AddV3(result, pnt0, &tmpV3_1) } func (p *Point3) SetX(x float32) { p.X = x } func (p *Point3) SetY(y float32) { p.Y = y } func (p *Point3) SetZ(z float32) { p.Z = z } func (p *Point3) SetElem(index int, value float32) { switch index { case 0: p.X = value case 1: p.Y = value case 2: p.Z = value } } func (p *Point3) GetElem(index int) float32 { switch index { case 0: return p.X case 1: return p.Y case 2: return p.Z } return 0 } func P3Sub(result *Vector3, pnt0, pnt1 *Point3) { result.X = pnt0.X - pnt1.X result.Y = pnt0.Y - pnt1.Y result.Z = pnt0.Z - pnt1.Z } func P3AddV3(result, pnt0 *Point3, vec1 *Vector3) { result.X = pnt0.X + vec1.X result.Y = pnt0.Y + vec1.Y result.Z = pnt0.Z + vec1.Z } func P3SubV3(result, pnt0 *Point3, vec1 *Vector3) { result.X = pnt0.X - vec1.X result.Y = pnt0.Y - vec1.Y result.Z = pnt0.Z - vec1.Z } func P3MulPerElem(result, pnt0, pnt1 *Point3) { result.X = pnt0.X * pnt1.X result.Y = pnt0.Y * pnt1.Y result.Z = pnt0.Z * pnt1.Z } func P3DivPerElem(result, pnt0, pnt1 *Point3) { result.X = pnt0.X / pnt1.X result.Y = pnt0.Y / pnt1.Y result.Z = pnt0.Z / pnt1.Z } func P3RecipPerElem(result, pnt *Point3) { result.X = 1.0 / pnt.X result.Y = 1.0 / pnt.Y result.Z = 1.0 / pnt.Z } func P3SqrtPerElem(result, pnt *Point3) { result.X = sqrt(pnt.X) result.Y = sqrt(pnt.Y) result.Z = sqrt(pnt.Z) } func P3RsqrtPerElem(result, pnt *Point3) { result.X = 1.0 / sqrt(pnt.X) result.Y = 1.0 / sqrt(pnt.Y) result.Z = 1.0 / sqrt(pnt.Z) } func P3AbsPerElem(result, pnt *Point3) { result.X = abs(pnt.X) result.Y = abs(pnt.Y) result.Z = abs(pnt.Z) } func P3CopySignPerElem(result, pnt0, pnt1 *Point3) { if pnt1.X < 0.0 { result.X = -abs(pnt0.X) } else { result.X = abs(pnt0.X) } if pnt1.Y < 0.0 { result.Y = -abs(pnt0.Y) } else { result.Y = abs(pnt0.Y) } if pnt1.Z < 0.0 { result.Z = -abs(pnt0.Z) } else { result.Z = abs(pnt0.Z) } } func P3MaxPerElem(result, pnt0, pnt1 *Point3) { result.X = max(pnt0.X, pnt1.X) result.Y = max(pnt0.Y, pnt1.Y) result.Z = max(pnt0.Z, pnt1.Z) } func (p *Point3) MaxElem() float32 { var result float32 result = max(p.X, p.Y) result = max(p.Z, result) return result } func P3MinPerElem(result, pnt0, pnt1 *Point3) { result.X = min(pnt0.X, pnt1.X) result.Y = min(pnt0.Y, pnt1.Y) result.Z = min(pnt0.Z, pnt1.Z) } func (p *Point3) MinElem() float32 { var result float32 result = min(p.X, p.Y) result = min(p.Z, result) return result } func (p *Point3) Sum() float32 { var result float32 result = p.X + p.Y + p.Z return result } func P3Scale(result, pnt *Point3, scaleVal float32) { var tmpP3_0 Point3 P3MakeFromScalar(&tmpP3_0, scaleVal) P3MulPerElem(result, pnt, &tmpP3_0) } func P3NonUniformScale(result, pnt *Point3, scaleVec *Vector3) { var tmpP3_0 Point3 P3MakeFromV3(&tmpP3_0, scaleVec) P3MulPerElem(result, pnt, &tmpP3_0) } func (p *Point3) Projection(unitVec *Vector3) float32 { result := p.X * unitVec.X result += p.Y * unitVec.Y result += p.Z * unitVec.Z return result } func (p *Point3) DistSqrFromOrigin() float32 { var tmpV3_0 Vector3 V3MakeFromP3(&tmpV3_0, p) return tmpV3_0.LengthSqr() } func (p *Point3) DistFromOrigin() float32 { var tmpV3_0 Vector3 V3MakeFromP3(&tmpV3_0, p) return tmpV3_0.Length() } func (p *Point3) DistSqr(pnt1 *Point3) float32 { var tmpV3_0 Vector3 P3Sub(&tmpV3_0, pnt1, p) return tmpV3_0.LengthSqr() } func (p *Point3) Dist(pnt1 *Point3) float32 { var tmpV3_0 Vector3 P3Sub(&tmpV3_0, pnt1, p) return tmpV3_0.Length() } func P3Select(result, pnt0, pnt1 *Point3, select1 int) { if select1 != 0 { result.X = pnt1.X result.Y = pnt1.Y result.Z = pnt1.Z } else { result.X = pnt0.X result.Y = pnt0.Y result.Z = pnt0.Z } } func (p *Point3) String() string { return fmt.Sprintf("( %f %f %f )", p.X, p.Y, p.Z) }
vec_aos.go
0.818193
0.50177
vec_aos.go
starcoder
package main // TinyGo version of the 1st WebGL Fundamentals lesson // https://webglfundamentals.org/webgl/lessons/webgl-fundamentals.html import ( "math/rand" "syscall/js" "github.com/justinclift/webgl" ) var ( // Vertex shader source code vertCode = ` // an attribute will receive data from a buffer attribute vec2 a_position; uniform vec2 u_resolution; // all shaders have a main function void main() { // convert the position from pixels to 0.0 to 1.0 vec2 zeroToOne = a_position.xy / u_resolution; // convert from 0->1 to 0->2 vec2 zeroToTwo = zeroToOne * 2.0; // convert from 0->2 to -1->+1 (clip space) vec2 clipSpace = zeroToTwo - 1.0; gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); }` // Fragment shader source code fragCode = ` precision mediump float; uniform vec4 u_color; void main() { gl_FragColor = u_color; }` ) func main() { // Set up the WebGL context doc := js.Global().Get("document") canvas := doc.Call("getElementById", "mycanvas") width := canvas.Get("clientWidth").Int() height := canvas.Get("clientHeight").Int() canvas.Call("setAttribute", "width", width) canvas.Call("setAttribute", "height", height) attrs := webgl.DefaultAttributes() attrs.Alpha = false gl, err := webgl.NewContext(&canvas, attrs) if err != nil { js.Global().Call("alert", "Error: "+err.Error()) return } // * WebGL initialisation code * // Create GLSL shaders, upload the GLSL source, compile the shaders vertexShader := createShader(gl, webgl.VERTEX_SHADER, vertCode) fragmentShader := createShader(gl, webgl.FRAGMENT_SHADER, fragCode) // Link the two shaders into a program program := createProgram(gl, vertexShader, fragmentShader) // Look up where the vertex data needs to go positionAttributeLocation := gl.GetAttribLocation(program, "a_position") // Look up uniform locations resolutionUniformLocation := gl.GetUniformLocation(program, "u_resolution") colorUniformLocation := gl.GetUniformLocation(program, "u_color") // Create a buffer and put three 2d clip space points in it positionBuffer := gl.CreateArrayBuffer() // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer) gl.BindBuffer(webgl.ARRAY_BUFFER, positionBuffer) // * WebGL rendering code * // Tell WebGL how to convert from clip space to pixels gl.Viewport(0, 0, width, height) // Clear the canvas gl.ClearColor(0, 0, 0, 0) gl.Clear(webgl.COLOR_BUFFER_BIT) // Tell it to use our program (pair of shaders) gl.UseProgram(program) // Turn on the attribute gl.EnableVertexAttribArray(positionAttributeLocation) // Bind the position buffer gl.BindBuffer(webgl.ARRAY_BUFFER, positionBuffer) // Tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER) pbSize := 2 // 2 components per iteration pbType := webgl.FLOAT // the data is 32bit floats pbNormalize := false // don't normalize the data pbStride := 0 // 0 = move forward size * sizeof(pbType) each iteration to get the next position pbOffset := 0 // start at the beginning of the buffer gl.VertexAttribPointer(positionAttributeLocation, pbSize, pbType, pbNormalize, pbStride, pbOffset) // Set the resolution gl.Uniform2f(resolutionUniformLocation, float32(width), float32(height)) // Draw 50 random rectangles in random colors for i := 0; i < 50; i++ { // Setup a random rectangle // This will write to positionBuffer because // its the last thing we bound on the ARRAY_BUFFER // bind point setRectangle(gl, float32(rand.Intn(300)), float32(rand.Intn(300)), float32(rand.Intn(300)), float32(rand.Intn(300))) // Set a random color gl.Uniform4f(colorUniformLocation, rand.Float32(), rand.Float32(), rand.Float32(), 1) // Draw the rectangle primType := webgl.TRIANGLES primOffset := 0 primCount := 6 gl.DrawArrays(primType, primOffset, primCount) } } func createShader(gl *webgl.Context, shaderType int, source string) *js.Value { shader := gl.CreateShader(shaderType) gl.ShaderSource(shader, source) gl.CompileShader(shader) success := gl.GetShaderParameter(shader, webgl.COMPILE_STATUS).Bool() if success { return shader } println(gl.GetShaderInfoLog(shader)) gl.DeleteShader(shader) return &js.Value{} } func createProgram(gl *webgl.Context, vertexShader *js.Value, fragmentShader *js.Value) *js.Value { program := gl.CreateProgram() gl.AttachShader(program, vertexShader) gl.AttachShader(program, fragmentShader) gl.LinkProgram(program) success := gl.GetProgramParameterb(program, webgl.LINK_STATUS) if success { return program } println(gl.GetProgramInfoLog(program)) gl.DeleteProgram(program) return &js.Value{} } // Fill the buffer with the values that define a rectangle func setRectangle(gl *webgl.Context, x, y, width, height float32) { x1 := x x2 := x + width y1 := y y2 := y + height positionsNative := []float32{ x1, y1, x2, y1, x1, y2, x1, y2, x2, y1, x2, y2, } positions := webgl.SliceToTypedArray(positionsNative) gl.BufferData(webgl.ARRAY_BUFFER, positions, webgl.STATIC_DRAW) }
main.go
0.75274
0.406332
main.go
starcoder
package sheet // BaseCofD2e describes the base of every CofD2e sheet type BaseCofD2e struct { // Core Name string `json:"name"` Chronicle string `json:"chronicle"` Concept string `json:"concept"` Experiences int `json:"experiences"` Beats int `json:"beats"` Notes []Note `json:"notes"` // Traits Aspirations []string `json:"aspirations"` Conditions string `json:"conditions"` Health struct { Max int `json:"max"` Aggravated int `json:"aggravated"` Lethal int `json:"lethal"` Bashing int `json:"bashing"` } `json:"health"` Merits []CofD2eMerit `json:"merits"` Size int `json:"size"` Willpower IntWithMax `json:"willpower"` } // CofD2eCreature describes attributes and skills for a non-ephemeral entity type CofD2eCreature struct { // Attributes Intelligence int `json:"intelligence"` Wits int `json:"wits"` Resolve int `json:"resolve"` Strength int `json:"strength"` Dexterity int `json:"dexterity"` Stamina int `json:"stamina"` Presence int `json:"presence"` Manipulation int `json:"manipulation"` Composure int `json:"composure"` // Skills Academics CofD2eSkill `json:"academics"` Computer CofD2eSkill `json:"computer"` Crafts CofD2eSkill `json:"crafts"` Investigation CofD2eSkill `json:"investigation"` Medicine CofD2eSkill `json:"medicine"` Occult CofD2eSkill `json:"occult"` Politics CofD2eSkill `json:"politics"` Science CofD2eSkill `json:"science"` Athletics CofD2eSkill `json:"athletics"` Brawl CofD2eSkill `json:"brawl"` Drive CofD2eSkill `json:"drive"` Firearms CofD2eSkill `json:"firearms"` Larceny CofD2eSkill `json:"larceny"` Stealth CofD2eSkill `json:"stealth"` Survival CofD2eSkill `json:"survival"` Weaponry CofD2eSkill `json:"weaponry"` AnimalKen CofD2eSkill `json:"animal_ken"` Empathy CofD2eSkill `json:"empathy"` Expression CofD2eSkill `json:"expression"` Intimidation CofD2eSkill `json:"intimidation"` Persuasion CofD2eSkill `json:"persuasion"` Socialize CofD2eSkill `json:"socialize"` Streetwise CofD2eSkill `json:"streetwise"` Subterfuge CofD2eSkill `json:"subterfuge"` } // CofD2e describes a sheet for a Mortal type CofD2e struct { *BaseCofD2e *CofD2eCreature // Core Vice string `json:"vice"` Virtue string `json:"virtue"` Faction string `json:"faction"` Group string `json:"group"` Template string `json:"template"` // Traits Integrity int `json:"integrity"` } // CofD2eSkill describes a skill within the CofD 2e system type CofD2eSkill struct { Dots int `json:"dots"` Specialties string `json:"specialties"` } // CofD2eMerit describes a merit within the CofD 2e system type CofD2eMerit struct { Name string `json:"name"` Dots int `json:"dots"` } // NewBaseCofD2e creates a new instance of a base CofD2e sheet, and initializes many of its values. func NewBaseCofD2e() *BaseCofD2e { sheet := new(BaseCofD2e) sheet.Size = 5 sheet.Notes = make([]Note, 0) sheet.Aspirations = make([]string, 0) sheet.Merits = make([]CofD2eMerit, 0) return sheet } // NewCofD2eCreature creates a new instance of a CofD2e creature sheet, and initializes many of its values. func NewCofD2eCreature() *CofD2eCreature { sheet := new(CofD2eCreature) sheet.Intelligence = 1 sheet.Wits = 1 sheet.Resolve = 1 sheet.Strength = 1 sheet.Dexterity = 1 sheet.Stamina = 1 sheet.Presence = 1 sheet.Manipulation = 1 sheet.Composure = 1 return sheet } // NewCofD2e creates a new instance of the mortal sheet and initializes its values func NewCofD2e() *CofD2e { sheet := new(CofD2e) sheet.BaseCofD2e = NewBaseCofD2e() sheet.CofD2eCreature = NewCofD2eCreature() return sheet } // System returns the system of the sheet func (s *CofD2e) System() string { return "cofd2e" }
usecases/sheet/cofd2e.go
0.717507
0.451447
cofd2e.go
starcoder
package json2 import ( "unicode" ) // Scanner is a func that returns a subset of the input and a success bool. type Scanner func([]rune) ([]rune, bool) // If returns a scanner that accepts the a rune if it satisfies the condition. func If(condition func(rune) bool) Scanner { return func(input []rune) ([]rune, bool) { if len(input) > 0 && condition(input[0]) { return input[0:1], true } return nil, false } } // Rune returns a scanner that accepts r. func Rune(r rune) Scanner { return If(func(b rune) bool { return r == b }) } // Space returns a scanner that accepts whitespace as defined in the unicode // package. func Space() Scanner { return func(input []rune) ([]rune, bool) { if len(input) > 0 && unicode.IsSpace(input[0]) { return input[0:1], true } return nil, false } } // And returns a scanner that accepts all scanners in sequence. func And(scanners ...Scanner) Scanner { return func(input []rune) ([]rune, bool) { remaining := input accumulated := []rune{} for _, s := range scanners { if read, ok := s(remaining); !ok { return nil, false } else { accumulated = append(accumulated, read...) remaining = remaining[len(read):] } } return accumulated, true } } // Or returns a scanner that accepts the first successful scan in scanners. func Or(scanners ...Scanner) Scanner { return func(input []rune) ([]rune, bool) { for _, s := range scanners { if read, ok := s(input); ok { return read, true } } return nil, false } } // Maybe runs scanner and returns true regardless of the output. func Maybe(scanner Scanner) Scanner { return func(input []rune) ([]rune, bool) { read, _ := scanner(input) return read, true } } // Any returns a scanner that accepts any number of occurrences of scanner, // including zero. func Any(scanner Scanner) Scanner { return func(input []rune) ([]rune, bool) { remaining := input accumulated := []rune{} for { if read, ok := scanner(remaining); !ok { return accumulated, true } else { accumulated = append(accumulated, read...) remaining = remaining[len(read):] } } } } // N returns a scanner that accepts scanner exactly n times. func N(n int, scanner Scanner) Scanner { return func(input []rune) ([]rune, bool) { scanners := make([]Scanner, n) for i := 0; i < n; i++ { scanners[i] = scanner } return And(scanners...)(input) } } // AtLeast returns a scanner that accepts scanner at least n times. func AtLeast(n int, scanner Scanner) Scanner { return func(input []rune) ([]rune, bool) { scanners := make([]Scanner, n, n+1) for i := range scanners { scanners[i] = scanner } scanners = append(scanners, Any(scanner)) return And(scanners...)(input) } }
scanner.go
0.753376
0.480052
scanner.go
starcoder
package commitment import ( "fmt" "io" "math/big" "gitlab.com/alephledger/threshold-ecdsa/pkg/curve" ) //NewElGamalFactory creates a new ElGamal-type Commitments factory func NewElGamalFactory(h curve.Point) *ElGamalFactory { egf := &ElGamalFactory{h: h} egf.curve = curve.NewSecp256k1Group() egf.neutral = egf.Create(big.NewInt(0), big.NewInt(0)) return egf } //ElGamalFactory is a factory for ElGamal-type Commitment type ElGamalFactory struct { h curve.Point neutral *ElGamal curve curve.Group } //ElGamal is an implementation of ElGamal-type Commitments type ElGamal struct { first, second curve.Point curve curve.Group } //Create creates new ElGamal Commitment func (e *ElGamalFactory) Create(value, r *big.Int) *ElGamal { return &ElGamal{ first: e.curve.ScalarBaseMult(r), second: e.curve.Add( e.curve.ScalarMult(e.h, r), e.curve.ScalarBaseMult(value)), curve: e.curve, } } //Curve returns group used by ElGamalFactory func (e *ElGamalFactory) Curve() curve.Group { return e.curve } //Neutral creates neutral element for compose operation of ElGamal Commitments func (e *ElGamalFactory) Neutral() *ElGamal { return e.Create(big.NewInt(0), big.NewInt(0)) } //IsNeutral Chackes if element is equal to neutral one func (e *ElGamalFactory) IsNeutral(a *ElGamal) bool { return a.Equal(e.neutral, a) } //Compose composes two ElGamal Commitments func (c *ElGamal) Compose(a, b *ElGamal) *ElGamal { c.first = c.curve.Add(a.first, b.first) c.second = c.curve.Add(a.second, b.second) return c } //Exp performs exp operation on ElGamal Commitments func (c *ElGamal) Exp(x *ElGamal, n *big.Int) *ElGamal { c.first = c.curve.ScalarMult(x.first, n) c.second = c.curve.ScalarMult(x.second, n) return c } //Inverse returns inversed element for given ElGamal Commitment func (c *ElGamal) Inverse(a *ElGamal) *ElGamal { c.first = c.curve.Neg(a.first) c.second = c.curve.Neg(a.second) return c } // Equal checks the equality of the provided commitments func (c *ElGamal) Equal(a, b *ElGamal) bool { return c.curve.Equal(a.first, b.first) && c.curve.Equal(a.second, b.second) } // Encode encodes ElGamal Commitment func (c *ElGamal) Encode(w io.Writer) error { if err := c.curve.Encode(c.first, w); err != nil { return fmt.Errorf("Encoding first coordinate in ElGamal: %v", err) } if err := c.curve.Encode(c.second, w); err != nil { return fmt.Errorf("Encoding second coordinate in ElGamal: %v", err) } return nil } // Decode decodes ElGamal Commitment func (c *ElGamal) Decode(r io.Reader) error { c.curve = curve.NewSecp256k1Group() var err error c.first, err = c.curve.Decode(r) if err != nil { return fmt.Errorf("Decoding first coordinate in ElGamal: %v", err) } c.second, err = c.curve.Decode(r) if err != nil { return fmt.Errorf("Decoding second coordinate in ElGamal: %v", err) } return nil }
pkg/crypto/commitment/commitment.go
0.859133
0.429429
commitment.go
starcoder
// Package convertor implements some functions to convert data. package convertor import ( "bytes" "encoding/gob" "encoding/json" "fmt" "reflect" "regexp" "strconv" "strings" ) // ToBool convert string to a boolean func ToBool(s string) (bool, error) { return strconv.ParseBool(s) } // ToBytes convert interface to bytes func ToBytes(data any) ([]byte, error) { var buf bytes.Buffer enc := gob.NewEncoder(&buf) err := enc.Encode(data) if err != nil { return nil, err } return buf.Bytes(), nil } // ToChar convert string to char slice func ToChar(s string) []string { c := make([]string, 0) if len(s) == 0 { c = append(c, "") } for _, v := range s { c = append(c, string(v)) } return c } // ToString convert value to string func ToString(value any) string { res := "" if value == nil { return res } v := reflect.ValueOf(value) switch value.(type) { case float32, float64: res = strconv.FormatFloat(v.Float(), 'f', -1, 64) return res case int, int8, int16, int32, int64: res = strconv.FormatInt(v.Int(), 10) return res case uint, uint8, uint16, uint32, uint64: res = strconv.FormatUint(v.Uint(), 10) return res case string: res = v.String() return res case []byte: res = string(v.Bytes()) return res default: newValue, _ := json.Marshal(value) res = string(newValue) return res } } // ToJson convert value to a valid json string func ToJson(value any) (string, error) { res, err := json.Marshal(value) if err != nil { return "", err } return string(res), nil } // ToFloat convert value to a float64, if input is not a float return 0.0 and error func ToFloat(value any) (float64, error) { v := reflect.ValueOf(value) res := 0.0 err := fmt.Errorf("ToInt: unvalid interface type %T", value) switch value.(type) { case int, int8, int16, int32, int64: res = float64(v.Int()) return res, nil case uint, uint8, uint16, uint32, uint64: res = float64(v.Uint()) return res, nil case float32, float64: res = v.Float() return res, nil case string: res, err = strconv.ParseFloat(v.String(), 64) if err != nil { res = 0.0 } return res, err default: return res, err } } // ToInt convert value to a int64, if input is not a numeric format return 0 and error func ToInt(value any) (int64, error) { v := reflect.ValueOf(value) var res int64 err := fmt.Errorf("ToInt: invalid interface type %T", value) switch value.(type) { case int, int8, int16, int32, int64: res = v.Int() return res, nil case uint, uint8, uint16, uint32, uint64: res = int64(v.Uint()) return res, nil case float32, float64: res = int64(v.Float()) return res, nil case string: res, err = strconv.ParseInt(v.String(), 0, 64) if err != nil { res = 0 } return res, err default: return res, err } } // StructToMap convert struct to map, only convert exported struct field // map key is specified same as struct field tag `json` value func StructToMap(value any) (map[string]any, error) { v := reflect.ValueOf(value) t := reflect.TypeOf(value) if t.Kind() == reflect.Ptr { t = t.Elem() } if t.Kind() != reflect.Struct { return nil, fmt.Errorf("data type %T not support, shuld be struct or pointer to struct", value) } res := make(map[string]any) fieldNum := t.NumField() pattern := `^[A-Z]` regex := regexp.MustCompile(pattern) for i := 0; i < fieldNum; i++ { name := t.Field(i).Name tag := t.Field(i).Tag.Get("json") if regex.MatchString(name) && tag != "" { //res[name] = v.Field(i).Interface() res[tag] = v.Field(i).Interface() } } return res, nil } // ColorHexToRGB convert hex color to rgb color func ColorHexToRGB(colorHex string) (red, green, blue int) { colorHex = strings.TrimPrefix(colorHex, "#") color64, err := strconv.ParseInt(colorHex, 16, 32) if err != nil { return } color := int(color64) return color >> 16, (color & 0x00FF00) >> 8, color & 0x0000FF } // ColorRGBToHex convert rgb color to hex color func ColorRGBToHex(red, green, blue int) string { r := strconv.FormatInt(int64(red), 16) g := strconv.FormatInt(int64(green), 16) b := strconv.FormatInt(int64(blue), 16) if len(r) == 1 { r = "0" + r } if len(g) == 1 { g = "0" + g } if len(b) == 1 { b = "0" + b } return "#" + r + g + b }
convertor/convertor.go
0.784071
0.413418
convertor.go
starcoder
package cue import ( "cuelang.org/go/cue/token" "cuelang.org/go/internal/core/adt" ) // Op indicates the operation at the top of an expression tree of the expression // use to evaluate a value. type Op = adt.Op // Values of Op. const ( NoOp Op = adt.NoOp AndOp Op = adt.AndOp OrOp Op = adt.OrOp SelectorOp Op = adt.SelectorOp IndexOp Op = adt.IndexOp SliceOp Op = adt.SliceOp CallOp Op = adt.CallOp BooleanAndOp Op = adt.BoolAndOp BooleanOrOp Op = adt.BoolOrOp EqualOp Op = adt.EqualOp NotOp Op = adt.NotOp NotEqualOp Op = adt.NotEqualOp LessThanOp Op = adt.LessThanOp LessThanEqualOp Op = adt.LessEqualOp GreaterThanOp Op = adt.GreaterThanOp GreaterThanEqualOp Op = adt.GreaterEqualOp RegexMatchOp Op = adt.MatchOp NotRegexMatchOp Op = adt.NotMatchOp AddOp Op = adt.AddOp SubtractOp Op = adt.SubtractOp MultiplyOp Op = adt.MultiplyOp FloatQuotientOp Op = adt.FloatQuotientOp IntQuotientOp Op = adt.IntQuotientOp IntRemainderOp Op = adt.IntRemainderOp IntDivideOp Op = adt.IntDivideOp IntModuloOp Op = adt.IntModuloOp InterpolationOp Op = adt.InterpolationOp ) // isCmp reports whether an op is a comparator. func (op op) isCmp() bool { return opEql <= op && op <= opGeq } func (op op) unifyType() (unchecked, ok bool) { if op == opUnifyUnchecked { return true, true } return false, op == opUnify } type op uint16 const ( opUnknown op = iota opUnify opUnifyUnchecked opDisjunction opLand opLor opNot opEql opNeq opMat opNMat opLss opGtr opLeq opGeq opAdd opSub opMul opQuo opRem opIDiv opIMod opIQuo opIRem ) var opStrings = []string{ opUnknown: "??", opUnify: "&", // opUnifyUnchecked is internal only. Syntactically this is // represented as embedding. opUnifyUnchecked: "&!", opDisjunction: "|", opLand: "&&", opLor: "||", opNot: "!", opEql: "==", opNeq: "!=", opMat: "=~", opNMat: "!~", opLss: "<", opGtr: ">", opLeq: "<=", opGeq: ">=", opAdd: "+", opSub: "-", opMul: "*", opQuo: "/", opIDiv: "div", opIMod: "mod", opIQuo: "quo", opIRem: "rem", } func (op op) String() string { return opStrings[op] } var tokenMap = map[token.Token]op{ token.OR: opDisjunction, // | token.AND: opUnify, // & token.ADD: opAdd, // + token.SUB: opSub, // - token.MUL: opMul, // * token.QUO: opQuo, // / token.IDIV: opIDiv, // div token.IMOD: opIMod, // mod token.IQUO: opIQuo, // quo token.IREM: opIRem, // rem token.LAND: opLand, // && token.LOR: opLor, // || token.EQL: opEql, // == token.LSS: opLss, // < token.GTR: opGtr, // > token.NOT: opNot, // ! token.NEQ: opNeq, // != token.LEQ: opLeq, // <= token.GEQ: opGeq, // >= token.MAT: opMat, // =~ token.NMAT: opNMat, // !~ } var opMap = map[op]token.Token{} func init() { for t, o := range tokenMap { opMap[o] = t } }
cue/op.go
0.573798
0.563558
op.go
starcoder
package iso20022 // Completion of a securities settlement instruction, wherein securities are delivered/debited from a securities account and received/credited to the designated securities account. type ReceiveInformation11 struct { // Date and time at which the securities are to be exchanged at the International Central Securities Depository (ICSD) or Central Securities Depository (CSD). RequestedSettlementDate *ISODate `xml:"ReqdSttlmDt,omitempty"` // Date and time at which the securities were exchanged at the International Central Securities Depository (ICSD) or Central Securities Depository (CSD). EffectiveSettlementDate *DateAndDateTimeChoice `xml:"FctvSttlmDt,omitempty"` // Total amount of money paid /to be paid or received in exchange for the financial instrument in the individual order. SettlementAmount *ActiveCurrencyAndAmount `xml:"SttlmAmt,omitempty"` // Indicates whether the settlement amount includes the stamp duty amount. StampDuty *StampDutyType2Code `xml:"StmpDty,omitempty"` // Deal amount. NetAmount *ActiveCurrencyAndAmount `xml:"NetAmt,omitempty"` // Charge related to the transfer of a financial instrument. ChargeDetails []*Charge20 `xml:"ChrgDtls,omitempty"` // Commission related to the transfer of a financial instrument. CommissionDetails []*Commission12 `xml:"ComssnDtls,omitempty"` // Tax related to the transfer of a financial instrument. TaxDetails []*Tax15 `xml:"TaxDtls,omitempty"` // Chain of parties involved in the settlement of a transaction. SettlementPartiesDetails *ReceivingPartiesAndAccount8 `xml:"SttlmPtiesDtls,omitempty"` // Indicates whether the financial instrument is to be physically delivered. PhysicalTransfer *PhysicalTransferType1Code `xml:"PhysTrf,omitempty"` // Parameters of a physical delivery. PhysicalTransferDetails *DeliveryParameters4 `xml:"PhysTrfDtls,omitempty"` } func (r *ReceiveInformation11) SetRequestedSettlementDate(value string) { r.RequestedSettlementDate = (*ISODate)(&value) } func (r *ReceiveInformation11) AddEffectiveSettlementDate() *DateAndDateTimeChoice { r.EffectiveSettlementDate = new(DateAndDateTimeChoice) return r.EffectiveSettlementDate } func (r *ReceiveInformation11) SetSettlementAmount(value, currency string) { r.SettlementAmount = NewActiveCurrencyAndAmount(value, currency) } func (r *ReceiveInformation11) SetStampDuty(value string) { r.StampDuty = (*StampDutyType2Code)(&value) } func (r *ReceiveInformation11) SetNetAmount(value, currency string) { r.NetAmount = NewActiveCurrencyAndAmount(value, currency) } func (r *ReceiveInformation11) AddChargeDetails() *Charge20 { newValue := new (Charge20) r.ChargeDetails = append(r.ChargeDetails, newValue) return newValue } func (r *ReceiveInformation11) AddCommissionDetails() *Commission12 { newValue := new (Commission12) r.CommissionDetails = append(r.CommissionDetails, newValue) return newValue } func (r *ReceiveInformation11) AddTaxDetails() *Tax15 { newValue := new (Tax15) r.TaxDetails = append(r.TaxDetails, newValue) return newValue } func (r *ReceiveInformation11) AddSettlementPartiesDetails() *ReceivingPartiesAndAccount8 { r.SettlementPartiesDetails = new(ReceivingPartiesAndAccount8) return r.SettlementPartiesDetails } func (r *ReceiveInformation11) SetPhysicalTransfer(value string) { r.PhysicalTransfer = (*PhysicalTransferType1Code)(&value) } func (r *ReceiveInformation11) AddPhysicalTransferDetails() *DeliveryParameters4 { r.PhysicalTransferDetails = new(DeliveryParameters4) return r.PhysicalTransferDetails }
ReceiveInformation11.go
0.731634
0.475118
ReceiveInformation11.go
starcoder
package radiance import ( "image" "image/color" "math" ) const R_LUMINANCE = 0.2126 const G_LUMINANCE = 0.7152 const B_LUMINANCE = 0.0722 const DISPLAY_LUMINANCE_MAX = 200.0 const GAMMA_ENCODE = 0.45 type Radiance struct { R, G, B float64 } type RadianceImage struct { Width, Height int pix []float64 } func NewRadianceImage(width, height int) *RadianceImage { buf := make([]float64, 3*width*height) return &RadianceImage{width, height, buf} } func (p *RadianceImage) pixOffset(x, y int) int { return y*p.Width*3 + x*3 } func (p *RadianceImage) Add(x int, y int, radiance Radiance) { i := p.pixOffset(x, y) p.pix[i+0] += radiance.R p.pix[i+1] += radiance.G p.pix[i+2] += radiance.B } func (p *RadianceImage) Get(x int, y int) Radiance { i := p.pixOffset(x, y) return Radiance{p.pix[i+0], p.pix[i+1], p.pix[i+2]} } func (p *RadianceImage) calculateScaleFactor(iterations int) float64 { // calculate the linear tone-mapping scalefactor for this image assuming // the given number of iterations. // calculate the log-mean luminance of the image var sum_of_logs float64 for x := 0; x < p.Width; x++ { for y := 0; y < p.Height; y++ { lum := p.pix[p.pixOffset(x, y)+0] * R_LUMINANCE lum += p.pix[p.pixOffset(x, y)+1] * G_LUMINANCE lum += p.pix[p.pixOffset(x, y)+2] * B_LUMINANCE lum /= float64(iterations) sum_of_logs += math.Log10(math.Max(lum, 0.0001)) } } log_mean_luminance := math.Pow(10.0, (sum_of_logs / float64(p.Height*p.Width))) // calculate the scalefactor for linear tone-mapping // formula from Ward "A Contrast-Based Scalefactor for Luminance Display" scalefactor_numerator := 1.219 + math.Pow(DISPLAY_LUMINANCE_MAX*0.25, 0.4) scalefactor := (math.Pow((scalefactor_numerator / (1.219 + math.Pow(log_mean_luminance, 0.4))), 2.5)) / DISPLAY_LUMINANCE_MAX return scalefactor } func (p *RadianceImage) ToRGBA64(iterations int) *image.RGBA64 { scalefactor := p.calculateScaleFactor(iterations) m := image.NewRGBA64(image.Rect(0, 0, p.Width, p.Height)) for x := 0; x < p.Width; x++ { for y := 0; y < p.Height; y++ { radiance := p.Get(x, y) r := uint16(65535 * math.Pow(math.Max(radiance.R*scalefactor/float64(iterations), 0), GAMMA_ENCODE)) g := uint16(65535 * math.Pow(math.Max(radiance.G*scalefactor/float64(iterations), 0), GAMMA_ENCODE)) b := uint16(65535 * math.Pow(math.Max(radiance.B*scalefactor/float64(iterations), 0), GAMMA_ENCODE)) a := uint16(65535) m.Set(x, y, color.RGBA64{r, g, b, a}) } } return m }
src/minilight/radiance/radiance.go
0.763043
0.467818
radiance.go
starcoder
package modelchecking import ( "errors" "fmt" ) /* TransitionSystemState Description: This type is an object which contains the Transition System's State. */ type TransitionSystemState struct { Name string System *TransitionSystem } /* Equals Description: Checks to see if two states in the transition system have the same value. */ func (stateIn TransitionSystemState) Equals(s2 TransitionSystemState) bool { return stateIn.Name == s2.Name } /* In Description: Determines if the state is in a given slice of TransitionSystemState objects. Usage: tf := s1.In( sliceIn ) */ func (stateIn TransitionSystemState) In(stateSliceIn []TransitionSystemState) bool { for _, tempState := range stateSliceIn { if tempState.Equals(stateIn) { return true //If there is a match, then return true. } } //If there is no match in the slice, //then return false return false } /* Satisfies Description: The state of the transition system satisfies the given formula. */ func (stateIn TransitionSystemState) Satisfies(formula interface{}) (bool, error) { // Input Processing if stateIn.System == nil { return false, errors.New("The system pointer is not defined for the input state.") } // Algorithm var tf = false var err error = nil if singleAP, ok := formula.(AtomicProposition); ok { tf, err = singleAP.SatisfactionHelper(stateIn) } return tf, err } /* AppendIfUniqueTo Description: Appends to the input slice sliceIn if and only if the new state is actually a unique state. Usage: newSlice := stateIn.AppendIfUniqueTo(sliceIn) */ func (stateIn TransitionSystemState) AppendIfUniqueTo(sliceIn []TransitionSystemState) []TransitionSystemState { for _, tempState := range sliceIn { if tempState.Equals(stateIn) { return sliceIn } } //If all checks were passed return append(sliceIn, stateIn) } /* Post Description: Finds the set of states that can follow a given state (or set of states). Usage: tempPost, err := Post( s0 ) tempPost, err := Post( s0 , a0 ) */ func Post(SorSA ...interface{}) ([]TransitionSystemState, error) { switch len(SorSA) { case 1: // Only State Is Given stateIn, ok := SorSA[0].(TransitionSystemState) if !ok { return []TransitionSystemState{}, errors.New("The first input to post is not of type TransitionSystemState.") } System := stateIn.System allActions := System.Act var nextStates []TransitionSystemState var tempPost []TransitionSystemState var err error for _, action := range allActions { tempPost, err = Post(stateIn, action) if err != nil { return []TransitionSystemState{}, err } for _, postElt := range tempPost { nextStates = postElt.AppendIfUniqueTo(nextStates) } } return nextStates, nil case 2: // State and Action is Given stateIn, ok := SorSA[0].(TransitionSystemState) if !ok { return []TransitionSystemState{}, errors.New("The first input to post is not of type TransitionSystemState.") } actionIn, ok := SorSA[1].(string) if !ok { return []TransitionSystemState{}, errors.New("The second input to post is not of type string!") } // Get Transition value System := stateIn.System tValues := System.Transition[stateIn][actionIn] var nextStates []TransitionSystemState for _, nextState := range tValues { nextStates = nextState.AppendIfUniqueTo(nextStates) } return nextStates, nil } // Return error return []TransitionSystemState{}, errors.New(fmt.Sprintf("Unexpected number of inputs to post (%v).", len(SorSA))) } /* Pre Description: Finds the set of states that can precede a given state (or set of states). Usage: tempPreSet , err := Pre( s0 ) tempPreSet , err := Pre( s0 , a0 ) */ func Pre(SorSA ...interface{}) ([]TransitionSystemState, error) { switch len(SorSA) { case 1: // Only State Is Given stateIn, ok := SorSA[0].(TransitionSystemState) if !ok { return []TransitionSystemState{}, errors.New("The first input to post is not of type TransitionSystemState.") } System := stateIn.System allActions := System.Act var predecessors []TransitionSystemState var tempPre []TransitionSystemState var err error for _, action := range allActions { tempPre, err = Pre(stateIn, action) if err != nil { return []TransitionSystemState{}, err } for _, preElt := range tempPre { predecessors = preElt.AppendIfUniqueTo(predecessors) } } return predecessors, nil case 2: // State and Action is Given stateIn, ok := SorSA[0].(TransitionSystemState) if !ok { return []TransitionSystemState{}, errors.New("The first input to post is not of type TransitionSystemState.") } actionIn, ok := SorSA[1].(string) if !ok { return []TransitionSystemState{}, errors.New("The second input to post is not of type string!") } // Get Transition value System := stateIn.System var matchingPredecessors []TransitionSystemState for predecessor, actionMap := range System.Transition { if stateIn.In(actionMap[actionIn]) { // If the target state is in the result of (predecessor,actionIn) -> stateIn, // then save the value of stateIn matchingPredecessors = append(matchingPredecessors, predecessor) } } return matchingPredecessors, nil } // Return error return []TransitionSystemState{}, errors.New(fmt.Sprintf("Unexpected number of inputs to post (%v).", len(SorSA))) } /* IsTerminal Description: Identifies if the given state is terminal. (i.e. if Post(stateIn) is empty) */ func (stateIn TransitionSystemState) IsTerminal() bool { // Construct the Ancestor States ancestors, _ := Post(stateIn) return len(ancestors) == 0 } /* IsReachable Description: Identifies if the given state is reachable or not. Usage: reachableFlag := state1.IsReachable() */ func (stateIn TransitionSystemState) IsReachable() bool { // Get Transition System System := stateIn.System // Check to see if state is initial. // If it is, then we are done. if stateIn.In(System.I) { return true } // Create loop variables SI := []TransitionSystemState{stateIn} SIm1 := []TransitionSystemState{} Reachable := SI // Create Loop Which Checks: // - If a predecessor of stateIn is in System.I // - Or if the predecessor set is equal to the for { // Compute the predecessors. for _, si := range SI { tempPre, _ := Pre(si) for _, sPre := range tempPre { Reachable = sPre.AppendIfUniqueTo(Reachable) SIm1 = sPre.AppendIfUniqueTo(SIm1) } } // Check to see if any predecessors are in the initial state set. for _, sIm1 := range SIm1 { if sIm1.In(System.I) { return true } } // Check if the predecessor set is a subset of the current set at i // If it is, then exit. And the state is not reachable if tf, _ := SliceSubset(SIm1, SI); tf { break } // Prepare for next iteration of loop SI = SIm1 SIm1 = []TransitionSystemState{} } return false } /* String Description: Returns the value of the state if the value is of type string. Otherwise, this returns the value of each part of the Value */ func (stateIn TransitionSystemState) String() string { return stateIn.Name }
transitionsystemstate.go
0.68056
0.48932
transitionsystemstate.go
starcoder
package artifacts import ( "github.com/pkg/errors" "github.com/insolar/insolar/insolar" ) func NewCodeDescriptor(code []byte, machineType insolar.MachineType, ref insolar.Reference) CodeDescriptor { return &codeDescriptor{ code: code, machineType: machineType, ref: ref, } } // CodeDescriptor represents meta info required to fetch all code data. type codeDescriptor struct { code []byte machineType insolar.MachineType ref insolar.Reference } // Ref returns reference to represented code record. func (d *codeDescriptor) Ref() *insolar.Reference { return &d.ref } // MachineType returns code machine type for represented code. func (d *codeDescriptor) MachineType() insolar.MachineType { return d.machineType } // Code returns code data. func (d *codeDescriptor) Code() ([]byte, error) { return d.code, nil } // ObjectDescriptor represents meta info required to fetch all object data. type objectDescriptor struct { head insolar.Reference state insolar.ID prototype *insolar.Reference memory []byte parent insolar.Reference requestID *insolar.ID } // Prototype returns prototype reference. func (d *objectDescriptor) Prototype() (*insolar.Reference, error) { if d.prototype == nil { return nil, errors.New("object has no prototype") } return d.prototype, nil } // HeadRef returns reference to represented object record. func (d *objectDescriptor) HeadRef() *insolar.Reference { return &d.head } // StateID returns reference to object state record. func (d *objectDescriptor) StateID() *insolar.ID { return &d.state } // Memory fetches latest memory of the object known to storage. func (d *objectDescriptor) Memory() []byte { return d.memory } // Parent returns object's parent. func (d *objectDescriptor) Parent() *insolar.Reference { return &d.parent } func (d *objectDescriptor) EarliestRequestID() *insolar.ID { return d.requestID } func NewPrototypeDescriptor( head insolar.Reference, state insolar.ID, code insolar.Reference, ) PrototypeDescriptor { return &prototypeDescriptor{ head: head, state: state, code: code, } } type prototypeDescriptor struct { head insolar.Reference state insolar.ID code insolar.Reference } // Code returns code reference. func (d *prototypeDescriptor) Code() *insolar.Reference { return &d.code } // HeadRef returns reference to represented object record. func (d *prototypeDescriptor) HeadRef() *insolar.Reference { return &d.head } // StateID returns reference to object state record. func (d *prototypeDescriptor) StateID() *insolar.ID { return &d.state }
logicrunner/artifacts/descriptors.go
0.840455
0.429788
descriptors.go
starcoder
package gosnowth import ( "bytes" "context" "encoding/json" "fmt" "net/url" "path" "strconv" "time" "github.com/openhistogram/circonusllhist" ) // HistogramValue values are individual data points of a histogram metric. type HistogramValue struct { Time time.Time Period time.Duration Data map[string]int64 } // MarshalJSON encodes a HistogramValue value into a JSON format byte slice. func (hv *HistogramValue) MarshalJSON() ([]byte, error) { v := []interface{}{} fv, err := strconv.ParseFloat(formatTimestamp(hv.Time), 64) if err != nil { return nil, fmt.Errorf("invalid histogram value time: " + formatTimestamp(hv.Time)) } v = append(v, fv) v = append(v, hv.Period.Seconds()) v = append(v, hv.Data) return json.Marshal(v) } // UnmarshalJSON decodes a JSON format byte slice into a HistogramValue value. func (hv *HistogramValue) UnmarshalJSON(b []byte) error { v := []interface{}{} err := json.Unmarshal(b, &v) if err != nil { return err } if len(v) != 3 { return fmt.Errorf("histogram value should contain three entries: " + string(b)) } if fv, ok := v[0].(float64); ok { tv, err := parseTimestamp(strconv.FormatFloat(fv, 'f', 3, 64)) if err != nil { return err } hv.Time = tv } if fv, ok := v[1].(float64); ok { hv.Period = time.Duration(fv) * time.Second } if m, ok := v[2].(map[string]interface{}); ok { hv.Data = make(map[string]int64, len(m)) for k, iv := range m { if fv, ok := iv.(float64); ok { hv.Data[k] = int64(fv) } } } return nil } // Timestamp returns the HistogramValue time as a string in the IRONdb // timestamp format. func (hv *HistogramValue) Timestamp() string { return formatTimestamp(hv.Time) } // ReadHistogramValues reads histogram data from a node. func (sc *SnowthClient) ReadHistogramValues( uuid, metric string, period time.Duration, start, end time.Time, nodes ...*SnowthNode) ([]HistogramValue, error) { return sc.ReadHistogramValuesContext(context.Background(), uuid, metric, period, start, end, nodes...) } // ReadHistogramValuesContext is the context aware version of // ReadHistogramValues. func (sc *SnowthClient) ReadHistogramValuesContext(ctx context.Context, uuid, metric string, period time.Duration, start, end time.Time, nodes ...*SnowthNode) ([]HistogramValue, error) { var node *SnowthNode if len(nodes) > 0 && nodes[0] != nil { node = nodes[0] } else { node = sc.GetActiveNode(sc.FindMetricNodeIDs(uuid, metric)) } startTS := start.Unix() - start.Unix()%int64(period.Seconds()) endTS := end.Unix() - end.Unix()%int64(period.Seconds()) + int64(period.Seconds()) r := []HistogramValue{} body, _, err := sc.DoRequestContext(ctx, node, "GET", path.Join("/histogram", strconv.FormatInt(startTS, 10), strconv.FormatInt(endTS, 10), strconv.FormatInt(int64(period.Seconds()), 10), uuid, url.QueryEscape(metric)), nil, nil) if err != nil { return nil, err } if err := decodeJSON(body, &r); err != nil { return nil, fmt.Errorf("unable to decode IRONdb response: %w", err) } return r, nil } // HistogramData values represent histogram data records in IRONdb. type HistogramData struct { AccountID int64 `json:"account_id"` Metric string `json:"metric"` ID string `json:"id"` CheckName string `json:"check_name"` Offset int64 `json:"offset"` Period int64 `json:"period"` Histogram *circonusllhist.Histogram `json:"histogram"` } // WriteHistogram sends a list of histogram data values to be written // to an IRONdb node. func (sc *SnowthClient) WriteHistogram(data []HistogramData, nodes ...*SnowthNode) error { return sc.WriteHistogramContext(context.Background(), data, nodes...) } // WriteHistogramContext is the context aware version of WriteHistogram. func (sc *SnowthClient) WriteHistogramContext(ctx context.Context, data []HistogramData, nodes ...*SnowthNode) error { var node *SnowthNode if len(nodes) > 0 && nodes[0] != nil { node = nodes[0] } else if len(data) > 0 { node = sc.GetActiveNode(sc.FindMetricNodeIDs(data[0].ID, data[0].Metric)) } buf := new(bytes.Buffer) if err := json.NewEncoder(buf).Encode(data); err != nil { return fmt.Errorf("failed to encode HistogramData for write: %w", err) } _, _, err := sc.DoRequestContext(ctx, node, "POST", "/histogram/write", buf, nil) return err }
vendor/github.com/circonus-labs/gosnowth/histogram.go
0.805517
0.404507
histogram.go
starcoder
package convert import ( "errors" "github.com/go-spatial/tegola" "github.com/go-spatial/tegola/basic" "github.com/go-spatial/tegola/geom" ) var ErrUnknownGeometry = errors.New("Unknown Geometry") func ToGeom(g tegola.Geometry) (geom.Geometry, error) { switch geo := g.(type) { default: return nil, ErrUnknownGeometry case tegola.Point: return geom.Point{geo.X(), geo.Y()}, nil case tegola.MultiPoint: pts := geo.Points() var mpts = make(geom.MultiPoint, len(pts)) for i := range pts { mpts[i][0] = pts[i].X() mpts[i][1] = pts[i].Y() } return mpts, nil case tegola.LineString: pts := geo.Subpoints() var ln = make(geom.LineString, len(pts)) for i := range pts { ln[i][0] = pts[i].X() ln[i][1] = pts[i].Y() } return ln, nil case tegola.MultiLine: lns := geo.Lines() var mln = make(geom.MultiLineString, len(lns)) for i := range lns { pts := lns[i].Subpoints() mln[i] = make(geom.LineString, len(pts)) for j := range pts { mln[i][j][0] = pts[j].X() mln[i][j][1] = pts[j].Y() } } return mln, nil case tegola.Polygon: lns := geo.Sublines() var ply = make(geom.Polygon, len(lns)) for i := range lns { pts := lns[i].Subpoints() ply[i] = make(geom.LineString, len(pts)) for j := range pts { ply[i][j][0] = pts[j].X() ply[i][j][1] = pts[j].Y() } } return ply, nil case tegola.MultiPolygon: mply := geo.Polygons() var mp = make(geom.MultiPolygon, len(mply)) for i := range mply { lns := mply[i].Sublines() mp[i] = make(geom.Polygon, len(lns)) for j := range lns { pts := lns[j].Subpoints() mp[i][j] = make(geom.LineString, len(pts)) for k := range pts { mp[i][j][k][0] = pts[k].X() mp[i][j][k][1] = pts[k].Y() } } } return mp, nil case tegola.Collection: geometries := geo.Geometries() var cl = make(geom.Collection, len(geometries)) for i := range geometries { tgeo, err := ToGeom(geometries[i]) if err != nil { return nil, err } cl[i] = tgeo } return cl, nil } } func toBasicLine(g geom.LineString) basic.Line { l := make(basic.Line, len(g)) for i := range g { l[i] = basic.Point(g[i]) } return l } func toBasic(g geom.Geometry) basic.Geometry { switch geo := g.(type) { default: return nil case geom.Point: return basic.Point(geo) case geom.MultiPoint: mp := make(basic.MultiPoint, len(geo)) for i := range geo { mp[i] = basic.Point(geo[i]) } return mp case geom.LineString: return toBasicLine(geo) case geom.MultiLineString: ml := make(basic.MultiLine, len(geo)) for i := range geo { ml[i] = toBasicLine(geo[i]) } return ml case geom.Polygon: plg := make(basic.Polygon, len(geo)) for i := range geo { plg[i] = toBasicLine(geo[i]) } return plg case geom.MultiPolygon: mplg := make(basic.MultiPolygon, len(geo)) for i := range geo { mplg[i] = make(basic.Polygon, len(geo[i])) for j := range geo[i] { mplg[i][j] = toBasicLine(geo[i][j]) } } return mplg case geom.Collection: geometries := geo.Geometries() bc := make(basic.Collection, len(geometries)) for i := range geometries { bc[i] = toBasic(geometries[i]) } return bc } } func ToTegola(geom geom.Geometry) (tegola.Geometry, error) { g := toBasic(geom) if g == nil { return g, ErrUnknownGeometry } return g, nil }
internal/convert/convert.go
0.508056
0.503235
convert.go
starcoder
package v1 import ( "bytes" "encoding/binary" "errors" "fmt" "strings" "github.com/golang/protobuf/proto" equality "github.com/solo-io/protoc-gen-ext/pkg/equality" ) // ensure the imports are used var ( _ = errors.New("") _ = fmt.Print _ = binary.LittleEndian _ = bytes.Compare _ = strings.Compare _ = equality.Equalizer(nil) _ = proto.Message(nil) ) // Equal function func (m *Upstream) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*Upstream) if !ok { that2, ok := that.(Upstream) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if h, ok := interface{}(m.GetStatus()).(equality.Equalizer); ok { if !h.Equal(target.GetStatus()) { return false } } else { if !proto.Equal(m.GetStatus(), target.GetStatus()) { return false } } if h, ok := interface{}(m.GetMetadata()).(equality.Equalizer); ok { if !h.Equal(target.GetMetadata()) { return false } } else { if !proto.Equal(m.GetMetadata(), target.GetMetadata()) { return false } } if h, ok := interface{}(m.GetDiscoveryMetadata()).(equality.Equalizer); ok { if !h.Equal(target.GetDiscoveryMetadata()) { return false } } else { if !proto.Equal(m.GetDiscoveryMetadata(), target.GetDiscoveryMetadata()) { return false } } if h, ok := interface{}(m.GetSslConfig()).(equality.Equalizer); ok { if !h.Equal(target.GetSslConfig()) { return false } } else { if !proto.Equal(m.GetSslConfig(), target.GetSslConfig()) { return false } } if h, ok := interface{}(m.GetCircuitBreakers()).(equality.Equalizer); ok { if !h.Equal(target.GetCircuitBreakers()) { return false } } else { if !proto.Equal(m.GetCircuitBreakers(), target.GetCircuitBreakers()) { return false } } if h, ok := interface{}(m.GetLoadBalancerConfig()).(equality.Equalizer); ok { if !h.Equal(target.GetLoadBalancerConfig()) { return false } } else { if !proto.Equal(m.GetLoadBalancerConfig(), target.GetLoadBalancerConfig()) { return false } } if h, ok := interface{}(m.GetConnectionConfig()).(equality.Equalizer); ok { if !h.Equal(target.GetConnectionConfig()) { return false } } else { if !proto.Equal(m.GetConnectionConfig(), target.GetConnectionConfig()) { return false } } if len(m.GetHealthChecks()) != len(target.GetHealthChecks()) { return false } for idx, v := range m.GetHealthChecks() { if h, ok := interface{}(v).(equality.Equalizer); ok { if !h.Equal(target.GetHealthChecks()[idx]) { return false } } else { if !proto.Equal(v, target.GetHealthChecks()[idx]) { return false } } } if h, ok := interface{}(m.GetOutlierDetection()).(equality.Equalizer); ok { if !h.Equal(target.GetOutlierDetection()) { return false } } else { if !proto.Equal(m.GetOutlierDetection(), target.GetOutlierDetection()) { return false } } if h, ok := interface{}(m.GetUseHttp2()).(equality.Equalizer); ok { if !h.Equal(target.GetUseHttp2()) { return false } } else { if !proto.Equal(m.GetUseHttp2(), target.GetUseHttp2()) { return false } } if h, ok := interface{}(m.GetFailover()).(equality.Equalizer); ok { if !h.Equal(target.GetFailover()) { return false } } else { if !proto.Equal(m.GetFailover(), target.GetFailover()) { return false } } if h, ok := interface{}(m.GetInitialStreamWindowSize()).(equality.Equalizer); ok { if !h.Equal(target.GetInitialStreamWindowSize()) { return false } } else { if !proto.Equal(m.GetInitialStreamWindowSize(), target.GetInitialStreamWindowSize()) { return false } } if h, ok := interface{}(m.GetInitialConnectionWindowSize()).(equality.Equalizer); ok { if !h.Equal(target.GetInitialConnectionWindowSize()) { return false } } else { if !proto.Equal(m.GetInitialConnectionWindowSize(), target.GetInitialConnectionWindowSize()) { return false } } switch m.UpstreamType.(type) { case *Upstream_Kube: if h, ok := interface{}(m.GetKube()).(equality.Equalizer); ok { if !h.Equal(target.GetKube()) { return false } } else { if !proto.Equal(m.GetKube(), target.GetKube()) { return false } } case *Upstream_Static: if h, ok := interface{}(m.GetStatic()).(equality.Equalizer); ok { if !h.Equal(target.GetStatic()) { return false } } else { if !proto.Equal(m.GetStatic(), target.GetStatic()) { return false } } case *Upstream_Pipe: if h, ok := interface{}(m.GetPipe()).(equality.Equalizer); ok { if !h.Equal(target.GetPipe()) { return false } } else { if !proto.Equal(m.GetPipe(), target.GetPipe()) { return false } } case *Upstream_Aws: if h, ok := interface{}(m.GetAws()).(equality.Equalizer); ok { if !h.Equal(target.GetAws()) { return false } } else { if !proto.Equal(m.GetAws(), target.GetAws()) { return false } } case *Upstream_Azure: if h, ok := interface{}(m.GetAzure()).(equality.Equalizer); ok { if !h.Equal(target.GetAzure()) { return false } } else { if !proto.Equal(m.GetAzure(), target.GetAzure()) { return false } } case *Upstream_Consul: if h, ok := interface{}(m.GetConsul()).(equality.Equalizer); ok { if !h.Equal(target.GetConsul()) { return false } } else { if !proto.Equal(m.GetConsul(), target.GetConsul()) { return false } } case *Upstream_AwsEc2: if h, ok := interface{}(m.GetAwsEc2()).(equality.Equalizer); ok { if !h.Equal(target.GetAwsEc2()) { return false } } else { if !proto.Equal(m.GetAwsEc2(), target.GetAwsEc2()) { return false } } } return true } // Equal function func (m *DiscoveryMetadata) Equal(that interface{}) bool { if that == nil { return m == nil } target, ok := that.(*DiscoveryMetadata) if !ok { that2, ok := that.(DiscoveryMetadata) if ok { target = &that2 } else { return false } } if target == nil { return m == nil } else if m == nil { return false } if len(m.GetLabels()) != len(target.GetLabels()) { return false } for k, v := range m.GetLabels() { if strings.Compare(v, target.GetLabels()[k]) != 0 { return false } } return true }
projects/gloo/pkg/api/v1/upstream.pb.equal.go
0.538498
0.435421
upstream.pb.equal.go
starcoder
package histogram import ( "sort" "strconv" "strings" "github.com/grokify/mogo/type/stringsutil" "github.com/grokify/gocharts/v2/data/table" ) type HistogramSets struct { Name string HistogramSetMap map[string]*HistogramSet } func NewHistogramSets(name string) *HistogramSets { return &HistogramSets{ Name: name, HistogramSetMap: map[string]*HistogramSet{}} } func (hsets *HistogramSets) Add(hsetName, histName, binName string, binCount int, trimSpace bool) { if trimSpace { hsetName = strings.TrimSpace(hsetName) histName = strings.TrimSpace(histName) binName = strings.TrimSpace(binName) } hset, ok := hsets.HistogramSetMap[hsetName] if !ok { hset = NewHistogramSet(hsetName) } hset.Add(histName, binName, binCount) hsets.HistogramSetMap[hsetName] = hset } func (hsets *HistogramSets) Flatten(name string) *HistogramSet { hsetFlat := NewHistogramSet(name) for _, hset := range hsets.HistogramSetMap { for histName, hist := range hset.HistogramMap { for binName, binCount := range hist.Bins { hsetFlat.Add(histName, binName, binCount) } } } return hsetFlat } func (hsets *HistogramSets) BinNames() []string { binNamesMap := map[string]int{} hsets.Visit(func(hsetName, histName, binName string, binCount int) { binNamesMap[binName] = 1 }) binNames := []string{} for binName := range binNamesMap { binNames = append(binNames, binName) } sort.Strings(binNames) return binNames } // ItemCount returns the number of histogram sets. func (hsets *HistogramSets) ItemCount() uint { return uint(len(hsets.HistogramSetMap)) } func (hsets *HistogramSets) Counts() *HistogramSetsCounts { return NewHistogramSetsCounts(*hsets) } func (hsets *HistogramSets) Visit(visit func(hsetName, histName, binName string, binCount int)) { for hsetName, hset := range hsets.HistogramSetMap { for histName, hist := range hset.HistogramMap { for binName, binCount := range hist.Bins { visit(hsetName, histName, binName, binCount) } } } } func (hsets *HistogramSets) Table(tableName, colNameHSet, colNameHist, colNameBinName, colNameBinCount string) table.Table { tbl := table.NewTable(tableName) tbl.Columns = []string{ stringsutil.FirstNonEmpty(colNameHSet, "Histogram Set"), stringsutil.FirstNonEmpty(colNameHist, "Histogram"), stringsutil.FirstNonEmpty(colNameBinName, "Bin Name"), stringsutil.FirstNonEmpty(colNameBinCount, "Bin Count")} hsets.Visit(func(hsetName, histName, binName string, binCount int) { tbl.Rows = append(tbl.Rows, []string{ hsetName, histName, binName, strconv.Itoa(binCount)}) }) return tbl } // TableMatrix returns a `*table.Table` where the first column is the histogram // set name, the second column is the histogram name and the other columns are // the bin names. func (hsets *HistogramSets) TableMatrix(tableName, colNameHSet, colNameHist, colNameBinNamePrefix, colNameBinNameSuffix string) table.Table { tbl := table.NewTable(tableName) tbl.FormatMap = map[int]string{ -1: table.FormatInt, 0: table.FormatString, 1: table.FormatString} binNames := table.Columns(hsets.BinNames()) tbl.Columns = []string{ stringsutil.FirstNonEmpty(colNameHSet, "Histogram Set"), stringsutil.FirstNonEmpty(colNameHist, "Histogram")} for i, binName := range binNames { if len(strings.TrimSpace(binName)) == 0 { binName = "Unnamed Bin " + strconv.Itoa(i+1) } tbl.Columns = append(tbl.Columns, colNameBinNamePrefix+binName+colNameBinNameSuffix) } for hsetName, hset := range hsets.HistogramSetMap { for histName, hist := range hset.HistogramMap { row := []string{hsetName, histName} for _, binName := range binNames { if val, ok := hist.Bins[binName]; ok { row = append(row, strconv.Itoa(val)) } else { row = append(row, "0") } } tbl.Rows = append(tbl.Rows, row) } } return tbl } func (hsets *HistogramSets) WriteXLSX(filename, sheetname, colNameHSet, colNameHist, colNameBinName, colNameBinCount string) error { tbl := hsets.Table(sheetname, colNameHSet, colNameHist, colNameBinName, colNameBinCount) return tbl.WriteXLSX(filename, sheetname) } func (hsets *HistogramSets) WriteXLSXMatrix(filename, sheetname, colNameHSet, colNameHist, colNameBinNamePrefix, colNameBinNameSuffix string) error { tbl := hsets.TableMatrix(sheetname, colNameHSet, colNameHist, colNameBinNamePrefix, colNameBinNameSuffix) return tbl.WriteXLSX(filename, sheetname) }
data/histogram/histogram_sets.go
0.628977
0.487551
histogram_sets.go
starcoder
package nn import ( mat "github.com/nlpodyssey/spago/pkg/mat32" "github.com/nlpodyssey/spago/pkg/ml/ag" ) // ProcessingMode regulates the different usage of some operations (e.g. Dropout, BatchNorm, etc.), // depending on whether you're doing training or inference. // Failing to set the right mode will yield inconsistent inference results. type ProcessingMode uint8 const ( // Training is to be used during the training phase of a model. For example, dropouts are enabled. Training ProcessingMode = iota // Inference keeps weights fixed while using the model and disables some operations (e.g. skip dropout). Inference ) // Model is implemented by all neural network architectures. // You can assign parameters (i.e. nn.Param) as regular attributes (if any). // A Model can also contain other Model(s), allowing to nest them in a tree structure. // Through "reification" (i.e. nn.Reify()), a Model operates as a "processor" using the computational graph. // The Forward() operation can only be performed on a reified model (a.k.a. processor). type Model interface { // Graph returns the computational graph on which the model operates (can be nil). Graph() *ag.Graph // Mode returns whether the model is being used for training or inference. Mode() ProcessingMode // IsProcessor returns whether the model has been reified (i.e., contextualized to operate // on a graph) and can perform the Forward(). IsProcessor() bool // InitProcessor is used to initialize structures and data useful for the Forward(). // nn.Reify() automatically invokes InitProcessor() for any sub-models. InitProcessor() // Close can be used to close or finalize model structures. // For example, embeddings.Model needs to close the underlying key-value store. Close() } // StandardForwarder consists of a Forward variadic function that accepts ag.Node and returns a slice of ag.Node. // It is called StandardForwarder since this is the most frequent forward method among all implemented neural models. type StandardForwarder interface { // Forward executes the forward step for each input and returns the result. // Recurrent networks, treats the input nodes as a sequence. Differently, feed-forward // networks are stateless so every computation is independent and possibly concurrent. Forward(xs ...ag.Node) []ag.Node } // StandardModel consists of a model that implements StandardForwarder. type StandardModel interface { Model StandardForwarder } // Reify returns a new "reified" model (a.k.a. processor) to execute the forward step. func Reify(m Model, g *ag.Graph, mode ProcessingMode) Model { return newReifier(g, mode).reify(m) } // ReifyForTraining returns a new reified model (a.k.a. processor) with the // given Graph, setting the mode to Training. func ReifyForTraining(m Model, g *ag.Graph) Model { return Reify(m, g, Training) } // ReifyForInference returns a new reified model (a.k.a. processor) with the // given Graph, setting the mode to Inference. func ReifyForInference(m Model, g *ag.Graph) Model { return Reify(m, g, Inference) } // ForEachParam iterate all the parameters of a model also exploring the sub-parameters recursively. func ForEachParam(m Model, callback func(param Param)) { newParamsTraversal(callback, true).walk(m) } // ForEachParamStrict iterate all the parameters of a model without exploring the sub-models. func ForEachParamStrict(m Model, callback func(param Param)) { newParamsTraversal(callback, false).walk(m) } // ZeroGrad set the gradients of all model's parameters (including sub-params) to zeros. func ZeroGrad(m Model) { ForEachParam(m, func(param Param) { param.ZeroGrad() }) } // ClearSupport clears the support structure of all model's parameters (including sub-params). func ClearSupport(m Model) { ForEachParam(m, func(param Param) { param.ClearPayload() }) } // DumpParamsVector dumps all params of a Model into a single Dense vector. func DumpParamsVector(model Model) mat.Matrix { data := make([]mat.Float, 0) ForEachParam(model, func(param Param) { data = append(data, param.Value().Data()...) }) return mat.NewVecDense(data) } // LoadParamsVector sets all params of a Model from a previously dumped Dense vector. func LoadParamsVector(model Model, vector mat.Matrix) { data := vector.Data() offset := 0 ForEachParam(model, func(param Param) { size := param.Value().Size() param.Value().SetData(data[offset : offset+size]) offset += size }) } // MakeNewModels return n new models. // The callback is delegated to return a new model for each i-item. func MakeNewModels(n int, callback func(i int) Model) []Model { lst := make([]Model, n) for i := 0; i < n; i++ { lst[i] = callback(i) } return lst }
pkg/ml/nn/model.go
0.817647
0.618435
model.go
starcoder
package graphics import ( "image" "image/color" "math" ) // reference white point var d65 = [3]float64{0.95047, 1.00000, 1.08883} func labF(t float64) float64 { if t > 6.0/29.0*6.0/29.0*6.0/29.0 { return math.Cbrt(t) } return t/3.0*29.0/6.0*29.0/6.0 + 4.0/29.0 } func square(value float64) float64 { return value * value } type labEntry struct { l float64 a float64 b float64 } func labEntryFromColor(clr color.Color) labEntry { rLinear, gLinear, bLinear, _ := clr.RGBA() r, g, b := float64(rLinear)/float64(0xFFFF), float64(gLinear)/float64(0xFFFF), float64(bLinear)/float64(0xFFFF) x := 0.4124564*r + 0.3575761*g + 0.1804375*b y := 0.2126729*r + 0.7151522*g + 0.0721750*b z := 0.0193339*r + 0.1191920*g + 0.9503041*b whiteRef := d65 fy := labF(y / whiteRef[1]) entry := labEntry{ l: 1.16*fy - 0.16, a: 5.0 * (labF(x/whiteRef[0]) - fy), b: 2.0 * (fy - labF(z/whiteRef[2]))} return entry } func (entry labEntry) distanceTo(other labEntry) float64 { return math.Sqrt(square(entry.l-other.l) + square(entry.a-other.a) + square(entry.b-other.b)) } // StandardBitmapper creates bitmap images from generic images. type StandardBitmapper struct { pal []labEntry } // NewStandardBitmapper returns a new bitmapper instance. func NewStandardBitmapper(palette []color.Color) *StandardBitmapper { bitmapper := &StandardBitmapper{} for _, clr := range palette { bitmapper.pal = append(bitmapper.pal, labEntryFromColor(clr)) } return bitmapper } // Map maps the provided image to a bitmap based on the internal palette. func (bitmapper *StandardBitmapper) Map(img image.Image) Bitmap { var bmp Bitmap bounds := img.Bounds() bmp.Width = bounds.Dx() bmp.Height = bounds.Dy() bmp.Pixels = make([]byte, bmp.Width*bmp.Height) for row := 0; row < bmp.Height; row++ { for column := 0; column < bmp.Width; column++ { bmp.Pixels[row*bmp.Width+column] = bitmapper.MapColor(img.At(column, row)) } } return bmp } // MapColor maps the provided color to the nearest index in the palette. func (bitmapper *StandardBitmapper) MapColor(clr color.Color) (palIndex byte) { _, _, _, a := clr.RGBA() if a > 0 { clrEntry := labEntryFromColor(clr) palDistance := 1000.0 for colorIndex, palEntry := range bitmapper.pal { distance := palEntry.distanceTo(clrEntry) if distance < palDistance { palDistance = distance palIndex = byte(colorIndex) } } } return }
src/github.com/inkyblackness/shocked-client/graphics/StandardBitmapper.go
0.843605
0.407805
StandardBitmapper.go
starcoder
package iso20022 // Details about tax paid, or to be paid, to the government in accordance with the law, including pre-defined parameters such as thresholds and type of account. type TaxInformation3 struct { // Party on the credit side of the transaction to which the tax applies. Creditor *TaxParty1 `xml:"Cdtr,omitempty"` // Set of elements used to identify the party on the debit side of the transaction to which the tax applies. Debtor *TaxParty2 `xml:"Dbtr,omitempty"` // Territorial part of a country to which the tax payment is related. AdministrationZone *Max35Text `xml:"AdmstnZn,omitempty"` // Tax reference information that is specific to a taxing agency. ReferenceNumber *Max140Text `xml:"RefNb,omitempty"` // Method used to indicate the underlying business or how the tax is paid. Method *Max35Text `xml:"Mtd,omitempty"` // Total amount of money on which the tax is based. TotalTaxableBaseAmount *ActiveOrHistoricCurrencyAndAmount `xml:"TtlTaxblBaseAmt,omitempty"` // Total amount of money as result of the calculation of the tax. TotalTaxAmount *ActiveOrHistoricCurrencyAndAmount `xml:"TtlTaxAmt,omitempty"` // Date by which tax is due. Date *ISODate `xml:"Dt,omitempty"` // Sequential number of the tax report. SequenceNumber *Number `xml:"SeqNb,omitempty"` // Record of tax details. Record []*TaxRecord1 `xml:"Rcrd,omitempty"` } func (t *TaxInformation3) AddCreditor() *TaxParty1 { t.Creditor = new(TaxParty1) return t.Creditor } func (t *TaxInformation3) AddDebtor() *TaxParty2 { t.Debtor = new(TaxParty2) return t.Debtor } func (t *TaxInformation3) SetAdministrationZone(value string) { t.AdministrationZone = (*Max35Text)(&value) } func (t *TaxInformation3) SetReferenceNumber(value string) { t.ReferenceNumber = (*Max140Text)(&value) } func (t *TaxInformation3) SetMethod(value string) { t.Method = (*Max35Text)(&value) } func (t *TaxInformation3) SetTotalTaxableBaseAmount(value, currency string) { t.TotalTaxableBaseAmount = NewActiveOrHistoricCurrencyAndAmount(value, currency) } func (t *TaxInformation3) SetTotalTaxAmount(value, currency string) { t.TotalTaxAmount = NewActiveOrHistoricCurrencyAndAmount(value, currency) } func (t *TaxInformation3) SetDate(value string) { t.Date = (*ISODate)(&value) } func (t *TaxInformation3) SetSequenceNumber(value string) { t.SequenceNumber = (*Number)(&value) } func (t *TaxInformation3) AddRecord() *TaxRecord1 { newValue := new(TaxRecord1) t.Record = append(t.Record, newValue) return newValue }
TaxInformation3.go
0.739422
0.560614
TaxInformation3.go
starcoder
package iso20022 // Margin required to cover the risk because of the price fluctuations occurred on the unsettled exposures towards central counterparty. type VariationMargin3 struct { // Provides details about the security identification. FinancialInstrumentIdentification *SecurityIdentification14 `xml:"FinInstrmId,omitempty"` // Margin required to cover the risk because of the price fluctuations occurred on the unsettled exposures towards the central counterparty. TotalVariationMargin []*TotalVariationMargin1 `xml:"TtlVartnMrgn"` // Net unrealised profit or loss on the value of the netted, gross and failing positions. TotalMarkToMarket *Amount2 `xml:"TtlMrkToMkt"` // Unrealised net loss calculated at the participant portfolio level. MarkToMarketNetted []*Amount2 `xml:"MrkToMktNetd,omitempty"` // Unrealised net loss calculated in that market/boundary. MarkToMarketGross []*Amount2 `xml:"MrkToMktGrss,omitempty"` // Sum of the unrealised loss without taking profit into consideration. MarkToMarketFails []*Amount2 `xml:"MrkToMktFls,omitempty"` // Haircut applied to the absolute value of the participants net positions. Calculation depends on a participants credit rating. FailsHaircut *Amount2 `xml:"FlsHrcut,omitempty"` } func (v *VariationMargin3) AddFinancialInstrumentIdentification() *SecurityIdentification14 { v.FinancialInstrumentIdentification = new(SecurityIdentification14) return v.FinancialInstrumentIdentification } func (v *VariationMargin3) AddTotalVariationMargin() *TotalVariationMargin1 { newValue := new(TotalVariationMargin1) v.TotalVariationMargin = append(v.TotalVariationMargin, newValue) return newValue } func (v *VariationMargin3) AddTotalMarkToMarket() *Amount2 { v.TotalMarkToMarket = new(Amount2) return v.TotalMarkToMarket } func (v *VariationMargin3) AddMarkToMarketNetted() *Amount2 { newValue := new(Amount2) v.MarkToMarketNetted = append(v.MarkToMarketNetted, newValue) return newValue } func (v *VariationMargin3) AddMarkToMarketGross() *Amount2 { newValue := new(Amount2) v.MarkToMarketGross = append(v.MarkToMarketGross, newValue) return newValue } func (v *VariationMargin3) AddMarkToMarketFails() *Amount2 { newValue := new(Amount2) v.MarkToMarketFails = append(v.MarkToMarketFails, newValue) return newValue } func (v *VariationMargin3) AddFailsHaircut() *Amount2 { v.FailsHaircut = new(Amount2) return v.FailsHaircut }
VariationMargin3.go
0.813868
0.442396
VariationMargin3.go
starcoder
package color import ( "github.com/juan-medina/goecs" ) // Solid represents a RGBA color type Solid struct { R uint8 // R is the green Color component G uint8 // G is the green Color component B uint8 // B is the blue Color component A uint8 // A is the alpha Color component } // Type return this goecs.ComponentType func (rc Solid) Type() goecs.ComponentType { return TYPE.Solid } // Alpha returns a new Color modifying the A component func (rc Solid) Alpha(alpha uint8) Solid { return Solid{R: rc.R, G: rc.G, B: rc.B, A: alpha} } // Blend the Color with a given Color using an scale func (rc Solid) Blend(other Solid, scale float32) Solid { r1 := float32(rc.R) g1 := float32(rc.G) b1 := float32(rc.B) a1 := float32(rc.A) r2 := float32(other.R) g2 := float32(other.G) b2 := float32(other.B) a2 := float32(other.A) r := r1 + ((r2 - r1) * scale) g := g1 + ((g2 - g1) * scale) b := b1 + ((b2 - b1) * scale) a := a1 + ((a2 - a1) * scale) return Solid{R: uint8(r), G: uint8(g), B: uint8(b), A: uint8(a)} } // Inverse the color.Solid func (rc Solid) Inverse() Solid { r1 := int32(rc.R) g1 := int32(rc.G) b1 := int32(rc.B) a1 := int32(rc.A) r := 255 - r1 g := 255 - g1 b := 255 - b1 a := a1 return Solid{R: uint8(r), G: uint8(g), B: uint8(b), A: uint8(a)} } // GrayScale converts a color.Solid to gray scale func (rc Solid) GrayScale() Solid { r := float64(rc.R) * 0.2989 g := float64(rc.G) * 0.5870 b := float64(rc.B) * 0.1140 gray := uint8(r + g + b) return Solid{R: gray, G: gray, B: gray, A: rc.A} } // Equals returns if two color.Solid are equal func (rc Solid) Equals(other Solid) bool { return rc.R == other.R && rc.G == other.G && rc.B == other.B && rc.A == other.A } // GradientDirection is the direction of color.Gradient type GradientDirection int // Directions for a color.Gradient //goland:noinspection ALL const ( GradientHorizontal = GradientDirection(iota) // GradientHorizontal is a horizontal color.Gradient GradientVertical // GradientHorizontal is a vertical color.Gradient ) // Gradient represents a gradient color type Gradient struct { From Solid // From what color.Solid the gradient stars To Solid // To what color.Solid the gradient ends Direction GradientDirection // Direction is GradientDirection for this color.Gradient } // Type return this goecs.ComponentType func (g Gradient) Type() goecs.ComponentType { return TYPE.Gradient } //goland:noinspection GoUnusedGlobalVariable var ( Black = Solid{A: 255} // Black Color White = Solid{R: 255, G: 255, B: 255, A: 255} // White Color Magenta = Solid{R: 255, B: 255, A: 255} // Magenta Color LightGray = Solid{R: 200, G: 200, B: 200, A: 255} // LightGray is a Light Gray Color Gray = Solid{R: 130, G: 130, B: 130, A: 255} // Gray Color DarkGray = Solid{R: 80, G: 80, B: 80, A: 255} // DarkGray Dark Gray Yellow = Solid{R: 253, G: 249, A: 255} // Yellow Color Gold = Solid{R: 255, G: 203, A: 255} // Gold Color Orange = Solid{R: 255, G: 161, A: 255} // Orange Color Pink = Solid{R: 255, G: 109, B: 194, A: 255} // Pink Color Red = Solid{R: 230, G: 41, B: 55, A: 255} // Red Color Maroon = Solid{R: 190, G: 33, B: 55, A: 255} // Marron Color Green = Solid{G: 228, B: 48, A: 255} // Green Color Lime = Solid{G: 158, B: 47, A: 255} // Lime Color DarkGreen = Solid{G: 117, B: 44, A: 255} // DarkGreen is a Dark Green Color SkyBlue = Solid{R: 102, G: 191, B: 255, A: 255} // SkyBlue Color Blue = Solid{G: 121, B: 241, A: 255} // Blue Color DarkBlue = Solid{G: 82, B: 172, A: 255} // DarkBlue is a Dark Blue Color Purple = Solid{R: 200, G: 122, B: 255, A: 255} // Purple Color Violet = Solid{R: 135, G: 60, B: 190, A: 255} // Violet Color DarkPurple = Solid{R: 112, G: 31, B: 126, A: 255} // DarkPurple is a Dark Purple Color Beige = Solid{R: 211, G: 176, B: 131, A: 255} // Beige Color Brown = Solid{R: 127, G: 106, B: 79, A: 255} // Brown Color DarkBrown = Solid{R: 76, G: 63, B: 47, A: 255} // DarkBrown Color Gopher = Solid{R: 106, G: 215, B: 229, A: 255} // Gopher Color ) type types struct { // Solid is the goecs.ComponentType for color.Solid Solid goecs.ComponentType // Gradient is the goecs.ComponentType for color.Gradient Gradient goecs.ComponentType } // TYPE hold the goecs.ComponentType for our color components var TYPE = types{ Solid: goecs.NewComponentType(), Gradient: goecs.NewComponentType(), } type gets struct { // Solid get a color.Solid from a goecs.Entity Solid func(e *goecs.Entity) Solid // Gradient get a color.Gradient from a goecs.Entity Gradient func(e *goecs.Entity) Gradient } // Get a color component var Get = gets{ // Solid get a color.Solid from a goecs.Entity Solid: func(e *goecs.Entity) Solid { return e.Get(TYPE.Solid).(Solid) }, // Gradient get a color.Gradient from a goecs.Entity Gradient: func(e *goecs.Entity) Gradient { return e.Get(TYPE.Gradient).(Gradient) }, }
components/color/color.go
0.881876
0.46035
color.go
starcoder
package seamcarving import ( "image" "github.com/wangjohn/quickselect" ) type EnergyFunction int const ( Energy1 EnergyFunction = iota Energy2 EnergyFunction = iota ) type Seam struct { Points []image.Point } func Resize(source image.Image, targetHeight, targetWidth int) (image.Image, error) { energies := initializeEnergies(source, Energy1) // TODO: don't just use Energy1 function bounds := source.Bounds() widthDiff := bounds.Dx() - targetWidth heightDiff := bounds.Dy() - targetHeight var resultImage image.Image var seams []Seam var newMax image.Point // TODO: figure out how to resize correctly. if widthDiff > heightDiff { seams = computeSeams(energies, widthDiff) newMax = image.Point{bounds.Max.X - widthDiff, bounds.Max.Y} } else { seams = computeSeams(energies, heightDiff) newMax = image.Point{bounds.Max.X, bounds.Max.Y - heightDiff} } newBounds := image.Rectangle{bounds.Min, newMax} resultImage, err := removeSeams(source, seams, newBounds) if err != nil { return nil, err } return resultImage, nil } func removeSeams(source image.Image, seams []Seam, newBounds image.Rectangle) (image.Image, error) { removedPoints := make(map[image.Point]bool) for _, seam := range seams { for _, point := range seam.Points { removedPoints[point] = true } } bounds := source.Bounds() newImage := image.NewRGBA(newBounds) for i := bounds.Min.X; i < bounds.Max.X; i++ { for j := bounds.Min.Y; j < bounds.Max.Y; j++ { curPoint := image.Point{i, j} _, removed := removedPoints[curPoint] if !removed { newImage.Set(i, j, source.At(i, j)) } } } return newImage, nil } func initializeEnergies(img image.Image, funcType EnergyFunction) ([][]float64) { rec := img.Bounds() height := rec.Max.X - rec.Min.X width := rec.Max.Y - rec.Min.Y energies := float64Matrix(height, width) for i := rec.Min.X; i < rec.Max.X; i++ { for j := rec.Min.Y; j < rec.Max.Y; j++ { xIndex := i - rec.Min.X yIndex := j - rec.Min.Y energies[xIndex][yIndex] = energyFunction(img, i, j, funcType) } } return energies } func float64Matrix(height, width int) ([][]float64) { matrix := make([][]float64, height) for i, _ := range matrix { matrix[i] = make([]float64, width) } return matrix } func intMatrix(height, width int) ([][]int) { matrix := make([][]int, height) for i, _ := range matrix { matrix[i] = make([]int, width) } return matrix } func energyFunction(img image.Image, i, j int, funcType EnergyFunction) (float64) { return 0.0 } func shouldReadjust(i, j int, candidate float64, matrix [][]float64, adjusted bool) (bool) { height := len(matrix) width := len(matrix[0]) return inMatrix(i, j, width, height) && (!adjusted || matrix[i][j] < candidate) } func computeSeams(energies [][]float64, numSeams int) ([]Seam) { height := len(energies) width := len(energies[0]) seamTable := float64Matrix(height, width) parentTable := intMatrix(height, width) for i := 0; i < height; i++ { for j := 0; j < width; j++ { var candidate float64 adjusted := false parent := 0 if shouldReadjust(i-1, j-1, candidate, seamTable, adjusted) { parent = -1 adjusted = true candidate = seamTable[i-1][j-1] } if shouldReadjust(i-1, j, candidate, seamTable, adjusted) { parent = 0 adjusted = true candidate = seamTable[i-1][j] } if shouldReadjust(i-1, j+1, candidate, seamTable, adjusted) { parent = 1 adjusted = true candidate = seamTable[i-1][j+1] } parentTable[i][j] = parent seamTable[i][j] = candidate + energies[i][j] } } var lastRowClone []float64 copy(lastRowClone, seamTable[height-1]) quickselect.QuickSelect(quickselect.Float64Slice(lastRowClone), numSeams) thresholdEnergy := lastRowClone[numSeams-1] computedSeams := make([]Seam, numSeams) seamNum := 0 for j := 0; j < width; j++ { if seamTable[height-1][j] <= thresholdEnergy { points := make([]image.Point, height) currentY := j for i := height-1; i >= 0; i-- { points[i] = image.Point{i, currentY} currentY = currentY + parentTable[i][j] } computedSeams[seamNum] = Seam{points} seamNum++ } } return computedSeams } func inMatrix(i, j, width, height int) (bool) { return 0 <= i && i < height && 0 <= j && j < width }
seamcarving/seamcarving.go
0.530723
0.473596
seamcarving.go
starcoder
package iso20022 // Information related to the transportation of goods by air. type TransportByAir4 struct { // Place from where the goods must leave. DepartureAirport *AirportName1Choice `xml:"DprtureAirprt"` // Place where the goods must arrive. DestinationAirport *AirportName1Choice `xml:"DstnAirprt"` // Flight number allocated by the airline that is carrying the goods from an airport of departure to an airport of destination;. FlightNumber *Max35Text `xml:"FlghtNb,omitempty"` // Identifies the party that is responsible for the conveyance of the goods from one place to another. AirCarrierName *Max70Text `xml:"AirCrrierNm,omitempty"` // Country in which the carrier of the goods, for example, shipping company, is located or registered. AirCarrierCountry *CountryCode `xml:"AirCrrierCtry,omitempty"` // Name of the carrier's (for example, shipping company's) agent that acts on behalf of the carrier and may be the issuer of transport documents relating to the underlying shipment. CarrierAgentName *Max70Text `xml:"CrrierAgtNm,omitempty"` // Country of registration of the carrier's (for example, shipping company's) agent that acts on behalf of the carrier and may be the issuer of transport documents relating to the underlying shipment. CarrierAgentCountry *CountryCode `xml:"CrrierAgtCtry,omitempty"` } func (t *TransportByAir4) AddDepartureAirport() *AirportName1Choice { t.DepartureAirport = new(AirportName1Choice) return t.DepartureAirport } func (t *TransportByAir4) AddDestinationAirport() *AirportName1Choice { t.DestinationAirport = new(AirportName1Choice) return t.DestinationAirport } func (t *TransportByAir4) SetFlightNumber(value string) { t.FlightNumber = (*Max35Text)(&value) } func (t *TransportByAir4) SetAirCarrierName(value string) { t.AirCarrierName = (*Max70Text)(&value) } func (t *TransportByAir4) SetAirCarrierCountry(value string) { t.AirCarrierCountry = (*CountryCode)(&value) } func (t *TransportByAir4) SetCarrierAgentName(value string) { t.CarrierAgentName = (*Max70Text)(&value) } func (t *TransportByAir4) SetCarrierAgentCountry(value string) { t.CarrierAgentCountry = (*CountryCode)(&value) }
TransportByAir4.go
0.787359
0.511046
TransportByAir4.go
starcoder
package base import "time" // ThroughputMetric is used to measure the byte throughput of some component // that performs work in a single-threaded manner. The throughput can be // approximated by Bytes/(WorkDuration+IdleTime). The idle time is represented // separately, so that the user of this metric could approximate the peak // throughput as Bytes/WorkTime. The metric is designed to be cumulative (see // Merge). type ThroughputMetric struct { // Bytes is the processes bytes by the component. Bytes int64 // WorkDuration is the duration that the component spent doing work. WorkDuration time.Duration // IdleDuration is the duration that the component was idling, waiting for // work. IdleDuration time.Duration } // Merge accumulates the information from another throughput metric. func (tm *ThroughputMetric) Merge(x ThroughputMetric) { tm.Bytes += x.Bytes tm.WorkDuration += x.WorkDuration tm.IdleDuration += x.IdleDuration } // PeakRate returns the approximate peak rate if there was no idling. func (tm *ThroughputMetric) PeakRate() int64 { if tm.Bytes == 0 { return 0 } return int64((float64(tm.Bytes) / float64(tm.WorkDuration)) * float64(time.Second)) } // Rate returns the observed rate. func (tm *ThroughputMetric) Rate() int64 { if tm.Bytes == 0 { return 0 } return int64((float64(tm.Bytes) / float64(tm.WorkDuration+tm.IdleDuration)) * float64(time.Second)) } // GaugeSampleMetric is used to measure a gauge value (e.g. queue length) by // accumulating samples of that gauge. type GaugeSampleMetric struct { // The sum of all the samples. sampleSum int64 // The number of samples. count int64 } // AddSample adds the given sample. func (gsm *GaugeSampleMetric) AddSample(sample int64) { gsm.sampleSum += sample gsm.count++ } // Merge accumulates the information from another gauge metric. func (gsm *GaugeSampleMetric) Merge(x GaugeSampleMetric) { gsm.sampleSum += x.sampleSum gsm.count += x.count } // Mean returns the mean value. func (gsm *GaugeSampleMetric) Mean() float64 { if gsm.count == 0 { return 0 } return float64(gsm.sampleSum) / float64(gsm.count) }
internal/base/metrics.go
0.845974
0.405125
metrics.go
starcoder
package auth0fga import ( "encoding/json" ) // Assertion struct for Assertion type Assertion struct { TupleKey *TupleKey `json:"tuple_key,omitempty"` Expectation bool `json:"expectation"` } // NewAssertion instantiates a new Assertion 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 NewAssertion(expectation bool) *Assertion { this := Assertion{} this.Expectation = expectation return &this } // NewAssertionWithDefaults instantiates a new Assertion 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 NewAssertionWithDefaults() *Assertion { this := Assertion{} return &this } // GetTupleKey returns the TupleKey field value if set, zero value otherwise. func (o *Assertion) GetTupleKey() TupleKey { if o == nil || o.TupleKey == nil { var ret TupleKey return ret } return *o.TupleKey } // GetTupleKeyOk returns a tuple with the TupleKey field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *Assertion) GetTupleKeyOk() (*TupleKey, bool) { if o == nil || o.TupleKey == nil { return nil, false } return o.TupleKey, true } // HasTupleKey returns a boolean if a field has been set. func (o *Assertion) HasTupleKey() bool { if o != nil && o.TupleKey != nil { return true } return false } // SetTupleKey gets a reference to the given TupleKey and assigns it to the TupleKey field. func (o *Assertion) SetTupleKey(v TupleKey) { o.TupleKey = &v } // GetExpectation returns the Expectation field value func (o *Assertion) GetExpectation() bool { if o == nil { var ret bool return ret } return o.Expectation } // GetExpectationOk returns a tuple with the Expectation field value // and a boolean to check if the value has been set. func (o *Assertion) GetExpectationOk() (*bool, bool) { if o == nil { return nil, false } return &o.Expectation, true } // SetExpectation sets field value func (o *Assertion) SetExpectation(v bool) { o.Expectation = v } func (o Assertion) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.TupleKey != nil { toSerialize["tuple_key"] = o.TupleKey } if true { toSerialize["expectation"] = o.Expectation } return json.Marshal(toSerialize) } type NullableAssertion struct { value *Assertion isSet bool } func (v NullableAssertion) Get() *Assertion { return v.value } func (v *NullableAssertion) Set(val *Assertion) { v.value = val v.isSet = true } func (v NullableAssertion) IsSet() bool { return v.isSet } func (v *NullableAssertion) Unset() { v.value = nil v.isSet = false } func NewNullableAssertion(val *Assertion) *NullableAssertion { return &NullableAssertion{value: val, isSet: true} } func (v NullableAssertion) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableAssertion) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
model_assertion.go
0.728169
0.469155
model_assertion.go
starcoder
package beautiful_array /* 对于某些固定的 N,如果数组 A 是整数 1, 2, ..., N 组成的排列,使得: 对于每个 i < j,都不存在 k 满足 i < k < j 使得 A[k] * 2 = A[i] + A[j]。 那么数组 A 是漂亮数组。 给定 N,返回任意漂亮数组 A(保证存在一个)。 示例 1: 输入:4 输出:[2,1,4,3] 示例 2: 输入:5 输出:[3,1,2,5,4] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/beautiful-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ /* 官方题解: 自顶向下递归 首先我们可以发现一个不错的性质,如果某个数组[a1,a2,⋯,an] 是漂亮的, 那么对这个数组进行仿射变换,得到的新数组[ka1+b,ka2+b,⋯,kan+b] 也是漂亮的(其中 k != 0)。 那么我们就有了一个想法:将数组分成两部分 left 和 right,分别求出一个漂亮的数组,然后将它们进行仿射变换,使得不存在满足下面条件的三元组: A[k] * 2 = A[i] + A[j], i < k < j; A[i] 来自 left 部分,A[j] 来自 right 部分。 可以发现,等式 A[k] * 2 = A[i] + A[j] 的左侧是一个偶数,右侧的两个元素分别来自两个部分。 要想等式恒不成立,一个简单的办法就是让 left 部分的数都是奇数,right 部分的数都是偶数。 因此我们将所有的奇数放在 left 部分,所有的偶数放在 right 部分,这样可以保证等式恒不成立。 对于 [1..N] 的排列,left 部分包括 (N + 1) / 2 个奇数,right 部分包括 N / 2 个偶数。 对于 left 部分,我们进行 k = 1/2, b = 1/2 的仿射变换,把这些奇数一一映射到不超过 (N + 1) / 2 的整数。 对于 right 部分,我们进行 k = 1/2, b = 0 的仿射变换,把这些偶数一一映射到不超过 N / 2 的整数。 经过映射,left 和 right 部分变成了和原问题一样,但规模减少一半的子问题,这样就可以使用分治算法解决了。 算法 在 [1..N] 中有 (N + 1) / 2 个奇数和 N / 2 个偶数。 我们将其分治成两个子问题,其中一个为不超过 (N + 1) / 2 的整数,并映射到所有的奇数;另一个为不超过 N / 2 的整数,并映射到所有的偶数。 作者:LeetCode 链接:https://leetcode-cn.com/problems/beautiful-array/solution/piao-liang-shu-zu-by-leetcode/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 */ func beautifulArray(N int) []int { if N < 1 { return nil } if N == 1 { return []int{1} } var r []int for _, v := range beautifulArray((N + 1) / 2) { // 奇数们 r = append(r, 2*v-1) } for _, v := range beautifulArray(N / 2) { // 偶数们 r = append(r, 2*v) } return r } /* 可用一个map储存计算结果,优化递归栈及时间 */ func beautifulArray2(N int) []int { if N < 1 { return nil } m := make(map[int][]int, 0) // 缓存中间计算结果,减少递归 var helper func(n int) []int helper = func(n int) []int { if n == 1 { return []int{1} } if v, ok := m[n]; ok { return v } var r []int for _, v := range helper((n + 1) / 2) { // 奇数们 r = append(r, 2*v-1) } for _, v := range helper(n / 2) { // 偶数们 r = append(r, 2*v) } m[n] = r return r } return helper(N) } /* 自底向上,循环 漂亮数组有以下性质: (1)A是一个漂亮数组,如果对A中所有元素添加一个常数,那么A还是一个漂亮数组。 (2)A是一个漂亮数组,如果对A中所有元素乘以一个常数,那么A还是一个漂亮数组。 (3)A是一个漂亮数组,如果删除一些A中元素,那么A还是一个漂亮数组。 (4) A是一个奇数构成的漂亮数组,B是一个偶数构成的漂亮数组,那么A+B也是一个漂亮数组 比如:{1,5,3,7}+{2,6,4,8}={1,5,3,7,2,6,4,8}也是一个漂亮数组。 所以我们假设一个{1,...,m}的数组是漂亮数组,可以通过下面的方式将其规模翻倍,构造漂亮数组{1,...,2m}: 对{1,...,m}中所有的数*2并-1,构成一个奇数漂亮数组A。如{1,3,2,4},变换为{1,5,3,7} 补齐偶数数组,如上面的{1,5,3,7}, 每个元素+1得到{2,6,4,8} A+B构成了漂亮数组{1,...,2m}。这个例子里:{1,5,3,7}+{2,6,4,8}={1,5,3,7,2,6,4,8} 因每次翻倍构造,会有些多余的元素(大于N),最后需要剔除这些元素 在N比较小时的构造结果如下: N == 1:{1}; N == 2:{1, 2}; N == 3:{1, 3, 2, 4} -> {1, 3, 2}; 元素4剔除 N == 4:{1, 5, 3, 2, 6, 4} -> {1, 3, 2, 4}; 5, 6被剔除 作者:zerorlis-2 链接:https://leetcode-cn.com/problems/beautiful-array/solution/piao-liang-shu-zu-de-yi-xie-xing-zhi-bing-qie-ji-y/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 */ func beautifulArray0(N int) []int { if N < 1 { return nil } r := []int{1} for len(r) < N { n := len(r) for i := 0; i < n; i++ { // 得到左侧奇数漂亮数组 r[i] = 2*r[i] - 1 } for i := 0; i < n; i++ { // 得到右侧偶数漂亮数组 r = append(r, r[i]+1) } } var result []int for _, v := range r { if v <= N { // 剔除多余, 只保留在N之内的元素 result = append(result, v) } } return result } // 可以精确控制上边实现里的r和result的大小 func beautifulArray1(N int) []int { if N < 1 { return nil } r := make([]int, 2*N-1) r[0] = 1 length := 1 for length < N { for i := 0; i < length; i++ { r[i] = 2*r[i] - 1 // 得到左侧奇数漂亮数组 r[i+length] = r[i] + 1 // 得到右侧偶数漂亮数组 } length *= 2 } if length == N { return r[:N] } result := make([]int, N) k := 0 for _, v := range r { if k == N { break } if v <= N { // 剔除多余, 只保留在N之内的元素 result[k] = v k++ } } return result }
solutions/beautiful-array/d.go
0.530236
0.523725
d.go
starcoder
package operator func calculateAddArray(array []float64, addarray []float64, numCPU int, channels []chan []float64) []float64 { addChannel := make([]float64, len(array)) for i := 0; i < numCPU; i++ { from := int(i * len(array) / numCPU) to := int((i + 1) * len(array) / numCPU) go addArrayRoutine(array[from:to], addarray[from:to], channels[i]) } for i := 0; i < numCPU; i++ { addChannel = append(addChannel, <- channels[i]...) } return addChannel } func calculateSum(array []float64, numCPU int, channels []chan float64) float64 { sumChannel := 0.0 for i := 0; i < numCPU; i++ { from := int(i * len(array) / numCPU) to := int((i + 1) * len(array) / numCPU) go sumRoutine(array[from:to], channels[i]) } for i := 0; i < numCPU; i++ { sumChannel += <- channels[i] } return sumChannel } func calculateScale(scale float64, array []float64, numCPU int, channels []chan []float64) []float64 { scaleChannel := make([]float64, len(array)) for i := 0; i < numCPU; i++ { from := int(i * len(array) / numCPU) to := int((i + 1) * len(array) / numCPU) go scaleRoutine(scale, array[from:to], channels[i]) } for i := 0; i < numCPU; i++ { scaleChannel = append(scaleChannel, <- channels[i]...) } return scaleChannel } func calculateMultiArray(array []float64, multiArray []float64, numCPU int, channels []chan float64) float64 { multiChannel := 0.0 for i := 0; i < numCPU; i++ { from := int(i * len(array) / numCPU) to := int((i + 1) * len(array) / numCPU) go multiArrayRoutine(array[from:to], multiArray[from:to], channels[i]) } for i := 0; i < numCPU; i++ { multiChannel += <- channels[i] } return multiChannel } func calculateTransform(array []float64, matrix [][]float64, numCPU int, channels []chan []float64) []float64 { scaleChannel := make([]float64, len(array)) for i := 0; i < numCPU; i++ { from := int(i * len(array) / numCPU) to := int((i + 1) * len(array) / numCPU) go matmulRoutine(array[from:to], matrix[from:to], channels[i]) } for i := 0; i < numCPU; i++ { scaleChannel = append(scaleChannel, <- channels[i]...) } return scaleChannel }
src/calculation/operator/calculate.go
0.504883
0.405743
calculate.go
starcoder
package Physics import ( "math" "fmt" ) type Vector struct{ X, Y, Z float64 } func (v *Vector) IsFilled() bool { if v.X != 0 || v.Y != 0 || v.Z != 0 { return true } return false } func (v *Vector) Rotate(axis *Vector, angle float64) *Vector { if axis == nil || !axis.IsFilled() { panic("Cannot Rotate Vector around Zero or nil Axis") } r := axis.X; s := axis.Y; t := axis.Z m := r * v.X + s * v.Y + t * v.Z xPrime := (float64)(r * m * (1 - math.Cos(angle)) + v.X * math.Cos(angle) + (-t * v.Y + s * v.Z) * math.Sin(angle)) yPrime := (float64)(s * m * (1 - math.Cos(angle)) + v.Y * math.Cos(angle) + ( t * v.X - r * v.Z) * math.Sin(angle)) zPrime := (float64)(t * m * (1 - math.Cos(angle)) + v.Z * math.Cos(angle) + (-s * v.X + r * v.Y) * math.Sin(angle)) v.X = xPrime;v.Y = yPrime;v.Z = zPrime return v } func (v *Vector) RotateAbs(axis *Vector, angle float64) *Vector { v.X=0;v.Y=0;v.Z=0 v.Rotate(axis, angle) return v } func (v *Vector) GetRotationXY() (angle float64) { angle = 0 if v.IsFilled() { if v.Y >= 0 { angle = math.Atan(v.X/v.Y)/(math.Pi)*180.0 }else{ angle = 180.0 - math.Atan(v.X/math.Abs(v.Y))/(math.Pi)*180.0 } if angle < 0 { angle += 360 } } return } func (v *Vector) DotProduct(B *Vector) (product float64) { if B == nil { panic("Cannot compute the DotProduct of a nil Vector") } product = 0 product += v.X * B.X product += v.Y * B.Y product += v.Z * B.Z return product } func (v *Vector) CrossProduct(B *Vector) *Vector { if B == nil { panic("Cannot compute the CrossProduct of a nil Vector") } cross_P := Vector{} cross_P.X=(v.Y * B.Z - v.Z * B.Y) cross_P.Y=(v.Z * B.X - v.X * B.Z) cross_P.Z=(v.X * B.Y - v.Y * B.X) return &cross_P } func (v *Vector) Add(B *Vector) *Vector { if B == nil { panic("Cannot add a nil Vector") } return &Vector{v.X+B.X, v.Y+B.Y, v.Z+B.Z} } func (v *Vector) Sub(B *Vector) *Vector { if B == nil { panic("Cannot subtract a nil Vector") } return &Vector{v.X-B.X, v.Y-B.Y, v.Z-B.Z} } func (v *Vector) Mul(num float64) *Vector { prod := Vector{} prod.X=(v.X * num) prod.Y=(v.Y * num) prod.Z=(v.Z * num) return &prod } func (v *Vector) Equals(B *Vector) bool { if B != nil { if v.X==B.X && v.Y==B.Y && v.Z==B.Z { return true } } return false } func (v *Vector) Absolute() float64 { if v.IsFilled() { return math.Sqrt(v.X*v.X+v.Y*v.Y+v.Z*v.Z) } return 0 } func (v *Vector) Normalize() *Vector { length := v.Absolute() if length != 0 { v.X=(v.X/length) v.Y=(v.Y/length) v.Z=(v.Z/length) }else { v.X=0;v.Y=0;v.Z=0 } return v.Copy() } func (v *Vector) Copy() *Vector { return &Vector{v.X,v.Y,v.Z} } func (v *Vector) GetInfos() string { return fmt.Sprintf("[%0.3f, %0.3f, %0.3f]", v.X, v.Y, v.Z) }
GoFiles/Utilities/Physics/vector.go
0.803829
0.51879
vector.go
starcoder
package ast //OperationType : A constant that defines the type of operation we're dealing with to allow information to be extracted by //converting the operation to the correct type. type OperationType int8 //StatementType : A constant that defines the type of statement we're dealing with to allow the compiler to generate the correct //code for the operation. type StatementType int8 const ( //VariableDeclaration : An operation that declares a variable. (Let) VariableDeclaration OperationType = iota //Return : An operation that returns a value (ie. returning from a function). Return //If : An operation that carries out a if/else operation. If //Match : An operation that carries out a match operation. Match //Assignment : An operation that changes the value of a property with an evaluated value. Assignment //Eval : An operation that evaluates and throw away the resulting value to use its side effect. //An example is a function call. Eval ) const ( //Equal : This statement compares if LHS is equal to RHS. Equal StatementType = iota //NotEqual : This statement compares if LHS is not equal to RHS. NotEqual //LesserThan : This statement compares if LHS is lesser than RHS. LesserThan //LesserEqualThan : This statement compares if LHS is lesser than or equal to RHS. LesserEqualThan //GreaterThan : This statement compares if LHS is greater than RHS. GreaterThan //GreaterEqualThan : This statement compares if LHS is greater than or equal to RHS. GreaterEqualThan //FunctionCall : This statement calls a function. Argument is stored in the format: [FunctionToCall, Arguments...] FunctionCall //Multiplication : This statement returns LHS multiplied by RHS. Multiplication //Division : This statement returns LHS divided by RHS. Division //Addition : This statement returns RHS added to LHS. Addition //Subtraction : This statement returns RHS subtracted from LHS. Subtraction //Modulus : This statement returns LHS mod RHS, keeping the sign. Modulus //Self : This is a statement without any arguments. It simply refers to oneself. Used in Impl declarations. Self //Literal : A statement that can be evaluated to a value. Literal //ArrayInitializer : A statement that initializes an array. ArrayInitializer //ObjectInitializer : A statement that initializes an object. ObjectInitializer //ArrayAccessor : A statement that accesses the value of an array. (array[i]) ArrayAccessor //PointerAccess : A statement that skips the dereferencing step and reads the struct value. (a->b) PointerAccess //Dereference : A statement that takes in a pointer and return the actual object. Dereference //Property : A statement that access a property of an object (like a field in a struct). Property //PropertyName : These are placeholders to show which fields to access. They'll evaluate to a value if the field exist. PropertyName //Type : A statement that tells ArrayInitializer and ObjectInitializer what type to initialize. Type none //A placeholder used in code to denote that the value is used as-is ) //NopFile : The parsed AST. It contains all info about a file. type NopFile struct { Source string CompilerPragma []string Import []string Structs []StructDecl Traits []TraitDecl Impls []ImplDecl Globals []VariableDecl Constants []VariableDecl //Globals but cannot be modified in runtime Functions []FunctionDecl } //StructDecl : A declaration of a struct. type StructDecl struct { Public bool Name string FieldNames []string FieldTypes []VariableType } //TraitDecl : A declaration of a trait. type TraitDecl struct { Name string Functions []FunctionDecl } //ImplDecl : A declaration of an implementation (impl). type ImplDecl struct { TraitName string TypeName VariableType Implementations []FunctionDecl } //VariableDecl : A declaration of variable (let). type VariableDecl struct { Targets []Variable DefaultValue Statement IsConstant bool } //Variable : A struct that holds information about a variable (that has been declared on is being assigned to). type Variable struct { Name string Type VariableType } //VariableType : A struct that holds information about a type. type VariableType struct { Name string ToInferType bool //Requests the compiler to infer Name and InnerType InnerType *VariableType //Outer<InnerType>. Pointer and Arrays go here too. Public bool Static bool Mutable bool } //FunctionDecl : A declaration of a function (fn). type FunctionDecl struct { Name string Parameters []FunctionParameter ReturnType VariableType Body []Operation } //FunctionParameter : A struct that holds the information about a specific function parameter. type FunctionParameter struct { Name string Type VariableType } //Operation : An operation that should be ran by a function. type Operation struct { Type OperationType Actual interface{} } //ReturnOperation : An operation that is used in a function to return. type ReturnOperation Statement //IfOperation : An operation that checks if the statement condition is true and run code conditionally. type IfOperation struct { Condition Statement IfBlock []Operation ElseBlock []Operation } //MatchOperation : An operation that chooses the first candidate to match with the list of candidates. type MatchOperation struct { Condition Statement Candidate []MatchCandidate } //MatchCandidate : A candidate to be matched by the MatchOperation. type MatchCandidate struct { Condition Statement RunBlock []Operation } //AssignmentOperation : An operation that assigns a value (result of statement) to a field or a variable. type AssignmentOperation struct { Target Statement Source Statement } //Statement : A struct containing anything that can be evaluated to a value. type Statement struct { Type StatementType ResolvedType VariableType LiteralValue interface{} Arguments []Statement }
src/ast/node.go
0.655446
0.634897
node.go
starcoder
package chainnode import ( sdk "github.com/hbtc-chain/bhchain/types" "github.com/stretchr/testify/mock" ) type MockChainnode struct { mock.Mock } var _ Chainnode = (*MockChainnode)(nil) func (m *MockChainnode) SupportChain(chain string) bool { args := m.Called(chain) return args.Bool(0) } func (m *MockChainnode) ValidAddress(chain, symbol, address string) (bool, string) { args := m.Called(chain, symbol, address) return args.Bool(0), args.String(1) } func (m *MockChainnode) ConvertAddress(chain string, publicKey []byte) (string, error) { return m.ConvertAddressFromSerializedPubKey(chain, publicKey) } func (m *MockChainnode) ConvertAddressFromSerializedPubKey(chain string, publicKey []byte) (string, error) { args := m.Called(chain, publicKey) return args.String(0), args.Error(1) } func (m *MockChainnode) QueryBalance(chain, symbol string, address, contractAddress string, blockHeight uint64) (sdk.Int, error) { args := m.Called(chain, symbol, address, contractAddress, blockHeight) return args.Get(0).(sdk.Int), args.Error(1) } func (m *MockChainnode) QueryUtxo(chain, symbol string, vin *sdk.UtxoIn) (bool, error) { args := m.Called(chain, symbol, vin) return args.Bool(0), args.Error(1) } func (m *MockChainnode) QueryNonce(chain, address string) (uint64, error) { args := m.Called(chain, address) return args.Get(0).(uint64), args.Error(1) } func (m *MockChainnode) QueryGasPrice(chain string) (sdk.Int, error) { args := m.Called(chain) return args.Get(0).(sdk.Int), args.Error(1) } func (m *MockChainnode) QueryUtxoTransaction(chain, symbol, hash string, asynMode bool) (*ExtUtxoTransaction, error) { args := m.Called(chain, symbol, hash, asynMode) return args.Get(0).(*ExtUtxoTransaction), args.Error(1) } func (m *MockChainnode) QueryAccountTransaction(chain, symbol, hash string, asynMode bool) (*ExtAccountTransaction, error) { args := m.Called(chain, symbol, hash, asynMode) return args.Get(0).(*ExtAccountTransaction), args.Error(1) } func (m *MockChainnode) CreateUtxoTransaction(chain, symbol string, transaction *ExtUtxoTransaction) ([]byte, [][]byte, error) { args := m.Called(chain, symbol, transaction) return args.Get(0).([]byte), args.Get(1).([][]byte), args.Error(2) } func (m *MockChainnode) CreateAccountTransaction(chain, symbol, contractAddress string, transaction *ExtAccountTransaction) ( []byte, []byte, error) { args := m.Called(chain, symbol, contractAddress, transaction) return args.Get(0).([]byte), args.Get(1).([]byte), args.Error(2) } func (m *MockChainnode) CreateUtxoSignedTransaction(chain, symbol string, raw []byte, signatures, pubKeys [][]byte) ([]byte, []byte, error) { panic("not implemented") } func (m *MockChainnode) CreateAccountSignedTransaction(chain, symbol string, raw []byte, signatures, pubKeys []byte) ([]byte, []byte, error) { args := m.Called(chain, symbol, raw, signatures, pubKeys) return args.Get(0).([]byte), args.Get(1).([]byte), args.Error(2) } func (m *MockChainnode) VerifyUtxoSignedTransaction(chain, symbol string, address []string, signedTxData []byte, vins []*sdk.UtxoIn) (bool, error) { args := m.Called(chain, symbol, address, signedTxData, vins) return args.Get(0).(bool), args.Error(1) } func (m *MockChainnode) VerifyAccountSignedTransaction(chain, symbol, address string, signedTxData []byte) (bool, error) { args := m.Called(chain, symbol, address, signedTxData) return args.Get(0).(bool), args.Error(1) } func (m *MockChainnode) QueryAccountTransactionFromSignedData(chain, symbol string, signedTxData []byte) (*ExtAccountTransaction, error) { args := m.Called(chain, symbol, signedTxData) return args.Get(0).(*ExtAccountTransaction), args.Error(1) } func (m *MockChainnode) QueryUtxoTransactionFromSignedData(chain, symbol string, signedTxData []byte, vins []*sdk.UtxoIn) (*ExtUtxoTransaction, error) { args := m.Called(chain, symbol, signedTxData, vins) return args.Get(0).(*ExtUtxoTransaction), args.Error(1) } func (m *MockChainnode) QueryAccountTransactionFromData(chain, symbol string, rawData []byte) (*ExtAccountTransaction, []byte, error) { args := m.Called(chain, symbol, rawData) return args.Get(0).(*ExtAccountTransaction), args.Get(1).([]byte), args.Error(2) } func (m *MockChainnode) QueryUtxoTransactionFromData(chain, symbol string, rawData []byte, vins []*sdk.UtxoIn) (*ExtUtxoTransaction, [][]byte, error) { args := m.Called(chain, symbol, rawData, vins) return args.Get(0).(*ExtUtxoTransaction), args.Get(1).([][]byte), args.Error(2) } func (m *MockChainnode) BroadcastTransaction(chain, symbol string, signedTxData []byte) (string, error) { args := m.Called(symbol, signedTxData) return args.Get(0).(string), args.Error(1) } func (m *MockChainnode) QueryUtxoInsFromData(chain, symbol string, data []byte) ([]*sdk.UtxoIn, error) { args := m.Called(chain, symbol, data) return args.Get(0).([]*sdk.UtxoIn), args.Error(1) }
chainnode/mock.go
0.753557
0.439807
mock.go
starcoder
package iter import "unicode/utf8" // Iterator[T] represents an iterator yielding elements of type T. type Iterator[T any] interface { // Next yields a new value from the Iterator. Next() Option[T] } type stringIter struct { input string } // String returns an Iterator yielding runes from the supplied string. func String(input string) Iterator[rune] { return &stringIter{ input: input, } } func (it *stringIter) Next() Option[rune] { if len(it.input) == 0 { return None[rune]() } value, width := utf8.DecodeRuneInString(it.input) it.input = it.input[width:] return Some(value) } type rangeIter struct { start, stop, step, i int } // Range returns an Iterator over a range of integers. func Range(start, stop, step int) Iterator[int] { return &rangeIter{ start: start, stop: stop, step: step, i: 0, } } func (it *rangeIter) Next() Option[int] { v := it.start + it.step*it.i if it.step > 0 { if v >= it.stop { return None[int]() } } else { if v <= it.stop { return None[int]() } } it.i++ return Some(v) } type sliceIter[T any] struct { slice []T } // Slice returns an Iterator that yields elements from a slice. func Slice[T any](slice []T) Iterator[T] { return &sliceIter[T]{ slice: slice, } } func (it *sliceIter[T]) Next() Option[T] { if len(it.slice) == 0 { return None[T]() } first := it.slice[0] it.slice = it.slice[1:] return Some[T](first) } // ToSlice consumes an Iterator creating a slice from the yielded values. func ToSlice[T any](it Iterator[T]) []T { result := []T{} ForEach(it, func(v T) { result = append(result, v) }) return result } // ToString consumes a rune Iterator creating a string. func ToString(it Iterator[rune]) string { return string(ToSlice(it)) } type mapIter[T, R any] struct { inner Iterator[T] fn func(T) R } // Map is an Iterator adapter that transforms each value yielded by the // underlying iterator using fn. func Map[T, R any](it Iterator[T], fn func(T) R) Iterator[R] { return &mapIter[T, R]{ inner: it, fn: fn, } } func (it *mapIter[T, R]) Next() Option[R] { return MapOption(it.inner.Next(), it.fn) } type filterIter[T any] struct { inner Iterator[T] pred func(T) bool } // Filter returns an Iterator adapter that yields elements from the underlying // Iterator for which pred returns true. func Filter[T any](it Iterator[T], pred func(T) bool) Iterator[T] { return &filterIter[T]{ inner: it, pred: pred, } } func (it *filterIter[T]) Next() Option[T] { v := it.inner.Next() for v.IsSome() { if it.pred(v.Unwrap()) { break } v = it.inner.Next() } return v } type takeIter[T any] struct { inner Iterator[T] take uint } // Take returns an Iterator adapter that yields the n first elements from the // underlying Iterator. func Take[T any](it Iterator[T], n uint) Iterator[T] { return &takeIter[T]{ inner: it, take: n, } } func (it *takeIter[T]) Next() Option[T] { if it.take == 0 { return None[T]() } v := it.inner.Next() if v.IsSome() { it.take-- } return v } type takeWhileIter[T any] struct { inner Iterator[T] pred func(T) bool done bool } // TakeWhile returns an Iterator adapter that yields values from the underlying // Iterator as long as pred predicate function returns true. func TakeWhile[T any](it Iterator[T], pred func(T) bool) Iterator[T] { return &takeWhileIter[T]{ inner: it, pred: pred, done: false, } } func (it *takeWhileIter[T]) Next() Option[T] { if it.done { return None[T]() } v := it.inner.Next() if v.IsNone() { it.done = true return v } if !it.pred(v.Unwrap()) { it.done = true return None[T]() } return v } type dropIter[T any] struct { inner Iterator[T] drop uint } // Drop returns an Iterator adapter that drops the first n elements from the // underlying Iterator before yielding any values. func Drop[T any](it Iterator[T], n uint) Iterator[T] { return &dropIter[T]{ inner: it, drop: n, } } func (it *dropIter[T]) Next() Option[T] { v := None[T]() for it.drop > 0 { v = it.inner.Next() if v.IsNone() { it.drop = 0 return v } it.drop-- } return it.inner.Next() } type dropWhileIter[T any] struct { inner Iterator[T] pred func(T) bool done bool } // DropWhile returns an Iterator adapter that drops elements from the underlying // Iterator until pred predicate function returns true. func DropWhile[T any](it Iterator[T], pred func(T) bool) Iterator[T] { return &dropWhileIter[T]{ inner: it, pred: pred, done: false, } } func (it *dropWhileIter[T]) Next() Option[T] { if !it.done { for { v := it.inner.Next() if v.IsNone() { it.done = true return v } if !it.pred(v.Unwrap()) { it.done = true return v } } } return it.inner.Next() } type repeatIter[T any] struct { value T } // Repeat returns an Iterator that repeatedly returns the same value. func Repeat[T any](value T) Iterator[T] { return &repeatIter[T]{ value: value, } } func (it *repeatIter[T]) Next() Option[T] { return Some(it.value) } // Count consumes an Iterator and returns the number of elements it yielded. func Count[T any](it Iterator[T]) uint { var length uint v := it.Next() for v.IsSome() { length++ v = it.Next() } return length } type funcIter[T any] struct { fn func() Option[T] } // Func returns an Iterator from a function. func Func[T any](fn func() Option[T]) Iterator[T] { return &funcIter[T]{ fn: fn, } } func (it *funcIter[T]) Next() Option[T] { return it.fn() } type emptyIter[T any] struct{} // Empty returns an empty Iterator. func Empty[T any]() Iterator[T] { return &emptyIter[T]{} } func (it *emptyIter[T]) Next() Option[T] { return None[T]() } type onceIter[T any] struct { value Option[T] } // Once returns an Iterator that returns a value exactly once. func Once[T any](value T) Iterator[T] { return &onceIter[T]{ value: Some(value), } } func (it *onceIter[T]) Next() Option[T] { v := it.value it.value = None[T]() return v } // ForEach consumes the Iterator applying fn to each yielded value. func ForEach[T any](it Iterator[T], fn func(T)) { v := it.Next() for v.IsSome() { fn(v.Unwrap()) v = it.Next() } } // Fold reduces Iterator using function fn. func Fold[T any, B any](it Iterator[T], init B, fn func(B, T) B) B { ret := init ForEach(it, func(v T) { ret = fn(ret, v) }) return ret } type fuseIter[T any] struct { inner Iterator[T] done bool } // Fuse returns an Iterator adapter that will keep yielding None after the // underlying Iterator has yielded None once. func Fuse[T any](it Iterator[T]) Iterator[T] { return &fuseIter[T]{ inner: it, done: false, } } func (it *fuseIter[T]) Next() Option[T] { if it.done { return None[T]() } v := it.inner.Next() if v.IsNone() { it.done = true } return v } type chainIter[T any] struct { first Iterator[T] second Iterator[T] } // Chain returns an Iterator that concatenates two iterators. func Chain[T any](first Iterator[T], second Iterator[T]) Iterator[T] { return &chainIter[T]{ first: Fuse(first), second: second, } } func (it *chainIter[T]) Next() Option[T] { v := it.first.Next() if v.IsSome() { return v } return it.second.Next() } // Find the first element from Iterator that satisfies pred predicate function. func Find[T any](it Iterator[T], pred func(T) bool) Option[T] { return Filter(it, pred).Next() } type flattenIter[T any] struct { inner Iterator[Iterator[T]] current Iterator[T] done bool } // Flatten returns an Iterator adapter that flattens nested iterators. func Flatten[T any](it Iterator[Iterator[T]]) Iterator[T] { return &flattenIter[T]{ inner: it, current: Empty[T](), done: false, } } func (it *flattenIter[T]) Next() Option[T] { for { if it.done { return None[T]() } v := it.current.Next() if v.IsSome() { return v } next := it.inner.Next() if next.IsNone() { it.done = true return None[T]() } it.current = next.Unwrap() } } // All tests if every element of the Iterator matches a predicate. An empty // Iterator returns true. func All[T any](it Iterator[T], pred func(T) bool) bool { v := it.Next() for v.IsSome() { if !pred(v.Unwrap()) { return false } v = it.Next() } return true } // Any tests if any element of the Iterator matches a predicate. An empty // Iterator returns false. func Any[T any](it Iterator[T], pred func(T) bool) bool { v := it.Next() for v.IsSome() { if pred(v.Unwrap()) { return true } v = it.Next() } return false } // Nth returns nth element of the Iterator. func Nth[T any](it Iterator[T], n uint) Option[T] { v := it.Next() for n > 0 { if v.IsNone() { break } v = it.Next() n-- } return v } // Determines if the elements of two Iterators are equal. func Equal[T comparable](first Iterator[T], second Iterator[T]) bool { return EqualBy( first, second, func(a T, b T) bool { return a == b }, ) } // Determines if the elements of two Iterators are equal using function cmp to // compare elements. func EqualBy[T any](first Iterator[T], second Iterator[T], cmp func(T, T) bool) bool { for { v := first.Next() if v.IsNone() { return second.Next().IsNone() } u := second.Next() if u.IsNone() { return false } if !cmp(v.Unwrap(), u.Unwrap()) { return false } } }
iterator.go
0.82308
0.444505
iterator.go
starcoder
package ytbx import ( "fmt" yaml "gopkg.in/yaml.v2" ) // Grab get the value from the provided YAML tree using a path to traverse through the tree structure func Grab(obj interface{}, pathString string) (interface{}, error) { path, err := ParsePathString(pathString, obj) if err != nil { return nil, err } pointer := obj pointerPath := Path{DocumentIdx: path.DocumentIdx} for _, element := range path.PathElements { switch { // Key/Value Map, where the element name is the key for the map case len(element.Key) == 0 && len(element.Name) > 0: if !isMapSlice(pointer) { return nil, fmt.Errorf("failed to traverse tree, expected a %s but found type %s at %s", typeMap, GetType(pointer), pointerPath.ToGoPatchStyle()) } entry, err := getValueByKey(pointer.(yaml.MapSlice), element.Name) if err != nil { return nil, err } pointer = entry // Complex List, where each list entry is a Key/Value map and the entry is identified by name using an indentifier (e.g. name, key, or id) case len(element.Key) > 0 && len(element.Name) > 0: complexList, ok := castAsComplexList(pointer) if !ok { return nil, fmt.Errorf("failed to traverse tree, expected a %s but found type %s at %s", typeComplexList, GetType(pointer), pointerPath.ToGoPatchStyle()) } entry, err := getEntryByIdentifierAndName(complexList, element.Key, element.Name) if err != nil { return nil, err } pointer = entry // Simple List (identified by index) case len(element.Key) == 0 && len(element.Name) == 0: if !isList(pointer) { return nil, fmt.Errorf("failed to traverse tree, expected a %s but found type %s at %s", typeSimpleList, GetType(pointer), pointerPath.ToGoPatchStyle()) } list := pointer.([]interface{}) if element.Idx < 0 || element.Idx >= len(list) { return nil, fmt.Errorf("failed to traverse tree, provided %s index %d is not in range: 0..%d", typeSimpleList, element.Idx, len(list)-1) } pointer = list[element.Idx] default: return nil, fmt.Errorf("failed to traverse tree, the provided path %s seems to be invalid", path) } // Update the path that the current pointer has (only used in error case to point to the right position) pointerPath.PathElements = append(pointerPath.PathElements, element) } return pointer, nil }
vendor/github.com/homeport/ytbx/pkg/v1/ytbx/getting.go
0.697403
0.472501
getting.go
starcoder
package geom // A Point represents a single point. type Point struct { geom0 } // NewPoint allocates a new Point with layout l and all values zero. func NewPoint(l Layout) *Point { return NewPointFlat(l, make([]float64, l.Stride())) } // NewPointFlat allocates a new Point with layout l and flat coordinates flatCoords. func NewPointFlat(l Layout, flatCoords []float64) *Point { p := new(Point) p.layout = l p.stride = l.Stride() p.flatCoords = flatCoords return p } // Area returns p's area, i.e. zero. func (p *Point) Area() float64 { return 0 } // Clone returns a copy of p that does not alias p. func (p *Point) Clone() *Point { flatCoords := make([]float64, len(p.flatCoords)) copy(flatCoords, p.flatCoords) return NewPointFlat(p.layout, flatCoords) } // Empty returns true if p contains no geometries, i.e. it returns false. func (p *Point) Empty() bool { return false } // Length returns the length of p, i.e. zero. func (p *Point) Length() float64 { return 0 } // MustSetCoords is like SetCoords but panics on any error. func (p *Point) MustSetCoords(coords Coord) *Point { Must(p.SetCoords(coords)) return p } // SetCoords sets the coordinates of p. func (p *Point) SetCoords(coords Coord) (*Point, error) { if err := p.setCoords(coords); err != nil { return nil, err } return p, nil } // SetSRID sets the SRID of p. func (p *Point) SetSRID(srid int) *Point { p.srid = srid return p } // Swap swaps the values of p and p2. func (p *Point) Swap(p2 *Point) { p.geom0.swap(&p2.geom0) } // X returns p's X-coordinate. func (p *Point) X() float64 { return p.flatCoords[0] } // Y returns p's Y-coordinate. func (p *Point) Y() float64 { return p.flatCoords[1] } // Z returns p's Z-coordinate, or zero if p has no Z-coordinate. func (p *Point) Z() float64 { zIndex := p.layout.ZIndex() if zIndex == -1 { return 0 } return p.flatCoords[zIndex] } // M returns p's M-coordinate, or zero if p has no M-coordinate. func (p *Point) M() float64 { mIndex := p.layout.MIndex() if mIndex == -1 { return 0 } return p.flatCoords[mIndex] }
vendor/github.com/twpayne/go-geom/point.go
0.915696
0.680608
point.go
starcoder
package slices import ( "reflect" "github.com/fatih/structs" "github.com/pkg/errors" ) var ( // ErrNotSlice happens when the value passed is not a slice. ErrNotSlice = errors.New("not slice") // ErrNotString happens when the value of the field is not a string. ErrNotString = errors.New("not string") // ErrNotInt happens when the value of the field is not an int. ErrNotInt = errors.New("not int") // ErrNotFloat happens when the value of the field is not a float64. ErrNotFloat = errors.New("not float64") // ErrNotBool happens when the value of the field is not a bool. ErrNotBool = errors.New("not bool") ) // IndexOf returns the first index at which a given element can be found in the slice, or -1 if it is not present. // The second argument must be a slice or array. func IndexOf(val any, slice any) int { v := reflect.ValueOf(val) arr := reflect.ValueOf(slice) t := reflect.TypeOf(slice).Kind() if t != reflect.Slice && t != reflect.Array { panic("Type Error! Second argument must be an array or a slice.") } for i := 0; i < arr.Len(); i++ { if arr.Index(i).Interface() == v.Interface() { return i } } return -1 } // ToStrings maps a field to a slice of string. func ToStrings(slice any, fieldName string) (s []string, err error) { switch reflect.TypeOf(slice).Kind() { case reflect.Slice: val := reflect.ValueOf(slice) for i := 0; i < val.Len(); i++ { fields := structs.Fields(val.Index(i).Interface()) for _, f := range fields { if f.IsExported() && f.Name() == fieldName { e := f.Value() switch e.(type) { case string: s = append(s, e.(string)) default: return nil, ErrNotString } } } } default: return nil, ErrNotSlice } return } // ToInts maps a field to a slice of int. func ToInts(slice any, fieldName string) (s []int, err error) { switch reflect.TypeOf(slice).Kind() { case reflect.Slice: val := reflect.ValueOf(slice) for i := 0; i < val.Len(); i++ { fields := structs.Fields(val.Index(i).Interface()) for _, f := range fields { if f.IsExported() && f.Name() == fieldName { e := f.Value() switch e.(type) { case int: s = append(s, e.(int)) default: return nil, ErrNotInt } } } } default: return nil, ErrNotSlice } return } // ToFloats maps a field to a slice of int. func ToFloats(slice any, fieldName string) (s []float64, err error) { switch reflect.TypeOf(slice).Kind() { case reflect.Slice: val := reflect.ValueOf(slice) for i := 0; i < val.Len(); i++ { fields := structs.Fields(val.Index(i).Interface()) for _, f := range fields { if f.IsExported() && f.Name() == fieldName { e := f.Value() switch e.(type) { case float64: s = append(s, e.(float64)) default: return nil, ErrNotFloat } } } } default: return nil, ErrNotSlice } return } // ToBools maps a field to a slice of bool. func ToBools(slice any, fieldName string) (s []bool, err error) { switch reflect.TypeOf(slice).Kind() { case reflect.Slice: val := reflect.ValueOf(slice) for i := 0; i < val.Len(); i++ { fields := structs.Fields(val.Index(i).Interface()) for _, f := range fields { if f.IsExported() && f.Name() == fieldName { e := f.Value() switch e.(type) { case bool: s = append(s, e.(bool)) default: return nil, ErrNotBool } } } } default: return nil, ErrNotSlice } return } // ToStringsUnsafe maps a field to a slice of string but not returns an error. // If an error still happens, s will be nil. func ToStringsUnsafe(slice any, fieldName string) []string { s, _ := ToStrings(slice, fieldName) return s } // ToIntsUnsafe maps a field to a slice of int but not returns an error. // If an error still happens, s will be nil. func ToIntsUnsafe(slice any, fieldName string) []int { s, _ := ToInts(slice, fieldName) return s } // ToFloatsUnsafe maps a field to a slice of float but not returns an error. // If an error still happens, s will be nil. func ToFloatsUnsafe(slice any, fieldName string) []float64 { s, _ := ToFloats(slice, fieldName) return s } // ToBoolsUnsafe maps a field to a slice of bool but not returns an error. // If an error still happens, s will be nil. func ToBoolsUnsafe(slice any, fieldName string) []bool { s, _ := ToBools(slice, fieldName) return s } // MaxInt max int of the slice func MaxInt(slice []int) int { var max int for _, v := range slice { if v > max { max = v } } return max } // MaxFloat max float of the slice func MaxFloat(slice []float64) float64 { var max float64 for _, v := range slice { if v > max { max = v } } return max } // MinInt min int of the slice func MinInt(slice []int) int { if len(slice) == 0 { return 0 } min := 9223372036854775807 for _, v := range slice { if v < min { min = v } } return min } // MinFloat min float of the slice func MinFloat(slice []float64) float64 { if len(slice) == 0 { return 0 } var min float64 = 9223372036854775807 for _, v := range slice { if v < min { min = v } } return min } func SumInt(slice []int) int { sum := 0 for _, v := range slice { sum += v } return sum } func SumFloat(slice []float64) float64 { sum := 0.0 for _, v := range slice { sum += v } return sum }
slices/slices.go
0.733738
0.400339
slices.go
starcoder
package types import ( "bytes" "errors" "math" "strconv" "time" pb "github.com/go-graphite/carbonzipper/carbonzipperpb3" pickle "github.com/lomik/og-rek" ) var ( // ErrWildcardNotAllowed is an eval error returned when a wildcard/glob argument is found where a single series is required. ErrWildcardNotAllowed = errors.New("found wildcard where series expected") // ErrTooManyArguments is an eval error returned when too many arguments are provided. ErrTooManyArguments = errors.New("too many arguments") ) // MetricData contains necessary data to represent parsed metric (ready to be send out or drawn) type MetricData struct { pb.FetchResponse GraphOptions ValuesPerPoint int aggregatedValues []float64 aggregatedAbsent []bool AggregateFunction func([]float64, []bool) (float64, bool) } // MakeMetricData creates new metrics data with given metric timeseries func MakeMetricData(name string, values []float64, step, start int32) *MetricData { absent := make([]bool, len(values)) for i, v := range values { if math.IsNaN(v) { values[i] = 0 absent[i] = true } } stop := start + int32(len(values))*step return &MetricData{FetchResponse: pb.FetchResponse{ Name: name, Values: values, StartTime: start, StepTime: step, StopTime: stop, IsAbsent: absent, }} } // MarshalCSV marshals metric data to CSV func MarshalCSV(results []*MetricData) []byte { var b []byte for _, r := range results { step := r.StepTime t := r.StartTime for i, v := range r.Values { b = append(b, '"') b = append(b, r.Name...) b = append(b, '"') b = append(b, ',') b = append(b, time.Unix(int64(t), 0).Format("2006-01-02 15:04:05")...) b = append(b, ',') if !r.IsAbsent[i] { b = strconv.AppendFloat(b, v, 'f', -1, 64) } b = append(b, '\n') t += step } } return b } // ConsolidateJSON consolidates values to maxDataPoints size func ConsolidateJSON(maxDataPoints int, results []*MetricData) { var startTime int32 = -1 var endTime int32 = -1 for _, r := range results { t := r.StartTime if startTime == -1 || startTime > t { startTime = t } t = r.StopTime if endTime == -1 || endTime < t { endTime = t } } timeRange := endTime - startTime if timeRange <= 0 { return } for _, r := range results { numberOfDataPoints := math.Floor(float64(timeRange / r.StepTime)) if numberOfDataPoints > float64(maxDataPoints) { valuesPerPoint := math.Ceil(numberOfDataPoints / float64(maxDataPoints)) r.SetValuesPerPoint(int(valuesPerPoint)) } } } // MarshalJSON marshals metric data to JSON func MarshalJSON(results []*MetricData) []byte { var b []byte b = append(b, '[') var topComma bool for _, r := range results { if r == nil { continue } if topComma { b = append(b, ',') } topComma = true b = append(b, `{"target":`...) b = strconv.AppendQuoteToASCII(b, r.Name) b = append(b, `,"datapoints":[`...) var innerComma bool t := r.StartTime absent := r.AggregatedAbsent() for i, v := range r.AggregatedValues() { if innerComma { b = append(b, ',') } innerComma = true b = append(b, '[') if absent[i] || math.IsInf(v, 0) || math.IsNaN(v) { b = append(b, "null"...) } else { b = strconv.AppendFloat(b, v, 'f', -1, 64) } b = append(b, ',') b = strconv.AppendInt(b, int64(t), 10) b = append(b, ']') t += r.AggregatedTimeStep() } b = append(b, `]}`...) } b = append(b, ']') return b } // MarshalPickle marshals metric data to pickle format func MarshalPickle(results []*MetricData) []byte { var p []map[string]interface{} for _, r := range results { values := make([]interface{}, len(r.Values)) for i, v := range r.Values { if r.IsAbsent[i] { values[i] = pickle.None{} } else { values[i] = v } } p = append(p, map[string]interface{}{ "name": r.Name, "start": r.StartTime, "end": r.StopTime, "step": r.StepTime, "values": values, }) } var buf bytes.Buffer penc := pickle.NewEncoder(&buf) penc.Encode(p) return buf.Bytes() } // MarshalProtobuf marshals metric data to protobuf func MarshalProtobuf(results []*MetricData) ([]byte, error) { response := pb.MultiFetchResponse{} for _, metric := range results { response.Metrics = append(response.Metrics, (*metric).FetchResponse) } b, err := response.Marshal() if err != nil { return nil, err } return b, nil } // MarshalRaw marshals metric data to graphite's internal format, called 'raw' func MarshalRaw(results []*MetricData) []byte { var b []byte for _, r := range results { b = append(b, r.Name...) b = append(b, ',') b = strconv.AppendInt(b, int64(r.StartTime), 10) b = append(b, ',') b = strconv.AppendInt(b, int64(r.StopTime), 10) b = append(b, ',') b = strconv.AppendInt(b, int64(r.StepTime), 10) b = append(b, '|') var comma bool for i, v := range r.Values { if comma { b = append(b, ',') } comma = true if r.IsAbsent[i] { b = append(b, "None"...) } else { b = strconv.AppendFloat(b, v, 'f', -1, 64) } } b = append(b, '\n') } return b } // SetValuesPerPoint sets value per point coefficient. func (r *MetricData) SetValuesPerPoint(v int) { r.ValuesPerPoint = v r.aggregatedValues = nil r.aggregatedAbsent = nil } // AggregatedTimeStep aggregates time step func (r *MetricData) AggregatedTimeStep() int32 { if r.ValuesPerPoint == 1 || r.ValuesPerPoint == 0 { return r.StepTime } return r.StepTime * int32(r.ValuesPerPoint) } // AggregatedValues aggregates values (with cache) func (r *MetricData) AggregatedValues() []float64 { if r.aggregatedValues == nil { r.AggregateValues() } return r.aggregatedValues } // AggregatedAbsent aggregates absent values func (r *MetricData) AggregatedAbsent() []bool { if r.aggregatedAbsent == nil { r.AggregateValues() } return r.aggregatedAbsent } // AggregateValues aggregates values func (r *MetricData) AggregateValues() { if r.ValuesPerPoint == 1 || r.ValuesPerPoint == 0 { r.aggregatedValues = make([]float64, len(r.Values)) r.aggregatedAbsent = make([]bool, len(r.Values)) copy(r.aggregatedValues, r.Values) copy(r.aggregatedAbsent, r.IsAbsent) return } if r.AggregateFunction == nil { r.AggregateFunction = AggMean } n := len(r.Values)/r.ValuesPerPoint + 1 aggV := make([]float64, 0, n) aggA := make([]bool, 0, n) v := r.Values absent := r.IsAbsent for len(v) >= r.ValuesPerPoint { val, abs := r.AggregateFunction(v[:r.ValuesPerPoint], absent[:r.ValuesPerPoint]) aggV = append(aggV, val) aggA = append(aggA, abs) v = v[r.ValuesPerPoint:] absent = absent[r.ValuesPerPoint:] } if len(v) > 0 { val, abs := r.AggregateFunction(v, absent) aggV = append(aggV, val) aggA = append(aggA, abs) } r.aggregatedValues = aggV r.aggregatedAbsent = aggA } // AggMean computes mean (sum(v)/len(v), excluding NaN points) of values func AggMean(v []float64, absent []bool) (float64, bool) { var sum float64 var n int for i, vv := range v { if !math.IsNaN(vv) && !absent[i] { sum += vv n++ } } return sum / float64(n), n == 0 } // AggMax computes max of values func AggMax(v []float64, absent []bool) (float64, bool) { var m = math.Inf(-1) var abs = true for i, vv := range v { if !absent[i] && !math.IsNaN(vv) { abs = false if m < vv { m = vv } } } return m, abs } // AggMin computes min of values func AggMin(v []float64, absent []bool) (float64, bool) { var m = math.Inf(1) var abs = true for i, vv := range v { if !absent[i] && !math.IsNaN(vv) { abs = false if m > vv { m = vv } } } return m, abs } // AggSum computes sum of values func AggSum(v []float64, absent []bool) (float64, bool) { var sum float64 var abs = true for i, vv := range v { if !math.IsNaN(vv) && !absent[i] { sum += vv abs = false } } return sum, abs } // AggFirst returns first point func AggFirst(v []float64, absent []bool) (float64, bool) { var m = math.Inf(-1) var abs = true if len(v) > 0 { return v[0], absent[0] } return m, abs } // AggLast returns last point func AggLast(v []float64, absent []bool) (float64, bool) { var m = math.Inf(-1) var abs = true if len(v) > 0 { return v[len(v)-1], absent[len(v)-1] } return m, abs }
expr/types/types.go
0.686895
0.431524
types.go
starcoder
package series import ( "fmt" "math" "strconv" ) type floatListElement struct { e []float64 nan bool } // force floatListElement struct to implement Element interface var _ Element = (*floatListElement)(nil) func (e *floatListElement) Set(value interface{}) { e.nan = false switch val := value.(type) { case string: if val == "NaN" { e.nan = true return } f, err := strconv.ParseFloat(val, 64) if err != nil { e.nan = true return } e.e = make([]float64, 1) e.e[0] = f case int: e.e = make([]float64, 1) e.e[0] = float64(val) case int32: e.e = make([]float64, 1) e.e[0] = float64(val) case int64: e.e = make([]float64, 1) e.e[0] = float64(val) case float32: e.e = make([]float64, 1) e.e[0] = float64(val) case float64: e.e = make([]float64, 1) e.e[0] = float64(val) case bool: e.e = make([]float64, 1) b := val if b { e.e[0] = 1 } else { e.e[0] = 0 } case []string: if val == nil { e.nan = true return } l := len(val) e.e = make([]float64, l) for i := 0; i < l; i++ { if val[i] == "NaN" { e.nan = true return } f, err := strconv.ParseFloat(val[i], 64) if err != nil { e.nan = true return } e.e[i] = f } case []int: if val == nil { e.nan = true return } l := len(val) e.e = make([]float64, l) for i := 0; i < l; i++ { e.e[i] = float64(val[i]) } case []int32: if val == nil { e.nan = true return } l := len(val) e.e = make([]float64, l) for i := 0; i < l; i++ { e.e[i] = float64(val[i]) } case []int64: if val == nil { e.nan = true return } l := len(val) e.e = make([]float64, l) for i := 0; i < l; i++ { e.e[i] = float64(val[i]) } case []float32: if val == nil { e.nan = true return } l := len(val) e.e = make([]float64, l) for i := 0; i < l; i++ { e.e[i] = float64(val[i]) } case []float64: if val == nil { e.nan = true return } l := len(val) e.e = make([]float64, l) for i := 0; i < l; i++ { e.e[i] = float64(val[i]) } case []bool: if val == nil { e.nan = true return } l := len(val) e.e = make([]float64, l) for i := 0; i < l; i++ { b := val[i] if b { e.e[i] = 1 } else { e.e[i] = 0 } } case Element: e.e = val.FloatList() default: e.nan = true return } } func (e floatListElement) Copy() Element { if e.IsNA() { return &floatListElement{[]float64{}, true} } return &floatListElement{e.e, false} } func (e floatListElement) IsNA() bool { return e.nan } func (e floatListElement) Type() Type { return FloatList } func (e floatListElement) Val() ElementValue { if e.IsNA() { return nil } return e.e } func (e floatListElement) String() string { if e.IsNA() { return "[NaN]" } return fmt.Sprintf("%f", e.e) } func (e floatListElement) Int() (int, error) { if e.IsNA() { return 0, fmt.Errorf("can't convert NaN to int") } return 0, fmt.Errorf("can't convert []float64 to int") } func (e floatListElement) Float() float64 { if e.IsNA() { return math.NaN() } return 0 } func (e floatListElement) Bool() (bool, error) { if e.IsNA() { return false, fmt.Errorf("can't convert NaN to bool") } return false, fmt.Errorf("can't convert []float64 to bool") } func (e floatListElement) StringList() []string { if e.IsNA() { return []string{"NaN"} } l := make([]string, len(e.e)) for i := 0; i < len(e.e); i++ { l[i] = fmt.Sprintf("%f", e.e[i]) } return l } func (e floatListElement) IntList() ([]int, error) { if e.IsNA() { return nil, fmt.Errorf("can't convert NaN to []int") } l := make([]int, len(e.e)) for i := 0; i < len(e.e); i++ { f := e.e[i] if math.IsInf(f, 1) || math.IsInf(f, -1) { return nil, fmt.Errorf("can't convert Inf to int") } if math.IsNaN(f) { return nil, fmt.Errorf("can't convert NaN to int") } l[i] = int(f) } return l, nil } func (e floatListElement) FloatList() []float64 { if e.IsNA() { return []float64{math.NaN()} } return e.e } func (e floatListElement) BoolList() ([]bool, error) { if e.IsNA() { return nil, fmt.Errorf("can't convert NaN to []bool") } l := make([]bool, len(e.e)) for i := 0; i < len(e.e); i++ { if e.e[i] == 1 { l[i] = true } else { l[i] = false } } return l, nil } func (e floatListElement) Eq(elem Element) bool { if e.IsNA() || elem.IsNA() { return e.IsNA() == elem.IsNA() } list := elem.FloatList() if len(e.e) != len(list) { return false } for i := 0; i < len(e.e); i++ { if e.e[i] != list[i] { return false } } return true } func (e floatListElement) Neq(elem Element) bool { if e.IsNA() || elem.IsNA() { return e.IsNA() != elem.IsNA() } list := elem.FloatList() if len(e.e) != len(list) { return false } count := 0 for i := 0; i < len(e.e); i++ { if e.e[i] == list[i] { count = count + 1 } } return count != len(e.e) } func (e floatListElement) Less(elem Element) bool { list := elem.FloatList() if len(e.e) < len(list) { return true } else if len(e.e) > len(list) { return false } for i := 0; i < len(e.e); i++ { if e.e[i] >= list[i] { return false } } return true } func (e floatListElement) LessEq(elem Element) bool { list := elem.FloatList() if len(e.e) < len(list) { return true } else if len(e.e) > len(list) { return false } for i := 0; i < len(e.e); i++ { if e.e[i] > list[i] { return false } } return true } func (e floatListElement) Greater(elem Element) bool { list := elem.FloatList() if len(e.e) > len(list) { return true } else if len(e.e) < len(list) { return false } for i := 0; i < len(e.e); i++ { if e.e[i] <= list[i] { return false } } return true } func (e floatListElement) GreaterEq(elem Element) bool { list := elem.FloatList() if len(e.e) > len(list) { return true } else if len(e.e) < len(list) { return false } for i := 0; i < len(e.e); i++ { if e.e[i] < list[i] { return false } } return true }
series/type-float-list.go
0.507324
0.555857
type-float-list.go
starcoder
package visualregression import ( "image" "image/color" "image/draw" "image/png" "os" ) var HighlightColor = color.RGBA{ R: 255, G: 0, B: 255, A: 255, } func readAndDecode(filename string) (image.Image, error) { f, err := os.Open(filename) if err != nil { return nil, err } defer f.Close() img, err := png.Decode(f) if err != nil { return nil, err } return img, nil } func combine(reference, test, diff image.Image) *image.RGBA { largest := findLargestRectangle(reference.Bounds(), test.Bounds(), diff.Bounds()) container := image.Rectangle{ Min: image.Point{}, Max: image.Point{X: largest.Dx() * 3, Y: largest.Dy()}, } testStartingPoint := image.Point{ X: reference.Bounds().Dx(), Y: 0, } testRectangle := image.Rectangle{ Min: testStartingPoint, Max: testStartingPoint.Add(test.Bounds().Size()), } diffStartingPoint := image.Point{ X: reference.Bounds().Dx() + testRectangle.Dx(), Y: 0, } diffRectangle := image.Rectangle{ Min: diffStartingPoint, Max: diffStartingPoint.Add(diff.Bounds().Size()), } rgba := image.NewRGBA(container) draw.Draw(rgba, reference.Bounds(), reference, image.Point{ X: 0, Y: 0, }, draw.Src) draw.Draw(rgba, testRectangle, test, image.Point{ X: 0, Y: 0, }, draw.Src) draw.Draw(rgba, diffRectangle, diff, image.Point{ X: 0, Y: 0, }, draw.Src) return rgba } func compare(reference, test image.Image) (float64, *image.RGBA) { diffImage := image.NewRGBA(reference.Bounds()) chunks := groupPix(imageToRGBA(reference).Pix) targetChunks := groupPix(imageToRGBA(test).Pix) diffCounter := uint64(0) diffImage.Pix = []uint8{} highlight := []uint8{HighlightColor.R, HighlightColor.G, HighlightColor.B, HighlightColor.A} for i := 0; i < len(chunks); i++ { if i >= len(targetChunks) { diffImage.Pix = append(diffImage.Pix, highlight...) diffCounter += 1 continue } if !comparePix(chunks[i], targetChunks[i]) { diffImage.Pix = append(diffImage.Pix, highlight...) diffCounter += 1 continue } diffImage.Pix = append(diffImage.Pix, chunks[i]...) } percentage := float64(100) * float64(diffCounter) / float64(reference.Bounds().Dx()*reference.Bounds().Dy()) return percentage, diffImage } func findLargestRectangle(rectangles ...image.Rectangle) image.Rectangle { maxX := 0 maxY := 0 for _, rect := range rectangles { if rect.Max.X > maxX { maxX = rect.Max.X } if rect.Max.Y > maxY { maxY = rect.Max.Y } } return image.Rectangle{ Min: image.Point{}, Max: image.Point{X: maxX, Y: maxY}, } } func imageToRGBA(i image.Image) *image.RGBA { rect := i.Bounds() rgba := image.NewRGBA(rect) draw.Draw(rgba, rect, i, rect.Min, draw.Src) return rgba } func groupPix(pix []uint8) [][]uint8 { size := 4 var chunks [][]uint8 for { if len(pix) == 0 { break } if len(pix) < size { size = len(pix) } chunks = append(chunks, pix[0:size]) pix = pix[size:] } return chunks } func comparePix(pixA, pixB []uint8) bool { if len(pixA) != len(pixB) { return false } for i := 0; i < len(pixA); i++ { if pixA[i] != pixB[i] { return false } } return true } func saveImage(filename string, img image.Image) error { f, err := fs.Create(filename) if err != nil { return err } if err = png.Encode(f, img); err != nil { return err } if err = f.Close(); err != nil { return err } return nil }
images.go
0.665302
0.581481
images.go
starcoder
package route import ( "fmt" "github.com/yasshi2525/RushHour/entities" ) // Model has minimux distance route information to specific Node. type Model struct { GoalIDs []uint Nodes map[entities.ModelType]map[uint]*Node Edges map[entities.ModelType]map[uint]*Edge } // NewModel creates instance or copies original if it is specified. func NewModel(origin ...*Model) *Model { nodes := make(map[entities.ModelType]map[uint]*Node) edges := make(map[entities.ModelType]map[uint]*Edge) if len(origin) > 0 { //copy origin := origin[0] goalIDs := make([]uint, len(origin.GoalIDs)) for i, goalID := range origin.GoalIDs { goalIDs[i] = goalID } for key := range origin.Nodes { nodes[key] = make(map[uint]*Node) } for key := range origin.Edges { edges[key] = make(map[uint]*Edge) } return &Model{goalIDs, nodes, edges} } return &Model{[]uint{}, nodes, edges} } // Export copies Nodes and Edges having same id. func (m *Model) Export() *Model { copy := NewModel(m) for res, ns := range m.Nodes { for id, n := range ns { copy.Nodes[res][id] = n.Export() } } for res, es := range m.Edges { for id, e := range es { oldFrom, oldTo := e.FromNode, e.ToNode newFrom := copy.Nodes[oldFrom.ModelType][oldFrom.ID] newTo := copy.Nodes[oldTo.ModelType][oldTo.ID] copy.Edges[res][id] = e.Export(newFrom, newTo) } } return copy } // ExportWith copies Nodes and Edges, then returns corresponding Node to specified goal. func (m *Model) ExportWith(t entities.ModelType, id uint) (*Model, *Node) { copy := m.Export() return copy, copy.Nodes[t][id] } // NumNodes returns the number of Nodes. func (m *Model) NumNodes() int { var sum int for _, ns := range m.Nodes { sum += len(ns) } return sum } // NumEdges returns the number of Edges. func (m *Model) NumEdges() int { var sum int for _, es := range m.Edges { sum += len(es) } return sum } // AddGoalID adds id as goal. func (m *Model) AddGoalID(id uint) { m.GoalIDs = append(m.GoalIDs, id) } // FindOrCreateNode returns corresponding Node. // If such Node doesn't exist, create and return new Node. func (m *Model) FindOrCreateNode(origin entities.Entity) *Node { if _, ok := m.Nodes[origin.B().Type()]; !ok { m.Nodes[origin.B().Type()] = make(map[uint]*Node) } if n, ok := m.Nodes[origin.B().Type()][origin.B().Idx()]; ok { return n } n := NewNode(origin) m.Nodes[origin.B().Type()][origin.B().Idx()] = n return n } // FindOrCreateEdge returns corresponding Edge. // If such Edge doesn't exist, create and return new Edge. func (m *Model) FindOrCreateEdge(origin entities.Connectable) *Edge { if _, ok := m.Edges[origin.B().Type()]; !ok { m.Edges[origin.B().Type()] = make(map[uint]*Edge) } if e, ok := m.Edges[origin.B().Type()][origin.B().Idx()]; ok { return e } from, to := m.FindOrCreateNode(origin.From()), m.FindOrCreateNode(origin.To()) e := NewEdge(origin, from, to) m.Edges[origin.B().Type()][origin.B().Idx()] = e return e } // Fix discards no more using data. func (m *Model) Fix() { for _, ns := range m.Nodes { for _, n := range ns { n.Fix() } } } func (m *Model) String() string { nodes := make(map[entities.ModelType][]uint) for res, ns := range m.Nodes { nodes[res] = make([]uint, len(ns)) var i int for id := range ns { nodes[res][i] = id i++ } } edges := make(map[entities.ModelType][]uint) for res, es := range m.Edges { edges[res] = make([]uint, len(es)) var i int for id := range es { edges[res][i] = id i++ } } return fmt.Sprintf("Route:g=%v,n=%v,e=%v", m.GoalIDs, nodes, edges) } // Payload is collection of Model. type Payload struct { Route map[uint]*Model Processed int Total int } // IsOK returns whether all Model was built or not. func (p *Payload) IsOK() bool { return p.Processed == p.Total } // Import accepts result of calcuration. func (p *Payload) Import(oth *Payload) { for goalID, model := range oth.Route { p.Route[goalID] = model } p.Processed++ }
route/model.go
0.613237
0.416975
model.go
starcoder
package smtproofs import ( "crypto/sha256" "fmt" ics23 "github.com/confio/ics23/go" "github.com/lazyledger/smt" ) // PreimageMap represents an interface for accessing hashed tree paths and retrieving their // corresponding preimages. type PreimageMap interface { // KeyFor returns the preimage (key) for given path index. KeyFor(int) []byte // FindPath returns the ordered index of a given path, and whether it's contained in the tree. // If not found, the returned index is where the path would be inserted. FindPath([32]byte) (int, bool) // Len returns the number of mapped paths. Len() int } // CreateMembershipProof will produce a CommitmentProof that the given key (and queries value) exists in the SMT. // If the key doesn't exist in the tree, this will return an error. func CreateMembershipProof(tree *smt.SparseMerkleTree, key []byte) (*ics23.CommitmentProof, error) { exist, err := createExistenceProof(tree, key) if err != nil { return nil, err } proof := &ics23.CommitmentProof{ Proof: &ics23.CommitmentProof_Exist{ Exist: exist, }, } return proof, nil } func createExistenceProof(tree *smt.SparseMerkleTree, key []byte) (*ics23.ExistenceProof, error) { has, err := tree.Has(key) if err != nil { return nil, err } if !has { return nil, fmt.Errorf("Cannot create ExistenceProof when key not in state") } value, err := tree.Get(key) if err != nil { return nil, err } proof, err := tree.Prove(key) if err != nil { return nil, err } path := sha256.Sum256(key) return &ics23.ExistenceProof{ Key: path[:], Value: value, Leaf: ics23.SmtSpec.LeafSpec, Path: convertInnerOps(path[:], proof.SideNodes), }, nil } // CreateNonMembershipProof will produce a CommitmentProof that the given key doesn't exist in the SMT. // If the key exists in the tree, this will return an error. func CreateNonMembershipProof(tree *smt.SparseMerkleTree, key []byte, preimages PreimageMap) (*ics23.CommitmentProof, error) { path := sha256.Sum256(key) has, err := tree.Has(key) if err != nil { return nil, err } if has { return nil, fmt.Errorf("Cannot create NonExistenceProof when key in state") } nonexist := &ics23.NonExistenceProof{ Key: path[:], } ix, found := preimages.FindPath(path) if found { return nil, fmt.Errorf("Found index for key not in state") } if ix > 0 { nonexist.Left, err = createExistenceProof(tree, preimages.KeyFor(ix-1)) if err != nil { return nil, err } } if ix < preimages.Len() { nonexist.Right, err = createExistenceProof(tree, preimages.KeyFor(ix)) if err != nil { return nil, err } } return &ics23.CommitmentProof{ Proof: &ics23.CommitmentProof_Nonexist{ nonexist, }, }, nil } func convertInnerOps(path []byte, sideNodes [][]byte) []*ics23.InnerOp { depth := len(sideNodes) inners := make([]*ics23.InnerOp, 0, depth) for i := 0; i < len(sideNodes); i++ { op := &ics23.InnerOp{ Hash: ics23.HashOp_SHA256, Prefix: []byte{1}, } if getBitAtFromMSB(path[:], depth-1-i) == 1 { // right child is on path op.Prefix = append(op.Prefix, sideNodes[i]...) } else { op.Suffix = sideNodes[i] } inners = append(inners, op) } return inners } // getBitAtFromMSB gets the bit at an offset from the most significant bit // Copied from github.com/celestiaorg/smt func getBitAtFromMSB(data []byte, position int) int { if int(data[position/8])&(1<<(8-1-uint(position)%8)) > 0 { return 1 } return 0 }
store/tools/ics23/smt/create.go
0.63443
0.438845
create.go
starcoder
package draw2d import ( "image/color" "github.com/lafriks/go-svg" "github.com/lafriks/go-svg/renderer" "github.com/llgcode/draw2d" ) // Draw the parsed SVG into the graphic context with the specified options. func Draw(gc draw2d.GraphicContext, s *svg.Svg, opts ...renderer.RenderOption) { opt := renderer.Options(s, opts...) for _, svgp := range s.SvgPaths { drawTransformed(gc, svgp, opt) } } func drawTo(gc draw2d.GraphicContext, op svg.Operation, m svg.Matrix2D) { switch op := op.(type) { case svg.OpMoveTo: gc.Close() gc.BeginPath() t := m.MoveTo(op) gc.MoveTo(float64(t.X)/64, float64(t.Y)/64) case svg.OpLineTo: t := m.LineTo(op) gc.LineTo(float64(t.X)/64, float64(t.Y)/64) case svg.OpQuadTo: t1, t2 := m.QuadTo(op) gc.QuadCurveTo(float64(t1.X)/64, float64(t1.Y)/64, float64(t2.X)/64, float64(t2.Y)/64) case svg.OpCubicTo: t1, t2, t3 := m.CubicTo(op) gc.CubicCurveTo(float64(t1.X)/64, float64(t1.Y)/64, float64(t2.X)/64, float64(t2.Y)/64, float64(t3.X)/64, float64(t3.Y)/64) case svg.OpClose: gc.Close() } } func toLineCap(cap svg.CapMode) draw2d.LineCap { switch cap { case svg.ButtCap, svg.CubicCap, svg.QuadraticCap: return draw2d.ButtCap case svg.RoundCap: return draw2d.RoundCap case svg.SquareCap: return draw2d.SquareCap } return draw2d.ButtCap } func toLineJoin(join svg.JoinMode) draw2d.LineJoin { switch join { case svg.Arc, svg.Miter, svg.MiterClip: return draw2d.MiterJoin case svg.Round: return draw2d.RoundJoin case svg.Bevel: return draw2d.BevelJoin } return draw2d.MiterJoin } func toColor(c color.Color, opacity float64) color.Color { r, g, b, a := c.RGBA() return color.NRGBA{uint8(r >> 8), uint8(g >> 8), uint8(b >> 8), uint8(uint32(float64(a)*opacity) >> 8)} } func toGradient(g svg.Gradient, opacity float64) color.Color { return toColor(svg.GetColor(g), opacity) } // drawTransformed draws the compiled SvgPath into the driver while applying transform t. func drawTransformed(gc draw2d.GraphicContext, svgp svg.SvgPath, opt *renderer.RenderOptions) { m := svgp.Style.Transform.Mult(opt.Target) if svgp.Style.FillerColor != nil { var fr draw2d.FillRule if svgp.Style.UseNonZeroWinding { fr = draw2d.FillRuleWinding } gc.SetFillRule(fr) switch c := svgp.Style.FillerColor.(type) { case svg.PlainColor: gc.SetFillColor(toColor(c, svgp.Style.FillOpacity*opt.Opacity)) case svg.Gradient: gc.SetFillColor(toGradient(c, svgp.Style.FillOpacity*opt.Opacity)) } } if svgp.Style.LinerColor != nil { gc.SetLineCap(toLineCap(svgp.Style.Join.TrailLineCap)) gc.SetLineJoin(toLineJoin(svgp.Style.Join.LineJoin)) switch c := svgp.Style.LinerColor.(type) { case svg.PlainColor: gc.SetStrokeColor(toColor(c, svgp.Style.LineOpacity*opt.Opacity)) case svg.Gradient: gc.SetStrokeColor(toGradient(c, svgp.Style.LineOpacity*opt.Opacity)) } gc.SetLineWidth(svgp.Style.LineWidth) gc.SetLineDash(svgp.Style.Dash.Dash, svgp.Style.Dash.DashOffset) } for _, op := range svgp.Path { drawTo(gc, op, m) } if svgp.Style.FillerColor != nil { if svgp.Style.LinerColor != nil { gc.FillStroke() } else { gc.Fill() } } else if svgp.Style.LinerColor != nil { gc.Stroke() } }
renderer/draw2d/draw.go
0.658418
0.457803
draw.go
starcoder
package array import ( "reflect" ) type Array []interface{} // Create an `Array` func NewArray(array ...interface{}) Array { a := Array{} if len(array) > 1 { a.Push(array...) } else if len(array) == 1 { v := reflect.ValueOf(array[0]) for i := 0; i < v.Len(); i++ { a.Push(v.Index(i).Interface()) } } return a } // Push one or more elements onto the end of `Array` func (a *Array) Push(values ...interface{}) { *a = append(*a, values...) } // Merge one or more arrays func (a *Array) Concat(array ...interface{}) { for _, val := range array { v := reflect.ValueOf(val) for i := 0; i < v.Len(); i++ { *a = append(*a, v.Index(i).Interface()) } } } // Returns the `Array` length func (a Array) Length() int { return len(a) } // Append one or more elements onto the end of `Array` func (a *Array) Append(values ...interface{}) { a.Push(values...) } // Prepend one or more elements to the beginning of an `Array` func (a *Array) UnShift(values ...interface{}) int { if len(values) == 0 { return len(*a) } values = append(values, *a...) *a = values return len(*a) } // Shift an element off the beginning of `Array` func (a *Array) Shift() interface{} { var x interface{} x, *a = (*a)[0], (*a)[1:] return x } // Pop the element off the end of `Array` func (a *Array) Pop() interface{} { ep := len(*a) - 1 var x interface{} x, *a = (*a)[ep], (*a)[:ep] return x } // Checks if the given index exists in the array func (a Array) Exists(i int) bool { return len(a) > i && nil != a[i] } // Returns given the index value in the `Array` func (a Array) Index(i int) interface{} { if a.Exists(i) { return a[i] } return nil } // Searches the array for a given value and returns the `index` if successful // If the given value no exists in the array, return -1 func (a Array) Search(val interface{}) int { for i, v := range a { if val == v { return i } } return -1 } // destroys the given index in the array func (a *Array) Unset(index int) bool { if index >= 0 && index < len(*a) { *a = append((*a)[:index], (*a)[index+1:]...) return true } return false } // Return an array or slice with elements in reverse order func Reverse(data interface{}) { t := reflect.TypeOf(data) v := reflect.ValueOf(data) if reflect.Ptr == t.Kind() { t = t.Elem() v = v.Elem() } n, x, y := v.Len(), 0, 0 switch t.Kind() { case reflect.Slice, reflect.Array: { for x = 0; x < n/2; x++ { y = n - x - 1 vx, vy := v.Index(x).Interface(), v.Index(y).Interface() // data[x], data[y] = data[y], data[x] v.Index(x).Set(reflect.ValueOf(vy)) v.Index(y).Set(reflect.ValueOf(vx)) } } } }
array/array.go
0.733261
0.511168
array.go
starcoder
package layer import ( "fmt" "github.com/aunum/log" g "gorgonia.org/gorgonia" t "gorgonia.org/tensor" ) // Conv2D is a 2D convolution. type Conv2D struct { // Input channels. // required Input int // Output channels. // required Output int // Height of the filter. // required Height int // Width of the filter. // required Width int // Name of the layer. Name string // Activation function for the layer. // Defaults to ReLU Activation ActivationFn // Pad // Defaults to (1, 1) Pad []int // Stride // Defaults to (1, 1) Stride []int // Dilation // Defaults to (1, 1) Dilation []int // Init function fot the weights. // Defaults to GlorotN(1) Init g.InitWFn } // Compile the config into a layer. func (c Conv2D) Compile(graph *g.ExprGraph, opts ...CompileOpt) Layer { cnv := newConv2D(&c) for _, opt := range opts { opt(cnv) } if cnv.shared != nil { cnv.filter = g.NewTensor(graph, cnv.dtype, 4, g.WithShape(cnv.filterShape...), g.WithInit(c.Init), g.WithName(c.Name), g.WithValue(cnv.shared.filter.Value())) return cnv } cnv.filter = g.NewTensor(graph, cnv.dtype, 4, g.WithShape(cnv.filterShape...), g.WithInit(c.Init), g.WithName(c.Name)) return cnv } // Validate the config. func (c Conv2D) Validate() error { if c.Input == 0 { return fmt.Errorf("input must be set") } if c.Output == 0 { return fmt.Errorf("output must be set") } if c.Width == 0 { return fmt.Errorf("width must be set") } if c.Height == 0 { return fmt.Errorf("height must be set") } return nil } // ApplyDefaults to the config. func (c Conv2D) ApplyDefaults() Config { if c.Activation == nil { c.Activation = ReLU } if len(c.Pad) == 0 { c.Pad = []int{1, 1} } if len(c.Stride) == 0 { c.Stride = []int{1, 1} } if len(c.Dilation) == 0 { c.Dilation = []int{1, 1} } if c.Init == nil { c.Init = g.GlorotU(1) } return c } // Clone the config. func (c Conv2D) Clone() Config { return Conv2D{ Input: c.Input, Output: c.Output, Height: c.Height, Width: c.Width, Name: c.Name, Activation: c.Activation.Clone(), Pad: c.Pad, Stride: c.Stride, Dilation: c.Dilation, Init: c.Init, } } // conv2D is a two dimensional convolution layer. type conv2D struct { *Conv2D dtype t.Dtype filterShape t.Shape kernelShape t.Shape filter *g.Node shared *conv2D isBatched bool } func newConv2D(config *Conv2D) *conv2D { config.ApplyDefaults() return &conv2D{ Conv2D: config, dtype: t.Float32, kernelShape: []int{config.Height, config.Width}, filterShape: []int{config.Output, config.Input, config.Height, config.Width}, } } // Fwd is a forward pass through the layer. func (c *conv2D) Fwd(x *g.Node) (*g.Node, error) { log.Debug("conv fwd") log.Debugv("xshape", x.Shape()) log.Debugv("filtershape", c.filter.Shape()) log.Debugv("kernel", c.kernelShape) log.Debugv("pad", c.Pad) log.Debugv("stride", c.Stride) log.Debugv("dilation", c.Dilation) n, err := g.Conv2d(x, c.filter, c.kernelShape, c.Pad, c.Stride, c.Dilation) if err != nil { return nil, err } n, err = c.Activation.Fwd(n) if err != nil { return nil, err } log.Debugf("conv2d name: %q output shape: %v", c.Name, n.Shape()) return n, nil } // Learnables returns all learnable nodes within this layer. func (c *conv2D) Learnables() g.Nodes { return g.Nodes{c.filter} } // Clone the layer. func (c *conv2D) Clone() Layer { return &conv2D{ Conv2D: c.Conv2D.Clone().(*Conv2D), dtype: c.dtype, filter: c.filter, isBatched: c.isBatched, } } // Graph returns the graph for this layer. func (c *conv2D) Graph() *g.ExprGraph { if c.filter == nil { return nil } return c.filter.Graph() }
vendor/github.com/aunum/goro/pkg/v1/layer/conv2d.go
0.831143
0.425247
conv2d.go
starcoder