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 main import ( "fmt" "math" "os" "sort" ) var bricksNum int func main() { fmt.Scan(&bricksNum) fmt.Printf("%d %d\n", logMin(buildNormalizedCuboid()).a, logMax(buildTallCuboid()).a, ) } // Maximum (experienced that by doing manual experiments with small number of bricks). func buildTallCuboid() match { return newMatch(bricksNum, 1) } // Minimum (experienced that by doing manual experiments with small number of bricks). func buildNormalizedCuboid() match { // Try cubic root first. cubicRoot := math.Pow(float64(bricksNum), 1.0/3.0) if rounded, ok := tolerantIsInt(cubicRoot); ok { // It can be a cube! return newMatch(int(rounded), int(rounded)) } // Let's grab all components for the brickNum (our cubic space V) var components []int smallestDivisible := 2 number := bricksNum for number > 1 { smallestDivisible = findSmallestDivisible(number, smallestDivisible-1) components = append(components, smallestDivisible) number = number / smallestDivisible } // Sort from the biggest first! sort.Sort(sort.Reverse(sort.IntSlice(components))) bestMatch := newMatch(bricksNum, 1) if len(components) == 1 { return bestMatch } if len(components) == 2 || len(components) == 3 { return newMatch(components[0], components[1]) } /* If we have more components than 3, then we need to: 1) Naively: Do every permutation of these to find optimum. (That is what works! =D so no need for better solution.) 2) We could optimize the solution since we know that x and y needs to be as close as possible to cubic root of V. We can construct function from surface and cubic space functions: func a(x, y, v int) int { return 2 * ((x * y) + (((x + y) * v) / (x * y))) } This function indicates (same as intuition) that x == y is the minimum of a. Having that in mind, we can just start from x ~ y and go down with x and up with y slowly and check if we can construct them having known components. This is not implemented here, since it was not needed to pass test cases (which proves that test cases should be better!) */ bestMatch = checkDeep([3]int{components[0], components[1], components[2]}, components[3:]) return bestMatch } type match struct { x, y, z int v int a int // Surface. } func newMatch(x, y int) match { m := match{ x: x, y: y, z: bricksNum / (x * y), v: bricksNum, } m.a = a(m.x, m.y, m.v) return m } func (m match) isSmaller(x, y int) bool { return m.a <= a(x, y, m.v) } func (m match) dimensions() (int, int, int) { return m.x, m.y, m.z } func a(x, y, v int) int { return 2 * ((x * y) + (((x + y) * v) / (x * y))) } func checkDeep(cuboid [3]int, components []int) match { if len(components) == 0 { return newMatch(cuboid[0], cuboid[1]) } bestMatch := checkDeep( [3]int{ cuboid[0] * components[0], cuboid[1], cuboid[2], }, components[1:], ) match2 := checkDeep( [3]int{ cuboid[0], cuboid[1] * components[0], cuboid[2], }, components[1:], ) if match2.isSmaller(bestMatch.x, bestMatch.y) { bestMatch = match2 } match3 := checkDeep( [3]int{ cuboid[0], cuboid[1], cuboid[2] * components[0], }, components[1:], ) if match3.isSmaller(bestMatch.x, bestMatch.y) { bestMatch = match3 } return bestMatch } func findSmallestDivisible(number int, greaterThan int) int { divisible := greaterThan + 1 for divisible < number { if math.Mod(float64(number), float64(divisible)) != 0 { divisible++ continue } return divisible } return number } func tolerantIsInt(number float64) (int, bool) { rounded := math.Floor(number + .5) if number-rounded > -0.0000001 && number-rounded < 0.0000001 { return int(rounded), true } return 0, false } func logMin(m match) match { fmt.Fprintln(os.Stderr, fmt.Sprintf("Minimum: %d x %d x %d", m.x, m.y, m.z)) return m } func logMax(m match) match { fmt.Fprintln(os.Stderr, fmt.Sprintf("Maximum: %d x %d x %d", m.x, m.y, m.z)) return m }
weekly/MaxSurfaceBox/main.go
0.692434
0.530297
main.go
starcoder
package accounting import ( "encoding/json" ) // CreateInvoiceSubFeatures Lists the individual aspects of creating invoices that are enabled for the integration, as part of the create invoice flow in HubSpot. type CreateInvoiceSubFeatures struct { // Indicates if a new customer can be created in the external accounting system. CreateCustomer bool `json:"createCustomer"` // Indicates if taxes can be specified by the HubSpot user for line items. Taxes bool `json:"taxes"` // Indicates if the external accounting system supports fetching exchange rates when create an invoice in HubSpot for a customer billed in a different currency. ExchangeRates bool `json:"exchangeRates"` // Indicates if the external accounting system supports fetching payment terms. Terms bool `json:"terms"` // Indicates if a visible comment can be added to invoices. InvoiceComments bool `json:"invoiceComments"` // Indicates if invoice-level discounts can be added to invoices. InvoiceDiscounts bool `json:"invoiceDiscounts"` } // NewCreateInvoiceSubFeatures instantiates a new CreateInvoiceSubFeatures 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 NewCreateInvoiceSubFeatures(createCustomer bool, taxes bool, exchangeRates bool, terms bool, invoiceComments bool, invoiceDiscounts bool) *CreateInvoiceSubFeatures { this := CreateInvoiceSubFeatures{} this.CreateCustomer = createCustomer this.Taxes = taxes this.ExchangeRates = exchangeRates this.Terms = terms this.InvoiceComments = invoiceComments this.InvoiceDiscounts = invoiceDiscounts return &this } // NewCreateInvoiceSubFeaturesWithDefaults instantiates a new CreateInvoiceSubFeatures 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 NewCreateInvoiceSubFeaturesWithDefaults() *CreateInvoiceSubFeatures { this := CreateInvoiceSubFeatures{} return &this } // GetCreateCustomer returns the CreateCustomer field value func (o *CreateInvoiceSubFeatures) GetCreateCustomer() bool { if o == nil { var ret bool return ret } return o.CreateCustomer } // GetCreateCustomerOk returns a tuple with the CreateCustomer field value // and a boolean to check if the value has been set. func (o *CreateInvoiceSubFeatures) GetCreateCustomerOk() (*bool, bool) { if o == nil { return nil, false } return &o.CreateCustomer, true } // SetCreateCustomer sets field value func (o *CreateInvoiceSubFeatures) SetCreateCustomer(v bool) { o.CreateCustomer = v } // GetTaxes returns the Taxes field value func (o *CreateInvoiceSubFeatures) GetTaxes() bool { if o == nil { var ret bool return ret } return o.Taxes } // GetTaxesOk returns a tuple with the Taxes field value // and a boolean to check if the value has been set. func (o *CreateInvoiceSubFeatures) GetTaxesOk() (*bool, bool) { if o == nil { return nil, false } return &o.Taxes, true } // SetTaxes sets field value func (o *CreateInvoiceSubFeatures) SetTaxes(v bool) { o.Taxes = v } // GetExchangeRates returns the ExchangeRates field value func (o *CreateInvoiceSubFeatures) GetExchangeRates() bool { if o == nil { var ret bool return ret } return o.ExchangeRates } // GetExchangeRatesOk returns a tuple with the ExchangeRates field value // and a boolean to check if the value has been set. func (o *CreateInvoiceSubFeatures) GetExchangeRatesOk() (*bool, bool) { if o == nil { return nil, false } return &o.ExchangeRates, true } // SetExchangeRates sets field value func (o *CreateInvoiceSubFeatures) SetExchangeRates(v bool) { o.ExchangeRates = v } // GetTerms returns the Terms field value func (o *CreateInvoiceSubFeatures) GetTerms() bool { if o == nil { var ret bool return ret } return o.Terms } // GetTermsOk returns a tuple with the Terms field value // and a boolean to check if the value has been set. func (o *CreateInvoiceSubFeatures) GetTermsOk() (*bool, bool) { if o == nil { return nil, false } return &o.Terms, true } // SetTerms sets field value func (o *CreateInvoiceSubFeatures) SetTerms(v bool) { o.Terms = v } // GetInvoiceComments returns the InvoiceComments field value func (o *CreateInvoiceSubFeatures) GetInvoiceComments() bool { if o == nil { var ret bool return ret } return o.InvoiceComments } // GetInvoiceCommentsOk returns a tuple with the InvoiceComments field value // and a boolean to check if the value has been set. func (o *CreateInvoiceSubFeatures) GetInvoiceCommentsOk() (*bool, bool) { if o == nil { return nil, false } return &o.InvoiceComments, true } // SetInvoiceComments sets field value func (o *CreateInvoiceSubFeatures) SetInvoiceComments(v bool) { o.InvoiceComments = v } // GetInvoiceDiscounts returns the InvoiceDiscounts field value func (o *CreateInvoiceSubFeatures) GetInvoiceDiscounts() bool { if o == nil { var ret bool return ret } return o.InvoiceDiscounts } // GetInvoiceDiscountsOk returns a tuple with the InvoiceDiscounts field value // and a boolean to check if the value has been set. func (o *CreateInvoiceSubFeatures) GetInvoiceDiscountsOk() (*bool, bool) { if o == nil { return nil, false } return &o.InvoiceDiscounts, true } // SetInvoiceDiscounts sets field value func (o *CreateInvoiceSubFeatures) SetInvoiceDiscounts(v bool) { o.InvoiceDiscounts = v } func (o CreateInvoiceSubFeatures) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["createCustomer"] = o.CreateCustomer } if true { toSerialize["taxes"] = o.Taxes } if true { toSerialize["exchangeRates"] = o.ExchangeRates } if true { toSerialize["terms"] = o.Terms } if true { toSerialize["invoiceComments"] = o.InvoiceComments } if true { toSerialize["invoiceDiscounts"] = o.InvoiceDiscounts } return json.Marshal(toSerialize) } type NullableCreateInvoiceSubFeatures struct { value *CreateInvoiceSubFeatures isSet bool } func (v NullableCreateInvoiceSubFeatures) Get() *CreateInvoiceSubFeatures { return v.value } func (v *NullableCreateInvoiceSubFeatures) Set(val *CreateInvoiceSubFeatures) { v.value = val v.isSet = true } func (v NullableCreateInvoiceSubFeatures) IsSet() bool { return v.isSet } func (v *NullableCreateInvoiceSubFeatures) Unset() { v.value = nil v.isSet = false } func NewNullableCreateInvoiceSubFeatures(val *CreateInvoiceSubFeatures) *NullableCreateInvoiceSubFeatures { return &NullableCreateInvoiceSubFeatures{value: val, isSet: true} } func (v NullableCreateInvoiceSubFeatures) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableCreateInvoiceSubFeatures) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
generated/accounting/model_create_invoice_sub_features.go
0.764804
0.526769
model_create_invoice_sub_features.go
starcoder
package token import ( "fmt" "github.com/hyperledger-labs/fabric-smart-client/platform/view/view" token2 "github.com/hyperledger-labs/fabric-token-sdk/token/token" ) type QueryService interface { IsMine(id *token2.ID) (bool, error) } // Output models the output of a token action type Output struct { ActionIndex int Owner view.Identity EnrollmentID string Type string Quantity token2.Quantity } // Input models an input of a token action type Input struct { ActionIndex int Id *token2.ID Owner view.Identity EnrollmentID string Type string Quantity token2.Quantity } // OutputStream models a stream over a set of outputs (Output). type OutputStream struct { Precision uint64 outputs []*Output } // NewOutputStream creates a new OutputStream for the passed outputs and Precision. func NewOutputStream(outputs []*Output, precision uint64) *OutputStream { return &OutputStream{outputs: outputs, Precision: precision} } // Filter filters the OutputStream to only include outputs that match the passed predicate. func (o *OutputStream) Filter(f func(t *Output) bool) *OutputStream { var filtered []*Output for _, output := range o.outputs { if f(output) { filtered = append(filtered, output) } } return &OutputStream{outputs: filtered, Precision: o.Precision} } // ByRecipient filters the OutputStream to only include outputs that match the passed recipient. func (o *OutputStream) ByRecipient(id view.Identity) *OutputStream { return o.Filter(func(t *Output) bool { return id.Equal(t.Owner) }) } // ByType filters the OutputStream to only include outputs that match the passed type. func (o *OutputStream) ByType(typ string) *OutputStream { return o.Filter(func(t *Output) bool { return t.Type == typ }) } // Outputs returns the outputs of the OutputStream. func (o *OutputStream) Outputs() []*Output { return o.outputs } // Count returns the number of outputs in the OutputStream. func (o *OutputStream) Count() int { return len(o.outputs) } // Sum returns the sum of the quantity of all outputs in the OutputStream. func (o *OutputStream) Sum() token2.Quantity { sum := token2.NewZeroQuantity(o.Precision) for _, output := range o.outputs { sum = sum.Add(output.Quantity) } return sum } // At returns the output at the passed index. func (o *OutputStream) At(i int) *Output { return o.outputs[i] } // ByEnrollmentID filters to only include outputs that match the passed enrollment ID. func (o *OutputStream) ByEnrollmentID(id string) *OutputStream { return o.Filter(func(t *Output) bool { return t.EnrollmentID == id }) } // EnrollmentIDs returns the enrollment IDs of the outputs in the OutputStream. func (o *OutputStream) EnrollmentIDs() []string { duplicates := map[string]interface{}{} var eIDs []string for _, output := range o.outputs { if len(output.EnrollmentID) == 0 { continue } if _, ok := duplicates[output.EnrollmentID]; !ok { eIDs = append(eIDs, output.EnrollmentID) duplicates[output.EnrollmentID] = true } } return eIDs } // TokenTypes returns the token types of the outputs in the OutputStream. func (o *OutputStream) TokenTypes() []string { duplicates := map[string]interface{}{} var types []string for _, output := range o.outputs { if _, ok := duplicates[output.Type]; !ok { types = append(types, output.Type) duplicates[output.Type] = true } } return types } // InputStream models a stream over a set of inputs (Input). type InputStream struct { qs QueryService inputs []*Input precision uint64 } // NewInputStream creates a new InputStream for the passed inputs and query service. func NewInputStream(qs QueryService, inputs []*Input, precision uint64) *InputStream { return &InputStream{qs: qs, inputs: inputs, precision: precision} } // Filter returns a new InputStream with only the inputs that satisfy the predicate func (is *InputStream) Filter(f func(t *Input) bool) *InputStream { var filtered []*Input for _, item := range is.inputs { if f(item) { filtered = append(filtered, item) } } return &InputStream{inputs: filtered, precision: is.precision} } // Count returns the number of inputs in the stream func (is *InputStream) Count() int { return len(is.inputs) } // Owners returns a list of identities that own the tokens in the stream func (is *InputStream) Owners() *OwnerStream { ownerMap := map[string]bool{} var owners []string for _, input := range is.inputs { _, ok := ownerMap[input.Owner.UniqueID()] if ok { continue } ownerMap[input.Owner.UniqueID()] = true owners = append(owners, input.Owner.UniqueID()) } return &OwnerStream{owners: owners} } // IsAnyMine returns true if any of the inputs are mine func (is *InputStream) IsAnyMine() bool { for _, input := range is.inputs { mine, err := is.qs.IsMine(input.Id) if err != nil { panic(err) } if mine { return true } } return false } // String returns a string representation of the input stream func (is *InputStream) String() string { return fmt.Sprintf("[%v]", is.inputs) } // At returns the input at the given index. func (is *InputStream) At(i int) *Input { return is.inputs[i] } // IDs returns the IDs of the inputs. func (is *InputStream) IDs() []*token2.ID { var res []*token2.ID for _, input := range is.inputs { res = append(res, input.Id) } return res } // EnrollmentIDs returns the enrollment IDs of the owners of the inputs. // It might be empty, if not available. func (is *InputStream) EnrollmentIDs() []string { duplicates := map[string]interface{}{} var eIDs []string for _, input := range is.inputs { if len(input.EnrollmentID) == 0 { continue } _, ok := duplicates[input.EnrollmentID] if !ok { eIDs = append(eIDs, input.EnrollmentID) duplicates[input.EnrollmentID] = true } } return eIDs } // TokenTypes returns the token types of the inputs. func (is *InputStream) TokenTypes() []string { duplicates := map[string]interface{}{} var types []string for _, input := range is.inputs { _, ok := duplicates[input.Type] if !ok { types = append(types, input.Type) duplicates[input.Type] = true } } return types } // ByEnrollmentID filters by enrollment ID. func (is *InputStream) ByEnrollmentID(id string) *InputStream { return is.Filter(func(t *Input) bool { return t.EnrollmentID == id }) } // ByType filters by token type. func (is *InputStream) ByType(tokenType string) *InputStream { return is.Filter(func(t *Input) bool { return t.Type == tokenType }) } // Sum returns the sum of the quantities of the inputs. func (is *InputStream) Sum() token2.Quantity { sum := token2.NewZeroQuantity(is.precision) for _, input := range is.inputs { sum = sum.Add(input.Quantity) } return sum } type OwnerStream struct { owners []string } func NewOwnerStream(owners []string) *OwnerStream { return &OwnerStream{owners: owners} } func (s *OwnerStream) Count() int { return len(s.owners) }
token/stream.go
0.793546
0.401512
stream.go
starcoder
package graph import ( "fmt" "github.com/moorara/algo/list" "github.com/moorara/algo/pkg/graphviz" ) // DirectedEdge represents a weighted directed edge data type. type DirectedEdge struct { from, to int weight float64 } // From returns the vertex this edge points from. func (e DirectedEdge) From() int { return e.from } // To returns the vertex this edge points to. func (e DirectedEdge) To() int { return e.to } // Weight returns the weight of this edge. func (e DirectedEdge) Weight() float64 { return e.weight } // WeightedDirected represents a weighted directed graph data type. type WeightedDirected struct { v, e int ins []int adj [][]DirectedEdge } // NewWeightedDirected creates a new weighted directed graph. func NewWeightedDirected(V int, edges ...DirectedEdge) *WeightedDirected { adj := make([][]DirectedEdge, V) for i := range adj { adj[i] = make([]DirectedEdge, 0) } g := &WeightedDirected{ v: V, // no. of vertices e: 0, // no. of edges ins: make([]int, V), adj: adj, } for _, e := range edges { g.AddEdge(e) } return g } // V returns the number of vertices. func (g *WeightedDirected) V() int { return g.v } // E returns the number of edges. func (g *WeightedDirected) E() int { return g.e } func (g *WeightedDirected) isVertexValid(v int) bool { return v >= 0 && v < g.v } // InDegree returns the number of directed edges incident to a vertex. func (g *WeightedDirected) InDegree(v int) int { if !g.isVertexValid(v) { return -1 } return g.ins[v] } // OutDegree returns the number of directed edges incident from a vertex. func (g *WeightedDirected) OutDegree(v int) int { if !g.isVertexValid(v) { return -1 } return len(g.adj[v]) } // Adj returns the vertices adjacent from vertex. func (g *WeightedDirected) Adj(v int) []DirectedEdge { if !g.isVertexValid(v) { return nil } return g.adj[v] } // AddEdge adds a new edge to the graph. func (g *WeightedDirected) AddEdge(e DirectedEdge) { v := e.From() w := e.To() if g.isVertexValid(v) && g.isVertexValid(w) { g.e++ g.ins[w]++ g.adj[v] = append(g.adj[v], e) } } // Edges returns all directed edges in the graph. func (g *WeightedDirected) Edges() []DirectedEdge { edges := make([]DirectedEdge, 0) for _, adjEdges := range g.adj { edges = append(edges, adjEdges...) } return edges } // Reverse returns the reverse of the directed graph. func (g *WeightedDirected) Reverse() *WeightedDirected { rev := NewWeightedDirected(g.V()) for v := 0; v < g.V(); v++ { for _, e := range g.adj[v] { rev.AddEdge(DirectedEdge{e.To(), e.From(), e.Weight()}) } } return rev } // DFS Traversal (Recursion) func (g *WeightedDirected) traverseDFS(v int, visited []bool, visitors *Visitors) { visited[v] = true if visitors != nil && visitors.VertexPreOrder != nil { if !visitors.VertexPreOrder(v) { return } } for _, e := range g.adj[v] { w := e.To() if !visited[w] { if visitors != nil && visitors.EdgePreOrder != nil { if !visitors.EdgePreOrder(v, w, e.Weight()) { return } } g.traverseDFS(w, visited, visitors) } } if visitors != nil && visitors.VertexPostOrder != nil { if !visitors.VertexPostOrder(v) { return } } } // Iterative DFS Traversal func (g *WeightedDirected) traverseDFSi(s int, visited []bool, visitors *Visitors) { stack := list.NewStack(listNodeSize) visited[s] = true stack.Push(s) if visitors != nil && visitors.VertexPreOrder != nil { if !visitors.VertexPreOrder(s) { return } } for !stack.IsEmpty() { v := stack.Pop().(int) if visitors != nil && visitors.VertexPostOrder != nil { if !visitors.VertexPostOrder(v) { return } } for _, e := range g.adj[v] { w := e.To() if !visited[w] { visited[w] = true stack.Push(w) if visitors != nil && visitors.VertexPreOrder != nil { if !visitors.VertexPreOrder(w) { return } } if visitors != nil && visitors.EdgePreOrder != nil { if !visitors.EdgePreOrder(v, w, e.Weight()) { return } } } } } } // BFS Traversal func (g *WeightedDirected) traverseBFS(s int, visited []bool, visitors *Visitors) { queue := list.NewQueue(listNodeSize) visited[s] = true queue.Enqueue(s) if visitors != nil && visitors.VertexPreOrder != nil { if !visitors.VertexPreOrder(s) { return } } for !queue.IsEmpty() { v := queue.Dequeue().(int) if visitors != nil && visitors.VertexPostOrder != nil { if !visitors.VertexPostOrder(v) { return } } for _, e := range g.adj[v] { w := e.To() if !visited[w] { visited[w] = true queue.Enqueue(w) if visitors != nil && visitors.VertexPreOrder != nil { if !visitors.VertexPreOrder(w) { return } } if visitors != nil && visitors.EdgePreOrder != nil { if !visitors.EdgePreOrder(v, w, e.Weight()) { return } } } } } } // Traverse is used for visiting all vertices and edges in graph. func (g *WeightedDirected) Traverse(s int, strategy TraversalStrategy, visitors *Visitors) { if !g.isVertexValid(s) { return } visited := make([]bool, g.V()) switch strategy { case DFS: g.traverseDFS(s, visited, visitors) case DFSi: g.traverseDFSi(s, visited, visitors) case BFS: g.traverseBFS(s, visited, visitors) } } // Paths finds all paths from a source vertex to every other vertex. func (g *WeightedDirected) Paths(s int, strategy TraversalStrategy) *Paths { p := &Paths{ s: s, visited: make([]bool, g.V()), edgeTo: make([]int, g.V()), } if g.isVertexValid(s) && isStrategyValid(strategy) { visitors := &Visitors{ EdgePreOrder: func(v, w int, weight float64) bool { p.edgeTo[w] = v return true }, } switch strategy { case DFS: g.traverseDFS(s, p.visited, visitors) case DFSi: g.traverseDFSi(s, p.visited, visitors) case BFS: g.traverseBFS(s, p.visited, visitors) } } return p } // Orders determines ordering of vertices in the graph. func (g *WeightedDirected) Orders(strategy TraversalStrategy) *Orders { o := &Orders{ preRank: make([]int, g.V()), postRank: make([]int, g.V()), preOrder: make([]int, 0), postOrder: make([]int, 0), } if isStrategyValid(strategy) { var preCounter, postCounter int visited := make([]bool, g.V()) visitors := &Visitors{ VertexPreOrder: func(v int) bool { o.preRank[v] = preCounter preCounter++ o.preOrder = append(o.preOrder, v) return true }, VertexPostOrder: func(v int) bool { o.postRank[v] = postCounter postCounter++ o.postOrder = append(o.postOrder, v) return true }, } for v := 0; v < g.V(); v++ { if !visited[v] { switch strategy { case DFS: g.traverseDFS(v, visited, visitors) case DFSi: g.traverseDFSi(v, visited, visitors) case BFS: g.traverseBFS(v, visited, visitors) } } } } return o } // StronglyConnectedComponents determines all the connected components in the graph. func (g *WeightedDirected) StronglyConnectedComponents() *StronglyConnectedComponents { scc := &StronglyConnectedComponents{ count: 0, id: make([]int, g.V()), } visited := make([]bool, g.V()) visitors := &Visitors{ VertexPreOrder: func(v int) bool { scc.id[v] = scc.count return true }, } order := g.Reverse().Orders(DFS).ReversePostOrder() for _, v := range order { if !visited[v] { g.traverseDFS(v, visited, visitors) scc.count++ } } return scc } // ShortestPathTree calculates the shortest path tree of the graph. func (g *WeightedDirected) ShortestPathTree(s int) *ShortestPathTree { return newShortestPathTree(g, s) } // Graphviz returns a visualization of the graph in Graphviz format. func (g *WeightedDirected) Graphviz() string { graph := graphviz.NewGraph(true, true, "", "", "", graphviz.StyleSolid, graphviz.ShapeCircle) for i := 0; i < g.v; i++ { name := fmt.Sprintf("%d", i) graph.AddNode(graphviz.NewNode("", "", name, "", "", "", "", "")) } for v := range g.adj { for _, e := range g.adj[v] { from := fmt.Sprintf("%d", e.From()) to := fmt.Sprintf("%d", e.To()) weight := fmt.Sprintf("%f", e.Weight()) graph.AddEdge(graphviz.NewEdge(from, to, graphviz.EdgeTypeDirected, "", weight, "", "", "")) } } return graph.DotCode() }
graph/weighted_directed.go
0.839635
0.521898
weighted_directed.go
starcoder
package twittership import ( "fmt" "image" "image/color" "image/draw" "image/png" "os" ) type userImage struct { height int width int tileHeight int tileWidth int img *image.RGBA } // GameImage stores the current information for the game image type GameImage struct { fullImage *image.RGBA playerImage userImage enemyImage userImage } // NewGameImageFromGame will create a new game image from a game. There is no validation when converting // a game image to a game because the validation is assume to have happened when creating the game. func NewGameImageFromGame(g Game, h, w int, template string) (GameImage, error) { gi, err := newGameImage(h, w, template) if err != nil { return GameImage{}, fmt.Errorf("unable to create new game image: %w", err) } for _, playerShip := range g.playerShips { switch playerShip.shipType { case shipAircraftCarrier: gi.playerImage.placeAircraftCarrier(playerShip.x, playerShip.y, playerShip.direction) case shipBattleship: gi.playerImage.placeBattleship(playerShip.x, playerShip.y, playerShip.direction) case shipSubmarine: gi.playerImage.placeSubmarine(playerShip.x, playerShip.y, playerShip.direction) case shipCruiser: gi.playerImage.placeCruiser(playerShip.x, playerShip.y, playerShip.direction) case shipDestroyer: gi.playerImage.placeDestroyer(playerShip.x, playerShip.y, playerShip.direction) } } for _, playerVolley := range g.playerVolleys { switch playerVolley.volleyType { case hit: gi.enemyImage.drawHit(playerVolley.x, playerVolley.y) case miss: gi.enemyImage.drawMiss(playerVolley.x, playerVolley.y) } } for _, enemyVolley := range g.enemyVolleys { switch enemyVolley.volleyType { case hit: gi.playerImage.drawHit(enemyVolley.x, enemyVolley.y) case miss: gi.playerImage.drawMiss(enemyVolley.x, enemyVolley.y) } } return gi, nil } // NewGameImage will create a battleship gameboard with a background. The GameImage returned represents // both the player image, and the enemy image. func newGameImage(h, w int, template string) (GameImage, error) { totalW, totalH := w*2+80, h+90 gi := GameImage{ fullImage: image.NewRGBA(image.Rect(0, 0, totalW, totalH)), playerImage: userImage{ height: h, width: w, tileHeight: h / 10, tileWidth: w / 10, }, enemyImage: userImage{ height: h, width: w, tileHeight: h / 10, tileWidth: w / 10, }, } f, err := os.Open(template) if err != nil { return GameImage{}, fmt.Errorf("opening game_template: %w", err) } gameTemplateImg, _, err := image.Decode(f) if err != nil { return GameImage{}, fmt.Errorf("decoding game_template: %w", err) } draw.Draw(gi.fullImage, image.Rect(0, 0, totalW, totalH), gameTemplateImg, image.Pt(0, 0), draw.Over) gi.playerImage.img = gi.fullImage.SubImage(image.Rect(40, 90, w+80, totalH)).(*image.RGBA) gi.playerImage.drawBackground() gi.enemyImage.img = gi.fullImage.SubImage(image.Rect(w+80, 90, totalW, totalH)).(*image.RGBA) gi.enemyImage.drawBackground() return gi, nil } func (ui userImage) drawBackground() { for x := 0; x < ui.width; x++ { for y := 0; y < ui.height; y++ { if y%ui.tileHeight == 0 || x%ui.tileWidth == 0 { c := color.RGBA{ R: 0, G: 0, B: 0, A: 255, } ui.img.Set(ui.img.Rect.Min.X+x, ui.img.Rect.Min.Y+y, c) } else { c := color.RGBA{ R: 255, G: 255, B: 255, A: 255, } ui.img.Set(ui.img.Rect.Min.X+x, ui.img.Rect.Min.Y+y, c) } } } } // placeAircraftCarrier draws an aircraft carrier on the game board. Size 5 func (ui userImage) placeAircraftCarrier(x, y int, direction shipDirection) { ui.drawShip(x, y, 5, direction) } // placeBattleship draws a battleship on the game board. Size 4 func (ui userImage) placeBattleship(x, y int, direction shipDirection) { ui.drawShip(x, y, 4, direction) } // placeSubmarine draws a submarine on the game board. Size 3 func (ui userImage) placeSubmarine(x, y int, direction shipDirection) { ui.drawShip(x, y, 3, direction) } // placeCruiser draws a cruiser on the game board. Size 3 func (ui userImage) placeCruiser(x, y int, direction shipDirection) { ui.drawShip(x, y, 3, direction) } // placeDestroyer draws a destroyer on the game board. Size 2 func (ui userImage) placeDestroyer(x, y int, direction shipDirection) { ui.drawShip(x, y, 2, direction) } func (ui userImage) drawShip(x, y, width int, direction shipDirection) { startX := x * ui.tileWidth startY := y * ui.tileWidth endX := startX + width*ui.tileWidth endY := startY + 1*ui.tileHeight if direction == vertical { endX = startX + 1*ui.tileWidth endY = startY + width*ui.tileHeight } for x := 0; x < endX-startX; x++ { for y := 0; y < endY-startY; y++ { if y%ui.tileHeight != 0 && x%ui.tileWidth != 0 { ui.img.Set(ui.img.Rect.Min.X+startX+x, ui.img.Rect.Min.Y+startY+y, color.RGBA{ R: 49, G: 83, B: 123, A: 255, }) } } } } // DrawHit draws a hit mark on the game image func (ui userImage) drawHit(x, y int) { ui.drawVolley(x, y, hit) } // DrawMiss draws a miss mark on the game image func (ui userImage) drawMiss(x, y int) { ui.drawVolley(x, y, miss) } func (ui userImage) drawVolley(x, y int, volley volleyType) { startX := x * ui.tileWidth startY := y * ui.tileWidth endX := startX + ui.tileWidth endY := startY + ui.tileHeight bgColor := color.RGBA{ R: 200, G: 200, B: 200, A: 255, } if volley == hit { bgColor = color.RGBA{ R: 255, G: 54, B: 51, A: 255, } } xWidth := endX - startX yWidth := endY - startY for x := 0; x < xWidth; x++ { for y := 0; y < yWidth; y++ { if ui.isPointOnX(x, y, xWidth, yWidth) { ui.img.Set(ui.img.Rect.Min.X+startX+x, ui.img.Rect.Min.Y+startY+y, color.RGBA{ R: 100, G: 100, B: 100, A: 255, }) continue } if y%ui.tileHeight != 0 && x%ui.tileWidth != 0 { ui.img.Set(ui.img.Rect.Min.X+startX+x, ui.img.Rect.Min.Y+startY+y, bgColor) } } } } // isPointOnX is used when drawing the X image on the game board to indicate a volley. // It will determine the the current pixel is anywhere on the X and need to be filled in. func (ui userImage) isPointOnX(x, y, xWidth, yWidth int) bool { thickness := 3 // padding around the X axis on the X if x < 5 || x > xWidth-5 { return false } // padding around the Y axis on the Y if y < 5 || y > yWidth-5 { return false } // Is the point on the X if (x > y-thickness && x < y+thickness) || (x > yWidth-y-thickness && x < yWidth-y+thickness) { return true } return false } // WriteImage will write a PNG to the disk at the location provided by filename. func (gi GameImage) WriteImage(filename string) error { f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0600) if err != nil { return fmt.Errorf("unable to write game board image: %w", err) } defer f.Close() err = png.Encode(f, gi.fullImage) if err != nil { return fmt.Errorf("unable to encode game board image to png: %w", err) } return nil } // GetFullImage returns the image.RGBA fullImage. This is mostly used for decoupling the // tests from the implementation of the fullImage. func (gi GameImage) GetFullImage() *image.RGBA { return gi.fullImage }
image.go
0.640411
0.446676
image.go
starcoder
// Package aa provides common holiday definitions that are frequently used. package aa import ( "github.com/uchti/cal" "time" ) var ( // NewYear represents New Year's Day on 1-Jan NewYear = &cal.Holiday{ Name: "New Year's Day", Month: time.January, Day: 1, Func: cal.CalcDayOfMonth, } // Epiphany represents Epiphany on 6-Jan Epiphany = &cal.Holiday{ Name: "Epiphany", Month: time.January, Day: 6, Func: cal.CalcDayOfMonth, } // MaundyThursday represents Maundy Thursday - three days before Easter MaundyThursday = &cal.Holiday{ Name: "Maundy Thursday", Offset: -3, Func: cal.CalcEasterOffset, } // GoodFriday represents Good Friday - two days before Easter GoodFriday = &cal.Holiday{ Name: "Good Friday", Offset: -2, Func: cal.CalcEasterOffset, } // EasterMonday represents Easter Monday - the day after Easter EasterMonday = &cal.Holiday{ Name: "Easter Monday", Offset: 1, Func: cal.CalcEasterOffset, } // WorkersDay represents International Workers' Day on 1-May WorkersDay = &cal.Holiday{ Name: "International Workers' Day", Month: time.May, Day: 1, Func: cal.CalcDayOfMonth, } // AscensionDay represents Ascension Day on the 39th day after Easter AscensionDay = &cal.Holiday{ Name: "Ascension Day", Offset: 39, Func: cal.CalcEasterOffset, } // PentecostMonday represents Pentecost Monday on the day after Pentecost (50 days after Easter) PentecostMonday = &cal.Holiday{ Name: "Pentecost Monday", Offset: 50, Func: cal.CalcEasterOffset, } // CorpusChristi represents Corpus Christi on the 60th day after Easter CorpusChristi = &cal.Holiday{ Name: "Corpus Christi", Offset: 60, Func: cal.CalcEasterOffset, } // AssumptionOfMary represents Assumption of Mary on 15-Aug AssumptionOfMary = &cal.Holiday{ Name: "Assumption of Mary", Month: time.August, Day: 15, Func: cal.CalcDayOfMonth, } // AllSaintsDay represents All Saints' Day on 1-Nov AllSaintsDay = &cal.Holiday{ Name: "All Saints' Day", Month: time.November, Day: 1, Func: cal.CalcDayOfMonth, } // ArmisticeDay represents Armistice Day on 11-Nov ArmisticeDay = &cal.Holiday{ Name: "Armistice Day", Month: time.November, Day: 11, Func: cal.CalcDayOfMonth, } // ImmaculateConception represents Immaculate Conception on 8-Dec ImmaculateConception = &cal.Holiday{ Name: "Immaculate Conception", Month: time.December, Day: 8, Func: cal.CalcDayOfMonth, } // ChristmasDay represents Christmas Day on 25-Dec ChristmasDay = &cal.Holiday{ Name: "Christmas Day", Month: time.December, Day: 25, Func: cal.CalcDayOfMonth, } // ChristmasDay2 represents the day after Christmas (Boxing Day / St. Stephen's Day) on 26-Dec ChristmasDay2 = &cal.Holiday{ Name: "2nd Day of Christmas", Month: time.December, Day: 26, Func: cal.CalcDayOfMonth, } )
aa/aa_holidays.go
0.565179
0.528655
aa_holidays.go
starcoder
package main import ( "fmt" "os" "text/tabwriter" ) func main() { tw := tabwriter.NewWriter(os.Stdout, 1, 4, 1, ' ', 0) defer tw.Flush() zero := NewPolynomial(0, 0) p1 := NewPolynomial(4, 3) p2 := NewPolynomial(3, 2) p3 := NewPolynomial(1, 0) p4 := NewPolynomial(2, 1) p := p1.Add(p2).Add(p3).Add(p4) q1 := NewPolynomial(3, 2) q2 := NewPolynomial(5, 0) q := q1.Add(q2) r := p.Add(q) s := p.Mul(q) t := p.Compose(q) u := p.Sub(p) fmt.Fprintf(tw, "zero(x)\t=\t%v\n", zero) fmt.Fprintf(tw, "p(x)\t=\t%v\n", p) fmt.Fprintf(tw, "q(x)\t=\t%v\n", q) fmt.Fprintf(tw, "p(x) + q(x)\t=\t%v\n", r) fmt.Fprintf(tw, "p(x) * q(x)\t=\t%v\n", s) fmt.Fprintf(tw, "p(q(x))\t=\t%v\n", t) fmt.Fprintf(tw, "p(x) - p(x)\t=\t%v\n", u) fmt.Fprintf(tw, "0 - p(x)\t=\t%v\n", zero.Sub(p)) fmt.Fprintf(tw, "p(3)\t=\t%v\n", p.Eval(3)) fmt.Fprintf(tw, "p'(x)\t=\t%v\n", p.Differentiate()) fmt.Fprintf(tw, "p''(x)\t=\t%v\n", p.Differentiate().Differentiate()) fmt.Fprintf(tw, "\n") for i := 0; i <= 32; i++ { fmt.Fprintf(tw, "chebyshev1(%d)\t=\t%v\n", i, chebyshev1(i)) } fmt.Fprintf(tw, "\n") for i := 0; i <= 32; i++ { fmt.Fprintf(tw, "chebyshev2(%d)\t=\t%v\n", i, chebyshev2(i)) } } func chebyshev1(n int) *Polynomial { if n < 0 { return NewPolynomial(0, 0) } a := NewPolynomial(1, 0) b := NewPolynomial(1, 1) if n == 0 { return a } if n == 1 { return b } k := NewPolynomial(2, 1) for i := 2; i <= n; i++ { c := k.Mul(b).Sub(a) a, b = b, c } return b } func chebyshev2(n int) *Polynomial { if n < 0 { return NewPolynomial(0, 0) } a := NewPolynomial(1, 0) b := NewPolynomial(2, 1) if n == 0 { return a } if n == 1 { return b } k := NewPolynomial(2, 1) for i := 2; i <= n; i++ { c := k.Mul(b).Sub(a) a, b = b, c } return b } type Polynomial struct { coef []int degree int } func NewPolynomial(a, b int, args ...int) *Polynomial { if len(args)%2 != 0 { panic("invalid polynomial argument length") } n := b for i := 0; i < len(args); i += 2 { n = max(n, args[i+1]) } p := &Polynomial{} p.coef = make([]int, n+1) p.coef[b] = a for i := 0; i < len(args); i += 2 { p.coef[args[i+1]] = args[i] } p.reduce() return p } func (p *Polynomial) reduce() { p.degree = -1 for i := len(p.coef) - 1; i >= 0; i-- { if p.coef[i] != 0 { p.degree = i return } } } func (p *Polynomial) Degree() int { return p.degree } func (p *Polynomial) Add(q *Polynomial) *Polynomial { r := NewPolynomial(0, max(p.degree, q.degree)) for i := 0; i <= p.degree; i++ { r.coef[i] += p.coef[i] } for i := 0; i <= q.degree; i++ { r.coef[i] += q.coef[i] } r.reduce() return r } func (p *Polynomial) Sub(q *Polynomial) *Polynomial { r := NewPolynomial(0, max(p.degree, q.degree)) for i := 0; i <= p.degree; i++ { r.coef[i] += p.coef[i] } for i := 0; i <= q.degree; i++ { r.coef[i] -= q.coef[i] } r.reduce() return r } func (p *Polynomial) Mul(q *Polynomial) *Polynomial { r := NewPolynomial(0, p.degree+q.degree) for i := 0; i <= p.degree; i++ { for j := 0; j <= q.degree; j++ { r.coef[i+j] += p.coef[i] * q.coef[j] } } r.reduce() return r } func (p *Polynomial) Compose(q *Polynomial) *Polynomial { r := NewPolynomial(0, 0) for i := p.degree; i >= 0; i-- { t := NewPolynomial(p.coef[i], 0) r = t.Add(q.Mul(r)) } return r } func (p *Polynomial) Differentiate() *Polynomial { if p.degree == 0 { return NewPolynomial(0, 0) } q := NewPolynomial(0, p.degree-1) q.degree = p.degree - 1 for i := 0; i < p.degree; i++ { q.coef[i] = (i + 1) * p.coef[i+1] } return q } func (p *Polynomial) Eval(x int) int { v := 0 for i := p.degree; i >= 0; i-- { v = p.coef[i] + (x * v) } return v } func (p *Polynomial) Compare(q *Polynomial) int { if p.degree < q.degree { return -1 } if p.degree > q.degree { return 1 } for i := p.degree; i >= 0; i-- { if p.coef[i] < q.coef[i] { return -1 } if p.coef[i] > q.coef[i] { return 1 } } return 0 } func (p *Polynomial) String() string { if p.degree == -1 { return "0" } if p.degree == 0 { return fmt.Sprint(p.coef[0]) } if p.degree == 1 { s := fmt.Sprintf("%vx", p.coef[1]) if p.coef[0] != 0 { s += fmt.Sprintf(" + %v", p.coef[0]) } return s } s := fmt.Sprintf("%vx^%v", p.coef[p.degree], p.degree) for i := p.degree - 1; i >= 0; i-- { if p.coef[i] == 0 { continue } else if p.coef[i] > 0 { s += fmt.Sprintf(" + %v", p.coef[i]) } else if p.coef[i] < 0 { s += fmt.Sprintf(" - %v", -p.coef[i]) } if i == 1 { s += "x" } else if i > 1 { s += fmt.Sprintf("x^%v", i) } } return s } func min(a, b int) int { if a < b { return a } return b } func max(a, b int) int { if a > b { return a } return b }
math/chebysev-polynomial.go
0.542863
0.478224
chebysev-polynomial.go
starcoder
package jsonpath import ( "errors" "fmt" httputil "github.com/steinfletcher/apitest-jsonpath/http" "github.com/steinfletcher/apitest-jsonpath/jsonpath" "net/http" "reflect" regex "regexp" ) // Contains is a convenience function to assert that a jsonpath expression extracts a value in an array func Contains(expression string, expected interface{}) func(*http.Response, *http.Request) error { return func(res *http.Response, req *http.Request) error { return jsonpath.Contains(expression, expected, res.Body) } } // Equal is a convenience function to assert that a jsonpath expression extracts a value func Equal(expression string, expected interface{}) func(*http.Response, *http.Request) error { return func(res *http.Response, req *http.Request) error { return jsonpath.Equal(expression, expected, res.Body) } } // NotEqual is a function to check json path expression value is not equal to given value func NotEqual(expression string, expected interface{}) func(*http.Response, *http.Request) error { return func(res *http.Response, req *http.Request) error { return jsonpath.NotEqual(expression, expected, res.Body) } } // Len asserts that value is the expected length, determined by reflect.Len func Len(expression string, expectedLength int) func(*http.Response, *http.Request) error { return func(res *http.Response, req *http.Request) error { return jsonpath.Length(expression, expectedLength, res.Body) } } // GreaterThan asserts that value is greater than the given length, determined by reflect.Len func GreaterThan(expression string, minimumLength int) func(*http.Response, *http.Request) error { return func(res *http.Response, req *http.Request) error { return jsonpath.GreaterThan(expression, minimumLength, res.Body) } } // LessThan asserts that value is less than the given length, determined by reflect.Len func LessThan(expression string, maximumLength int) func(*http.Response, *http.Request) error { return func(res *http.Response, req *http.Request) error { return jsonpath.LessThan(expression, maximumLength, res.Body) } } // Present asserts that value returned by the expression is present func Present(expression string) func(*http.Response, *http.Request) error { return func(res *http.Response, req *http.Request) error { return jsonpath.Present(expression, res.Body) } } // NotPresent asserts that value returned by the expression is not present func NotPresent(expression string) func(*http.Response, *http.Request) error { return func(res *http.Response, req *http.Request) error { return jsonpath.NotPresent(expression, res.Body) } } // Matches asserts that the value matches the given regular expression func Matches(expression string, regexp string) func(*http.Response, *http.Request) error { return func(res *http.Response, req *http.Request) error { pattern, err := regex.Compile(regexp) if err != nil { return errors.New(fmt.Sprintf("invalid pattern: '%s'", regexp)) } value, _ := jsonpath.JsonPath(res.Body, expression) if value == nil { return errors.New(fmt.Sprintf("no match for pattern: '%s'", expression)) } kind := reflect.ValueOf(value).Kind() switch kind { case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64, reflect.String: if !pattern.Match([]byte(fmt.Sprintf("%v", value))) { return errors.New(fmt.Sprintf("value '%v' does not match pattern '%v'", value, regexp)) } return nil default: return errors.New(fmt.Sprintf("unable to match using type: %s", kind.String())) } } } // Chain creates a new assertion chain func Chain() *AssertionChain { return &AssertionChain{rootExpression: ""} } // Root creates a new assertion chain prefixed with the given expression func Root(expression string) *AssertionChain { return &AssertionChain{rootExpression: expression + "."} } // AssertionChain supports chaining assertions and root expressions type AssertionChain struct { rootExpression string assertions []func(*http.Response, *http.Request) error } // Equal adds an Equal assertion to the chain func (r *AssertionChain) Equal(expression string, expected interface{}) *AssertionChain { r.assertions = append(r.assertions, Equal(r.rootExpression+expression, expected)) return r } // NotEqual adds an NotEqual assertion to the chain func (r *AssertionChain) NotEqual(expression string, expected interface{}) *AssertionChain { r.assertions = append(r.assertions, NotEqual(r.rootExpression+expression, expected)) return r } // Contains adds an Contains assertion to the chain func (r *AssertionChain) Contains(expression string, expected interface{}) *AssertionChain { r.assertions = append(r.assertions, Contains(r.rootExpression+expression, expected)) return r } // Present adds an Present assertion to the chain func (r *AssertionChain) Present(expression string) *AssertionChain { r.assertions = append(r.assertions, Present(r.rootExpression+expression)) return r } // NotPresent adds an NotPresent assertion to the chain func (r *AssertionChain) NotPresent(expression string) *AssertionChain { r.assertions = append(r.assertions, NotPresent(r.rootExpression+expression)) return r } // Matches adds an Matches assertion to the chain func (r *AssertionChain) Matches(expression, regexp string) *AssertionChain { r.assertions = append(r.assertions, Matches(r.rootExpression+expression, regexp)) return r } // End returns an func(*http.Response, *http.Request) error which is a combination of the registered assertions func (r *AssertionChain) End() func(*http.Response, *http.Request) error { return func(res *http.Response, req *http.Request) error { for _, assertion := range r.assertions { if err := assertion(httputil.CopyResponse(res), httputil.CopyRequest(req)); err != nil { return err } } return nil } }
vendor/github.com/steinfletcher/apitest-jsonpath/jsonpath.go
0.682785
0.402157
jsonpath.go
starcoder
package vm import ( "reflect" "strings" ) type theArrayVectorType struct{} func (t *theArrayVectorType) String() string { return t.Name() } func (t *theArrayVectorType) Type() ValueType { return TypeType } func (t *theArrayVectorType) Unbox() interface{} { return reflect.TypeOf(t) } func (lt *theArrayVectorType) Name() string { return "let-go.lang.ArrayVector" } func (lt *theArrayVectorType) Box(bare interface{}) (Value, error) { arr, ok := bare.([]Value) if !ok { return NIL, NewTypeError(bare, "can't be boxed as", lt) } return ArrayVector(arr), nil } // ArrayVectorType is the type of ArrayVectors var ArrayVectorType *theArrayVectorType func init() { ArrayVectorType = &theArrayVectorType{} } // ArrayVector is boxed singly linked list that can hold other Values. type ArrayVector []Value // Type implements Value func (l ArrayVector) Type() ValueType { return ArrayVectorType } // Unbox implements Value func (l ArrayVector) Unbox() interface{} { return []Value(l) } // First implements Seq func (l ArrayVector) First() Value { if len(l) == 0 { return NIL } return l[0] } // More implements Seq func (l ArrayVector) More() Seq { if len(l) <= 1 { return EmptyList } newl, _ := ListType.Box([]Value(l[1:])) return newl.(*List) } // Next implements Seq func (l ArrayVector) Next() Seq { return l.More() } // Cons implements Seq func (l ArrayVector) Cons(val Value) Seq { newl, _ := ListType.Box(l[1:]) return newl.(*List).Cons(val) } // Count implements Collection func (l ArrayVector) Count() Value { return Int(len(l)) } func (l ArrayVector) RawCount() int { return len(l) } // Empty implements Collection func (l ArrayVector) Empty() Collection { return make(ArrayVector, 0) } func NewArrayVector(v []Value) Value { return ArrayVector(v) } func (l ArrayVector) String() string { b := &strings.Builder{} b.WriteRune('[') n := len(l) for i := range l { b.WriteString(l[i].String()) if i < n-1 { b.WriteRune(' ') } } b.WriteRune(']') return b.String() }
pkg/vm/vector.go
0.598312
0.492798
vector.go
starcoder
package aran // simple binary serach tree to find the maximum lower range of incoming key type node struct { root *node left *node right *node lowerRange uint32 idx []uint32 } func (n *node) insert(lowerRange, idx uint32) { if n.lowerRange == lowerRange { n.idx = append(n.idx, idx) return } if n.lowerRange > lowerRange { if n.left == nil { n.left = &node{ left: nil, right: nil, root: n, idx: []uint32{idx}, lowerRange: lowerRange, } return } n.left.insert(lowerRange, idx) return } if n.right == nil { n.right = &node{ left: nil, right: nil, root: n, idx: []uint32{idx}, lowerRange: lowerRange, } return } n.right.insert(lowerRange, idx) } func (n *node) rootNode() *node { return n.root } func (n *node) findLargestLowerRange(r uint32) *node { if n.lowerRange < r { if n.right != nil { return n.right.findLargestLowerRange(r) } } if n.lowerRange > r { if n.left != nil { return n.left.findLargestLowerRange(r) } } if n.lowerRange > r { return nil } return n } type tree struct { root *node } func (n *node) deleteTable(idx uint32) { i, ok := in_array(idx, n.idx) if ok { n.idx[i] = n.idx[len(n.idx)-1] n.idx = n.idx[:len(n.idx)-1] if len(n.idx) != 0 { return } if n.right != nil { n = n.right return } n = n.left return } if n.right != nil { n.right.deleteTable(idx) } if n.left != nil { n.left.deleteTable(idx) } } func newTree() *tree { return &tree{} } func (t *tree) insert(lowerRange, idx uint32) { if t.root == nil { t.root = &node{ lowerRange: lowerRange, idx: []uint32{idx}, left: nil, right: nil, root: t.root, } return } t.root.insert(lowerRange, idx) } func (t *tree) deleteTable(idx uint32) { i, ok := in_array(idx, t.root.idx) if ok { t.root.idx[i] = t.root.idx[len(t.root.idx)-1] t.root.idx = t.root.idx[:len(t.root.idx)-1] if len(t.root.idx) != 0 { return } if t.root.right != nil { t.root = t.root.right return } t.root = t.root.left return } if t.root.right != nil { t.root.right.deleteTable(idx) } if t.root.left != nil { t.root.left.deleteTable(idx) } } func (t *tree) findLargestLowerRange(r uint32) *node { if t.root == nil { return nil } if t.root.lowerRange < r { if t.root.right != nil { n := t.root.right.findLargestLowerRange(r) if n != nil { return n } } } if t.root.lowerRange > r { if t.root.left != nil { return t.root.left.findLargestLowerRange(r) } } if t.root.lowerRange > r { return nil } return t.root } func (t *tree) findAllLargestRange(r uint32) []*node { //TODO: it's a naive implementation. //It has to be changed to some stack based finding in the one iteration itself //instead of looping several time. //anyway I don't think so that It'll bring much performance that's why I kept it simple(Big lie I'm too lazy to do it) //It is good have that stack based finding nodes := []*node{} for { n := t.findLargestLowerRange(r) if n == nil { break } nodes = append(nodes, n) r = n.lowerRange - 1 } return nodes }
tree.go
0.614857
0.41941
tree.go
starcoder
package keras2go import ( "math" ) /** * Linear activation function. * y=x * * :param x: Array of input values. Gets overwritten by output. */ func K2c_linear(x []float64) { } /** * Exponential activation function. * y = exp(x) * * :param x: Array of input values. Gets overwritten by output. */ func K2c_exponential(x []float64) { for idx, value := range x { x[idx] = math.Exp(value) } } /** * ReLU activation function. * y = max(x,0) * * :param x: Array of input values. Gets overwritten by output. */ func K2c_relu(x []float64) { for idx, value := range x { if value <= 0 { x[idx] = 0 } } } /** * ReLU activation function. * y = {1 if x> 2.5} * {0.2*x+0.5 if -2.5<x< 2.5} * {0 if x<-2.5} * * :param x: Array of input values. Gets overwritten by output. */ func K2c_hard_sigmoid(x []float64) { for idx, value := range x { if value <= -2.5 { x[idx] = 0 } else if value >= 2.5 { x[idx] = 1 } else { x[idx] = 0.2*x[idx] + 0.5 } } } /** * Tanh activation function. * y = tanh(x) * * :param x: Array of input values. Gets overwritten by output. */ func K2c_tanh(x []float64) { for idx, value := range x { x[idx] = math.Tanh(value) } } /** * Sigmoid activation function. * y = 1/(1+exp(-x)) * * :param x: Array of input values. Gets overwritten by output. */ func K2c_sigmoid(x []float64) { for idx, value := range x { x[idx] = 1 / (1 + math.Exp(-value)) } } /** * Soft max activation function. * z[i] = exp(x[i]-max(x)) * y = z/sum(z) * * :param x: Array of input values. Gets overwritten by output. */ func K2c_softmax(x []float64) { xmax := x[0] var sum float64 for _, value := range x { if value > xmax { xmax = value } } for idx, value := range x { x[idx] = math.Exp(value - xmax) } for _, value := range x { sum += value } sum = 1 / sum for idx, value := range x { x[idx] = value * sum } } /** * Soft plus activation function. * y = ln(1+exp(x)) * * :param x: Array of input values. Gets overwritten by output. */ func K2c_softplus(x []float64) { for idx, value := range x { x[idx] = math.Log1p(math.Exp(value)) } } /** * Soft sign activation function. * y = x/(1+|x|) * * :param x: Array of input values. Gets overwritten by output. */ func K2c_softsign(x []float64) { for idx, value := range x { x[idx] = value / (1 + math.Abs(value)) } } /** * Leaky version of a Rectified Linear Unit. * It allows a small gradient when the unit is not active: * y = {alpha*x if x < 0} * {x if x >= 0} * * :param x: Array of input values. Gets overwritten by output. * :param alpha: slope of negative portion of activation curve. */ func k2c_LeakyReLU(x []float64, alpha float64) { for idx, value := range x { if value < 0 { x[idx] = alpha * value } } } /** * Parametric Rectified Linear Unit. * It allows a small gradient when the unit is not active: * y = {alpha*x if x < 0} * {x if x >= 0} * Where alpha is a learned Array with the same Shape as x. * * :param x: Array of input values. Gets overwritten by output. * :param alpha: slope of negative portion of activation curve for each unit. */ func k2c_PReLU(x []float64, alpha []float64) { for idx := range x { if x[idx] < 0 { x[idx] = x[idx] * alpha[idx] } } } /** * Exponential Linear Unit activation (ELU). * y = {alpha*(exp(x) - 1) if x < 0} * {x if x >= 0} * * :param x: Array of input values. Gets overwritten by output. * :param alpha: slope of negative portion of activation curve. */ func k2c_ELU(x []float64, alpha float64) { for idx, value := range x { if value < 0 { x[idx] = alpha * math.Expm1(value) } } } /** * Thresholded Rectified Linear Unit. * y = {x if x > theta} {0 if x <= theta} * * :param x: Array of input values. Gets overwritten by output. * :param theta: threshold for activation. */ func k2c_ThresholdedReLU(x []float64, theta float64) { for idx, value := range x { if value < theta { x[idx] = 0 } } } /** * Rectified Linear Unit activation function. * y = {max_value if x >= max_value} * {x if theta <= x < max_value} * {alpha*(x-theta) if x < theta} * * :param x: Array of input values. Gets overwritten by output. * :param max_value: maximum value for activated x. * :param alpha: slope of negative portion of activation curve. * :param theta: threshold for activation. */ func k2c_ReLU(x []float64, max_value float64, alpha float64, theta float64) { for idx, value := range x { if value >= max_value { x[idx] = max_value } else if value < theta { x[idx] = alpha * (value - theta) } } }
activations.go
0.777046
0.617138
activations.go
starcoder
package datadog import ( "encoding/json" ) // GetCreator returns the Creator field if non-nil, zero value otherwise. func (a *Alert) GetCreator() int { if a == nil || a.Creator == nil { return 0 } return *a.Creator } // GetOkCreator returns a tuple with the Creator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetCreatorOk() (int, bool) { if a == nil || a.Creator == nil { return 0, false } return *a.Creator, true } // HasCreator returns a boolean if a field has been set. func (a *Alert) HasCreator() bool { if a != nil && a.Creator != nil { return true } return false } // SetCreator allocates a new a.Creator and returns the pointer to it. func (a *Alert) SetCreator(v int) { a.Creator = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (a *Alert) GetId() int { if a == nil || a.Id == nil { return 0 } return *a.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetIdOk() (int, bool) { if a == nil || a.Id == nil { return 0, false } return *a.Id, true } // HasId returns a boolean if a field has been set. func (a *Alert) HasId() bool { if a != nil && a.Id != nil { return true } return false } // SetId allocates a new a.Id and returns the pointer to it. func (a *Alert) SetId(v int) { a.Id = &v } // GetMessage returns the Message field if non-nil, zero value otherwise. func (a *Alert) GetMessage() string { if a == nil || a.Message == nil { return "" } return *a.Message } // GetOkMessage returns a tuple with the Message field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetMessageOk() (string, bool) { if a == nil || a.Message == nil { return "", false } return *a.Message, true } // HasMessage returns a boolean if a field has been set. func (a *Alert) HasMessage() bool { if a != nil && a.Message != nil { return true } return false } // SetMessage allocates a new a.Message and returns the pointer to it. func (a *Alert) SetMessage(v string) { a.Message = &v } // GetName returns the Name field if non-nil, zero value otherwise. func (a *Alert) GetName() string { if a == nil || a.Name == nil { return "" } return *a.Name } // GetOkName returns a tuple with the Name field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetNameOk() (string, bool) { if a == nil || a.Name == nil { return "", false } return *a.Name, true } // HasName returns a boolean if a field has been set. func (a *Alert) HasName() bool { if a != nil && a.Name != nil { return true } return false } // SetName allocates a new a.Name and returns the pointer to it. func (a *Alert) SetName(v string) { a.Name = &v } // GetNotifyNoData returns the NotifyNoData field if non-nil, zero value otherwise. func (a *Alert) GetNotifyNoData() bool { if a == nil || a.NotifyNoData == nil { return false } return *a.NotifyNoData } // GetOkNotifyNoData returns a tuple with the NotifyNoData field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetNotifyNoDataOk() (bool, bool) { if a == nil || a.NotifyNoData == nil { return false, false } return *a.NotifyNoData, true } // HasNotifyNoData returns a boolean if a field has been set. func (a *Alert) HasNotifyNoData() bool { if a != nil && a.NotifyNoData != nil { return true } return false } // SetNotifyNoData allocates a new a.NotifyNoData and returns the pointer to it. func (a *Alert) SetNotifyNoData(v bool) { a.NotifyNoData = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (a *Alert) GetQuery() string { if a == nil || a.Query == nil { return "" } return *a.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetQueryOk() (string, bool) { if a == nil || a.Query == nil { return "", false } return *a.Query, true } // HasQuery returns a boolean if a field has been set. func (a *Alert) HasQuery() bool { if a != nil && a.Query != nil { return true } return false } // SetQuery allocates a new a.Query and returns the pointer to it. func (a *Alert) SetQuery(v string) { a.Query = &v } // GetSilenced returns the Silenced field if non-nil, zero value otherwise. func (a *Alert) GetSilenced() bool { if a == nil || a.Silenced == nil { return false } return *a.Silenced } // GetOkSilenced returns a tuple with the Silenced field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetSilencedOk() (bool, bool) { if a == nil || a.Silenced == nil { return false, false } return *a.Silenced, true } // HasSilenced returns a boolean if a field has been set. func (a *Alert) HasSilenced() bool { if a != nil && a.Silenced != nil { return true } return false } // SetSilenced allocates a new a.Silenced and returns the pointer to it. func (a *Alert) SetSilenced(v bool) { a.Silenced = &v } // GetState returns the State field if non-nil, zero value otherwise. func (a *Alert) GetState() string { if a == nil || a.State == nil { return "" } return *a.State } // GetOkState returns a tuple with the State field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *Alert) GetStateOk() (string, bool) { if a == nil || a.State == nil { return "", false } return *a.State, true } // HasState returns a boolean if a field has been set. func (a *Alert) HasState() bool { if a != nil && a.State != nil { return true } return false } // SetState allocates a new a.State and returns the pointer to it. func (a *Alert) SetState(v string) { a.State = &v } // GetAddTimeframe returns the AddTimeframe field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetAddTimeframe() bool { if a == nil || a.AddTimeframe == nil { return false } return *a.AddTimeframe } // GetOkAddTimeframe returns a tuple with the AddTimeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetAddTimeframeOk() (bool, bool) { if a == nil || a.AddTimeframe == nil { return false, false } return *a.AddTimeframe, true } // HasAddTimeframe returns a boolean if a field has been set. func (a *AlertGraphWidget) HasAddTimeframe() bool { if a != nil && a.AddTimeframe != nil { return true } return false } // SetAddTimeframe allocates a new a.AddTimeframe and returns the pointer to it. func (a *AlertGraphWidget) SetAddTimeframe(v bool) { a.AddTimeframe = &v } // GetAlertId returns the AlertId field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetAlertId() int { if a == nil || a.AlertId == nil { return 0 } return *a.AlertId } // GetOkAlertId returns a tuple with the AlertId field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetAlertIdOk() (int, bool) { if a == nil || a.AlertId == nil { return 0, false } return *a.AlertId, true } // HasAlertId returns a boolean if a field has been set. func (a *AlertGraphWidget) HasAlertId() bool { if a != nil && a.AlertId != nil { return true } return false } // SetAlertId allocates a new a.AlertId and returns the pointer to it. func (a *AlertGraphWidget) SetAlertId(v int) { a.AlertId = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetHeight() int { if a == nil || a.Height == nil { return 0 } return *a.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetHeightOk() (int, bool) { if a == nil || a.Height == nil { return 0, false } return *a.Height, true } // HasHeight returns a boolean if a field has been set. func (a *AlertGraphWidget) HasHeight() bool { if a != nil && a.Height != nil { return true } return false } // SetHeight allocates a new a.Height and returns the pointer to it. func (a *AlertGraphWidget) SetHeight(v int) { a.Height = &v } // GetTimeframe returns the Timeframe field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetTimeframe() string { if a == nil || a.Timeframe == nil { return "" } return *a.Timeframe } // GetOkTimeframe returns a tuple with the Timeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetTimeframeOk() (string, bool) { if a == nil || a.Timeframe == nil { return "", false } return *a.Timeframe, true } // HasTimeframe returns a boolean if a field has been set. func (a *AlertGraphWidget) HasTimeframe() bool { if a != nil && a.Timeframe != nil { return true } return false } // SetTimeframe allocates a new a.Timeframe and returns the pointer to it. func (a *AlertGraphWidget) SetTimeframe(v string) { a.Timeframe = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetTitle() bool { if a == nil || a.Title == nil { return false } return *a.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetTitleOk() (bool, bool) { if a == nil || a.Title == nil { return false, false } return *a.Title, true } // HasTitle returns a boolean if a field has been set. func (a *AlertGraphWidget) HasTitle() bool { if a != nil && a.Title != nil { return true } return false } // SetTitle allocates a new a.Title and returns the pointer to it. func (a *AlertGraphWidget) SetTitle(v bool) { a.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetTitleAlign() string { if a == nil || a.TitleAlign == nil { return "" } return *a.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetTitleAlignOk() (string, bool) { if a == nil || a.TitleAlign == nil { return "", false } return *a.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (a *AlertGraphWidget) HasTitleAlign() bool { if a != nil && a.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new a.TitleAlign and returns the pointer to it. func (a *AlertGraphWidget) SetTitleAlign(v string) { a.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetTitleSize() int { if a == nil || a.TitleSize == nil { return 0 } return *a.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetTitleSizeOk() (int, bool) { if a == nil || a.TitleSize == nil { return 0, false } return *a.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (a *AlertGraphWidget) HasTitleSize() bool { if a != nil && a.TitleSize != nil { return true } return false } // SetTitleSize allocates a new a.TitleSize and returns the pointer to it. func (a *AlertGraphWidget) SetTitleSize(v int) { a.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetTitleText() string { if a == nil || a.TitleText == nil { return "" } return *a.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetTitleTextOk() (string, bool) { if a == nil || a.TitleText == nil { return "", false } return *a.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (a *AlertGraphWidget) HasTitleText() bool { if a != nil && a.TitleText != nil { return true } return false } // SetTitleText allocates a new a.TitleText and returns the pointer to it. func (a *AlertGraphWidget) SetTitleText(v string) { a.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetType() string { if a == nil || a.Type == nil { return "" } return *a.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetTypeOk() (string, bool) { if a == nil || a.Type == nil { return "", false } return *a.Type, true } // HasType returns a boolean if a field has been set. func (a *AlertGraphWidget) HasType() bool { if a != nil && a.Type != nil { return true } return false } // SetType allocates a new a.Type and returns the pointer to it. func (a *AlertGraphWidget) SetType(v string) { a.Type = &v } // GetVizType returns the VizType field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetVizType() string { if a == nil || a.VizType == nil { return "" } return *a.VizType } // GetOkVizType returns a tuple with the VizType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetVizTypeOk() (string, bool) { if a == nil || a.VizType == nil { return "", false } return *a.VizType, true } // HasVizType returns a boolean if a field has been set. func (a *AlertGraphWidget) HasVizType() bool { if a != nil && a.VizType != nil { return true } return false } // SetVizType allocates a new a.VizType and returns the pointer to it. func (a *AlertGraphWidget) SetVizType(v string) { a.VizType = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetWidth() int { if a == nil || a.Width == nil { return 0 } return *a.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetWidthOk() (int, bool) { if a == nil || a.Width == nil { return 0, false } return *a.Width, true } // HasWidth returns a boolean if a field has been set. func (a *AlertGraphWidget) HasWidth() bool { if a != nil && a.Width != nil { return true } return false } // SetWidth allocates a new a.Width and returns the pointer to it. func (a *AlertGraphWidget) SetWidth(v int) { a.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetX() int { if a == nil || a.X == nil { return 0 } return *a.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetXOk() (int, bool) { if a == nil || a.X == nil { return 0, false } return *a.X, true } // HasX returns a boolean if a field has been set. func (a *AlertGraphWidget) HasX() bool { if a != nil && a.X != nil { return true } return false } // SetX allocates a new a.X and returns the pointer to it. func (a *AlertGraphWidget) SetX(v int) { a.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (a *AlertGraphWidget) GetY() int { if a == nil || a.Y == nil { return 0 } return *a.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertGraphWidget) GetYOk() (int, bool) { if a == nil || a.Y == nil { return 0, false } return *a.Y, true } // HasY returns a boolean if a field has been set. func (a *AlertGraphWidget) HasY() bool { if a != nil && a.Y != nil { return true } return false } // SetY allocates a new a.Y and returns the pointer to it. func (a *AlertGraphWidget) SetY(v int) { a.Y = &v } // GetAddTimeframe returns the AddTimeframe field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetAddTimeframe() bool { if a == nil || a.AddTimeframe == nil { return false } return *a.AddTimeframe } // GetOkAddTimeframe returns a tuple with the AddTimeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetAddTimeframeOk() (bool, bool) { if a == nil || a.AddTimeframe == nil { return false, false } return *a.AddTimeframe, true } // HasAddTimeframe returns a boolean if a field has been set. func (a *AlertValueWidget) HasAddTimeframe() bool { if a != nil && a.AddTimeframe != nil { return true } return false } // SetAddTimeframe allocates a new a.AddTimeframe and returns the pointer to it. func (a *AlertValueWidget) SetAddTimeframe(v bool) { a.AddTimeframe = &v } // GetAlertId returns the AlertId field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetAlertId() int { if a == nil || a.AlertId == nil { return 0 } return *a.AlertId } // GetOkAlertId returns a tuple with the AlertId field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetAlertIdOk() (int, bool) { if a == nil || a.AlertId == nil { return 0, false } return *a.AlertId, true } // HasAlertId returns a boolean if a field has been set. func (a *AlertValueWidget) HasAlertId() bool { if a != nil && a.AlertId != nil { return true } return false } // SetAlertId allocates a new a.AlertId and returns the pointer to it. func (a *AlertValueWidget) SetAlertId(v int) { a.AlertId = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetHeight() int { if a == nil || a.Height == nil { return 0 } return *a.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetHeightOk() (int, bool) { if a == nil || a.Height == nil { return 0, false } return *a.Height, true } // HasHeight returns a boolean if a field has been set. func (a *AlertValueWidget) HasHeight() bool { if a != nil && a.Height != nil { return true } return false } // SetHeight allocates a new a.Height and returns the pointer to it. func (a *AlertValueWidget) SetHeight(v int) { a.Height = &v } // GetPrecision returns the Precision field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetPrecision() int { if a == nil || a.Precision == nil { return 0 } return *a.Precision } // GetOkPrecision returns a tuple with the Precision field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetPrecisionOk() (int, bool) { if a == nil || a.Precision == nil { return 0, false } return *a.Precision, true } // HasPrecision returns a boolean if a field has been set. func (a *AlertValueWidget) HasPrecision() bool { if a != nil && a.Precision != nil { return true } return false } // SetPrecision allocates a new a.Precision and returns the pointer to it. func (a *AlertValueWidget) SetPrecision(v int) { a.Precision = &v } // GetTextAlign returns the TextAlign field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetTextAlign() string { if a == nil || a.TextAlign == nil { return "" } return *a.TextAlign } // GetOkTextAlign returns a tuple with the TextAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetTextAlignOk() (string, bool) { if a == nil || a.TextAlign == nil { return "", false } return *a.TextAlign, true } // HasTextAlign returns a boolean if a field has been set. func (a *AlertValueWidget) HasTextAlign() bool { if a != nil && a.TextAlign != nil { return true } return false } // SetTextAlign allocates a new a.TextAlign and returns the pointer to it. func (a *AlertValueWidget) SetTextAlign(v string) { a.TextAlign = &v } // GetTextSize returns the TextSize field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetTextSize() string { if a == nil || a.TextSize == nil { return "" } return *a.TextSize } // GetOkTextSize returns a tuple with the TextSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetTextSizeOk() (string, bool) { if a == nil || a.TextSize == nil { return "", false } return *a.TextSize, true } // HasTextSize returns a boolean if a field has been set. func (a *AlertValueWidget) HasTextSize() bool { if a != nil && a.TextSize != nil { return true } return false } // SetTextSize allocates a new a.TextSize and returns the pointer to it. func (a *AlertValueWidget) SetTextSize(v string) { a.TextSize = &v } // GetTimeframe returns the Timeframe field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetTimeframe() string { if a == nil || a.Timeframe == nil { return "" } return *a.Timeframe } // GetOkTimeframe returns a tuple with the Timeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetTimeframeOk() (string, bool) { if a == nil || a.Timeframe == nil { return "", false } return *a.Timeframe, true } // HasTimeframe returns a boolean if a field has been set. func (a *AlertValueWidget) HasTimeframe() bool { if a != nil && a.Timeframe != nil { return true } return false } // SetTimeframe allocates a new a.Timeframe and returns the pointer to it. func (a *AlertValueWidget) SetTimeframe(v string) { a.Timeframe = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetTitle() bool { if a == nil || a.Title == nil { return false } return *a.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetTitleOk() (bool, bool) { if a == nil || a.Title == nil { return false, false } return *a.Title, true } // HasTitle returns a boolean if a field has been set. func (a *AlertValueWidget) HasTitle() bool { if a != nil && a.Title != nil { return true } return false } // SetTitle allocates a new a.Title and returns the pointer to it. func (a *AlertValueWidget) SetTitle(v bool) { a.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetTitleAlign() string { if a == nil || a.TitleAlign == nil { return "" } return *a.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetTitleAlignOk() (string, bool) { if a == nil || a.TitleAlign == nil { return "", false } return *a.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (a *AlertValueWidget) HasTitleAlign() bool { if a != nil && a.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new a.TitleAlign and returns the pointer to it. func (a *AlertValueWidget) SetTitleAlign(v string) { a.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetTitleSize() int { if a == nil || a.TitleSize == nil { return 0 } return *a.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetTitleSizeOk() (int, bool) { if a == nil || a.TitleSize == nil { return 0, false } return *a.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (a *AlertValueWidget) HasTitleSize() bool { if a != nil && a.TitleSize != nil { return true } return false } // SetTitleSize allocates a new a.TitleSize and returns the pointer to it. func (a *AlertValueWidget) SetTitleSize(v int) { a.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetTitleText() string { if a == nil || a.TitleText == nil { return "" } return *a.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetTitleTextOk() (string, bool) { if a == nil || a.TitleText == nil { return "", false } return *a.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (a *AlertValueWidget) HasTitleText() bool { if a != nil && a.TitleText != nil { return true } return false } // SetTitleText allocates a new a.TitleText and returns the pointer to it. func (a *AlertValueWidget) SetTitleText(v string) { a.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetType() string { if a == nil || a.Type == nil { return "" } return *a.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetTypeOk() (string, bool) { if a == nil || a.Type == nil { return "", false } return *a.Type, true } // HasType returns a boolean if a field has been set. func (a *AlertValueWidget) HasType() bool { if a != nil && a.Type != nil { return true } return false } // SetType allocates a new a.Type and returns the pointer to it. func (a *AlertValueWidget) SetType(v string) { a.Type = &v } // GetUnit returns the Unit field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetUnit() string { if a == nil || a.Unit == nil { return "" } return *a.Unit } // GetOkUnit returns a tuple with the Unit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetUnitOk() (string, bool) { if a == nil || a.Unit == nil { return "", false } return *a.Unit, true } // HasUnit returns a boolean if a field has been set. func (a *AlertValueWidget) HasUnit() bool { if a != nil && a.Unit != nil { return true } return false } // SetUnit allocates a new a.Unit and returns the pointer to it. func (a *AlertValueWidget) SetUnit(v string) { a.Unit = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetWidth() int { if a == nil || a.Width == nil { return 0 } return *a.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetWidthOk() (int, bool) { if a == nil || a.Width == nil { return 0, false } return *a.Width, true } // HasWidth returns a boolean if a field has been set. func (a *AlertValueWidget) HasWidth() bool { if a != nil && a.Width != nil { return true } return false } // SetWidth allocates a new a.Width and returns the pointer to it. func (a *AlertValueWidget) SetWidth(v int) { a.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetX() int { if a == nil || a.X == nil { return 0 } return *a.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetXOk() (int, bool) { if a == nil || a.X == nil { return 0, false } return *a.X, true } // HasX returns a boolean if a field has been set. func (a *AlertValueWidget) HasX() bool { if a != nil && a.X != nil { return true } return false } // SetX allocates a new a.X and returns the pointer to it. func (a *AlertValueWidget) SetX(v int) { a.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (a *AlertValueWidget) GetY() int { if a == nil || a.Y == nil { return 0 } return *a.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (a *AlertValueWidget) GetYOk() (int, bool) { if a == nil || a.Y == nil { return 0, false } return *a.Y, true } // HasY returns a boolean if a field has been set. func (a *AlertValueWidget) HasY() bool { if a != nil && a.Y != nil { return true } return false } // SetY allocates a new a.Y and returns the pointer to it. func (a *AlertValueWidget) SetY(v int) { a.Y = &v } // GetAggregator returns the Aggregator field if non-nil, zero value otherwise. func (c *ChangeWidget) GetAggregator() string { if c == nil || c.Aggregator == nil { return "" } return *c.Aggregator } // GetOkAggregator returns a tuple with the Aggregator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChangeWidget) GetAggregatorOk() (string, bool) { if c == nil || c.Aggregator == nil { return "", false } return *c.Aggregator, true } // HasAggregator returns a boolean if a field has been set. func (c *ChangeWidget) HasAggregator() bool { if c != nil && c.Aggregator != nil { return true } return false } // SetAggregator allocates a new c.Aggregator and returns the pointer to it. func (c *ChangeWidget) SetAggregator(v string) { c.Aggregator = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (c *ChangeWidget) GetHeight() int { if c == nil || c.Height == nil { return 0 } return *c.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChangeWidget) GetHeightOk() (int, bool) { if c == nil || c.Height == nil { return 0, false } return *c.Height, true } // HasHeight returns a boolean if a field has been set. func (c *ChangeWidget) HasHeight() bool { if c != nil && c.Height != nil { return true } return false } // SetHeight allocates a new c.Height and returns the pointer to it. func (c *ChangeWidget) SetHeight(v int) { c.Height = &v } // GetTileDef returns the TileDef field if non-nil, zero value otherwise. func (c *ChangeWidget) GetTileDef() TileDef { if c == nil || c.TileDef == nil { return TileDef{} } return *c.TileDef } // GetOkTileDef returns a tuple with the TileDef field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChangeWidget) GetTileDefOk() (TileDef, bool) { if c == nil || c.TileDef == nil { return TileDef{}, false } return *c.TileDef, true } // HasTileDef returns a boolean if a field has been set. func (c *ChangeWidget) HasTileDef() bool { if c != nil && c.TileDef != nil { return true } return false } // SetTileDef allocates a new c.TileDef and returns the pointer to it. func (c *ChangeWidget) SetTileDef(v TileDef) { c.TileDef = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (c *ChangeWidget) GetTitle() bool { if c == nil || c.Title == nil { return false } return *c.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChangeWidget) GetTitleOk() (bool, bool) { if c == nil || c.Title == nil { return false, false } return *c.Title, true } // HasTitle returns a boolean if a field has been set. func (c *ChangeWidget) HasTitle() bool { if c != nil && c.Title != nil { return true } return false } // SetTitle allocates a new c.Title and returns the pointer to it. func (c *ChangeWidget) SetTitle(v bool) { c.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (c *ChangeWidget) GetTitleAlign() string { if c == nil || c.TitleAlign == nil { return "" } return *c.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChangeWidget) GetTitleAlignOk() (string, bool) { if c == nil || c.TitleAlign == nil { return "", false } return *c.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (c *ChangeWidget) HasTitleAlign() bool { if c != nil && c.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new c.TitleAlign and returns the pointer to it. func (c *ChangeWidget) SetTitleAlign(v string) { c.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (c *ChangeWidget) GetTitleSize() int { if c == nil || c.TitleSize == nil { return 0 } return *c.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChangeWidget) GetTitleSizeOk() (int, bool) { if c == nil || c.TitleSize == nil { return 0, false } return *c.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (c *ChangeWidget) HasTitleSize() bool { if c != nil && c.TitleSize != nil { return true } return false } // SetTitleSize allocates a new c.TitleSize and returns the pointer to it. func (c *ChangeWidget) SetTitleSize(v int) { c.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (c *ChangeWidget) GetTitleText() string { if c == nil || c.TitleText == nil { return "" } return *c.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChangeWidget) GetTitleTextOk() (string, bool) { if c == nil || c.TitleText == nil { return "", false } return *c.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (c *ChangeWidget) HasTitleText() bool { if c != nil && c.TitleText != nil { return true } return false } // SetTitleText allocates a new c.TitleText and returns the pointer to it. func (c *ChangeWidget) SetTitleText(v string) { c.TitleText = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (c *ChangeWidget) GetWidth() int { if c == nil || c.Width == nil { return 0 } return *c.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChangeWidget) GetWidthOk() (int, bool) { if c == nil || c.Width == nil { return 0, false } return *c.Width, true } // HasWidth returns a boolean if a field has been set. func (c *ChangeWidget) HasWidth() bool { if c != nil && c.Width != nil { return true } return false } // SetWidth allocates a new c.Width and returns the pointer to it. func (c *ChangeWidget) SetWidth(v int) { c.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (c *ChangeWidget) GetX() int { if c == nil || c.X == nil { return 0 } return *c.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChangeWidget) GetXOk() (int, bool) { if c == nil || c.X == nil { return 0, false } return *c.X, true } // HasX returns a boolean if a field has been set. func (c *ChangeWidget) HasX() bool { if c != nil && c.X != nil { return true } return false } // SetX allocates a new c.X and returns the pointer to it. func (c *ChangeWidget) SetX(v int) { c.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (c *ChangeWidget) GetY() int { if c == nil || c.Y == nil { return 0 } return *c.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ChangeWidget) GetYOk() (int, bool) { if c == nil || c.Y == nil { return 0, false } return *c.Y, true } // HasY returns a boolean if a field has been set. func (c *ChangeWidget) HasY() bool { if c != nil && c.Y != nil { return true } return false } // SetY allocates a new c.Y and returns the pointer to it. func (c *ChangeWidget) SetY(v int) { c.Y = &v } // GetCheck returns the Check field if non-nil, zero value otherwise. func (c *Check) GetCheck() string { if c == nil || c.Check == nil { return "" } return *c.Check } // GetOkCheck returns a tuple with the Check field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Check) GetCheckOk() (string, bool) { if c == nil || c.Check == nil { return "", false } return *c.Check, true } // HasCheck returns a boolean if a field has been set. func (c *Check) HasCheck() bool { if c != nil && c.Check != nil { return true } return false } // SetCheck allocates a new c.Check and returns the pointer to it. func (c *Check) SetCheck(v string) { c.Check = &v } // GetHostName returns the HostName field if non-nil, zero value otherwise. func (c *Check) GetHostName() string { if c == nil || c.HostName == nil { return "" } return *c.HostName } // GetOkHostName returns a tuple with the HostName field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Check) GetHostNameOk() (string, bool) { if c == nil || c.HostName == nil { return "", false } return *c.HostName, true } // HasHostName returns a boolean if a field has been set. func (c *Check) HasHostName() bool { if c != nil && c.HostName != nil { return true } return false } // SetHostName allocates a new c.HostName and returns the pointer to it. func (c *Check) SetHostName(v string) { c.HostName = &v } // GetMessage returns the Message field if non-nil, zero value otherwise. func (c *Check) GetMessage() string { if c == nil || c.Message == nil { return "" } return *c.Message } // GetOkMessage returns a tuple with the Message field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Check) GetMessageOk() (string, bool) { if c == nil || c.Message == nil { return "", false } return *c.Message, true } // HasMessage returns a boolean if a field has been set. func (c *Check) HasMessage() bool { if c != nil && c.Message != nil { return true } return false } // SetMessage allocates a new c.Message and returns the pointer to it. func (c *Check) SetMessage(v string) { c.Message = &v } // GetStatus returns the Status field if non-nil, zero value otherwise. func (c *Check) GetStatus() Status { if c == nil || c.Status == nil { return 0 } return *c.Status } // GetOkStatus returns a tuple with the Status field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Check) GetStatusOk() (Status, bool) { if c == nil || c.Status == nil { return 0, false } return *c.Status, true } // HasStatus returns a boolean if a field has been set. func (c *Check) HasStatus() bool { if c != nil && c.Status != nil { return true } return false } // SetStatus allocates a new c.Status and returns the pointer to it. func (c *Check) SetStatus(v Status) { c.Status = &v } // GetTimestamp returns the Timestamp field if non-nil, zero value otherwise. func (c *Check) GetTimestamp() string { if c == nil || c.Timestamp == nil { return "" } return *c.Timestamp } // GetOkTimestamp returns a tuple with the Timestamp field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Check) GetTimestampOk() (string, bool) { if c == nil || c.Timestamp == nil { return "", false } return *c.Timestamp, true } // HasTimestamp returns a boolean if a field has been set. func (c *Check) HasTimestamp() bool { if c != nil && c.Timestamp != nil { return true } return false } // SetTimestamp allocates a new c.Timestamp and returns the pointer to it. func (c *Check) SetTimestamp(v string) { c.Timestamp = &v } // GetCheck returns the Check field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetCheck() string { if c == nil || c.Check == nil { return "" } return *c.Check } // GetOkCheck returns a tuple with the Check field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetCheckOk() (string, bool) { if c == nil || c.Check == nil { return "", false } return *c.Check, true } // HasCheck returns a boolean if a field has been set. func (c *CheckStatusWidget) HasCheck() bool { if c != nil && c.Check != nil { return true } return false } // SetCheck allocates a new c.Check and returns the pointer to it. func (c *CheckStatusWidget) SetCheck(v string) { c.Check = &v } // GetGroup returns the Group field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetGroup() string { if c == nil || c.Group == nil { return "" } return *c.Group } // GetOkGroup returns a tuple with the Group field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetGroupOk() (string, bool) { if c == nil || c.Group == nil { return "", false } return *c.Group, true } // HasGroup returns a boolean if a field has been set. func (c *CheckStatusWidget) HasGroup() bool { if c != nil && c.Group != nil { return true } return false } // SetGroup allocates a new c.Group and returns the pointer to it. func (c *CheckStatusWidget) SetGroup(v string) { c.Group = &v } // GetGrouping returns the Grouping field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetGrouping() string { if c == nil || c.Grouping == nil { return "" } return *c.Grouping } // GetOkGrouping returns a tuple with the Grouping field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetGroupingOk() (string, bool) { if c == nil || c.Grouping == nil { return "", false } return *c.Grouping, true } // HasGrouping returns a boolean if a field has been set. func (c *CheckStatusWidget) HasGrouping() bool { if c != nil && c.Grouping != nil { return true } return false } // SetGrouping allocates a new c.Grouping and returns the pointer to it. func (c *CheckStatusWidget) SetGrouping(v string) { c.Grouping = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetHeight() int { if c == nil || c.Height == nil { return 0 } return *c.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetHeightOk() (int, bool) { if c == nil || c.Height == nil { return 0, false } return *c.Height, true } // HasHeight returns a boolean if a field has been set. func (c *CheckStatusWidget) HasHeight() bool { if c != nil && c.Height != nil { return true } return false } // SetHeight allocates a new c.Height and returns the pointer to it. func (c *CheckStatusWidget) SetHeight(v int) { c.Height = &v } // GetTags returns the Tags field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetTags() string { if c == nil || c.Tags == nil { return "" } return *c.Tags } // GetOkTags returns a tuple with the Tags field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetTagsOk() (string, bool) { if c == nil || c.Tags == nil { return "", false } return *c.Tags, true } // HasTags returns a boolean if a field has been set. func (c *CheckStatusWidget) HasTags() bool { if c != nil && c.Tags != nil { return true } return false } // SetTags allocates a new c.Tags and returns the pointer to it. func (c *CheckStatusWidget) SetTags(v string) { c.Tags = &v } // GetTextAlign returns the TextAlign field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetTextAlign() string { if c == nil || c.TextAlign == nil { return "" } return *c.TextAlign } // GetOkTextAlign returns a tuple with the TextAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetTextAlignOk() (string, bool) { if c == nil || c.TextAlign == nil { return "", false } return *c.TextAlign, true } // HasTextAlign returns a boolean if a field has been set. func (c *CheckStatusWidget) HasTextAlign() bool { if c != nil && c.TextAlign != nil { return true } return false } // SetTextAlign allocates a new c.TextAlign and returns the pointer to it. func (c *CheckStatusWidget) SetTextAlign(v string) { c.TextAlign = &v } // GetTextSize returns the TextSize field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetTextSize() string { if c == nil || c.TextSize == nil { return "" } return *c.TextSize } // GetOkTextSize returns a tuple with the TextSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetTextSizeOk() (string, bool) { if c == nil || c.TextSize == nil { return "", false } return *c.TextSize, true } // HasTextSize returns a boolean if a field has been set. func (c *CheckStatusWidget) HasTextSize() bool { if c != nil && c.TextSize != nil { return true } return false } // SetTextSize allocates a new c.TextSize and returns the pointer to it. func (c *CheckStatusWidget) SetTextSize(v string) { c.TextSize = &v } // GetTimeframe returns the Timeframe field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetTimeframe() string { if c == nil || c.Timeframe == nil { return "" } return *c.Timeframe } // GetOkTimeframe returns a tuple with the Timeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetTimeframeOk() (string, bool) { if c == nil || c.Timeframe == nil { return "", false } return *c.Timeframe, true } // HasTimeframe returns a boolean if a field has been set. func (c *CheckStatusWidget) HasTimeframe() bool { if c != nil && c.Timeframe != nil { return true } return false } // SetTimeframe allocates a new c.Timeframe and returns the pointer to it. func (c *CheckStatusWidget) SetTimeframe(v string) { c.Timeframe = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetTitle() bool { if c == nil || c.Title == nil { return false } return *c.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetTitleOk() (bool, bool) { if c == nil || c.Title == nil { return false, false } return *c.Title, true } // HasTitle returns a boolean if a field has been set. func (c *CheckStatusWidget) HasTitle() bool { if c != nil && c.Title != nil { return true } return false } // SetTitle allocates a new c.Title and returns the pointer to it. func (c *CheckStatusWidget) SetTitle(v bool) { c.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetTitleAlign() string { if c == nil || c.TitleAlign == nil { return "" } return *c.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetTitleAlignOk() (string, bool) { if c == nil || c.TitleAlign == nil { return "", false } return *c.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (c *CheckStatusWidget) HasTitleAlign() bool { if c != nil && c.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new c.TitleAlign and returns the pointer to it. func (c *CheckStatusWidget) SetTitleAlign(v string) { c.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetTitleSize() int { if c == nil || c.TitleSize == nil { return 0 } return *c.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetTitleSizeOk() (int, bool) { if c == nil || c.TitleSize == nil { return 0, false } return *c.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (c *CheckStatusWidget) HasTitleSize() bool { if c != nil && c.TitleSize != nil { return true } return false } // SetTitleSize allocates a new c.TitleSize and returns the pointer to it. func (c *CheckStatusWidget) SetTitleSize(v int) { c.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetTitleText() string { if c == nil || c.TitleText == nil { return "" } return *c.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetTitleTextOk() (string, bool) { if c == nil || c.TitleText == nil { return "", false } return *c.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (c *CheckStatusWidget) HasTitleText() bool { if c != nil && c.TitleText != nil { return true } return false } // SetTitleText allocates a new c.TitleText and returns the pointer to it. func (c *CheckStatusWidget) SetTitleText(v string) { c.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetType() string { if c == nil || c.Type == nil { return "" } return *c.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetTypeOk() (string, bool) { if c == nil || c.Type == nil { return "", false } return *c.Type, true } // HasType returns a boolean if a field has been set. func (c *CheckStatusWidget) HasType() bool { if c != nil && c.Type != nil { return true } return false } // SetType allocates a new c.Type and returns the pointer to it. func (c *CheckStatusWidget) SetType(v string) { c.Type = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetWidth() int { if c == nil || c.Width == nil { return 0 } return *c.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetWidthOk() (int, bool) { if c == nil || c.Width == nil { return 0, false } return *c.Width, true } // HasWidth returns a boolean if a field has been set. func (c *CheckStatusWidget) HasWidth() bool { if c != nil && c.Width != nil { return true } return false } // SetWidth allocates a new c.Width and returns the pointer to it. func (c *CheckStatusWidget) SetWidth(v int) { c.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetX() int { if c == nil || c.X == nil { return 0 } return *c.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetXOk() (int, bool) { if c == nil || c.X == nil { return 0, false } return *c.X, true } // HasX returns a boolean if a field has been set. func (c *CheckStatusWidget) HasX() bool { if c != nil && c.X != nil { return true } return false } // SetX allocates a new c.X and returns the pointer to it. func (c *CheckStatusWidget) SetX(v int) { c.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (c *CheckStatusWidget) GetY() int { if c == nil || c.Y == nil { return 0 } return *c.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *CheckStatusWidget) GetYOk() (int, bool) { if c == nil || c.Y == nil { return 0, false } return *c.Y, true } // HasY returns a boolean if a field has been set. func (c *CheckStatusWidget) HasY() bool { if c != nil && c.Y != nil { return true } return false } // SetY allocates a new c.Y and returns the pointer to it. func (c *CheckStatusWidget) SetY(v int) { c.Y = &v } // GetHandle returns the Handle field if non-nil, zero value otherwise. func (c *Comment) GetHandle() string { if c == nil || c.Handle == nil { return "" } return *c.Handle } // GetOkHandle returns a tuple with the Handle field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Comment) GetHandleOk() (string, bool) { if c == nil || c.Handle == nil { return "", false } return *c.Handle, true } // HasHandle returns a boolean if a field has been set. func (c *Comment) HasHandle() bool { if c != nil && c.Handle != nil { return true } return false } // SetHandle allocates a new c.Handle and returns the pointer to it. func (c *Comment) SetHandle(v string) { c.Handle = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (c *Comment) GetId() int { if c == nil || c.Id == nil { return 0 } return *c.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Comment) GetIdOk() (int, bool) { if c == nil || c.Id == nil { return 0, false } return *c.Id, true } // HasId returns a boolean if a field has been set. func (c *Comment) HasId() bool { if c != nil && c.Id != nil { return true } return false } // SetId allocates a new c.Id and returns the pointer to it. func (c *Comment) SetId(v int) { c.Id = &v } // GetMessage returns the Message field if non-nil, zero value otherwise. func (c *Comment) GetMessage() string { if c == nil || c.Message == nil { return "" } return *c.Message } // GetOkMessage returns a tuple with the Message field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Comment) GetMessageOk() (string, bool) { if c == nil || c.Message == nil { return "", false } return *c.Message, true } // HasMessage returns a boolean if a field has been set. func (c *Comment) HasMessage() bool { if c != nil && c.Message != nil { return true } return false } // SetMessage allocates a new c.Message and returns the pointer to it. func (c *Comment) SetMessage(v string) { c.Message = &v } // GetRelatedId returns the RelatedId field if non-nil, zero value otherwise. func (c *Comment) GetRelatedId() int { if c == nil || c.RelatedId == nil { return 0 } return *c.RelatedId } // GetOkRelatedId returns a tuple with the RelatedId field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Comment) GetRelatedIdOk() (int, bool) { if c == nil || c.RelatedId == nil { return 0, false } return *c.RelatedId, true } // HasRelatedId returns a boolean if a field has been set. func (c *Comment) HasRelatedId() bool { if c != nil && c.RelatedId != nil { return true } return false } // SetRelatedId allocates a new c.RelatedId and returns the pointer to it. func (c *Comment) SetRelatedId(v int) { c.RelatedId = &v } // GetResource returns the Resource field if non-nil, zero value otherwise. func (c *Comment) GetResource() string { if c == nil || c.Resource == nil { return "" } return *c.Resource } // GetOkResource returns a tuple with the Resource field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Comment) GetResourceOk() (string, bool) { if c == nil || c.Resource == nil { return "", false } return *c.Resource, true } // HasResource returns a boolean if a field has been set. func (c *Comment) HasResource() bool { if c != nil && c.Resource != nil { return true } return false } // SetResource allocates a new c.Resource and returns the pointer to it. func (c *Comment) SetResource(v string) { c.Resource = &v } // GetUrl returns the Url field if non-nil, zero value otherwise. func (c *Comment) GetUrl() string { if c == nil || c.Url == nil { return "" } return *c.Url } // GetOkUrl returns a tuple with the Url field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Comment) GetUrlOk() (string, bool) { if c == nil || c.Url == nil { return "", false } return *c.Url, true } // HasUrl returns a boolean if a field has been set. func (c *Comment) HasUrl() bool { if c != nil && c.Url != nil { return true } return false } // SetUrl allocates a new c.Url and returns the pointer to it. func (c *Comment) SetUrl(v string) { c.Url = &v } // GetColor returns the Color field if non-nil, zero value otherwise. func (c *ConditionalFormat) GetColor() string { if c == nil || c.Color == nil { return "" } return *c.Color } // GetOkColor returns a tuple with the Color field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ConditionalFormat) GetColorOk() (string, bool) { if c == nil || c.Color == nil { return "", false } return *c.Color, true } // HasColor returns a boolean if a field has been set. func (c *ConditionalFormat) HasColor() bool { if c != nil && c.Color != nil { return true } return false } // SetColor allocates a new c.Color and returns the pointer to it. func (c *ConditionalFormat) SetColor(v string) { c.Color = &v } // GetComparator returns the Comparator field if non-nil, zero value otherwise. func (c *ConditionalFormat) GetComparator() string { if c == nil || c.Comparator == nil { return "" } return *c.Comparator } // GetOkComparator returns a tuple with the Comparator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ConditionalFormat) GetComparatorOk() (string, bool) { if c == nil || c.Comparator == nil { return "", false } return *c.Comparator, true } // HasComparator returns a boolean if a field has been set. func (c *ConditionalFormat) HasComparator() bool { if c != nil && c.Comparator != nil { return true } return false } // SetComparator allocates a new c.Comparator and returns the pointer to it. func (c *ConditionalFormat) SetComparator(v string) { c.Comparator = &v } // GetInverted returns the Inverted field if non-nil, zero value otherwise. func (c *ConditionalFormat) GetInverted() bool { if c == nil || c.Inverted == nil { return false } return *c.Inverted } // GetOkInverted returns a tuple with the Inverted field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ConditionalFormat) GetInvertedOk() (bool, bool) { if c == nil || c.Inverted == nil { return false, false } return *c.Inverted, true } // HasInverted returns a boolean if a field has been set. func (c *ConditionalFormat) HasInverted() bool { if c != nil && c.Inverted != nil { return true } return false } // SetInverted allocates a new c.Inverted and returns the pointer to it. func (c *ConditionalFormat) SetInverted(v bool) { c.Inverted = &v } // GetValue returns the Value field if non-nil, zero value otherwise. func (c *ConditionalFormat) GetValue() int { if c == nil || c.Value == nil { return 0 } return *c.Value } // GetOkValue returns a tuple with the Value field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *ConditionalFormat) GetValueOk() (int, bool) { if c == nil || c.Value == nil { return 0, false } return *c.Value, true } // HasValue returns a boolean if a field has been set. func (c *ConditionalFormat) HasValue() bool { if c != nil && c.Value != nil { return true } return false } // SetValue allocates a new c.Value and returns the pointer to it. func (c *ConditionalFormat) SetValue(v int) { c.Value = &v } // GetEmail returns the Email field if non-nil, zero value otherwise. func (c *Creator) GetEmail() string { if c == nil || c.Email == nil { return "" } return *c.Email } // GetOkEmail returns a tuple with the Email field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Creator) GetEmailOk() (string, bool) { if c == nil || c.Email == nil { return "", false } return *c.Email, true } // HasEmail returns a boolean if a field has been set. func (c *Creator) HasEmail() bool { if c != nil && c.Email != nil { return true } return false } // SetEmail allocates a new c.Email and returns the pointer to it. func (c *Creator) SetEmail(v string) { c.Email = &v } // GetHandle returns the Handle field if non-nil, zero value otherwise. func (c *Creator) GetHandle() string { if c == nil || c.Handle == nil { return "" } return *c.Handle } // GetOkHandle returns a tuple with the Handle field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Creator) GetHandleOk() (string, bool) { if c == nil || c.Handle == nil { return "", false } return *c.Handle, true } // HasHandle returns a boolean if a field has been set. func (c *Creator) HasHandle() bool { if c != nil && c.Handle != nil { return true } return false } // SetHandle allocates a new c.Handle and returns the pointer to it. func (c *Creator) SetHandle(v string) { c.Handle = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (c *Creator) GetId() int { if c == nil || c.Id == nil { return 0 } return *c.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Creator) GetIdOk() (int, bool) { if c == nil || c.Id == nil { return 0, false } return *c.Id, true } // HasId returns a boolean if a field has been set. func (c *Creator) HasId() bool { if c != nil && c.Id != nil { return true } return false } // SetId allocates a new c.Id and returns the pointer to it. func (c *Creator) SetId(v int) { c.Id = &v } // GetName returns the Name field if non-nil, zero value otherwise. func (c *Creator) GetName() string { if c == nil || c.Name == nil { return "" } return *c.Name } // GetOkName returns a tuple with the Name field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (c *Creator) GetNameOk() (string, bool) { if c == nil || c.Name == nil { return "", false } return *c.Name, true } // HasName returns a boolean if a field has been set. func (c *Creator) HasName() bool { if c != nil && c.Name != nil { return true } return false } // SetName allocates a new c.Name and returns the pointer to it. func (c *Creator) SetName(v string) { c.Name = &v } // GetDescription returns the Description field if non-nil, zero value otherwise. func (d *Dashboard) GetDescription() string { if d == nil || d.Description == nil { return "" } return *d.Description } // GetOkDescription returns a tuple with the Description field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Dashboard) GetDescriptionOk() (string, bool) { if d == nil || d.Description == nil { return "", false } return *d.Description, true } // HasDescription returns a boolean if a field has been set. func (d *Dashboard) HasDescription() bool { if d != nil && d.Description != nil { return true } return false } // SetDescription allocates a new d.Description and returns the pointer to it. func (d *Dashboard) SetDescription(v string) { d.Description = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (d *Dashboard) GetId() int { if d == nil || d.Id == nil { return 0 } return *d.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Dashboard) GetIdOk() (int, bool) { if d == nil || d.Id == nil { return 0, false } return *d.Id, true } // HasId returns a boolean if a field has been set. func (d *Dashboard) HasId() bool { if d != nil && d.Id != nil { return true } return false } // SetId allocates a new d.Id and returns the pointer to it. func (d *Dashboard) SetId(v int) { d.Id = &v } // GetReadOnly returns the ReadOnly field if non-nil, zero value otherwise. func (d *Dashboard) GetReadOnly() bool { if d == nil || d.ReadOnly == nil { return false } return *d.ReadOnly } // GetOkReadOnly returns a tuple with the ReadOnly field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Dashboard) GetReadOnlyOk() (bool, bool) { if d == nil || d.ReadOnly == nil { return false, false } return *d.ReadOnly, true } // HasReadOnly returns a boolean if a field has been set. func (d *Dashboard) HasReadOnly() bool { if d != nil && d.ReadOnly != nil { return true } return false } // SetReadOnly allocates a new d.ReadOnly and returns the pointer to it. func (d *Dashboard) SetReadOnly(v bool) { d.ReadOnly = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (d *Dashboard) GetTitle() string { if d == nil || d.Title == nil { return "" } return *d.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Dashboard) GetTitleOk() (string, bool) { if d == nil || d.Title == nil { return "", false } return *d.Title, true } // HasTitle returns a boolean if a field has been set. func (d *Dashboard) HasTitle() bool { if d != nil && d.Title != nil { return true } return false } // SetTitle allocates a new d.Title and returns the pointer to it. func (d *Dashboard) SetTitle(v string) { d.Title = &v } // GetComparator returns the Comparator field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetComparator() string { if d == nil || d.Comparator == nil { return "" } return *d.Comparator } // GetOkComparator returns a tuple with the Comparator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetComparatorOk() (string, bool) { if d == nil || d.Comparator == nil { return "", false } return *d.Comparator, true } // HasComparator returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasComparator() bool { if d != nil && d.Comparator != nil { return true } return false } // SetComparator allocates a new d.Comparator and returns the pointer to it. func (d *DashboardConditionalFormat) SetComparator(v string) { d.Comparator = &v } // GetCustomBgColor returns the CustomBgColor field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetCustomBgColor() string { if d == nil || d.CustomBgColor == nil { return "" } return *d.CustomBgColor } // GetOkCustomBgColor returns a tuple with the CustomBgColor field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetCustomBgColorOk() (string, bool) { if d == nil || d.CustomBgColor == nil { return "", false } return *d.CustomBgColor, true } // HasCustomBgColor returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasCustomBgColor() bool { if d != nil && d.CustomBgColor != nil { return true } return false } // SetCustomBgColor allocates a new d.CustomBgColor and returns the pointer to it. func (d *DashboardConditionalFormat) SetCustomBgColor(v string) { d.CustomBgColor = &v } // GetCustomFgColor returns the CustomFgColor field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetCustomFgColor() string { if d == nil || d.CustomFgColor == nil { return "" } return *d.CustomFgColor } // GetOkCustomFgColor returns a tuple with the CustomFgColor field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetCustomFgColorOk() (string, bool) { if d == nil || d.CustomFgColor == nil { return "", false } return *d.CustomFgColor, true } // HasCustomFgColor returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasCustomFgColor() bool { if d != nil && d.CustomFgColor != nil { return true } return false } // SetCustomFgColor allocates a new d.CustomFgColor and returns the pointer to it. func (d *DashboardConditionalFormat) SetCustomFgColor(v string) { d.CustomFgColor = &v } // GetCustomImageUrl returns the CustomImageUrl field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetCustomImageUrl() string { if d == nil || d.CustomImageUrl == nil { return "" } return *d.CustomImageUrl } // GetOkCustomImageUrl returns a tuple with the CustomImageUrl field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetCustomImageUrlOk() (string, bool) { if d == nil || d.CustomImageUrl == nil { return "", false } return *d.CustomImageUrl, true } // HasCustomImageUrl returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasCustomImageUrl() bool { if d != nil && d.CustomImageUrl != nil { return true } return false } // SetCustomImageUrl allocates a new d.CustomImageUrl and returns the pointer to it. func (d *DashboardConditionalFormat) SetCustomImageUrl(v string) { d.CustomImageUrl = &v } // GetInverted returns the Inverted field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetInverted() bool { if d == nil || d.Inverted == nil { return false } return *d.Inverted } // GetOkInverted returns a tuple with the Inverted field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetInvertedOk() (bool, bool) { if d == nil || d.Inverted == nil { return false, false } return *d.Inverted, true } // HasInverted returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasInverted() bool { if d != nil && d.Inverted != nil { return true } return false } // SetInverted allocates a new d.Inverted and returns the pointer to it. func (d *DashboardConditionalFormat) SetInverted(v bool) { d.Inverted = &v } // GetPalette returns the Palette field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetPalette() string { if d == nil || d.Palette == nil { return "" } return *d.Palette } // GetOkPalette returns a tuple with the Palette field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetPaletteOk() (string, bool) { if d == nil || d.Palette == nil { return "", false } return *d.Palette, true } // HasPalette returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasPalette() bool { if d != nil && d.Palette != nil { return true } return false } // SetPalette allocates a new d.Palette and returns the pointer to it. func (d *DashboardConditionalFormat) SetPalette(v string) { d.Palette = &v } // GetValue returns the Value field if non-nil, zero value otherwise. func (d *DashboardConditionalFormat) GetValue() json.Number { if d == nil || d.Value == nil { return "" } return *d.Value } // GetOkValue returns a tuple with the Value field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardConditionalFormat) GetValueOk() (json.Number, bool) { if d == nil || d.Value == nil { return "", false } return *d.Value, true } // HasValue returns a boolean if a field has been set. func (d *DashboardConditionalFormat) HasValue() bool { if d != nil && d.Value != nil { return true } return false } // SetValue allocates a new d.Value and returns the pointer to it. func (d *DashboardConditionalFormat) SetValue(v json.Number) { d.Value = &v } // GetDescription returns the Description field if non-nil, zero value otherwise. func (d *DashboardLite) GetDescription() string { if d == nil || d.Description == nil { return "" } return *d.Description } // GetOkDescription returns a tuple with the Description field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardLite) GetDescriptionOk() (string, bool) { if d == nil || d.Description == nil { return "", false } return *d.Description, true } // HasDescription returns a boolean if a field has been set. func (d *DashboardLite) HasDescription() bool { if d != nil && d.Description != nil { return true } return false } // SetDescription allocates a new d.Description and returns the pointer to it. func (d *DashboardLite) SetDescription(v string) { d.Description = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (d *DashboardLite) GetId() int { if d == nil || d.Id == nil { return 0 } return *d.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardLite) GetIdOk() (int, bool) { if d == nil || d.Id == nil { return 0, false } return *d.Id, true } // HasId returns a boolean if a field has been set. func (d *DashboardLite) HasId() bool { if d != nil && d.Id != nil { return true } return false } // SetId allocates a new d.Id and returns the pointer to it. func (d *DashboardLite) SetId(v int) { d.Id = &v } // GetResource returns the Resource field if non-nil, zero value otherwise. func (d *DashboardLite) GetResource() string { if d == nil || d.Resource == nil { return "" } return *d.Resource } // GetOkResource returns a tuple with the Resource field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardLite) GetResourceOk() (string, bool) { if d == nil || d.Resource == nil { return "", false } return *d.Resource, true } // HasResource returns a boolean if a field has been set. func (d *DashboardLite) HasResource() bool { if d != nil && d.Resource != nil { return true } return false } // SetResource allocates a new d.Resource and returns the pointer to it. func (d *DashboardLite) SetResource(v string) { d.Resource = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (d *DashboardLite) GetTitle() string { if d == nil || d.Title == nil { return "" } return *d.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *DashboardLite) GetTitleOk() (string, bool) { if d == nil || d.Title == nil { return "", false } return *d.Title, true } // HasTitle returns a boolean if a field has been set. func (d *DashboardLite) HasTitle() bool { if d != nil && d.Title != nil { return true } return false } // SetTitle allocates a new d.Title and returns the pointer to it. func (d *DashboardLite) SetTitle(v string) { d.Title = &v } // GetActive returns the Active field if non-nil, zero value otherwise. func (d *Downtime) GetActive() bool { if d == nil || d.Active == nil { return false } return *d.Active } // GetOkActive returns a tuple with the Active field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetActiveOk() (bool, bool) { if d == nil || d.Active == nil { return false, false } return *d.Active, true } // HasActive returns a boolean if a field has been set. func (d *Downtime) HasActive() bool { if d != nil && d.Active != nil { return true } return false } // SetActive allocates a new d.Active and returns the pointer to it. func (d *Downtime) SetActive(v bool) { d.Active = &v } // GetCanceled returns the Canceled field if non-nil, zero value otherwise. func (d *Downtime) GetCanceled() int { if d == nil || d.Canceled == nil { return 0 } return *d.Canceled } // GetOkCanceled returns a tuple with the Canceled field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetCanceledOk() (int, bool) { if d == nil || d.Canceled == nil { return 0, false } return *d.Canceled, true } // HasCanceled returns a boolean if a field has been set. func (d *Downtime) HasCanceled() bool { if d != nil && d.Canceled != nil { return true } return false } // SetCanceled allocates a new d.Canceled and returns the pointer to it. func (d *Downtime) SetCanceled(v int) { d.Canceled = &v } // GetDisabled returns the Disabled field if non-nil, zero value otherwise. func (d *Downtime) GetDisabled() bool { if d == nil || d.Disabled == nil { return false } return *d.Disabled } // GetOkDisabled returns a tuple with the Disabled field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetDisabledOk() (bool, bool) { if d == nil || d.Disabled == nil { return false, false } return *d.Disabled, true } // HasDisabled returns a boolean if a field has been set. func (d *Downtime) HasDisabled() bool { if d != nil && d.Disabled != nil { return true } return false } // SetDisabled allocates a new d.Disabled and returns the pointer to it. func (d *Downtime) SetDisabled(v bool) { d.Disabled = &v } // GetEnd returns the End field if non-nil, zero value otherwise. func (d *Downtime) GetEnd() int { if d == nil || d.End == nil { return 0 } return *d.End } // GetOkEnd returns a tuple with the End field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetEndOk() (int, bool) { if d == nil || d.End == nil { return 0, false } return *d.End, true } // HasEnd returns a boolean if a field has been set. func (d *Downtime) HasEnd() bool { if d != nil && d.End != nil { return true } return false } // SetEnd allocates a new d.End and returns the pointer to it. func (d *Downtime) SetEnd(v int) { d.End = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (d *Downtime) GetId() int { if d == nil || d.Id == nil { return 0 } return *d.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetIdOk() (int, bool) { if d == nil || d.Id == nil { return 0, false } return *d.Id, true } // HasId returns a boolean if a field has been set. func (d *Downtime) HasId() bool { if d != nil && d.Id != nil { return true } return false } // SetId allocates a new d.Id and returns the pointer to it. func (d *Downtime) SetId(v int) { d.Id = &v } // GetMessage returns the Message field if non-nil, zero value otherwise. func (d *Downtime) GetMessage() string { if d == nil || d.Message == nil { return "" } return *d.Message } // GetOkMessage returns a tuple with the Message field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetMessageOk() (string, bool) { if d == nil || d.Message == nil { return "", false } return *d.Message, true } // HasMessage returns a boolean if a field has been set. func (d *Downtime) HasMessage() bool { if d != nil && d.Message != nil { return true } return false } // SetMessage allocates a new d.Message and returns the pointer to it. func (d *Downtime) SetMessage(v string) { d.Message = &v } // GetMonitorId returns the MonitorId field if non-nil, zero value otherwise. func (d *Downtime) GetMonitorId() int { if d == nil || d.MonitorId == nil { return 0 } return *d.MonitorId } // GetOkMonitorId returns a tuple with the MonitorId field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetMonitorIdOk() (int, bool) { if d == nil || d.MonitorId == nil { return 0, false } return *d.MonitorId, true } // HasMonitorId returns a boolean if a field has been set. func (d *Downtime) HasMonitorId() bool { if d != nil && d.MonitorId != nil { return true } return false } // SetMonitorId allocates a new d.MonitorId and returns the pointer to it. func (d *Downtime) SetMonitorId(v int) { d.MonitorId = &v } // GetRecurrence returns the Recurrence field if non-nil, zero value otherwise. func (d *Downtime) GetRecurrence() Recurrence { if d == nil || d.Recurrence == nil { return Recurrence{} } return *d.Recurrence } // GetOkRecurrence returns a tuple with the Recurrence field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetRecurrenceOk() (Recurrence, bool) { if d == nil || d.Recurrence == nil { return Recurrence{}, false } return *d.Recurrence, true } // HasRecurrence returns a boolean if a field has been set. func (d *Downtime) HasRecurrence() bool { if d != nil && d.Recurrence != nil { return true } return false } // SetRecurrence allocates a new d.Recurrence and returns the pointer to it. func (d *Downtime) SetRecurrence(v Recurrence) { d.Recurrence = &v } // GetStart returns the Start field if non-nil, zero value otherwise. func (d *Downtime) GetStart() int { if d == nil || d.Start == nil { return 0 } return *d.Start } // GetOkStart returns a tuple with the Start field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (d *Downtime) GetStartOk() (int, bool) { if d == nil || d.Start == nil { return 0, false } return *d.Start, true } // HasStart returns a boolean if a field has been set. func (d *Downtime) HasStart() bool { if d != nil && d.Start != nil { return true } return false } // SetStart allocates a new d.Start and returns the pointer to it. func (d *Downtime) SetStart(v int) { d.Start = &v } // GetAggregation returns the Aggregation field if non-nil, zero value otherwise. func (e *Event) GetAggregation() string { if e == nil || e.Aggregation == nil { return "" } return *e.Aggregation } // GetOkAggregation returns a tuple with the Aggregation field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetAggregationOk() (string, bool) { if e == nil || e.Aggregation == nil { return "", false } return *e.Aggregation, true } // HasAggregation returns a boolean if a field has been set. func (e *Event) HasAggregation() bool { if e != nil && e.Aggregation != nil { return true } return false } // SetAggregation allocates a new e.Aggregation and returns the pointer to it. func (e *Event) SetAggregation(v string) { e.Aggregation = &v } // GetAlertType returns the AlertType field if non-nil, zero value otherwise. func (e *Event) GetAlertType() string { if e == nil || e.AlertType == nil { return "" } return *e.AlertType } // GetOkAlertType returns a tuple with the AlertType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetAlertTypeOk() (string, bool) { if e == nil || e.AlertType == nil { return "", false } return *e.AlertType, true } // HasAlertType returns a boolean if a field has been set. func (e *Event) HasAlertType() bool { if e != nil && e.AlertType != nil { return true } return false } // SetAlertType allocates a new e.AlertType and returns the pointer to it. func (e *Event) SetAlertType(v string) { e.AlertType = &v } // GetEventType returns the EventType field if non-nil, zero value otherwise. func (e *Event) GetEventType() string { if e == nil || e.EventType == nil { return "" } return *e.EventType } // GetOkEventType returns a tuple with the EventType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetEventTypeOk() (string, bool) { if e == nil || e.EventType == nil { return "", false } return *e.EventType, true } // HasEventType returns a boolean if a field has been set. func (e *Event) HasEventType() bool { if e != nil && e.EventType != nil { return true } return false } // SetEventType allocates a new e.EventType and returns the pointer to it. func (e *Event) SetEventType(v string) { e.EventType = &v } // GetHost returns the Host field if non-nil, zero value otherwise. func (e *Event) GetHost() string { if e == nil || e.Host == nil { return "" } return *e.Host } // GetOkHost returns a tuple with the Host field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetHostOk() (string, bool) { if e == nil || e.Host == nil { return "", false } return *e.Host, true } // HasHost returns a boolean if a field has been set. func (e *Event) HasHost() bool { if e != nil && e.Host != nil { return true } return false } // SetHost allocates a new e.Host and returns the pointer to it. func (e *Event) SetHost(v string) { e.Host = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (e *Event) GetId() int { if e == nil || e.Id == nil { return 0 } return *e.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetIdOk() (int, bool) { if e == nil || e.Id == nil { return 0, false } return *e.Id, true } // HasId returns a boolean if a field has been set. func (e *Event) HasId() bool { if e != nil && e.Id != nil { return true } return false } // SetId allocates a new e.Id and returns the pointer to it. func (e *Event) SetId(v int) { e.Id = &v } // GetPriority returns the Priority field if non-nil, zero value otherwise. func (e *Event) GetPriority() string { if e == nil || e.Priority == nil { return "" } return *e.Priority } // GetOkPriority returns a tuple with the Priority field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetPriorityOk() (string, bool) { if e == nil || e.Priority == nil { return "", false } return *e.Priority, true } // HasPriority returns a boolean if a field has been set. func (e *Event) HasPriority() bool { if e != nil && e.Priority != nil { return true } return false } // SetPriority allocates a new e.Priority and returns the pointer to it. func (e *Event) SetPriority(v string) { e.Priority = &v } // GetResource returns the Resource field if non-nil, zero value otherwise. func (e *Event) GetResource() string { if e == nil || e.Resource == nil { return "" } return *e.Resource } // GetOkResource returns a tuple with the Resource field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetResourceOk() (string, bool) { if e == nil || e.Resource == nil { return "", false } return *e.Resource, true } // HasResource returns a boolean if a field has been set. func (e *Event) HasResource() bool { if e != nil && e.Resource != nil { return true } return false } // SetResource allocates a new e.Resource and returns the pointer to it. func (e *Event) SetResource(v string) { e.Resource = &v } // GetSourceType returns the SourceType field if non-nil, zero value otherwise. func (e *Event) GetSourceType() string { if e == nil || e.SourceType == nil { return "" } return *e.SourceType } // GetOkSourceType returns a tuple with the SourceType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetSourceTypeOk() (string, bool) { if e == nil || e.SourceType == nil { return "", false } return *e.SourceType, true } // HasSourceType returns a boolean if a field has been set. func (e *Event) HasSourceType() bool { if e != nil && e.SourceType != nil { return true } return false } // SetSourceType allocates a new e.SourceType and returns the pointer to it. func (e *Event) SetSourceType(v string) { e.SourceType = &v } // GetText returns the Text field if non-nil, zero value otherwise. func (e *Event) GetText() string { if e == nil || e.Text == nil { return "" } return *e.Text } // GetOkText returns a tuple with the Text field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetTextOk() (string, bool) { if e == nil || e.Text == nil { return "", false } return *e.Text, true } // HasText returns a boolean if a field has been set. func (e *Event) HasText() bool { if e != nil && e.Text != nil { return true } return false } // SetText allocates a new e.Text and returns the pointer to it. func (e *Event) SetText(v string) { e.Text = &v } // GetTime returns the Time field if non-nil, zero value otherwise. func (e *Event) GetTime() int { if e == nil || e.Time == nil { return 0 } return *e.Time } // GetOkTime returns a tuple with the Time field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetTimeOk() (int, bool) { if e == nil || e.Time == nil { return 0, false } return *e.Time, true } // HasTime returns a boolean if a field has been set. func (e *Event) HasTime() bool { if e != nil && e.Time != nil { return true } return false } // SetTime allocates a new e.Time and returns the pointer to it. func (e *Event) SetTime(v int) { e.Time = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (e *Event) GetTitle() string { if e == nil || e.Title == nil { return "" } return *e.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetTitleOk() (string, bool) { if e == nil || e.Title == nil { return "", false } return *e.Title, true } // HasTitle returns a boolean if a field has been set. func (e *Event) HasTitle() bool { if e != nil && e.Title != nil { return true } return false } // SetTitle allocates a new e.Title and returns the pointer to it. func (e *Event) SetTitle(v string) { e.Title = &v } // GetUrl returns the Url field if non-nil, zero value otherwise. func (e *Event) GetUrl() string { if e == nil || e.Url == nil { return "" } return *e.Url } // GetOkUrl returns a tuple with the Url field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *Event) GetUrlOk() (string, bool) { if e == nil || e.Url == nil { return "", false } return *e.Url, true } // HasUrl returns a boolean if a field has been set. func (e *Event) HasUrl() bool { if e != nil && e.Url != nil { return true } return false } // SetUrl allocates a new e.Url and returns the pointer to it. func (e *Event) SetUrl(v string) { e.Url = &v } // GetEventSize returns the EventSize field if non-nil, zero value otherwise. func (e *EventStreamWidget) GetEventSize() string { if e == nil || e.EventSize == nil { return "" } return *e.EventSize } // GetOkEventSize returns a tuple with the EventSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventStreamWidget) GetEventSizeOk() (string, bool) { if e == nil || e.EventSize == nil { return "", false } return *e.EventSize, true } // HasEventSize returns a boolean if a field has been set. func (e *EventStreamWidget) HasEventSize() bool { if e != nil && e.EventSize != nil { return true } return false } // SetEventSize allocates a new e.EventSize and returns the pointer to it. func (e *EventStreamWidget) SetEventSize(v string) { e.EventSize = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (e *EventStreamWidget) GetHeight() int { if e == nil || e.Height == nil { return 0 } return *e.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventStreamWidget) GetHeightOk() (int, bool) { if e == nil || e.Height == nil { return 0, false } return *e.Height, true } // HasHeight returns a boolean if a field has been set. func (e *EventStreamWidget) HasHeight() bool { if e != nil && e.Height != nil { return true } return false } // SetHeight allocates a new e.Height and returns the pointer to it. func (e *EventStreamWidget) SetHeight(v int) { e.Height = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (e *EventStreamWidget) GetQuery() string { if e == nil || e.Query == nil { return "" } return *e.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventStreamWidget) GetQueryOk() (string, bool) { if e == nil || e.Query == nil { return "", false } return *e.Query, true } // HasQuery returns a boolean if a field has been set. func (e *EventStreamWidget) HasQuery() bool { if e != nil && e.Query != nil { return true } return false } // SetQuery allocates a new e.Query and returns the pointer to it. func (e *EventStreamWidget) SetQuery(v string) { e.Query = &v } // GetTimeframe returns the Timeframe field if non-nil, zero value otherwise. func (e *EventStreamWidget) GetTimeframe() string { if e == nil || e.Timeframe == nil { return "" } return *e.Timeframe } // GetOkTimeframe returns a tuple with the Timeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventStreamWidget) GetTimeframeOk() (string, bool) { if e == nil || e.Timeframe == nil { return "", false } return *e.Timeframe, true } // HasTimeframe returns a boolean if a field has been set. func (e *EventStreamWidget) HasTimeframe() bool { if e != nil && e.Timeframe != nil { return true } return false } // SetTimeframe allocates a new e.Timeframe and returns the pointer to it. func (e *EventStreamWidget) SetTimeframe(v string) { e.Timeframe = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (e *EventStreamWidget) GetTitle() bool { if e == nil || e.Title == nil { return false } return *e.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventStreamWidget) GetTitleOk() (bool, bool) { if e == nil || e.Title == nil { return false, false } return *e.Title, true } // HasTitle returns a boolean if a field has been set. func (e *EventStreamWidget) HasTitle() bool { if e != nil && e.Title != nil { return true } return false } // SetTitle allocates a new e.Title and returns the pointer to it. func (e *EventStreamWidget) SetTitle(v bool) { e.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (e *EventStreamWidget) GetTitleAlign() string { if e == nil || e.TitleAlign == nil { return "" } return *e.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventStreamWidget) GetTitleAlignOk() (string, bool) { if e == nil || e.TitleAlign == nil { return "", false } return *e.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (e *EventStreamWidget) HasTitleAlign() bool { if e != nil && e.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new e.TitleAlign and returns the pointer to it. func (e *EventStreamWidget) SetTitleAlign(v string) { e.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (e *EventStreamWidget) GetTitleSize() TextSize { if e == nil || e.TitleSize == nil { return TextSize{} } return *e.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventStreamWidget) GetTitleSizeOk() (TextSize, bool) { if e == nil || e.TitleSize == nil { return TextSize{}, false } return *e.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (e *EventStreamWidget) HasTitleSize() bool { if e != nil && e.TitleSize != nil { return true } return false } // SetTitleSize allocates a new e.TitleSize and returns the pointer to it. func (e *EventStreamWidget) SetTitleSize(v TextSize) { e.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (e *EventStreamWidget) GetTitleText() string { if e == nil || e.TitleText == nil { return "" } return *e.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventStreamWidget) GetTitleTextOk() (string, bool) { if e == nil || e.TitleText == nil { return "", false } return *e.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (e *EventStreamWidget) HasTitleText() bool { if e != nil && e.TitleText != nil { return true } return false } // SetTitleText allocates a new e.TitleText and returns the pointer to it. func (e *EventStreamWidget) SetTitleText(v string) { e.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (e *EventStreamWidget) GetType() string { if e == nil || e.Type == nil { return "" } return *e.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventStreamWidget) GetTypeOk() (string, bool) { if e == nil || e.Type == nil { return "", false } return *e.Type, true } // HasType returns a boolean if a field has been set. func (e *EventStreamWidget) HasType() bool { if e != nil && e.Type != nil { return true } return false } // SetType allocates a new e.Type and returns the pointer to it. func (e *EventStreamWidget) SetType(v string) { e.Type = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (e *EventStreamWidget) GetWidth() int { if e == nil || e.Width == nil { return 0 } return *e.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventStreamWidget) GetWidthOk() (int, bool) { if e == nil || e.Width == nil { return 0, false } return *e.Width, true } // HasWidth returns a boolean if a field has been set. func (e *EventStreamWidget) HasWidth() bool { if e != nil && e.Width != nil { return true } return false } // SetWidth allocates a new e.Width and returns the pointer to it. func (e *EventStreamWidget) SetWidth(v int) { e.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (e *EventStreamWidget) GetX() int { if e == nil || e.X == nil { return 0 } return *e.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventStreamWidget) GetXOk() (int, bool) { if e == nil || e.X == nil { return 0, false } return *e.X, true } // HasX returns a boolean if a field has been set. func (e *EventStreamWidget) HasX() bool { if e != nil && e.X != nil { return true } return false } // SetX allocates a new e.X and returns the pointer to it. func (e *EventStreamWidget) SetX(v int) { e.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (e *EventStreamWidget) GetY() int { if e == nil || e.Y == nil { return 0 } return *e.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventStreamWidget) GetYOk() (int, bool) { if e == nil || e.Y == nil { return 0, false } return *e.Y, true } // HasY returns a boolean if a field has been set. func (e *EventStreamWidget) HasY() bool { if e != nil && e.Y != nil { return true } return false } // SetY allocates a new e.Y and returns the pointer to it. func (e *EventStreamWidget) SetY(v int) { e.Y = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (e *EventTimelineWidget) GetHeight() int { if e == nil || e.Height == nil { return 0 } return *e.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventTimelineWidget) GetHeightOk() (int, bool) { if e == nil || e.Height == nil { return 0, false } return *e.Height, true } // HasHeight returns a boolean if a field has been set. func (e *EventTimelineWidget) HasHeight() bool { if e != nil && e.Height != nil { return true } return false } // SetHeight allocates a new e.Height and returns the pointer to it. func (e *EventTimelineWidget) SetHeight(v int) { e.Height = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (e *EventTimelineWidget) GetQuery() string { if e == nil || e.Query == nil { return "" } return *e.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventTimelineWidget) GetQueryOk() (string, bool) { if e == nil || e.Query == nil { return "", false } return *e.Query, true } // HasQuery returns a boolean if a field has been set. func (e *EventTimelineWidget) HasQuery() bool { if e != nil && e.Query != nil { return true } return false } // SetQuery allocates a new e.Query and returns the pointer to it. func (e *EventTimelineWidget) SetQuery(v string) { e.Query = &v } // GetTimeframe returns the Timeframe field if non-nil, zero value otherwise. func (e *EventTimelineWidget) GetTimeframe() string { if e == nil || e.Timeframe == nil { return "" } return *e.Timeframe } // GetOkTimeframe returns a tuple with the Timeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventTimelineWidget) GetTimeframeOk() (string, bool) { if e == nil || e.Timeframe == nil { return "", false } return *e.Timeframe, true } // HasTimeframe returns a boolean if a field has been set. func (e *EventTimelineWidget) HasTimeframe() bool { if e != nil && e.Timeframe != nil { return true } return false } // SetTimeframe allocates a new e.Timeframe and returns the pointer to it. func (e *EventTimelineWidget) SetTimeframe(v string) { e.Timeframe = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (e *EventTimelineWidget) GetTitle() bool { if e == nil || e.Title == nil { return false } return *e.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventTimelineWidget) GetTitleOk() (bool, bool) { if e == nil || e.Title == nil { return false, false } return *e.Title, true } // HasTitle returns a boolean if a field has been set. func (e *EventTimelineWidget) HasTitle() bool { if e != nil && e.Title != nil { return true } return false } // SetTitle allocates a new e.Title and returns the pointer to it. func (e *EventTimelineWidget) SetTitle(v bool) { e.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (e *EventTimelineWidget) GetTitleAlign() string { if e == nil || e.TitleAlign == nil { return "" } return *e.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventTimelineWidget) GetTitleAlignOk() (string, bool) { if e == nil || e.TitleAlign == nil { return "", false } return *e.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (e *EventTimelineWidget) HasTitleAlign() bool { if e != nil && e.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new e.TitleAlign and returns the pointer to it. func (e *EventTimelineWidget) SetTitleAlign(v string) { e.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (e *EventTimelineWidget) GetTitleSize() int { if e == nil || e.TitleSize == nil { return 0 } return *e.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventTimelineWidget) GetTitleSizeOk() (int, bool) { if e == nil || e.TitleSize == nil { return 0, false } return *e.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (e *EventTimelineWidget) HasTitleSize() bool { if e != nil && e.TitleSize != nil { return true } return false } // SetTitleSize allocates a new e.TitleSize and returns the pointer to it. func (e *EventTimelineWidget) SetTitleSize(v int) { e.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (e *EventTimelineWidget) GetTitleText() string { if e == nil || e.TitleText == nil { return "" } return *e.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventTimelineWidget) GetTitleTextOk() (string, bool) { if e == nil || e.TitleText == nil { return "", false } return *e.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (e *EventTimelineWidget) HasTitleText() bool { if e != nil && e.TitleText != nil { return true } return false } // SetTitleText allocates a new e.TitleText and returns the pointer to it. func (e *EventTimelineWidget) SetTitleText(v string) { e.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (e *EventTimelineWidget) GetType() string { if e == nil || e.Type == nil { return "" } return *e.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventTimelineWidget) GetTypeOk() (string, bool) { if e == nil || e.Type == nil { return "", false } return *e.Type, true } // HasType returns a boolean if a field has been set. func (e *EventTimelineWidget) HasType() bool { if e != nil && e.Type != nil { return true } return false } // SetType allocates a new e.Type and returns the pointer to it. func (e *EventTimelineWidget) SetType(v string) { e.Type = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (e *EventTimelineWidget) GetWidth() int { if e == nil || e.Width == nil { return 0 } return *e.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventTimelineWidget) GetWidthOk() (int, bool) { if e == nil || e.Width == nil { return 0, false } return *e.Width, true } // HasWidth returns a boolean if a field has been set. func (e *EventTimelineWidget) HasWidth() bool { if e != nil && e.Width != nil { return true } return false } // SetWidth allocates a new e.Width and returns the pointer to it. func (e *EventTimelineWidget) SetWidth(v int) { e.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (e *EventTimelineWidget) GetX() int { if e == nil || e.X == nil { return 0 } return *e.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventTimelineWidget) GetXOk() (int, bool) { if e == nil || e.X == nil { return 0, false } return *e.X, true } // HasX returns a boolean if a field has been set. func (e *EventTimelineWidget) HasX() bool { if e != nil && e.X != nil { return true } return false } // SetX allocates a new e.X and returns the pointer to it. func (e *EventTimelineWidget) SetX(v int) { e.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (e *EventTimelineWidget) GetY() int { if e == nil || e.Y == nil { return 0 } return *e.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (e *EventTimelineWidget) GetYOk() (int, bool) { if e == nil || e.Y == nil { return 0, false } return *e.Y, true } // HasY returns a boolean if a field has been set. func (e *EventTimelineWidget) HasY() bool { if e != nil && e.Y != nil { return true } return false } // SetY allocates a new e.Y and returns the pointer to it. func (e *EventTimelineWidget) SetY(v int) { e.Y = &v } // GetColor returns the Color field if non-nil, zero value otherwise. func (f *FreeTextWidget) GetColor() string { if f == nil || f.Color == nil { return "" } return *f.Color } // GetOkColor returns a tuple with the Color field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (f *FreeTextWidget) GetColorOk() (string, bool) { if f == nil || f.Color == nil { return "", false } return *f.Color, true } // HasColor returns a boolean if a field has been set. func (f *FreeTextWidget) HasColor() bool { if f != nil && f.Color != nil { return true } return false } // SetColor allocates a new f.Color and returns the pointer to it. func (f *FreeTextWidget) SetColor(v string) { f.Color = &v } // GetFontSize returns the FontSize field if non-nil, zero value otherwise. func (f *FreeTextWidget) GetFontSize() string { if f == nil || f.FontSize == nil { return "" } return *f.FontSize } // GetOkFontSize returns a tuple with the FontSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (f *FreeTextWidget) GetFontSizeOk() (string, bool) { if f == nil || f.FontSize == nil { return "", false } return *f.FontSize, true } // HasFontSize returns a boolean if a field has been set. func (f *FreeTextWidget) HasFontSize() bool { if f != nil && f.FontSize != nil { return true } return false } // SetFontSize allocates a new f.FontSize and returns the pointer to it. func (f *FreeTextWidget) SetFontSize(v string) { f.FontSize = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (f *FreeTextWidget) GetHeight() int { if f == nil || f.Height == nil { return 0 } return *f.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (f *FreeTextWidget) GetHeightOk() (int, bool) { if f == nil || f.Height == nil { return 0, false } return *f.Height, true } // HasHeight returns a boolean if a field has been set. func (f *FreeTextWidget) HasHeight() bool { if f != nil && f.Height != nil { return true } return false } // SetHeight allocates a new f.Height and returns the pointer to it. func (f *FreeTextWidget) SetHeight(v int) { f.Height = &v } // GetText returns the Text field if non-nil, zero value otherwise. func (f *FreeTextWidget) GetText() string { if f == nil || f.Text == nil { return "" } return *f.Text } // GetOkText returns a tuple with the Text field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (f *FreeTextWidget) GetTextOk() (string, bool) { if f == nil || f.Text == nil { return "", false } return *f.Text, true } // HasText returns a boolean if a field has been set. func (f *FreeTextWidget) HasText() bool { if f != nil && f.Text != nil { return true } return false } // SetText allocates a new f.Text and returns the pointer to it. func (f *FreeTextWidget) SetText(v string) { f.Text = &v } // GetTextAlign returns the TextAlign field if non-nil, zero value otherwise. func (f *FreeTextWidget) GetTextAlign() string { if f == nil || f.TextAlign == nil { return "" } return *f.TextAlign } // GetOkTextAlign returns a tuple with the TextAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (f *FreeTextWidget) GetTextAlignOk() (string, bool) { if f == nil || f.TextAlign == nil { return "", false } return *f.TextAlign, true } // HasTextAlign returns a boolean if a field has been set. func (f *FreeTextWidget) HasTextAlign() bool { if f != nil && f.TextAlign != nil { return true } return false } // SetTextAlign allocates a new f.TextAlign and returns the pointer to it. func (f *FreeTextWidget) SetTextAlign(v string) { f.TextAlign = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (f *FreeTextWidget) GetType() string { if f == nil || f.Type == nil { return "" } return *f.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (f *FreeTextWidget) GetTypeOk() (string, bool) { if f == nil || f.Type == nil { return "", false } return *f.Type, true } // HasType returns a boolean if a field has been set. func (f *FreeTextWidget) HasType() bool { if f != nil && f.Type != nil { return true } return false } // SetType allocates a new f.Type and returns the pointer to it. func (f *FreeTextWidget) SetType(v string) { f.Type = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (f *FreeTextWidget) GetWidth() int { if f == nil || f.Width == nil { return 0 } return *f.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (f *FreeTextWidget) GetWidthOk() (int, bool) { if f == nil || f.Width == nil { return 0, false } return *f.Width, true } // HasWidth returns a boolean if a field has been set. func (f *FreeTextWidget) HasWidth() bool { if f != nil && f.Width != nil { return true } return false } // SetWidth allocates a new f.Width and returns the pointer to it. func (f *FreeTextWidget) SetWidth(v int) { f.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (f *FreeTextWidget) GetX() int { if f == nil || f.X == nil { return 0 } return *f.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (f *FreeTextWidget) GetXOk() (int, bool) { if f == nil || f.X == nil { return 0, false } return *f.X, true } // HasX returns a boolean if a field has been set. func (f *FreeTextWidget) HasX() bool { if f != nil && f.X != nil { return true } return false } // SetX allocates a new f.X and returns the pointer to it. func (f *FreeTextWidget) SetX(v int) { f.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (f *FreeTextWidget) GetY() int { if f == nil || f.Y == nil { return 0 } return *f.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (f *FreeTextWidget) GetYOk() (int, bool) { if f == nil || f.Y == nil { return 0, false } return *f.Y, true } // HasY returns a boolean if a field has been set. func (f *FreeTextWidget) HasY() bool { if f != nil && f.Y != nil { return true } return false } // SetY allocates a new f.Y and returns the pointer to it. func (f *FreeTextWidget) SetY(v int) { f.Y = &v } // GetDefinition returns the Definition field if non-nil, zero value otherwise. func (g *Graph) GetDefinition() GraphDefinition { if g == nil || g.Definition == nil { return GraphDefinition{} } return *g.Definition } // GetOkDefinition returns a tuple with the Definition field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *Graph) GetDefinitionOk() (GraphDefinition, bool) { if g == nil || g.Definition == nil { return GraphDefinition{}, false } return *g.Definition, true } // HasDefinition returns a boolean if a field has been set. func (g *Graph) HasDefinition() bool { if g != nil && g.Definition != nil { return true } return false } // SetDefinition allocates a new g.Definition and returns the pointer to it. func (g *Graph) SetDefinition(v GraphDefinition) { g.Definition = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (g *Graph) GetTitle() string { if g == nil || g.Title == nil { return "" } return *g.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *Graph) GetTitleOk() (string, bool) { if g == nil || g.Title == nil { return "", false } return *g.Title, true } // HasTitle returns a boolean if a field has been set. func (g *Graph) HasTitle() bool { if g != nil && g.Title != nil { return true } return false } // SetTitle allocates a new g.Title and returns the pointer to it. func (g *Graph) SetTitle(v string) { g.Title = &v } // GetAutoscale returns the Autoscale field if non-nil, zero value otherwise. func (g *GraphDefinition) GetAutoscale() bool { if g == nil || g.Autoscale == nil { return false } return *g.Autoscale } // GetOkAutoscale returns a tuple with the Autoscale field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetAutoscaleOk() (bool, bool) { if g == nil || g.Autoscale == nil { return false, false } return *g.Autoscale, true } // HasAutoscale returns a boolean if a field has been set. func (g *GraphDefinition) HasAutoscale() bool { if g != nil && g.Autoscale != nil { return true } return false } // SetAutoscale allocates a new g.Autoscale and returns the pointer to it. func (g *GraphDefinition) SetAutoscale(v bool) { g.Autoscale = &v } // GetCustomUnit returns the CustomUnit field if non-nil, zero value otherwise. func (g *GraphDefinition) GetCustomUnit() string { if g == nil || g.CustomUnit == nil { return "" } return *g.CustomUnit } // GetOkCustomUnit returns a tuple with the CustomUnit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetCustomUnitOk() (string, bool) { if g == nil || g.CustomUnit == nil { return "", false } return *g.CustomUnit, true } // HasCustomUnit returns a boolean if a field has been set. func (g *GraphDefinition) HasCustomUnit() bool { if g != nil && g.CustomUnit != nil { return true } return false } // SetCustomUnit allocates a new g.CustomUnit and returns the pointer to it. func (g *GraphDefinition) SetCustomUnit(v string) { g.CustomUnit = &v } // GetIncludeNoMetricHosts returns the IncludeNoMetricHosts field if non-nil, zero value otherwise. func (g *GraphDefinition) GetIncludeNoMetricHosts() bool { if g == nil || g.IncludeNoMetricHosts == nil { return false } return *g.IncludeNoMetricHosts } // GetOkIncludeNoMetricHosts returns a tuple with the IncludeNoMetricHosts field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetIncludeNoMetricHostsOk() (bool, bool) { if g == nil || g.IncludeNoMetricHosts == nil { return false, false } return *g.IncludeNoMetricHosts, true } // HasIncludeNoMetricHosts returns a boolean if a field has been set. func (g *GraphDefinition) HasIncludeNoMetricHosts() bool { if g != nil && g.IncludeNoMetricHosts != nil { return true } return false } // SetIncludeNoMetricHosts allocates a new g.IncludeNoMetricHosts and returns the pointer to it. func (g *GraphDefinition) SetIncludeNoMetricHosts(v bool) { g.IncludeNoMetricHosts = &v } // GetIncludeUngroupedHosts returns the IncludeUngroupedHosts field if non-nil, zero value otherwise. func (g *GraphDefinition) GetIncludeUngroupedHosts() bool { if g == nil || g.IncludeUngroupedHosts == nil { return false } return *g.IncludeUngroupedHosts } // GetOkIncludeUngroupedHosts returns a tuple with the IncludeUngroupedHosts field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetIncludeUngroupedHostsOk() (bool, bool) { if g == nil || g.IncludeUngroupedHosts == nil { return false, false } return *g.IncludeUngroupedHosts, true } // HasIncludeUngroupedHosts returns a boolean if a field has been set. func (g *GraphDefinition) HasIncludeUngroupedHosts() bool { if g != nil && g.IncludeUngroupedHosts != nil { return true } return false } // SetIncludeUngroupedHosts allocates a new g.IncludeUngroupedHosts and returns the pointer to it. func (g *GraphDefinition) SetIncludeUngroupedHosts(v bool) { g.IncludeUngroupedHosts = &v } // GetPrecision returns the Precision field if non-nil, zero value otherwise. func (g *GraphDefinition) GetPrecision() string { if g == nil || g.Precision == nil { return "" } return *g.Precision } // GetOkPrecision returns a tuple with the Precision field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetPrecisionOk() (string, bool) { if g == nil || g.Precision == nil { return "", false } return *g.Precision, true } // HasPrecision returns a boolean if a field has been set. func (g *GraphDefinition) HasPrecision() bool { if g != nil && g.Precision != nil { return true } return false } // SetPrecision allocates a new g.Precision and returns the pointer to it. func (g *GraphDefinition) SetPrecision(v string) { g.Precision = &v } // GetStyle returns the Style field if non-nil, zero value otherwise. func (g *GraphDefinition) GetStyle() Style { if g == nil || g.Style == nil { return Style{} } return *g.Style } // GetOkStyle returns a tuple with the Style field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetStyleOk() (Style, bool) { if g == nil || g.Style == nil { return Style{}, false } return *g.Style, true } // HasStyle returns a boolean if a field has been set. func (g *GraphDefinition) HasStyle() bool { if g != nil && g.Style != nil { return true } return false } // SetStyle allocates a new g.Style and returns the pointer to it. func (g *GraphDefinition) SetStyle(v Style) { g.Style = &v } // GetTextAlign returns the TextAlign field if non-nil, zero value otherwise. func (g *GraphDefinition) GetTextAlign() string { if g == nil || g.TextAlign == nil { return "" } return *g.TextAlign } // GetOkTextAlign returns a tuple with the TextAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetTextAlignOk() (string, bool) { if g == nil || g.TextAlign == nil { return "", false } return *g.TextAlign, true } // HasTextAlign returns a boolean if a field has been set. func (g *GraphDefinition) HasTextAlign() bool { if g != nil && g.TextAlign != nil { return true } return false } // SetTextAlign allocates a new g.TextAlign and returns the pointer to it. func (g *GraphDefinition) SetTextAlign(v string) { g.TextAlign = &v } // GetViz returns the Viz field if non-nil, zero value otherwise. func (g *GraphDefinition) GetViz() string { if g == nil || g.Viz == nil { return "" } return *g.Viz } // GetOkViz returns a tuple with the Viz field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinition) GetVizOk() (string, bool) { if g == nil || g.Viz == nil { return "", false } return *g.Viz, true } // HasViz returns a boolean if a field has been set. func (g *GraphDefinition) HasViz() bool { if g != nil && g.Viz != nil { return true } return false } // SetViz allocates a new g.Viz and returns the pointer to it. func (g *GraphDefinition) SetViz(v string) { g.Viz = &v } // GetLabel returns the Label field if non-nil, zero value otherwise. func (g *GraphDefinitionMarker) GetLabel() string { if g == nil || g.Label == nil { return "" } return *g.Label } // GetOkLabel returns a tuple with the Label field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionMarker) GetLabelOk() (string, bool) { if g == nil || g.Label == nil { return "", false } return *g.Label, true } // HasLabel returns a boolean if a field has been set. func (g *GraphDefinitionMarker) HasLabel() bool { if g != nil && g.Label != nil { return true } return false } // SetLabel allocates a new g.Label and returns the pointer to it. func (g *GraphDefinitionMarker) SetLabel(v string) { g.Label = &v } // GetMax returns the Max field if non-nil, zero value otherwise. func (g *GraphDefinitionMarker) GetMax() json.Number { if g == nil || g.Max == nil { return "" } return *g.Max } // GetOkMax returns a tuple with the Max field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionMarker) GetMaxOk() (json.Number, bool) { if g == nil || g.Max == nil { return "", false } return *g.Max, true } // HasMax returns a boolean if a field has been set. func (g *GraphDefinitionMarker) HasMax() bool { if g != nil && g.Max != nil { return true } return false } // SetMax allocates a new g.Max and returns the pointer to it. func (g *GraphDefinitionMarker) SetMax(v json.Number) { g.Max = &v } // GetMin returns the Min field if non-nil, zero value otherwise. func (g *GraphDefinitionMarker) GetMin() json.Number { if g == nil || g.Min == nil { return "" } return *g.Min } // GetOkMin returns a tuple with the Min field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionMarker) GetMinOk() (json.Number, bool) { if g == nil || g.Min == nil { return "", false } return *g.Min, true } // HasMin returns a boolean if a field has been set. func (g *GraphDefinitionMarker) HasMin() bool { if g != nil && g.Min != nil { return true } return false } // SetMin allocates a new g.Min and returns the pointer to it. func (g *GraphDefinitionMarker) SetMin(v json.Number) { g.Min = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (g *GraphDefinitionMarker) GetType() string { if g == nil || g.Type == nil { return "" } return *g.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionMarker) GetTypeOk() (string, bool) { if g == nil || g.Type == nil { return "", false } return *g.Type, true } // HasType returns a boolean if a field has been set. func (g *GraphDefinitionMarker) HasType() bool { if g != nil && g.Type != nil { return true } return false } // SetType allocates a new g.Type and returns the pointer to it. func (g *GraphDefinitionMarker) SetType(v string) { g.Type = &v } // GetVal returns the Val field if non-nil, zero value otherwise. func (g *GraphDefinitionMarker) GetVal() json.Number { if g == nil || g.Val == nil { return "" } return *g.Val } // GetOkVal returns a tuple with the Val field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionMarker) GetValOk() (json.Number, bool) { if g == nil || g.Val == nil { return "", false } return *g.Val, true } // HasVal returns a boolean if a field has been set. func (g *GraphDefinitionMarker) HasVal() bool { if g != nil && g.Val != nil { return true } return false } // SetVal allocates a new g.Val and returns the pointer to it. func (g *GraphDefinitionMarker) SetVal(v json.Number) { g.Val = &v } // GetValue returns the Value field if non-nil, zero value otherwise. func (g *GraphDefinitionMarker) GetValue() string { if g == nil || g.Value == nil { return "" } return *g.Value } // GetOkValue returns a tuple with the Value field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionMarker) GetValueOk() (string, bool) { if g == nil || g.Value == nil { return "", false } return *g.Value, true } // HasValue returns a boolean if a field has been set. func (g *GraphDefinitionMarker) HasValue() bool { if g != nil && g.Value != nil { return true } return false } // SetValue allocates a new g.Value and returns the pointer to it. func (g *GraphDefinitionMarker) SetValue(v string) { g.Value = &v } // GetAggregator returns the Aggregator field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetAggregator() string { if g == nil || g.Aggregator == nil { return "" } return *g.Aggregator } // GetOkAggregator returns a tuple with the Aggregator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetAggregatorOk() (string, bool) { if g == nil || g.Aggregator == nil { return "", false } return *g.Aggregator, true } // HasAggregator returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasAggregator() bool { if g != nil && g.Aggregator != nil { return true } return false } // SetAggregator allocates a new g.Aggregator and returns the pointer to it. func (g *GraphDefinitionRequest) SetAggregator(v string) { g.Aggregator = &v } // GetChangeType returns the ChangeType field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetChangeType() string { if g == nil || g.ChangeType == nil { return "" } return *g.ChangeType } // GetOkChangeType returns a tuple with the ChangeType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetChangeTypeOk() (string, bool) { if g == nil || g.ChangeType == nil { return "", false } return *g.ChangeType, true } // HasChangeType returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasChangeType() bool { if g != nil && g.ChangeType != nil { return true } return false } // SetChangeType allocates a new g.ChangeType and returns the pointer to it. func (g *GraphDefinitionRequest) SetChangeType(v string) { g.ChangeType = &v } // GetCompareTo returns the CompareTo field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetCompareTo() string { if g == nil || g.CompareTo == nil { return "" } return *g.CompareTo } // GetOkCompareTo returns a tuple with the CompareTo field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetCompareToOk() (string, bool) { if g == nil || g.CompareTo == nil { return "", false } return *g.CompareTo, true } // HasCompareTo returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasCompareTo() bool { if g != nil && g.CompareTo != nil { return true } return false } // SetCompareTo allocates a new g.CompareTo and returns the pointer to it. func (g *GraphDefinitionRequest) SetCompareTo(v string) { g.CompareTo = &v } // GetExtraCol returns the ExtraCol field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetExtraCol() string { if g == nil || g.ExtraCol == nil { return "" } return *g.ExtraCol } // GetOkExtraCol returns a tuple with the ExtraCol field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetExtraColOk() (string, bool) { if g == nil || g.ExtraCol == nil { return "", false } return *g.ExtraCol, true } // HasExtraCol returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasExtraCol() bool { if g != nil && g.ExtraCol != nil { return true } return false } // SetExtraCol allocates a new g.ExtraCol and returns the pointer to it. func (g *GraphDefinitionRequest) SetExtraCol(v string) { g.ExtraCol = &v } // GetIncreaseGood returns the IncreaseGood field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetIncreaseGood() bool { if g == nil || g.IncreaseGood == nil { return false } return *g.IncreaseGood } // GetOkIncreaseGood returns a tuple with the IncreaseGood field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetIncreaseGoodOk() (bool, bool) { if g == nil || g.IncreaseGood == nil { return false, false } return *g.IncreaseGood, true } // HasIncreaseGood returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasIncreaseGood() bool { if g != nil && g.IncreaseGood != nil { return true } return false } // SetIncreaseGood allocates a new g.IncreaseGood and returns the pointer to it. func (g *GraphDefinitionRequest) SetIncreaseGood(v bool) { g.IncreaseGood = &v } // GetOrderBy returns the OrderBy field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetOrderBy() string { if g == nil || g.OrderBy == nil { return "" } return *g.OrderBy } // GetOkOrderBy returns a tuple with the OrderBy field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetOrderByOk() (string, bool) { if g == nil || g.OrderBy == nil { return "", false } return *g.OrderBy, true } // HasOrderBy returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasOrderBy() bool { if g != nil && g.OrderBy != nil { return true } return false } // SetOrderBy allocates a new g.OrderBy and returns the pointer to it. func (g *GraphDefinitionRequest) SetOrderBy(v string) { g.OrderBy = &v } // GetOrderDirection returns the OrderDirection field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetOrderDirection() string { if g == nil || g.OrderDirection == nil { return "" } return *g.OrderDirection } // GetOkOrderDirection returns a tuple with the OrderDirection field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetOrderDirectionOk() (string, bool) { if g == nil || g.OrderDirection == nil { return "", false } return *g.OrderDirection, true } // HasOrderDirection returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasOrderDirection() bool { if g != nil && g.OrderDirection != nil { return true } return false } // SetOrderDirection allocates a new g.OrderDirection and returns the pointer to it. func (g *GraphDefinitionRequest) SetOrderDirection(v string) { g.OrderDirection = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetQuery() string { if g == nil || g.Query == nil { return "" } return *g.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetQueryOk() (string, bool) { if g == nil || g.Query == nil { return "", false } return *g.Query, true } // HasQuery returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasQuery() bool { if g != nil && g.Query != nil { return true } return false } // SetQuery allocates a new g.Query and returns the pointer to it. func (g *GraphDefinitionRequest) SetQuery(v string) { g.Query = &v } // GetStacked returns the Stacked field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetStacked() bool { if g == nil || g.Stacked == nil { return false } return *g.Stacked } // GetOkStacked returns a tuple with the Stacked field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetStackedOk() (bool, bool) { if g == nil || g.Stacked == nil { return false, false } return *g.Stacked, true } // HasStacked returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasStacked() bool { if g != nil && g.Stacked != nil { return true } return false } // SetStacked allocates a new g.Stacked and returns the pointer to it. func (g *GraphDefinitionRequest) SetStacked(v bool) { g.Stacked = &v } // GetStyle returns the Style field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetStyle() GraphDefinitionRequestStyle { if g == nil || g.Style == nil { return GraphDefinitionRequestStyle{} } return *g.Style } // GetOkStyle returns a tuple with the Style field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetStyleOk() (GraphDefinitionRequestStyle, bool) { if g == nil || g.Style == nil { return GraphDefinitionRequestStyle{}, false } return *g.Style, true } // HasStyle returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasStyle() bool { if g != nil && g.Style != nil { return true } return false } // SetStyle allocates a new g.Style and returns the pointer to it. func (g *GraphDefinitionRequest) SetStyle(v GraphDefinitionRequestStyle) { g.Style = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (g *GraphDefinitionRequest) GetType() string { if g == nil || g.Type == nil { return "" } return *g.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequest) GetTypeOk() (string, bool) { if g == nil || g.Type == nil { return "", false } return *g.Type, true } // HasType returns a boolean if a field has been set. func (g *GraphDefinitionRequest) HasType() bool { if g != nil && g.Type != nil { return true } return false } // SetType allocates a new g.Type and returns the pointer to it. func (g *GraphDefinitionRequest) SetType(v string) { g.Type = &v } // GetPalette returns the Palette field if non-nil, zero value otherwise. func (g *GraphDefinitionRequestStyle) GetPalette() string { if g == nil || g.Palette == nil { return "" } return *g.Palette } // GetOkPalette returns a tuple with the Palette field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequestStyle) GetPaletteOk() (string, bool) { if g == nil || g.Palette == nil { return "", false } return *g.Palette, true } // HasPalette returns a boolean if a field has been set. func (g *GraphDefinitionRequestStyle) HasPalette() bool { if g != nil && g.Palette != nil { return true } return false } // SetPalette allocates a new g.Palette and returns the pointer to it. func (g *GraphDefinitionRequestStyle) SetPalette(v string) { g.Palette = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (g *GraphDefinitionRequestStyle) GetType() string { if g == nil || g.Type == nil { return "" } return *g.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequestStyle) GetTypeOk() (string, bool) { if g == nil || g.Type == nil { return "", false } return *g.Type, true } // HasType returns a boolean if a field has been set. func (g *GraphDefinitionRequestStyle) HasType() bool { if g != nil && g.Type != nil { return true } return false } // SetType allocates a new g.Type and returns the pointer to it. func (g *GraphDefinitionRequestStyle) SetType(v string) { g.Type = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (g *GraphDefinitionRequestStyle) GetWidth() string { if g == nil || g.Width == nil { return "" } return *g.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphDefinitionRequestStyle) GetWidthOk() (string, bool) { if g == nil || g.Width == nil { return "", false } return *g.Width, true } // HasWidth returns a boolean if a field has been set. func (g *GraphDefinitionRequestStyle) HasWidth() bool { if g != nil && g.Width != nil { return true } return false } // SetWidth allocates a new g.Width and returns the pointer to it. func (g *GraphDefinitionRequestStyle) SetWidth(v string) { g.Width = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (g *GraphEvent) GetQuery() string { if g == nil || g.Query == nil { return "" } return *g.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphEvent) GetQueryOk() (string, bool) { if g == nil || g.Query == nil { return "", false } return *g.Query, true } // HasQuery returns a boolean if a field has been set. func (g *GraphEvent) HasQuery() bool { if g != nil && g.Query != nil { return true } return false } // SetQuery allocates a new g.Query and returns the pointer to it. func (g *GraphEvent) SetQuery(v string) { g.Query = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (g *GraphWidget) GetHeight() int { if g == nil || g.Height == nil { return 0 } return *g.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetHeightOk() (int, bool) { if g == nil || g.Height == nil { return 0, false } return *g.Height, true } // HasHeight returns a boolean if a field has been set. func (g *GraphWidget) HasHeight() bool { if g != nil && g.Height != nil { return true } return false } // SetHeight allocates a new g.Height and returns the pointer to it. func (g *GraphWidget) SetHeight(v int) { g.Height = &v } // GetLegend returns the Legend field if non-nil, zero value otherwise. func (g *GraphWidget) GetLegend() bool { if g == nil || g.Legend == nil { return false } return *g.Legend } // GetOkLegend returns a tuple with the Legend field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetLegendOk() (bool, bool) { if g == nil || g.Legend == nil { return false, false } return *g.Legend, true } // HasLegend returns a boolean if a field has been set. func (g *GraphWidget) HasLegend() bool { if g != nil && g.Legend != nil { return true } return false } // SetLegend allocates a new g.Legend and returns the pointer to it. func (g *GraphWidget) SetLegend(v bool) { g.Legend = &v } // GetLegendSize returns the LegendSize field if non-nil, zero value otherwise. func (g *GraphWidget) GetLegendSize() int { if g == nil || g.LegendSize == nil { return 0 } return *g.LegendSize } // GetOkLegendSize returns a tuple with the LegendSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetLegendSizeOk() (int, bool) { if g == nil || g.LegendSize == nil { return 0, false } return *g.LegendSize, true } // HasLegendSize returns a boolean if a field has been set. func (g *GraphWidget) HasLegendSize() bool { if g != nil && g.LegendSize != nil { return true } return false } // SetLegendSize allocates a new g.LegendSize and returns the pointer to it. func (g *GraphWidget) SetLegendSize(v int) { g.LegendSize = &v } // GetTileDef returns the TileDef field if non-nil, zero value otherwise. func (g *GraphWidget) GetTileDef() TileDef { if g == nil || g.TileDef == nil { return TileDef{} } return *g.TileDef } // GetOkTileDef returns a tuple with the TileDef field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetTileDefOk() (TileDef, bool) { if g == nil || g.TileDef == nil { return TileDef{}, false } return *g.TileDef, true } // HasTileDef returns a boolean if a field has been set. func (g *GraphWidget) HasTileDef() bool { if g != nil && g.TileDef != nil { return true } return false } // SetTileDef allocates a new g.TileDef and returns the pointer to it. func (g *GraphWidget) SetTileDef(v TileDef) { g.TileDef = &v } // GetTimeframe returns the Timeframe field if non-nil, zero value otherwise. func (g *GraphWidget) GetTimeframe() string { if g == nil || g.Timeframe == nil { return "" } return *g.Timeframe } // GetOkTimeframe returns a tuple with the Timeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetTimeframeOk() (string, bool) { if g == nil || g.Timeframe == nil { return "", false } return *g.Timeframe, true } // HasTimeframe returns a boolean if a field has been set. func (g *GraphWidget) HasTimeframe() bool { if g != nil && g.Timeframe != nil { return true } return false } // SetTimeframe allocates a new g.Timeframe and returns the pointer to it. func (g *GraphWidget) SetTimeframe(v string) { g.Timeframe = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (g *GraphWidget) GetTitle() bool { if g == nil || g.Title == nil { return false } return *g.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetTitleOk() (bool, bool) { if g == nil || g.Title == nil { return false, false } return *g.Title, true } // HasTitle returns a boolean if a field has been set. func (g *GraphWidget) HasTitle() bool { if g != nil && g.Title != nil { return true } return false } // SetTitle allocates a new g.Title and returns the pointer to it. func (g *GraphWidget) SetTitle(v bool) { g.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (g *GraphWidget) GetTitleAlign() string { if g == nil || g.TitleAlign == nil { return "" } return *g.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetTitleAlignOk() (string, bool) { if g == nil || g.TitleAlign == nil { return "", false } return *g.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (g *GraphWidget) HasTitleAlign() bool { if g != nil && g.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new g.TitleAlign and returns the pointer to it. func (g *GraphWidget) SetTitleAlign(v string) { g.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (g *GraphWidget) GetTitleSize() int { if g == nil || g.TitleSize == nil { return 0 } return *g.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetTitleSizeOk() (int, bool) { if g == nil || g.TitleSize == nil { return 0, false } return *g.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (g *GraphWidget) HasTitleSize() bool { if g != nil && g.TitleSize != nil { return true } return false } // SetTitleSize allocates a new g.TitleSize and returns the pointer to it. func (g *GraphWidget) SetTitleSize(v int) { g.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (g *GraphWidget) GetTitleText() string { if g == nil || g.TitleText == nil { return "" } return *g.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetTitleTextOk() (string, bool) { if g == nil || g.TitleText == nil { return "", false } return *g.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (g *GraphWidget) HasTitleText() bool { if g != nil && g.TitleText != nil { return true } return false } // SetTitleText allocates a new g.TitleText and returns the pointer to it. func (g *GraphWidget) SetTitleText(v string) { g.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (g *GraphWidget) GetType() string { if g == nil || g.Type == nil { return "" } return *g.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetTypeOk() (string, bool) { if g == nil || g.Type == nil { return "", false } return *g.Type, true } // HasType returns a boolean if a field has been set. func (g *GraphWidget) HasType() bool { if g != nil && g.Type != nil { return true } return false } // SetType allocates a new g.Type and returns the pointer to it. func (g *GraphWidget) SetType(v string) { g.Type = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (g *GraphWidget) GetWidth() int { if g == nil || g.Width == nil { return 0 } return *g.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetWidthOk() (int, bool) { if g == nil || g.Width == nil { return 0, false } return *g.Width, true } // HasWidth returns a boolean if a field has been set. func (g *GraphWidget) HasWidth() bool { if g != nil && g.Width != nil { return true } return false } // SetWidth allocates a new g.Width and returns the pointer to it. func (g *GraphWidget) SetWidth(v int) { g.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (g *GraphWidget) GetX() int { if g == nil || g.X == nil { return 0 } return *g.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetXOk() (int, bool) { if g == nil || g.X == nil { return 0, false } return *g.X, true } // HasX returns a boolean if a field has been set. func (g *GraphWidget) HasX() bool { if g != nil && g.X != nil { return true } return false } // SetX allocates a new g.X and returns the pointer to it. func (g *GraphWidget) SetX(v int) { g.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (g *GraphWidget) GetY() int { if g == nil || g.Y == nil { return 0 } return *g.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (g *GraphWidget) GetYOk() (int, bool) { if g == nil || g.Y == nil { return 0, false } return *g.Y, true } // HasY returns a boolean if a field has been set. func (g *GraphWidget) HasY() bool { if g != nil && g.Y != nil { return true } return false } // SetY allocates a new g.Y and returns the pointer to it. func (g *GraphWidget) SetY(v int) { g.Y = &v } // GetEndTime returns the EndTime field if non-nil, zero value otherwise. func (h *HostActionMute) GetEndTime() string { if h == nil || h.EndTime == nil { return "" } return *h.EndTime } // GetOkEndTime returns a tuple with the EndTime field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostActionMute) GetEndTimeOk() (string, bool) { if h == nil || h.EndTime == nil { return "", false } return *h.EndTime, true } // HasEndTime returns a boolean if a field has been set. func (h *HostActionMute) HasEndTime() bool { if h != nil && h.EndTime != nil { return true } return false } // SetEndTime allocates a new h.EndTime and returns the pointer to it. func (h *HostActionMute) SetEndTime(v string) { h.EndTime = &v } // GetMessage returns the Message field if non-nil, zero value otherwise. func (h *HostActionMute) GetMessage() string { if h == nil || h.Message == nil { return "" } return *h.Message } // GetOkMessage returns a tuple with the Message field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostActionMute) GetMessageOk() (string, bool) { if h == nil || h.Message == nil { return "", false } return *h.Message, true } // HasMessage returns a boolean if a field has been set. func (h *HostActionMute) HasMessage() bool { if h != nil && h.Message != nil { return true } return false } // SetMessage allocates a new h.Message and returns the pointer to it. func (h *HostActionMute) SetMessage(v string) { h.Message = &v } // GetOverride returns the Override field if non-nil, zero value otherwise. func (h *HostActionMute) GetOverride() bool { if h == nil || h.Override == nil { return false } return *h.Override } // GetOkOverride returns a tuple with the Override field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostActionMute) GetOverrideOk() (bool, bool) { if h == nil || h.Override == nil { return false, false } return *h.Override, true } // HasOverride returns a boolean if a field has been set. func (h *HostActionMute) HasOverride() bool { if h != nil && h.Override != nil { return true } return false } // SetOverride allocates a new h.Override and returns the pointer to it. func (h *HostActionMute) SetOverride(v bool) { h.Override = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (h *HostMapWidget) GetHeight() int { if h == nil || h.Height == nil { return 0 } return *h.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetHeightOk() (int, bool) { if h == nil || h.Height == nil { return 0, false } return *h.Height, true } // HasHeight returns a boolean if a field has been set. func (h *HostMapWidget) HasHeight() bool { if h != nil && h.Height != nil { return true } return false } // SetHeight allocates a new h.Height and returns the pointer to it. func (h *HostMapWidget) SetHeight(v int) { h.Height = &v } // GetLegend returns the Legend field if non-nil, zero value otherwise. func (h *HostMapWidget) GetLegend() bool { if h == nil || h.Legend == nil { return false } return *h.Legend } // GetOkLegend returns a tuple with the Legend field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetLegendOk() (bool, bool) { if h == nil || h.Legend == nil { return false, false } return *h.Legend, true } // HasLegend returns a boolean if a field has been set. func (h *HostMapWidget) HasLegend() bool { if h != nil && h.Legend != nil { return true } return false } // SetLegend allocates a new h.Legend and returns the pointer to it. func (h *HostMapWidget) SetLegend(v bool) { h.Legend = &v } // GetLegendSize returns the LegendSize field if non-nil, zero value otherwise. func (h *HostMapWidget) GetLegendSize() int { if h == nil || h.LegendSize == nil { return 0 } return *h.LegendSize } // GetOkLegendSize returns a tuple with the LegendSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetLegendSizeOk() (int, bool) { if h == nil || h.LegendSize == nil { return 0, false } return *h.LegendSize, true } // HasLegendSize returns a boolean if a field has been set. func (h *HostMapWidget) HasLegendSize() bool { if h != nil && h.LegendSize != nil { return true } return false } // SetLegendSize allocates a new h.LegendSize and returns the pointer to it. func (h *HostMapWidget) SetLegendSize(v int) { h.LegendSize = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (h *HostMapWidget) GetQuery() string { if h == nil || h.Query == nil { return "" } return *h.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetQueryOk() (string, bool) { if h == nil || h.Query == nil { return "", false } return *h.Query, true } // HasQuery returns a boolean if a field has been set. func (h *HostMapWidget) HasQuery() bool { if h != nil && h.Query != nil { return true } return false } // SetQuery allocates a new h.Query and returns the pointer to it. func (h *HostMapWidget) SetQuery(v string) { h.Query = &v } // GetTileDef returns the TileDef field if non-nil, zero value otherwise. func (h *HostMapWidget) GetTileDef() TileDef { if h == nil || h.TileDef == nil { return TileDef{} } return *h.TileDef } // GetOkTileDef returns a tuple with the TileDef field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetTileDefOk() (TileDef, bool) { if h == nil || h.TileDef == nil { return TileDef{}, false } return *h.TileDef, true } // HasTileDef returns a boolean if a field has been set. func (h *HostMapWidget) HasTileDef() bool { if h != nil && h.TileDef != nil { return true } return false } // SetTileDef allocates a new h.TileDef and returns the pointer to it. func (h *HostMapWidget) SetTileDef(v TileDef) { h.TileDef = &v } // GetTimeframe returns the Timeframe field if non-nil, zero value otherwise. func (h *HostMapWidget) GetTimeframe() string { if h == nil || h.Timeframe == nil { return "" } return *h.Timeframe } // GetOkTimeframe returns a tuple with the Timeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetTimeframeOk() (string, bool) { if h == nil || h.Timeframe == nil { return "", false } return *h.Timeframe, true } // HasTimeframe returns a boolean if a field has been set. func (h *HostMapWidget) HasTimeframe() bool { if h != nil && h.Timeframe != nil { return true } return false } // SetTimeframe allocates a new h.Timeframe and returns the pointer to it. func (h *HostMapWidget) SetTimeframe(v string) { h.Timeframe = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (h *HostMapWidget) GetTitle() bool { if h == nil || h.Title == nil { return false } return *h.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetTitleOk() (bool, bool) { if h == nil || h.Title == nil { return false, false } return *h.Title, true } // HasTitle returns a boolean if a field has been set. func (h *HostMapWidget) HasTitle() bool { if h != nil && h.Title != nil { return true } return false } // SetTitle allocates a new h.Title and returns the pointer to it. func (h *HostMapWidget) SetTitle(v bool) { h.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (h *HostMapWidget) GetTitleAlign() string { if h == nil || h.TitleAlign == nil { return "" } return *h.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetTitleAlignOk() (string, bool) { if h == nil || h.TitleAlign == nil { return "", false } return *h.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (h *HostMapWidget) HasTitleAlign() bool { if h != nil && h.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new h.TitleAlign and returns the pointer to it. func (h *HostMapWidget) SetTitleAlign(v string) { h.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (h *HostMapWidget) GetTitleSize() int { if h == nil || h.TitleSize == nil { return 0 } return *h.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetTitleSizeOk() (int, bool) { if h == nil || h.TitleSize == nil { return 0, false } return *h.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (h *HostMapWidget) HasTitleSize() bool { if h != nil && h.TitleSize != nil { return true } return false } // SetTitleSize allocates a new h.TitleSize and returns the pointer to it. func (h *HostMapWidget) SetTitleSize(v int) { h.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (h *HostMapWidget) GetTitleText() string { if h == nil || h.TitleText == nil { return "" } return *h.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetTitleTextOk() (string, bool) { if h == nil || h.TitleText == nil { return "", false } return *h.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (h *HostMapWidget) HasTitleText() bool { if h != nil && h.TitleText != nil { return true } return false } // SetTitleText allocates a new h.TitleText and returns the pointer to it. func (h *HostMapWidget) SetTitleText(v string) { h.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (h *HostMapWidget) GetType() string { if h == nil || h.Type == nil { return "" } return *h.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetTypeOk() (string, bool) { if h == nil || h.Type == nil { return "", false } return *h.Type, true } // HasType returns a boolean if a field has been set. func (h *HostMapWidget) HasType() bool { if h != nil && h.Type != nil { return true } return false } // SetType allocates a new h.Type and returns the pointer to it. func (h *HostMapWidget) SetType(v string) { h.Type = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (h *HostMapWidget) GetWidth() int { if h == nil || h.Width == nil { return 0 } return *h.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetWidthOk() (int, bool) { if h == nil || h.Width == nil { return 0, false } return *h.Width, true } // HasWidth returns a boolean if a field has been set. func (h *HostMapWidget) HasWidth() bool { if h != nil && h.Width != nil { return true } return false } // SetWidth allocates a new h.Width and returns the pointer to it. func (h *HostMapWidget) SetWidth(v int) { h.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (h *HostMapWidget) GetX() int { if h == nil || h.X == nil { return 0 } return *h.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetXOk() (int, bool) { if h == nil || h.X == nil { return 0, false } return *h.X, true } // HasX returns a boolean if a field has been set. func (h *HostMapWidget) HasX() bool { if h != nil && h.X != nil { return true } return false } // SetX allocates a new h.X and returns the pointer to it. func (h *HostMapWidget) SetX(v int) { h.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (h *HostMapWidget) GetY() int { if h == nil || h.Y == nil { return 0 } return *h.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (h *HostMapWidget) GetYOk() (int, bool) { if h == nil || h.Y == nil { return 0, false } return *h.Y, true } // HasY returns a boolean if a field has been set. func (h *HostMapWidget) HasY() bool { if h != nil && h.Y != nil { return true } return false } // SetY allocates a new h.Y and returns the pointer to it. func (h *HostMapWidget) SetY(v int) { h.Y = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (i *IFrameWidget) GetHeight() int { if i == nil || i.Height == nil { return 0 } return *i.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IFrameWidget) GetHeightOk() (int, bool) { if i == nil || i.Height == nil { return 0, false } return *i.Height, true } // HasHeight returns a boolean if a field has been set. func (i *IFrameWidget) HasHeight() bool { if i != nil && i.Height != nil { return true } return false } // SetHeight allocates a new i.Height and returns the pointer to it. func (i *IFrameWidget) SetHeight(v int) { i.Height = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (i *IFrameWidget) GetTitle() bool { if i == nil || i.Title == nil { return false } return *i.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IFrameWidget) GetTitleOk() (bool, bool) { if i == nil || i.Title == nil { return false, false } return *i.Title, true } // HasTitle returns a boolean if a field has been set. func (i *IFrameWidget) HasTitle() bool { if i != nil && i.Title != nil { return true } return false } // SetTitle allocates a new i.Title and returns the pointer to it. func (i *IFrameWidget) SetTitle(v bool) { i.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (i *IFrameWidget) GetTitleAlign() string { if i == nil || i.TitleAlign == nil { return "" } return *i.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IFrameWidget) GetTitleAlignOk() (string, bool) { if i == nil || i.TitleAlign == nil { return "", false } return *i.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (i *IFrameWidget) HasTitleAlign() bool { if i != nil && i.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new i.TitleAlign and returns the pointer to it. func (i *IFrameWidget) SetTitleAlign(v string) { i.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (i *IFrameWidget) GetTitleSize() int { if i == nil || i.TitleSize == nil { return 0 } return *i.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IFrameWidget) GetTitleSizeOk() (int, bool) { if i == nil || i.TitleSize == nil { return 0, false } return *i.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (i *IFrameWidget) HasTitleSize() bool { if i != nil && i.TitleSize != nil { return true } return false } // SetTitleSize allocates a new i.TitleSize and returns the pointer to it. func (i *IFrameWidget) SetTitleSize(v int) { i.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (i *IFrameWidget) GetTitleText() string { if i == nil || i.TitleText == nil { return "" } return *i.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IFrameWidget) GetTitleTextOk() (string, bool) { if i == nil || i.TitleText == nil { return "", false } return *i.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (i *IFrameWidget) HasTitleText() bool { if i != nil && i.TitleText != nil { return true } return false } // SetTitleText allocates a new i.TitleText and returns the pointer to it. func (i *IFrameWidget) SetTitleText(v string) { i.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (i *IFrameWidget) GetType() string { if i == nil || i.Type == nil { return "" } return *i.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IFrameWidget) GetTypeOk() (string, bool) { if i == nil || i.Type == nil { return "", false } return *i.Type, true } // HasType returns a boolean if a field has been set. func (i *IFrameWidget) HasType() bool { if i != nil && i.Type != nil { return true } return false } // SetType allocates a new i.Type and returns the pointer to it. func (i *IFrameWidget) SetType(v string) { i.Type = &v } // GetUrl returns the Url field if non-nil, zero value otherwise. func (i *IFrameWidget) GetUrl() string { if i == nil || i.Url == nil { return "" } return *i.Url } // GetOkUrl returns a tuple with the Url field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IFrameWidget) GetUrlOk() (string, bool) { if i == nil || i.Url == nil { return "", false } return *i.Url, true } // HasUrl returns a boolean if a field has been set. func (i *IFrameWidget) HasUrl() bool { if i != nil && i.Url != nil { return true } return false } // SetUrl allocates a new i.Url and returns the pointer to it. func (i *IFrameWidget) SetUrl(v string) { i.Url = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (i *IFrameWidget) GetWidth() int { if i == nil || i.Width == nil { return 0 } return *i.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IFrameWidget) GetWidthOk() (int, bool) { if i == nil || i.Width == nil { return 0, false } return *i.Width, true } // HasWidth returns a boolean if a field has been set. func (i *IFrameWidget) HasWidth() bool { if i != nil && i.Width != nil { return true } return false } // SetWidth allocates a new i.Width and returns the pointer to it. func (i *IFrameWidget) SetWidth(v int) { i.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (i *IFrameWidget) GetX() int { if i == nil || i.X == nil { return 0 } return *i.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IFrameWidget) GetXOk() (int, bool) { if i == nil || i.X == nil { return 0, false } return *i.X, true } // HasX returns a boolean if a field has been set. func (i *IFrameWidget) HasX() bool { if i != nil && i.X != nil { return true } return false } // SetX allocates a new i.X and returns the pointer to it. func (i *IFrameWidget) SetX(v int) { i.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (i *IFrameWidget) GetY() int { if i == nil || i.Y == nil { return 0 } return *i.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *IFrameWidget) GetYOk() (int, bool) { if i == nil || i.Y == nil { return 0, false } return *i.Y, true } // HasY returns a boolean if a field has been set. func (i *IFrameWidget) HasY() bool { if i != nil && i.Y != nil { return true } return false } // SetY allocates a new i.Y and returns the pointer to it. func (i *IFrameWidget) SetY(v int) { i.Y = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (i *ImageWidget) GetHeight() int { if i == nil || i.Height == nil { return 0 } return *i.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *ImageWidget) GetHeightOk() (int, bool) { if i == nil || i.Height == nil { return 0, false } return *i.Height, true } // HasHeight returns a boolean if a field has been set. func (i *ImageWidget) HasHeight() bool { if i != nil && i.Height != nil { return true } return false } // SetHeight allocates a new i.Height and returns the pointer to it. func (i *ImageWidget) SetHeight(v int) { i.Height = &v } // GetSizing returns the Sizing field if non-nil, zero value otherwise. func (i *ImageWidget) GetSizing() string { if i == nil || i.Sizing == nil { return "" } return *i.Sizing } // GetOkSizing returns a tuple with the Sizing field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *ImageWidget) GetSizingOk() (string, bool) { if i == nil || i.Sizing == nil { return "", false } return *i.Sizing, true } // HasSizing returns a boolean if a field has been set. func (i *ImageWidget) HasSizing() bool { if i != nil && i.Sizing != nil { return true } return false } // SetSizing allocates a new i.Sizing and returns the pointer to it. func (i *ImageWidget) SetSizing(v string) { i.Sizing = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (i *ImageWidget) GetTitle() bool { if i == nil || i.Title == nil { return false } return *i.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *ImageWidget) GetTitleOk() (bool, bool) { if i == nil || i.Title == nil { return false, false } return *i.Title, true } // HasTitle returns a boolean if a field has been set. func (i *ImageWidget) HasTitle() bool { if i != nil && i.Title != nil { return true } return false } // SetTitle allocates a new i.Title and returns the pointer to it. func (i *ImageWidget) SetTitle(v bool) { i.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (i *ImageWidget) GetTitleAlign() string { if i == nil || i.TitleAlign == nil { return "" } return *i.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *ImageWidget) GetTitleAlignOk() (string, bool) { if i == nil || i.TitleAlign == nil { return "", false } return *i.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (i *ImageWidget) HasTitleAlign() bool { if i != nil && i.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new i.TitleAlign and returns the pointer to it. func (i *ImageWidget) SetTitleAlign(v string) { i.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (i *ImageWidget) GetTitleSize() TextSize { if i == nil || i.TitleSize == nil { return TextSize{} } return *i.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *ImageWidget) GetTitleSizeOk() (TextSize, bool) { if i == nil || i.TitleSize == nil { return TextSize{}, false } return *i.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (i *ImageWidget) HasTitleSize() bool { if i != nil && i.TitleSize != nil { return true } return false } // SetTitleSize allocates a new i.TitleSize and returns the pointer to it. func (i *ImageWidget) SetTitleSize(v TextSize) { i.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (i *ImageWidget) GetTitleText() string { if i == nil || i.TitleText == nil { return "" } return *i.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *ImageWidget) GetTitleTextOk() (string, bool) { if i == nil || i.TitleText == nil { return "", false } return *i.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (i *ImageWidget) HasTitleText() bool { if i != nil && i.TitleText != nil { return true } return false } // SetTitleText allocates a new i.TitleText and returns the pointer to it. func (i *ImageWidget) SetTitleText(v string) { i.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (i *ImageWidget) GetType() string { if i == nil || i.Type == nil { return "" } return *i.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *ImageWidget) GetTypeOk() (string, bool) { if i == nil || i.Type == nil { return "", false } return *i.Type, true } // HasType returns a boolean if a field has been set. func (i *ImageWidget) HasType() bool { if i != nil && i.Type != nil { return true } return false } // SetType allocates a new i.Type and returns the pointer to it. func (i *ImageWidget) SetType(v string) { i.Type = &v } // GetUrl returns the Url field if non-nil, zero value otherwise. func (i *ImageWidget) GetUrl() string { if i == nil || i.Url == nil { return "" } return *i.Url } // GetOkUrl returns a tuple with the Url field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *ImageWidget) GetUrlOk() (string, bool) { if i == nil || i.Url == nil { return "", false } return *i.Url, true } // HasUrl returns a boolean if a field has been set. func (i *ImageWidget) HasUrl() bool { if i != nil && i.Url != nil { return true } return false } // SetUrl allocates a new i.Url and returns the pointer to it. func (i *ImageWidget) SetUrl(v string) { i.Url = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (i *ImageWidget) GetWidth() int { if i == nil || i.Width == nil { return 0 } return *i.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *ImageWidget) GetWidthOk() (int, bool) { if i == nil || i.Width == nil { return 0, false } return *i.Width, true } // HasWidth returns a boolean if a field has been set. func (i *ImageWidget) HasWidth() bool { if i != nil && i.Width != nil { return true } return false } // SetWidth allocates a new i.Width and returns the pointer to it. func (i *ImageWidget) SetWidth(v int) { i.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (i *ImageWidget) GetX() int { if i == nil || i.X == nil { return 0 } return *i.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *ImageWidget) GetXOk() (int, bool) { if i == nil || i.X == nil { return 0, false } return *i.X, true } // HasX returns a boolean if a field has been set. func (i *ImageWidget) HasX() bool { if i != nil && i.X != nil { return true } return false } // SetX allocates a new i.X and returns the pointer to it. func (i *ImageWidget) SetX(v int) { i.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (i *ImageWidget) GetY() int { if i == nil || i.Y == nil { return 0 } return *i.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (i *ImageWidget) GetYOk() (int, bool) { if i == nil || i.Y == nil { return 0, false } return *i.Y, true } // HasY returns a boolean if a field has been set. func (i *ImageWidget) HasY() bool { if i != nil && i.Y != nil { return true } return false } // SetY allocates a new i.Y and returns the pointer to it. func (i *ImageWidget) SetY(v int) { i.Y = &v } // GetHost returns the Host field if non-nil, zero value otherwise. func (m *Metric) GetHost() string { if m == nil || m.Host == nil { return "" } return *m.Host } // GetOkHost returns a tuple with the Host field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Metric) GetHostOk() (string, bool) { if m == nil || m.Host == nil { return "", false } return *m.Host, true } // HasHost returns a boolean if a field has been set. func (m *Metric) HasHost() bool { if m != nil && m.Host != nil { return true } return false } // SetHost allocates a new m.Host and returns the pointer to it. func (m *Metric) SetHost(v string) { m.Host = &v } // GetMetric returns the Metric field if non-nil, zero value otherwise. func (m *Metric) GetMetric() string { if m == nil || m.Metric == nil { return "" } return *m.Metric } // GetOkMetric returns a tuple with the Metric field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Metric) GetMetricOk() (string, bool) { if m == nil || m.Metric == nil { return "", false } return *m.Metric, true } // HasMetric returns a boolean if a field has been set. func (m *Metric) HasMetric() bool { if m != nil && m.Metric != nil { return true } return false } // SetMetric allocates a new m.Metric and returns the pointer to it. func (m *Metric) SetMetric(v string) { m.Metric = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (m *Metric) GetType() string { if m == nil || m.Type == nil { return "" } return *m.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Metric) GetTypeOk() (string, bool) { if m == nil || m.Type == nil { return "", false } return *m.Type, true } // HasType returns a boolean if a field has been set. func (m *Metric) HasType() bool { if m != nil && m.Type != nil { return true } return false } // SetType allocates a new m.Type and returns the pointer to it. func (m *Metric) SetType(v string) { m.Type = &v } // GetUnit returns the Unit field if non-nil, zero value otherwise. func (m *Metric) GetUnit() string { if m == nil || m.Unit == nil { return "" } return *m.Unit } // GetOkUnit returns a tuple with the Unit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Metric) GetUnitOk() (string, bool) { if m == nil || m.Unit == nil { return "", false } return *m.Unit, true } // HasUnit returns a boolean if a field has been set. func (m *Metric) HasUnit() bool { if m != nil && m.Unit != nil { return true } return false } // SetUnit allocates a new m.Unit and returns the pointer to it. func (m *Metric) SetUnit(v string) { m.Unit = &v } // GetDescription returns the Description field if non-nil, zero value otherwise. func (m *MetricMetadata) GetDescription() string { if m == nil || m.Description == nil { return "" } return *m.Description } // GetOkDescription returns a tuple with the Description field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *MetricMetadata) GetDescriptionOk() (string, bool) { if m == nil || m.Description == nil { return "", false } return *m.Description, true } // HasDescription returns a boolean if a field has been set. func (m *MetricMetadata) HasDescription() bool { if m != nil && m.Description != nil { return true } return false } // SetDescription allocates a new m.Description and returns the pointer to it. func (m *MetricMetadata) SetDescription(v string) { m.Description = &v } // GetPerUnit returns the PerUnit field if non-nil, zero value otherwise. func (m *MetricMetadata) GetPerUnit() string { if m == nil || m.PerUnit == nil { return "" } return *m.PerUnit } // GetOkPerUnit returns a tuple with the PerUnit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *MetricMetadata) GetPerUnitOk() (string, bool) { if m == nil || m.PerUnit == nil { return "", false } return *m.PerUnit, true } // HasPerUnit returns a boolean if a field has been set. func (m *MetricMetadata) HasPerUnit() bool { if m != nil && m.PerUnit != nil { return true } return false } // SetPerUnit allocates a new m.PerUnit and returns the pointer to it. func (m *MetricMetadata) SetPerUnit(v string) { m.PerUnit = &v } // GetShortName returns the ShortName field if non-nil, zero value otherwise. func (m *MetricMetadata) GetShortName() string { if m == nil || m.ShortName == nil { return "" } return *m.ShortName } // GetOkShortName returns a tuple with the ShortName field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *MetricMetadata) GetShortNameOk() (string, bool) { if m == nil || m.ShortName == nil { return "", false } return *m.ShortName, true } // HasShortName returns a boolean if a field has been set. func (m *MetricMetadata) HasShortName() bool { if m != nil && m.ShortName != nil { return true } return false } // SetShortName allocates a new m.ShortName and returns the pointer to it. func (m *MetricMetadata) SetShortName(v string) { m.ShortName = &v } // GetStatsdInterval returns the StatsdInterval field if non-nil, zero value otherwise. func (m *MetricMetadata) GetStatsdInterval() int { if m == nil || m.StatsdInterval == nil { return 0 } return *m.StatsdInterval } // GetOkStatsdInterval returns a tuple with the StatsdInterval field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *MetricMetadata) GetStatsdIntervalOk() (int, bool) { if m == nil || m.StatsdInterval == nil { return 0, false } return *m.StatsdInterval, true } // HasStatsdInterval returns a boolean if a field has been set. func (m *MetricMetadata) HasStatsdInterval() bool { if m != nil && m.StatsdInterval != nil { return true } return false } // SetStatsdInterval allocates a new m.StatsdInterval and returns the pointer to it. func (m *MetricMetadata) SetStatsdInterval(v int) { m.StatsdInterval = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (m *MetricMetadata) GetType() string { if m == nil || m.Type == nil { return "" } return *m.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *MetricMetadata) GetTypeOk() (string, bool) { if m == nil || m.Type == nil { return "", false } return *m.Type, true } // HasType returns a boolean if a field has been set. func (m *MetricMetadata) HasType() bool { if m != nil && m.Type != nil { return true } return false } // SetType allocates a new m.Type and returns the pointer to it. func (m *MetricMetadata) SetType(v string) { m.Type = &v } // GetUnit returns the Unit field if non-nil, zero value otherwise. func (m *MetricMetadata) GetUnit() string { if m == nil || m.Unit == nil { return "" } return *m.Unit } // GetOkUnit returns a tuple with the Unit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *MetricMetadata) GetUnitOk() (string, bool) { if m == nil || m.Unit == nil { return "", false } return *m.Unit, true } // HasUnit returns a boolean if a field has been set. func (m *MetricMetadata) HasUnit() bool { if m != nil && m.Unit != nil { return true } return false } // SetUnit allocates a new m.Unit and returns the pointer to it. func (m *MetricMetadata) SetUnit(v string) { m.Unit = &v } // GetCreator returns the Creator field if non-nil, zero value otherwise. func (m *Monitor) GetCreator() Creator { if m == nil || m.Creator == nil { return Creator{} } return *m.Creator } // GetOkCreator returns a tuple with the Creator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetCreatorOk() (Creator, bool) { if m == nil || m.Creator == nil { return Creator{}, false } return *m.Creator, true } // HasCreator returns a boolean if a field has been set. func (m *Monitor) HasCreator() bool { if m != nil && m.Creator != nil { return true } return false } // SetCreator allocates a new m.Creator and returns the pointer to it. func (m *Monitor) SetCreator(v Creator) { m.Creator = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (m *Monitor) GetId() int { if m == nil || m.Id == nil { return 0 } return *m.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetIdOk() (int, bool) { if m == nil || m.Id == nil { return 0, false } return *m.Id, true } // HasId returns a boolean if a field has been set. func (m *Monitor) HasId() bool { if m != nil && m.Id != nil { return true } return false } // SetId allocates a new m.Id and returns the pointer to it. func (m *Monitor) SetId(v int) { m.Id = &v } // GetMessage returns the Message field if non-nil, zero value otherwise. func (m *Monitor) GetMessage() string { if m == nil || m.Message == nil { return "" } return *m.Message } // GetOkMessage returns a tuple with the Message field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetMessageOk() (string, bool) { if m == nil || m.Message == nil { return "", false } return *m.Message, true } // HasMessage returns a boolean if a field has been set. func (m *Monitor) HasMessage() bool { if m != nil && m.Message != nil { return true } return false } // SetMessage allocates a new m.Message and returns the pointer to it. func (m *Monitor) SetMessage(v string) { m.Message = &v } // GetName returns the Name field if non-nil, zero value otherwise. func (m *Monitor) GetName() string { if m == nil || m.Name == nil { return "" } return *m.Name } // GetOkName returns a tuple with the Name field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetNameOk() (string, bool) { if m == nil || m.Name == nil { return "", false } return *m.Name, true } // HasName returns a boolean if a field has been set. func (m *Monitor) HasName() bool { if m != nil && m.Name != nil { return true } return false } // SetName allocates a new m.Name and returns the pointer to it. func (m *Monitor) SetName(v string) { m.Name = &v } // GetOptions returns the Options field if non-nil, zero value otherwise. func (m *Monitor) GetOptions() Options { if m == nil || m.Options == nil { return Options{} } return *m.Options } // GetOkOptions returns a tuple with the Options field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetOptionsOk() (Options, bool) { if m == nil || m.Options == nil { return Options{}, false } return *m.Options, true } // HasOptions returns a boolean if a field has been set. func (m *Monitor) HasOptions() bool { if m != nil && m.Options != nil { return true } return false } // SetOptions allocates a new m.Options and returns the pointer to it. func (m *Monitor) SetOptions(v Options) { m.Options = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (m *Monitor) GetQuery() string { if m == nil || m.Query == nil { return "" } return *m.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetQueryOk() (string, bool) { if m == nil || m.Query == nil { return "", false } return *m.Query, true } // HasQuery returns a boolean if a field has been set. func (m *Monitor) HasQuery() bool { if m != nil && m.Query != nil { return true } return false } // SetQuery allocates a new m.Query and returns the pointer to it. func (m *Monitor) SetQuery(v string) { m.Query = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (m *Monitor) GetType() string { if m == nil || m.Type == nil { return "" } return *m.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (m *Monitor) GetTypeOk() (string, bool) { if m == nil || m.Type == nil { return "", false } return *m.Type, true } // HasType returns a boolean if a field has been set. func (m *Monitor) HasType() bool { if m != nil && m.Type != nil { return true } return false } // SetType allocates a new m.Type and returns the pointer to it. func (m *Monitor) SetType(v string) { m.Type = &v } // GetAutoRefresh returns the AutoRefresh field if non-nil, zero value otherwise. func (n *NoteWidget) GetAutoRefresh() bool { if n == nil || n.AutoRefresh == nil { return false } return *n.AutoRefresh } // GetOkAutoRefresh returns a tuple with the AutoRefresh field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetAutoRefreshOk() (bool, bool) { if n == nil || n.AutoRefresh == nil { return false, false } return *n.AutoRefresh, true } // HasAutoRefresh returns a boolean if a field has been set. func (n *NoteWidget) HasAutoRefresh() bool { if n != nil && n.AutoRefresh != nil { return true } return false } // SetAutoRefresh allocates a new n.AutoRefresh and returns the pointer to it. func (n *NoteWidget) SetAutoRefresh(v bool) { n.AutoRefresh = &v } // GetColor returns the Color field if non-nil, zero value otherwise. func (n *NoteWidget) GetColor() string { if n == nil || n.Color == nil { return "" } return *n.Color } // GetOkColor returns a tuple with the Color field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetColorOk() (string, bool) { if n == nil || n.Color == nil { return "", false } return *n.Color, true } // HasColor returns a boolean if a field has been set. func (n *NoteWidget) HasColor() bool { if n != nil && n.Color != nil { return true } return false } // SetColor allocates a new n.Color and returns the pointer to it. func (n *NoteWidget) SetColor(v string) { n.Color = &v } // GetFontSize returns the FontSize field if non-nil, zero value otherwise. func (n *NoteWidget) GetFontSize() int { if n == nil || n.FontSize == nil { return 0 } return *n.FontSize } // GetOkFontSize returns a tuple with the FontSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetFontSizeOk() (int, bool) { if n == nil || n.FontSize == nil { return 0, false } return *n.FontSize, true } // HasFontSize returns a boolean if a field has been set. func (n *NoteWidget) HasFontSize() bool { if n != nil && n.FontSize != nil { return true } return false } // SetFontSize allocates a new n.FontSize and returns the pointer to it. func (n *NoteWidget) SetFontSize(v int) { n.FontSize = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (n *NoteWidget) GetHeight() int { if n == nil || n.Height == nil { return 0 } return *n.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetHeightOk() (int, bool) { if n == nil || n.Height == nil { return 0, false } return *n.Height, true } // HasHeight returns a boolean if a field has been set. func (n *NoteWidget) HasHeight() bool { if n != nil && n.Height != nil { return true } return false } // SetHeight allocates a new n.Height and returns the pointer to it. func (n *NoteWidget) SetHeight(v int) { n.Height = &v } // GetHtml returns the Html field if non-nil, zero value otherwise. func (n *NoteWidget) GetHtml() string { if n == nil || n.Html == nil { return "" } return *n.Html } // GetOkHtml returns a tuple with the Html field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetHtmlOk() (string, bool) { if n == nil || n.Html == nil { return "", false } return *n.Html, true } // HasHtml returns a boolean if a field has been set. func (n *NoteWidget) HasHtml() bool { if n != nil && n.Html != nil { return true } return false } // SetHtml allocates a new n.Html and returns the pointer to it. func (n *NoteWidget) SetHtml(v string) { n.Html = &v } // GetNote returns the Note field if non-nil, zero value otherwise. func (n *NoteWidget) GetNote() string { if n == nil || n.Note == nil { return "" } return *n.Note } // GetOkNote returns a tuple with the Note field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetNoteOk() (string, bool) { if n == nil || n.Note == nil { return "", false } return *n.Note, true } // HasNote returns a boolean if a field has been set. func (n *NoteWidget) HasNote() bool { if n != nil && n.Note != nil { return true } return false } // SetNote allocates a new n.Note and returns the pointer to it. func (n *NoteWidget) SetNote(v string) { n.Note = &v } // GetRefreshEvery returns the RefreshEvery field if non-nil, zero value otherwise. func (n *NoteWidget) GetRefreshEvery() int { if n == nil || n.RefreshEvery == nil { return 0 } return *n.RefreshEvery } // GetOkRefreshEvery returns a tuple with the RefreshEvery field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetRefreshEveryOk() (int, bool) { if n == nil || n.RefreshEvery == nil { return 0, false } return *n.RefreshEvery, true } // HasRefreshEvery returns a boolean if a field has been set. func (n *NoteWidget) HasRefreshEvery() bool { if n != nil && n.RefreshEvery != nil { return true } return false } // SetRefreshEvery allocates a new n.RefreshEvery and returns the pointer to it. func (n *NoteWidget) SetRefreshEvery(v int) { n.RefreshEvery = &v } // GetTextAlign returns the TextAlign field if non-nil, zero value otherwise. func (n *NoteWidget) GetTextAlign() string { if n == nil || n.TextAlign == nil { return "" } return *n.TextAlign } // GetOkTextAlign returns a tuple with the TextAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetTextAlignOk() (string, bool) { if n == nil || n.TextAlign == nil { return "", false } return *n.TextAlign, true } // HasTextAlign returns a boolean if a field has been set. func (n *NoteWidget) HasTextAlign() bool { if n != nil && n.TextAlign != nil { return true } return false } // SetTextAlign allocates a new n.TextAlign and returns the pointer to it. func (n *NoteWidget) SetTextAlign(v string) { n.TextAlign = &v } // GetTick returns the Tick field if non-nil, zero value otherwise. func (n *NoteWidget) GetTick() bool { if n == nil || n.Tick == nil { return false } return *n.Tick } // GetOkTick returns a tuple with the Tick field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetTickOk() (bool, bool) { if n == nil || n.Tick == nil { return false, false } return *n.Tick, true } // HasTick returns a boolean if a field has been set. func (n *NoteWidget) HasTick() bool { if n != nil && n.Tick != nil { return true } return false } // SetTick allocates a new n.Tick and returns the pointer to it. func (n *NoteWidget) SetTick(v bool) { n.Tick = &v } // GetTickEdge returns the TickEdge field if non-nil, zero value otherwise. func (n *NoteWidget) GetTickEdge() string { if n == nil || n.TickEdge == nil { return "" } return *n.TickEdge } // GetOkTickEdge returns a tuple with the TickEdge field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetTickEdgeOk() (string, bool) { if n == nil || n.TickEdge == nil { return "", false } return *n.TickEdge, true } // HasTickEdge returns a boolean if a field has been set. func (n *NoteWidget) HasTickEdge() bool { if n != nil && n.TickEdge != nil { return true } return false } // SetTickEdge allocates a new n.TickEdge and returns the pointer to it. func (n *NoteWidget) SetTickEdge(v string) { n.TickEdge = &v } // GetTickPos returns the TickPos field if non-nil, zero value otherwise. func (n *NoteWidget) GetTickPos() string { if n == nil || n.TickPos == nil { return "" } return *n.TickPos } // GetOkTickPos returns a tuple with the TickPos field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetTickPosOk() (string, bool) { if n == nil || n.TickPos == nil { return "", false } return *n.TickPos, true } // HasTickPos returns a boolean if a field has been set. func (n *NoteWidget) HasTickPos() bool { if n != nil && n.TickPos != nil { return true } return false } // SetTickPos allocates a new n.TickPos and returns the pointer to it. func (n *NoteWidget) SetTickPos(v string) { n.TickPos = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (n *NoteWidget) GetTitle() bool { if n == nil || n.Title == nil { return false } return *n.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetTitleOk() (bool, bool) { if n == nil || n.Title == nil { return false, false } return *n.Title, true } // HasTitle returns a boolean if a field has been set. func (n *NoteWidget) HasTitle() bool { if n != nil && n.Title != nil { return true } return false } // SetTitle allocates a new n.Title and returns the pointer to it. func (n *NoteWidget) SetTitle(v bool) { n.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (n *NoteWidget) GetTitleAlign() string { if n == nil || n.TitleAlign == nil { return "" } return *n.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetTitleAlignOk() (string, bool) { if n == nil || n.TitleAlign == nil { return "", false } return *n.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (n *NoteWidget) HasTitleAlign() bool { if n != nil && n.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new n.TitleAlign and returns the pointer to it. func (n *NoteWidget) SetTitleAlign(v string) { n.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (n *NoteWidget) GetTitleSize() int { if n == nil || n.TitleSize == nil { return 0 } return *n.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetTitleSizeOk() (int, bool) { if n == nil || n.TitleSize == nil { return 0, false } return *n.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (n *NoteWidget) HasTitleSize() bool { if n != nil && n.TitleSize != nil { return true } return false } // SetTitleSize allocates a new n.TitleSize and returns the pointer to it. func (n *NoteWidget) SetTitleSize(v int) { n.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (n *NoteWidget) GetTitleText() string { if n == nil || n.TitleText == nil { return "" } return *n.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetTitleTextOk() (string, bool) { if n == nil || n.TitleText == nil { return "", false } return *n.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (n *NoteWidget) HasTitleText() bool { if n != nil && n.TitleText != nil { return true } return false } // SetTitleText allocates a new n.TitleText and returns the pointer to it. func (n *NoteWidget) SetTitleText(v string) { n.TitleText = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (n *NoteWidget) GetWidth() int { if n == nil || n.Width == nil { return 0 } return *n.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetWidthOk() (int, bool) { if n == nil || n.Width == nil { return 0, false } return *n.Width, true } // HasWidth returns a boolean if a field has been set. func (n *NoteWidget) HasWidth() bool { if n != nil && n.Width != nil { return true } return false } // SetWidth allocates a new n.Width and returns the pointer to it. func (n *NoteWidget) SetWidth(v int) { n.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (n *NoteWidget) GetX() int { if n == nil || n.X == nil { return 0 } return *n.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetXOk() (int, bool) { if n == nil || n.X == nil { return 0, false } return *n.X, true } // HasX returns a boolean if a field has been set. func (n *NoteWidget) HasX() bool { if n != nil && n.X != nil { return true } return false } // SetX allocates a new n.X and returns the pointer to it. func (n *NoteWidget) SetX(v int) { n.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (n *NoteWidget) GetY() int { if n == nil || n.Y == nil { return 0 } return *n.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (n *NoteWidget) GetYOk() (int, bool) { if n == nil || n.Y == nil { return 0, false } return *n.Y, true } // HasY returns a boolean if a field has been set. func (n *NoteWidget) HasY() bool { if n != nil && n.Y != nil { return true } return false } // SetY allocates a new n.Y and returns the pointer to it. func (n *NoteWidget) SetY(v int) { n.Y = &v } // GetEscalationMessage returns the EscalationMessage field if non-nil, zero value otherwise. func (o *Options) GetEscalationMessage() string { if o == nil || o.EscalationMessage == nil { return "" } return *o.EscalationMessage } // GetOkEscalationMessage returns a tuple with the EscalationMessage field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetEscalationMessageOk() (string, bool) { if o == nil || o.EscalationMessage == nil { return "", false } return *o.EscalationMessage, true } // HasEscalationMessage returns a boolean if a field has been set. func (o *Options) HasEscalationMessage() bool { if o != nil && o.EscalationMessage != nil { return true } return false } // SetEscalationMessage allocates a new o.EscalationMessage and returns the pointer to it. func (o *Options) SetEscalationMessage(v string) { o.EscalationMessage = &v } // GetEvaluationDelay returns the EvaluationDelay field if non-nil, zero value otherwise. func (o *Options) GetEvaluationDelay() int { if o == nil || o.EvaluationDelay == nil { return 0 } return *o.EvaluationDelay } // GetOkEvaluationDelay returns a tuple with the EvaluationDelay field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetEvaluationDelayOk() (int, bool) { if o == nil || o.EvaluationDelay == nil { return 0, false } return *o.EvaluationDelay, true } // HasEvaluationDelay returns a boolean if a field has been set. func (o *Options) HasEvaluationDelay() bool { if o != nil && o.EvaluationDelay != nil { return true } return false } // SetEvaluationDelay allocates a new o.EvaluationDelay and returns the pointer to it. func (o *Options) SetEvaluationDelay(v int) { o.EvaluationDelay = &v } // GetIncludeTags returns the IncludeTags field if non-nil, zero value otherwise. func (o *Options) GetIncludeTags() bool { if o == nil || o.IncludeTags == nil { return false } return *o.IncludeTags } // GetOkIncludeTags returns a tuple with the IncludeTags field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetIncludeTagsOk() (bool, bool) { if o == nil || o.IncludeTags == nil { return false, false } return *o.IncludeTags, true } // HasIncludeTags returns a boolean if a field has been set. func (o *Options) HasIncludeTags() bool { if o != nil && o.IncludeTags != nil { return true } return false } // SetIncludeTags allocates a new o.IncludeTags and returns the pointer to it. func (o *Options) SetIncludeTags(v bool) { o.IncludeTags = &v } // GetLocked returns the Locked field if non-nil, zero value otherwise. func (o *Options) GetLocked() bool { if o == nil || o.Locked == nil { return false } return *o.Locked } // GetOkLocked returns a tuple with the Locked field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetLockedOk() (bool, bool) { if o == nil || o.Locked == nil { return false, false } return *o.Locked, true } // HasLocked returns a boolean if a field has been set. func (o *Options) HasLocked() bool { if o != nil && o.Locked != nil { return true } return false } // SetLocked allocates a new o.Locked and returns the pointer to it. func (o *Options) SetLocked(v bool) { o.Locked = &v } // GetNewHostDelay returns the NewHostDelay field if non-nil, zero value otherwise. func (o *Options) GetNewHostDelay() int { if o == nil || o.NewHostDelay == nil { return 0 } return *o.NewHostDelay } // GetOkNewHostDelay returns a tuple with the NewHostDelay field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetNewHostDelayOk() (int, bool) { if o == nil || o.NewHostDelay == nil { return 0, false } return *o.NewHostDelay, true } // HasNewHostDelay returns a boolean if a field has been set. func (o *Options) HasNewHostDelay() bool { if o != nil && o.NewHostDelay != nil { return true } return false } // SetNewHostDelay allocates a new o.NewHostDelay and returns the pointer to it. func (o *Options) SetNewHostDelay(v int) { o.NewHostDelay = &v } // GetNotifyAudit returns the NotifyAudit field if non-nil, zero value otherwise. func (o *Options) GetNotifyAudit() bool { if o == nil || o.NotifyAudit == nil { return false } return *o.NotifyAudit } // GetOkNotifyAudit returns a tuple with the NotifyAudit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetNotifyAuditOk() (bool, bool) { if o == nil || o.NotifyAudit == nil { return false, false } return *o.NotifyAudit, true } // HasNotifyAudit returns a boolean if a field has been set. func (o *Options) HasNotifyAudit() bool { if o != nil && o.NotifyAudit != nil { return true } return false } // SetNotifyAudit allocates a new o.NotifyAudit and returns the pointer to it. func (o *Options) SetNotifyAudit(v bool) { o.NotifyAudit = &v } // GetNotifyNoData returns the NotifyNoData field if non-nil, zero value otherwise. func (o *Options) GetNotifyNoData() bool { if o == nil || o.NotifyNoData == nil { return false } return *o.NotifyNoData } // GetOkNotifyNoData returns a tuple with the NotifyNoData field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetNotifyNoDataOk() (bool, bool) { if o == nil || o.NotifyNoData == nil { return false, false } return *o.NotifyNoData, true } // HasNotifyNoData returns a boolean if a field has been set. func (o *Options) HasNotifyNoData() bool { if o != nil && o.NotifyNoData != nil { return true } return false } // SetNotifyNoData allocates a new o.NotifyNoData and returns the pointer to it. func (o *Options) SetNotifyNoData(v bool) { o.NotifyNoData = &v } // GetRenotifyInterval returns the RenotifyInterval field if non-nil, zero value otherwise. func (o *Options) GetRenotifyInterval() int { if o == nil || o.RenotifyInterval == nil { return 0 } return *o.RenotifyInterval } // GetOkRenotifyInterval returns a tuple with the RenotifyInterval field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetRenotifyIntervalOk() (int, bool) { if o == nil || o.RenotifyInterval == nil { return 0, false } return *o.RenotifyInterval, true } // HasRenotifyInterval returns a boolean if a field has been set. func (o *Options) HasRenotifyInterval() bool { if o != nil && o.RenotifyInterval != nil { return true } return false } // SetRenotifyInterval allocates a new o.RenotifyInterval and returns the pointer to it. func (o *Options) SetRenotifyInterval(v int) { o.RenotifyInterval = &v } // GetRequireFullWindow returns the RequireFullWindow field if non-nil, zero value otherwise. func (o *Options) GetRequireFullWindow() bool { if o == nil || o.RequireFullWindow == nil { return false } return *o.RequireFullWindow } // GetOkRequireFullWindow returns a tuple with the RequireFullWindow field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetRequireFullWindowOk() (bool, bool) { if o == nil || o.RequireFullWindow == nil { return false, false } return *o.RequireFullWindow, true } // HasRequireFullWindow returns a boolean if a field has been set. func (o *Options) HasRequireFullWindow() bool { if o != nil && o.RequireFullWindow != nil { return true } return false } // SetRequireFullWindow allocates a new o.RequireFullWindow and returns the pointer to it. func (o *Options) SetRequireFullWindow(v bool) { o.RequireFullWindow = &v } // GetThresholds returns the Thresholds field if non-nil, zero value otherwise. func (o *Options) GetThresholds() ThresholdCount { if o == nil || o.Thresholds == nil { return ThresholdCount{} } return *o.Thresholds } // GetOkThresholds returns a tuple with the Thresholds field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetThresholdsOk() (ThresholdCount, bool) { if o == nil || o.Thresholds == nil { return ThresholdCount{}, false } return *o.Thresholds, true } // HasThresholds returns a boolean if a field has been set. func (o *Options) HasThresholds() bool { if o != nil && o.Thresholds != nil { return true } return false } // SetThresholds allocates a new o.Thresholds and returns the pointer to it. func (o *Options) SetThresholds(v ThresholdCount) { o.Thresholds = &v } // GetTimeoutH returns the TimeoutH field if non-nil, zero value otherwise. func (o *Options) GetTimeoutH() int { if o == nil || o.TimeoutH == nil { return 0 } return *o.TimeoutH } // GetOkTimeoutH returns a tuple with the TimeoutH field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (o *Options) GetTimeoutHOk() (int, bool) { if o == nil || o.TimeoutH == nil { return 0, false } return *o.TimeoutH, true } // HasTimeoutH returns a boolean if a field has been set. func (o *Options) HasTimeoutH() bool { if o != nil && o.TimeoutH != nil { return true } return false } // SetTimeoutH allocates a new o.TimeoutH and returns the pointer to it. func (o *Options) SetTimeoutH(v int) { o.TimeoutH = &v } // GetAggregator returns the Aggregator field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetAggregator() string { if q == nil || q.Aggregator == nil { return "" } return *q.Aggregator } // GetOkAggregator returns a tuple with the Aggregator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetAggregatorOk() (string, bool) { if q == nil || q.Aggregator == nil { return "", false } return *q.Aggregator, true } // HasAggregator returns a boolean if a field has been set. func (q *QueryValueWidget) HasAggregator() bool { if q != nil && q.Aggregator != nil { return true } return false } // SetAggregator allocates a new q.Aggregator and returns the pointer to it. func (q *QueryValueWidget) SetAggregator(v string) { q.Aggregator = &v } // GetCalcFunc returns the CalcFunc field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetCalcFunc() string { if q == nil || q.CalcFunc == nil { return "" } return *q.CalcFunc } // GetOkCalcFunc returns a tuple with the CalcFunc field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetCalcFuncOk() (string, bool) { if q == nil || q.CalcFunc == nil { return "", false } return *q.CalcFunc, true } // HasCalcFunc returns a boolean if a field has been set. func (q *QueryValueWidget) HasCalcFunc() bool { if q != nil && q.CalcFunc != nil { return true } return false } // SetCalcFunc allocates a new q.CalcFunc and returns the pointer to it. func (q *QueryValueWidget) SetCalcFunc(v string) { q.CalcFunc = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetHeight() int { if q == nil || q.Height == nil { return 0 } return *q.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetHeightOk() (int, bool) { if q == nil || q.Height == nil { return 0, false } return *q.Height, true } // HasHeight returns a boolean if a field has been set. func (q *QueryValueWidget) HasHeight() bool { if q != nil && q.Height != nil { return true } return false } // SetHeight allocates a new q.Height and returns the pointer to it. func (q *QueryValueWidget) SetHeight(v int) { q.Height = &v } // GetIsValidQuery returns the IsValidQuery field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetIsValidQuery() bool { if q == nil || q.IsValidQuery == nil { return false } return *q.IsValidQuery } // GetOkIsValidQuery returns a tuple with the IsValidQuery field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetIsValidQueryOk() (bool, bool) { if q == nil || q.IsValidQuery == nil { return false, false } return *q.IsValidQuery, true } // HasIsValidQuery returns a boolean if a field has been set. func (q *QueryValueWidget) HasIsValidQuery() bool { if q != nil && q.IsValidQuery != nil { return true } return false } // SetIsValidQuery allocates a new q.IsValidQuery and returns the pointer to it. func (q *QueryValueWidget) SetIsValidQuery(v bool) { q.IsValidQuery = &v } // GetMetric returns the Metric field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetMetric() string { if q == nil || q.Metric == nil { return "" } return *q.Metric } // GetOkMetric returns a tuple with the Metric field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetMetricOk() (string, bool) { if q == nil || q.Metric == nil { return "", false } return *q.Metric, true } // HasMetric returns a boolean if a field has been set. func (q *QueryValueWidget) HasMetric() bool { if q != nil && q.Metric != nil { return true } return false } // SetMetric allocates a new q.Metric and returns the pointer to it. func (q *QueryValueWidget) SetMetric(v string) { q.Metric = &v } // GetMetricType returns the MetricType field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetMetricType() string { if q == nil || q.MetricType == nil { return "" } return *q.MetricType } // GetOkMetricType returns a tuple with the MetricType field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetMetricTypeOk() (string, bool) { if q == nil || q.MetricType == nil { return "", false } return *q.MetricType, true } // HasMetricType returns a boolean if a field has been set. func (q *QueryValueWidget) HasMetricType() bool { if q != nil && q.MetricType != nil { return true } return false } // SetMetricType allocates a new q.MetricType and returns the pointer to it. func (q *QueryValueWidget) SetMetricType(v string) { q.MetricType = &v } // GetPrecision returns the Precision field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetPrecision() int { if q == nil || q.Precision == nil { return 0 } return *q.Precision } // GetOkPrecision returns a tuple with the Precision field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetPrecisionOk() (int, bool) { if q == nil || q.Precision == nil { return 0, false } return *q.Precision, true } // HasPrecision returns a boolean if a field has been set. func (q *QueryValueWidget) HasPrecision() bool { if q != nil && q.Precision != nil { return true } return false } // SetPrecision allocates a new q.Precision and returns the pointer to it. func (q *QueryValueWidget) SetPrecision(v int) { q.Precision = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetQuery() string { if q == nil || q.Query == nil { return "" } return *q.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetQueryOk() (string, bool) { if q == nil || q.Query == nil { return "", false } return *q.Query, true } // HasQuery returns a boolean if a field has been set. func (q *QueryValueWidget) HasQuery() bool { if q != nil && q.Query != nil { return true } return false } // SetQuery allocates a new q.Query and returns the pointer to it. func (q *QueryValueWidget) SetQuery(v string) { q.Query = &v } // GetResultCalcFunc returns the ResultCalcFunc field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetResultCalcFunc() string { if q == nil || q.ResultCalcFunc == nil { return "" } return *q.ResultCalcFunc } // GetOkResultCalcFunc returns a tuple with the ResultCalcFunc field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetResultCalcFuncOk() (string, bool) { if q == nil || q.ResultCalcFunc == nil { return "", false } return *q.ResultCalcFunc, true } // HasResultCalcFunc returns a boolean if a field has been set. func (q *QueryValueWidget) HasResultCalcFunc() bool { if q != nil && q.ResultCalcFunc != nil { return true } return false } // SetResultCalcFunc allocates a new q.ResultCalcFunc and returns the pointer to it. func (q *QueryValueWidget) SetResultCalcFunc(v string) { q.ResultCalcFunc = &v } // GetTextAlign returns the TextAlign field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetTextAlign() string { if q == nil || q.TextAlign == nil { return "" } return *q.TextAlign } // GetOkTextAlign returns a tuple with the TextAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetTextAlignOk() (string, bool) { if q == nil || q.TextAlign == nil { return "", false } return *q.TextAlign, true } // HasTextAlign returns a boolean if a field has been set. func (q *QueryValueWidget) HasTextAlign() bool { if q != nil && q.TextAlign != nil { return true } return false } // SetTextAlign allocates a new q.TextAlign and returns the pointer to it. func (q *QueryValueWidget) SetTextAlign(v string) { q.TextAlign = &v } // GetTextSize returns the TextSize field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetTextSize() TextSize { if q == nil || q.TextSize == nil { return TextSize{} } return *q.TextSize } // GetOkTextSize returns a tuple with the TextSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetTextSizeOk() (TextSize, bool) { if q == nil || q.TextSize == nil { return TextSize{}, false } return *q.TextSize, true } // HasTextSize returns a boolean if a field has been set. func (q *QueryValueWidget) HasTextSize() bool { if q != nil && q.TextSize != nil { return true } return false } // SetTextSize allocates a new q.TextSize and returns the pointer to it. func (q *QueryValueWidget) SetTextSize(v TextSize) { q.TextSize = &v } // GetTimeframe returns the Timeframe field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetTimeframe() string { if q == nil || q.Timeframe == nil { return "" } return *q.Timeframe } // GetOkTimeframe returns a tuple with the Timeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetTimeframeOk() (string, bool) { if q == nil || q.Timeframe == nil { return "", false } return *q.Timeframe, true } // HasTimeframe returns a boolean if a field has been set. func (q *QueryValueWidget) HasTimeframe() bool { if q != nil && q.Timeframe != nil { return true } return false } // SetTimeframe allocates a new q.Timeframe and returns the pointer to it. func (q *QueryValueWidget) SetTimeframe(v string) { q.Timeframe = &v } // GetTimeframeAggregator returns the TimeframeAggregator field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetTimeframeAggregator() string { if q == nil || q.TimeframeAggregator == nil { return "" } return *q.TimeframeAggregator } // GetOkTimeframeAggregator returns a tuple with the TimeframeAggregator field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetTimeframeAggregatorOk() (string, bool) { if q == nil || q.TimeframeAggregator == nil { return "", false } return *q.TimeframeAggregator, true } // HasTimeframeAggregator returns a boolean if a field has been set. func (q *QueryValueWidget) HasTimeframeAggregator() bool { if q != nil && q.TimeframeAggregator != nil { return true } return false } // SetTimeframeAggregator allocates a new q.TimeframeAggregator and returns the pointer to it. func (q *QueryValueWidget) SetTimeframeAggregator(v string) { q.TimeframeAggregator = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetTitle() bool { if q == nil || q.Title == nil { return false } return *q.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetTitleOk() (bool, bool) { if q == nil || q.Title == nil { return false, false } return *q.Title, true } // HasTitle returns a boolean if a field has been set. func (q *QueryValueWidget) HasTitle() bool { if q != nil && q.Title != nil { return true } return false } // SetTitle allocates a new q.Title and returns the pointer to it. func (q *QueryValueWidget) SetTitle(v bool) { q.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetTitleAlign() string { if q == nil || q.TitleAlign == nil { return "" } return *q.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetTitleAlignOk() (string, bool) { if q == nil || q.TitleAlign == nil { return "", false } return *q.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (q *QueryValueWidget) HasTitleAlign() bool { if q != nil && q.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new q.TitleAlign and returns the pointer to it. func (q *QueryValueWidget) SetTitleAlign(v string) { q.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetTitleSize() TextSize { if q == nil || q.TitleSize == nil { return TextSize{} } return *q.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetTitleSizeOk() (TextSize, bool) { if q == nil || q.TitleSize == nil { return TextSize{}, false } return *q.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (q *QueryValueWidget) HasTitleSize() bool { if q != nil && q.TitleSize != nil { return true } return false } // SetTitleSize allocates a new q.TitleSize and returns the pointer to it. func (q *QueryValueWidget) SetTitleSize(v TextSize) { q.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetTitleText() string { if q == nil || q.TitleText == nil { return "" } return *q.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetTitleTextOk() (string, bool) { if q == nil || q.TitleText == nil { return "", false } return *q.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (q *QueryValueWidget) HasTitleText() bool { if q != nil && q.TitleText != nil { return true } return false } // SetTitleText allocates a new q.TitleText and returns the pointer to it. func (q *QueryValueWidget) SetTitleText(v string) { q.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetType() string { if q == nil || q.Type == nil { return "" } return *q.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetTypeOk() (string, bool) { if q == nil || q.Type == nil { return "", false } return *q.Type, true } // HasType returns a boolean if a field has been set. func (q *QueryValueWidget) HasType() bool { if q != nil && q.Type != nil { return true } return false } // SetType allocates a new q.Type and returns the pointer to it. func (q *QueryValueWidget) SetType(v string) { q.Type = &v } // GetUnit returns the Unit field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetUnit() string { if q == nil || q.Unit == nil { return "" } return *q.Unit } // GetOkUnit returns a tuple with the Unit field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetUnitOk() (string, bool) { if q == nil || q.Unit == nil { return "", false } return *q.Unit, true } // HasUnit returns a boolean if a field has been set. func (q *QueryValueWidget) HasUnit() bool { if q != nil && q.Unit != nil { return true } return false } // SetUnit allocates a new q.Unit and returns the pointer to it. func (q *QueryValueWidget) SetUnit(v string) { q.Unit = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetWidth() int { if q == nil || q.Width == nil { return 0 } return *q.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetWidthOk() (int, bool) { if q == nil || q.Width == nil { return 0, false } return *q.Width, true } // HasWidth returns a boolean if a field has been set. func (q *QueryValueWidget) HasWidth() bool { if q != nil && q.Width != nil { return true } return false } // SetWidth allocates a new q.Width and returns the pointer to it. func (q *QueryValueWidget) SetWidth(v int) { q.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetX() int { if q == nil || q.X == nil { return 0 } return *q.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetXOk() (int, bool) { if q == nil || q.X == nil { return 0, false } return *q.X, true } // HasX returns a boolean if a field has been set. func (q *QueryValueWidget) HasX() bool { if q != nil && q.X != nil { return true } return false } // SetX allocates a new q.X and returns the pointer to it. func (q *QueryValueWidget) SetX(v int) { q.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (q *QueryValueWidget) GetY() int { if q == nil || q.Y == nil { return 0 } return *q.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (q *QueryValueWidget) GetYOk() (int, bool) { if q == nil || q.Y == nil { return 0, false } return *q.Y, true } // HasY returns a boolean if a field has been set. func (q *QueryValueWidget) HasY() bool { if q != nil && q.Y != nil { return true } return false } // SetY allocates a new q.Y and returns the pointer to it. func (q *QueryValueWidget) SetY(v int) { q.Y = &v } // GetPeriod returns the Period field if non-nil, zero value otherwise. func (r *Recurrence) GetPeriod() int { if r == nil || r.Period == nil { return 0 } return *r.Period } // GetOkPeriod returns a tuple with the Period field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *Recurrence) GetPeriodOk() (int, bool) { if r == nil || r.Period == nil { return 0, false } return *r.Period, true } // HasPeriod returns a boolean if a field has been set. func (r *Recurrence) HasPeriod() bool { if r != nil && r.Period != nil { return true } return false } // SetPeriod allocates a new r.Period and returns the pointer to it. func (r *Recurrence) SetPeriod(v int) { r.Period = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (r *Recurrence) GetType() string { if r == nil || r.Type == nil { return "" } return *r.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *Recurrence) GetTypeOk() (string, bool) { if r == nil || r.Type == nil { return "", false } return *r.Type, true } // HasType returns a boolean if a field has been set. func (r *Recurrence) HasType() bool { if r != nil && r.Type != nil { return true } return false } // SetType allocates a new r.Type and returns the pointer to it. func (r *Recurrence) SetType(v string) { r.Type = &v } // GetUntilDate returns the UntilDate field if non-nil, zero value otherwise. func (r *Recurrence) GetUntilDate() int { if r == nil || r.UntilDate == nil { return 0 } return *r.UntilDate } // GetOkUntilDate returns a tuple with the UntilDate field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *Recurrence) GetUntilDateOk() (int, bool) { if r == nil || r.UntilDate == nil { return 0, false } return *r.UntilDate, true } // HasUntilDate returns a boolean if a field has been set. func (r *Recurrence) HasUntilDate() bool { if r != nil && r.UntilDate != nil { return true } return false } // SetUntilDate allocates a new r.UntilDate and returns the pointer to it. func (r *Recurrence) SetUntilDate(v int) { r.UntilDate = &v } // GetUntilOccurrences returns the UntilOccurrences field if non-nil, zero value otherwise. func (r *Recurrence) GetUntilOccurrences() int { if r == nil || r.UntilOccurrences == nil { return 0 } return *r.UntilOccurrences } // GetOkUntilOccurrences returns a tuple with the UntilOccurrences field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *Recurrence) GetUntilOccurrencesOk() (int, bool) { if r == nil || r.UntilOccurrences == nil { return 0, false } return *r.UntilOccurrences, true } // HasUntilOccurrences returns a boolean if a field has been set. func (r *Recurrence) HasUntilOccurrences() bool { if r != nil && r.UntilOccurrences != nil { return true } return false } // SetUntilOccurrences allocates a new r.UntilOccurrences and returns the pointer to it. func (r *Recurrence) SetUntilOccurrences(v int) { r.UntilOccurrences = &v } // GetComment returns the Comment field if non-nil, zero value otherwise. func (r *reqComment) GetComment() Comment { if r == nil || r.Comment == nil { return Comment{} } return *r.Comment } // GetOkComment returns a tuple with the Comment field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *reqComment) GetCommentOk() (Comment, bool) { if r == nil || r.Comment == nil { return Comment{}, false } return *r.Comment, true } // HasComment returns a boolean if a field has been set. func (r *reqComment) HasComment() bool { if r != nil && r.Comment != nil { return true } return false } // SetComment allocates a new r.Comment and returns the pointer to it. func (r *reqComment) SetComment(v Comment) { r.Comment = &v } // GetDashboard returns the Dashboard field if non-nil, zero value otherwise. func (r *reqGetDashboard) GetDashboard() Dashboard { if r == nil || r.Dashboard == nil { return Dashboard{} } return *r.Dashboard } // GetOkDashboard returns a tuple with the Dashboard field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *reqGetDashboard) GetDashboardOk() (Dashboard, bool) { if r == nil || r.Dashboard == nil { return Dashboard{}, false } return *r.Dashboard, true } // HasDashboard returns a boolean if a field has been set. func (r *reqGetDashboard) HasDashboard() bool { if r != nil && r.Dashboard != nil { return true } return false } // SetDashboard allocates a new r.Dashboard and returns the pointer to it. func (r *reqGetDashboard) SetDashboard(v Dashboard) { r.Dashboard = &v } // GetResource returns the Resource field if non-nil, zero value otherwise. func (r *reqGetDashboard) GetResource() string { if r == nil || r.Resource == nil { return "" } return *r.Resource } // GetOkResource returns a tuple with the Resource field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *reqGetDashboard) GetResourceOk() (string, bool) { if r == nil || r.Resource == nil { return "", false } return *r.Resource, true } // HasResource returns a boolean if a field has been set. func (r *reqGetDashboard) HasResource() bool { if r != nil && r.Resource != nil { return true } return false } // SetResource allocates a new r.Resource and returns the pointer to it. func (r *reqGetDashboard) SetResource(v string) { r.Resource = &v } // GetUrl returns the Url field if non-nil, zero value otherwise. func (r *reqGetDashboard) GetUrl() string { if r == nil || r.Url == nil { return "" } return *r.Url } // GetOkUrl returns a tuple with the Url field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *reqGetDashboard) GetUrlOk() (string, bool) { if r == nil || r.Url == nil { return "", false } return *r.Url, true } // HasUrl returns a boolean if a field has been set. func (r *reqGetDashboard) HasUrl() bool { if r != nil && r.Url != nil { return true } return false } // SetUrl allocates a new r.Url and returns the pointer to it. func (r *reqGetDashboard) SetUrl(v string) { r.Url = &v } // GetEvent returns the Event field if non-nil, zero value otherwise. func (r *reqGetEvent) GetEvent() Event { if r == nil || r.Event == nil { return Event{} } return *r.Event } // GetOkEvent returns a tuple with the Event field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *reqGetEvent) GetEventOk() (Event, bool) { if r == nil || r.Event == nil { return Event{}, false } return *r.Event, true } // HasEvent returns a boolean if a field has been set. func (r *reqGetEvent) HasEvent() bool { if r != nil && r.Event != nil { return true } return false } // SetEvent allocates a new r.Event and returns the pointer to it. func (r *reqGetEvent) SetEvent(v Event) { r.Event = &v } // GetTags returns the Tags field if non-nil, zero value otherwise. func (r *reqGetTags) GetTags() TagMap { if r == nil || r.Tags == nil { return TagMap{} } return *r.Tags } // GetOkTags returns a tuple with the Tags field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (r *reqGetTags) GetTagsOk() (TagMap, bool) { if r == nil || r.Tags == nil { return TagMap{}, false } return *r.Tags, true } // HasTags returns a boolean if a field has been set. func (r *reqGetTags) HasTags() bool { if r != nil && r.Tags != nil { return true } return false } // SetTags allocates a new r.Tags and returns the pointer to it. func (r *reqGetTags) SetTags(v TagMap) { r.Tags = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (s *Screenboard) GetHeight() string { if s == nil || s.Height == nil { return "" } return *s.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetHeightOk() (string, bool) { if s == nil || s.Height == nil { return "", false } return *s.Height, true } // HasHeight returns a boolean if a field has been set. func (s *Screenboard) HasHeight() bool { if s != nil && s.Height != nil { return true } return false } // SetHeight allocates a new s.Height and returns the pointer to it. func (s *Screenboard) SetHeight(v string) { s.Height = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (s *Screenboard) GetId() int { if s == nil || s.Id == nil { return 0 } return *s.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetIdOk() (int, bool) { if s == nil || s.Id == nil { return 0, false } return *s.Id, true } // HasId returns a boolean if a field has been set. func (s *Screenboard) HasId() bool { if s != nil && s.Id != nil { return true } return false } // SetId allocates a new s.Id and returns the pointer to it. func (s *Screenboard) SetId(v int) { s.Id = &v } // GetReadOnly returns the ReadOnly field if non-nil, zero value otherwise. func (s *Screenboard) GetReadOnly() bool { if s == nil || s.ReadOnly == nil { return false } return *s.ReadOnly } // GetOkReadOnly returns a tuple with the ReadOnly field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetReadOnlyOk() (bool, bool) { if s == nil || s.ReadOnly == nil { return false, false } return *s.ReadOnly, true } // HasReadOnly returns a boolean if a field has been set. func (s *Screenboard) HasReadOnly() bool { if s != nil && s.ReadOnly != nil { return true } return false } // SetReadOnly allocates a new s.ReadOnly and returns the pointer to it. func (s *Screenboard) SetReadOnly(v bool) { s.ReadOnly = &v } // GetShared returns the Shared field if non-nil, zero value otherwise. func (s *Screenboard) GetShared() bool { if s == nil || s.Shared == nil { return false } return *s.Shared } // GetOkShared returns a tuple with the Shared field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetSharedOk() (bool, bool) { if s == nil || s.Shared == nil { return false, false } return *s.Shared, true } // HasShared returns a boolean if a field has been set. func (s *Screenboard) HasShared() bool { if s != nil && s.Shared != nil { return true } return false } // SetShared allocates a new s.Shared and returns the pointer to it. func (s *Screenboard) SetShared(v bool) { s.Shared = &v } // GetTemplated returns the Templated field if non-nil, zero value otherwise. func (s *Screenboard) GetTemplated() bool { if s == nil || s.Templated == nil { return false } return *s.Templated } // GetOkTemplated returns a tuple with the Templated field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetTemplatedOk() (bool, bool) { if s == nil || s.Templated == nil { return false, false } return *s.Templated, true } // HasTemplated returns a boolean if a field has been set. func (s *Screenboard) HasTemplated() bool { if s != nil && s.Templated != nil { return true } return false } // SetTemplated allocates a new s.Templated and returns the pointer to it. func (s *Screenboard) SetTemplated(v bool) { s.Templated = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (s *Screenboard) GetTitle() string { if s == nil || s.Title == nil { return "" } return *s.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetTitleOk() (string, bool) { if s == nil || s.Title == nil { return "", false } return *s.Title, true } // HasTitle returns a boolean if a field has been set. func (s *Screenboard) HasTitle() bool { if s != nil && s.Title != nil { return true } return false } // SetTitle allocates a new s.Title and returns the pointer to it. func (s *Screenboard) SetTitle(v string) { s.Title = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (s *Screenboard) GetWidth() string { if s == nil || s.Width == nil { return "" } return *s.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Screenboard) GetWidthOk() (string, bool) { if s == nil || s.Width == nil { return "", false } return *s.Width, true } // HasWidth returns a boolean if a field has been set. func (s *Screenboard) HasWidth() bool { if s != nil && s.Width != nil { return true } return false } // SetWidth allocates a new s.Width and returns the pointer to it. func (s *Screenboard) SetWidth(v string) { s.Width = &v } // GetId returns the Id field if non-nil, zero value otherwise. func (s *ScreenboardLite) GetId() int { if s == nil || s.Id == nil { return 0 } return *s.Id } // GetOkId returns a tuple with the Id field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *ScreenboardLite) GetIdOk() (int, bool) { if s == nil || s.Id == nil { return 0, false } return *s.Id, true } // HasId returns a boolean if a field has been set. func (s *ScreenboardLite) HasId() bool { if s != nil && s.Id != nil { return true } return false } // SetId allocates a new s.Id and returns the pointer to it. func (s *ScreenboardLite) SetId(v int) { s.Id = &v } // GetResource returns the Resource field if non-nil, zero value otherwise. func (s *ScreenboardLite) GetResource() string { if s == nil || s.Resource == nil { return "" } return *s.Resource } // GetOkResource returns a tuple with the Resource field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *ScreenboardLite) GetResourceOk() (string, bool) { if s == nil || s.Resource == nil { return "", false } return *s.Resource, true } // HasResource returns a boolean if a field has been set. func (s *ScreenboardLite) HasResource() bool { if s != nil && s.Resource != nil { return true } return false } // SetResource allocates a new s.Resource and returns the pointer to it. func (s *ScreenboardLite) SetResource(v string) { s.Resource = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (s *ScreenboardLite) GetTitle() string { if s == nil || s.Title == nil { return "" } return *s.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *ScreenboardLite) GetTitleOk() (string, bool) { if s == nil || s.Title == nil { return "", false } return *s.Title, true } // HasTitle returns a boolean if a field has been set. func (s *ScreenboardLite) HasTitle() bool { if s != nil && s.Title != nil { return true } return false } // SetTitle allocates a new s.Title and returns the pointer to it. func (s *ScreenboardLite) SetTitle(v string) { s.Title = &v } // GetAggr returns the Aggr field if non-nil, zero value otherwise. func (s *Series) GetAggr() string { if s == nil || s.Aggr == nil { return "" } return *s.Aggr } // GetOkAggr returns a tuple with the Aggr field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetAggrOk() (string, bool) { if s == nil || s.Aggr == nil { return "", false } return *s.Aggr, true } // HasAggr returns a boolean if a field has been set. func (s *Series) HasAggr() bool { if s != nil && s.Aggr != nil { return true } return false } // SetAggr allocates a new s.Aggr and returns the pointer to it. func (s *Series) SetAggr(v string) { s.Aggr = &v } // GetDisplayName returns the DisplayName field if non-nil, zero value otherwise. func (s *Series) GetDisplayName() string { if s == nil || s.DisplayName == nil { return "" } return *s.DisplayName } // GetOkDisplayName returns a tuple with the DisplayName field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetDisplayNameOk() (string, bool) { if s == nil || s.DisplayName == nil { return "", false } return *s.DisplayName, true } // HasDisplayName returns a boolean if a field has been set. func (s *Series) HasDisplayName() bool { if s != nil && s.DisplayName != nil { return true } return false } // SetDisplayName allocates a new s.DisplayName and returns the pointer to it. func (s *Series) SetDisplayName(v string) { s.DisplayName = &v } // GetEnd returns the End field if non-nil, zero value otherwise. func (s *Series) GetEnd() float64 { if s == nil || s.End == nil { return 0 } return *s.End } // GetOkEnd returns a tuple with the End field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetEndOk() (float64, bool) { if s == nil || s.End == nil { return 0, false } return *s.End, true } // HasEnd returns a boolean if a field has been set. func (s *Series) HasEnd() bool { if s != nil && s.End != nil { return true } return false } // SetEnd allocates a new s.End and returns the pointer to it. func (s *Series) SetEnd(v float64) { s.End = &v } // GetExpression returns the Expression field if non-nil, zero value otherwise. func (s *Series) GetExpression() string { if s == nil || s.Expression == nil { return "" } return *s.Expression } // GetOkExpression returns a tuple with the Expression field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetExpressionOk() (string, bool) { if s == nil || s.Expression == nil { return "", false } return *s.Expression, true } // HasExpression returns a boolean if a field has been set. func (s *Series) HasExpression() bool { if s != nil && s.Expression != nil { return true } return false } // SetExpression allocates a new s.Expression and returns the pointer to it. func (s *Series) SetExpression(v string) { s.Expression = &v } // GetInterval returns the Interval field if non-nil, zero value otherwise. func (s *Series) GetInterval() int { if s == nil || s.Interval == nil { return 0 } return *s.Interval } // GetOkInterval returns a tuple with the Interval field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetIntervalOk() (int, bool) { if s == nil || s.Interval == nil { return 0, false } return *s.Interval, true } // HasInterval returns a boolean if a field has been set. func (s *Series) HasInterval() bool { if s != nil && s.Interval != nil { return true } return false } // SetInterval allocates a new s.Interval and returns the pointer to it. func (s *Series) SetInterval(v int) { s.Interval = &v } // GetLength returns the Length field if non-nil, zero value otherwise. func (s *Series) GetLength() int { if s == nil || s.Length == nil { return 0 } return *s.Length } // GetOkLength returns a tuple with the Length field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetLengthOk() (int, bool) { if s == nil || s.Length == nil { return 0, false } return *s.Length, true } // HasLength returns a boolean if a field has been set. func (s *Series) HasLength() bool { if s != nil && s.Length != nil { return true } return false } // SetLength allocates a new s.Length and returns the pointer to it. func (s *Series) SetLength(v int) { s.Length = &v } // GetMetric returns the Metric field if non-nil, zero value otherwise. func (s *Series) GetMetric() string { if s == nil || s.Metric == nil { return "" } return *s.Metric } // GetOkMetric returns a tuple with the Metric field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetMetricOk() (string, bool) { if s == nil || s.Metric == nil { return "", false } return *s.Metric, true } // HasMetric returns a boolean if a field has been set. func (s *Series) HasMetric() bool { if s != nil && s.Metric != nil { return true } return false } // SetMetric allocates a new s.Metric and returns the pointer to it. func (s *Series) SetMetric(v string) { s.Metric = &v } // GetScope returns the Scope field if non-nil, zero value otherwise. func (s *Series) GetScope() string { if s == nil || s.Scope == nil { return "" } return *s.Scope } // GetOkScope returns a tuple with the Scope field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetScopeOk() (string, bool) { if s == nil || s.Scope == nil { return "", false } return *s.Scope, true } // HasScope returns a boolean if a field has been set. func (s *Series) HasScope() bool { if s != nil && s.Scope != nil { return true } return false } // SetScope allocates a new s.Scope and returns the pointer to it. func (s *Series) SetScope(v string) { s.Scope = &v } // GetStart returns the Start field if non-nil, zero value otherwise. func (s *Series) GetStart() float64 { if s == nil || s.Start == nil { return 0 } return *s.Start } // GetOkStart returns a tuple with the Start field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Series) GetStartOk() (float64, bool) { if s == nil || s.Start == nil { return 0, false } return *s.Start, true } // HasStart returns a boolean if a field has been set. func (s *Series) HasStart() bool { if s != nil && s.Start != nil { return true } return false } // SetStart allocates a new s.Start and returns the pointer to it. func (s *Series) SetStart(v float64) { s.Start = &v } // GetPalette returns the Palette field if non-nil, zero value otherwise. func (s *Style) GetPalette() string { if s == nil || s.Palette == nil { return "" } return *s.Palette } // GetOkPalette returns a tuple with the Palette field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Style) GetPaletteOk() (string, bool) { if s == nil || s.Palette == nil { return "", false } return *s.Palette, true } // HasPalette returns a boolean if a field has been set. func (s *Style) HasPalette() bool { if s != nil && s.Palette != nil { return true } return false } // SetPalette allocates a new s.Palette and returns the pointer to it. func (s *Style) SetPalette(v string) { s.Palette = &v } // GetPaletteFlip returns the PaletteFlip field if non-nil, zero value otherwise. func (s *Style) GetPaletteFlip() bool { if s == nil || s.PaletteFlip == nil { return false } return *s.PaletteFlip } // GetOkPaletteFlip returns a tuple with the PaletteFlip field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (s *Style) GetPaletteFlipOk() (bool, bool) { if s == nil || s.PaletteFlip == nil { return false, false } return *s.PaletteFlip, true } // HasPaletteFlip returns a boolean if a field has been set. func (s *Style) HasPaletteFlip() bool { if s != nil && s.PaletteFlip != nil { return true } return false } // SetPaletteFlip allocates a new s.PaletteFlip and returns the pointer to it. func (s *Style) SetPaletteFlip(v bool) { s.PaletteFlip = &v } // GetDefault returns the Default field if non-nil, zero value otherwise. func (t *TemplateVariable) GetDefault() string { if t == nil || t.Default == nil { return "" } return *t.Default } // GetOkDefault returns a tuple with the Default field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TemplateVariable) GetDefaultOk() (string, bool) { if t == nil || t.Default == nil { return "", false } return *t.Default, true } // HasDefault returns a boolean if a field has been set. func (t *TemplateVariable) HasDefault() bool { if t != nil && t.Default != nil { return true } return false } // SetDefault allocates a new t.Default and returns the pointer to it. func (t *TemplateVariable) SetDefault(v string) { t.Default = &v } // GetName returns the Name field if non-nil, zero value otherwise. func (t *TemplateVariable) GetName() string { if t == nil || t.Name == nil { return "" } return *t.Name } // GetOkName returns a tuple with the Name field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TemplateVariable) GetNameOk() (string, bool) { if t == nil || t.Name == nil { return "", false } return *t.Name, true } // HasName returns a boolean if a field has been set. func (t *TemplateVariable) HasName() bool { if t != nil && t.Name != nil { return true } return false } // SetName allocates a new t.Name and returns the pointer to it. func (t *TemplateVariable) SetName(v string) { t.Name = &v } // GetPrefix returns the Prefix field if non-nil, zero value otherwise. func (t *TemplateVariable) GetPrefix() string { if t == nil || t.Prefix == nil { return "" } return *t.Prefix } // GetOkPrefix returns a tuple with the Prefix field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TemplateVariable) GetPrefixOk() (string, bool) { if t == nil || t.Prefix == nil { return "", false } return *t.Prefix, true } // HasPrefix returns a boolean if a field has been set. func (t *TemplateVariable) HasPrefix() bool { if t != nil && t.Prefix != nil { return true } return false } // SetPrefix allocates a new t.Prefix and returns the pointer to it. func (t *TemplateVariable) SetPrefix(v string) { t.Prefix = &v } // GetAuto returns the Auto field if non-nil, zero value otherwise. func (t *TextSize) GetAuto() bool { if t == nil || t.Auto == nil { return false } return *t.Auto } // GetOkAuto returns a tuple with the Auto field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TextSize) GetAutoOk() (bool, bool) { if t == nil || t.Auto == nil { return false, false } return *t.Auto, true } // HasAuto returns a boolean if a field has been set. func (t *TextSize) HasAuto() bool { if t != nil && t.Auto != nil { return true } return false } // SetAuto allocates a new t.Auto and returns the pointer to it. func (t *TextSize) SetAuto(v bool) { t.Auto = &v } // GetSize returns the Size field if non-nil, zero value otherwise. func (t *TextSize) GetSize() int { if t == nil || t.Size == nil { return 0 } return *t.Size } // GetOkSize returns a tuple with the Size field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TextSize) GetSizeOk() (int, bool) { if t == nil || t.Size == nil { return 0, false } return *t.Size, true } // HasSize returns a boolean if a field has been set. func (t *TextSize) HasSize() bool { if t != nil && t.Size != nil { return true } return false } // SetSize allocates a new t.Size and returns the pointer to it. func (t *TextSize) SetSize(v int) { t.Size = &v } // GetCritical returns the Critical field if non-nil, zero value otherwise. func (t *ThresholdCount) GetCritical() json.Number { if t == nil || t.Critical == nil { return "" } return *t.Critical } // GetOkCritical returns a tuple with the Critical field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ThresholdCount) GetCriticalOk() (json.Number, bool) { if t == nil || t.Critical == nil { return "", false } return *t.Critical, true } // HasCritical returns a boolean if a field has been set. func (t *ThresholdCount) HasCritical() bool { if t != nil && t.Critical != nil { return true } return false } // SetCritical allocates a new t.Critical and returns the pointer to it. func (t *ThresholdCount) SetCritical(v json.Number) { t.Critical = &v } // GetCriticalRecovery returns the CriticalRecovery field if non-nil, zero value otherwise. func (t *ThresholdCount) GetCriticalRecovery() json.Number { if t == nil || t.CriticalRecovery == nil { return "" } return *t.CriticalRecovery } // GetOkCriticalRecovery returns a tuple with the CriticalRecovery field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ThresholdCount) GetCriticalRecoveryOk() (json.Number, bool) { if t == nil || t.CriticalRecovery == nil { return "", false } return *t.CriticalRecovery, true } // HasCriticalRecovery returns a boolean if a field has been set. func (t *ThresholdCount) HasCriticalRecovery() bool { if t != nil && t.CriticalRecovery != nil { return true } return false } // SetCriticalRecovery allocates a new t.CriticalRecovery and returns the pointer to it. func (t *ThresholdCount) SetCriticalRecovery(v json.Number) { t.CriticalRecovery = &v } // GetOk returns the Ok field if non-nil, zero value otherwise. func (t *ThresholdCount) GetOk() json.Number { if t == nil || t.Ok == nil { return "" } return *t.Ok } // GetOkOk returns a tuple with the Ok field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ThresholdCount) GetOkOk() (json.Number, bool) { if t == nil || t.Ok == nil { return "", false } return *t.Ok, true } // HasOk returns a boolean if a field has been set. func (t *ThresholdCount) HasOk() bool { if t != nil && t.Ok != nil { return true } return false } // SetOk allocates a new t.Ok and returns the pointer to it. func (t *ThresholdCount) SetOk(v json.Number) { t.Ok = &v } // GetWarning returns the Warning field if non-nil, zero value otherwise. func (t *ThresholdCount) GetWarning() json.Number { if t == nil || t.Warning == nil { return "" } return *t.Warning } // GetOkWarning returns a tuple with the Warning field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ThresholdCount) GetWarningOk() (json.Number, bool) { if t == nil || t.Warning == nil { return "", false } return *t.Warning, true } // HasWarning returns a boolean if a field has been set. func (t *ThresholdCount) HasWarning() bool { if t != nil && t.Warning != nil { return true } return false } // SetWarning allocates a new t.Warning and returns the pointer to it. func (t *ThresholdCount) SetWarning(v json.Number) { t.Warning = &v } // GetWarningRecovery returns the WarningRecovery field if non-nil, zero value otherwise. func (t *ThresholdCount) GetWarningRecovery() json.Number { if t == nil || t.WarningRecovery == nil { return "" } return *t.WarningRecovery } // GetOkWarningRecovery returns a tuple with the WarningRecovery field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ThresholdCount) GetWarningRecoveryOk() (json.Number, bool) { if t == nil || t.WarningRecovery == nil { return "", false } return *t.WarningRecovery, true } // HasWarningRecovery returns a boolean if a field has been set. func (t *ThresholdCount) HasWarningRecovery() bool { if t != nil && t.WarningRecovery != nil { return true } return false } // SetWarningRecovery allocates a new t.WarningRecovery and returns the pointer to it. func (t *ThresholdCount) SetWarningRecovery(v json.Number) { t.WarningRecovery = &v } // GetViz returns the Viz field if non-nil, zero value otherwise. func (t *TileDef) GetViz() string { if t == nil || t.Viz == nil { return "" } return *t.Viz } // GetOkViz returns a tuple with the Viz field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDef) GetVizOk() (string, bool) { if t == nil || t.Viz == nil { return "", false } return *t.Viz, true } // HasViz returns a boolean if a field has been set. func (t *TileDef) HasViz() bool { if t != nil && t.Viz != nil { return true } return false } // SetViz allocates a new t.Viz and returns the pointer to it. func (t *TileDef) SetViz(v string) { t.Viz = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (t *TileDefEvent) GetQuery() string { if t == nil || t.Query == nil { return "" } return *t.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TileDefEvent) GetQueryOk() (string, bool) { if t == nil || t.Query == nil { return "", false } return *t.Query, true } // HasQuery returns a boolean if a field has been set. func (t *TileDefEvent) HasQuery() bool { if t != nil && t.Query != nil { return true } return false } // SetQuery allocates a new t.Query and returns the pointer to it. func (t *TileDefEvent) SetQuery(v string) { t.Query = &v } // GetLabel returns the Label field if non-nil, zero value otherwise. func (t *TimeseriesMarker) GetLabel() string { if t == nil || t.Label == nil { return "" } return *t.Label } // GetOkLabel returns a tuple with the Label field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesMarker) GetLabelOk() (string, bool) { if t == nil || t.Label == nil { return "", false } return *t.Label, true } // HasLabel returns a boolean if a field has been set. func (t *TimeseriesMarker) HasLabel() bool { if t != nil && t.Label != nil { return true } return false } // SetLabel allocates a new t.Label and returns the pointer to it. func (t *TimeseriesMarker) SetLabel(v string) { t.Label = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (t *TimeseriesMarker) GetType() string { if t == nil || t.Type == nil { return "" } return *t.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesMarker) GetTypeOk() (string, bool) { if t == nil || t.Type == nil { return "", false } return *t.Type, true } // HasType returns a boolean if a field has been set. func (t *TimeseriesMarker) HasType() bool { if t != nil && t.Type != nil { return true } return false } // SetType allocates a new t.Type and returns the pointer to it. func (t *TimeseriesMarker) SetType(v string) { t.Type = &v } // GetValue returns the Value field if non-nil, zero value otherwise. func (t *TimeseriesMarker) GetValue() string { if t == nil || t.Value == nil { return "" } return *t.Value } // GetOkValue returns a tuple with the Value field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesMarker) GetValueOk() (string, bool) { if t == nil || t.Value == nil { return "", false } return *t.Value, true } // HasValue returns a boolean if a field has been set. func (t *TimeseriesMarker) HasValue() bool { if t != nil && t.Value != nil { return true } return false } // SetValue allocates a new t.Value and returns the pointer to it. func (t *TimeseriesMarker) SetValue(v string) { t.Value = &v } // GetQuery returns the Query field if non-nil, zero value otherwise. func (t *TimeseriesRequest) GetQuery() string { if t == nil || t.Query == nil { return "" } return *t.Query } // GetOkQuery returns a tuple with the Query field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesRequest) GetQueryOk() (string, bool) { if t == nil || t.Query == nil { return "", false } return *t.Query, true } // HasQuery returns a boolean if a field has been set. func (t *TimeseriesRequest) HasQuery() bool { if t != nil && t.Query != nil { return true } return false } // SetQuery allocates a new t.Query and returns the pointer to it. func (t *TimeseriesRequest) SetQuery(v string) { t.Query = &v } // GetStyle returns the Style field if non-nil, zero value otherwise. func (t *TimeseriesRequest) GetStyle() TimeseriesRequestStyle { if t == nil || t.Style == nil { return TimeseriesRequestStyle{} } return *t.Style } // GetOkStyle returns a tuple with the Style field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesRequest) GetStyleOk() (TimeseriesRequestStyle, bool) { if t == nil || t.Style == nil { return TimeseriesRequestStyle{}, false } return *t.Style, true } // HasStyle returns a boolean if a field has been set. func (t *TimeseriesRequest) HasStyle() bool { if t != nil && t.Style != nil { return true } return false } // SetStyle allocates a new t.Style and returns the pointer to it. func (t *TimeseriesRequest) SetStyle(v TimeseriesRequestStyle) { t.Style = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (t *TimeseriesRequest) GetType() string { if t == nil || t.Type == nil { return "" } return *t.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesRequest) GetTypeOk() (string, bool) { if t == nil || t.Type == nil { return "", false } return *t.Type, true } // HasType returns a boolean if a field has been set. func (t *TimeseriesRequest) HasType() bool { if t != nil && t.Type != nil { return true } return false } // SetType allocates a new t.Type and returns the pointer to it. func (t *TimeseriesRequest) SetType(v string) { t.Type = &v } // GetPalette returns the Palette field if non-nil, zero value otherwise. func (t *TimeseriesRequestStyle) GetPalette() string { if t == nil || t.Palette == nil { return "" } return *t.Palette } // GetOkPalette returns a tuple with the Palette field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesRequestStyle) GetPaletteOk() (string, bool) { if t == nil || t.Palette == nil { return "", false } return *t.Palette, true } // HasPalette returns a boolean if a field has been set. func (t *TimeseriesRequestStyle) HasPalette() bool { if t != nil && t.Palette != nil { return true } return false } // SetPalette allocates a new t.Palette and returns the pointer to it. func (t *TimeseriesRequestStyle) SetPalette(v string) { t.Palette = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (t *TimeseriesWidget) GetHeight() int { if t == nil || t.Height == nil { return 0 } return *t.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesWidget) GetHeightOk() (int, bool) { if t == nil || t.Height == nil { return 0, false } return *t.Height, true } // HasHeight returns a boolean if a field has been set. func (t *TimeseriesWidget) HasHeight() bool { if t != nil && t.Height != nil { return true } return false } // SetHeight allocates a new t.Height and returns the pointer to it. func (t *TimeseriesWidget) SetHeight(v int) { t.Height = &v } // GetLegend returns the Legend field if non-nil, zero value otherwise. func (t *TimeseriesWidget) GetLegend() bool { if t == nil || t.Legend == nil { return false } return *t.Legend } // GetOkLegend returns a tuple with the Legend field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesWidget) GetLegendOk() (bool, bool) { if t == nil || t.Legend == nil { return false, false } return *t.Legend, true } // HasLegend returns a boolean if a field has been set. func (t *TimeseriesWidget) HasLegend() bool { if t != nil && t.Legend != nil { return true } return false } // SetLegend allocates a new t.Legend and returns the pointer to it. func (t *TimeseriesWidget) SetLegend(v bool) { t.Legend = &v } // GetTileDef returns the TileDef field if non-nil, zero value otherwise. func (t *TimeseriesWidget) GetTileDef() TileDef { if t == nil || t.TileDef == nil { return TileDef{} } return *t.TileDef } // GetOkTileDef returns a tuple with the TileDef field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesWidget) GetTileDefOk() (TileDef, bool) { if t == nil || t.TileDef == nil { return TileDef{}, false } return *t.TileDef, true } // HasTileDef returns a boolean if a field has been set. func (t *TimeseriesWidget) HasTileDef() bool { if t != nil && t.TileDef != nil { return true } return false } // SetTileDef allocates a new t.TileDef and returns the pointer to it. func (t *TimeseriesWidget) SetTileDef(v TileDef) { t.TileDef = &v } // GetTimeframe returns the Timeframe field if non-nil, zero value otherwise. func (t *TimeseriesWidget) GetTimeframe() string { if t == nil || t.Timeframe == nil { return "" } return *t.Timeframe } // GetOkTimeframe returns a tuple with the Timeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesWidget) GetTimeframeOk() (string, bool) { if t == nil || t.Timeframe == nil { return "", false } return *t.Timeframe, true } // HasTimeframe returns a boolean if a field has been set. func (t *TimeseriesWidget) HasTimeframe() bool { if t != nil && t.Timeframe != nil { return true } return false } // SetTimeframe allocates a new t.Timeframe and returns the pointer to it. func (t *TimeseriesWidget) SetTimeframe(v string) { t.Timeframe = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (t *TimeseriesWidget) GetTitle() bool { if t == nil || t.Title == nil { return false } return *t.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesWidget) GetTitleOk() (bool, bool) { if t == nil || t.Title == nil { return false, false } return *t.Title, true } // HasTitle returns a boolean if a field has been set. func (t *TimeseriesWidget) HasTitle() bool { if t != nil && t.Title != nil { return true } return false } // SetTitle allocates a new t.Title and returns the pointer to it. func (t *TimeseriesWidget) SetTitle(v bool) { t.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (t *TimeseriesWidget) GetTitleAlign() string { if t == nil || t.TitleAlign == nil { return "" } return *t.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesWidget) GetTitleAlignOk() (string, bool) { if t == nil || t.TitleAlign == nil { return "", false } return *t.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (t *TimeseriesWidget) HasTitleAlign() bool { if t != nil && t.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new t.TitleAlign and returns the pointer to it. func (t *TimeseriesWidget) SetTitleAlign(v string) { t.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (t *TimeseriesWidget) GetTitleSize() TextSize { if t == nil || t.TitleSize == nil { return TextSize{} } return *t.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesWidget) GetTitleSizeOk() (TextSize, bool) { if t == nil || t.TitleSize == nil { return TextSize{}, false } return *t.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (t *TimeseriesWidget) HasTitleSize() bool { if t != nil && t.TitleSize != nil { return true } return false } // SetTitleSize allocates a new t.TitleSize and returns the pointer to it. func (t *TimeseriesWidget) SetTitleSize(v TextSize) { t.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (t *TimeseriesWidget) GetTitleText() string { if t == nil || t.TitleText == nil { return "" } return *t.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesWidget) GetTitleTextOk() (string, bool) { if t == nil || t.TitleText == nil { return "", false } return *t.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (t *TimeseriesWidget) HasTitleText() bool { if t != nil && t.TitleText != nil { return true } return false } // SetTitleText allocates a new t.TitleText and returns the pointer to it. func (t *TimeseriesWidget) SetTitleText(v string) { t.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (t *TimeseriesWidget) GetType() string { if t == nil || t.Type == nil { return "" } return *t.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesWidget) GetTypeOk() (string, bool) { if t == nil || t.Type == nil { return "", false } return *t.Type, true } // HasType returns a boolean if a field has been set. func (t *TimeseriesWidget) HasType() bool { if t != nil && t.Type != nil { return true } return false } // SetType allocates a new t.Type and returns the pointer to it. func (t *TimeseriesWidget) SetType(v string) { t.Type = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (t *TimeseriesWidget) GetWidth() int { if t == nil || t.Width == nil { return 0 } return *t.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesWidget) GetWidthOk() (int, bool) { if t == nil || t.Width == nil { return 0, false } return *t.Width, true } // HasWidth returns a boolean if a field has been set. func (t *TimeseriesWidget) HasWidth() bool { if t != nil && t.Width != nil { return true } return false } // SetWidth allocates a new t.Width and returns the pointer to it. func (t *TimeseriesWidget) SetWidth(v int) { t.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (t *TimeseriesWidget) GetX() int { if t == nil || t.X == nil { return 0 } return *t.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesWidget) GetXOk() (int, bool) { if t == nil || t.X == nil { return 0, false } return *t.X, true } // HasX returns a boolean if a field has been set. func (t *TimeseriesWidget) HasX() bool { if t != nil && t.X != nil { return true } return false } // SetX allocates a new t.X and returns the pointer to it. func (t *TimeseriesWidget) SetX(v int) { t.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (t *TimeseriesWidget) GetY() int { if t == nil || t.Y == nil { return 0 } return *t.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *TimeseriesWidget) GetYOk() (int, bool) { if t == nil || t.Y == nil { return 0, false } return *t.Y, true } // HasY returns a boolean if a field has been set. func (t *TimeseriesWidget) HasY() bool { if t != nil && t.Y != nil { return true } return false } // SetY allocates a new t.Y and returns the pointer to it. func (t *TimeseriesWidget) SetY(v int) { t.Y = &v } // GetHeight returns the Height field if non-nil, zero value otherwise. func (t *ToplistWidget) GetHeight() int { if t == nil || t.Height == nil { return 0 } return *t.Height } // GetOkHeight returns a tuple with the Height field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetHeightOk() (int, bool) { if t == nil || t.Height == nil { return 0, false } return *t.Height, true } // HasHeight returns a boolean if a field has been set. func (t *ToplistWidget) HasHeight() bool { if t != nil && t.Height != nil { return true } return false } // SetHeight allocates a new t.Height and returns the pointer to it. func (t *ToplistWidget) SetHeight(v int) { t.Height = &v } // GetLegend returns the Legend field if non-nil, zero value otherwise. func (t *ToplistWidget) GetLegend() bool { if t == nil || t.Legend == nil { return false } return *t.Legend } // GetOkLegend returns a tuple with the Legend field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetLegendOk() (bool, bool) { if t == nil || t.Legend == nil { return false, false } return *t.Legend, true } // HasLegend returns a boolean if a field has been set. func (t *ToplistWidget) HasLegend() bool { if t != nil && t.Legend != nil { return true } return false } // SetLegend allocates a new t.Legend and returns the pointer to it. func (t *ToplistWidget) SetLegend(v bool) { t.Legend = &v } // GetLegendSize returns the LegendSize field if non-nil, zero value otherwise. func (t *ToplistWidget) GetLegendSize() int { if t == nil || t.LegendSize == nil { return 0 } return *t.LegendSize } // GetOkLegendSize returns a tuple with the LegendSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetLegendSizeOk() (int, bool) { if t == nil || t.LegendSize == nil { return 0, false } return *t.LegendSize, true } // HasLegendSize returns a boolean if a field has been set. func (t *ToplistWidget) HasLegendSize() bool { if t != nil && t.LegendSize != nil { return true } return false } // SetLegendSize allocates a new t.LegendSize and returns the pointer to it. func (t *ToplistWidget) SetLegendSize(v int) { t.LegendSize = &v } // GetTileDef returns the TileDef field if non-nil, zero value otherwise. func (t *ToplistWidget) GetTileDef() TileDef { if t == nil || t.TileDef == nil { return TileDef{} } return *t.TileDef } // GetOkTileDef returns a tuple with the TileDef field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetTileDefOk() (TileDef, bool) { if t == nil || t.TileDef == nil { return TileDef{}, false } return *t.TileDef, true } // HasTileDef returns a boolean if a field has been set. func (t *ToplistWidget) HasTileDef() bool { if t != nil && t.TileDef != nil { return true } return false } // SetTileDef allocates a new t.TileDef and returns the pointer to it. func (t *ToplistWidget) SetTileDef(v TileDef) { t.TileDef = &v } // GetTimeframe returns the Timeframe field if non-nil, zero value otherwise. func (t *ToplistWidget) GetTimeframe() string { if t == nil || t.Timeframe == nil { return "" } return *t.Timeframe } // GetOkTimeframe returns a tuple with the Timeframe field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetTimeframeOk() (string, bool) { if t == nil || t.Timeframe == nil { return "", false } return *t.Timeframe, true } // HasTimeframe returns a boolean if a field has been set. func (t *ToplistWidget) HasTimeframe() bool { if t != nil && t.Timeframe != nil { return true } return false } // SetTimeframe allocates a new t.Timeframe and returns the pointer to it. func (t *ToplistWidget) SetTimeframe(v string) { t.Timeframe = &v } // GetTitle returns the Title field if non-nil, zero value otherwise. func (t *ToplistWidget) GetTitle() bool { if t == nil || t.Title == nil { return false } return *t.Title } // GetOkTitle returns a tuple with the Title field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetTitleOk() (bool, bool) { if t == nil || t.Title == nil { return false, false } return *t.Title, true } // HasTitle returns a boolean if a field has been set. func (t *ToplistWidget) HasTitle() bool { if t != nil && t.Title != nil { return true } return false } // SetTitle allocates a new t.Title and returns the pointer to it. func (t *ToplistWidget) SetTitle(v bool) { t.Title = &v } // GetTitleAlign returns the TitleAlign field if non-nil, zero value otherwise. func (t *ToplistWidget) GetTitleAlign() string { if t == nil || t.TitleAlign == nil { return "" } return *t.TitleAlign } // GetOkTitleAlign returns a tuple with the TitleAlign field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetTitleAlignOk() (string, bool) { if t == nil || t.TitleAlign == nil { return "", false } return *t.TitleAlign, true } // HasTitleAlign returns a boolean if a field has been set. func (t *ToplistWidget) HasTitleAlign() bool { if t != nil && t.TitleAlign != nil { return true } return false } // SetTitleAlign allocates a new t.TitleAlign and returns the pointer to it. func (t *ToplistWidget) SetTitleAlign(v string) { t.TitleAlign = &v } // GetTitleSize returns the TitleSize field if non-nil, zero value otherwise. func (t *ToplistWidget) GetTitleSize() TextSize { if t == nil || t.TitleSize == nil { return TextSize{} } return *t.TitleSize } // GetOkTitleSize returns a tuple with the TitleSize field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetTitleSizeOk() (TextSize, bool) { if t == nil || t.TitleSize == nil { return TextSize{}, false } return *t.TitleSize, true } // HasTitleSize returns a boolean if a field has been set. func (t *ToplistWidget) HasTitleSize() bool { if t != nil && t.TitleSize != nil { return true } return false } // SetTitleSize allocates a new t.TitleSize and returns the pointer to it. func (t *ToplistWidget) SetTitleSize(v TextSize) { t.TitleSize = &v } // GetTitleText returns the TitleText field if non-nil, zero value otherwise. func (t *ToplistWidget) GetTitleText() string { if t == nil || t.TitleText == nil { return "" } return *t.TitleText } // GetOkTitleText returns a tuple with the TitleText field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetTitleTextOk() (string, bool) { if t == nil || t.TitleText == nil { return "", false } return *t.TitleText, true } // HasTitleText returns a boolean if a field has been set. func (t *ToplistWidget) HasTitleText() bool { if t != nil && t.TitleText != nil { return true } return false } // SetTitleText allocates a new t.TitleText and returns the pointer to it. func (t *ToplistWidget) SetTitleText(v string) { t.TitleText = &v } // GetType returns the Type field if non-nil, zero value otherwise. func (t *ToplistWidget) GetType() string { if t == nil || t.Type == nil { return "" } return *t.Type } // GetOkType returns a tuple with the Type field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetTypeOk() (string, bool) { if t == nil || t.Type == nil { return "", false } return *t.Type, true } // HasType returns a boolean if a field has been set. func (t *ToplistWidget) HasType() bool { if t != nil && t.Type != nil { return true } return false } // SetType allocates a new t.Type and returns the pointer to it. func (t *ToplistWidget) SetType(v string) { t.Type = &v } // GetWidth returns the Width field if non-nil, zero value otherwise. func (t *ToplistWidget) GetWidth() int { if t == nil || t.Width == nil { return 0 } return *t.Width } // GetOkWidth returns a tuple with the Width field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetWidthOk() (int, bool) { if t == nil || t.Width == nil { return 0, false } return *t.Width, true } // HasWidth returns a boolean if a field has been set. func (t *ToplistWidget) HasWidth() bool { if t != nil && t.Width != nil { return true } return false } // SetWidth allocates a new t.Width and returns the pointer to it. func (t *ToplistWidget) SetWidth(v int) { t.Width = &v } // GetX returns the X field if non-nil, zero value otherwise. func (t *ToplistWidget) GetX() int { if t == nil || t.X == nil { return 0 } return *t.X } // GetOkX returns a tuple with the X field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetXOk() (int, bool) { if t == nil || t.X == nil { return 0, false } return *t.X, true } // HasX returns a boolean if a field has been set. func (t *ToplistWidget) HasX() bool { if t != nil && t.X != nil { return true } return false } // SetX allocates a new t.X and returns the pointer to it. func (t *ToplistWidget) SetX(v int) { t.X = &v } // GetY returns the Y field if non-nil, zero value otherwise. func (t *ToplistWidget) GetY() int { if t == nil || t.Y == nil { return 0 } return *t.Y } // GetOkY returns a tuple with the Y field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (t *ToplistWidget) GetYOk() (int, bool) { if t == nil || t.Y == nil { return 0, false } return *t.Y, true } // HasY returns a boolean if a field has been set. func (t *ToplistWidget) HasY() bool { if t != nil && t.Y != nil { return true } return false } // SetY allocates a new t.Y and returns the pointer to it. func (t *ToplistWidget) SetY(v int) { t.Y = &v } // GetDisabled returns the Disabled field if non-nil, zero value otherwise. func (u *User) GetDisabled() bool { if u == nil || u.Disabled == nil { return false } return *u.Disabled } // GetOkDisabled returns a tuple with the Disabled field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetDisabledOk() (bool, bool) { if u == nil || u.Disabled == nil { return false, false } return *u.Disabled, true } // HasDisabled returns a boolean if a field has been set. func (u *User) HasDisabled() bool { if u != nil && u.Disabled != nil { return true } return false } // SetDisabled allocates a new u.Disabled and returns the pointer to it. func (u *User) SetDisabled(v bool) { u.Disabled = &v } // GetEmail returns the Email field if non-nil, zero value otherwise. func (u *User) GetEmail() string { if u == nil || u.Email == nil { return "" } return *u.Email } // GetOkEmail returns a tuple with the Email field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetEmailOk() (string, bool) { if u == nil || u.Email == nil { return "", false } return *u.Email, true } // HasEmail returns a boolean if a field has been set. func (u *User) HasEmail() bool { if u != nil && u.Email != nil { return true } return false } // SetEmail allocates a new u.Email and returns the pointer to it. func (u *User) SetEmail(v string) { u.Email = &v } // GetHandle returns the Handle field if non-nil, zero value otherwise. func (u *User) GetHandle() string { if u == nil || u.Handle == nil { return "" } return *u.Handle } // GetOkHandle returns a tuple with the Handle field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetHandleOk() (string, bool) { if u == nil || u.Handle == nil { return "", false } return *u.Handle, true } // HasHandle returns a boolean if a field has been set. func (u *User) HasHandle() bool { if u != nil && u.Handle != nil { return true } return false } // SetHandle allocates a new u.Handle and returns the pointer to it. func (u *User) SetHandle(v string) { u.Handle = &v } // GetIsAdmin returns the IsAdmin field if non-nil, zero value otherwise. func (u *User) GetIsAdmin() bool { if u == nil || u.IsAdmin == nil { return false } return *u.IsAdmin } // GetOkIsAdmin returns a tuple with the IsAdmin field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetIsAdminOk() (bool, bool) { if u == nil || u.IsAdmin == nil { return false, false } return *u.IsAdmin, true } // HasIsAdmin returns a boolean if a field has been set. func (u *User) HasIsAdmin() bool { if u != nil && u.IsAdmin != nil { return true } return false } // SetIsAdmin allocates a new u.IsAdmin and returns the pointer to it. func (u *User) SetIsAdmin(v bool) { u.IsAdmin = &v } // GetName returns the Name field if non-nil, zero value otherwise. func (u *User) GetName() string { if u == nil || u.Name == nil { return "" } return *u.Name } // GetOkName returns a tuple with the Name field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetNameOk() (string, bool) { if u == nil || u.Name == nil { return "", false } return *u.Name, true } // HasName returns a boolean if a field has been set. func (u *User) HasName() bool { if u != nil && u.Name != nil { return true } return false } // SetName allocates a new u.Name and returns the pointer to it. func (u *User) SetName(v string) { u.Name = &v } // GetRole returns the Role field if non-nil, zero value otherwise. func (u *User) GetRole() string { if u == nil || u.Role == nil { return "" } return *u.Role } // GetOkRole returns a tuple with the Role field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetRoleOk() (string, bool) { if u == nil || u.Role == nil { return "", false } return *u.Role, true } // HasRole returns a boolean if a field has been set. func (u *User) HasRole() bool { if u != nil && u.Role != nil { return true } return false } // SetRole allocates a new u.Role and returns the pointer to it. func (u *User) SetRole(v string) { u.Role = &v } // GetVerified returns the Verified field if non-nil, zero value otherwise. func (u *User) GetVerified() bool { if u == nil || u.Verified == nil { return false } return *u.Verified } // GetOkVerified returns a tuple with the Verified field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (u *User) GetVerifiedOk() (bool, bool) { if u == nil || u.Verified == nil { return false, false } return *u.Verified, true } // HasVerified returns a boolean if a field has been set. func (u *User) HasVerified() bool { if u != nil && u.Verified != nil { return true } return false } // SetVerified allocates a new u.Verified and returns the pointer to it. func (u *User) SetVerified(v bool) { u.Verified = &v } // GetAlertGraphWidget returns the AlertGraphWidget field if non-nil, zero value otherwise. func (w *Widget) GetAlertGraphWidget() AlertGraphWidget { if w == nil || w.AlertGraphWidget == nil { return AlertGraphWidget{} } return *w.AlertGraphWidget } // GetOkAlertGraphWidget returns a tuple with the AlertGraphWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetAlertGraphWidgetOk() (AlertGraphWidget, bool) { if w == nil || w.AlertGraphWidget == nil { return AlertGraphWidget{}, false } return *w.AlertGraphWidget, true } // HasAlertGraphWidget returns a boolean if a field has been set. func (w *Widget) HasAlertGraphWidget() bool { if w != nil && w.AlertGraphWidget != nil { return true } return false } // SetAlertGraphWidget allocates a new w.AlertGraphWidget and returns the pointer to it. func (w *Widget) SetAlertGraphWidget(v AlertGraphWidget) { w.AlertGraphWidget = &v } // GetAlertValueWidget returns the AlertValueWidget field if non-nil, zero value otherwise. func (w *Widget) GetAlertValueWidget() AlertValueWidget { if w == nil || w.AlertValueWidget == nil { return AlertValueWidget{} } return *w.AlertValueWidget } // GetOkAlertValueWidget returns a tuple with the AlertValueWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetAlertValueWidgetOk() (AlertValueWidget, bool) { if w == nil || w.AlertValueWidget == nil { return AlertValueWidget{}, false } return *w.AlertValueWidget, true } // HasAlertValueWidget returns a boolean if a field has been set. func (w *Widget) HasAlertValueWidget() bool { if w != nil && w.AlertValueWidget != nil { return true } return false } // SetAlertValueWidget allocates a new w.AlertValueWidget and returns the pointer to it. func (w *Widget) SetAlertValueWidget(v AlertValueWidget) { w.AlertValueWidget = &v } // GetChangeWidget returns the ChangeWidget field if non-nil, zero value otherwise. func (w *Widget) GetChangeWidget() ChangeWidget { if w == nil || w.ChangeWidget == nil { return ChangeWidget{} } return *w.ChangeWidget } // GetOkChangeWidget returns a tuple with the ChangeWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetChangeWidgetOk() (ChangeWidget, bool) { if w == nil || w.ChangeWidget == nil { return ChangeWidget{}, false } return *w.ChangeWidget, true } // HasChangeWidget returns a boolean if a field has been set. func (w *Widget) HasChangeWidget() bool { if w != nil && w.ChangeWidget != nil { return true } return false } // SetChangeWidget allocates a new w.ChangeWidget and returns the pointer to it. func (w *Widget) SetChangeWidget(v ChangeWidget) { w.ChangeWidget = &v } // GetCheckStatusWidget returns the CheckStatusWidget field if non-nil, zero value otherwise. func (w *Widget) GetCheckStatusWidget() CheckStatusWidget { if w == nil || w.CheckStatusWidget == nil { return CheckStatusWidget{} } return *w.CheckStatusWidget } // GetOkCheckStatusWidget returns a tuple with the CheckStatusWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetCheckStatusWidgetOk() (CheckStatusWidget, bool) { if w == nil || w.CheckStatusWidget == nil { return CheckStatusWidget{}, false } return *w.CheckStatusWidget, true } // HasCheckStatusWidget returns a boolean if a field has been set. func (w *Widget) HasCheckStatusWidget() bool { if w != nil && w.CheckStatusWidget != nil { return true } return false } // SetCheckStatusWidget allocates a new w.CheckStatusWidget and returns the pointer to it. func (w *Widget) SetCheckStatusWidget(v CheckStatusWidget) { w.CheckStatusWidget = &v } // GetDefault returns the Default field if non-nil, zero value otherwise. func (w *Widget) GetDefault() string { if w == nil || w.Default == nil { return "" } return *w.Default } // GetOkDefault returns a tuple with the Default field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetDefaultOk() (string, bool) { if w == nil || w.Default == nil { return "", false } return *w.Default, true } // HasDefault returns a boolean if a field has been set. func (w *Widget) HasDefault() bool { if w != nil && w.Default != nil { return true } return false } // SetDefault allocates a new w.Default and returns the pointer to it. func (w *Widget) SetDefault(v string) { w.Default = &v } // GetEventStreamWidget returns the EventStreamWidget field if non-nil, zero value otherwise. func (w *Widget) GetEventStreamWidget() EventStreamWidget { if w == nil || w.EventStreamWidget == nil { return EventStreamWidget{} } return *w.EventStreamWidget } // GetOkEventStreamWidget returns a tuple with the EventStreamWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetEventStreamWidgetOk() (EventStreamWidget, bool) { if w == nil || w.EventStreamWidget == nil { return EventStreamWidget{}, false } return *w.EventStreamWidget, true } // HasEventStreamWidget returns a boolean if a field has been set. func (w *Widget) HasEventStreamWidget() bool { if w != nil && w.EventStreamWidget != nil { return true } return false } // SetEventStreamWidget allocates a new w.EventStreamWidget and returns the pointer to it. func (w *Widget) SetEventStreamWidget(v EventStreamWidget) { w.EventStreamWidget = &v } // GetEventTimelineWidget returns the EventTimelineWidget field if non-nil, zero value otherwise. func (w *Widget) GetEventTimelineWidget() EventTimelineWidget { if w == nil || w.EventTimelineWidget == nil { return EventTimelineWidget{} } return *w.EventTimelineWidget } // GetOkEventTimelineWidget returns a tuple with the EventTimelineWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetEventTimelineWidgetOk() (EventTimelineWidget, bool) { if w == nil || w.EventTimelineWidget == nil { return EventTimelineWidget{}, false } return *w.EventTimelineWidget, true } // HasEventTimelineWidget returns a boolean if a field has been set. func (w *Widget) HasEventTimelineWidget() bool { if w != nil && w.EventTimelineWidget != nil { return true } return false } // SetEventTimelineWidget allocates a new w.EventTimelineWidget and returns the pointer to it. func (w *Widget) SetEventTimelineWidget(v EventTimelineWidget) { w.EventTimelineWidget = &v } // GetFreeTextWidget returns the FreeTextWidget field if non-nil, zero value otherwise. func (w *Widget) GetFreeTextWidget() FreeTextWidget { if w == nil || w.FreeTextWidget == nil { return FreeTextWidget{} } return *w.FreeTextWidget } // GetOkFreeTextWidget returns a tuple with the FreeTextWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetFreeTextWidgetOk() (FreeTextWidget, bool) { if w == nil || w.FreeTextWidget == nil { return FreeTextWidget{}, false } return *w.FreeTextWidget, true } // HasFreeTextWidget returns a boolean if a field has been set. func (w *Widget) HasFreeTextWidget() bool { if w != nil && w.FreeTextWidget != nil { return true } return false } // SetFreeTextWidget allocates a new w.FreeTextWidget and returns the pointer to it. func (w *Widget) SetFreeTextWidget(v FreeTextWidget) { w.FreeTextWidget = &v } // GetGraphWidget returns the GraphWidget field if non-nil, zero value otherwise. func (w *Widget) GetGraphWidget() GraphWidget { if w == nil || w.GraphWidget == nil { return GraphWidget{} } return *w.GraphWidget } // GetOkGraphWidget returns a tuple with the GraphWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetGraphWidgetOk() (GraphWidget, bool) { if w == nil || w.GraphWidget == nil { return GraphWidget{}, false } return *w.GraphWidget, true } // HasGraphWidget returns a boolean if a field has been set. func (w *Widget) HasGraphWidget() bool { if w != nil && w.GraphWidget != nil { return true } return false } // SetGraphWidget allocates a new w.GraphWidget and returns the pointer to it. func (w *Widget) SetGraphWidget(v GraphWidget) { w.GraphWidget = &v } // GetHostMapWidget returns the HostMapWidget field if non-nil, zero value otherwise. func (w *Widget) GetHostMapWidget() HostMapWidget { if w == nil || w.HostMapWidget == nil { return HostMapWidget{} } return *w.HostMapWidget } // GetOkHostMapWidget returns a tuple with the HostMapWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetHostMapWidgetOk() (HostMapWidget, bool) { if w == nil || w.HostMapWidget == nil { return HostMapWidget{}, false } return *w.HostMapWidget, true } // HasHostMapWidget returns a boolean if a field has been set. func (w *Widget) HasHostMapWidget() bool { if w != nil && w.HostMapWidget != nil { return true } return false } // SetHostMapWidget allocates a new w.HostMapWidget and returns the pointer to it. func (w *Widget) SetHostMapWidget(v HostMapWidget) { w.HostMapWidget = &v } // GetIFrameWidget returns the IFrameWidget field if non-nil, zero value otherwise. func (w *Widget) GetIFrameWidget() IFrameWidget { if w == nil || w.IFrameWidget == nil { return IFrameWidget{} } return *w.IFrameWidget } // GetOkIFrameWidget returns a tuple with the IFrameWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetIFrameWidgetOk() (IFrameWidget, bool) { if w == nil || w.IFrameWidget == nil { return IFrameWidget{}, false } return *w.IFrameWidget, true } // HasIFrameWidget returns a boolean if a field has been set. func (w *Widget) HasIFrameWidget() bool { if w != nil && w.IFrameWidget != nil { return true } return false } // SetIFrameWidget allocates a new w.IFrameWidget and returns the pointer to it. func (w *Widget) SetIFrameWidget(v IFrameWidget) { w.IFrameWidget = &v } // GetImageWidget returns the ImageWidget field if non-nil, zero value otherwise. func (w *Widget) GetImageWidget() ImageWidget { if w == nil || w.ImageWidget == nil { return ImageWidget{} } return *w.ImageWidget } // GetOkImageWidget returns a tuple with the ImageWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetImageWidgetOk() (ImageWidget, bool) { if w == nil || w.ImageWidget == nil { return ImageWidget{}, false } return *w.ImageWidget, true } // HasImageWidget returns a boolean if a field has been set. func (w *Widget) HasImageWidget() bool { if w != nil && w.ImageWidget != nil { return true } return false } // SetImageWidget allocates a new w.ImageWidget and returns the pointer to it. func (w *Widget) SetImageWidget(v ImageWidget) { w.ImageWidget = &v } // GetName returns the Name field if non-nil, zero value otherwise. func (w *Widget) GetName() string { if w == nil || w.Name == nil { return "" } return *w.Name } // GetOkName returns a tuple with the Name field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetNameOk() (string, bool) { if w == nil || w.Name == nil { return "", false } return *w.Name, true } // HasName returns a boolean if a field has been set. func (w *Widget) HasName() bool { if w != nil && w.Name != nil { return true } return false } // SetName allocates a new w.Name and returns the pointer to it. func (w *Widget) SetName(v string) { w.Name = &v } // GetNoteWidget returns the NoteWidget field if non-nil, zero value otherwise. func (w *Widget) GetNoteWidget() NoteWidget { if w == nil || w.NoteWidget == nil { return NoteWidget{} } return *w.NoteWidget } // GetOkNoteWidget returns a tuple with the NoteWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetNoteWidgetOk() (NoteWidget, bool) { if w == nil || w.NoteWidget == nil { return NoteWidget{}, false } return *w.NoteWidget, true } // HasNoteWidget returns a boolean if a field has been set. func (w *Widget) HasNoteWidget() bool { if w != nil && w.NoteWidget != nil { return true } return false } // SetNoteWidget allocates a new w.NoteWidget and returns the pointer to it. func (w *Widget) SetNoteWidget(v NoteWidget) { w.NoteWidget = &v } // GetPrefix returns the Prefix field if non-nil, zero value otherwise. func (w *Widget) GetPrefix() string { if w == nil || w.Prefix == nil { return "" } return *w.Prefix } // GetOkPrefix returns a tuple with the Prefix field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetPrefixOk() (string, bool) { if w == nil || w.Prefix == nil { return "", false } return *w.Prefix, true } // HasPrefix returns a boolean if a field has been set. func (w *Widget) HasPrefix() bool { if w != nil && w.Prefix != nil { return true } return false } // SetPrefix allocates a new w.Prefix and returns the pointer to it. func (w *Widget) SetPrefix(v string) { w.Prefix = &v } // GetQueryValueWidget returns the QueryValueWidget field if non-nil, zero value otherwise. func (w *Widget) GetQueryValueWidget() QueryValueWidget { if w == nil || w.QueryValueWidget == nil { return QueryValueWidget{} } return *w.QueryValueWidget } // GetOkQueryValueWidget returns a tuple with the QueryValueWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetQueryValueWidgetOk() (QueryValueWidget, bool) { if w == nil || w.QueryValueWidget == nil { return QueryValueWidget{}, false } return *w.QueryValueWidget, true } // HasQueryValueWidget returns a boolean if a field has been set. func (w *Widget) HasQueryValueWidget() bool { if w != nil && w.QueryValueWidget != nil { return true } return false } // SetQueryValueWidget allocates a new w.QueryValueWidget and returns the pointer to it. func (w *Widget) SetQueryValueWidget(v QueryValueWidget) { w.QueryValueWidget = &v } // GetTimeseriesWidget returns the TimeseriesWidget field if non-nil, zero value otherwise. func (w *Widget) GetTimeseriesWidget() TimeseriesWidget { if w == nil || w.TimeseriesWidget == nil { return TimeseriesWidget{} } return *w.TimeseriesWidget } // GetOkTimeseriesWidget returns a tuple with the TimeseriesWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetTimeseriesWidgetOk() (TimeseriesWidget, bool) { if w == nil || w.TimeseriesWidget == nil { return TimeseriesWidget{}, false } return *w.TimeseriesWidget, true } // HasTimeseriesWidget returns a boolean if a field has been set. func (w *Widget) HasTimeseriesWidget() bool { if w != nil && w.TimeseriesWidget != nil { return true } return false } // SetTimeseriesWidget allocates a new w.TimeseriesWidget and returns the pointer to it. func (w *Widget) SetTimeseriesWidget(v TimeseriesWidget) { w.TimeseriesWidget = &v } // GetToplistWidget returns the ToplistWidget field if non-nil, zero value otherwise. func (w *Widget) GetToplistWidget() ToplistWidget { if w == nil || w.ToplistWidget == nil { return ToplistWidget{} } return *w.ToplistWidget } // GetOkToplistWidget returns a tuple with the ToplistWidget field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (w *Widget) GetToplistWidgetOk() (ToplistWidget, bool) { if w == nil || w.ToplistWidget == nil { return ToplistWidget{}, false } return *w.ToplistWidget, true } // HasToplistWidget returns a boolean if a field has been set. func (w *Widget) HasToplistWidget() bool { if w != nil && w.ToplistWidget != nil { return true } return false } // SetToplistWidget allocates a new w.ToplistWidget and returns the pointer to it. func (w *Widget) SetToplistWidget(v ToplistWidget) { w.ToplistWidget = &v } // GetMax returns the Max field if non-nil, zero value otherwise. func (y *Yaxis) GetMax() float64 { if y == nil || y.Max == nil { return 0 } return *y.Max } // GetOkMax returns a tuple with the Max field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (y *Yaxis) GetMaxOk() (float64, bool) { if y == nil || y.Max == nil { return 0, false } return *y.Max, true } // HasMax returns a boolean if a field has been set. func (y *Yaxis) HasMax() bool { if y != nil && y.Max != nil { return true } return false } // SetMax allocates a new y.Max and returns the pointer to it. func (y *Yaxis) SetMax(v float64) { y.Max = &v } // GetMin returns the Min field if non-nil, zero value otherwise. func (y *Yaxis) GetMin() float64 { if y == nil || y.Min == nil { return 0 } return *y.Min } // GetOkMin returns a tuple with the Min field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (y *Yaxis) GetMinOk() (float64, bool) { if y == nil || y.Min == nil { return 0, false } return *y.Min, true } // HasMin returns a boolean if a field has been set. func (y *Yaxis) HasMin() bool { if y != nil && y.Min != nil { return true } return false } // SetMin allocates a new y.Min and returns the pointer to it. func (y *Yaxis) SetMin(v float64) { y.Min = &v } // GetScale returns the Scale field if non-nil, zero value otherwise. func (y *Yaxis) GetScale() string { if y == nil || y.Scale == nil { return "" } return *y.Scale } // GetOkScale returns a tuple with the Scale field if it's non-nil, zero value otherwise // and a boolean to check if the value has been set. func (y *Yaxis) GetScaleOk() (string, bool) { if y == nil || y.Scale == nil { return "", false } return *y.Scale, true } // HasScale returns a boolean if a field has been set. func (y *Yaxis) HasScale() bool { if y != nil && y.Scale != nil { return true } return false } // SetScale allocates a new y.Scale and returns the pointer to it. func (y *Yaxis) SetScale(v string) { y.Scale = &v }
vendor/github.com/zorkian/go-datadog-api/datadog-accessors.go
0.789031
0.434761
datadog-accessors.go
starcoder
package flac import ( "bytes" ) // BlockType representation of types of FLAC Metadata Block type BlockType int // BlockData data in a FLAC Metadata Block. Custom Metadata decoders and modifiers should accept/modify whole MetaDataBlock instead. type BlockData []byte const ( // StreamInfo METADATA_BLOCK_STREAMINFO // This block has information about the whole stream, like sample rate, number of channels, total number of samples, etc. It must be present as the first metadata block in the stream. Other metadata blocks may follow, and ones that the decoder doesn't understand, it will skip. StreamInfo BlockType = iota // Padding METADATA_BLOCK_PADDING // This block allows for an arbitrary amount of padding. The contents of a PADDING block have no meaning. This block is useful when it is known that metadata will be edited after encoding; the user can instruct the encoder to reserve a PADDING block of sufficient size so that when metadata is added, it will simply overwrite the padding (which is relatively quick) instead of having to insert it into the right place in the existing file (which would normally require rewriting the entire file). Padding // Application METADATA_BLOCK_APPLICATION // This block is for use by third-party applications. The only mandatory field is a 32-bit identifier. This ID is granted upon request to an application by the FLAC maintainers. The remainder is of the block is defined by the registered application. Visit the registration page if you would like to register an ID for your application with FLAC. Application // SeekTable METADATA_BLOCK_SEEKTABLE // This is an optional block for storing seek points. It is possible to seek to any given sample in a FLAC stream without a seek table, but the delay can be unpredictable since the bitrate may vary widely within a stream. By adding seek points to a stream, this delay can be significantly reduced. Each seek point takes 18 bytes, so 1% resolution within a stream adds less than 2k. There can be only one SEEKTABLE in a stream, but the table can have any number of seek points. There is also a special 'placeholder' seekpoint which will be ignored by decoders but which can be used to reserve space for future seek point insertion. SeekTable // VorbisComment METADATA_BLOCK_VORBIS_COMMENT // This block is for storing a list of human-readable name/value pairs. Values are encoded using UTF-8. It is an implementation of the Vorbis comment specification (without the framing bit). This is the only officially supported tagging mechanism in FLAC. There may be only one VORBIS_COMMENT block in a stream. In some external documentation, Vorbis comments are called FLAC tags to lessen confusion. VorbisComment // CueSheet METADATA_BLOCK_CUESHEET // This block is for storing various information that can be used in a cue sheet. It supports track and index points, compatible with Red Book CD digital audio discs, as well as other CD-DA metadata such as media catalog number and track ISRCs. The CUESHEET block is especially useful for backing up CD-DA discs, but it can be used as a general purpose cueing mechanism for playback. CueSheet // Picture METADATA_BLOCK_PICTURE // This block is for storing pictures associated with the file, most commonly cover art from CDs. There may be more than one PICTURE block in a file. The picture format is similar to the APIC frame in ID3v2. The PICTURE block has a type, MIME type, and UTF-8 description like ID3v2, and supports external linking via URL (though this is discouraged). The differences are that there is no uniqueness constraint on the description field, and the MIME type is mandatory. The FLAC PICTURE block also includes the resolution, color depth, and palette size so that the client can search for a suitable picture without having to scan them all. Picture // Reserved Reserved Metadata Block Types Reserved // Invalid Invalid Metadata Block Type Invalid BlockType = 127 ) // MetaDataBlock is the struct representation of a FLAC Metadata Block type MetaDataBlock struct { Type BlockType Data BlockData } // Marshal encodes this MetaDataBlock without touching block data // isfinal defines whether this is the last metadata block of the FLAC file func (c *MetaDataBlock) Marshal(isfinal bool) []byte { res := bytes.NewBuffer([]byte{}) if isfinal { res.WriteByte(byte(c.Type + 1<<7)) } else { res.WriteByte(byte(c.Type)) } size := encodeUint32(uint32(len(c.Data))) res.Write(size[len(size)-3:]) res.Write(c.Data) return res.Bytes() }
metablock.go
0.572723
0.438004
metablock.go
starcoder
package features2d import ( "runtime" . "github.com/gooid/gocv/opencv3/core" . "github.com/gooid/gocv/opencv3/internal/native" ) const gRIDDETECTORFeatureDetector = 1000 const pYRAMIDDETECTORFeatureDetector = 2000 const dYNAMICDETECTORFeatureDetector = 3000 const FeatureDetectorFAST = 1 const FeatureDetectorSTAR = 2 const FeatureDetectorSIFT = 3 const FeatureDetectorSURF = 4 const FeatureDetectorORB = 5 const FeatureDetectorMSER = 6 const FeatureDetectorGFTT = 7 const FeatureDetectorHARRIS = 8 const FeatureDetectorSIMPLEBLOB = 9 const FeatureDetectorDENSE = 10 const FeatureDetectorBRISK = 11 const FeatureDetectorAKAZE = 12 var FeatureDetectorGRID_FAST = gRIDDETECTORFeatureDetector + FeatureDetectorFAST var FeatureDetectorGRID_STAR = gRIDDETECTORFeatureDetector + FeatureDetectorSTAR var FeatureDetectorGRID_SIFT = gRIDDETECTORFeatureDetector + FeatureDetectorSIFT var FeatureDetectorGRID_SURF = gRIDDETECTORFeatureDetector + FeatureDetectorSURF var FeatureDetectorGRID_ORB = gRIDDETECTORFeatureDetector + FeatureDetectorORB var FeatureDetectorGRID_MSER = gRIDDETECTORFeatureDetector + FeatureDetectorMSER var FeatureDetectorGRID_GFTT = gRIDDETECTORFeatureDetector + FeatureDetectorGFTT var FeatureDetectorGRID_HARRIS = gRIDDETECTORFeatureDetector + FeatureDetectorHARRIS var FeatureDetectorGRID_SIMPLEBLOB = gRIDDETECTORFeatureDetector + FeatureDetectorSIMPLEBLOB var FeatureDetectorGRID_DENSE = gRIDDETECTORFeatureDetector + FeatureDetectorDENSE var FeatureDetectorGRID_BRISK = gRIDDETECTORFeatureDetector + FeatureDetectorBRISK var FeatureDetectorGRID_AKAZE = gRIDDETECTORFeatureDetector + FeatureDetectorAKAZE var FeatureDetectorPYRAMID_FAST = pYRAMIDDETECTORFeatureDetector + FeatureDetectorFAST var FeatureDetectorPYRAMID_STAR = pYRAMIDDETECTORFeatureDetector + FeatureDetectorSTAR var FeatureDetectorPYRAMID_SIFT = pYRAMIDDETECTORFeatureDetector + FeatureDetectorSIFT var FeatureDetectorPYRAMID_SURF = pYRAMIDDETECTORFeatureDetector + FeatureDetectorSURF var FeatureDetectorPYRAMID_ORB = pYRAMIDDETECTORFeatureDetector + FeatureDetectorORB var FeatureDetectorPYRAMID_MSER = pYRAMIDDETECTORFeatureDetector + FeatureDetectorMSER var FeatureDetectorPYRAMID_GFTT = pYRAMIDDETECTORFeatureDetector + FeatureDetectorGFTT var FeatureDetectorPYRAMID_HARRIS = pYRAMIDDETECTORFeatureDetector + FeatureDetectorHARRIS var FeatureDetectorPYRAMID_SIMPLEBLOB = pYRAMIDDETECTORFeatureDetector + FeatureDetectorSIMPLEBLOB var FeatureDetectorPYRAMID_DENSE = pYRAMIDDETECTORFeatureDetector + FeatureDetectorDENSE var FeatureDetectorPYRAMID_BRISK = pYRAMIDDETECTORFeatureDetector + FeatureDetectorBRISK var FeatureDetectorPYRAMID_AKAZE = pYRAMIDDETECTORFeatureDetector + FeatureDetectorAKAZE var FeatureDetectorDYNAMIC_FAST = dYNAMICDETECTORFeatureDetector + FeatureDetectorFAST var FeatureDetectorDYNAMIC_STAR = dYNAMICDETECTORFeatureDetector + FeatureDetectorSTAR var FeatureDetectorDYNAMIC_SIFT = dYNAMICDETECTORFeatureDetector + FeatureDetectorSIFT var FeatureDetectorDYNAMIC_SURF = dYNAMICDETECTORFeatureDetector + FeatureDetectorSURF var FeatureDetectorDYNAMIC_ORB = dYNAMICDETECTORFeatureDetector + FeatureDetectorORB var FeatureDetectorDYNAMIC_MSER = dYNAMICDETECTORFeatureDetector + FeatureDetectorMSER var FeatureDetectorDYNAMIC_GFTT = dYNAMICDETECTORFeatureDetector + FeatureDetectorGFTT var FeatureDetectorDYNAMIC_HARRIS = dYNAMICDETECTORFeatureDetector + FeatureDetectorHARRIS var FeatureDetectorDYNAMIC_SIMPLEBLOB = dYNAMICDETECTORFeatureDetector + FeatureDetectorSIMPLEBLOB var FeatureDetectorDYNAMIC_DENSE = dYNAMICDETECTORFeatureDetector + FeatureDetectorDENSE var FeatureDetectorDYNAMIC_BRISK = dYNAMICDETECTORFeatureDetector + FeatureDetectorBRISK var FeatureDetectorDYNAMIC_AKAZE = dYNAMICDETECTORFeatureDetector + FeatureDetectorAKAZE type FeatureDetector struct { nativeObj int64 } func NewFeatureDetector(addr int64) (rcvr *FeatureDetector) { rcvr = &FeatureDetector{} rcvr.nativeObj = addr runtime.SetFinalizer(rcvr, func(interface{}) { rcvr.finalize() }) return } func FeatureDetectorCreate(detectorType int) *FeatureDetector { retVal := NewFeatureDetector(FeatureDetectorNative_create_0(detectorType)) return retVal } func (rcvr *FeatureDetector) Detect(image *Mat, keypoints *MatOfKeyPoint, mask *Mat) { keypoints_mat := keypoints FeatureDetectorNative_detect_0(rcvr.nativeObj, image.GetNativeObjAddr(), keypoints_mat.GetNativeObjAddr(), mask.GetNativeObjAddr()) return } func (rcvr *FeatureDetector) Detect2(image *Mat, keypoints *MatOfKeyPoint) { keypoints_mat := keypoints FeatureDetectorNative_detect_1(rcvr.nativeObj, image.GetNativeObjAddr(), keypoints_mat.GetNativeObjAddr()) return } func (rcvr *FeatureDetector) Detect3(images []*Mat, masks []*Mat) (keypoints []*MatOfKeyPoint) { images_mat := ConvertersVectorMat(images) keypoints_mat := NewMat2() masks_mat := ConvertersVectorMat(masks) FeatureDetectorNative_detect_2(rcvr.nativeObj, images_mat.GetNativeObjAddr(), keypoints_mat.GetNativeObjAddr(), masks_mat.GetNativeObjAddr()) keypoints = ConvertersToVectorVectorKeyPoint(keypoints_mat) keypoints_mat.Release() return } func (rcvr *FeatureDetector) Detect4(images []*Mat) (keypoints []*MatOfKeyPoint) { images_mat := ConvertersVectorMat(images) keypoints_mat := NewMat2() FeatureDetectorNative_detect_3(rcvr.nativeObj, images_mat.GetNativeObjAddr(), keypoints_mat.GetNativeObjAddr()) keypoints = ConvertersToVectorVectorKeyPoint(keypoints_mat) keypoints_mat.Release() return } func (rcvr *FeatureDetector) Empty() bool { retVal := FeatureDetectorNative_empty_0(rcvr.nativeObj) return retVal } func (rcvr *FeatureDetector) finalize() { FeatureDetectorNative_delete(rcvr.nativeObj) } func (rcvr *FeatureDetector) GetNativeObjAddr() int64 { return rcvr.nativeObj } func (rcvr *FeatureDetector) Read(fileName string) { FeatureDetectorNative_read_0(rcvr.nativeObj, fileName) return } func (rcvr *FeatureDetector) Write(fileName string) { FeatureDetectorNative_write_0(rcvr.nativeObj, fileName) return }
opencv3/features2d/FeatureDetector.java.go
0.528047
0.479016
FeatureDetector.java.go
starcoder
package measurement import ( "fmt" "sync" "sync/atomic" "time" ) type Measurement struct { warmUp int32 // use as bool, 1 means in warmup progress, 0 means warmup finished. sync.RWMutex OpCurMeasurement map[string]*Histogram OpSumMeasurement map[string]*Histogram } func (m *Measurement) getHist(op string, err error, current bool) *Histogram { opMeasurement := m.OpSumMeasurement if current { opMeasurement = m.OpCurMeasurement } // Create hist of {op} and {op}_ERR at the same time, or else the TPM would be incorrect opPairedKey := fmt.Sprintf("%s_ERR", op) if err != nil { op, opPairedKey = opPairedKey, op } m.RLock() opM, ok := opMeasurement[op] m.RUnlock() if !ok { opM = NewHistogram() opPairedM := NewHistogram() m.Lock() opMeasurement[op] = opM opMeasurement[opPairedKey] = opPairedM m.Unlock() } return opM } func (m *Measurement) measure(op string, err error, lan time.Duration) { m.getHist(op, err, true).Measure(lan) m.getHist(op, err, false).Measure(lan) } func (m *Measurement) takeCurMeasurement() (ret map[string]*Histogram) { m.RLock() defer m.RUnlock() ret, m.OpCurMeasurement = m.OpCurMeasurement, make(map[string]*Histogram, 16) return } func (m *Measurement) getOpName() []string { m.RLock() defer m.RUnlock() res := make([]string, 0, len(m.OpSumMeasurement)) for op := range m.OpSumMeasurement { res = append(res, op) } return res } // Output prints the measurement summary. func (m *Measurement) Output(ifSummaryReport bool, outputFunc func(string, map[string]*Histogram)) { if ifSummaryReport { m.RLock() defer m.RUnlock() outputFunc("[Summary] ", m.OpSumMeasurement) return } // Clear current measure data every time var opCurMeasurement = m.takeCurMeasurement() m.RLock() defer m.RUnlock() outputFunc("[Current] ", opCurMeasurement) } // EnableWarmUp sets whether to enable warm-up. func (m *Measurement) EnableWarmUp(b bool) { if b { atomic.StoreInt32(&m.warmUp, 1) } else { atomic.StoreInt32(&m.warmUp, 0) } } // IsWarmUpFinished returns whether warm-up is finished or not. func (m *Measurement) IsWarmUpFinished() bool { return atomic.LoadInt32(&m.warmUp) == 0 } // Measure measures the operation. func (m *Measurement) Measure(op string, lan time.Duration, err error) { if !m.IsWarmUpFinished() { return } m.measure(op, err, lan) } func NewMeasurement() *Measurement { return &Measurement{ 0, sync.RWMutex{}, make(map[string]*Histogram, 16), make(map[string]*Histogram, 16), } }
pkg/measurement/measure.go
0.638385
0.510619
measure.go
starcoder
package main import ( "errors" "fmt" ) // Functions main purpose is to break a large program into a number of smaller // tasks (functions). It also helps enforce the D-R-Y (dont repeat yourself) // principle, the same task can be invoked several times, so a function promotes code reuse. // There are 3 types of functions in Go: // - Normal functions with an identifier // - Anonymous or lamda functions // - Methods // Any of these can have parameters and return values. The definition of all the // function parameters and return values, together with their types, is called // the function signature. // The function main is special, go programs begins execution in the function // named main located in package main. func main() { // You invoke the function by specifying the name of the package it is // defined in followed by a . (dot) followed by the name of the function // and any parameters within a set of parantheses. // However if the function is defined in the current package then it can // be invoked by referring to its name and providing the values for // all defined parameters, if any. Greet() x, y := 1, 2 // You can capture the returned value either assigning it to a variable or // passing it as argument to another function r := add(x, y) fmt.Printf("The sum of %d and %d is %d\n", x, y, r) numr, denom := 3, 0 quot, err := divide(numr, denom) if err != nil { fmt.Println(err) } else { fmt.Printf("Result of %d / %d is %d\n", numr, denom, quot) } // One or more returned values can be discarded using the blank identifier _ (underscore) // When would this be useful? // Recall that its illegal to declare a variable and not use it. Now suppose // you have function that you wrote or calling a function defined in some // package, but you do not want to consume one or more returned values. // The only way out, is to use the blank indentifier. // For example here the second retured value error is being discarded // NOTE: Its considered bad parctice to ignore errors. Please dont do this in normal code. // I am ignoring the error returned only to demonstrate how to discard one or more returned values. q, _ := divide(numr, denom) fmt.Printf("Result of %d / %d is %d\n", numr, denom, q) // call the variadic function sum n := []int{1, 2, 3, 4, 5, 6, 7, 8, 9} // n... is the shorthand to pass each element of the slice to the function s := sum("Sum of input number is:", n...) fmt.Printf("%s", s) // call recursive function fmt.Printf("Fibonacci of 10 is %d\n", fibonacci(10)) // A function that does not have a name is called anonymous function // (also known under the names of a lambda function, a function literal, or a closure). // Such a function cannot stand on its own, since complier would throw an error. // Hence such functions must be either assigned to variable or must be // directly invoked or returned as output value of a named function // The variable prod's value is a function that returns product of the passed numbers prod := func(x, y int) int { return x * y } fmt.Printf("%d * %d = %d\n", x, y, prod(x, y)) // To directly invoke an anonymous function, put pair of () after the closing // '}' brackets within which we can list the optional parameters to the function. func(x, y int) { fmt.Printf("%d %% %d = %d\n", x, y, x%y) }(4, 2) // 4,2 are the parameters to the anonymous function } // The keyword func introduces a function // A function can take zero or more paramaters // One of the functions parameters can accept arbitary number of values // A function can return zero or more values, unlike other languages // A function can take other function as paramters or return functions as return values // A function which starts with capital/uppercase letter is exported (visible/accessible from other packages) // The order in which functions are defined in go source file is of no // consequence, however it is idiomatic to define the main function as first function. // Greet is a function that take no paraters and returns no values. Notice this // function start with capital letter hence it is said to be a exported function. func Greet() { fmt.Printf("Hello how are you?\n") } // add is a function that take two parameters of type int and return a single // value of the type int. Notice this function start with lowercase letter hence // it is said to be un-exported function. func add(x, y int) int { return x + y } var ErrDivideByZero = errors.New("Division by zero is not allowed") // A function can return one or more values. This forms very foundations of Go's error // handling machinary, since unlike other languages go does not support exception handling // NOTE: If you have more than one returned value then they must enclosed in set of parens func divide(x, y int) (int, error) { if y == 0 { return 0, ErrDivideByZero } return x / y, nil } // A function parameter can accept arbitary number of values. Such functions are // called as variadic functions. A variadic parameter is prefixed by ... (three asterisks) // to its type. There can only be one such parameter. If a function happens to take // more than one parameter, then the parameter that accepts multiple values // must be the last one. The following example show one such function. // The value of the variadic parameter is accessible as a slice within the // function body, which are be iterated over using the for..range loop func sum(title string, nums ...int) string { fmt.Printf("Data type of nums is %T\n", nums) s := 0 for _, v := range nums { s += v } return fmt.Sprintf("%s %d\n", title, s) } // A function that calls itself in the body of the function is called a recursive function. func fibonacci(num int) int { if num == 0 { return 0 } else if num == 1 { return 1 } return fibonacci(num-1) + fibonacci(num-2) } // A function can have named return values, in which case you can assign name to // the returned types and have naked retrun statement. The last computed value // of the variable would be retuned when the function exits func IsEven(n int) (result bool) { // Since the dafault value of bool type is false // the following statement is redundant result = false if n%2 == 0 { result = true } return }
11.function/1.function.go
0.616474
0.608856
1.function.go
starcoder
package day12 import ( "math" "strconv" ) // Waypoint creates a waypoint type Waypoint struct { Movements map[Direction]int } // NewWaypoint creates a new way point func NewWaypoint() *Waypoint { return &Waypoint{ Movements: map[Direction]int{ North: 1, East: 10, }, } } // Move moves the waypoint a distance given a direction func (w *Waypoint) Move(direction Direction, distance int) { w.Movements[direction] += distance } // RotateRight rotates the waypoint right respective to the boat func (w *Waypoint) RotateRight(degrees int) { times := degrees / 90 var north, south, east, west int for i := 0; i < times; i++ { north, south, east, west = w.Movements[North], w.Movements[South], w.Movements[East], w.Movements[West] w.Movements[North] = west w.Movements[East] = north w.Movements[South] = east w.Movements[West] = south } } // RotateLeft rotates the waypoint left respective to the boat func (w *Waypoint) RotateLeft(degrees int) { w.RotateRight(360 - degrees) } // Boat represents the boat we want to move type Boat struct { Direction Direction Movements map[Direction]int Waypoint *Waypoint } // NewBoat initializes a new boat func NewBoat() *Boat { return &Boat{ Direction: East, Movements: make(map[Direction]int), Waypoint: NewWaypoint(), } } // MoveBoatForward moves a specific distance in // the boat's direction func (b *Boat) MoveBoatForward(distance int) { b.Movements[b.Direction] += distance } // MoveForwardRelativeToWaypoint moves the boat a number of times // the waypoint's direction func (b *Boat) MoveForwardRelativeToWaypoint(times int) { for direction, distance := range b.Waypoint.Movements { b.Movements[direction] += (distance * times) } } // RotateRight rotates the boat in the right direction func (b *Boat) RotateRight(degrees int) { times := degrees / 90 for i := 0; i < times; i++ { switch b.Direction { case North: b.Direction = East case East: b.Direction = South case South: b.Direction = West case West: b.Direction = North } } } // RotateLeft rotates the boat in left direction func (b *Boat) RotateLeft(degrees int) { b.RotateRight(360 - degrees) } // RotateWaypointRight rotates the waypoint right func (b *Boat) RotateWaypointRight(degrees int) { b.Waypoint.RotateRight(degrees) } // RotateWaypointLeft rotates the waypoint left func (b *Boat) RotateWaypointLeft(degrees int) { b.Waypoint.RotateLeft(degrees) } // MoveBoat moves the boat a specific distance in the // given direction func (b *Boat) MoveBoat(direction Direction, distance int) { b.Movements[direction] += distance } // MoveWaypoint moves the waypoint at a given direction func (b *Boat) MoveWaypoint(direction Direction, distance int) { b.Waypoint.Move(direction, distance) } // ManhattanDistance calculates the manhattan distance // between (0,0) and the point where the boat is func (b *Boat) ManhattanDistance() int { north, south := b.Movements[North], b.Movements[South] west, east := b.Movements[West], b.Movements[East] y := math.Abs(float64(north - south)) x := math.Abs(float64(west - east)) return int(x + y) } // RunActionsWithoutWaypoint runs the actions without taking into account // the waypoint func (b *Boat) RunActionsWithoutWaypoint(actions []Action) { for _, a := range actions { switch a.Action { case "N": b.MoveBoat(North, a.Value) case "E": b.MoveBoat(East, a.Value) case "S": b.MoveBoat(South, a.Value) case "W": b.MoveBoat(West, a.Value) case "F": b.MoveBoatForward(a.Value) case "R": b.RotateRight(a.Value) case "L": b.RotateLeft(a.Value) } } } // RunActionsWithWaypoint runs the actions taking into account the waypoint func (b *Boat) RunActionsWithWaypoint(actions []Action) { for _, a := range actions { switch a.Action { case "N": b.MoveWaypoint(North, a.Value) case "E": b.MoveWaypoint(East, a.Value) case "S": b.MoveWaypoint(South, a.Value) case "W": b.MoveWaypoint(West, a.Value) case "F": b.MoveForwardRelativeToWaypoint(a.Value) case "R": b.RotateWaypointRight(a.Value) case "L": b.RotateWaypointLeft(a.Value) } } } // FirstPart runs the instructions and calcs the manhattan distance // between the boat's initial position and the final one func FirstPart(lines []string) (int, error) { actions, err := parseLines(lines) if err != nil { return 0, err } b := NewBoat() b.RunActionsWithoutWaypoint(actions) return b.ManhattanDistance(), nil } // SecondPart runs the instructions and calcs the manhattan distance // between the boat's initial position and the final one // taking into account the waypoint's relative position func SecondPart(lines []string) (int, error) { actions, err := parseLines(lines) if err != nil { return 0, err } b := NewBoat() b.RunActionsWithWaypoint(actions) return b.ManhattanDistance(), nil } // Action represents an action // e.g. R90, L180, F10 type Action struct { Action string Value int } func parseLines(lines []string) ([]Action, error) { actions := make([]Action, len(lines)) for i, l := range lines { action, strValue := l[:1], l[1:] v, err := strconv.Atoi(strValue) if err != nil { return nil, err } actions[i] = Action{ Action: action, Value: v, } } return actions, nil }
day12/day12.go
0.766337
0.491456
day12.go
starcoder
package scheme import ( "errors" "fmt" "math" "strconv" "github.com/iomz/go-llrp/binutil" ) // PartitionTableKey is used for PartitionTables type PartitionTableKey int // PartitionTable is used to get the related values for each coding scheme type PartitionTable map[int]map[PartitionTableKey]int // Key values for PartitionTables const ( PValue PartitionTableKey = iota CPBits IRBits IRDigits EBits EDigits ATBits ATDigits IARBits IARDigits ) // GIAI96PartitionTable is PT for GIAI var GIAI96PartitionTable = PartitionTable{ 12: {PValue: 0, CPBits: 40, IARBits: 42, IARDigits: 13}, 11: {PValue: 1, CPBits: 37, IARBits: 45, IARDigits: 14}, 10: {PValue: 2, CPBits: 34, IARBits: 48, IARDigits: 15}, 9: {PValue: 3, CPBits: 30, IARBits: 52, IARDigits: 16}, 8: {PValue: 4, CPBits: 27, IARBits: 55, IARDigits: 17}, 7: {PValue: 5, CPBits: 24, IARBits: 58, IARDigits: 18}, 6: {PValue: 6, CPBits: 20, IARBits: 62, IARDigits: 19}, } // GRAI96PartitionTable is PT for GRAI var GRAI96PartitionTable = PartitionTable{ 12: {PValue: 0, CPBits: 40, ATBits: 4, ATDigits: 0}, 11: {PValue: 1, CPBits: 37, ATBits: 7, ATDigits: 1}, 10: {PValue: 2, CPBits: 34, ATBits: 10, ATDigits: 2}, 9: {PValue: 3, CPBits: 30, ATBits: 14, ATDigits: 3}, 8: {PValue: 4, CPBits: 27, ATBits: 17, ATDigits: 4}, 7: {PValue: 5, CPBits: 24, ATBits: 20, ATDigits: 5}, 6: {PValue: 6, CPBits: 20, ATBits: 24, ATDigits: 6}, } // SGTIN96PartitionTable is PT for SGTIN var SGTIN96PartitionTable = PartitionTable{ 12: {PValue: 0, CPBits: 40, IRBits: 4, IRDigits: 1}, 11: {PValue: 1, CPBits: 37, IRBits: 7, IRDigits: 2}, 10: {PValue: 2, CPBits: 34, IRBits: 10, IRDigits: 3}, 9: {PValue: 3, CPBits: 30, IRBits: 14, IRDigits: 4}, 8: {PValue: 4, CPBits: 27, IRBits: 17, IRDigits: 5}, 7: {PValue: 5, CPBits: 24, IRBits: 20, IRDigits: 6}, 6: {PValue: 6, CPBits: 20, IRBits: 24, IRDigits: 7}, } // SSCC96PartitionTable is PT for SSCC var SSCC96PartitionTable = PartitionTable{ 12: {PValue: 0, CPBits: 40, EBits: 18, EDigits: 5}, 11: {PValue: 1, CPBits: 37, EBits: 21, EDigits: 6}, 10: {PValue: 2, CPBits: 34, EBits: 24, EDigits: 7}, 9: {PValue: 3, CPBits: 30, EBits: 28, EDigits: 8}, 8: {PValue: 4, CPBits: 27, EBits: 31, EDigits: 9}, 7: {PValue: 5, CPBits: 24, EBits: 34, EDigits: 10}, 6: {PValue: 6, CPBits: 20, EBits: 38, EDigits: 11}, } // GetAssetType returns Asset Type as rune slice func GetAssetType(at string, pr map[PartitionTableKey]int) (assetType []rune) { if at != "" { assetType = binutil.ParseDecimalStringToBinRuneSlice(at) if pr[ATBits] > len(assetType) { leftPadding := binutil.GenerateNLengthZeroPaddingRuneSlice(pr[ATBits] - len(assetType)) assetType = append(leftPadding, assetType...) } } else { assetType, _ = binutil.GenerateNLengthRandomBinRuneSlice(pr[ATBits], uint(math.Pow(float64(10), float64(pr[ATDigits])))) } return } // GetCompanyPrefix returns Company Prefix as rune slice func GetCompanyPrefix(cp string, pt PartitionTable) (companyPrefix []rune) { if cp != "" { companyPrefix = binutil.ParseDecimalStringToBinRuneSlice(cp) if pt[len(cp)][CPBits] > len(companyPrefix) { leftPadding := binutil.GenerateNLengthZeroPaddingRuneSlice(pt[len(cp)][CPBits] - len(companyPrefix)) companyPrefix = append(leftPadding, companyPrefix...) } } return } // GetExtension returns Extension digit and Serial Reference as rune slice func GetExtension(e string, pr map[PartitionTableKey]int) (extension []rune) { if e != "" { extension = binutil.ParseDecimalStringToBinRuneSlice(e) if pr[EBits] > len(extension) { leftPadding := binutil.GenerateNLengthZeroPaddingRuneSlice(pr[EBits] - len(extension)) extension = append(leftPadding, extension...) } } else { extension, _ = binutil.GenerateNLengthRandomBinRuneSlice(pr[EBits], uint(math.Pow(float64(10), float64(pr[EDigits])))) } return } // GetFilter returns filter value as rune slice func GetFilter(fv string) (filter []rune) { if fv != "" { n, _ := strconv.ParseInt(fv, 10, 32) filter = []rune(fmt.Sprintf("%.3b", n)) } else { filter, _ = binutil.GenerateNLengthRandomBinRuneSlice(3, 7) } return } // GetIndivisualAssetReference returns iar as rune slice // IARDigits is the "max" length func GetIndivisualAssetReference(iar string, pr map[PartitionTableKey]int) (indivisualAssetReference []rune) { if iar != "" { indivisualAssetReference = binutil.ParseDecimalStringToBinRuneSlice(iar) if pr[IARBits] > len(indivisualAssetReference) { leftPadding := binutil.GenerateNLengthZeroPaddingRuneSlice(pr[IARBits] - len(indivisualAssetReference)) indivisualAssetReference = append(leftPadding, indivisualAssetReference...) } } else { indivisualAssetReference, _ = binutil.GenerateNLengthRandomBinRuneSlice(pr[IARBits], uint(math.Pow(float64(10), float64(pr[IARDigits])))) } return } // GetItemReference converts ItemReference value to rune slice func GetItemReference(ir string, pr map[PartitionTableKey]int) (itemReference []rune) { if ir != "" { itemReference = binutil.ParseDecimalStringToBinRuneSlice(ir) // If the itemReference is short, pad zeroes to the left if pr[IRBits] > len(itemReference) { leftPadding := binutil.GenerateNLengthZeroPaddingRuneSlice(pr[IRBits] - len(itemReference)) itemReference = append(leftPadding, itemReference...) } } else { itemReference, _ = binutil.GenerateNLengthRandomBinRuneSlice(pr[IRBits], uint(math.Pow(float64(10), float64(pr[IRDigits])))) } return } // GetSerial converts serial to rune slice func GetSerial(s string, serialLength int) (serial []rune) { if s != "" { serial = binutil.ParseDecimalStringToBinRuneSlice(s) if serialLength > len(serial) { leftPadding := binutil.GenerateNLengthZeroPaddingRuneSlice(serialLength - len(serial)) serial = append(leftPadding, serial...) } } else { serial, _ = binutil.GenerateNLengthRandomBinRuneSlice(serialLength, uint(math.Pow(float64(2), float64(serialLength)))) } return serial } // MakeGIAI96 generates GIAI-96 func MakeGIAI96(pf bool, fv string, cp string, iar string) ([]byte, string, string, error) { filter := GetFilter(fv) if fv == "" { fv = strconv.Itoa(binutil.ParseBinRuneSliceToInt(filter)) } // CP if cp == "" { if pf { return []byte{}, "00110100" + string(filter), "urn:epc:pat:giai-96:" + fv, nil } return []byte{}, "", "", errors.New("companyPrefix is empty") } companyPrefix := GetCompanyPrefix(cp, GIAI96PartitionTable) partition := []rune(fmt.Sprintf("%.3b", GIAI96PartitionTable[len(cp)][PValue])) // IAR if iar == "" { if pf { return []byte{}, "00110100" + string(filter) + string(partition) + string(companyPrefix), "urn:epc:pat:giai-96:" + fv + "." + cp, nil } } indivisualAssetReference := GetIndivisualAssetReference(iar, GIAI96PartitionTable[len(cp)]) // Exact match if pf { return []byte{}, "00110100" + string(filter) + string(partition) + string(companyPrefix) + string(indivisualAssetReference), "urn:epc:pat:giai-96:" + fv + "." + cp + "." + iar, nil } bs := append(filter, partition...) bs = append(bs, companyPrefix...) bs = append(bs, indivisualAssetReference...) if len(bs) != 88 { return []byte{}, "", "", fmt.Errorf("invalid len(bs): %v, want 88", len(bs)) } p, err := binutil.ParseBinRuneSliceToUint8Slice(bs) if err != nil { return []byte{}, "", "", err } var giai96 = []interface{}{ uint8(52), // GIAI-96 Header 0011 0100 p[0], // 8 bits -> 16 bits p[1], // 8 bits -> 24 bits p[2], // 8 bits -> 32 bits p[3], // 8 bits -> 40 bits p[4], // 8 bits -> 48 bits p[5], // 8 bits -> 56 bits p[6], // 8 bits -> 64 bits p[7], // 8 bits -> 72 bits p[8], // 8 bits -> 80 bits p[9], // 8 bits -> 88 bits p[10], // 8 bits -> 96 bits } return binutil.Pack(giai96), "", "", nil } // MakeGRAI96 generates GRAI-96 func MakeGRAI96(pf bool, fv string, cp string, at string, ser string) ([]byte, string, string, error) { filter := GetFilter(fv) //CP if cp == "" { if pf { return []byte{}, "00110011" + string(filter), "urn:epc:pat:grai-96:" + fv, nil } return []byte{}, "", "", errors.New("companyPrefix is empty") } companyPrefix := GetCompanyPrefix(cp, GRAI96PartitionTable) partition := []rune(fmt.Sprintf("%.3b", GRAI96PartitionTable[len(cp)][PValue])) //AT if at == "" { if pf { return []byte{}, "00110011" + string(filter) + string(partition) + string(companyPrefix), "urn:epc:pat:grai-96:" + fv + "." + cp, nil } } assetType := GetAssetType(at, GRAI96PartitionTable[len(cp)]) // SER if ser == "" { if pf { return []byte{}, "00110011" + string(filter) + string(partition) + string(companyPrefix) + string(assetType), "urn:epc:pat:grai-96:" + fv + "." + cp + "." + at, nil } } serial := GetSerial(ser, 38) // Exact match if pf { return []byte{}, "00110011" + string(filter) + string(partition) + string(companyPrefix) + string(assetType) + string(serial), "urn:epc:pat:grai-96:" + fv + "." + cp + "." + at + "." + ser, nil } bs := append(filter, partition...) bs = append(bs, companyPrefix...) bs = append(bs, assetType...) bs = append(bs, serial...) if len(bs) != 88 { return []byte{}, "", "", fmt.Errorf("len(bs): %v, want 88", len(bs)) } p, err := binutil.ParseBinRuneSliceToUint8Slice(bs) if err != nil { return []byte{}, "", "", err } var grai96 = []interface{}{ uint8(51), // GRAI-96 Header 0011 0011 p[0], // 8 bits -> 16 bits p[1], // 8 bits -> 24 bits p[2], // 8 bits -> 32 bits p[3], // 8 bits -> 40 bits p[4], // 8 bits -> 48 bits p[5], // 8 bits -> 56 bits p[6], // 8 bits -> 64 bits p[7], // 8 bits -> 72 bits p[8], // 8 bits -> 80 bits p[9], // 8 bits -> 88 bits p[10], // 8 bits -> 96 bits } return binutil.Pack(grai96), "", "", nil } // MakeSGTIN96 generates SGTIN-96 func MakeSGTIN96(pf bool, fv string, cp string, ir string, ser string) ([]byte, string, string, error) { filter := GetFilter(fv) // CP if cp == "" { if pf { return []byte{}, "00110000" + string(filter), "urn:epc:pat:sgtin-96:" + fv, nil } return []byte{}, "", "", errors.New("companyPrefix is empty") } companyPrefix := GetCompanyPrefix(cp, SGTIN96PartitionTable) partition := []rune(fmt.Sprintf("%.3b", SGTIN96PartitionTable[len(cp)][PValue])) // IR if ir == "" { if pf { return []byte{}, "00110000" + string(filter) + string(partition) + string(companyPrefix), "urn:epc:pat:sgtin-96:" + fv + "." + cp, nil } } itemReference := GetItemReference(ir, SGTIN96PartitionTable[len(cp)]) // SER if ser == "" { if pf { return []byte{}, "00110000" + string(filter) + string(partition) + string(companyPrefix) + string(itemReference), "urn:epc:pat:sgtin-96:" + fv + "." + cp + "." + ir, nil } } serial := GetSerial(ser, 38) // Exact match if pf { return []byte{}, "00110000" + string(filter) + string(partition) + string(companyPrefix) + string(itemReference) + string(serial), "urn:epc:pat:sgtin-96:" + fv + "." + cp + "." + ir + "." + ser, nil } bs := append(filter, partition...) bs = append(bs, companyPrefix...) bs = append(bs, itemReference...) bs = append(bs, serial...) if len(bs) != 88 { return []byte{}, "", "", fmt.Errorf("len(bs): %v, want 88", len(bs)) } p, err := binutil.ParseBinRuneSliceToUint8Slice(bs) if err != nil { return []byte{}, "", "", err } var sgtin96 = []interface{}{ uint8(48), // SGTIN-96 Header 0011 0000 p[0], // 8 bits -> 16 bits p[1], // 8 bits -> 24 bits p[2], // 8 bits -> 32 bits p[3], // 8 bits -> 40 bits p[4], // 8 bits -> 48 bits p[5], // 8 bits -> 56 bits p[6], // 8 bits -> 64 bits p[7], // 8 bits -> 72 bits p[8], // 8 bits -> 80 bits p[9], // 8 bits -> 88 bits p[10], // 8 bits -> 96 bits } return binutil.Pack(sgtin96), "", "", nil } // MakeSSCC96 generates SSCC-96 func MakeSSCC96(pf bool, fv string, cp string, ext string) ([]byte, string, string, error) { filter := GetFilter(fv) // CP if cp == "" { if pf { return []byte{}, "00110001" + string(filter), "urn:epc:pat:sscc-96:" + fv, nil } return []byte{}, "", "", errors.New("companyPrefix is empty") } companyPrefix := GetCompanyPrefix(cp, SSCC96PartitionTable) partition := []rune(fmt.Sprintf("%.3b", SSCC96PartitionTable[len(cp)][PValue])) // EXT if ext == "" { if pf { return []byte{}, "00110001" + string(filter) + string(partition) + string(companyPrefix), "urn:epc:pat:sscc-96:" + fv + "." + cp, nil } } extension := GetExtension(ext, SSCC96PartitionTable[len(cp)]) // Exact match (ignore rsvd if pf { return []byte{}, "00110001" + string(filter) + string(partition) + string(companyPrefix) + string(extension), "urn:epc:pat:sscc-96:" + fv + "." + cp + "." + ext, nil } // 24 '0's reserved := binutil.GenerateNLengthZeroPaddingRuneSlice(24) bs := append(filter, partition...) bs = append(bs, companyPrefix...) bs = append(bs, extension...) bs = append(bs, reserved...) if len(bs) != 88 { return []byte{}, "", "", fmt.Errorf("len(bs): %v, want 88", len(bs)) } p, err := binutil.ParseBinRuneSliceToUint8Slice(bs) if err != nil { return []byte{}, "", "", err } var sscc96 = []interface{}{ uint8(49), // SSCC-96 Header 0011 0001 p[0], // 8 bits -> 16 bits p[1], // 8 bits -> 24 bits p[2], // 8 bits -> 32 bits p[3], // 8 bits -> 40 bits p[4], // 8 bits -> 48 bits p[5], // 8 bits -> 56 bits p[6], // 8 bits -> 64 bits p[7], // 8 bits -> 72 bits p[8], // 8 bits -> 80 bits p[9], // 8 bits -> 88 bits p[10], // 8 bits -> 96 bits } return binutil.Pack(sscc96), "", "", nil }
scheme/epc.go
0.668339
0.46393
epc.go
starcoder
package schema // ExtensionSchemaJSON is the content of the file "extension.schema.json". const ExtensionSchemaJSON = `{ "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://sourcegraph.com/v1/extension.schema.json#", "title": "Sourcegraph extension manifest", "description": "The Sourcegraph extension manifest describes the extension and the features it provides.", "type": "object", "additionalProperties": false, "required": ["url", "activationEvents"], "properties": { "title": { "description": "The title of the extension. If not specified, the extension ID is used.", "type": "string" }, "description": { "description": "The extension's description, which summarizes the extension's purpose and features. It should not exceed a few sentences.", "type": "string", "maxLength": 280 }, "icon": { "description": "The extension icon in data URI format (must begin with data:image/png).", "type": "string", "format": "^data:image/png" }, "readme": { "description": "The extension's README, which should describe (in detail) the extension's purpose, features, and usage instructions. Markdown formatting is supported.", "type": "string", "format": "markdown" }, "url": { "description": "A URL to a file containing the bundled JavaScript source code of this extension.", "type": "string", "format": "uri" }, "repository": { "$ref": "#/definitions/ExtensionRepository" }, "activationEvents": { "description": "A list of events that cause this extension to be activated. '*' means that it will always be activated.", "type": "array", "items": { "type": "string", "pattern": "^(\\*|onLanguage:\\w+)$", "examples": ["onLanguage:javascript", "onLanguage:python", "*"] } }, "args": { "description": "Arguments provided to the extension upon initialization (in the ` + "`" + `initialize` + "`" + ` message's ` + "`" + `initializationOptions` + "`" + ` field).", "type": "object", "additionalProperties": true, "!go": { "pointer": true } }, "contributes": { "$ref": "#/definitions/Contributions" } }, "definitions": { "Contributions": { "description": "Features contributed by this extension. Extensions may also register certain types of contributions dynamically.", "additionalProperties": false, "type": "object", "properties": { "configuration": { "description": "The JSON Schema for the configuration settings used by this extension. This schema is merged with the Sourcegraph settings schema. The final schema for settings is the union of Sourcegraph settings and all added extensions' settings.", "$ref": "http://json-schema.org/draft-07/schema#" }, "actions": { "description": "The actions that this extension supports.", "type": "array", "items": { "type": "object", "title": "action", "properties": { "id": { "description": "The unique ID for this action.", "type": "string" }, "command": { "description": "The command to execute when this action is taken.", "type": "string" }, "commandArguments": { "description": "The arguments to the command.", "type": "array", "items": {} }, "title": { "description": "The templated text that is shown in the UI.", "type": "string" }, "category": { "description": "The templated prefix for the title (e.g. a category of ` + "`" + `Codecov` + "`" + ` shows up as ` + "`" + `Codecov: ...` + "`" + ` in the command palette).", "type": "string" }, "iconURL": { "description": "The templated icon that is shown in the UI (usually a data URI).", "type": "string" }, "actionItem": { "description": "The action item.", "type": "object", "properties": { "label": { "description": "The templated text that is shown on the action item the UI.", "type": "string" }, "description": { "description": "The templated tooltip text for an action item that is shown in the UI.", "type": "string" }, "iconURL": { "description": "The templated icon that is shown in the UI (usually a data URI).", "type": "string" } } } } } }, "menus": { "description": "Describes where to place actions in menus.", "type": "object", "properties": { "editor/title": { "description": "The file header.", "type": "array", "items": { "$ref": "#/definitions/MenuItem" } }, "commandPalette": { "description": "The command palette (usually in the upper right).", "type": "array", "items": { "$ref": "#/definitions/MenuItem" } }, "help": { "description": "The help menu.", "type": "array", "items": { "$ref": "#/definitions/MenuItem" } } } } } }, "MenuItem": { "type": "object", "properties": { "action": { "description": "The ID of the action to take when this menu item is clicked.", "type": "string" }, "alt": { "description": "The tooltip text to show when hovering over this menu item.", "type": "string" }, "when": { "description": "An expression that determines whether or not to show this menu item.", "type": "string" } } }, "ExtensionRepository": { "description": "The location of the version control repository for this extension.", "type": "object", "additionalProperties": false, "required": ["url"], "properties": { "type": { "description": "The version control system (e.g. git).", "type": "string" }, "url": { "description": "A URL to the source code for this extension.", "type": "string", "format": "uri" } } } } } `
schema/extension_stringdata.go
0.826852
0.517876
extension_stringdata.go
starcoder
package block import "errors" // Service facilitates the creation and management of stored data. type Service struct { BlockStore Store ChainStore ChainStore } // NewBlock creates a new block for the provided chain and // guarantees it as a valid next block on the chain. func (s *Service) NewBlock(c *Chain, data []byte) (*Block, error) { for { b := c.NewBlock(nil) err := c.AddBlock(b) if err == ErrInvalidPrevHash { continue } else if err != nil { return nil, err } return b, nil } } func (s *Service) DeleteBlock(hash Hash) error { return s.BlockStore.Delete(hash) } func (s *Service) ReadBlock(hash Hash) (*Block, error) { return s.BlockStore.Read(hash) } func (s *Service) WriteBlock(b *Block) error { return s.BlockStore.Write(b) } // NewBranch creates a branch from a chain's block. func (s *Service) NewBranch(fromChain *Chain, fromBlock *Block) (*Branch, error) { c2, err := s.NewChain() if err != nil { return nil, err } branch, err := fromChain.NewBranch(fromBlock, c2) if err != nil { return nil, err } return branch, nil } // DeleteChain deletes a chain from the chain store. func (s *Service) DeleteChain(hash ChainHash) error { if s.ChainStore == nil { return errors.New("no ChainStore provided to the storage service") } return s.ChainStore.Delete(hash) } // NewChain creates new chain with a genesis block. func (s *Service) NewChain() (*Chain, error) { hash, err := NewChainHash() if err != nil { return nil, err } c := &Chain{ Blocks: make(map[Hash]Index), Branches: make(map[BranchHash]*Branch), Hash: hash, } b := c.NewBlock(nil) err = c.AddBlock(b) if err != nil { return nil, err } return c, nil } // ReadChain reads a chain from the chain store using its hash. func (s *Service) ReadChain(hash ChainHash) (*Chain, error) { if s.ChainStore == nil { return nil, errors.New("no ChainStore provided to the storage service") } return s.ChainStore.Read(hash) } // WriteChain writes a chain to the chain store. func (s *Service) WriteChain(c *Chain) error { if s.ChainStore == nil { return errors.New("no ChainStore provided to the storage service") } return s.ChainStore.Write(c) }
internal/xzor/block/service.go
0.657758
0.424591
service.go
starcoder
package scw import ( "net" "time" ) // StringPtr returns a pointer to the string value passed in. func StringPtr(v string) *string { return &v } // StringSlicePtr converts a slice of string values into a slice of // string pointers func StringSlicePtr(src []string) []*string { dst := make([]*string, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // StringsPtr returns a pointer to the []string value passed in. func StringsPtr(v []string) *[]string { return &v } // StringsSlicePtr converts a slice of []string values into a slice of // []string pointers func StringsSlicePtr(src [][]string) []*[]string { dst := make([]*[]string, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // BytesPtr returns a pointer to the []byte value passed in. func BytesPtr(v []byte) *[]byte { return &v } // BytesSlicePtr converts a slice of []byte values into a slice of // []byte pointers func BytesSlicePtr(src [][]byte) []*[]byte { dst := make([]*[]byte, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // BoolPtr returns a pointer to the bool value passed in. func BoolPtr(v bool) *bool { return &v } // BoolSlicePtr converts a slice of bool values into a slice of // bool pointers func BoolSlicePtr(src []bool) []*bool { dst := make([]*bool, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Int32Ptr returns a pointer to the int32 value passed in. func Int32Ptr(v int32) *int32 { return &v } // Int32SlicePtr converts a slice of int32 values into a slice of // int32 pointers func Int32SlicePtr(src []int32) []*int32 { dst := make([]*int32, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Int64Ptr returns a pointer to the int64 value passed in. func Int64Ptr(v int64) *int64 { return &v } // Int64SlicePtr converts a slice of int64 values into a slice of // int64 pointers func Int64SlicePtr(src []int64) []*int64 { dst := make([]*int64, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Uint32Ptr returns a pointer to the uint32 value passed in. func Uint32Ptr(v uint32) *uint32 { return &v } // Uint32SlicePtr converts a slice of uint32 values into a slice of // uint32 pointers func Uint32SlicePtr(src []uint32) []*uint32 { dst := make([]*uint32, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Uint64Ptr returns a pointer to the uint64 value passed in. func Uint64Ptr(v uint64) *uint64 { return &v } // Uint64SlicePtr converts a slice of uint64 values into a slice of // uint64 pointers func Uint64SlicePtr(src []uint64) []*uint64 { dst := make([]*uint64, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Float32Ptr returns a pointer to the float32 value passed in. func Float32Ptr(v float32) *float32 { return &v } // Float32SlicePtr converts a slice of float32 values into a slice of // float32 pointers func Float32SlicePtr(src []float32) []*float32 { dst := make([]*float32, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // Float64Ptr returns a pointer to the float64 value passed in. func Float64Ptr(v float64) *float64 { return &v } // Float64SlicePtr converts a slice of float64 values into a slice of // float64 pointers func Float64SlicePtr(src []float64) []*float64 { dst := make([]*float64, len(src)) for i := 0; i < len(src); i++ { dst[i] = &(src[i]) } return dst } // TimeDurationPtr returns a pointer to the Duration value passed in. // Deprecated: the use of time.Duration in request is deprecated and only available in lb API func TimeDurationPtr(v time.Duration) *time.Duration { return &v } // TimePtr returns a pointer to the Time value passed in. func TimePtr(v time.Time) *time.Time { return &v } // SizePtr returns a pointer to the Size value passed in. func SizePtr(v Size) *Size { return &v } // IPPtr returns a pointer to the net.IP value passed in. func IPPtr(v net.IP) *net.IP { return &v }
scw/convert.go
0.690559
0.418578
convert.go
starcoder
package detector import ( "fmt" "strings" "talisman/git_repo" ) //DetectionResults represents all interesting information collected during a detection run. //It serves as a collecting parameter for the tests performed by the various Detectors in the DetectorChain //Currently, it keeps track of failures and ignored files. //The results are grouped by FilePath for easy reporting of all detected problems with individual files. type DetectionResults struct { failures map[git_repo.FilePath][]string ignores map[git_repo.FilePath][]string } //NewDetectionResults is a new DetectionResults struct. It represents the pre-run state of a Detection run. func NewDetectionResults() *DetectionResults { result := DetectionResults{make(map[git_repo.FilePath][]string), make(map[git_repo.FilePath][]string)} return &result } //Fail is used to mark the supplied FilePath as failing a detection for a supplied reason. //Detectors are encouraged to provide context sensitive messages so that fixing the errors is made simple for the end user //Fail may be called multiple times for each FilePath and the calls accumulate the provided reasons func (r *DetectionResults) Fail(filePath git_repo.FilePath, message string) { errors, ok := r.failures[filePath] if !ok { r.failures[filePath] = []string{message} } else { r.failures[filePath] = append(errors, message) } } //Ignore is used to mark the supplied FilePath as being ignored. //The most common reason for this is that the FilePath is Denied by the Ignores supplied to the Detector, however, Detectors may use more sophisticated reasons to ignore files. func (r *DetectionResults) Ignore(filePath git_repo.FilePath, detector string) { ignores, ok := r.ignores[filePath] if !ok { r.ignores[filePath] = []string{detector} } else { r.ignores[filePath] = append(ignores, detector) } } //HasFailures answers if any failures were detected for any FilePath in the current run func (r *DetectionResults) HasFailures() bool { return len(r.failures) > 0 } //HasIgnores answers if any FilePaths were ignored in the current run func (r *DetectionResults) HasIgnores() bool { return len(r.ignores) > 0 } //Successful answers if no detector was able to find any possible result to fail the run func (r *DetectionResults) Successful() bool { return !r.HasFailures() } //Failures returns the various reasons that a given FilePath was marked as failing by all the detectors in the current run func (r *DetectionResults) Failures(fileName git_repo.FilePath) []string { return r.failures[fileName] } //Report returns a string documenting the various failures and ignored files for the current run func (r *DetectionResults) Report() string { var result string for filePath := range r.failures { result = result + r.ReportFileFailures(filePath) } if len(r.ignores) > 0 { result = result + fmt.Sprintf("The following files were ignored:\n") } for filePath := range r.ignores { result = result + fmt.Sprintf("\t%s was ignored by .talismanignore for the following detectors: %s\n", filePath, strings.Join(r.ignores[filePath], ", ")) } return result } //ReportFileFailures returns a string documenting the various failures detected on the supplied FilePath by all detectors in the current run func (r *DetectionResults) ReportFileFailures(filePath git_repo.FilePath) string { failures := r.failures[filePath] if len(failures) > 0 { result := fmt.Sprintf("The following errors were detected in %s\n", filePath) for _, failure := range failures { result = result + fmt.Sprintf("\t %s\n", failure) } return result } return "" } func (r *DetectionResults) failurePaths() []git_repo.FilePath { return keys(r.failures) } func (r *DetectionResults) ignorePaths() []git_repo.FilePath { return keys(r.ignores) } func keys(aMap map[git_repo.FilePath][]string) []git_repo.FilePath { var result []git_repo.FilePath for filePath := range aMap { result = append(result, filePath) } return result }
detector/detection_results.go
0.735262
0.494934
detection_results.go
starcoder
package parsetime import ( "strings" ) const ( year = `(2[0-9]{3}|19[7-9][0-9])` month = `(1[012]|0?[1-9])` day = `([12][0-9]|3[01]|0?[1-9])` hour = `(2[0-3]|[01]?[0-9])` min = `([0-5]?[0-9])` sec = min nsec = `(?:[.])?([0-9]{1,9})?` weekday = `(?:Mon|Monday|Tue|Tuesday|Wed|Wednesday|Thu|Thursday|Fri|Friday|Sat|Saturday|Sun|Sunday)` monthAbbr = `(Jan|January|Feb|Februray|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December|1[012]|0?[1-9])` offset = `(Z|[+-][01][1-9]:[0-9]{2})?` zone = `(?:[a-zA-Z0-9+-]{3,6})?` ymdSep = `[ /.-]?` hmsSep = `[ :.]?` t = `(?:t|T|\s*)?` s = `(?:\s*)?` ampm = `([aApP][mM])` ampmHour = `(1[01]|[0]?[0-9])` shortYear = `(2[0-9]{3}|19[7-9][0-9]|[0-9]{2})` offsetZone = `([+-][01][1-9]:[0-9]{2}|[a-zA-Z0-9+-]{3,6})?` usOffsetZone = `(?:[(])?([+-][01][1-9]:[0-9]{2}|[a-zA-Z0-9+-]{3,6})?(?:[)])?` ) // Regular expressions var ( // ISO8601, RFC3339 ISO8601 = strings.Join([]string{ `(?:`, year, ymdSep, month, ymdSep, day, `)?`, t, `(?:`, hour, hmsSep, min, hmsSep, sec, `?`, nsec, `)?`, s, offset, s, zone, }, "") // RFC822, RFC850, RFC1123 RFC8xx1123 = strings.Join([]string{ `(?:`, weekday, `,?`, s, `)?`, day, ymdSep, monthAbbr, ymdSep, shortYear, hmsSep, `(?:`, hour, hmsSep, min, hmsSep, sec, `?`, nsec, `)?`, s, offsetZone, }, "") ANSIC = strings.Join([]string{ `(?:`, weekday, s, `)?`, monthAbbr, ymdSep, day, ymdSep, `(?:`, hour, hmsSep, min, hmsSep, sec, `?`, nsec, `)?`, s, `(?:`, offsetZone, s, year, `)?`, }, "") US = strings.Join([]string{ `(?:`, monthAbbr, ymdSep, day, `(?:,)?`, ymdSep, shortYear, `)?`, s, `(?:at)?`, s, `(?:`, hour, hmsSep, min, hmsSep, sec, `?`, nsec, `)?`, s, ampm, `?`, s, usOffsetZone, }, "") Months = map[string]int{ "Jan": 1, "January": 1, "Feb": 2, "Februray": 2, "Mar": 3, "March": 3, "Apr": 4, "April": 4, "May": 5, "Jun": 6, "June": 6, "Jul": 7, "July": 7, "Aug": 8, "August": 8, "Sep": 9, "September": 9, "Oct": 10, "October": 10, "Nov": 11, "November": 11, "Dec": 12, "December": 12, } )
const.go
0.510496
0.402921
const.go
starcoder
package goh // IncludeStrings replace a value with new value // and returns a new slice without modifying original. func Replace(values []int, old, newValue int) []int { result := make([]int, len(values)) for i, v := range values { if v == old { result[i] = newValue continue } result[i] = v } return result } // FilterStrings gets a slice of strings // and returns a new slice with values which passed condition check. func FilterStrings(values []string, condition func(v string) bool) []string { var result []string for _, v := range values { if condition(v) { result = append(result, v) } } return result } // FilterStrings gets a slice of integers // and returns a new one with values which passed condition check. func FilterInt(values []int, condition func(v int) bool) []int { var result []int for _, v := range values { if condition(v) { result = append(result, v) } } return result } // IncludeStrings checks if a value is present in a slice. func IncludeString(values []string, value string) bool { for _, v := range values { if v == value { return true } } return false } // IncludeInt checks if a value is present in a slice. func IncludeInt(values []int, value int) bool { for _, v := range values { if v == value { return true } } return false } // Between checks if a value is between two values in a slice. func Between(values []int, value, beforeValue, afterValue int) bool { if len(values) == 2 || len(values) == 1 || len(values) == 0 { return false } if len(values) == 3 { for i, v := range values { if (i == 1 && v == value) && values[i-1] == beforeValue && values[i+1] == afterValue { return true } } } for i, v := range values { if (i != 0 && i != len(values)) && v == value && values[i-1] == beforeValue && values[i+1] == afterValue { return true } } return false } // MapString creates a new value based on function argument // and returns a new slice. func MapString(values []string, f func(v string) string) []string { result := make([]string, len(values)) for i, v := range values { result[i] = f(v) } return result } // MapString creates a new value based on function argument // and returns a new slice. func MapInt(values []int, f func(v int) int) []int { result := make([]int, len(values)) for i, v := range values { result[i] = f(v) } return result } // StringSliceEqual checks if two slices of strings are equal func StringSliceEqual(f, s []string) bool { var resultCount int if len(f) == len(s) { for i, v := range f { if v == s[i] { resultCount++ } } } if resultCount == len(f) { return true } return false } // IntSliceEqual checks if two slices of integers are equal func IntSliceEqual(f, s []int) bool { var resultCount int if len(f) == len(s) { for i, v := range f { if v == s[i] { resultCount++ } } } if resultCount == len(f) { return true } return false }
goh.go
0.859103
0.499573
goh.go
starcoder
// Package gpucuj tests GPU CUJ tests on lacros Chrome and Chrome OS Chrome. package gpucuj import ( "context" "math" "time" "chromiumos/tast/common/perf" "chromiumos/tast/errors" "chromiumos/tast/local/chrome" "chromiumos/tast/local/chrome/ash" "chromiumos/tast/local/chrome/cdputil" "chromiumos/tast/local/chrome/display" "chromiumos/tast/local/chrome/lacros" "chromiumos/tast/local/chrome/lacros/launcher" "chromiumos/tast/local/chrome/ui" "chromiumos/tast/local/chrome/uiauto/mouse" "chromiumos/tast/local/coords" "chromiumos/tast/local/input" "chromiumos/tast/testing" ) // TestType describes the type of GpuCUJ test to run. type TestType string // TestParams holds parameters describing how to run a GpuCUJ test. type TestParams struct { TestType TestType Rot90 bool // Whether to rotate the screen 90 or not. } const ( // TestTypeMaximized is a simple test of performance with a maximized window opening various web content. // This is useful for tracking the performance w.r.t hardware overlay forwarding of video or WebGL content. TestTypeMaximized TestType = "maximized" // TestTypeThreeDot is a test of performance while showing the three-dot context menu. This is intended to track the // performance impact of potential double composition of the context menu and hardware overlay usage. TestTypeThreeDot TestType = "threedot" // TestTypeResize is a test of performance during a drag-resize operation. TestTypeResize TestType = "resize" // TestTypeMoveOcclusion is a test of performance of gradual occlusion via drag-move of web content. This is useful for tracking impact // of hardware overlay forwarding and clipping (due to occlusion) of tiles optimisations. TestTypeMoveOcclusion TestType = "moveocclusion" // TestTypeMoveOcclusionWithCrosWindow is a test similar to TestTypeMoveOcclusion but always occludes using a ChromeOS chrome window. TestTypeMoveOcclusionWithCrosWindow TestType = "moveocclusion_withcroswindow" // testDuration indicates how long histograms should be sampled for during performance tests. testDuration time.Duration = 20 * time.Second // dragMoveOffsetDP indicates the offset from the top-left of a Chrome window to drag to ensure we can drag move it. dragMoveOffsetDP int = 5 // insetSlopDP indicates how much to inset the work area (display area) to avoid window snapping to the // edges of the screen interfering with drag-move and drag-resize of windows. insetSlopDP int = 40 ) type page struct { name string // url indicates a web page to navigate to as part of a GpuCUJ test. If url begins with a '/' it is instead // interpreted as a path to a local data file, which will be accessed via a local HTTP server. url string } var pageSet = []page{ { name: "aquarium", // WebGL Aquarium. This page is for testing WebGL. url: "https://webglsamples.org/aquarium/aquarium.html", }, { name: "poster", // Poster Circle. This page is for testing compositor performance. url: "https://webkit.org/blog-files/3d-transforms/poster-circle.html", }, { name: "maps", // Google Maps. This page is for testing WebGL. url: "https://www.google.com/maps/@35.652772,139.6605155,14z", }, { name: "video", // Static video. This page is for testing video playback. url: "/video.html", }, { name: "wikipedia", // Wikipedia. This page is for testing conventional web-pages. url: "https://en.wikipedia.org/wiki/Cat", }, } // This test deals with both ChromeOS chrome and lacros chrome. In order to reduce confusion, // we adopt the following naming convention for chrome.TestConn objects: // ctconn: chrome.TestConn to ChromeOS chrome. // ltconn: chrome.TestConn to lacros chrome. // tconn: chrome.TestConn to either ChromeOS or lacros chrome, i.e. both are usable. func leftClickLacros(ctx context.Context, ctconn *chrome.TestConn, windowID int, n *ui.Node) error { if err := n.Update(ctx); err != nil { return errors.Wrap(err, "failed to update the node's location") } if n.Location.Empty() { return errors.New("this node doesn't have a location on the screen and can't be clicked") } w, err := ash.GetWindow(ctx, ctconn, windowID) if err != nil { return err } // Compute the node coordinates in cros-chrome root window coordinate space by // adding the top left coordinate of the lacros-chrome window in cros-chrome root window coorindates. return mouse.Click(ctconn, w.BoundsInRoot.TopLeft().Add(n.Location.CenterPoint()), mouse.LeftButton)(ctx) } func toggleThreeDotMenu(ctx context.Context, tconn *chrome.TestConn, clickFn func(*ui.Node) error) error { // Open the three-dot menu via keyboard shortcut. kb, err := input.Keyboard(ctx) if err != nil { return err } defer kb.Close() // Press Alt+F to open three-dot menu. if err := kb.Accel(ctx, "Alt+F"); err != nil { return err } return nil } func setWindowBounds(ctx context.Context, ctconn *chrome.TestConn, windowID int, to coords.Rect) error { w, err := ash.GetWindow(ctx, ctconn, windowID) if err != nil { return err } info, err := display.GetPrimaryInfo(ctx, ctconn) if err != nil { return err } b, d, err := ash.SetWindowBounds(ctx, ctconn, w.ID, to, info.ID) if err != nil { return err } if b != to { return errors.Errorf("unable to set window bounds; got: %v, want: %v", b, to) } if d != info.ID { return errors.Errorf("unable to set window display; got: %v, want: %v", d, info.ID) } return nil } // testInvocation describes a particular test run. A test run involves running a particular scenario // (e.g. moveocclusion) with a particular type of Chrome (ChromeOS or Lacros) on a particular page. // This structure holds the necessary data to do this. type testInvocation struct { pv *perf.Values scenario TestType page page crt lacros.ChromeType metrics *metricsRecorder traceDir string } // runTest runs the common part of the GpuCUJ performance test - that is, shared between ChromeOS chrome and lacros chrome. // tconn is a test connection to the current browser being used (either ChromeOS or lacros chrome). func runTest(ctx context.Context, tconn *chrome.TestConn, f launcher.FixtValue, tracer traceable, invoc *testInvocation) error { w, err := lacros.FindFirstNonBlankWindow(ctx, f.TestAPIConn()) if err != nil { return err } info, err := display.GetPrimaryInfo(ctx, f.TestAPIConn()) if err != nil { return err } perfFn := func(ctx context.Context) error { return testing.Sleep(ctx, testDuration) } if invoc.scenario == TestTypeResize { // Restore window. if err := ash.SetWindowStateAndWait(ctx, f.TestAPIConn(), w.ID, ash.WindowStateNormal); err != nil { return errors.Wrap(err, "failed to restore non-blank window") } // Create a landscape rectangle. Avoid snapping by insetting by insetSlopDP. ms := math.Min(float64(info.WorkArea.Width), float64(info.WorkArea.Height)) sb := coords.NewRect(info.WorkArea.Left, info.WorkArea.Top, int(ms), int(ms*0.6)).WithInset(insetSlopDP, insetSlopDP) if err := setWindowBounds(ctx, f.TestAPIConn(), w.ID, sb); err != nil { return errors.Wrap(err, "failed to set window initial bounds") } perfFn = func(ctx context.Context) error { // End bounds are just flipping the rectangle. // TODO(crbug.com/1067535): Subtract -1 to ensure drag-resize occurs for now. start := coords.NewPoint(sb.Left+sb.Width-1, sb.Top+sb.Height-1) end := coords.NewPoint(sb.Left+sb.Height, sb.Top+sb.Width) if err := mouse.Drag(f.TestAPIConn(), start, end, testDuration)(ctx); err != nil { return errors.Wrap(err, "failed to drag resize") } return nil } } else if invoc.scenario == TestTypeMoveOcclusion || invoc.scenario == TestTypeMoveOcclusionWithCrosWindow { wb, err := lacros.FindFirstBlankWindow(ctx, f.TestAPIConn()) if err != nil { return err } // Restore windows. if err := ash.SetWindowStateAndWait(ctx, f.TestAPIConn(), w.ID, ash.WindowStateNormal); err != nil { return errors.Wrap(err, "failed to restore non-blank window") } if err := ash.SetWindowStateAndWait(ctx, f.TestAPIConn(), wb.ID, ash.WindowStateNormal); err != nil { return errors.Wrap(err, "failed to restore blank window") } // Set content window to take up the left half of the screen in landscape, or top half in portrait. isp := info.WorkArea.Width < info.WorkArea.Height sbl := coords.NewRect(info.WorkArea.Left, info.WorkArea.Top, info.WorkArea.Width/2, info.WorkArea.Height) if isp { sbl = coords.NewRect(info.WorkArea.Left, info.WorkArea.Top, info.WorkArea.Width, info.WorkArea.Height/2) } sbl = sbl.WithInset(insetSlopDP, insetSlopDP) if err := setWindowBounds(ctx, f.TestAPIConn(), w.ID, sbl); err != nil { return errors.Wrap(err, "failed to set non-blank window initial bounds") } // Set the occluding window to take up the right side of the screen in landscape, or bottom half in portrait. sbr := sbl.WithOffset(sbl.Width, 0) if isp { sbr = sbl.WithOffset(0, sbl.Height) } if err := setWindowBounds(ctx, f.TestAPIConn(), wb.ID, sbr); err != nil { return errors.Wrap(err, "failed to set blank window initial bounds") } perfFn = func(ctx context.Context) error { // Drag from not occluding to completely occluding. start := coords.NewPoint(sbr.Left+dragMoveOffsetDP, sbr.Top+dragMoveOffsetDP) end := coords.NewPoint(sbl.Left+dragMoveOffsetDP, sbl.Top+dragMoveOffsetDP) if err := mouse.Drag(f.TestAPIConn(), start, end, testDuration)(ctx); err != nil { return errors.Wrap(err, "failed to drag move") } return nil } } else { // Maximize window. if err := ash.SetWindowStateAndWait(ctx, f.TestAPIConn(), w.ID, ash.WindowStateMaximized); err != nil { return errors.Wrap(err, "failed to maximize window") } } // Open the threedot menu if indicated. // TODO(edcourtney): Sometimes the accessibility tree isn't populated for lacros chrome, which causes this code to fail. if invoc.scenario == TestTypeThreeDot { clickFn := func(n *ui.Node) error { return n.LeftClick(ctx) } if invoc.crt == lacros.ChromeTypeLacros { clickFn = func(n *ui.Node) error { return leftClickLacros(ctx, f.TestAPIConn(), w.ID, n) } } if err := toggleThreeDotMenu(ctx, tconn, clickFn); err != nil { return errors.Wrap(err, "failed to open three dot menu") } defer toggleThreeDotMenu(ctx, tconn, clickFn) } // Sleep for three seconds after loading pages / setting up the environment. // Loading a page can cause some transient spikes in activity or similar // 'unstable' state. Unfortunately there's no clear condition to wait for like // there is before the test starts (CPU activity and temperature). Wait three // seconds before measuring performance stats to try to reduce the variance. // Three seconds seems to work for most of the pages we're using (checked via // manual inspection). testing.Sleep(ctx, 3*time.Second) return runHistogram(ctx, tconn, tracer, invoc, perfFn) } func runLacrosTest(ctx context.Context, f launcher.FixtValue, invoc *testInvocation) error { _, ltconn, l, cleanup, err := lacros.SetupLacrosTestWithPage(ctx, f, invoc.page.url) if err != nil { return errors.Wrap(err, "failed to setup cros-chrome test page") } defer cleanup(ctx) // Setup extra window for multi-window tests. if invoc.scenario == TestTypeMoveOcclusion { connBlank, err := l.NewConn(ctx, chrome.BlankURL, cdputil.WithNewWindow()) if err != nil { return errors.Wrap(err, "failed to open new tab") } defer connBlank.Close() defer connBlank.CloseTarget(ctx) } else if invoc.scenario == TestTypeMoveOcclusionWithCrosWindow { connBlank, err := f.Chrome().NewConn(ctx, chrome.BlankURL, cdputil.WithNewWindow()) if err != nil { return errors.Wrap(err, "failed to open new tab") } defer connBlank.Close() defer connBlank.CloseTarget(ctx) } return runTest(ctx, ltconn, f, l, invoc) } func runCrosTest(ctx context.Context, f launcher.FixtValue, invoc *testInvocation) error { _, cleanup, err := lacros.SetupCrosTestWithPage(ctx, f, invoc.page.url) if err != nil { return errors.Wrap(err, "failed to setup cros-chrome test page") } defer cleanup(ctx) // Setup extra window for multi-window tests. if invoc.scenario == TestTypeMoveOcclusion || invoc.scenario == TestTypeMoveOcclusionWithCrosWindow { connBlank, err := f.Chrome().NewConn(ctx, chrome.BlankURL, cdputil.WithNewWindow()) if err != nil { return errors.Wrap(err, "failed to open new tab") } defer connBlank.Close() defer connBlank.CloseTarget(ctx) } return runTest(ctx, f.TestAPIConn(), f, f.Chrome(), invoc) } // RunGpuCUJ runs a GpuCUJ test according to the given parameters. func RunGpuCUJ(ctx context.Context, f launcher.FixtValue, params TestParams, serverURL, traceDir string) ( retPV *perf.Values, retCleanup lacros.CleanupCallback, retErr error) { cleanup, err := lacros.SetupPerfTest(ctx, f.TestAPIConn(), "lacros.GpuCUJ") if err != nil { return nil, nil, errors.Wrap(err, "failed to setup GpuCUJ test") } defer func() { if retErr != nil { cleanup(ctx) } }() if params.Rot90 { infos, err := display.GetInfo(ctx, f.TestAPIConn()) if err != nil { return nil, nil, errors.Wrap(err, "failed to get display info") } if len(infos) != 1 { return nil, nil, errors.New("failed to find unique display") } rot := 90 if err := display.SetDisplayProperties(ctx, f.TestAPIConn(), infos[0].ID, display.DisplayProperties{Rotation: &rot}); err != nil { return nil, nil, errors.Wrap(err, "failed to rotate display") } // Restore the initial rotation. cleanup = lacros.CombineCleanup(ctx, cleanup, func(ctx context.Context) error { return display.SetDisplayProperties(ctx, f.TestAPIConn(), infos[0].ID, display.DisplayProperties{Rotation: &infos[0].Rotation}) }, "failed to restore the initial display rotation") } pv := perf.NewValues() m := metricsRecorder{buckets: make(map[statBucketKey][]float64), metricMap: make(map[string]metricInfo)} for _, page := range pageSet { if page.url[0] == '/' { page.url = serverURL + page.url } if err := runLacrosTest(ctx, f, &testInvocation{ pv: pv, scenario: params.TestType, page: page, crt: lacros.ChromeTypeLacros, metrics: &m, traceDir: traceDir, }); err != nil { return nil, nil, errors.Wrap(err, "failed to run lacros test") } if err := runCrosTest(ctx, f, &testInvocation{ pv: pv, scenario: params.TestType, page: page, crt: lacros.ChromeTypeChromeOS, metrics: &m, traceDir: traceDir, }); err != nil { return nil, nil, errors.Wrap(err, "failed to run cros test") } } if err := m.computeStatistics(ctx, pv); err != nil { return nil, nil, errors.Wrap(err, "could not compute derived statistics") } return pv, cleanup, nil }
src/chromiumos/tast/local/bundles/cros/lacros/gpucuj/gpu_cuj.go
0.665193
0.438364
gpu_cuj.go
starcoder
package parsed // Uninomial are details for names with cardinality 1. type Uninomial struct { // Value is the uninomial name. Value string `json:"uninomial"` // Rank of the uninomial in a combination name, for example // "Pereskia subg. <NAME> ex F.A.C.Weber, 1898" Rank string `json:"rank,omitempty"` // Cultivar is a value of a cultivar of a uninomial. Cultivar string `json:"cultivar,omitempty"` // Parent of a uninomial in a combination name. Parent string `json:"parent,omitempty"` // Authorship of the uninomial. Authorship *Authorship `json:"authorship,omitempty"` } // Species are details for binomial names with cardinality 2. type Species struct { // Genus is a value of a genus of a binomial. Genus string `json:"genus"` // Subgenus is a value of subgenus of binomial. Subgenus string `json:"subgenus,omitempty"` // Species is a value of a specific epithet. Species string `json:"species"` // Cultivar is a value of a cultivar of a binomial. Cultivar string `json:"cultivar,omitempty"` // Authorship of the binomial. Authorship *Authorship `json:"authorship,omitempty"` } // Infraspecies are details for names with cardinality higher than 2. type Infraspecies struct { // Species are details for the binomial part of a name. Species // Infraspecies is a slice of infraspecific epithets of a name. Infraspecies []InfraspeciesElem `json:"infraspecies,omitempty"` } // InfraspeciesElem are details for an infraspecific epithet of an // Infraspecies name. type InfraspeciesElem struct { // Value of an infraspecific epithet. Value string `json:"value"` // Rank of the infraspecific epithet. Rank string `json:"rank,omitempty"` // Authorship of the infraspecific epithet. Authorship *Authorship `json:"authorship,omitempty"` } // Comparison are details for a surrogate comparison name. type Comparison struct { // Genus is the genus of a name. Genus string `json:"genus"` // Species is a specific epithet of a name. Species string `json:"species,omitempty"` // Cultivar is a value of a cultivar of a binomial. Cultivar string `json:"cultivar,omitempty"` // SpeciesAuthorship the authorship of Species. SpeciesAuthorship *Authorship `json:"authorship,omitempty"` // CompMarker, usually "cf.". CompMarker string `json:"comparisonMarker"` } // Approximation are details for a surrogate approximation name. type Approximation struct { // Genus is the genus of a name. Genus string `json:"genus"` // Species is a specific epithet of a name. Species string `json:"species,omitempty"` // Cultivar is a value of a cultivar of a binomial. Cultivar string `json:"cultivar,omitempty"` // SpeciesAuthorship the authorship of Species. SpeciesAuthorship *Authorship `json:"authorship,omitempty"` // ApproxMarker describes what kind of approximation it is (sp., spp. etc.). ApproxMarker string `json:"approximationMarker,omitempty"` // Part of a name after ApproxMarker. Ignored string `json:"ignored,omitempty"` } // DetailsHybridFormula are details for a hybrid formula names. type DetailsHybridFormula struct { HybridFormula []Details `json:"hybridFormula"` } // DetailsGraftChimeraFormula are details for a graft-chimera formula names. type DetailsGraftChimeraFormula struct { GraftChimeraFormula []Details `json:"graftChimeraFormula"` } // isDetails implements Details interface. func (DetailsHybridFormula) isDetails() {} // isDetails implements Details interface. func (DetailsGraftChimeraFormula) isDetails() {} // DetailsUninomial are Uninomial details. type DetailsUninomial struct { // Uninomial details. Uninomial Uninomial `json:"uninomial"` } // isDetails implements Details interface. func (DetailsUninomial) isDetails() {} // DetailsSpecies are binomial details. type DetailsSpecies struct { // Species is details for binomial names. Species Species `json:"species"` } // isDetails implements Details interface. func (DetailsSpecies) isDetails() {} // DetailsInfraspecies are multinomial details. type DetailsInfraspecies struct { // Infraspecies details. Infraspecies Infraspecies `json:"infraspecies"` } // isDetails implements Details interface. func (DetailsInfraspecies) isDetails() {} // DetailsComparison are details for comparison surrogate names. type DetailsComparison struct { // Comparison details. Comparison Comparison `json:"comparison"` } // isDetails implements Details interface. func (DetailsComparison) isDetails() {} // DetailsApproximation are details for approximation surrogate names. type DetailsApproximation struct { // Approximation details. Approximation Approximation `json:"approximation"` } // isDetails implements Details interface. func (DetailsApproximation) isDetails() {}
ent/parsed/details.go
0.819677
0.448487
details.go
starcoder
package repeatgenome import ( "unsafe" ) /* Converts a TextSeq to the more memory-efficient Seq type. Upper- and lower-case base bytes are currently supported, but stable code should immediately convert to lower-case. The logic works and is sane, but could be altered in the future for brevity and efficiency. */ func GetSeq(textSeq []byte) Seq { numBytes := ceilDiv(len(textSeq), 4) seq := Seq{ Bytes: make([]byte, numBytes, numBytes), Len: uint64(len(textSeq)), } /* Determines how much to shift the current byte of interest. Starts at 6, wraps around to 254, which mods to 0. Therefore loops 6 -> 4 -> 2 -> 0 -> ... See the last line of the for-loop. */ var shift uint8 = 6 for i := 0; i < len(textSeq); i++ { switch textSeq[i] { case 'a': // already zero break case 'c': seq.Bytes[i/4] |= 1 << shift break case 'g': seq.Bytes[i/4] |= 2 << shift break case 't': seq.Bytes[i/4] |= 3 << shift break case 'A': // already zero break case 'C': seq.Bytes[i/4] |= 1 << shift break case 'G': seq.Bytes[i/4] |= 2 << shift break case 'T': seq.Bytes[i/4] |= 3 << shift break default: panic("TextSeq.GetSeq(): byte other than 'a', 'c', 'g', or 't' encountered") } shift = (shift - 2) % 8 } return seq } /* Return the subsequence of the supplied Seq from a (inclusive) to b (exclusive), like a slice. */ func (seq Seq) Subseq(a, b uint64) Seq { numBytes := ceilDiv_U64(b-a, 4) subseq := Seq{ Bytes: make([]byte, numBytes, numBytes), Len: b - a, } /* How much to left-shift the byte currently being altered. For more details, see the identical usage in TextSeq.Seq() */ var shift uint8 = 6 var i uint64 for i = 0; i < subseq.Len; i++ { subseq.Bytes[i/4] |= seq.GetBase(i+a) << shift } shift = (shift - 2) % 8 return subseq } // Return the i-th byte of the Seq (zero-indexed). func (seq Seq) GetBase(i uint64) uint8 { thisByte := seq.Bytes[i/4] return thisByte >> (6 - 2*(i%4)) } /* A more declarative and modifiable accessor function. While it would almost certainly be inlined, this is such a performance-critical operation that this function isn't currently used. */ func (kmer Kmer) Int() uint64 { return *(*uint64)(unsafe.Pointer(&kmer)) } /* A more declarative and modifiable accessor function. While it would almost certainly be inlined, this is such a performance-critical operation that this function isn't currently used. */ func (kmer Kmer) ClassID() ClassID { return *(*ClassID)(unsafe.Pointer(&kmer[8])) } func (kmer *Kmer) SetInt(kmerInt uint64) { *(*uint64)(unsafe.Pointer(kmer)) = kmerInt } func (kmer *Kmer) SetClassID(classID ClassID) { *(*ClassID)(unsafe.Pointer(&kmer[8])) = classID }
repeatgenome/seq-rg.go
0.672117
0.449695
seq-rg.go
starcoder
package imagediff import ( "errors" "image" "image/color" ) // SmartImageComparer uses perceptual color difference metrics to determine if pixels look the same. // See http://www.progmat.uaem.mx:8080/artVol2Num2/Articulo3Vol2Num2.pdf type SmartImageComparer struct { ignoreColor *color.NRGBA useignoreColor bool DiffColor color.NRGBA threshold float32 } // NewSmartImageComparer constructs a SmartImageComparer. func NewSmartImageComparer() *SmartImageComparer { return &SmartImageComparer{ threshold: 0.1, DiffColor: color.NRGBA{R: 255, G: 0, B: 0, A: 255}, } } //SetIgnoreColor tells the comparer to ignore any pixel of the specified color in either images. func (comparer *SmartImageComparer) SetIgnoreColor(c *color.NRGBA) { comparer.ignoreColor = c comparer.useignoreColor = true } //SetThreshold tells the comparer how different a pixel must be before its significant. func (comparer *SmartImageComparer) SetThreshold(t float32) { comparer.threshold = t } //CompareImages compares 2 images, returns the number of different pixels and an output image that highlights the differences. func (comparer SmartImageComparer) CompareImages(img1 image.Image, img2 image.Image) (int, *image.NRGBA, error) { img1Bounds := img1.Bounds() img2Bounds := img2.Bounds() XBoundsDifferent := img1Bounds.Max.X-img1Bounds.Min.X != img2Bounds.Max.X-img2Bounds.Min.X YBoundsDifferent := img1Bounds.Max.Y-img1Bounds.Min.Y != img2Bounds.Max.Y-img2Bounds.Min.Y if XBoundsDifferent || YBoundsDifferent { return 0, nil, errors.New("Images not same size") } //Determine if each pixel is same or different numDifferentPixel := 0 diffImage := image.NewNRGBA(img1Bounds) // maximum acceptable square distance between two colors; // 35215 is the maximum possible value for the YIQ difference metric maxDifference := 35215 * comparer.threshold * comparer.threshold for y := img1Bounds.Min.Y; y < img1Bounds.Max.Y; y++ { for x := img1Bounds.Min.X; x < img1Bounds.Max.X; x++ { Pixel1 := img1.At(x, y) Pixel2 := img2.At(x, y) P1NRGBA := color2nrgba(Pixel1) P2NRGBA := color2nrgba(Pixel2) if comparer.useignoreColor && isIgnorePixel(P1NRGBA.R, P1NRGBA.G, P1NRGBA.B, P1NRGBA.A, P2NRGBA.R, P2NRGBA.G, P2NRGBA.B, P2NRGBA.A, comparer.ignoreColor) { //These pixels should be ignored diffImage.SetNRGBA(x, y, niceOutputPixel(*comparer.ignoreColor)) continue } difference := perceptualColorDifference(&P1NRGBA, &P2NRGBA) if difference > maxDifference { //These 2 pixels are not significantly different. numDifferentPixel++ diffImage.SetNRGBA(x, y, comparer.DiffColor) } else { //These 2 pixels are not different enough. diffImage.SetNRGBA(x, y, niceOutputPixel(P1NRGBA)) } } } return numDifferentPixel, diffImage, nil } // calculate color difference according to the paper "Measuring perceived color difference // using YIQ NTSC transmission color space in mobile applications" by <NAME> and <NAME> func perceptualColorDifference(Pixel1 *color.NRGBA, Pixel2 *color.NRGBA) float32 { a1 := float32(Pixel1.A) / 255 a2 := float32(Pixel2.A) / 255 r1 := blend(float32(Pixel1.R), a1) g1 := blend(float32(Pixel1.G), a1) b1 := blend(float32(Pixel1.B), a1) r2 := blend(float32(Pixel2.R), a2) g2 := blend(float32(Pixel2.G), a2) b2 := blend(float32(Pixel2.B), a2) y := rgb2y(r1, g1, b1) - rgb2y(r2, g2, b2) i := rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2) q := rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2) return 0.5053*y*y + 0.299*i*i + 0.1957*q*q } func rgb2y(r, g, b float32) float32 { return r*0.29889531 + g*0.58662247 + b*0.11448223 } func rgb2i(r, g, b float32) float32 { return r*0.59597799 - g*0.27417610 - b*0.32180189 } func rgb2q(r, g, b float32) float32 { return r*0.21147017 - g*0.52261711 + b*0.31114694 } // blend semi-transparent color with white func blend(c float32, a float32) float32 { return 255 + float32(c-255)*a } func grayPixel(Pixel *color.NRGBA) float32 { a := float32(Pixel.A) / 255 r := blend(float32(Pixel.R), a) g := blend(float32(Pixel.G), a) b := blend(float32(Pixel.B), a) return rgb2y(r, g, b) }
imagediff/SmartImageComparer.go
0.877405
0.61341
SmartImageComparer.go
starcoder
package easycel import ( "fmt" "reflect" "github.com/google/cel-go/checker/decls" "github.com/google/cel-go/common/types" "github.com/google/cel-go/common/types/ref" exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" ) type adapter struct { adapter ref.TypeAdapter } func newAdapter(a ref.TypeAdapter) *adapter { return &adapter{ adapter: a, } } func (t *adapter) TypeToPbType(typ reflect.Type) (*exprpb.Type, error) { switch typ.Kind() { case reflect.Ptr: return t.TypeToPbType(typ.Elem()) case reflect.Bool: return decls.Bool, nil case reflect.Float64, reflect.Float32: return decls.Double, nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return decls.Int, nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return decls.Uint, nil case reflect.String: return decls.String, nil case reflect.Slice: if typ.Elem().Kind() == reflect.Uint8 { return decls.Bytes, nil } fallthrough case reflect.Array: elem, err := t.TypeToPbType(typ.Elem()) if err != nil { return nil, err } return decls.NewListType(elem), nil case reflect.Map: key, err := t.TypeToPbType(typ.Elem()) if err != nil { return nil, err } val, err := t.TypeToPbType(typ.Elem()) if err != nil { return nil, err } return decls.NewMapType(key, val), nil case reflect.Struct, reflect.Interface: typeName := getUniqTypeName("object", typ) return decls.NewObjectType(typeName), nil } return nil, fmt.Errorf("unsupported type conversion kind %s", typ.Kind()) } func (t *adapter) ValueToCelValue(val reflect.Value) (ref.Val, error) { v, ok := val.Interface().(ref.Val) if ok { return v, nil } switch val.Kind() { case reflect.Bool: return types.Bool(val.Bool()), nil case reflect.Float64, reflect.Float32: return types.Double(val.Float()), nil case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return types.Int(val.Int()), nil case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return types.Uint(val.Uint()), nil case reflect.String: return types.String(val.String()), nil case reflect.Slice: if val.Type().Elem().Kind() == reflect.Uint8 { return types.Bytes(val.Bytes()), nil } fallthrough case reflect.Array: sz := val.Len() elts := make([]ref.Val, 0, sz) for i := 0; i < sz; i++ { v, err := t.ValueToCelValue(val.Index(i)) if err != nil { return nil, err } elts = append(elts, v) } return types.NewRefValList(t.adapter, elts), nil case reflect.Map: entries := map[ref.Val]ref.Val{} iter := val.MapRange() for iter.Next() { k := iter.Key() v := iter.Value() kv, err := t.ValueToCelValue(k) if err != nil { return nil, err } vv, err := t.ValueToCelValue(v) if err != nil { return nil, err } entries[kv] = vv } return types.NewDynamicMap(t.adapter, entries), nil } return nil, fmt.Errorf("unsupported type conversion kind %s", val.Kind()) }
adapter.go
0.547706
0.453685
adapter.go
starcoder
package main import ( "fmt" ) func main() { /* Decisions and Loops are some of the most basic bread and butter of not only a Go program, but programs in general. Without decisions and loops, programs would not be of much computational use (see Turing machines and their impact - https://en.wikipedia.org/wiki/Turing_machine). Decisions in go are done using conditional statements, and is something we all use in our daily lives. It's as simple as making decisions based on conditions - if it's hot outside, where a T-Shirt; if I'm hungry, I'll eat. Programs do the same thing, based on conditions you've set. The main two ways to achieve decisions are through if/else statements, and switch statements. Looping is the process of iterating multiple times based on a set condition, to the effect of manipulating other values or conditions. Looping in go is done exclusively through 'for' loops - there are no while / do while loops in go. */ // first, let's set a boolean value a := false /* now, let's introduce an if/else statement if statements do not need parentheses in Go, unlike some languages like C or Java. Also, else if / else statements MUST start after the preceding closing brace }, not doing so will give a compilation error. */ if a == true { fmt.Println("a is true") } else { fmt.Println("a is false") } // The above snippet can also be shortened to this (only for boolean values): if a { fmt.Println("a is true") } else { fmt.Println("a is false") } /* Switch statements are also a form of decision making, and are particularly useful when a target condition can be multiple values depending on other conditions. Each of those conditions you'd like to test for are called 'cases', and can be chained one after another to cover the full range of values you want to test for. You can also set a default case, which will be executed when none of the previous cases are met. */ // initialize a value b := 3 // now, the switch statement switch b { case 1: fmt.Println("b is 1") case 2: fmt.Println("b is 2") case 3: fmt.Println("b is 3") default: fmt.Println("b is something else") } /* Now, let's try looping. Loops are identified with a 'for' statement. Similar to C and Java syntax, a for loop requires 3 different arguments, semicolon separated: - iterator variable - condition for loop end - iterator increment / decrement pattern The below loop will initialize a variable 'i' to start at 0, set its break condition to be when i = 5 (ie the loop will keep going while i is less than 5), and that i will increment by one for every iteration of the loop. Iterators in a for loop can also decrement (like i--), and even skip by a multiple number. For example, i += 2 would increase i by 2 every iteration of the loop instead of 1. for loops, like if statements, do not necessarily need enclosing parentheses. */ // This loop will print "Hello!" 5 times for i := 0; i < 5; i++ { fmt.Println("Hello!") } /* To better demonstrate a switch statement's usage, let's now combine our knowledge of loops and switch statements: */ // iterate from 1 to 4 for i := 1; i <= 4; i++ { // set b equal to i b = i switch b { case 1: fmt.Println("b is 1") case 2: fmt.Println("b is 2") case 3: fmt.Println("b is 3") default: fmt.Println("b is something else") } } /* Now, we can start to see the use of the switch statement. b is changing its value on every iteration of the loop, and our switch statement can now pick up (some) of the different values b is being set to. */ }
decisions-loops/dl.go
0.635562
0.545165
dl.go
starcoder
package ipmigo // Event/Reading Type (Table 42-2) type EventType uint8 func (e EventType) IsUnspecified() bool { return e == 0x00 } func (e EventType) IsThreshold() bool { return e == 0x01 } func (e EventType) IsGeneric() bool { return e >= 0x02 && e <= 0x0c } func (e EventType) IsSensorSpecific() bool { return e == 0x6f } func (e EventType) IsOEM() bool { return e >= 0x70 && e <= 0x7f } // Sensor generic event description (Table 42-2) var sensorGenericEventDesc = map[uint32]string{ // Event Type, Offset (0x01 << 8) | 0x00: "Lower Non-critical - going low", (0x01 << 8) | 0x01: "Lower Non-critical - going high", (0x01 << 8) | 0x02: "Lower Critical - going low", (0x01 << 8) | 0x03: "Lower Critical - going high", (0x01 << 8) | 0x04: "Lower Non-recoverable - going low", (0x01 << 8) | 0x05: "Lower Non-recoverable - going high", (0x01 << 8) | 0x06: "Upper Non-critical - going low", (0x01 << 8) | 0x07: "Upper Non-critical - going high", (0x01 << 8) | 0x08: "Upper Critical - going low", (0x01 << 8) | 0x09: "Upper Critical - going high", (0x01 << 8) | 0x0a: "Upper Non-recoverable - going low", (0x01 << 8) | 0x0b: "Upper Non-recoverable - going high", (0x02 << 8) | 0x00: "Transition to Idle", (0x02 << 8) | 0x01: "Transition to Active", (0x02 << 8) | 0x02: "Transition to Busy", (0x03 << 8) | 0x00: "State Deasserted", (0x03 << 8) | 0x01: "State Asserted", (0x04 << 8) | 0x00: "Predictive Failure deasserted", (0x04 << 8) | 0x01: "Predictive Failure asserted", (0x05 << 8) | 0x00: "Limit Not Exceeded", (0x05 << 8) | 0x01: "Limit Exceeded", (0x06 << 8) | 0x00: "Performance Met", (0x06 << 8) | 0x01: "Performance Lags", (0x07 << 8) | 0x00: "transition to OK", (0x07 << 8) | 0x01: "transition to Non-Critical from OK", (0x07 << 8) | 0x02: "transition to Critical from less severe", (0x07 << 8) | 0x03: "transition to Non-recoverable from less severe", (0x07 << 8) | 0x04: "transition to Non-Critical from more severe", (0x07 << 8) | 0x05: "transition to Critical from Non-recoverable", (0x07 << 8) | 0x06: "transition to Non-recoverable", (0x07 << 8) | 0x07: "Monitor", (0x07 << 8) | 0x08: "Informational", (0x08 << 8) | 0x00: "Device Removed/Device Absent", (0x08 << 8) | 0x01: "Device Inserted/Device Present", (0x09 << 8) | 0x00: "Device Disabled", (0x09 << 8) | 0x01: "Device Enabled", (0x0a << 8) | 0x00: "transition to Running", (0x0a << 8) | 0x01: "transition to In Test", (0x0a << 8) | 0x02: "transition to Power Off", (0x0a << 8) | 0x03: "transition to On Line", (0x0a << 8) | 0x04: "transition to Off Line", (0x0a << 8) | 0x05: "transition to Off Duty", (0x0a << 8) | 0x06: "transition to Degraded", (0x0a << 8) | 0x07: "transition to Power Save", (0x0a << 8) | 0x08: "install Error", (0x0b << 8) | 0x00: "Fully Redundant (formerly \"Redundancy Regained\")", (0x0b << 8) | 0x01: "Redundancy Lost", (0x0b << 8) | 0x02: "Redundancy Degraded", (0x0b << 8) | 0x03: "Non-redundant:Sufficient Resources from Redundant", (0x0b << 8) | 0x04: "Non-redundant:Sufficient Resources from Insufficient Resources", (0x0b << 8) | 0x05: "Non-redundant:Insufficient Resources", (0x0b << 8) | 0x06: "Redundancy Degraded from Fully Redundant", (0x0b << 8) | 0x07: "Redundancy Degraded from Non-redundant", (0x0c << 8) | 0x00: "D0 Power State", (0x0c << 8) | 0x01: "D1 Power State", (0x0c << 8) | 0x02: "D2 Power State", (0x0c << 8) | 0x03: "D3 Power State", } // Sensor specific event description (Table 42-3) var sensorSpecificEventDesc = map[uint32]string{ // Sensor Type, Offset, Event Data2, Event Data3 (0x05 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "General Chassis Intrusion", (0x05 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Drive Bay intrusion", (0x05 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "I/O Card area intrusion", (0x05 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Processor area intrusion", (0x05 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "LAN Leash Lost (system is unplugged from LAN)", (0x05 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "Unauthorized dock", (0x05 << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "FAN area intrusion (supports detection of hot plug fan tampering)", (0x06 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Secure Mode (Front Panel Lockout) Violation attempt", (0x06 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Pre-boot Password Violation - user password", (0x06 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Pre-boot Password Violation attempt - setup password", (0x06 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Pre-boot Password Violation - network boot password", (0x06 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "Other pre-boot Password Violation", (0x06 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "Out-of-band Access Password Violation", (0x07 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "IERR", (0x07 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Thermal Trip", (0x07 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "FRB1/BIST failure", (0x07 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "FRB2/Hang in POST failure", (0x07 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "FRB3/Processor Startup/Initialization failure", (0x07 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "Configuration Error", (0x07 << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "SM BIOS `Uncorrectable CPU-complex Error'", (0x07 << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "Processor Presence detected", (0x07 << 24) | (0x08 << 16) | (0xff << 8) | 0xff: "Processor disabled", (0x07 << 24) | (0x09 << 16) | (0xff << 8) | 0xff: "Terminator Presence Detected", (0x07 << 24) | (0x0a << 16) | (0xff << 8) | 0xff: "Processor Automatically Throttled", (0x07 << 24) | (0x0b << 16) | (0xff << 8) | 0xff: "Machine Check Exception (Uncorrectable)", (0x07 << 24) | (0x0c << 16) | (0xff << 8) | 0xff: "Correctable Machine Check Error", (0x08 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Presence detected", (0x08 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Power Supply Failure detected", (0x08 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Predictive Failure", (0x08 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Power Supply input lost (AC/DC)", (0x08 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "Power Supply input lost or out-of-range", (0x08 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "Power Supply input out-of-range, but present", (0x08 << 24) | (0x06 << 16) | (0xff << 8) | 0x00: "Configuration error : Vendor mismatch", (0x08 << 24) | (0x06 << 16) | (0xff << 8) | 0x01: "Configuration error : Revision mismatch", (0x08 << 24) | (0x06 << 16) | (0xff << 8) | 0x02: "Configuration error : Processor missing", (0x08 << 24) | (0x06 << 16) | (0xff << 8) | 0x03: "Configuration error : Power Supply rating mismatch", (0x08 << 24) | (0x06 << 16) | (0xff << 8) | 0x04: "Configuration error : Voltage rating mismatch", (0x08 << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "Configuration error", (0x08 << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "Power Supply Inactive (in standby state)", (0x09 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Power Off / Power Down", (0x09 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Power Cycle", (0x09 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "240VA Power Down", (0x09 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Interlock Power Down", (0x09 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "AC lost / Power input lost", (0x09 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "Soft Power Control Failure", (0x09 << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "Power Unit Failure detected", (0x09 << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "Predictive Failure", (0x0c << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Correctable ECC / other correctable memory error", (0x0c << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Uncorrectable ECC / other uncorrectable memory error", (0x0c << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Parity", (0x0c << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Memory Scrub Failed (stuck bit)", (0x0c << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "Memory Device Disabled", (0x0c << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "Correctable ECC / other correctable memory error logging limit reached", (0x0c << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "Presence detected", (0x0c << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "Configuration error", (0x0c << 24) | (0x08 << 16) | (0xff << 8) | 0xff: "Spare", (0x0c << 24) | (0x09 << 16) | (0xff << 8) | 0xff: "Memory Automatically Throttled", (0x0c << 24) | (0x0a << 16) | (0xff << 8) | 0xff: "Critical Overtemperature", (0x0d << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Drive Presence", (0x0d << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Drive Fault", (0x0d << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Predictive Failure", (0x0d << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Hot Spare", (0x0d << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "Consistency Check / Parity Check in progress", (0x0d << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "In Critical Array", (0x0d << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "In Failed Array", (0x0d << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "Rebuild/Remap in progress", (0x0d << 24) | (0x08 << 16) | (0xff << 8) | 0xff: "Rebuild/Remap Aborted (was not completed normally)", (0x0f << 24) | (0x00 << 16) | (0x00 << 8) | 0xff: "System Firmware Error : Unspecified", (0x0f << 24) | (0x00 << 16) | (0x01 << 8) | 0xff: "System Firmware Error : No system memory is physically installed in the system", (0x0f << 24) | (0x00 << 16) | (0x02 << 8) | 0xff: "System Firmware Error : No usable system memory", (0x0f << 24) | (0x00 << 16) | (0x03 << 8) | 0xff: "System Firmware Error : Unrecoverable hard-disk/ATAPI/IDE device failure", (0x0f << 24) | (0x00 << 16) | (0x04 << 8) | 0xff: "System Firmware Error : Unrecoverable system-board failure", (0x0f << 24) | (0x00 << 16) | (0x05 << 8) | 0xff: "System Firmware Error : Unrecoverable diskette subsystem failure", (0x0f << 24) | (0x00 << 16) | (0x06 << 8) | 0xff: "System Firmware Error : Unrecoverable hard-disk controller failure", (0x0f << 24) | (0x00 << 16) | (0x07 << 8) | 0xff: "System Firmware Error : Unrecoverable PS/2 or USB keyboard failure", (0x0f << 24) | (0x00 << 16) | (0x08 << 8) | 0xff: "System Firmware Error : Removable boot media not found", (0x0f << 24) | (0x00 << 16) | (0x09 << 8) | 0xff: "System Firmware Error : Unrecoverable video controller failure", (0x0f << 24) | (0x00 << 16) | (0x0a << 8) | 0xff: "System Firmware Error : No video device detected", (0x0f << 24) | (0x00 << 16) | (0x0b << 8) | 0xff: "System Firmware Error : Firmware (BIOS) ROM corruption detected", (0x0f << 24) | (0x00 << 16) | (0x0c << 8) | 0xff: "System Firmware Error : CPU voltage mismatch", (0x0f << 24) | (0x00 << 16) | (0x0d << 8) | 0xff: "System Firmware Error : CPU speed matching failure", (0x0f << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "System Firmware Error", (0x0f << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "System Firmware Hang", (0x0f << 24) | (0x02 << 16) | (0x00 << 8) | 0xff: "System Firmware Progress : Unspecified", (0x0f << 24) | (0x02 << 16) | (0x01 << 8) | 0xff: "System Firmware Progress : Memory initialization", (0x0f << 24) | (0x02 << 16) | (0x02 << 8) | 0xff: "System Firmware Progress : Hard-disk initialization", (0x0f << 24) | (0x02 << 16) | (0x03 << 8) | 0xff: "System Firmware Progress : Secondary processor(s) initialization", (0x0f << 24) | (0x02 << 16) | (0x04 << 8) | 0xff: "System Firmware Progress : User authentication", (0x0f << 24) | (0x02 << 16) | (0x05 << 8) | 0xff: "System Firmware Progress : User-initiated system setup", (0x0f << 24) | (0x02 << 16) | (0x06 << 8) | 0xff: "System Firmware Progress : USB resource configuration", (0x0f << 24) | (0x02 << 16) | (0x07 << 8) | 0xff: "System Firmware Progress : PCI resource configuration", (0x0f << 24) | (0x02 << 16) | (0x08 << 8) | 0xff: "System Firmware Progress : Option ROM initialization", (0x0f << 24) | (0x02 << 16) | (0x09 << 8) | 0xff: "System Firmware Progress : Video initialization", (0x0f << 24) | (0x02 << 16) | (0x0a << 8) | 0xff: "System Firmware Progress : Cache initialization", (0x0f << 24) | (0x02 << 16) | (0x0b << 8) | 0xff: "System Firmware Progress : SM Bus initialization", (0x0f << 24) | (0x02 << 16) | (0x0c << 8) | 0xff: "System Firmware Progress : Keyboard controller initialization", (0x0f << 24) | (0x02 << 16) | (0x0d << 8) | 0xff: "System Firmware Progress : Embedded controller/management controller initialization", (0x0f << 24) | (0x02 << 16) | (0x0e << 8) | 0xff: "System Firmware Progress : Docking station attachment", (0x0f << 24) | (0x02 << 16) | (0x0f << 8) | 0xff: "System Firmware Progress : Enabling docking station", (0x0f << 24) | (0x02 << 16) | (0x10 << 8) | 0xff: "System Firmware Progress : Docking station ejection", (0x0f << 24) | (0x02 << 16) | (0x11 << 8) | 0xff: "System Firmware Progress : Disabling docking station", (0x0f << 24) | (0x02 << 16) | (0x12 << 8) | 0xff: "System Firmware Progress : Calling operating system wake-up vector", (0x0f << 24) | (0x02 << 16) | (0x13 << 8) | 0xff: "System Firmware Progress : Starting operating system boot process", (0x0f << 24) | (0x02 << 16) | (0x14 << 8) | 0xff: "System Firmware Progress : Baseboard or motherboard initialization", (0x0f << 24) | (0x02 << 16) | (0x15 << 8) | 0xff: "System Firmware Progress : reserved", (0x0f << 24) | (0x02 << 16) | (0x16 << 8) | 0xff: "System Firmware Progress : Floppy initialization", (0x0f << 24) | (0x02 << 16) | (0x17 << 8) | 0xff: "System Firmware Progress : Keyboard test", (0x0f << 24) | (0x02 << 16) | (0x18 << 8) | 0xff: "System Firmware Progress : Pointing device test", (0x0f << 24) | (0x02 << 16) | (0x19 << 8) | 0xff: "System Firmware Progress : Primary processor initialization", (0x0f << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "System Firmware Progress", (0x10 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Correctable Memory Error Logging Disabled", (0x10 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Event 'Type' Logging Disabled", (0x10 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Log Area Reset/Cleared", (0x10 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "All Event Logging Disabled", (0x10 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "SEL Full", (0x10 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "SEL Almost Full", (0x10 << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "Correctable Machine Check Error Logging Disabled", (0x11 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "BIOS Watchdog Reset", (0x11 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "OS Watchdog Reset", (0x11 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "OS Watchdog Shut Down", (0x11 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "OS Watchdog Power Down", (0x11 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "OS Watchdog Power Cycle", (0x11 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "OS Watchdog NMI / Diagnostic Interrupt", (0x11 << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "OS Watchdog Expired, status only", (0x11 << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "OS Watchdog pre-timeout Interrupt, non-NMI", (0x12 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "System Reconfigured", (0x12 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "OEM System Boot Event", (0x12 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Undetermined system hardware failure", (0x12 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Entry added to Auxiliary Log", (0x12 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "PEF Action", (0x12 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "Timestamp Clock Synch", (0x13 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Front Panel NMI / Diagnostic Interrupt", (0x13 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Bus Timeout", (0x13 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "I/O channel check NMI", (0x13 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Software NMI", (0x13 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "PCI PERR", (0x13 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "PCI SERR", (0x13 << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "EISA Fail Safe Timeout", (0x13 << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "Bus Correctable Error", (0x13 << 24) | (0x08 << 16) | (0xff << 8) | 0xff: "Bus Uncorrectable Error", (0x13 << 24) | (0x09 << 16) | (0xff << 8) | 0xff: "Fatal NMI", (0x13 << 24) | (0x0a << 16) | (0xff << 8) | 0xff: "Bus Fatal Error", (0x13 << 24) | (0x0b << 16) | (0xff << 8) | 0xff: "Bus Degraded", (0x14 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Power Button pressed", (0x14 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Sleep Button pressed", (0x14 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Reset Button pressed", (0x14 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "FRU latch open", (0x14 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "FRU service request button", (0x19 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Soft Power Control Failure", (0x19 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Thermal Trip", (0x1b << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Cable/Interconnect is connected", (0x1b << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Configuration Error", (0x1d << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Initiated by power up", (0x1d << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Initiated by hard reset", (0x1d << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Initiated by warm reset", (0x1d << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "User requested PXE boot", (0x1d << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "Automatic boot to diagnostic", (0x1d << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "OS / run-time software initiated hard reset", (0x1d << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "OS / run-time software initiated warm reset", (0x1d << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "System Restart", (0x1e << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "No bootable media", (0x1e << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Non-bootable diskette left in drive", (0x1e << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "PXE Server not found", (0x1e << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Invalid boot sector", (0x1e << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "Timeout waiting for user selection of boot source", (0x1f << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "A: boot completed", (0x1f << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "C: boot completed", (0x1f << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "PXE boot completed", (0x1f << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Diagnostic boot completed", (0x1f << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "CD-ROM boot completed", (0x1f << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "ROM boot completed", (0x1f << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "boot completed - boot device not specified", (0x1f << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "Base OS/Hypervisor Installation started", (0x1f << 24) | (0x08 << 16) | (0xff << 8) | 0xff: "Base OS/Hypervisor Installation completed", (0x1f << 24) | (0x09 << 16) | (0xff << 8) | 0xff: "Base OS/Hypervisor Installation aborted", (0x1f << 24) | (0x0a << 16) | (0xff << 8) | 0xff: "Base OS/Hypervisor Installation failed", (0x20 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Critical stop during OS load / initialization", (0x20 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Run-time Critical Stop", (0x20 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "OS Graceful Stop", (0x20 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "OS Graceful Shutdown", (0x20 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "Soft Shutdown initiated by PEF", (0x20 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "Agent Not Responding", (0x21 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Fault Status asserted", (0x21 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Identify Status asserted", (0x21 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Slot/Connector Device installed/attached", (0x21 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Slot/Connector Ready for Device Installation", (0x21 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "Slot/Connector Ready for Device Removal", (0x21 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "Slot Power is Off", (0x21 << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "Slot/Connector Device Removal Request", (0x21 << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "Interlock asserted", (0x21 << 24) | (0x08 << 16) | (0xff << 8) | 0xff: "Slot is Disabled", (0x21 << 24) | (0x09 << 16) | (0xff << 8) | 0xff: "Slot holds spare device", (0x22 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "S0/G0 \"working\"", (0x22 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "S1 \"sleeping with system h/w & processor context maintained\"", (0x22 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "S2 \"sleeping, processor context lost\"", (0x22 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "S3 \"sleeping, processor & h/w context lost, memory retained\"", (0x22 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "S4 \"non-volatile sleep / suspend-to disk\"", (0x22 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "S5/G2 \"soft-off\"", (0x22 << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "S4/S5 soft-off, particular S4 / S5 state cannot be determined", (0x22 << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "G3/Mechanical Off", (0x22 << 24) | (0x08 << 16) | (0xff << 8) | 0xff: "Sleeping in an S1, S2, or S3 states", (0x22 << 24) | (0x09 << 16) | (0xff << 8) | 0xff: "G1 sleeping", (0x22 << 24) | (0x0a << 16) | (0xff << 8) | 0xff: "S5 entered by override", (0x22 << 24) | (0x0b << 16) | (0xff << 8) | 0xff: "Legacy ON state", (0x22 << 24) | (0x0c << 16) | (0xff << 8) | 0xff: "Legacy OFF state", (0x22 << 24) | (0x0e << 16) | (0xff << 8) | 0xff: "Unknown", (0x23 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Timer expired, status only", (0x23 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Hard Reset", (0x23 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Power Down", (0x23 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Power Cycle", (0x23 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "reserved", (0x23 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "reserved", (0x23 << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "reserved", (0x23 << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "reserved", (0x23 << 24) | (0x08 << 16) | (0xff << 8) | 0xff: "Timer interrupt", (0x24 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "platform generated page", (0x24 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "platform generated LAN alert", (0x24 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Platform Event Trap generated", (0x24 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "platform generated SNMP trap, OEM format", (0x25 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Entity Present", (0x25 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Entity Absent", (0x25 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Entity Disabled", (0x27 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "LAN Heartbeat Lost", (0x27 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "LAN Heartbeat", (0x28 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "sensor access degraded or unavailable", (0x28 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "controller access degraded or unavailable", (0x28 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "management controller off-line", (0x28 << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "management controller unavailable", (0x28 << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "sensor failure", (0x28 << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "FRU failure", (0x29 << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "battery low", (0x29 << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "battery failed", (0x29 << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "battery presence detected", (0x2a << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Session Activated", (0x2a << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Session Deactivated", (0x2a << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Invalid Username or Password", (0x2a << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Invalid Password Disable", (0x2b << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "Hardware change detected with associated Entity", (0x2b << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "Firmware or software change detected with associated Entity", (0x2b << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "Hardware incompatibility detected with associated Entity", (0x2b << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "Firmware or software incompatibility detected with associated Entity", (0x2b << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "Entity is of an invalid or unsupported hardware version", (0x2b << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "Entity contains an invalid or unsupported firmware or software version", (0x2b << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "Hardware Change detected with associated Entity was successful", (0x2b << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "Software or F/W Change detected with associated Entity was successful", (0x2c << 24) | (0x00 << 16) | (0xff << 8) | 0xff: "FRU Not Installed", (0x2c << 24) | (0x01 << 16) | (0xff << 8) | 0xff: "FRU Inactive", (0x2c << 24) | (0x02 << 16) | (0xff << 8) | 0xff: "FRU Activation Requested", (0x2c << 24) | (0x03 << 16) | (0xff << 8) | 0xff: "FRU Activation In Progress", (0x2c << 24) | (0x04 << 16) | (0xff << 8) | 0xff: "FRU Active", (0x2c << 24) | (0x05 << 16) | (0xff << 8) | 0xff: "FRU Deactivation Requested", (0x2c << 24) | (0x06 << 16) | (0xff << 8) | 0xff: "FRU Deactivation In Progress", (0x2c << 24) | (0x07 << 16) | (0xff << 8) | 0xff: "FRU Communication Lost", }
event.go
0.541409
0.60013
event.go
starcoder
package sm9curve import "math/big" // For details of the algorithms used, see "Multiplication and Squaring on // Pairing-Friendly Fields, Devegili et al. // http://eprint.iacr.org/2006/471.pdf. // gfP2 implements a field of size p² as a quadratic extension of the base field // where i²=-2. type gfP2 struct { x, y gfP // value is xi+y. } func gfP2Decode(in *gfP2) *gfP2 { out := &gfP2{} montDecode(&out.x, &in.x) montDecode(&out.y, &in.y) return out } func (e *gfP2) String() string { return "(" + e.x.String() + ", " + e.y.String() + ")" } func (e *gfP2) Set(a *gfP2) *gfP2 { e.x.Set(&a.x) e.y.Set(&a.y) return e } func (e *gfP2) SetZero() *gfP2 { e.x = gfP{0} e.y = gfP{0} return e } func (e *gfP2) SetOne() *gfP2 { e.x = gfP{0} e.y = *newGFp(1) return e } func (e *gfP2) IsZero() bool { zero := gfP{0} return e.x == zero && e.y == zero } func (e *gfP2) IsOne() bool { zero, one := gfP{0}, *newGFp(1) return e.x == zero && e.y == one } func (e *gfP2) Conjugate(a *gfP2) *gfP2 { e.y.Set(&a.y) gfpNeg(&e.x, &a.x) return e } func (e *gfP2) Neg(a *gfP2) *gfP2 { gfpNeg(&e.x, &a.x) gfpNeg(&e.y, &a.y) return e } func (e *gfP2) Add(a, b *gfP2) *gfP2 { gfpAdd(&e.x, &a.x, &b.x) gfpAdd(&e.y, &a.y, &b.y) return e } func (e *gfP2) Sub(a, b *gfP2) *gfP2 { gfpSub(&e.x, &a.x, &b.x) gfpSub(&e.y, &a.y, &b.y) return e } // See "Multiplication and Squaring in Pairing-Friendly Fields", // http://eprint.iacr.org/2006/471.pdf //(ai+b)(ci+d)=(bd-2ac)+i((a+b)(c+d)-ac-bd) func (e *gfP2) Mul(a, b *gfP2) *gfP2 { tx, t1, t2 := &gfP{}, &gfP{}, &gfP{} gfpAdd(t1, &a.x, &a.y) //a+b gfpAdd(t2, &b.x, &b.y) //c+d gfpMul(tx, t1, t2) gfpMul(t1, &a.x, &b.x) //ac gfpMul(t2, &a.y, &b.y) //bd gfpSub(tx, tx, t1) gfpSub(tx, tx, t2) //x=(a+b)(c+d)-ac-bd ty := &gfP{} gfpSub(ty, t2, t1) //bd-ac gfpSub(ty, ty, t1) //bd-2ac e.x.Set(tx) e.y.Set(ty) return e } func (e *gfP2) MulScalar(a *gfP2, b *gfP) *gfP2 { gfpMul(&e.x, &a.x, b) gfpMul(&e.y, &a.y, b) return e } // MulXi sets e=ξa where ξ=bi=(-1/2)i and then returns e. func (e *gfP2) MulXi(a *gfP2) *gfP2 { // (xi+y)bi = ybi-2bx=-1/2yi+x tx := &gfP{} ty := &gfP{} gfpMul(tx, &a.y, &bi) ty.Set(&a.x) e.x.Set(tx) e.y.Set(ty) return e } func (e *gfP2) Square(a *gfP2) *gfP2 { // Complex squaring algorithm: // (xi+y)² = (y²-2x²) + 2*i*x*y tx1, tx2, ty1, ty2 := &gfP{}, &gfP{}, &gfP{}, &gfP{} gfpMul(tx1, &a.x, &a.y) gfpAdd(tx2, tx1, tx1) gfpMul(ty1, &a.y, &a.y) gfpMul(ty2, &a.x, &a.x) ty := &gfP{} gfpAdd(ty, ty2, ty2) gfpSub(ty1, ty1, ty) e.x.Set(tx2) e.y.Set(ty1) return e } func (e *gfP2) Invert(a *gfP2) *gfP2 { // See "Implementing cryptographic pairings", <NAME>, section 3.2. // ftp://136.206.11.249/pub/crypto/pairings.pdf t1, t2 := &gfP{}, &gfP{} gfpMul(t1, &a.x, &a.x) t3 := &gfP{} gfpAdd(t3, t1, t1) gfpMul(t2, &a.y, &a.y) gfpAdd(t3, t3, t2) inv := &gfP{} inv.Invert(t3) gfpNeg(t1, &a.x) gfpMul(&e.x, t1, inv) gfpMul(&e.y, &a.y, inv) return e } func (c *gfP2) GFp2Exp(a *gfP2, b *big.Int) *gfP2 { sum := (&gfP2{}).SetOne() t := &gfP2{} for i := b.BitLen() - 1; i >= 0; i-- { t.Square(sum) if b.Bit(i) != 0 { sum.Mul(t, a) } else { sum.Set(t) } } c.Set(sum) return c }
elliptic/sm9curve/gfp2.go
0.788583
0.415907
gfp2.go
starcoder
// Mapping from PC to SP offset (called CFA - Canonical Frame Address - in DWARF). // This value is the offset from the stack pointer to the virtual frame pointer // (address of zeroth argument) at each PC value in the program. package dwarf import "fmt" // http://www.dwarfstd.org/doc/DWARF4.pdf Section 6.4 page 126 // We implement only the CFA column of the table, not the location // information about other registers. In other words, we implement // only what we need to understand Go programs compiled by gc. // PCToSPOffset returns the offset, at the specified PC, to add to the // SP to reach the virtual frame pointer, which corresponds to the // address of the zeroth argument of the function, the word on the // stack immediately above the return PC. func (d *Data) PCToSPOffset(pc uint64) (offset int64, err error) { if len(d.frame) == 0 { return 0, fmt.Errorf("PCToSPOffset: no frame table") } var m frameMachine // Assume the first info unit is the same as us. Extremely likely. TODO? if len(d.unit) == 0 { return 0, fmt.Errorf("PCToSPOffset: no info section") } buf := makeBuf(d, &d.unit[0], "frame", 0, d.frame) for len(buf.data) > 0 { offset, err := m.evalCompilationUnit(&buf, pc) if err != nil { return 0, err } return offset, nil } return 0, fmt.Errorf("PCToSPOffset: no frame defined for PC %#x", pc) } // Call Frame instructions. Figure 40, page 181. // Structure is high two bits plus low 6 bits specified by + in comment. // Some take one or two operands. const ( frameNop = 0<<6 + 0x00 frameAdvanceLoc = 1<<6 + 0x00 // + delta frameOffset = 2<<6 + 0x00 // + register op: ULEB128 offset frameRestore = 3<<6 + 0x00 // + register frameSetLoc = 0<<6 + 0x01 // op: address frameAdvanceLoc1 = 0<<6 + 0x02 // op: 1-byte delta frameAdvanceLoc2 = 0<<6 + 0x03 // op: 2-byte delta frameAdvanceLoc4 = 0<<6 + 0x04 // op: 4-byte delta frameOffsetExtended = 0<<6 + 0x05 // ops: ULEB128 register ULEB128 offset frameRestoreExtended = 0<<6 + 0x06 // op: ULEB128 register frameUndefined = 0<<6 + 0x07 // op: ULEB128 register frameSameValue = 0<<6 + 0x08 // op: ULEB128 register frameRegister = 0<<6 + 0x09 // op: ULEB128 register ULEB128 register frameRememberState = 0<<6 + 0x0a frameRestoreState = 0<<6 + 0x0b frameDefCFA = 0<<6 + 0x0c // op: ULEB128 register ULEB128 offset frameDefCFARegister = 0<<6 + 0x0d // op: ULEB128 register frameDefCFAOffset = 0<<6 + 0x0e // op: ULEB128 offset frameDefCFAExpression = 0<<6 + 0x0f // op: BLOCK frameExpression = 0<<6 + 0x10 // op: ULEB128 register BLOCK frameOffsetExtendedSf = 0<<6 + 0x11 // op: ULEB128 register SLEB128 offset frameDefCFASf = 0<<6 + 0x12 // op: ULEB128 register SLEB128 offset frameDefCFAOffsetSf = 0<<6 + 0x13 // op: SLEB128 offset frameValOffset = 0<<6 + 0x14 // op: ULEB128 ULEB128 frameValOffsetSf = 0<<6 + 0x15 // op: ULEB128 SLEB128 frameValExpression = 0<<6 + 0x16 // op: ULEB128 BLOCK frameLoUser = 0<<6 + 0x1c frameHiUser = 0<<6 + 0x3f ) // frameMachine represents the PC/SP engine. // Section 6.4, page 129. type frameMachine struct { // Initial values from CIE. version uint8 // Version number, "independent of DWARF version" augmentation string // Augmentation; treated as unexpected for now. TODO. addressSize uint8 // In DWARF v4 and above. Size of a target address. segmentSize uint8 // In DWARF v4 and above. Size of a segment selector. codeAlignmentFactor uint64 // Unit of code size in advance instructions. dataAlignmentFactor int64 // Unit of data size in certain offset instructions. returnAddressRegister int // Pseudo-register (actually data column) representing return address. returnRegisterOffset int64 // Offset to saved PC from CFA in bytes. // CFA definition. cfaRegister int // Which register represents the SP. cfaOffset int64 // CFA offset value. // Running machine. location uint64 } // evalCompilationUnit scans the frame data for one compilation unit to retrieve // the offset information for the specified pc. func (m *frameMachine) evalCompilationUnit(b *buf, pc uint64) (int64, error) { err := m.parseCIE(b) if err != nil { return 0, err } for { offset, found, err := m.scanFDE(b, pc) if err != nil { return 0, err } if found { return offset, nil } } } // parseCIE assumes the incoming buffer starts with a CIE block and parses it // to initialize a frameMachine. func (m *frameMachine) parseCIE(allBuf *buf) error { length := int(allBuf.uint32()) if len(allBuf.data) < length { return fmt.Errorf("CIE parse error: too short") } // Create buffer for just this section. b := allBuf.slice(length) cie := b.uint32() if cie != 0xFFFFFFFF { return fmt.Errorf("CIE parse error: not CIE: %x", cie) } m.version = b.uint8() if m.version != 3 && m.version != 4 { return fmt.Errorf("CIE parse error: unsupported version %d", m.version) } m.augmentation = b.string() if len(m.augmentation) > 0 { return fmt.Errorf("CIE: can't handled augmentation string %q", m.augmentation) } if m.version >= 4 { m.addressSize = b.uint8() m.segmentSize = b.uint8() } else { // Unused. Gc generates version 3, so these values will not be // set, but they are also not used so it's OK. } m.codeAlignmentFactor = b.uint() m.dataAlignmentFactor = b.int() m.returnAddressRegister = int(b.uint()) // Initial instructions. At least for Go, establishes SP register number // and initial value of CFA offset at start of function. _, err := m.run(&b, ^uint64(0)) if err != nil { return err } // There's padding, but we can ignore it. return nil } // scanFDE assumes the incoming buffer starts with a FDE block and parses it // to run a frameMachine and, if the PC is represented in its range, return // the CFA offset for that PC. The boolean returned reports whether the // PC is in range for this FDE. func (m *frameMachine) scanFDE(allBuf *buf, pc uint64) (int64, bool, error) { length := int(allBuf.uint32()) if len(allBuf.data) < length { return 0, false, fmt.Errorf("FDE parse error: too short") } if length <= 0 { if length == 0 { // EOF. return 0, false, fmt.Errorf("PC %#x not found in PC/SP table", pc) } return 0, false, fmt.Errorf("bad FDE length %d", length) } // Create buffer for just this section. b := allBuf.slice(length) cieOffset := b.uint32() // TODO: assumes 32 bits. // Expect 0: first CIE in this segment. TODO. if cieOffset != 0 { return 0, false, fmt.Errorf("FDE parse error: bad CIE offset: %.2x", cieOffset) } // Initial location. m.location = b.addr() addressRange := b.addr() // If the PC is not in this function, there's no point in executing the instructions. if pc < m.location || m.location+addressRange <= pc { return 0, false, nil } // The PC appears in this FDE. Scan to find the location. offset, err := m.run(&b, pc) if err != nil { return 0, false, err } // There's padding, but we can ignore it. return offset, true, nil } // run executes the instructions in the buffer, which has been sliced to contain // only the data for this block. When we run out of data, we return. // Since we are only called when we know the PC is in this block, reaching // EOF is not an error, it just means the final CFA definition matches the // tail of the block that holds the PC. // The return value is the CFA at the end of the block or the PC, whichever // comes first. func (m *frameMachine) run(b *buf, pc uint64) (int64, error) { // We run the machine at location == PC because if the PC is at the first // instruction of a block, the definition of its offset arrives as an // offset-defining operand after the PC is set to that location. for m.location <= pc && len(b.data) > 0 { op := b.uint8() // Ops with embedded operands switch op & 0xC0 { case frameAdvanceLoc: // (6.4.2.1) // delta in low bits m.location += uint64(op & 0x3F) continue case frameOffset: // (6.4.2.3) // Register in low bits; ULEB128 offset. // For Go binaries we only see this in the CIE for the return address register. if int(op&0x3F) != m.returnAddressRegister { return 0, fmt.Errorf("invalid frameOffset register R%d should be R%d", op&0x3f, m.returnAddressRegister) } m.returnRegisterOffset = int64(b.uint()) * m.dataAlignmentFactor continue case frameRestore: // (6.4.2.3) // register in low bits return 0, fmt.Errorf("unimplemented frameRestore(R%d)\n", op&0x3F) } // The remaining ops do not have embedded operands. switch op { // Row creation instructions (6.4.2.1) case frameNop: case frameSetLoc: // op: address return 0, fmt.Errorf("unimplemented setloc") // what size is operand? case frameAdvanceLoc1: // op: 1-byte delta m.location += uint64(b.uint8()) case frameAdvanceLoc2: // op: 2-byte delta m.location += uint64(b.uint16()) case frameAdvanceLoc4: // op: 4-byte delta m.location += uint64(b.uint32()) // CFA definition instructions (6.4.2.2) case frameDefCFA: // op: ULEB128 register ULEB128 offset m.cfaRegister = int(b.int()) m.cfaOffset = int64(b.uint()) case frameDefCFASf: // op: ULEB128 register SLEB128 offset return 0, fmt.Errorf("unimplemented frameDefCFASf") case frameDefCFARegister: // op: ULEB128 register return 0, fmt.Errorf("unimplemented frameDefCFARegister") case frameDefCFAOffset: // op: ULEB128 offset return 0, fmt.Errorf("unimplemented frameDefCFAOffset") case frameDefCFAOffsetSf: // op: SLEB128 offset offset := b.int() m.cfaOffset = offset * m.dataAlignmentFactor // TODO: Verify we are using a factored offset. case frameDefCFAExpression: // op: BLOCK return 0, fmt.Errorf("unimplemented frameDefCFAExpression") // Register Rule instructions (6.4.2.3) case frameOffsetExtended: // ops: ULEB128 register ULEB128 offset // The same as frameOffset, but with the register specified in an operand. reg := b.uint() // For Go binaries we only see this in the CIE for the return address register. if reg != uint64(m.returnAddressRegister) { return 0, fmt.Errorf("invalid frameOffsetExtended: register R%d should be R%d", reg, m.returnAddressRegister) } m.returnRegisterOffset = int64(b.uint()) * m.dataAlignmentFactor case frameRestoreExtended: // op: ULEB128 register return 0, fmt.Errorf("unimplemented frameRestoreExtended") case frameUndefined: // op: ULEB128 register; unimplemented return 0, fmt.Errorf("unimplemented frameUndefined") case frameSameValue: // op: ULEB128 register return 0, fmt.Errorf("unimplemented frameSameValue") case frameRegister: // op: ULEB128 register ULEB128 register return 0, fmt.Errorf("unimplemented frameRegister") case frameRememberState: return 0, fmt.Errorf("unimplemented frameRememberState") case frameRestoreState: return 0, fmt.Errorf("unimplemented frameRestoreState") case frameExpression: // op: ULEB128 register BLOCK return 0, fmt.Errorf("unimplemented frameExpression") case frameOffsetExtendedSf: // op: ULEB128 register SLEB128 offset return 0, fmt.Errorf("unimplemented frameOffsetExtended_sf") case frameValOffset: // op: ULEB128 ULEB128 return 0, fmt.Errorf("unimplemented frameValOffset") case frameValOffsetSf: // op: ULEB128 SLEB128 return 0, fmt.Errorf("unimplemented frameValOffsetSf") case frameValExpression: // op: ULEB128 BLOCK return 0, fmt.Errorf("unimplemented frameValExpression") default: if frameLoUser <= op && op <= frameHiUser { return 0, fmt.Errorf("unknown user-defined frame op %#x", op) } return 0, fmt.Errorf("unknown frame op %#x", op) } } return m.cfaOffset, nil }
vendor/cloud.google.com/go/cmd/go-cloud-debug-agent/internal/debug/dwarf/frame.go
0.564219
0.517632
frame.go
starcoder
package math import ( "fmt" "math" ) // Vec4 represents a four component vector. type Vec4 struct { X, Y, Z, W float64 } // String returns an string representation of this vector. func (a Vec4) String() string { return fmt.Sprintf("Vec4(X=%f, Y=%f, Z=%f, W=%f)", a.X, a.Y, a.Z, a.W) } // AlmostEquals tells if a == b using the specified epsilon value. func (a Vec4) AlmostEquals(b Vec4, epsilon float64) bool { return AlmostEqual(a.X, b.X, epsilon) && AlmostEqual(a.Y, b.Y, epsilon) && AlmostEqual(a.Z, b.Z, epsilon) && AlmostEqual(a.W, b.W, epsilon) } // Equals tells if a == b using the default EPSILON value. func (a Vec4) Equals(b Vec4) bool { return a.AlmostEquals(b, EPSILON) } // Add performs a componentwise addition of the two vectors, returning a + b. func (a Vec4) Add(b Vec4) Vec4 { return Vec4{a.X + b.X, a.Y + b.Y, a.Z + b.Z, a.W + a.W} } // AddScalar performs a componentwise scalar addition of a + b. func (a Vec4) AddScalar(b float64) Vec4 { return Vec4{a.X + b, a.Y + b, a.Z + b, a.W + b} } // Sub performs a componentwise subtraction of the two vectors, returning // a - b. func (a Vec4) Sub(b Vec4) Vec4 { return Vec4{a.X - b.X, a.Y - b.Y, a.Z - b.Z, a.W - b.W} } // SubScalar performs a componentwise scalar subtraction of a - b. func (a Vec4) SubScalar(b float64) Vec4 { return Vec4{a.X - b, a.Y - b, a.Z - b, a.W - b} } // Mul performs a componentwise multiplication of the two vectors, returning // a * b. func (a Vec4) Mul(b Vec4) Vec4 { return Vec4{a.X * b.X, a.Y * b.Y, a.Z * b.Z, a.W * b.W} } // MulScalar performs a componentwise scalar multiplication of a * b. func (a Vec4) MulScalar(b float64) Vec4 { return Vec4{a.X * b, a.Y * b, a.Z * b, a.W * b} } // Div performs a componentwise division of the two vectors, returning a * b. func (a Vec4) Div(b Vec4) Vec4 { return Vec4{a.X / b.X, a.Y / b.Y, a.Z / b.Z, a.W / b.W} } // DivScalar performs a componentwise scalar division of a * b. func (a Vec4) DivScalar(b float64) Vec4 { return Vec4{a.X / b, a.Y / b, a.Z / b, a.W / b} } // IsNaN tells if any components of this vector are not an number. func (a Vec4) IsNaN() bool { return math.IsNaN(a.X) || math.IsNaN(a.Y) || math.IsNaN(a.Z) || math.IsNaN(a.W) } // Less tells if a is componentwise less than b: // return a.X < b.X && a.Y < b.Y func (a Vec4) Less(b Vec4) bool { return a.X < b.X && a.Y < b.Y && a.Z < b.Z && a.W < b.W } // Greater tells if a is componentwise greater than b: // return a.X > b.X && a.Y > b.Y func (a Vec4) Greater(b Vec4) bool { return a.X > b.X && a.Y > b.Y && a.Z < b.Z && a.W < b.W } // AnyLess tells if a is componentwise any less than b: // return a.X < b.X || a.Y < b.Y || a.Z < b.Z || a.W < b.W func (a Vec4) AnyLess(b Vec4) bool { return a.X < b.X || a.Y < b.Y || a.Z < b.Z || a.W < b.W } // AnyGreater tells if a is componentwise any greater than b: // return a.X > b.X || a.Y > b.Y || a.Z > b.Z || a.W > b.W func (a Vec4) AnyGreater(b Vec4) bool { return a.X > b.X || a.Y > b.Y || a.Z > b.Z || a.W > b.W } // Clamp clamps each value in the vector to the range of [min, max] and returns // it. func (a Vec4) Clamp(min, max float64) Vec4 { return Vec4{ Clamp(a.X, min, max), Clamp(a.Y, min, max), Clamp(a.Z, min, max), Clamp(a.W, min, max), } } // Radians converts each value in the vector from degrees to radians and // returns it. func (a Vec4) Radians() Vec4 { return Vec4{ Radians(a.X), Radians(a.Y), Radians(a.Z), Radians(a.W), } } // Degrees converts each value in the vector from radians to degrees and // returns it. func (a Vec4) Degrees() Vec4 { return Vec4{ Degrees(a.X), Degrees(a.Y), Degrees(a.Z), Degrees(a.W), } } // Rounded rounds each value in the vector to the nearest whole number and // returns it. func (a Vec4) Rounded() Vec4 { return Vec4{ Rounded(a.X), Rounded(a.Y), Rounded(a.Z), Rounded(a.W), } } // Dot returns the dot product of a and b. func (a Vec4) Dot(b Vec4) float64 { return a.X*b.X + a.Y*b.Y + a.Z*b.Z + a.W*b.W } // LengthSq returns the magnitude squared of this vector, useful for comparing // distances. func (a Vec4) LengthSq() float64 { return a.X*a.X + a.Y*a.Y + a.Z*a.Z + a.W*a.W } // Length returns the magnitude of this vector. To avoid a sqrt call when // strictly comparing distances, LengthSq can be used instead. func (a Vec4) Length() float64 { return math.Sqrt(a.X*a.X + a.Y*a.Y + a.Z*a.Z + a.W*a.W) } // Normalized returns the normalized (i.e. length/magnitude == 1) vector of a. // If the vector's length is zero (and division by zero would occur) then // [Vec4Zero, false] is returned. func (a Vec4) Normalized() (v Vec4, ok bool) { length := math.Sqrt(a.X*a.X + a.Y*a.Y + a.Z*a.Z + a.W*a.W) if Equal(length, 0) { return Vec4Zero, false } return Vec4{ a.X / length, a.Y / length, a.Z / length, a.W / length, }, true } // Proj returns a vector representing the projection of vector a onto b. func (a Vec4) Proj(b Vec4) Vec4 { return b.MulScalar(a.Dot(b) / b.LengthSq()) } // Min returns a vector representing the smallest components of both the // vectors. func (a Vec4) Min(b Vec4) Vec4 { var r Vec4 if a.X < b.X { r.X = a.X } else { r.X = b.X } if a.Y < b.Y { r.Y = a.Y } else { r.Y = b.Y } if a.Z < b.Z { r.Z = a.Z } else { r.Z = b.Z } if a.W < b.W { r.W = a.W } else { r.W = b.W } return r } // Max returns a vector representing the largest components of both the // vectors. func (a Vec4) Max(b Vec4) Vec4 { var r Vec4 if a.X > b.X { r.X = a.X } else { r.X = b.X } if a.Y > b.Y { r.Y = a.Y } else { r.Y = b.Y } if a.Z > b.Z { r.Z = a.Z } else { r.Z = b.Z } if a.W > b.W { r.W = a.W } else { r.W = b.W } return r } // Lerp returns a vector representing the linear interpolation between the // vectors a and b. The t parameter is the amount to interpolate (0.0 - 1.0) // between the vectors. func (a Vec4) Lerp(b Vec4, t float64) Vec4 { return a.Mul(b.MulScalar(t)) } // Transform transforms this vector by the matrix (vector * matrix) and returns // the result. // This is an fully general operation. func (a Vec4) Transform(b Mat4) Vec4 { return Vec4{ a.X*b[0][0] + a.Y*b[1][0] + a.Z*b[2][0] + a.W*b[3][0], a.X*b[0][1] + a.Y*b[1][1] + a.Z*b[2][1] + a.W*b[3][1], a.X*b[0][2] + a.Y*b[1][2] + a.Z*b[2][2] + a.W*b[3][2], a.X*b[0][3] + a.Y*b[1][3] + a.Z*b[2][3] + a.W*b[3][3], } } // Quat converts this vector to a quaternion. It's short-hand for: // Quat{a.X, a.Y, a.Z, a.W} func (a Vec4) Quat() Quat { return Quat{a.X, a.Y, a.Z, a.W} } // Vec3 converts this four-vector to three-component one. It's short-hand for: // Vec3{a.X, a.Y, a.Z} func (a Vec3) Vec3() Vec3 { return Vec3{a.X, a.Y, a.Z} } var ( Vec4One = Vec4{1, 1, 1, 1} Vec4XUnit = Vec4{1, 0, 0, 0} Vec4YUnit = Vec4{0, 1, 0, 0} Vec4ZUnit = Vec4{0, 0, 1, 0} Vec4WUnit = Vec4{0, 0, 0, 1} Vec4Zero = Vec4{0, 0, 0, 0} )
math/vec4.go
0.927058
0.729712
vec4.go
starcoder
package beehive import "fmt" // CellKey represents a key in a dictionary. type CellKey struct { Dict string Key string } // AppCellKey represents a key in a dictionary of a specific app. type AppCellKey struct { App string Dict string Key string } // Cell returns the CellKey of this AppCellKey. func (ack AppCellKey) Cell() CellKey { return CellKey{ Dict: ack.Dict, Key: ack.Key, } } // IsNil returns whether the AppCellKey represents no cells. func (ack AppCellKey) IsNil() bool { return ack.App == "" } // MappedCells is the list of dictionary keys returned by the map functions. type MappedCells []CellKey func (mc MappedCells) String() string { return fmt.Sprintf("Cells{%v}", []CellKey(mc)) } func (mc MappedCells) Len() int { return len(mc) } func (mc MappedCells) Swap(i, j int) { mc[i], mc[j] = mc[j], mc[i] } func (mc MappedCells) Less(i, j int) bool { return mc[i].Dict < mc[j].Dict || (mc[i].Dict == mc[j].Dict && mc[i].Key < mc[j].Key) } // LocalBroadcast returns whether the mapped cells indicate a local broadcast. // An empty set means a local broadcast of message. Note that nil means drop. func (mc MappedCells) LocalBroadcast() bool { return len(mc) == 0 } type cellStore struct { // colonyid -> term Colonies map[uint64]uint64 // appname -> dict -> key -> colony CellBees map[string]map[string]map[string]Colony // beeid -> dict -> key BeeCells map[uint64]map[string]map[string]struct{} } func newCellStore() cellStore { return cellStore{ Colonies: make(map[uint64]uint64), CellBees: make(map[string]map[string]map[string]Colony), BeeCells: make(map[uint64]map[string]map[string]struct{}), } } func (s *cellStore) assign(app string, k CellKey, c Colony) { s.assignCellBees(app, k, c) s.assignBeeCells(app, k, c) } func (s *cellStore) assignCellBees(app string, k CellKey, c Colony) { dicts, ok := s.CellBees[app] if !ok { dicts = make(map[string]map[string]Colony) s.CellBees[app] = dicts } keys, ok := dicts[k.Dict] if !ok { keys = make(map[string]Colony) dicts[k.Dict] = keys } keys[k.Key] = c } func (s *cellStore) assignBeeCells(app string, k CellKey, c Colony) { dicts, ok := s.BeeCells[c.Leader] if !ok { dicts = make(map[string]map[string]struct{}) s.BeeCells[c.Leader] = dicts } keys, ok := dicts[k.Dict] if !ok { keys = make(map[string]struct{}) dicts[k.Dict] = keys } keys[k.Key] = struct{}{} } func (s *cellStore) colony(app string, cell CellKey) (c Colony, ok bool) { dicts, ok := s.CellBees[app] if !ok { return Colony{}, false } keys, ok := dicts[cell.Dict] if !ok { return Colony{}, false } c, ok = keys[cell.Key] return c, ok } func (s *cellStore) cells(bee uint64) MappedCells { dicts, ok := s.BeeCells[bee] if !ok { return nil } c := make(MappedCells, 0, len(dicts)) for d, dict := range dicts { for k := range dict { c = append(c, CellKey{Dict: d, Key: k}) } } return c } func (s *cellStore) updateColony(app string, oldc Colony, newc Colony, term uint64) error { if t, ok := s.Colonies[newc.ID]; ok { if term < t { return fmt.Errorf("cellstore: colony is older than %v", t) } } s.Colonies[newc.ID] = term bcells := s.BeeCells[oldc.Leader] if oldc.Leader != newc.Leader { s.BeeCells[newc.Leader] = bcells delete(s.BeeCells, oldc.Leader) } acells := s.CellBees[app] for d, dict := range bcells { for k := range dict { acells[d][k] = newc } } return nil }
cell.go
0.709623
0.458288
cell.go
starcoder
package jet // TimestampzExpression interface type TimestampzExpression interface { Expression EQ(rhs TimestampzExpression) BoolExpression NOT_EQ(rhs TimestampzExpression) BoolExpression IS_DISTINCT_FROM(rhs TimestampzExpression) BoolExpression IS_NOT_DISTINCT_FROM(rhs TimestampzExpression) BoolExpression LT(rhs TimestampzExpression) BoolExpression LT_EQ(rhs TimestampzExpression) BoolExpression GT(rhs TimestampzExpression) BoolExpression GT_EQ(rhs TimestampzExpression) BoolExpression BETWEEN(min, max TimestampzExpression) BoolExpression NOT_BETWEEN(min, max TimestampzExpression) BoolExpression ADD(rhs Interval) TimestampzExpression SUB(rhs Interval) TimestampzExpression } type timestampzInterfaceImpl struct { parent TimestampzExpression } func (t *timestampzInterfaceImpl) EQ(rhs TimestampzExpression) BoolExpression { return Eq(t.parent, rhs) } func (t *timestampzInterfaceImpl) NOT_EQ(rhs TimestampzExpression) BoolExpression { return NotEq(t.parent, rhs) } func (t *timestampzInterfaceImpl) IS_DISTINCT_FROM(rhs TimestampzExpression) BoolExpression { return IsDistinctFrom(t.parent, rhs) } func (t *timestampzInterfaceImpl) IS_NOT_DISTINCT_FROM(rhs TimestampzExpression) BoolExpression { return IsNotDistinctFrom(t.parent, rhs) } func (t *timestampzInterfaceImpl) LT(rhs TimestampzExpression) BoolExpression { return Lt(t.parent, rhs) } func (t *timestampzInterfaceImpl) LT_EQ(rhs TimestampzExpression) BoolExpression { return LtEq(t.parent, rhs) } func (t *timestampzInterfaceImpl) GT(rhs TimestampzExpression) BoolExpression { return Gt(t.parent, rhs) } func (t *timestampzInterfaceImpl) GT_EQ(rhs TimestampzExpression) BoolExpression { return GtEq(t.parent, rhs) } func (t *timestampzInterfaceImpl) BETWEEN(min, max TimestampzExpression) BoolExpression { return NewBetweenOperatorExpression(t.parent, min, max, false) } func (t *timestampzInterfaceImpl) NOT_BETWEEN(min, max TimestampzExpression) BoolExpression { return NewBetweenOperatorExpression(t.parent, min, max, true) } func (t *timestampzInterfaceImpl) ADD(rhs Interval) TimestampzExpression { return TimestampzExp(Add(t.parent, rhs)) } func (t *timestampzInterfaceImpl) SUB(rhs Interval) TimestampzExpression { return TimestampzExp(Sub(t.parent, rhs)) } //------------------------------------------------- type timestampzExpressionWrapper struct { timestampzInterfaceImpl Expression } func newTimestampzExpressionWrap(expression Expression) TimestampzExpression { timestampzExpressionWrap := timestampzExpressionWrapper{Expression: expression} timestampzExpressionWrap.timestampzInterfaceImpl.parent = &timestampzExpressionWrap return &timestampzExpressionWrap } // TimestampzExp is timestamp with time zone expression wrapper around arbitrary expression. // Allows go compiler to see any expression as timestamp with time zone expression. // Does not add sql cast to generated sql builder output. func TimestampzExp(expression Expression) TimestampzExpression { return newTimestampzExpressionWrap(expression) }
internal/jet/timestampz_expression.go
0.810479
0.495545
timestampz_expression.go
starcoder
package game import "github.com/anilmisirlioglu/Tic-Tac-Toe-AI/math" type Controller struct { game *Game scores map[int]int } type MinimaxPacket struct { Vector2 math.Vector2 Score int } const ( MaxInt = int(^uint(0) >> 1) MinInt = -MaxInt - 1 ) func (c Controller) Minimax(matrix math.Matrix, depth int, player int) MinimaxPacket { cpu := c.game.CPU packetScore := MaxInt if cpu.GetSymbolByInt() == player { packetScore = MinInt } optimumAxisAlignment := MinimaxPacket{ Vector2: math.Vector2{X: -1, Y: -1}, Score: packetScore, } if depth == 0 || c.over() { return MinimaxPacket{ Vector2: math.Vector2{X: -1, Y: -1}, Score: c.toScore(c.evaluate()), } } for row := 0; row < matrix.Rows; row++ { for column := 0; column < matrix.Columns; column++ { if matrix.GetElement(row, column) == NullIndex { matrix.SetElement(row, column, player) nextPlayer := XIndex if player == XIndex { nextPlayer = OIndex } score := c.Minimax(matrix, depth-1, nextPlayer) matrix.SetElement(row, column, NullIndex) score.Vector2 = math.Vector2{ X: row, Y: column, } if player == cpu.GetSymbolByInt() { if score.Score > optimumAxisAlignment.Score { optimumAxisAlignment = score } } else { if score.Score < optimumAxisAlignment.Score { optimumAxisAlignment = score } } } } } return optimumAxisAlignment } func (c Controller) evaluate() int { matrix := c.game.matrix // Vertical Axis for v := 0; v < matrix.Rows; v++ { middle := matrix.GetElement(1, v) if middle != NullIndex { if matrix.GetElement(0, v) == middle && matrix.GetElement(2, v) == middle { return middle } } } // Horizontal Axis for h := 0; h < matrix.Columns; h++ { middle := matrix.GetElement(h, 1) if middle != NullIndex { if matrix.GetElement(h, 0) == middle && matrix.GetElement(h, 2) == middle { return middle } } } middle := matrix.GetElement(1, 1) // Cross Axis Middle if middle != NullIndex { // Cross Axis (Top Left, Bottom Right) if matrix.GetElement(0, 0) == middle && matrix.GetElement(2, 2) == middle { return middle } // Cross Axis (Top Right, Bottom Left) if matrix.GetElement(2, 0) == middle && matrix.GetElement(0, 2) == middle { return middle } } for v := 0; v < matrix.Rows; v++ { for h := 0; h < matrix.Columns; h++ { if matrix.GetElement(v, h) == NullIndex { return Unfinished } } } return Draw } func (c Controller) over() bool { evaluate := c.evaluate() return evaluate == XWon || evaluate == OWon } func (c Controller) toScore(winner int) int { score, ok := c.scores[winner] if !ok { score = 0 } return score } func NewController(game *Game) *Controller { return &Controller{ game: game, scores: map[int]int{ game.CPU.GetSymbolByInt(): 1, game.Human.GetSymbolByInt(): -1, }, } }
game/controller.go
0.57821
0.524577
controller.go
starcoder
package graphql import ( gql "github.com/graphql-go/graphql" ) var settingsType = gql.NewObject(gql.ObjectConfig{ Name: "settings", Description: "Settings represents the current deloominator", Fields: gql.Fields{ "isReadOnly": &gql.Field{ Description: "Readonly server value", Type: gql.Boolean, }, }, }) var queryErrorType = gql.NewObject(gql.ObjectConfig{ Name: "queryError", Description: "An error represents an error message from the data source", Fields: gql.Fields{ "message": &gql.Field{ Description: "Error message from the server", Type: gql.NewNonNull(gql.String), }, }, IsTypeOf: func(p gql.IsTypeOfParams) bool { _, ok := p.Value.(queryError) return ok }, }) var cellType = gql.NewObject(gql.ObjectConfig{ Name: "Cell", Description: "A cell represents a single piece of returnted data", Fields: gql.Fields{ "value": &gql.Field{ Description: "Value of the cell", Type: gql.String, }, }, }) var rowType = gql.NewObject(gql.ObjectConfig{ Name: "Row", Description: "A row holds the representation of a set of cells of the raw data returned by the data source", Fields: gql.Fields{ "cells": &gql.Field{ Description: "Name of the column", Type: gql.NewList(cellType), }, }, }) var columnType = gql.NewObject(gql.ObjectConfig{ Name: "Column", Description: "A column holds the representation of one column of the raw data returned by a data source", Fields: gql.Fields{ "name": &gql.Field{ Description: "Name of the column", Type: gql.String, }, "type": &gql.Field{ Description: "Type of the column", Type: gql.String, }, }, }) var variableType = gql.NewObject(gql.ObjectConfig{ Name: "Variable", Description: "variable represents a single query variable", Fields: gql.Fields{ "name": &gql.Field{ Description: "variable name", Type: gql.String, }, "value": &gql.Field{ Description: "variable value", Type: gql.String, }, "isControllable": &gql.Field{ Description: "true if the variable has a controllable UI", Type: gql.Boolean, }, }, IsTypeOf: func(p gql.IsTypeOfParams) bool { _, ok := p.Value.(variable) return ok }, }) var resultsType = gql.NewObject(gql.ObjectConfig{ Name: "results", Description: "results represents a collection of raw data returned by a data source", Fields: gql.Fields{ "chartName": &gql.Field{ Description: "Detected chart name", Type: gql.String, }, "variables": &gql.Field{ Description: "query variables", Type: gql.NewList(variableType), }, "columns": &gql.Field{ Description: "Columns of the returned results", Type: gql.NewList(columnType), }, "rows": &gql.Field{ Description: "Rows of the returned results", Type: gql.NewList(rowType), }, }, IsTypeOf: func(p gql.IsTypeOfParams) bool { _, ok := p.Value.(results) return ok }, }) var queryResultType = gql.NewUnion(gql.UnionConfig{ Name: "QueryResult", Description: "QueryResult represents all the possible outcomes of a Query", Types: []*gql.Object{resultsType, queryErrorType}, ResolveType: func(p gql.ResolveTypeParams) *gql.Object { if _, ok := p.Value.(results); ok { return resultsType } if _, ok := p.Value.(queryError); ok { return queryErrorType } return nil }, }) var tableType = gql.NewObject(gql.ObjectConfig{ Name: "Table", Description: "A table of a data source", Fields: gql.Fields{ "name": &gql.Field{ Type: gql.NewNonNull(gql.String), }, }, }) var dataSourceType = gql.NewObject(gql.ObjectConfig{ Name: "DataSource", Description: "A DataSource represents a single source of data to analyze", Fields: gql.Fields{ "name": &gql.Field{ Type: gql.NewNonNull(gql.String), }, "tables": &gql.Field{ Type: gql.NewList(tableType), }, }, }) var questionType = gql.NewObject(gql.ObjectConfig{ Name: "Question", Fields: gql.Fields{ "id": &gql.Field{ Type: gql.String, }, "title": &gql.Field{ Type: gql.String, }, "description": &gql.Field{ Type: gql.String, }, "query": &gql.Field{ Type: gql.String, }, "createdAt": &gql.Field{ Type: gql.String, }, "updatedAt": &gql.Field{ Type: gql.String, }, "dataSource": &gql.Field{ Type: gql.String, }, "variables": &gql.Field{ Type: gql.NewList(variableType), }, "results": &gql.Field{ Type: queryResultType, }, }, })
pkg/api/graphql/types.go
0.523908
0.471953
types.go
starcoder
package slice // CopyBool creates a copy of a bool slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyBool(a []bool) []bool { return append(a[:0:0], a...) } // CopyByte creates a copy of a byte slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyByte(a []byte) []byte { return append(a[:0:0], a...) } // CopyComplex128 creates a copy of a complex128 slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyComplex128(a []complex128) []complex128 { return append(a[:0:0], a...) } // CopyComplex64 creates a copy of a complex64 slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyComplex64(a []complex64) []complex64 { return append(a[:0:0], a...) } // CopyFloat32 creates a copy of a float32 slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyFloat32(a []float32) []float32 { return append(a[:0:0], a...) } // CopyFloat64 creates a copy of a float64 slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyFloat64(a []float64) []float64 { return append(a[:0:0], a...) } // CopyInt creates a copy of an int slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyInt(a []int) []int { return append(a[:0:0], a...) } // CopyInt16 creates a copy of an int16 slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyInt16(a []int16) []int16 { return append(a[:0:0], a...) } // CopyInt32 creates a copy of an int32 slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyInt32(a []int32) []int32 { return append(a[:0:0], a...) } // CopyInt64 creates a copy of an int64 slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyInt64(a []int64) []int64 { return append(a[:0:0], a...) } // CopyInt8 creates a copy of an int8 slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyInt8(a []int8) []int8 { return append(a[:0:0], a...) } // CopyRune creates a copy of a rune slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyRune(a []rune) []rune { return append(a[:0:0], a...) } // CopyString creates a copy of a string slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyString(a []string) []string { return append(a[:0:0], a...) } // CopyUint creates a copy of a uint slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyUint(a []uint) []uint { return append(a[:0:0], a...) } // CopyUint16 creates a copy of a uint16 slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyUint16(a []uint16) []uint16 { return append(a[:0:0], a...) } // CopyUint32 creates a copy of a uint32 slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyUint32(a []uint32) []uint32 { return append(a[:0:0], a...) } // CopyUint64 creates a copy of a uint64 slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyUint64(a []uint64) []uint64 { return append(a[:0:0], a...) } // CopyUint8 creates a copy of a uint8 slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyUint8(a []uint8) []uint8 { return append(a[:0:0], a...) } // CopyUintptr creates a copy of a uintptr slice. // The resulting slice has the same elements as the original but the underlying array is different. // See https://github.com/go101/go101/wiki func CopyUintptr(a []uintptr) []uintptr { return append(a[:0:0], a...) }
copy.go
0.894081
0.821152
copy.go
starcoder
package matrix import ( "fmt" "log" "math" "math/rand" ) //Vector type type Vector struct { row []float64 } //NewVector returns a vector type func NewVector(slice []float64) Vector { return Vector{row: slice} } // PrintVector prints the vector components func PrintVector(vec Vector) { fmt.Println(vec.row) } //VecToArray returns a slice of vector elements. func VecToArray(vec Vector) []float64 { slice := make([]float64, len(vec.row)) for i := range vec.row { slice = append(slice, vec.row[i]) } return slice } //RandomVector returns a random valued vector. func RandomVector(size int) Vector { slice := make([]float64, size) for i := 0; i < size; i++ { slice = append(slice, rand.Float64()/0.3) } return NewVector(slice) } // InnerProduct returns the inner product of two vectors via the matrix. // Check the dotProduct function for a simplified dot product of two vectors. func InnerProduct(matrix Matrix, vector1, vector2 Vector) float64 { var product Vector for _, r := range matrix.slice { for i := 0; i < len(r); i++ { product.row[i] = r[i] * vector1.row[i] } } return vector2.DotProduct(product) } //NumberOfElements returns the number of elements. func (v Vector) NumberOfElements() int { return len(v.row) } // Slice returns vector.slice. // You can perform indexing with this method. func (v Vector) Slice() []float64 { return v.row } //DotProduct returns the dot product of two vectors. func (v Vector) DotProduct(v2 Vector) float64 { var sum float64 for i := 0; i < len(v.row); i++ { sum += v.row[i] * v2.row[i] } return sum } //ApplyMatrix returns the vector through a matrix transformation. func (v Vector) ApplyMatrix(matrix Matrix) Vector { var product Vector for _, r := range matrix.slice { for i := 0; i < len(r); i++ { product.row[i] = r[i] * v.row[i] } } return product } //Add returns an elementary operation on two vectors. func (v Vector) Add(v2 Vector) Vector { var resultVector Vector for i := 0; i < len(v.row); i++ { resultVector.row[i] = v.row[i] + v2.row[i] } return resultVector } //Substract returns an elementary operation on two vectors. func (v Vector) Substract(v2 Vector) Vector { var resultVector Vector for i := 0; i < len(v.row); i++ { resultVector.row[i] = v.row[i] - v2.row[i] } return resultVector } //AddMany takes a slice of vectors and outputs their sum. func (v Vector) AddMany(vectors []Vector) Vector { var resultVector Vector for _, vec := range vectors { for i := 0; i < len(v.row); i++ { resultVector.row[i] = v.row[i] + vec.row[i] } } return resultVector } //SubstractMany takes a slice of vectors and outputs their divergence. func (v Vector) SubstractMany(vectors []Vector) Vector { var resultVector Vector for _, vec := range vectors { for i := 0; i < len(v.row); i++ { resultVector.row[i] = v.row[i] - vec.row[i] } } return resultVector } // VecZeros returns a vector of zeros func VecZeros(size int) Vector { slc := make([]float64, size) for i := 0; i < size; i++ { slc = append(slc, 0) } return Vector{row: slc} } // VecOnes returns a vector of zeros func VecOnes(size int) Vector { slc := make([]float64, size) for i := 0; i < size; i++ { slc = append(slc, 1) } return Vector{row: slc} } // VecAllSameNumber returns a vector of zeros func VecAllSameNumber(size int, number float64) Vector { slc := make([]float64, size) for i := 0; i < size; i++ { slc = append(slc, number) } return Vector{row: slc} } //Map maps the vector by with the function func (v Vector) Map(f func(float64) float64) Vector { for i := range v.row { v.row[i] = f(v.row[i]) } return v } //GetLength returns the length of a vector. func (v Vector) GetLength() float64 { var result float64 for _, g := range v.row { result += math.Pow(g, 2) } return math.Sqrt(result) } //AngleBetween returns the angle between two vectors. func (v Vector) AngleBetween(v2 Vector) float64 { return math.Cos(v.DotProduct(v2) / (v.GetLength() * v2.GetLength())) } //ScalarProjection returns the scalar projection of v onto v2. func (v Vector) ScalarProjection(v2 Vector) float64 { x := v2.GetLength() * v.AngleBetween(v2) return x } //MultiplyByScalar operates by adding a scalar elementary. func (v Vector) MultiplyByScalar(scalar float64) Vector { for _, g := range v.row { g = g * scalar } return v } //VectorProjection returns the vector projection of v onto v2. func (v Vector) VectorProjection(v2 Vector) Vector { x := v.DotProduct(v2) y := v2.DotProduct(v2) return v.MultiplyByScalar(x / y) } //ChangingBasis returns the transformed vector if we were to change its basis vectors. //Similar to a simple matrix transformation but inputs are two basis vectors. //Basis vectors have to be perpendicular to each other in order to apply this transformation. //The function takes care of this for you by sending back an error func (v Vector) ChangingBasis(b1, b2 Vector) (Vector, error) { var newVector Vector var db1, db2 float64 if b1.AngleBetween(b2) != 0 { return Vector{}, fmt.Errorf("basis vectors have to be perpendicular") } db1 = v.DotProduct(b1) / math.Pow(b1.GetLength(), 2) db2 = v.DotProduct(b2) / math.Pow(b2.GetLength(), 2) newVector.row[0] = db1 newVector.row[1] = db2 return newVector, nil } //GramSchmidt function returns the concatenated matrix of orthogonal based vectors out of the vectors dataset. //Based on the Mathematics for Machine learning Specialization. func GramSchmidt(vectors []Vector) ([]Vector, error) { var normalizedvectors []Vector var xs []Vector for i, vector := range vectors { normalized := vectors[i-1].MultiplyByScalar(1 / vector.GetLength()) if i != 1 { s := vectors[i].DotProduct(normalized) x := normalized.MultiplyByScalar(s) xs = append(xs, x) normalizedvectors[i] = vectors[i].Substract(vectors[i].SubstractMany(xs)) } } return normalizedvectors, nil } //PageRank algorithm returns the probabilites of randomly ending up on either of the pages. //Page connections should be put inside the link matrix. func PageRank(linkMatrix Matrix, pages int) { slice := make([]float64, pages) for i := range slice { slice[i] = 1 / float64(pages) } initVector := Vector{row: slice} for i := 0; i < len(initVector.row); i++ { initVector = initVector.ApplyMatrix(linkMatrix) } } //CalculateEigenvectors2x2 returns the eigenvectors of the given 2x2 matrix func CalculateEigenvectors2x2(m Matrix) ([]Vector, error) { var vectors []Vector q := m.slice det := m.Find2x2Determinant() lambda1, lambda2 := Quadratic(1, q[0][0]+q[1][1], det) vec1 := []float64{lambda1, 0} vec2 := []float64{0, lambda2} vector1 := Vector{row: vec1} vector2 := Vector{row: vec2} vectors = append(vectors, vector1) vectors = append(vectors, vector2) return vectors, nil } //Quadratic takes a,b,c parameters of a quadratic equation as inputs and returns both solutions via the discriminant. func Quadratic(a, b, c float64) (float64, float64) { disc := math.Pow(b, 2) - 4*a*c if disc < 0 { log.Fatalf("The discriminant is negative. Therefore solutions will be complex numbers. ") } x1 := (-b + math.Sqrt(disc)) / 2 * a x2 := (-b - math.Sqrt(disc)) / 2 * a return x1, x2 }
vector.go
0.805861
0.567877
vector.go
starcoder
package event import ( "context" "reflect" "github.com/google/gapid/core/fault" "github.com/google/gapid/core/log" ) var ( contextType = reflect.TypeOf((*context.Context)(nil)).Elem() errorType = reflect.TypeOf((*error)(nil)).Elem() boolType = reflect.TypeOf(true) ) // checkSignature is an internal function for verifying a function signature matches the expected one. // It is special in that it allows functions parameterised by one of the types, either input or output. // You indicate the parameterised entry by having a nil for that type record, and the matching type is // returned from the fuction. // It is an error to try to parameterise on more than one, behaviour is undefined in that case. func checkSignature(ctx context.Context, f reflect.Type, in []reflect.Type, out []reflect.Type) (reflect.Type, error) { if !(f.Kind() == reflect.Func) { return nil, log.Errf(ctx, nil, "Expected a function. Got: %v", f) } if f.NumIn() != len(in) { return nil, log.Errf(ctx, nil, "Invalid argument count: %d", f.NumIn()) } if f.NumOut() != len(out) { return nil, log.Errf(ctx, nil, "Invalid return count: %v", f.NumOut()) } var res reflect.Type for i, t := range in { check := f.In(i) if t == nil { res = check } else if check != t { return nil, log.Errf(ctx, nil, "Incorrect parameter type: %v", check) } } for i, t := range out { check := f.Out(i) if t == nil { res = check } else if check != t { return nil, log.Errf(ctx, nil, "Incorrect return type: %v", check) } } return res, nil } func safeValue(v interface{}, t reflect.Type) reflect.Value { if v == nil { return reflect.Zero(t) } return reflect.ValueOf(v) } func safeObject(v reflect.Value) interface{} { if v.IsNil() { return nil } return v.Interface() } func funcToHandler(ctx context.Context, f reflect.Value) Handler { t, err := checkSignature(ctx, f.Type(), []reflect.Type{contextType, nil}, []reflect.Type{errorType}, ) if err != nil { log.F(ctx, "Checking handler signature. Error: %v", err) } return func(ctx context.Context, event interface{}) error { args := []reflect.Value{ reflect.ValueOf(ctx), safeValue(event, t), } if !args[1].Type().AssignableTo(t) { return log.Errf(ctx, nil, "Invalid event type: %v. Expected: %v", args[1].Type(), t) } result := f.Call(args) if !result[0].IsNil() { return fault.From(result[0].Interface()) } return nil } } func funcToProducer(ctx context.Context, f reflect.Value) Producer { _, err := checkSignature(ctx, f.Type(), []reflect.Type{contextType}, []reflect.Type{nil}, ) if err != nil { log.F(ctx, "Checking producer signature. Error: %v", err) } return func(ctx context.Context) interface{} { args := []reflect.Value{reflect.ValueOf(ctx)} return safeObject(f.Call(args)[0]) } } func funcToPredicate(ctx context.Context, f reflect.Value) Predicate { t, err := checkSignature(ctx, f.Type(), []reflect.Type{contextType, nil}, []reflect.Type{boolType}, ) if err != nil { log.F(ctx, "Checking handler signature. Error: %v", err) } return func(ctx context.Context, event interface{}) bool { args := []reflect.Value{reflect.ValueOf(ctx), safeValue(event, t)} if args[1].Type() != t { return false } result := f.Call(args) return result[0].Bool() } }
core/event/function.go
0.509032
0.40028
function.go
starcoder
// This file contains an implementation of IndexColumn which is // a storage for n-ngram tree nodes with the same depth (= position // within an n-gram) package column // MetadataWriter is used for writing metadata attributes // during indexing. It collects individual metadata // columns into a single object providing similar methods // (Get, Set, Extend, Size, Resize, Save). type MetadataWriter struct { dicts ArgsWriterList cols []AttrValColumn } func (mw *MetadataWriter) ForEachArg(fn func(i int, v *ArgsDictWriter, col AttrValColumn)) { for i := 0; i < len(mw.dicts); i++ { // we expect len(dicts) == len(cols) fn(i, mw.dicts[i], mw.cols[i]) } } func (mw *MetadataWriter) NumCols() int { return len(mw.dicts) } func (mw *MetadataWriter) Get(idx int) []AttrVal { ans := make([]AttrVal, len(mw.cols)) for i, v := range mw.cols { ans[i] = v.Get(idx) } return ans } func (mw *MetadataWriter) Set(idx int, val []AttrVal) { for i := 0; i < len(mw.cols); i++ { mw.cols[i].Set(idx, val[i]) } } func (mw *MetadataWriter) Extend(appendSize int) { for _, v := range mw.cols { v.Extend(appendSize) } } func (mw *MetadataWriter) Size() int { if len(mw.cols) > 0 { return mw.cols[0].Size() // we expect all the columns to have the same len/cap } return 0 } func (mw *MetadataWriter) Shrink(rightIdx int) { for _, v := range mw.cols { v.Shrink(rightIdx) } } func (mw *MetadataWriter) Save(dirPath string) error { for _, avc := range mw.cols { err := avc.Save(dirPath) if err != nil { return err } } for _, d := range mw.dicts { err := d.Save(dirPath) if err != nil { return err } } return nil } func NewMetadataWriter(attrs map[string]string) *MetadataWriter { cols := make([]AttrValColumn, len(attrs)) dicts := make([]*ArgsDictWriter, len(attrs)) i := 0 var err error for k, v := range attrs { cols[i], err = NewMetadataColumn(k, v, 0) // TODO size if err != nil { panic(err) } dicts[i] = NewArgsDictWriter(k) i++ } return &MetadataWriter{cols: cols, dicts: dicts} } // ----------------------------------------------------------------------- // MetadataReader is used for reading indexed // metadata attributes when in search mode. // It collects individual metadata columns // into a single object. type MetadataReader struct { dicts ArgsReaderList cols []AttrValColumn } func (mr *MetadataReader) LoadChunk(fromIdx int, toIdx int) { for _, v := range mr.cols { v.LoadChunk(fromIdx, toIdx) } } func (mr *MetadataReader) Get(idx int) []string { ans := make([]string, len(mr.cols)) for i, v := range mr.cols { ans[i] = mr.dicts[i].index[v.Get(idx)] } return ans } func LoadMetadataReader(dirPath string, attrNames []string) (*MetadataReader, error) { cols := make([]AttrValColumn, len(attrNames)) dicts := make([]*ArgsDictReader, len(attrNames)) for i, attrName := range attrNames { tmp, err := LoadMetadataColumn(attrName, dirPath) if err != nil { return nil, err } cols[i] = tmp var err2 error dicts[i], err2 = LoadArgsDict(dirPath, attrName) if err2 != nil { return nil, err2 } } return &MetadataReader{cols: cols, dicts: dicts}, nil }
index/column/metadata.go
0.53777
0.41401
metadata.go
starcoder
package drw import ( "github.com/jakubDoka/mlok/ggl" "github.com/jakubDoka/mlok/mat" ) type LineProcessor struct { Points []mat.Vec Indices ggl.Indices } func (l *LineProcessor) Process(g *Geom, ld LineDrawer, points ...mat.Vec) { if ld == nil { ld = Default } ld.Init(g.thickness) l.Indices.Clear() l.Points = l.Points[:0] ln := len(points) rl := ln - 2 if g.loop { rl++ } else { var e End e.Init(points[0], points[1], g.thickness) ld.Start(&e, l) } var e Edge for i := 0; i < rl; i++ { e.Init(points, g.thickness, i, ln) ld.Edge(&e, l) } if g.loop { e.Init(points, g.thickness, rl, ln) ld.Close(&e, l) } else { var e End e.Init(points[ln-1], points[ln-2], g.thickness) ld.End(&e, l) } } func (l *LineProcessor) AppendPoints(center mat.Vec, points ...mat.Vec) { l.Points = append(l.Points, points...) slice := l.Points[len(l.Points)-len(points):] for i := range slice { slice[i].AddE(center) } } func (l *LineProcessor) AppendIndices(indices ...uint32) { l.Indices = append(l.Indices, indices...) l.Indices[len(l.Indices)-len(indices):].Shift(uint32(len(l.Points))) } type RoundLine struct { LineDrawerBase Circle } func (r *RoundLine) Init(thickness float64) { r.Filled(thickness, 0, 0, AutoResolution(thickness, 0, 0, 1)) } func (r *RoundLine) Start(e *End, lp *LineProcessor) { lp.Indices = append(lp.Indices, r.Indices...) lp.AppendPoints(e.A, r.Base...) r.LineDrawerBase.Start(e, lp) } func (r *RoundLine) End(e *End, lp *LineProcessor) { r.LineDrawerBase.End(e, lp) lp.AppendIndices(r.Indices...) lp.AppendPoints(e.A, r.Base...) } func (r *RoundLine) Edge(e *Edge, lp *LineProcessor) { r.PreEdge(e, lp) lp.AppendIndices(r.Indices...) lp.AppendPoints(e.B, r.Base...) r.PostEnge(e, lp) } func (r *RoundLine) Close(e *Edge, lp *LineProcessor) { r.LineDrawerBase.Close(e, lp) lp.AppendIndices(r.Indices...) lp.AppendPoints(e.B, r.Base...) } type SharpLine struct{ LineDrawerBase } func (s *SharpLine) Start(e *End, lp *LineProcessor) { lp.Indices = append(lp.Indices, 0, 1, 2) s.AddEnd(e, lp) s.LineDrawerBase.Start(e, lp) } func (s *SharpLine) End(e *End, lp *LineProcessor) { s.LineDrawerBase.End(e, lp) l := uint32(len(lp.Points)) lp.Indices = append(lp.Indices, l-2, l-1, l) s.AddEnd(e, lp) } func (s *SharpLine) AddEnd(e *End, lp *LineProcessor) { lp.Points = append(lp.Points, e.A.Add(e.A.To(e.B1).Normal())) } func (s *SharpLine) Edge(e *Edge, lp *LineProcessor) { s.PreEdge(e, lp) l := uint32(len(lp.Points)) if e.Convex { lp.Indices = append(lp.Indices, l-2, l-1, l) } else { lp.Indices = append(lp.Indices, l-2, l-1, l+1) } s.PostEnge(e, lp) } func (s *SharpLine) Close(e *Edge, lp *LineProcessor) { s.LineDrawerBase.Close(e, lp) l := uint32(len(lp.Points)) if e.Convex { lp.Indices = append(lp.Indices, l-1, l-2, l-4) } else { lp.Indices = append(lp.Indices, l-1, l-2, l-3) } } type LineDrawerBase struct{} func (*LineDrawerBase) Init(thickness float64) {} func (*LineDrawerBase) Start(e *End, lp *LineProcessor) { lp.AppendIndices(LineIndicePatern...) lp.Points = append(lp.Points, e.B1, e.B2) } func (*LineDrawerBase) End(e *End, lp *LineProcessor) { lp.Points = append(lp.Points, e.B2, e.B1) } func (l *LineDrawerBase) Edge(e *Edge, lp *LineProcessor) { l.PreEdge(e, lp) l.PostEnge(e, lp) } func (*LineDrawerBase) PostEnge(e *Edge, lp *LineProcessor) { lp.AppendIndices(LineIndicePatern...) lp.Points = append(lp.Points, e.B3, e.B4) } func (*LineDrawerBase) PreEdge(e *Edge, lp *LineProcessor) { lp.Points = append(lp.Points, e.B1, e.B2) } func (l *LineDrawerBase) Close(e *Edge, lp *LineProcessor) { l.Edge(e, lp) ln := len(lp.Indices) lp.Indices[ln-1] = 0 lp.Indices[ln-2] = 1 lp.Indices[ln-4] = 1 } var LineIndicePatern = ggl.Indices{0, 1, 3, 0, 3, 2} type LineDrawer interface { Init(thickness float64) Start(*End, *LineProcessor) End(*End, *LineProcessor) Edge(*Edge, *LineProcessor) Close(*Edge, *LineProcessor) } // Line Modes var ( Default = &LineDrawerBase{} Sharp = &SharpLine{} // Round holds some inner state so if you are drawing on multiple threads, you need to create own instances Round = &RoundLine{} ) type End struct { A, B, BA, B1, B2 mat.Vec Thickness float64 } func (e *End) Init(a, b mat.Vec, thickness float64) { e.A, e.B, e.BA = a, b, b.To(a) nba := e.BA.Normal().Normalized().Scaled(thickness) e.B1, e.B2 = a.Sub(nba), a.Add(nba) } type Edge struct { End C, BC, B3, B4 mat.Vec Convex bool } func (e *Edge) Init(points []mat.Vec, thickness float64, i, ln int) { e.A, e.B, e.C = points[i], points[(i+1)%ln], points[(i+2)%ln] e.BA, e.BC = e.B.To(e.A), e.B.To(e.C) e.Convex = e.BA.Cross(e.BC) >= 0 nba, nbc := e.BA.Normal().Normalized().Scaled(thickness), e.BC.Normal().Normalized().Scaled(thickness) e.B1, e.B2, e.B3, e.B4 = e.B.Sub(nba), e.B.Add(nba), e.B.Add(nbc), e.B.Sub(nbc) }
ggl/drw/lines.go
0.530236
0.417628
lines.go
starcoder
package day14 import ( "fmt" ) // KnotHash is adapted from the day 10 challenge and returns a hash of the // given input. func KnotHash(input []byte) []byte { input = append(input, 17, 31, 73, 47, 23) A := make([]byte, 256) for i := 0; i < len(A); i++ { A[i] = byte(i) } var pos, skip, a, b int for r := 0; r < 64; r++ { for _, l := range input { for i := byte(0); i < l/2; i++ { a = (pos + int(i)) % len(A) b = (pos + int(l-i) - 1) % len(A) A[a], A[b] = A[b], A[a] } pos = (pos + int(l) + skip) % len(A) skip++ } } h := make([]byte, 16) for i := 0; i < 16; i++ { var b byte for j := 0; j < 16; j++ { b ^= A[(16*i)+j] } h[i] = b } return h } // A Grid is a bitmap representation of a disk which requires defragmentation. type Grid struct { Width int Data []byte } // NewGrid returns a grid of the given width and populates it with a hash of the // given input string. func NewGrid(n int, s string) *Grid { g := &Grid{ Width: n, Data: make([]byte, n*n/8), } for i := 0; i < n; i++ { b := KnotHash([]byte(fmt.Sprintf("%s-%d", s, i))) copy(g.Data[i*16:], b) } return g } // BitCount is my solution to Part One and returns the number of bits set in the // Grid. func (g *Grid) BitCount() int { count := 0 for i := 0; i < len(g.Data); i++ { for j := byte(0); j < 8; j++ { if g.Data[i]&(1<<j) != 0 { count++ } } } return count } // GroupCount is my solution to Part Two and returns the number of bit groups, // where all bits are adjacent to eachother. func (g *Grid) GroupCount() int { count := 0 for i := 0; i < len(g.Data)*8; i++ { count += g.squash(i) } return count } // squash returns 1 if the value at the given bit offset is not 0. The bit at // the given offset will be set to zero and this function applied recursively to // all of its adjacent neighbours, like a depth-first search. func (g *Grid) squash(i int) int { var b, m byte var o int b = g.Data[i/8] m = byte(1 << uint(7-(i%8))) if b&m == 0 { return 0 } g.Data[i/8] = b &^ m // above o = i - g.Width if o >= 0 { g.squash(o) } // right if i%g.Width < g.Width-1 { g.squash(i + 1) } // below o = i + g.Width if o < g.Width*g.Width { g.squash(o) } // left if i%g.Width > 0 { g.squash(i - 1) } return 1 }
go/2017/day14/day14.go
0.717903
0.403244
day14.go
starcoder
package svg func opDataToSVG(op *Op, sf *svgFlow, x0, y0, y1 int, ) (nsf *svgFlow, lsr *svgRect, ny0 int, xn, yn int) { var y int opW := maxTextWidth(op.Main) + 2*12 // text + padding opH := y1 - y0 for _, f := range op.Plugins { w := maxPluginWidth(f) opW = max(opW, w) } if sf.completedMerge != nil { x0 = sf.completedMerge.x0 y0 = sf.completedMerge.y0 ny0 = y0 opH = max(opH, sf.completedMerge.yn-y0) } lsr, y, xn, yn = outerOpToSVG(op.Main, opW, opH, sf, x0, y0) for _, f := range op.Plugins { y = pluginDataToSVG(f, xn-x0, sf, x0, y) } if len(op.Plugins) > 0 { y += 6 lsr.Height = max(lsr.Height+6, y-y0) yn = max(yn, y0+lsr.Height+2*6) } return sf, lsr, y0, xn, yn } func outerOpToSVG(r *Rect, w int, h int, sf *svgFlow, x0, y0 int, ) (svgMainRect *svgRect, y02 int, xn int, yn int) { x := x0 y := y0 + 6 h0 := len(r.Text)*24 + 6*2 h = max(h, h0) svgMainRect = &svgRect{ X: x, Y: y, Width: w, Height: h, IsPlugin: false, } sf.Rects = append(sf.Rects, svgMainRect) y += 6 for _, t := range r.Text { sf.Texts = append(sf.Texts, &svgText{ X: x + 12, Y: y + 24 - 6, Width: len(t) * 12, Text: t, }) y += 24 } return svgMainRect, y0 + 6 + h0, x + w, y0 + h + 2*6 } func pluginDataToSVG( f *Plugin, width int, sf *svgFlow, x0, y0 int, ) (yn int) { x := x0 y := y0 y += 3 if f.Title != "" { sf.Texts = append(sf.Texts, &svgText{ X: x + 6, Y: y + 24 - 6, Width: (len(f.Title) + 1) * 12, Text: f.Title + ":", }) y += 24 } for i, r := range f.Rects { if i > 0 || f.Title != "" { sf.Lines = append(sf.Lines, &svgLine{ X1: x0, Y1: y, X2: x0 + width, Y2: y, }) y += 3 } for _, t := range r.Text { sf.Texts = append(sf.Texts, &svgText{ X: x + 6, Y: y + 24 - 6, Width: len(t) * 12, Text: t, }) y += 24 } } y += 3 sf.Rects = append(sf.Rects, &svgRect{ X: x0, Y: y0, Width: width, Height: y - y0, IsPlugin: true, }) return y } func maxPluginWidth(f *Plugin) int { width := 0 if f.Title != "" { width = (len(f.Title)+1)*12 + 2*6 // title text and padding } for _, r := range f.Rects { w := maxTextWidth(r) width = max(width, w+2*6) } return width } func maxTextWidth(r *Rect) int { return maxLen(r.Text) * 12 } func maxLen(ss []string) int { m := 0 for _, s := range ss { m = max(m, len(s)) } return m }
svg/op.go
0.549399
0.540863
op.go
starcoder
package day6 import ( "ryepup/advent2021/utils" ) /* The sea floor is getting steeper. Maybe the sleigh keys got carried this way? A massive school of glowing lanternfish swims past. They must spawn quickly to reach such large numbers - maybe exponentially quickly? You should model their growth rate to be sure. Although you know nothing about this specific species of lanternfish, you make some guesses about their attributes. Surely, each lanternfish creates a new lanternfish once every 7 days. However, this process isn't necessarily synchronized between every lanternfish - one lanternfish might have 2 days left until it creates another lanternfish, while another might have 4. So, you can model each fish as a single number that represents the number of days until it creates a new lanternfish. Furthermore, you reason, a new lanternfish would surely need slightly longer before it's capable of producing more lanternfish: two more days for its first cycle. So, suppose you have a lanternfish with an internal timer value of 3: After one day, its internal timer would become 2. After another day, its internal timer would become 1. After another day, its internal timer would become 0. After another day, its internal timer would reset to 6, and it would create a new lanternfish with an internal timer of 8. After another day, the first lanternfish would have an internal timer of 5, and the second lanternfish would have an internal timer of 7. A lanternfish that creates a new fish resets its timer to 6, not 7 (because 0 is included as a valid timer value). The new lanternfish starts with an internal timer of 8 and does not start counting down until the next day. Realizing what you're trying to do, the submarine automatically produces a list of the ages of several hundred nearby lanternfish (your puzzle input). For example, suppose you were given the following list: 3,4,3,1,2 This list means that the first fish has an internal timer of 3, the second fish has an internal timer of 4, and so on until the fifth fish, which has an internal timer of 2. Simulating these fish over several days would proceed as follows: Initial state: 3,4,3,1,2 After 1 day: 2,3,2,0,1 After 2 days: 1,2,1,6,0,8 After 3 days: 0,1,0,5,6,7,8 After 4 days: 6,0,6,4,5,6,7,8,8 After 5 days: 5,6,5,3,4,5,6,7,7,8 After 6 days: 4,5,4,2,3,4,5,6,6,7 After 7 days: 3,4,3,1,2,3,4,5,5,6 After 8 days: 2,3,2,0,1,2,3,4,4,5 After 9 days: 1,2,1,6,0,1,2,3,3,4,8 After 10 days: 0,1,0,5,6,0,1,2,2,3,7,8 After 11 days: 6,0,6,4,5,6,0,1,1,2,6,7,8,8,8 After 12 days: 5,6,5,3,4,5,6,0,0,1,5,6,7,7,7,8,8 After 13 days: 4,5,4,2,3,4,5,6,6,0,4,5,6,6,6,7,7,8,8 After 14 days: 3,4,3,1,2,3,4,5,5,6,3,4,5,5,5,6,6,7,7,8 After 15 days: 2,3,2,0,1,2,3,4,4,5,2,3,4,4,4,5,5,6,6,7 After 16 days: 1,2,1,6,0,1,2,3,3,4,1,2,3,3,3,4,4,5,5,6,8 After 17 days: 0,1,0,5,6,0,1,2,2,3,0,1,2,2,2,3,3,4,4,5,7,8 After 18 days: 6,0,6,4,5,6,0,1,1,2,6,0,1,1,1,2,2,3,3,4,6,7,8,8,8,8 Each day, a 0 becomes a 6 and adds a new 8 to the end of the list, while each other number decreases by 1 if it was present at the start of the day. In this example, after 18 days, there are a total of 26 fish. After 80 days, there would be a total of 5934. Find a way to simulate lanternfish. How many lanternfish would there be after 80 days? */ func Part1(path string) (int, error) { return runFishSim(path, 80) } /* store population as a map of age -> # of fish Modeling as individual objects took too much memory */ type population map[int]int func runFishSim(path string, steps int) (int, error) { fishies, err := parseFish(path) if err != nil { return 0, err } for i := 0; i < steps; i++ { nextPopulation := make(population) for age, fish := range fishies { if age == 0 { nextPopulation[6] += fish nextPopulation[8] += fish } else { nextPopulation[age-1] += fish } } fishies = nextPopulation } total := 0 for _, fish := range fishies { total += fish } return total, nil } func parseFish(path string) (population, error) { ages, err := utils.ReadIntCsv(path) if err != nil { return nil, err } results := make(population) for _, age := range ages { results[age]++ } return results, nil }
day6/part1.go
0.596316
0.53959
part1.go
starcoder
package godate import ( "math" "strconv" "strings" "time" ) type goDate struct { Time time.Time TimeZone *time.Location FirstDayOfWeek time.Weekday } //IsBefore checks if the goDate is before the passed goDate func (d *goDate) IsBefore(compare *goDate) bool { return d.Time.Before(compare.Time) } //IsAfter checks if the goDate is before the passed goDate func (d *goDate) IsAfter(compare *goDate) bool { return d.Time.After(compare.Time) } //Sub subtracts the 'count' from the goDate using the unit passed func (d goDate) Sub(count int, unit Unit) *goDate { return d.Add(-count, unit) } //Add adds the 'count' from the goDate using the unit passed func (d goDate) Add(count int, unit Unit) *goDate { d.Time = d.Time.Add(time.Duration(unit * Unit(count))) return &d } //Get the difference as a duration type func (d *goDate) DifferenceAsDuration(compare *goDate) time.Duration { return d.Time.Sub(compare.Time) } //Difference Returns the difference between the Godate and another in the specified unit //If the difference is negative then the 'compare' date occurs after the date //Else it occurs before the the date func (d goDate) Difference(compare *goDate, unit Unit) int { difference := d.DifferenceAsFloat(compare, unit) return int(difference) } //Get the difference as a float func (d goDate) DifferenceAsFloat(compare *goDate, unit Unit) float64 { duration := d.DifferenceAsDuration(compare) return float64(duration) / float64(time.Duration(unit)) } //Gets the difference between the relative to the date value in the form of //1 month before //1 month after func (d goDate) DifferenceForHumans(compare *goDate) string { differenceString, differenceInt := d.AbsDifferenceForHumans(compare) if differenceInt > 0 { return differenceString + " before" } else { return differenceString + " after" } } //Gets the difference between the relative to current time value in the form of //1 month ago //1 month from now func (d goDate) DifferenceFromNowForHumans() string { now := Now(d.TimeZone) differenceString, differenceInt := now.AbsDifferenceForHumans(&d) if differenceInt > 0 { return differenceString + " ago" } else { return differenceString + " from now" } } //Get the abs difference relative to compare time in the form //1 month //2 days func (d goDate) AbsDifferenceForHumans(compare *goDate) (string, int) { sentence := make([]string, 2, 2) duration := Unit(math.Abs(float64(d.DifferenceAsDuration(compare)))) var unit Unit if duration >= YEAR { unit = YEAR } else if duration < YEAR && duration >= MONTH { unit = MONTH } else if duration < MONTH && duration >= WEEK { unit = WEEK } else if duration < WEEK && duration >= DAY { unit = DAY } else if duration < DAY && duration >= HOUR { unit = HOUR } else if duration < HOUR && duration >= MINUTE { unit = MINUTE } else { unit = SECOND } difference := d.Difference(compare, unit) sentence[0] = strconv.Itoa(int(math.Abs(float64(difference)))) sentence[1] = unit.String() if difference == 1 || difference == -1 { sentence[1] = strings.TrimSuffix(sentence[1], "s") } return strings.Join(sentence, " "), difference } //MidDay gets the midday time usually 12:00 PM of the current day func (d *goDate) MidDay() *goDate { y, m, day := d.Time.Date() return &goDate{time.Date(y, m, day, 12, 0, 0, 0, d.TimeZone), d.TimeZone,0} } //ToDateTimeString Formats and returns the goDate in the form 2006-01-02 15:04:05 func (d *goDate) ToDateTimeString() string{ return d.Format("2006-01-02 15:04:05") } //ToDateString Formats and returns the goDate in the form 2006-01-02 func (d *goDate) ToDateString() string{ return d.Format("2006-01-02") } //ToFormattedDateString Formats and returns the goDate in the form Jan 02, 2006 func (d *goDate) ToFormattedDateString() string{ return d.Format("Jan 02, 2006") } //ToTimeString Formats and returns the goDate in the form 15:04:05 func (d *goDate) ToTimeString() string{ return d.Format("15:04:05") } //ToDayTimeString Formats and returns the goDate in the form Mon, Jan 2, 2006 03:04 PM func (d *goDate) ToDayTimeString() string{ return d.Format("Mon, Jan 2, 2006 03:04 PM") } //Check if this is the weekend func (d *goDate) IsWeekend() bool { day := d.Time.Weekday() return day == time.Saturday || day == time.Sunday } func (d *goDate) Format(format string) string{ return d.Time.Format(format) } func (d *goDate) SetFirstDay(weekday time.Weekday){ d.FirstDayOfWeek = weekday } func (d goDate) String() string{ return d.Format("Mon Jan 2 15:04:05 -0700 MST 2006") }
godate.go
0.809615
0.626181
godate.go
starcoder
package moreland import ( "image/color" "math" ) // rgb represents a physically linear RGB color. type rgb struct { R, G, B float64 } // cieXYZ returns a CIE XYZ color representation of the receiver. func (c rgb) cieXYZ() cieXYZ { return cieXYZ{ X: 0.4124*c.R + 0.3576*c.G + 0.1805*c.B, Y: 0.2126*c.R + 0.7152*c.G + 0.0722*c.B, Z: 0.0193*c.R + 0.1192*c.G + 0.9505*c.B, } } // sRGBA returns an sRGB color representation of the receiver using the // provided alpha which must be in [0, 1]. func (c rgb) sRGBA(alpha float64) sRGBA { // f converts from a linear RGB component to an sRGB component. f := func(v float64) float64 { if v > 0.0031308 { return 1.055*math.Pow(v, 1/2.4) - 0.055 } return 12.92 * v } return sRGBA{ R: f(c.R), G: f(c.G), B: f(c.B), A: alpha, } } // cieXYZ represents a color in CIE XYZ space. // Y must be in the range [0,1]. X and Z must be greater than 0. type cieXYZ struct { X, Y, Z float64 } // rgb returns a linear RGB representation of the receiver. func (c cieXYZ) rgb() rgb { return rgb{ R: c.X*3.2406 + c.Y*-1.5372 + c.Z*-0.4986, G: c.X*-0.9689 + c.Y*1.8758 + c.Z*0.0415, B: c.X*0.0557 + c.Y*-0.204 + c.Z*1.057, } } // cieLAB returns a CIELAB color representation of the receiver. func (c cieXYZ) cieLAB() cieLAB { // f is an intermediate step in converting from CIE XYZ to CIE LAB. f := func(v float64) float64 { if v > 0.008856 { return math.Pow(v, 1.0/3.0) } return 7.787*v + 16.0/116.0 } tempX := f(c.X / 0.9505) tempY := f(c.Y) tempZ := f(c.Z / 1.089) return cieLAB{ L: (116.0 * tempY) - 16.0, A: 500.0 * (tempX - tempY), B: 200 * (tempY - tempZ), } } // sRGBA represents a color within the sRGB color space, with an alpha channel // but not premultiplied. All values must be in the range [0,1]. type sRGBA struct { R, G, B, A float64 } // rgb returns a linear RGB representation of the receiver. func (c sRGBA) rgb() rgb { // f converts from an sRGB component to a linear RGB component. f := func(v float64) float64 { if v > 0.04045 { return math.Pow((v+0.055)/1.055, 2.4) } return v / 12.92 } return rgb{ R: f(c.R), G: f(c.G), B: f(c.B), } } // RGBA implements the color.Color interface. func (c sRGBA) RGBA() (r, g, b, a uint32) { return uint32(c.R * c.A * 0xffff), uint32(c.G * c.A * 0xffff), uint32(c.B * c.A * 0xffff), uint32(c.A * 0xffff) } // cieLAB returns a CIE LAB representation of the receiver. func (c sRGBA) cieLAB() cieLAB { return c.rgb().cieXYZ().cieLAB() } // colorTosRGBA converts a color to an sRGBA. func colorTosRGBA(c color.Color) sRGBA { r, g, b, a := c.RGBA() if a == 0 { return sRGBA{} } return sRGBA{ R: float64(r) / float64(a), G: float64(g) / float64(a), B: float64(b) / float64(a), A: float64(a) / 0xffff, } } // clamp forces all channels in c to be within the range [0, 1]. func (c *sRGBA) clamp() { if c.R > 1 { c.R = 1 } if c.G > 1 { c.G = 1 } if c.B > 1 { c.B = 1 } if c.A > 1 { c.A = 1 } if c.R < 0 { c.R = 0 } if c.G < 0 { c.G = 0 } if c.B < 0 { c.B = 0 } if c.A < 0 { c.A = 0 } } // cieLAB represents a color in CIE LAB space. // L must be in the range [0, 100]. type cieLAB struct { L, A, B float64 } // sRGBA return a linear RGB color representation of the receiver using the // provided alpha which must be in [0, 1]. func (c cieLAB) sRGBA(alpha float64) sRGBA { return c.cieXYZ().rgb().sRGBA(alpha) } // cieXYZ returns a CIE XYZ color representation of the receiver. func (c cieLAB) cieXYZ() cieXYZ { // f is an intermediate step in converting from CIE LAB to CIE XYZ. f := func(v float64) float64 { const ( xlim = 0.008856 a = 7.787 b = 16. / 116. ylim = a*xlim + b ) if v > ylim { return v * v * v } return (v - b) / a } // Reference white-point D65 const xn, yn, zn = 0.95047, 1.0, 1.08883 return cieXYZ{ X: xn * f((c.A/500)+(c.L+16)/116), Y: yn * f((c.L+16)/116), Z: zn * f((c.L+16)/116-(c.B/200)), } } // MSH returns an MSH color representation of the receiver. func (c cieLAB) MSH() msh { m := math.Pow(c.L*c.L+c.A*c.A+c.B*c.B, 0.5) return msh{ M: m, S: math.Acos(c.L / m), H: math.Atan2(c.B, c.A), } } // MSH represents a color in Magnitude-Saturation-Hue color space. type msh struct { M, S, H float64 } // colorToMSH converts a color to MSH space. // TODO: If msh ever becomes exported, change this to implment color.Model func colorToMSH(c color.Color) msh { return colorTosRGBA(c).cieLAB().MSH() } // cieLAB returns a CIELAB representation of the receiver. func (c msh) cieLAB() cieLAB { return cieLAB{ L: c.M * math.Cos(c.S), A: c.M * math.Sin(c.S) * math.Cos(c.H), B: c.M * math.Sin(c.S) * math.Sin(c.H), } } // RGBA implements the color.Color interface. func (c msh) RGBA() (r, g, b, a uint32) { return c.cieLAB().sRGBA(1.0).RGBA() } // hueTwist returns the hue twist between color c and converge magnitude // convergeM. func hueTwist(c msh, convergeM float64) float64 { signH := c.H / math.Abs(c.H) return signH * c.S * math.Sqrt(convergeM*convergeM-c.M*c.M) / (c.M * math.Sin(c.S)) }
palette/moreland/convert.go
0.865082
0.481027
convert.go
starcoder
package slicemultimap import multimap "github.com/jwangsadinata/go-multimap" // MultiMap holds the elements in go's native map. type MultiMap struct { m map[interface{}][]interface{} } // New instantiates a new multimap. func New() *MultiMap { return &MultiMap{m: make(map[interface{}][]interface{})} } // Get searches the element in the multimap by key. // It returns its value or nil if key is not found in multimap. // Second return parameter is true if key was found, otherwise false. func (m *MultiMap) Get(key interface{}) (values []interface{}, found bool) { values, found = m.m[key] return } // Put stores a key-value pair in this multimap. func (m *MultiMap) Put(key interface{}, value interface{}) { m.m[key] = append(m.m[key], value) } // PutAll stores a key-value pair in this multimap for each of the values, all using the same key key. func (m *MultiMap) PutAll(key interface{}, values []interface{}) { for _, value := range values { m.Put(key, value) } } // Contains returns true if this multimap contains at least one key-value pair with the key key and the value value. func (m *MultiMap) Contains(key interface{}, value interface{}) bool { values, found := m.m[key] for _, v := range values { if v == value { return true && found } } return false && found } // ContainsKey returns true if this multimap contains at least one key-value pair with the key key. func (m *MultiMap) ContainsKey(key interface{}) (found bool) { _, found = m.m[key] return } // ContainsValue returns true if this multimap contains at least one key-value pair with the value value. func (m *MultiMap) ContainsValue(value interface{}) bool { for _, values := range m.m { for _, v := range values { if v == value { return true } } } return false } // Remove removes a single key-value pair from this multimap, if such exists. func (m *MultiMap) Remove(key interface{}, value interface{}) { values, found := m.m[key] if found { for i, v := range values { if v == value { m.m[key] = append(values[:i], values[i+1:]...) } } } if len(m.m[key]) == 0 { delete(m.m, key) } } // RemoveAll removes all values associated with the key from the multimap. func (m *MultiMap) RemoveAll(key interface{}) { delete(m.m, key) } // Empty returns true if multimap does not contain any key-value pairs. func (m *MultiMap) Empty() bool { return m.Size() == 0 } // Size returns number of key-value pairs in the multimap. func (m *MultiMap) Size() int { size := 0 for _, value := range m.m { size += len(value) } return size } // Keys returns a view collection containing the key from each key-value pair in this multimap. // This is done without collapsing duplicates. func (m *MultiMap) Keys() []interface{} { keys := make([]interface{}, m.Size()) count := 0 for key, value := range m.m { for range value { keys[count] = key count++ } } return keys } // KeySet returns all distinct keys contained in this multimap. func (m *MultiMap) KeySet() []interface{} { keys := make([]interface{}, len(m.m)) count := 0 for key := range m.m { keys[count] = key count++ } return keys } // Values returns all values from each key-value pair contained in this multimap. // This is done without collapsing duplicates. (size of Values() = MultiMap.Size()). func (m *MultiMap) Values() []interface{} { values := make([]interface{}, m.Size()) count := 0 for _, vs := range m.m { for _, value := range vs { values[count] = value count++ } } return values } // Entries view collection of all key-value pairs contained in this multimap. // The return type is a slice of multimap.Entry instances. // Retrieving the key and value from the entries result will be as trivial as: // - var entry = m.Entries()[0] // - var key = entry.Key // - var value = entry.Value func (m *MultiMap) Entries() []multimap.Entry { entries := make([]multimap.Entry, m.Size()) count := 0 for key, values := range m.m { for _, value := range values { entries[count] = multimap.Entry{Key: key, Value: value} count++ } } return entries } // Clear removes all elements from the map. func (m *MultiMap) Clear() { m.m = make(map[interface{}][]interface{}) }
vendor/github.com/jwangsadinata/go-multimap/slicemultimap/slicemultimap.go
0.818954
0.445288
slicemultimap.go
starcoder
package tfimage // Modified from github.com/fogleman/gg // Oct 28, 2019 // <NAME> and Contributors // LICENSE: MIT import ( "math" "golang.org/x/image/math/f64" ) // Matrix - type Matrix struct { XX, YX, XY, YY, X0, Y0 float64 } // NewMatrix - Create a new Matrix func NewMatrix() Matrix { return Matrix{ 1, 0, 0, 1, 0, 0, } } // Translate New Matrix by x and y func Translate(x, y float64) Matrix { return Matrix{ 1, 0, 0, 1, x, y, } } // Scale New Matrix by x and y func Scale(x, y float64) Matrix { return Matrix{ x, 0, 0, y, 0, 0, } } // Rotate New Matrix by x and y func Rotate(angle float64) Matrix { c := math.Cos(angle) s := math.Sin(angle) return Matrix{ c, s, -s, c, 0, 0, } } // Shear New Matrix by x and y func Shear(x, y float64) Matrix { return Matrix{ 1, y, x, 1, 0, 0, } } // Multiply Matrix and another Matrix func (m Matrix) Multiply(b Matrix) Matrix { return Matrix{ m.XX*b.XX + m.YX*b.XY, m.XX*b.YX + m.YX*b.YY, m.XY*b.XX + m.YY*b.XY, m.XY*b.YX + m.YY*b.YY, m.X0*b.XX + m.Y0*b.XY + b.X0, m.X0*b.YX + m.Y0*b.YY + b.Y0, } } // TransformVector using a Matrix and x and y func (m Matrix) TransformVector(x, y float64) (tx, ty float64) { tx = m.XX*x + m.XY*y ty = m.YX*x + m.YY*y return } // TransformPoint using a Matrix and x and y func (m Matrix) TransformPoint(x, y float64) (tx, ty float64) { tx = m.XX*x + m.XY*y + m.X0 ty = m.YX*x + m.YY*y + m.Y0 return } // Translate a Matrix using x and y func (m Matrix) Translate(x, y float64) Matrix { return Translate(x, y).Multiply(m) } // Scale a Matrix using x and y func (m Matrix) Scale(x, y float64) Matrix { return Scale(x, y).Multiply(m) } // AdjustScale - func (m Matrix) AdjustScale(scale float64) Matrix { m.XX *= scale m.XY *= scale m.YX *= scale m.YY *= scale return m } // RotationMatrix2D creates a Rotation and Transformation Matrix. // This is similiar to OpenCV's function. // Angle in Radians func RotationMatrix2D(centerX, centerY float64, angle, scale float64) Matrix { a := scale * math.Cos(angle) b := scale * math.Sin(angle) return Matrix{ a, -b, b, a, (1-a)*centerX - b*centerY, b*centerX + (1-a)*centerY, } } // AdjustPosition adjust position of the matrix by x and y func (m *Matrix) AdjustPosition(x, y float64) { m.X0 += x m.Y0 += y } // Rotate a Matrix using x and y func (m Matrix) Rotate(angle float64) Matrix { return Rotate(angle).Multiply(m) } // Shear a Matrix using x and y func (m Matrix) Shear(x, y float64) Matrix { return Shear(x, y).Multiply(m) } func (m Matrix) ToAffineMatrix() f64.Aff3 { return f64.Aff3{m.XX, m.XY, m.X0, m.YX, m.YY, m.Y0} }
matrix.go
0.820829
0.680695
matrix.go
starcoder
package parser import ( "fmt" "go/ast" "strconv" "github.com/switchupcb/copygen/cli/models" ) type parsedTypes struct { fromTypes []models.Type toTypes []models.Type } // parseTypes parses an ast.Field (of type func) for to-types and from-types. func (p *Parser) parseTypes(function *ast.Field, options []Option) (parsedTypes, error) { var result parsedTypes fn, ok := function.Type.(*ast.FuncType) if !ok { return result, fmt.Errorf("an error occurred parsing the types of function %v at Line %d", parseMethodForName(function), p.Fileset.Position(function.Pos()).Line) } fromTypes, err := p.parseFieldList(fn.Params.List, options) // (incoming) parameters "non-nil" if err != nil { return result, err } var toTypes []models.Type if fn.Results != nil { toTypes, err = p.parseFieldList(fn.Results.List, options) // (outgoing) results "or nil" if err != nil { return result, err } } if len(fromTypes) == 0 { return result, fmt.Errorf("function %v at Line %d has no types to copy from", parseMethodForName(function), p.Fileset.Position(function.Pos()).Line) } else if len(toTypes) == 0 { return result, fmt.Errorf("function %v at Line %d has no types to copy to", parseMethodForName(function), p.Fileset.Position(function.Pos()).Line) } // assign variable names and determine the definition and sub-fields of each type paramMap := make(map[string]bool) for i := 0; i < len(fromTypes); i++ { fromTypes[i].Field.VariableName = createVariable(paramMap, "f"+fromTypes[i].Field.Name, 0) } for i := 0; i < len(toTypes); i++ { toTypes[i].Field.VariableName = createVariable(paramMap, "t"+toTypes[i].Field.Name, 0) } result.fromTypes = fromTypes result.toTypes = toTypes return result, nil } // parseFieldList parses an Abstract Syntax Tree field list for a type's fields. func (p *Parser) parseFieldList(fieldlist []*ast.Field, options []Option) ([]models.Type, error) { types := make([]models.Type, 0, len(fieldlist)) for _, astfield := range fieldlist { field, err := p.parseTypeField(astfield, options) if err != nil { return nil, err } types = append(types, models.Type{Field: field}) } return types, nil } // parseTypeField parses a function *ast.Field into a field model. func (p *Parser) parseTypeField(field *ast.Field, options []Option) (*models.Field, error) { parsed := astParseFieldName(field) if parsed.name == "" { return nil, fmt.Errorf("unexpected field expression %v in the Abstract Syntax Tree", field) } typefield, err := p.SearchForField(&FieldSearch{ DecFile: p.SetupFile, Import: "file=" + p.Setpath, Package: parsed.pkg, Name: parsed.name, Definition: "", Options: options, Parent: nil, cache: make(map[string]bool), }) if err != nil { return nil, fmt.Errorf("an error occurred while searching for the top-level Field %q of package %q.\n%v", parsed.name, parsed.pkg, err) } typefield.Pointer = parsed.ptr return typefield, nil } // createVariable generates a valid variable name for a 'set' of parameters. func createVariable(parameters map[string]bool, typename string, occurrence int) string { if occurrence < 0 { createVariable(parameters, typename, 0) } varName := typename[:2] if occurrence > 0 { varName += strconv.Itoa(occurrence + 1) } if _, exists := parameters[varName]; exists { createVariable(parameters, typename, occurrence+1) } return varName }
cli/parser/type.go
0.585575
0.422386
type.go
starcoder
package kafka import "go.k6.io/k6/stats" var ( ReaderDials = stats.New("kafka.reader.dial.count", stats.Counter) ReaderFetches = stats.New("kafka.reader.fetches.count", stats.Counter) ReaderMessages = stats.New("kafka.reader.message.count", stats.Counter) ReaderBytes = stats.New("kafka.reader.message.bytes", stats.Counter, stats.Data) ReaderRebalances = stats.New("kafka.reader.rebalance.count", stats.Counter) ReaderTimeouts = stats.New("kafka.reader.timeouts.count", stats.Counter) ReaderErrors = stats.New("kafka.reader.error.count", stats.Counter) ReaderDialTime = stats.New("kafka.reader.dial.seconds", stats.Trend, stats.Time) ReaderReadTime = stats.New("kafka.reader.read.seconds", stats.Trend, stats.Time) ReaderWaitTime = stats.New("kafka.reader.wait.seconds", stats.Trend, stats.Time) ReaderFetchSize = stats.New("kafka.reader.fetch.size", stats.Counter) ReaderFetchBytes = stats.New("kafka.reader.fetch.bytes", stats.Counter, stats.Data) ReaderOffset = stats.New("kafka.reader.offset", stats.Gauge) ReaderLag = stats.New("kafka.reader.lag", stats.Gauge) ReaderMinBytes = stats.New("kafka.reader.fetch_bytes.min", stats.Gauge) ReaderMaxBytes = stats.New("kafka.reader.fetch_bytes.max", stats.Gauge) ReaderMaxWait = stats.New("kafka.reader.fetch_wait.max", stats.Gauge, stats.Time) ReaderQueueLength = stats.New("kafka.reader.queue.length", stats.Gauge) ReaderQueueCapacity = stats.New("kafka.reader.queue.capacity", stats.Gauge) WriterDials = stats.New("kafka.writer.dial.count", stats.Counter) WriterWrites = stats.New("kafka.writer.write.count", stats.Counter) WriterMessages = stats.New("kafka.writer.message.count", stats.Counter) WriterBytes = stats.New("kafka.writer.message.bytes", stats.Counter, stats.Data) WriterRebalances = stats.New("kafka.writer.rebalance.count", stats.Counter) WriterErrors = stats.New("kafka.writer.error.count", stats.Counter) WriterDialTime = stats.New("kafka.writer.dial.seconds", stats.Trend, stats.Time) WriterWriteTime = stats.New("kafka.writer.write.seconds", stats.Trend, stats.Time) WriterWaitTime = stats.New("kafka.writer.wait.seconds", stats.Trend, stats.Time) WriterRetries = stats.New("kafka.writer.retries.count", stats.Counter) WriterBatchSize = stats.New("kafka.writer.batch.size", stats.Counter) WriterBatchBytes = stats.New("kafka.writer.batch.bytes", stats.Counter, stats.Data) WriterMaxAttempts = stats.New("kafka.writer.attempts.max", stats.Gauge) WriterMaxBatchSize = stats.New("kafka.writer.batch.max", stats.Gauge) WriterBatchTimeout = stats.New("kafka.writer.batch.timeout", stats.Gauge, stats.Time) WriterReadTimeout = stats.New("kafka.writer.read.timeout", stats.Gauge, stats.Time) WriterWriteTimeout = stats.New("kafka.writer.write.timeout", stats.Gauge, stats.Time) WriterRebalanceInterval = stats.New("kafka.writer.rebalance.interval", stats.Gauge, stats.Time) WriterRequiredAcks = stats.New("kafka.writer.acks.required", stats.Gauge) WriterAsync = stats.New("kafka.writer.async", stats.Rate) WriterQueueLength = stats.New("kafka.writer.queue.length", stats.Gauge) WriterQueueCapacity = stats.New("kafka.writer.queue.capacity", stats.Gauge) )
stats.go
0.52074
0.517266
stats.go
starcoder
package forecast import "math" type weighted struct { value float64 weight float64 rate float64 } func (w *weighted) get() float64 { return w.value } func (w *weighted) observe(y float64) { if math.IsNaN(y) { w.skip() return } if w.weight == 0 || math.IsNaN(w.value) || math.IsInf(w.value, 0) { // Special case to prevent 'NaN' w.value = y w.weight = w.rate return } w.weight *= 1 - w.rate w.value = (w.value*w.weight + y*w.rate) / (w.weight + w.rate) w.weight += w.rate } func (w *weighted) boostAdd(dy float64) { if math.IsNaN(dy) { return } w.value += dy } func (w *weighted) skip() { w.weight *= 1 - w.rate } func newWeighted(rate float64) *weighted { return &weighted{ value: 0, weight: 0, rate: rate, } } type cycle struct { season []*weighted } func (c cycle) index(i int) int { return (i%len(c.season) + len(c.season)) % len(c.season) } func (c cycle) get(i int) float64 { return c.season[c.index(i)].get() } func (c cycle) observe(i int, v float64) { c.season[c.index(i)].observe(v) } func (c cycle) skip(i int) { c.season[c.index(i)].skip() } func newCycle(rate float64, n int) cycle { c := make([]*weighted, n) for i := range c { c[i] = newWeighted(rate) } return cycle{ season: c, } } // RollingMultiplicativeHoltWinters approximate the given input using the Holt-Winters model by performing exponential averaging on the HW parameters. // It scales 'levelLearningRate' and 'trendLearningRate' by the 'period'. // That is, if you double the period, it will take twice as long as before for the level and trend parameters to update. // This makes it easier to use with varying period values. func RollingMultiplicativeHoltWinters(ys []float64, period int, levelLearningRate float64, trendLearningRate float64, seasonalLearningRate float64) []float64 { // We'll interpret the rates as "the effective change per whole period" (so the seasonal learning rate is unchanged). // The intensity of the old value after n iterations is (1-rate)^n. We want to find rate' such that // 1 - rate = (1 - rate')^n // so // 1 - (1 - rate)^(1/n) = rate' levelLearningRate = 1 - math.Pow(1-levelLearningRate, 1/float64(period)) trendLearningRate = 1 - math.Pow(1-trendLearningRate, 1/float64(period)) estimate := make([]float64, len(ys)) level := newWeighted(levelLearningRate) trend := newWeighted(trendLearningRate) season := newCycle(seasonalLearningRate, period) // we need to initialize the season to '1': for i := 0; i < period; i++ { season.observe(i, 1) } for i, y := range ys { // Remember the old values. oldLevel := level.get() oldTrend := trend.get() oldSeason := season.get(i) // Update the level, by increasing it by the estimate slope level.boostAdd(oldTrend) // Then observing the new y [if y is NaN, this skips, as desired] level.observe(y / oldSeason) // observe the y's non-seasonal value // Next, observe the trend- difference between this level and last. // If y is NaN, we want to skip instead of updating. if math.IsNaN(y) { trend.skip() } else { // Compare the new level against the old. trend.observe(level.get() - oldLevel) } // Lastly, the seasonal value is just y / (l+b) the non-seasonal component. // If y is NaN, this will be NaN too, causing it to skip (as desired). season.observe(i, y/(oldLevel+oldTrend)) // Our estimate is the level times the seasonal component. estimate[i] = level.get() * season.get(i) } return estimate } // RollingSeasonal estimates purely seasonal data without a trend or level component. // For data which shows no long- or short-term trends, this model is more likely to recognize // deviant behavior. However, it will perform worse than Holt-Winters on data which does // have any significant trends. func RollingSeasonal(ys []float64, period int, seasonalLearningRate float64) []float64 { season := newCycle(seasonalLearningRate, period) estimate := make([]float64, len(ys)) for i := range ys { season.observe(i, ys[i]) estimate[i] = season.get(i) } return estimate } // Linear estimates a purely linear trend from the data. func Linear(ys []float64) []float64 { estimate := make([]float64, len(ys)) a, b := LinearRegression(ys) for i := range ys { estimate[i] = a + b*float64(i) } return estimate }
function/builtin/forecast/rolling.go
0.831006
0.551332
rolling.go
starcoder
package nzproj import ( "math" ) /* The Lambert Conformal Conic projection is a projection in which geographic meridians are represented by straight lines which meet at the projection of the pole and geographic parallels are represented by a series of arcs of circles with this point as their centre. */ // LambertConformalConicParams holds the projection parameters for a Lambert Conformal Conic projection. type LambertConformalConicParams struct { SemiMajorAxisOfReferenceEllipsoid float64 OriginFlatteningOfReferenceEllipsoid float64 LatitudeOfFirstStandardParallel float64 LatitudeOfSecondStandardParallel float64 OriginLatitude float64 OriginLongitude float64 FalseNorthingOfProjection float64 FalseEastingOfProjection float64 } type lambertConformalConic struct { // projection parameters a float64 // semi-major axis of reference ellipsoid f0 float64 // origin flattening of reference ellipsoid ϕ1 float64 // latitude of the first standard parallel ϕ2 float64 // latitude of the second standard parallel ϕ0 float64 // origin latitude λ0 float64 // origin longitude n0 float64 // false Northing of projection e0 float64 // false Easting of projection // derived parameters e float64 n float64 f float64 ρ0 float64 } // NewLambertConformalConic provides an implementation of the Lambert Conformal Conic projection with the given parameters. func NewLambertConformalConic(params LambertConformalConicParams) lambertConformalConic { lc := lambertConformalConic{ a: params.SemiMajorAxisOfReferenceEllipsoid, f0: params.OriginFlatteningOfReferenceEllipsoid, ϕ1: params.LatitudeOfFirstStandardParallel, ϕ2: params.LatitudeOfSecondStandardParallel, ϕ0: params.OriginLatitude, λ0: params.OriginLongitude, n0: params.FalseNorthingOfProjection, e0: params.FalseEastingOfProjection, } lc.e = math.Sqrt(2.0*lc.f0 - math.Pow(lc.f0, 2.0)) lc.n = (math.Log(lc.m(lc.ϕ1)) - math.Log(lc.m(lc.ϕ2))) / (math.Log(lc.t(lc.ϕ1)) - math.Log(lc.t(lc.ϕ2))) lc.f = lc.m(lc.ϕ1) / (lc.n * math.Pow(lc.t(lc.ϕ1), lc.n)) lc.ρ0 = lc.ρ(lc.ϕ0) return lc } func (lc *lambertConformalConic) m(l float64) float64 { return math.Cos(l) / math.Sqrt(1.0-math.Pow(lc.e, 2.0)*math.Pow(math.Sin(l), 2.0)) } func (lc *lambertConformalConic) t(l float64) float64 { return math.Tan((math.Pi/4.0)-(l/2.0)) / math.Pow((1.0-lc.e*math.Sin(l))/(1.0+lc.e*math.Sin(l)), lc.e/2.0) } func (lc *lambertConformalConic) ρ(l float64) float64 { return lc.a * lc.f * math.Pow(lc.t(l), lc.n) } func (lc lambertConformalConic) Forward(lon, lat float64) (float64, float64) { return lc.forward(math.Pi*lon/180.0, math.Pi*lat/180.0) } func (lc lambertConformalConic) forward(λ, ϕ float64) (float64, float64) { y := lc.n * (λ - lc.λ0) X := lc.e0 + lc.ρ(ϕ)*math.Sin(y) Y := lc.n0 + lc.ρ0 - lc.ρ(ϕ)*math.Cos(y) return X, Y } func (lc lambertConformalConic) Inverse(x, y float64) (float64, float64) { λ, ϕ := lc.inverse(x, y) return 180.0 * λ / math.Pi, 180.0 * ϕ / math.Pi } func (lc lambertConformalConic) inverse(x, y float64) (float64, float64) { E := x - lc.e0 N := y - lc.n0 λ := lc.λ0 + math.Atan(E/(lc.ρ0-N))/lc.n ρ := math.Sqrt(math.Pow(E, 2.0) + math.Pow(lc.ρ0-N, 2.0)) if lc.n < 0.0 { ρ = -ρ } t := math.Pow(ρ/(lc.a*lc.f), 1.0/lc.n) ϕ, ϕ0 := math.Pi/2.0-2.0*math.Atan(t), math.Inf(1) for math.Abs(ϕ-ϕ0) > 1.0e-09 { ϕ, ϕ0 = math.Pi/2.0-2.0*math.Atan(t*math.Pow((1.0-lc.e*math.Sin(ϕ))/(1.0+lc.e*math.Sin(ϕ)), lc.e/2.0)), ϕ } return λ, ϕ }
lambert_conformal_conic.go
0.797951
0.669934
lambert_conformal_conic.go
starcoder
package fields import "reflect" // DefaultValueEquality is the default instance of a ValueEquality. The initial // initialization of this global variable should be able to deal with // the majority of the cases. var DefaultValueEquality ValueEquality = ValueEqualityFunc(func(key string, leftValue, rightValue interface{}) (bool, error) { if v, ok := leftValue.(Lazy); ok { leftValue = v.Get() } if v, ok := rightValue.(Lazy); ok { rightValue = v.Get() } if isFunction(leftValue) { lV, rV := reflect.ValueOf(leftValue), reflect.ValueOf(rightValue) if lV.Kind() == reflect.Func { return rV.Kind() == reflect.Func && lV.Pointer() == rV.Pointer(), nil } } return reflect.DeepEqual(leftValue, rightValue), nil }) // ValueEquality is comparing two values (of the same key) with each // other and check if both are equal. type ValueEquality interface { // AreValuesEqual compares the two given values for their equality for // the given key. AreValuesEqual(key string, left, right interface{}) (bool, error) } // ValueEqualityFunc is wrapping a given func into ValueEquality. type ValueEqualityFunc func(key string, left, right interface{}) (bool, error) // AreValuesEqual implements ValueEquality.AreValuesEqual(). func (instance ValueEqualityFunc) AreValuesEqual(key string, left, right interface{}) (bool, error) { return instance(key, left, right) } // NewValueEqualityFacade creates a re-implementation of ValueEquality which // uses the given provider to retrieve the actual instance of ValueEquality in // the moment when it is used. This is useful especially in cases where you want // to deal with concurrency while creation of objects that need to hold a // reference to an ValueEquality. func NewValueEqualityFacade(provider func() ValueEquality) ValueEquality { return valueEqualityFacade(provider) } type valueEqualityFacade func() ValueEquality func (instance valueEqualityFacade) AreValuesEqual(name string, left, right interface{}) (bool, error) { return instance.Unwrap().AreValuesEqual(name, left, right) } func (instance valueEqualityFacade) Unwrap() ValueEquality { return instance() } func isFunction(arg interface{}) bool { return arg != nil && reflect.TypeOf(arg).Kind() == reflect.Func }
fields/equality_value.go
0.811228
0.531939
equality_value.go
starcoder
package trietree import ( "errors" "github.com/howz97/algorithm/alphabet" "github.com/howz97/algorithm/queue" ) // Three direction trie tree type TSTNode struct { r rune v T left, mid, right *TSTNode } func newTSTNode(r rune) *TSTNode { return &TSTNode{r: r} } func (t *TSTNode) Upsert(_ alphabet.Interface, k []rune, v T) { if len(k) == 0 { return } switch true { case k[0] < t.r: if t.left == nil { t.left = newTSTNode(k[0]) } t.left.Upsert(nil, k, v) case k[0] > t.r: if t.right == nil { t.right = newTSTNode(k[0]) } t.right.Upsert(nil, k, v) default: if len(k) == 1 { t.v = v } else { if t.mid == nil { t.mid = newTSTNode(k[1]) } t.mid.Upsert(nil, k[1:], v) } } } func (t *TSTNode) Delete(_ alphabet.Interface, k []rune) { if len(k) == 0 { return } switch true { case k[0] < t.r: if t.left != nil { t.left.Delete(nil, k) } case k[0] > t.r: if t.right != nil { t.right.Delete(nil, k) } default: if len(k) == 1 { t.v = nil } else if t.mid != nil { t.mid.Delete(nil, k[1:]) } } } func (t *TSTNode) Find(a alphabet.Interface, k []rune) T { node, _ := t.Locate(a, k) if node == nil { return nil } return node.(*TSTNode).v } // find 找到k对应的节点(n),有这个节点不代表k存在,是否存在需要看n.v是否为nil func (t *TSTNode) Locate(_ alphabet.Interface, k []rune) (TrieNode, []rune) { if len(k) == 0 { return nil, nil } switch true { case k[0] < t.r: if t.left != nil { return t.left.Locate(nil, k) } case k[0] > t.r: if t.right != nil { return t.right.Locate(nil, k) } default: if len(k) == 1 { return t, nil } else if t.mid != nil { return t.mid.Locate(nil, k[1:]) } } return nil, nil } func (t *TSTNode) LongestPrefixOf(_ alphabet.Interface, s []rune, d, l int) int { if len(s) == 0 { return l } switch true { case s[d] < t.r: if t.left != nil { return t.left.LongestPrefixOf(nil, s, d, l) } case s[d] > t.r: if t.right != nil { return t.right.LongestPrefixOf(nil, s, d, l) } default: if t.v != nil { l = d + 1 } if d == len(s)-1 { return l } else if t.mid != nil { return t.mid.LongestPrefixOf(nil, s, d+1, l) } } return l } func (t *TSTNode) Collect(_ alphabet.Interface, prefix string, keys *queue.SliStr) { if t.v != nil { keys.PushBack(prefix) } if t.mid != nil { t.mid.collect(nil, prefix, keys) } } func (t *TSTNode) collect(_ alphabet.Interface, prefix string, keys *queue.SliStr) { if t.v != nil { keys.PushBack(prefix + string(t.r)) } if t.left != nil { t.left.collect(nil, prefix, keys) } if t.mid != nil { t.mid.collect(nil, prefix+string(t.r), keys) } if t.right != nil { t.right.collect(nil, prefix, keys) } } func (t *TSTNode) KeysMatch(_ alphabet.Interface, pattern []rune, prefix string, keys *queue.SliStr) { if len(pattern) == 0 { return } if t.left != nil && (pattern[0] == '.' || pattern[0] < t.r) { t.left.KeysMatch(nil, pattern, prefix, keys) } if t.right != nil && (pattern[0] == '.' || pattern[0] > t.r) { t.right.KeysMatch(nil, pattern, prefix, keys) } if pattern[0] == '.' || pattern[0] == t.r { if len(pattern) == 1 { if t.v != nil { keys.PushBack(prefix + string(t.r)) } } else if t.mid != nil { t.mid.KeysMatch(nil, pattern[1:], prefix+string(t.r), keys) } } } func (t *TSTNode) Keys(_ alphabet.Interface, keys *queue.SliStr) { t.collect(nil, "", keys) } func (t *TSTNode) Compress() error { return errors.New("compress not support") } func (t *TSTNode) IsCompressed() bool { return false } func (t *TSTNode) SetVal(v T) { t.v = v }
trie_tree/tst_node.go
0.52829
0.431584
tst_node.go
starcoder
package sssa import ( "bytes" "crypto/rand" "encoding/base64" "encoding/hex" "fmt" "math" "math/big" "strings" ) var prime *big.Int /** * Returns a random number from the range (0, prime-1) inclusive **/ func random() *big.Int { result := big.NewInt(0).Set(prime) result = result.Sub(result, big.NewInt(1)) result, _ = rand.Int(rand.Reader, result) return result } /** * Converts a byte array into an a 256-bit big.Int, arraied based upon size of * the input byte; all values are right-padded to length 256, even if the most * significant bit is zero. **/ func splitByteToInt(secret []byte) []*big.Int { hex_data := hex.EncodeToString(secret) count := int(math.Ceil(float64(len(hex_data)) / 64.0)) result := make([]*big.Int, count) for i := 0; i < count; i++ { if (i+1)*64 < len(hex_data) { result[i], _ = big.NewInt(0).SetString(hex_data[i*64:(i+1)*64], 16) } else { data := strings.Join([]string{hex_data[i*64:], strings.Repeat("0", 64-(len(hex_data)-i*64))}, "") result[i], _ = big.NewInt(0).SetString(data, 16) } } return result } /** * Converts an array of big.Ints to the original byte array, removing any * least significant nulls **/ func mergeIntToByte(secret []*big.Int) []byte { var hex_data = "" for i := range secret { tmp := fmt.Sprintf("%x", secret[i]) hex_data += strings.Join([]string{strings.Repeat("0", (64 - len(tmp))), tmp}, "") } result, _ := hex.DecodeString(hex_data) result = bytes.TrimRight(result, "\x00") return result } /** * Evauluates a polynomial with coefficients specified in reverse order: * evaluatePolynomial([a, b, c, d], x): * returns a + bx + cx^2 + dx^3 **/ func evaluatePolynomial(polynomial []*big.Int, value *big.Int) *big.Int { last := len(polynomial) - 1 var result *big.Int = big.NewInt(0).Set(polynomial[last]) for s := last - 1; s >= 0; s-- { result = result.Mul(result, value) result = result.Add(result, polynomial[s]) result = result.Mod(result, prime) } return result } /** * inNumbers(array, value) returns boolean whether or not value is in array **/ func inNumbers(numbers []*big.Int, value *big.Int) bool { for n := range numbers { if numbers[n].Cmp(value) == 0 { return true } } return false } /** * Returns the big.Int number base10 in base64 representation; note: this is * not a string representation; the base64 output is exactly 256 bits long **/ func toBase64(number *big.Int) string { hexdata := fmt.Sprintf("%x", number) for i := 0; len(hexdata) < 64; i++ { hexdata = "0" + hexdata } bytedata, success := hex.DecodeString(hexdata) if success != nil { fmt.Println("Error!") fmt.Println("hexdata: ", hexdata) fmt.Println("bytedata: ", bytedata) fmt.Println(success) } return base64.URLEncoding.EncodeToString(bytedata) } /** * Returns the number base64 in base 10 big.Int representation; note: this is * not coming from a string representation; the base64 input is exactly 256 * bits long, and the output is an arbitrary size base 10 integer. * * Returns -1 on failure **/ func fromBase64(number string) *big.Int { bytedata, err := base64.URLEncoding.DecodeString(number) if err != nil { return big.NewInt(-1) } hexdata := hex.EncodeToString(bytedata) result, ok := big.NewInt(0).SetString(hexdata, 16) if ok == false { return big.NewInt(-1) } return result } /** * Computes the multiplicative inverse of the number on the field prime; more * specifically, number * inverse == 1; Note: number should never be zero **/ func modInverse(number *big.Int) *big.Int { copy := big.NewInt(0).Set(number) copy = copy.Mod(copy, prime) pcopy := big.NewInt(0).Set(prime) x := big.NewInt(0) y := big.NewInt(0) copy.GCD(x, y, pcopy, copy) result := big.NewInt(0).Set(prime) result = result.Add(result, y) result = result.Mod(result, prime) return result }
pkg/sssa/utils.go
0.76454
0.417687
utils.go
starcoder
package ijson // Del deletes element form the the data pointed by the path. // An error is returned if it fails to resolve the path. func Del(data interface{}, path ...string) (interface{}, error) { if len(path) == 0 || data == nil { return data, nil } pathType := DetectDelPath(path[0]) switch pathType { case PDel_Obj: object, valid := data.(map[string]interface{}) if !valid { return nil, errExpObj } if len(path) == 1 { delete(object, path[0]) return object, nil } newData, err := Del(object[path[0]], path[1:]...) if err != nil { return nil, err } object[path[0]] = newData return object, nil case PDel_ArrIdx, PDel_ArrIdxPO: idx, err := index(path[0], pathType) if err != nil { return nil, err } array, valid := data.([]interface{}) if !valid { return nil, errExpArr } if len(path) == 1 { return DeleteAtArrayIndex(array, idx, pathType == PDel_ArrIdxPO) } newData, err := Del(array[idx], path[1:]...) if err != nil { return nil, err } array[idx] = newData return array, nil case PDel_ArrEnd: array, valid := data.([]interface{}) if !valid { return nil, errExpArr } l := len(array) array[l-1] = nil return array[:l-1], nil default: return nil, errInvPth } } // DelP is same as Del() function. It just takes `"."` separated path. func DelP(data interface{}, path string) (interface{}, error) { return Del(data, split(path)...) } // DeleteAtArrayIndex deletes the provides index from array. // Set po to true if you want to preserve the order while deleting the index. // An error is returned if the index is out of range. func DeleteAtArrayIndex( arr []interface{}, idx int, po bool, /* preser order(inefficient) */ ) ([]interface{}, error) { if po { return DeleteAtIndexPO(arr, idx) } return DeleteAtIndex(arr, idx) } // DeleteAtIndexPO deletes the provides index from array with preserving the order. func DeleteAtIndexPO(arr []interface{}, idx int) ([]interface{}, error) { l := len(arr) if l == 0 { return arr, nil } if idx < 0 || idx >= l { return nil, errOutBnd } // Remove the element at index i from a. copy(arr[idx:], arr[idx+1:]) // Shift a[i+1:] left one index. arr[l-1] = nil // Erase last element (write zero value). // Truncate slice. return arr[:l-1], nil } // DeleteAtIndex deletes the provides index from array withput preserving the order. func DeleteAtIndex(arr []interface{}, idx int) ([]interface{}, error) { l := len(arr) if l == 0 { return arr, nil } if idx < 0 || idx >= l { return nil, errOutBnd } // Remove the element at index i from a. arr[idx] = arr[l-1] // Copy last element to index i. arr[l-1] = nil // Erase last element (write zero value). // Truncate slice. return arr[:l-1], nil }
del.go
0.622459
0.463019
del.go
starcoder
// Package xor implements a nearest-neighbor data structure for the XOR-metric package xor import ( "errors" "fmt" "strconv" "unsafe" ) // Key represents a point in the XOR-space type Key uint64 // Key implements interface Item func (id Key) Key() Key { return id } // Bit returns the k-th bit from metric point of view. The zero-th bit is most significant. func (id Key) Bit(k int) int { return int((id >> uint(k)) & 1) } // String returns a textual representation of the id func (id Key) String() string { return fmt.Sprintf("%016x", id) } // String returns a textual representation of the id, truncated to the k MSBs. func (id Key) ShortString(k uint) string { shift := uint(8*unsafe.Sizeof(id)) - k return fmt.Sprintf("%0"+strconv.Itoa(int(k))+"b", ((id << shift) >> shift)) } // Item is any type that has an XOR-space Key type Item interface { Key() Key } // Metric is an XOR-metric space that supports point addition and nearest neighbor (NN) queries. // The zero value is an empty metric space. type Metric struct { Item sub [2]*Metric n int // Number of items (not nodes) in the subtree of and including this node } var ErrDup = errors.New("duplicate point") // Iterate calls f on each node of the XOR-tree that has a non-nil item. func (m *Metric) Iterate(f func(Item)) { if m.Item != nil { f(m.Item) } if m.sub[0] != nil { m.sub[0].Iterate(f) } if m.sub[1] != nil { m.sub[1].Iterate(f) } } func (m *Metric) Dump() []Item { var result []Item m.Iterate(func(item Item) { result = append(result, item) }) return result } // Copy returns a deep copy of the metric func (m *Metric) Copy() *Metric { m_ := &Metric{ Item: m.Item, n: m.n, } if m.sub[0] != nil { m_.sub[0] = m.sub[0].Copy() } if m.sub[1] != nil { m_.sub[1] = m.sub[1].Copy() } return m_ } // Clear removes all points from the metric func (m *Metric) Clear() { *m = Metric{} } // Size returns the number of points in the metric func (m *Metric) Size() int { return m.n } func (m *Metric) calcSize() { m.n = 0 if m.sub[0] != nil { m.n += m.sub[0].n } if m.sub[1] != nil { m.n += m.sub[1].n } if m.Item != nil { m.n++ } } // Add adds the item to the metric. It returns the smallest number of // significant bits that distinguish this item from the rest in the metric. func (m *Metric) Add(item Item) (level int, err error) { return m.add(item, 0) } func (m *Metric) add(item Item, r int) (bottom int, err error) { defer m.calcSize() if m.Item == nil { if m.sub[0] == nil && m.sub[1] == nil { // This is an empty leaf node m.Item = item return r, nil } // This is an intermediate node return m.forward(item, r) } // This is a non-empty leaf node if m.Item.Key() == item.Key() { return r, ErrDup } if _, err = m.forward(m.Item, r); err != nil { panic("¢") } m.Item = nil bottom, err = m.forward(item, r) if err != nil { panic("¢") } return bottom, err } func (m *Metric) forward(item Item, r int) (bottom int, err error) { j := item.Key().Bit(r) if m.sub[j] == nil { m.sub[j] = &Metric{} } return m.sub[j].add(item, r+1) } // Remove removes an item with id from the metric, if present. // It returns the removed item, or nil if non present. func (m *Metric) Remove(id Key) Item { item, _ := m.remove(id, 0) return item } func (m *Metric) remove(id Key, r int) (Item, bool) { defer m.calcSize() if m.Item != nil { if m.Item.Key() == id { item := m.Item m.Item = nil return item, true } return nil, false } b := id.Bit(r) sub := m.sub[b] if sub == nil { return nil, false } item, emptied := sub.remove(id, r+1) if emptied { m.sub[b] = nil if m.sub[1-b] == nil { return item, true } } return item, false } // Nearest returns the k points in the metric that are closest to the pivot. func (m *Metric) Nearest(pivot Key, k int) []Item { return m.nearest(pivot, k, 0) } func (m *Metric) nearest(pivot Key, k int, r int) []Item { if k == 0 { return nil } if m.Item != nil { return []Item{m.Item} } var result []Item b := pivot.Bit(r) sub := m.sub[b] if sub != nil { result = sub.nearest(pivot, k, r+1) } k -= len(result) sub = m.sub[1-b] if sub != nil { result = append(result, sub.nearest(pivot, k, r+1)...) } return result }
kit/xor/xor.go
0.855957
0.436622
xor.go
starcoder
package main import ( "fmt" "regexp" "strconv" "github.com/theatlasroom/advent-of-code/go/utils" ) /** --- Day 2: Password Philosophy --- Your flight departs in a few days from the coastal airport; the easiest way down to the coast from here is via toboggan. The shopkeeper at the North Pole Toboggan Rental Shop is having a bad day. "Something's wrong with our computers; we can't log in!" You ask if you can take a look. Their password database seems to be a little corrupted: some of the passwords wouldn't have been allowed by the Official Toboggan Corporate Policy that was in effect when they were chosen. To try to debug the problem, they have created a list (your puzzle input) of passwords (according to the corrupted database) and the corporate policy when that password was set. For example, suppose you have the following list: 1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times. In the above example, 2 passwords are valid. The middle password, cdefg, is not; it contains no instances of b, but needs at least 1. The first and third passwords are valid: they contain one a or nine c, both within the limits of their respective policies. How many passwords are valid according to their policies? **/ type rule struct { min, max int character string } type policy struct { rule password string } var re = regexp.MustCompile(`^(\d+)-(\d+)\s([a-z]):\s(.*)$`) func newPolicy(input string) policy { str := re.FindStringSubmatch(input) minStr, maxStr, character, password := str[1], str[2], str[3], str[4] min, err := strconv.Atoi(minStr) utils.CheckAndPanic(err) max, err := strconv.Atoi(maxStr) utils.CheckAndPanic(err) return policy{ rule{ min, max, character, }, password, } } func extractPolicies(data []string) []policy { var policies []policy for _, d := range data { policies = append(policies, newPolicy(d)) } return policies } type validatorFn = func(policy) bool func isValidRentalRule(p policy) bool { tally := 0 for _, c := range p.password { if string(c) == p.character { tally++ } } if p.min <= tally && tally <= p.max { return true } return false } func isValidTobogganRule(p policy) bool { x := string(p.password[p.min-1]) == p.character y := string(p.password[p.max-1]) == p.character if (x || y) && !(x && y) { return true } return false } func findValidPasswords(policies []policy, validator validatorFn) int { tally := 0 for _, p := range policies { if validator(p) { tally++ } } return tally } func main() { utils.Banner(utils.BannerConfig{Year: 2020, Day: 2}) data := utils.LoadData("2.txt") policies := extractPolicies(data) fmt.Printf("%d valid rental passwords\n", findValidPasswords(policies, isValidRentalRule)) fmt.Printf("%d valid toboggan passwords\n", findValidPasswords(policies, isValidTobogganRule)) }
go/2020/2.go
0.650023
0.52756
2.go
starcoder
package main import ( "strings" "github.com/cucumber/gherkin-go" "github.com/willf/pad/utf8" ) type renderer struct { *strings.Builder } func newRenderer() renderer { return renderer{&strings.Builder{}} } func (r renderer) Render(d *gherkin.GherkinDocument) string { r.renderFeature(d.Feature) return r.Builder.String() } func (r renderer) renderFeature(f *gherkin.Feature) { r.writeLine("# " + f.Name) r.writeDescription(f.Description) for _, x := range f.Children { r.writeLine("") switch x := x.(type) { case *gherkin.Background: r.renderBackground(x) case *gherkin.Scenario: r.renderScenario(x) case *gherkin.ScenarioOutline: r.renderScenarioOutline(x) default: panic("unreachable") } } } func (r renderer) renderBackground(b *gherkin.Background) { r.writeLine("## Background (" + b.Name + ")") r.writeDescription(b.Description) r.renderSteps(b.Steps) } func (r renderer) renderScenario(s *gherkin.Scenario) { r.renderScenarioDefinition(&s.ScenarioDefinition) } func (r renderer) renderScenarioOutline(s *gherkin.ScenarioOutline) { r.renderScenarioDefinition(&s.ScenarioDefinition) if len(s.Examples) != 0 { r.writeLine("") r.renderExamples(s.Examples) } } func (r renderer) renderScenarioDefinition(s *gherkin.ScenarioDefinition) { r.writeLine("## " + s.Name) r.writeDescription(s.Description) r.renderSteps(s.Steps) } func (r renderer) renderSteps(ss []*gherkin.Step) { for i, s := range ss { r.writeLine("") r.renderStep(s, i == len(ss)-1) } } func (r renderer) renderDocString(d *gherkin.DocString) { r.writeLine("```") r.writeLine(d.Content) r.writeLine("```") } func (r renderer) renderStep(s *gherkin.Step, last bool) { if last && s.Argument == nil && s.Text[len(s.Text)-1] != '.' { s.Text += "." } r.writeLine("_" + strings.TrimSpace(s.Keyword) + "_ " + s.Text) if s.Argument != nil { r.writeLine("") switch x := s.Argument.(type) { case *gherkin.DocString: r.renderDocString(x) case *gherkin.DataTable: r.renderDataTable(x) default: panic("unreachable") } } } func (r renderer) renderExamples(es []*gherkin.Examples) { r.writeLine("### Examples") for _, e := range es { if e.Name != "" { r.writeLine("") r.writeLine("#### " + e.Name) } r.writeDescription(e.Description) r.writeLine("") r.renderExampleTable(e.TableHeader, e.TableBody) } } func (r renderer) renderExampleTable(h *gherkin.TableRow, rs []*gherkin.TableRow) { ws := r.getCellWidths(append([]*gherkin.TableRow{h}, rs...)) r.renderCells(h.Cells, ws) s := "|" for _, w := range ws { s += strings.Repeat("-", w+2) + "|" } r.writeLine(s) for _, t := range rs { r.renderCells(t.Cells, ws) } } func (r renderer) renderDataTable(t *gherkin.DataTable) { ws := r.getCellWidths(t.Rows) for _, t := range t.Rows { r.renderCells(t.Cells, ws) } } func (r renderer) renderCells(cs []*gherkin.TableCell, ws []int) { s := "|" for i, c := range cs { s += " " + utf8.Right(c.Value, ws[i], " ") + " |" } r.writeLine(s) } func (renderer) getCellWidths(rs []*gherkin.TableRow) []int { ws := make([]int, len(rs[0].Cells)) for _, r := range rs { for i, c := range r.Cells { if w := len(c.Value); w > ws[i] { ws[i] = w } } } return ws } func (r renderer) writeDescription(s string) { if s != "" { r.writeLine("") r.writeLine(strings.TrimSpace(s)) } } func (r renderer) writeLine(s string) { _, err := r.WriteString(s + "\n") if err != nil { panic(err) } }
renderer.go
0.535584
0.433622
renderer.go
starcoder
package DG2D import ( "fmt" "math" "strings" "github.com/notargets/gocfd/types" "github.com/notargets/gocfd/readfiles" graphics2D "github.com/notargets/avs/geometry" "github.com/notargets/gocfd/geometry2D" "github.com/notargets/gocfd/utils" ) type DFR2D struct { N int SolutionElement *LagrangeElement2D FluxElement *RTElement FluxInterp utils.Matrix // Interpolates from the interior (solution) points to all of the flux points FluxEdgeInterp utils.Matrix // Interpolates only from interior to the edge points in the flux element FluxDr, FluxDs utils.Matrix // Derivatives from the interior (solution) points to all of the flux points DXMetric, DYMetric utils.Matrix // X and Y derivative metrics, multiply by scalar field values to create DOF for RT // Mesh Parameters K int // Number of elements (triangles) in mesh VX, VY utils.Vector // X,Y vertex points in mesh (vertices) BCEdges types.BCMAP FluxX, FluxY utils.Matrix // Flux Element local coordinates SolutionX, SolutionY utils.Matrix // Solution Element local coordinates Tris *Triangulation // Triangle mesh and edge/face structures J, Jinv, Jdet utils.Matrix // Mesh Transform Jacobian, Kx[4], each K element has a 2x2 matrix, det is |J| FaceNorm [2]utils.Matrix // Face normal (normalized), Kx3 IInII utils.Matrix // Mag face normal divided by unit triangle face norm mag, Kx3 dimension EdgeNumber []types.EdgeKey // Edge number for each edge, used to index into edge structures, Kx3 dimension } func NewDFR2D(N int, plotMesh bool, meshFileO ...string) (dfr *DFR2D) { if N < 1 { panic(fmt.Errorf("Polynomial order must be >= 1, have %d", N)) } le := NewLagrangeElement2D(N, Epsilon) rt := NewRTElement(N+1, le.R, le.S) RFlux := utils.NewVector(rt.Nedge*3, rt.GetEdgeLocations(rt.R)) // For the Interpolation matrix across three edges SFlux := utils.NewVector(rt.Nedge*3, rt.GetEdgeLocations(rt.S)) // For the Interpolation matrix across three edges dfr = &DFR2D{ N: N, SolutionElement: le, FluxElement: rt, FluxInterp: le.Simplex2DInterpolatingPolyMatrix(rt.R, rt.S), // Interpolation matrix for flux nodes FluxEdgeInterp: le.Simplex2DInterpolatingPolyMatrix(RFlux, SFlux), // Interpolation matrix across three edges } dfr.FluxDr, dfr.FluxDs = le.GetDerivativeMatrices(rt.R, rt.S) if len(meshFileO) != 0 { var EToV utils.Matrix t := getFileTypeFromExtension(meshFileO[0]) switch t { case GAMBIT_FILE: dfr.K, dfr.VX, dfr.VY, EToV, dfr.BCEdges = readfiles.ReadGambit2d(meshFileO[0], false) case SU2_FILE: dfr.K, dfr.VX, dfr.VY, EToV, dfr.BCEdges = readfiles.ReadSU2(meshFileO[0], false) } //dfr.BCEdges.Print() dfr.Tris = NewTriangulation(dfr.VX, dfr.VY, EToV, dfr.BCEdges) // Build connectivity matrices dfr.FluxX, dfr.FluxY = CalculateElementLocalGeometry(dfr.Tris.EToV, dfr.VX, dfr.VY, dfr.FluxElement.R, dfr.FluxElement.S) dfr.SolutionX, dfr.SolutionY = CalculateElementLocalGeometry(dfr.Tris.EToV, dfr.VX, dfr.VY, dfr.SolutionElement.R, dfr.SolutionElement.S) if plotMesh { readfiles.PlotMesh(dfr.VX, dfr.VY, EToV, dfr.SolutionX, dfr.SolutionY, true) utils.SleepFor(50000) } // Calculate RT based derivative metrics for use in calculating Dx and Dy using the RT element dfr.CalculateJacobian() dfr.CalculateFaceNorms() dfr.CalculateRTBasedDerivativeMetrics() dfr.DXMetric.SetReadOnly("DXMetric") dfr.DYMetric.SetReadOnly("DYMetric") dfr.J.SetReadOnly("GeometricJacobian") dfr.Jdet.SetReadOnly("GeometricJacobianDeterminant") dfr.Jinv.SetReadOnly("GeometricJacobianInverse") dfr.FluxX.SetReadOnly("FluxX") dfr.FluxY.SetReadOnly("FluxY") dfr.SolutionX.SetReadOnly("SolutionX") dfr.SolutionY.SetReadOnly("SolutionY") } return } type MeshFileType uint8 const ( GAMBIT_FILE MeshFileType = iota SU2_FILE ) func getFileTypeFromExtension(fileName string) (t MeshFileType) { var ( err error ) fileName = strings.Trim(fileName, " ") l := len(fileName) if l < 4 || fileName[l-4] != '.' { err = fmt.Errorf("unable to determine file type from name: %s", fileName) panic(err) } ext := fileName[l-3:] switch ext { case "neu": // Gambit neutral file return GAMBIT_FILE case "su2": // SU2 file return SU2_FILE default: err = fmt.Errorf("unsupported file type: %s", fileName) panic(err) } } func (dfr *DFR2D) GetJacobian(k int) (J, Jinv []float64, Jdet float64) { J = dfr.J.DataP[k*4 : (k+1)*4] Jinv = dfr.Jinv.DataP[k*4 : (k+1)*4] Jdet = dfr.Jdet.At(k, 0) return } func (dfr *DFR2D) CalculateRTBasedDerivativeMetrics() { /* Multiply either of these matrices by a scalar solution value at NpFlux points, then multiply that result by rt.Div to get either the X or Y derivative of that field Note that you can specify arbitrary solution values at the edges to establish continuity and you will still have accuracy of the X or Y derivative equal to the interior element polynomial degree */ var ( NpFlux, NpInt, Kmax = dfr.FluxElement.Np, dfr.FluxElement.Nint, dfr.K NpEdge = dfr.FluxElement.Nedge Jinv, Jdet = dfr.Jinv, dfr.Jdet ) dfr.DXMetric, dfr.DYMetric = utils.NewMatrix(NpFlux, Kmax), utils.NewMatrix(NpFlux, Kmax) RTDXmd, RTDYmd := dfr.DXMetric.DataP, dfr.DYMetric.DataP for k := 0; k < Kmax; k++ { var ( JinvD = Jinv.DataP[4*k : 4*(k+1)] ) for i := 0; i < NpInt; i++ { ind := k + i*Kmax ind2 := k + (i+NpInt)*Kmax RTDXmd[ind], RTDXmd[ind2] = JinvD[0], JinvD[2] RTDYmd[ind], RTDYmd[ind2] = JinvD[1], JinvD[3] } } var ( fnd0, fnd1 = dfr.FaceNorm[0].DataP, dfr.FaceNorm[1].DataP ) for k := 0; k < Kmax; k++ { ooJd := 1. / Jdet.DataP[k] for fn := 0; fn < 3; fn++ { faceInd := k + Kmax*fn norm := [2]float64{fnd0[faceInd], fnd1[faceInd]} IInII := dfr.IInII.DataP[faceInd] for i := 0; i < NpEdge; i++ { shift := fn * NpEdge indFull := k + (2*NpInt+i+shift)*Kmax RTDXmd[indFull], RTDYmd[indFull] = ooJd*norm[0]*IInII, ooJd*norm[1]*IInII } } } } func (dfr *DFR2D) CalculateJacobian() { Jd := make([]float64, 4*dfr.K) Jdetd := make([]float64, dfr.K) JdInv := make([]float64, 4*dfr.K) for k := 0; k < dfr.K; k++ { tri := dfr.Tris.EToV.Row(k).DataP v := [3]int{int(tri[0]), int(tri[1]), int(tri[2])} v1x, v2x, v3x := dfr.VX.AtVec(v[0]), dfr.VX.AtVec(v[1]), dfr.VX.AtVec(v[2]) v1y, v2y, v3y := dfr.VY.AtVec(v[0]), dfr.VY.AtVec(v[1]), dfr.VY.AtVec(v[2]) //xr, yr := 0.5*(v2x-v1x), 0.5*(v2y-v1y) //xs, ys := 0.5*(v3x-v1x), 0.5*(v3y-v1y) xr, yr := 0.5*(v2x-v1x), 0.5*(v2y-v1y) xs, ys := 0.5*(v3x-v1x), 0.5*(v3y-v1y) // Jacobian is [xr, xs] // [yr, ys] ind := k * 4 Jd[ind+0], Jd[ind+1], Jd[ind+2], Jd[ind+3] = xr, xs, yr, ys Jdetd[k] = xr*ys - xs*yr // Inverse Jacobian is: // [ ys,-xs] * (1/(xr*ys-xs*yr)) // [-yr, xr] JdInv[ind+0], JdInv[ind+1], JdInv[ind+2], JdInv[ind+3] = ys, -xs, -yr, xr for i := 0; i < 4; i++ { JdInv[ind+i] /= Jdetd[k] } } dfr.J, dfr.Jinv = utils.NewMatrix(dfr.K, 4, Jd), utils.NewMatrix(dfr.K, 4, JdInv) dfr.Jdet = utils.NewMatrix(dfr.K, 1, Jdetd) dfr.J.SetReadOnly("J") dfr.Jdet.SetReadOnly("Jdet") dfr.Jinv.SetReadOnly("Jinv") } func (dfr *DFR2D) CalculateFaceNorms() { var ( Kmax = dfr.K ) dfr.FaceNorm[0], dfr.FaceNorm[1] = utils.NewMatrix(3, Kmax), utils.NewMatrix(3, Kmax) dfr.IInII = utils.NewMatrix(3, Kmax) dfr.EdgeNumber = make([]types.EdgeKey, 3*Kmax) for en, e := range dfr.Tris.Edges { for connNum := 0; connNum < int(e.NumConnectedTris); connNum++ { k := int(e.ConnectedTris[connNum]) edgeNum := e.ConnectedTriEdgeNumber[connNum].Index() // one of [0,1,2], aka "First", "Second", "Third" ind := k + Kmax*edgeNum dfr.IInII.DataP[ind] = e.IInII[connNum] dfr.EdgeNumber[ind] = en fnD1, fnD2 := dfr.FaceNorm[0].DataP, dfr.FaceNorm[1].DataP x1, x2 := GetEdgeCoordinates(en, bool(e.ConnectedTriDirection[connNum]), dfr.VX, dfr.VY) dx, dy := x2[0]-x1[0], x2[1]-x1[1] oonorm := 1. / math.Sqrt(dx*dx+dy*dy) nx, ny := -dy*oonorm, dx*oonorm fnD1[ind], fnD2[ind] = nx, ny } } dfr.FaceNorm[0].SetReadOnly("FaceNorm1") dfr.FaceNorm[1].SetReadOnly("FaceNorm2") dfr.IInII.SetReadOnly("IInII") } func (dfr *DFR2D) ProjectFluxOntoRTSpace(Fx, Fy utils.Matrix) (Fp utils.Matrix) { var ( Np = dfr.FluxElement.Np K = dfr.K rt = dfr.FluxElement JdetD = dfr.Jdet.DataP JinvD = dfr.Jinv.DataP fxD, fyD = Fx.DataP, Fy.DataP ) Fp = utils.NewMatrix(K, Np) fpD := Fp.DataP for k := 0; k < K; k++ { var ( Jdet = JdetD[k] Jinv = JinvD[4*k : 4*k+4] ) for n := 0; n < Np; n++ { ind := n + k*Np fT := [2]float64{Jdet * (Jinv[0]*fxD[ind] + Jinv[1]*fyD[ind]), Jdet * (Jinv[2]*fxD[ind] + Jinv[3]*fyD[ind])} oosr2 := 1 / math.Sqrt(2) switch rt.GetTermType(n) { case All: panic("bad input") case InteriorR: // Unit vector is [1,0] fpD[ind] = fT[0] case InteriorS: // Unit vector is [0,1] fpD[ind] = fT[1] case Edge1: // Edge3: fpD[ind] = -fT[1] case Edge2: // Edge1: fpD[ind] = oosr2 * (fT[0] + fT[1]) case Edge3: // Edge2: fpD[ind] = -fT[0] } } } return } func (dfr *DFR2D) ConvertScalarToOutputMesh(f utils.Matrix) (fI []float32) { /* Input f contains the function data to be associated with the output mesh The input dimensions of f are: f(Np, K), where Np is the number of RT nodes and K is the element count Output fI contains the function data in the same order as the vertices of the output mesh The corners of each element are formed by averaging the nearest two edge values */ var ( fD = f.DataP Kmax = dfr.K Nint = dfr.FluxElement.Nint Nedge = dfr.FluxElement.Nedge NpFlux = dfr.FluxElement.Np Np = NpFlux - Nint + 3 // Subtract Nint to remove the dup pts and add 3 for the verts ) Ind := func(k, i, Kmax int) (ind int) { ind = k + i*Kmax return } fI = make([]float32, Kmax*Np) for k := 0; k < Kmax; k++ { var ( edge [3][2]float32 ) for ii := 0; ii < 3; ii++ { beg := 2*Nint + ii*Nedge end := beg + Nedge - 1 ie0, ie1 := Ind(k, beg, Kmax), Ind(k, end, Kmax) // [ii][0] is the first point on the edge, [ii][1] is the second edge[ii][0], edge[ii][1] = float32(fD[ie0]), float32(fD[ie1]) } for ii := 0; ii < Np; ii++ { ind := Ind(k, ii, Kmax) switch { case ii < 3: // Create values for each corner by averaging the nodes opposite each fI[ind] = 0.5 * (edge[(ii+2)%3][1] + edge[ii][0]) case ii >= 3: indFlux := Ind(k, ii-3+Nint, Kmax) // Refers to the nodes, skipping the first Nint repeated points fI[ind] = float32(fD[indFlux]) } } } return } func (dfr *DFR2D) OutputMesh() (gm *graphics2D.TriMesh) { /* For each of K elements, the layout of the output mesh is: Indexed geometry: Three vertices of the base triangle, followed by RT node points, excluding duplicated Nint pts Triangles: Some number of triangles, defined by indexing into the Indexed Geometry / function values ****************************************************************************************************** Given there is no function data for the corners of the RT element, these will have to be supplied when constructing the indexed function data to complement this output mesh */ // Triangulate the unit RT triangle: start with the bounding triangle, which includes the corners to constrain // the Delaunay triangulation var ( Kmax = dfr.K Nint = dfr.FluxElement.Nint NpFlux = dfr.FluxElement.Np ) Ind := func(k, i, Kmax int) (ind int) { ind = k + i*Kmax return } R := []float64{-1, 1, -1} // Vertices of unit triangle S := []float64{-1, -1, 1} tm := geometry2D.NewTriMesh(R, S) tri := &geometry2D.Tri{} tri.AddEdge(tm.NewEdge([2]int{0, 1}, true)) e2 := tm.NewEdge([2]int{1, 2}, true) tri.AddEdge(e2) tri.AddEdge(tm.NewEdge([2]int{2, 0}, true)) tm.AddBoundingTriangle(tri) // Now we add points to incrementally define the triangulation for i := Nint; i < NpFlux; i++ { r := dfr.FluxElement.R.DataP[i] s := dfr.FluxElement.S.DataP[i] tm.AddPoint(r, s) } gmB := tm.ToGraphMesh() gm = &gmB // Build the X,Y coordinates to support the triangulation index Np := NpFlux - Nint + 3 // Subtract Nint to remove the dup pts and add 3 for the verts VX, VY := utils.NewMatrix(Np, Kmax), utils.NewMatrix(Np, Kmax) vxd, vyd := VX.DataP, VY.DataP for k := 0; k < Kmax; k++ { verts := dfr.Tris.GetTriVerts(uint32(k)) for ii := 0; ii < Np; ii++ { ind := Ind(k, ii, Kmax) switch { case ii < 3: vxd[ind], vyd[ind] = dfr.VX.DataP[verts[ii]], dfr.VY.DataP[verts[ii]] case ii >= 3: indFlux := Ind(k, ii-3+Nint, Kmax) // Refers to the nodes, skipping the first Nint repeated points vxd[ind], vyd[ind] = dfr.FluxX.DataP[indFlux], dfr.FluxY.DataP[indFlux] } } } //fmt.Println(VX.Transpose().Print("VX_Out")) //fmt.Println(VY.Transpose().Print("VY_Out")) // Now replicate the triangle mesh for all triangles baseTris := gm.Triangles gm.Triangles = make([]graphics2D.Triangle, Kmax*len(baseTris)) for k := 0; k < Kmax; k++ { for i, tri := range baseTris { newTri := graphics2D.Triangle{Nodes: tri.Nodes} for ii := 0; ii < 3; ii++ { newTri.Nodes[ii] = int32(Ind(k, int(newTri.Nodes[ii]), Kmax)) } gm.Triangles[Ind(k, i, Kmax)] = newTri } } gm.BaseGeometryClass.Geometry = make([]graphics2D.Point, Kmax*Np) for k := 0; k < Kmax; k++ { for ii := 0; ii < Np; ii++ { ind := Ind(k, ii, Kmax) gm.BaseGeometryClass.Geometry[ind] = graphics2D.Point{X: [2]float32{float32(vxd[ind]), float32(vyd[ind])}} } } //gm.Attributes = make([][]float32, len(gm.Triangles)) // Empty attributes gm.Attributes = nil return }
DG2D/dfr_startup.go
0.678753
0.664363
dfr_startup.go
starcoder
package agozon var LocaleESMap = map[string]LocaleSearchIndex{ "All": LocaleES.All, "Apparel": LocaleES.Apparel, "Automotive": LocaleES.Automotive, "Baby": LocaleES.Baby, "Books": LocaleES.Books, "DVD": LocaleES.DVD, "Electronics": LocaleES.Electronics, "ForeignBooks": LocaleES.ForeignBooks, "GiftCards": LocaleES.GiftCards, "HealthPersonalCare": LocaleES.HealthPersonalCare, "Jewelry": LocaleES.Jewelry, "KindleStore": LocaleES.KindleStore, "Kitchen": LocaleES.Kitchen, "Lighting": LocaleES.Lighting, "Luggage": LocaleES.Luggage, "MP3Downloads": LocaleES.MP3Downloads, "MobileApps": LocaleES.MobileApps, "Music": LocaleES.Music, "MusicalInstruments": LocaleES.MusicalInstruments, "OfficeProducts": LocaleES.OfficeProducts, "Shoes": LocaleES.Shoes, "Software": LocaleES.Software, "SportingGoods": LocaleES.SportingGoods, "Tools": LocaleES.Tools, "Toys": LocaleES.Toys, "VideoGames": LocaleES.VideoGames, "Watches": LocaleES.Watches, } var LocaleES = struct { All, Apparel, Automotive, Baby, Books, DVD, Electronics, ForeignBooks, GiftCards, HealthPersonalCare, Jewelry, KindleStore, Kitchen, Lighting, Luggage, MP3Downloads, MobileApps, Music, MusicalInstruments, OfficeProducts, Shoes, Software, SportingGoods, Tools, Toys, VideoGames, Watches LocaleSearchIndex }{ Kitchen: LocaleSearchIndex{ BrowseNode: 599392031, SortValues: []string{"-price", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Author", "Availability", "Brand", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, Books: LocaleSearchIndex{ BrowseNode: 599365031, SortValues: []string{"-price", "-pubdate", "-publication_date", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Author", "Availability", "ItemPage", "Keywords", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Power", "Publisher", "Sort", "Title"}, }, GiftCards: LocaleSearchIndex{ BrowseNode: 0, SortValues: []string{"-price", "date-desc-rank", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Artist", "Availability", "Keywords", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice"}, }, Software: LocaleSearchIndex{ BrowseNode: 599377031, SortValues: []string{"-price", "-releasedate", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Author", "Availability", "Brand", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, All: LocaleSearchIndex{ BrowseNode: 0, SortValues: []string{}, ItemSearchParameters: []string{"Availability", "ItemPage", "Keywords", "MerchantId"}, }, Automotive: LocaleSearchIndex{ BrowseNode: 1951052031, SortValues: []string{"-price", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Availability", "Brand", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, MobileApps: LocaleSearchIndex{ BrowseNode: 1661651031, SortValues: []string{"-price", "pmrank", "price", "relevancerank", "reviewrank", "reviewrank_authority"}, ItemSearchParameters: []string{"Author", "Availability", "Brand", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, OfficeProducts: LocaleSearchIndex{ BrowseNode: 0, SortValues: []string{"-price", "-release-date", "popularityrank", "price", "relevancerank", "reviewrank"}, ItemSearchParameters: []string{"Availability", "Brand", "ItemPage", "Keywords", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, VideoGames: LocaleSearchIndex{ BrowseNode: 599383031, SortValues: []string{"-price", "-releasedate", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Author", "Availability", "Brand", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, HealthPersonalCare: LocaleSearchIndex{ BrowseNode: 0, SortValues: []string{"-price", "date-desc-rank", "price", "relevancerank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Author", "Availability", "Brand", "Director", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, KindleStore: LocaleSearchIndex{ BrowseNode: 0, SortValues: []string{"-edition-sales-velocity", "-price", "daterank", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Author", "Availability", "ItemPage", "Keywords", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Publisher", "Sort", "Title"}, }, Tools: LocaleSearchIndex{ BrowseNode: 2454134031, SortValues: []string{"-price", "date-desc-rank", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Actor", "Artist", "AudienceRating", "Author", "Availability", "Brand", "Composer", "Conductor", "Director", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Neighborhood", "Orchestra", "Power", "Publisher", "ReleaseDate", "Sort", "Title"}, }, MP3Downloads: LocaleSearchIndex{ BrowseNode: 1748201031, SortValues: []string{"-albumrank", "-artistalbumrank", "-price", "-releasedate", "-runtime", "-titlerank", "albumrank", "artistalbumrank", "price", "relevancerank", "reviewrank", "reviewrank_authority", "runtime", "salesrank", "titlerank"}, ItemSearchParameters: []string{"Availability", "ItemPage", "Keywords", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, Watches: LocaleSearchIndex{ BrowseNode: 599389031, SortValues: []string{"-price", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Availability", "ItemPage", "Keywords", "MerchantId", "MinPercentageOff", "Sort", "Title"}, }, SportingGoods: LocaleSearchIndex{ BrowseNode: 2665403031, SortValues: []string{"-price", "date-desc-rank", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Availability", "ItemPage", "Keywords", "MerchantId", "MinPercentageOff", "Sort", "Title"}, }, Baby: LocaleSearchIndex{ BrowseNode: 1703496031, SortValues: []string{"-price", "price", "relevancerank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Author", "Availability", "Brand", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, Jewelry: LocaleSearchIndex{ BrowseNode: 2454127031, SortValues: []string{"-price", "date-desc-rank", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Availability", "ItemPage", "Keywords", "MerchantId", "MinPercentageOff", "Sort", "Title"}, }, Electronics: LocaleSearchIndex{ BrowseNode: 667050031, SortValues: []string{"-price", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Availability", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, ForeignBooks: LocaleSearchIndex{ BrowseNode: 599368031, SortValues: []string{"-price", "-pubdate", "-publication_date", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Author", "Availability", "ItemPage", "Keywords", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Power", "Publisher", "Sort", "Title"}, }, MusicalInstruments: LocaleSearchIndex{ BrowseNode: 0, SortValues: []string{"-price", "-release-date", "popularityrank", "price", "relevancerank", "reviewrank"}, ItemSearchParameters: []string{"Author", "Availability", "Brand", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, Apparel: LocaleSearchIndex{ BrowseNode: 0, SortValues: []string{"-price", "price", "relevancerank", "reviewrank", "salesrank"}, ItemSearchParameters: []string{"Author", "Availability", "Brand", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, DVD: LocaleSearchIndex{ BrowseNode: 599380031, SortValues: []string{"-price", "-releasedate", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Actor", "AudienceRating", "Availability", "Director", "ItemPage", "Keywords", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Publisher", "Sort", "Title"}, }, Music: LocaleSearchIndex{ BrowseNode: 599374031, SortValues: []string{"-price", "-releasedate", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Artist", "Availability", "ItemPage", "Keywords", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, Shoes: LocaleSearchIndex{ BrowseNode: 1571263031, SortValues: []string{"-launch-date", "-price", "popularity-rank", "price", "relevancerank", "reviewrank", "reviewrank_authority"}, ItemSearchParameters: []string{"Availability", "Brand", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, Toys: LocaleSearchIndex{ BrowseNode: 599386031, SortValues: []string{"-price", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Availability", "ItemPage", "Keywords", "MerchantId", "MinPercentageOff", "Sort", "Title"}, }, Lighting: LocaleSearchIndex{ BrowseNode: 0, SortValues: []string{"-price", "-release-date", "popularityrank", "price", "relevancerank", "reviewrank"}, ItemSearchParameters: []string{"Availability", "Brand", "ItemPage", "Keywords", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}, }, Luggage: LocaleSearchIndex{ BrowseNode: 2454130031, SortValues: []string{"-price", "date-desc-rank", "price", "relevancerank", "reviewrank", "reviewrank_authority", "salesrank"}, ItemSearchParameters: []string{"Availability", "Brand", "ItemPage", "Keywords", "Manufacturer", "MaximumPrice", "MerchantId", "MinPercentageOff", "MinimumPrice", "Sort", "Title"}}}
LocaleES.go
0.572484
0.426023
LocaleES.go
starcoder
package graphs import ( "github.com/howz97/algorithm/util" ) func NewGraph(size uint) *Graph { return &Graph{ Digraph: NewDigraph(size), } } // Graph has no direction type Graph struct { *Digraph } // NumEdge get the number of no-direction edges func (g *Graph) NumEdge() uint { return g.Digraph.NumEdge() / 2 } // AddEdge add an edge func (g *Graph) AddEdge(a, b int) error { return g.addWeightedEdge(a, b, 1) } func (g *Graph) addWeightedEdge(src, dst int, w float64) error { if !g.HasVert(src) || !g.HasVert(dst) { return ErrVerticalNotExist } if src == dst { return ErrSelfLoop } g.Digraph.edges[src].Put(util.Int(dst), w) g.Digraph.edges[dst].Put(util.Int(src), w) return nil } // DelEdge delete an edge func (g *Graph) DelEdge(a, b int) { g.Digraph.DelEdge(a, b) g.Digraph.DelEdge(b, a) } // TotalWeight sum the weight of all edges func (g *Graph) TotalWeight() float64 { return g.Digraph.TotalWeight() / 2 } // IterWEdge iterate all no-direction edges and their weight func (g *Graph) IterWEdge(fn func(int, int, float64) bool) { visited := make(map[uint64]struct{}) g.Digraph.IterWEdge(func(from int, to int, w float64) bool { if _, v := visited[uint64(to)<<32+uint64(from)]; v { return true } visited[uint64(from)<<32+uint64(to)] = struct{}{} return fn(from, to, w) }) } // IterEdge iterate all no-direction edges func (g *Graph) IterEdge(fn func(int, int) bool) { g.IterWEdge(func(src int, dst int, _ float64) bool { return fn(src, dst) }) } // IterWEdgeFrom iterate all reachable edges and their weight from vertical src func (g *Graph) IterWEdgeFrom(src int, fn func(int, int, float64) bool) { visited := make(map[uint64]struct{}) g.Digraph.IterWEdgeFrom(src, func(from int, to int, w float64) bool { if _, v := visited[uint64(to)<<32+uint64(from)]; v { return true } visited[uint64(from)<<32+uint64(to)] = struct{}{} return fn(from, to, w) }) } // IterEdgeFrom iterate all reachable edges from vertical src func (g *Graph) IterEdgeFrom(src int, fn func(int, int) bool) { g.IterWEdgeFrom(src, func(a int, b int, _ float64) bool { return fn(a, b) }) } // HasCycle check whether graph contains cycle func (g *Graph) HasCycle() bool { marked := make([]bool, g.NumVert()) for i, m := range marked { if m { continue } if g.detectCycleDFS(i, i, marked) { return true } } return false } func (g *Graph) detectCycleDFS(last, cur int, marked []bool) bool { marked[cur] = true found := false g.IterAdjacent(cur, func(adj int) bool { if adj == last { // here is different from digraph return true } if marked[adj] { found = true return false } if g.detectCycleDFS(cur, adj, marked) { found = true return false } return true }) return found } type SubGraphs struct { locate []int // vertical -> subGraphID subGraphs [][]int // subGraphID -> all vertices } // SubGraphs calculate all sub-graphs of g func (g *Graph) SubGraphs() *SubGraphs { tc := &SubGraphs{ locate: make([]int, g.NumVert()), } for i := range tc.locate { tc.locate[i] = -1 } subGraphID := 0 for i, c := range tc.locate { if c < 0 { dfs := g.ReachableSlice(i) for _, v := range dfs { tc.locate[v] = subGraphID } tc.subGraphs = append(tc.subGraphs, dfs) subGraphID++ } } return tc } // IsConn check whether a and b located in the same sub-graph func (tc *SubGraphs) IsConn(a, b int) bool { return tc.locate[a] == tc.locate[b] } // Iterate all vertices of sub-graph where v located func (tc *SubGraphs) Iterate(v int, fn func(int) bool) { for _, v := range tc.subGraphs[tc.locate[v]] { if !fn(v) { break } } } // NumSubGraph get the number of sub-graphs func (tc *SubGraphs) NumSubGraph() int { return len(tc.subGraphs) } // Locate get the ID of sub-graph where v located func (tc *SubGraphs) Locate(v int) int { return tc.locate[v] }
graphs/graph.go
0.721743
0.441673
graph.go
starcoder
package main import ("fmt"; "math"; "os"; "strconv") type segment struct { x float64 y float64 } func no_struct_distance(x1, x2, y1, y2 float64) float64 { delta_x := x2 - x1 delta_y := y2 - y1 return math.Sqrt(math.Pow(delta_x, 2) + math.Pow(delta_y, 2)) } func struct_distance(segment_1, segment_2 segment) float64 { delta_x := segment_2.x - segment_1.x delta_y := segment_2.y - segment_1.y return math.Sqrt(math.Pow(delta_x, 2) + math.Pow(delta_y, 2)) } /* Will add a method here */ func (self *segment) distanceTo(other segment) float64 { delta_x := other.x - self.x delta_y := other.y - self.y return math.Sqrt(math.Pow(delta_x, 2) + math.Pow(delta_y, 2)) } func no_args() { /* 5 | b | | | a |__.__.__.__.__ | a = (x1, y1) = (0.9, 1.1) b = (x2, y2) = (3.2, 4.3) */ var (x1, x2, y1, y2 float64) x1 = 0.9 x2 = 3.2 y1 = 1.1 y2 = 4.3 distance := no_struct_distance(x1, x2, y1, y2) fmt.Println("[No Struct] Distance between (",x1,",",y1,") and (",x2,",",y2,"): ", distance) var segment_1 segment var segment_2 segment segment_1.x = 0.9 segment_1.y = 1.1 segment_2.x = 3.2 segment_2.y = 4.3 distance = struct_distance(segment_1, segment_2) fmt.Println("[Struct] Distance between (",segment_1,") and (",segment_2,"): ", distance) } func get_float(to_parse string) float64 { var return_value float64 // This is basically an anonymous function that runs in the background defer func() { stack_trace := recover() if stack_trace != nil { fmt.Println("Run time panic: ", stack_trace) return_value = 0.0 } }() return_value, err := strconv.ParseFloat(to_parse, 64) if err != nil { panic(err) } return return_value } func with_args(arguments []string) { var (x1, y1, x2, y2 float64) for index, value := range arguments { switch index { case 0: x1 = get_float(value) case 1: y1 = get_float(value) case 2: x2 = get_float(value) case 3: y2 = get_float(value) default: fmt.Println("There must never be more than 4 values.") panic("Number of values exceded.") } } segment_1 := segment{x: x1, y: y1} segment_2 := segment{x: x2, y: y2} fmt.Println("[Method] Distance: ", segment_1.distanceTo(segment_2)) } func main() { arguments := os.Args[1:] if len(arguments) == 4 { with_args(arguments) } else if len(arguments) == 0 { no_args() } else { fmt.Println("Must have 0 or 4 arguments. With 0 arguments, will use default values, with 4 will use x1, y1, x2, y2") } }
Tutorial/Chapter8/structs.go
0.802826
0.622832
structs.go
starcoder
package main import ( "bufio" "errors" "fmt" "io" "log" "math" "os" "sort" ) // Asteroid is a celestial body in the asteroid belt. type Asteroid struct { x, y int } // LineOfSight represent the direction or angle from one Asteroid to another. // The zero value represent the direction from an Asteroid to itself. A // LineOfSight hold the invariant gcd(x, y) == 1. type LineOfSight struct { x, y int } // BeamShot is a giant laser setting to vaporize the victim Asteroid. type BeamShot struct { From, To Asteroid LineOfSight Distance int } // String returns "x,y" to match the README format for Asteroid positions. func (a Asteroid) String() string { return fmt.Sprintf("%d,%d", a.x, a.y) } // Angle of this line of sight, up being 0 and increasing clockwise. func (l LineOfSight) Angle() float64 { return 180 - (180/math.Pi)*math.Atan2(float64(l.x), float64(l.y)) } // BeamShot compute and returns the shot needed to vaporize o from a. func (a Asteroid) BeamShot(o Asteroid) BeamShot { dx, dy := o.x-a.x, o.y-a.y div := gcd(dx, dy) switch { case div < 0: div = -div case div == 0: return BeamShot{From: a, To: o} } los := LineOfSight{x: dx / div, y: dy / div} return BeamShot{From: a, To: o, LineOfSight: los, Distance: div} } // Detect returns the count of others asteroid in direct line of sight from a. // When two asteroids are in the same line of sight they will be counted as one // since the farthest one is "hidden behind" the closest one. func (a Asteroid) Detect(asteroids []Asteroid) int { detected := make(map[LineOfSight]struct{}) // "set-like" map for _, o := range asteroids { if a != o { detected[a.BeamShot(o).LineOfSight] = struct{}{} } } return len(detected) } // Vaporize returns a channel of Asteroid to be vaporized (in order) by a giant // laser installed at the given station. func Vaporize(station Asteroid, asteroids []Asteroid) <-chan Asteroid { victims := make(chan Asteroid) go func() { defer close(victims) // create a BeamShot for every asteroid that is going to be vaporized. // The ring represent the victims indexed by their shooting angle. ring := make(map[LineOfSight][]*BeamShot) // count how many asteroid we're shooting at, because asteroids may contain // the station which we obviously don't want to vaporize. n := 0 for _, o := range asteroids { if o != station { shot := station.BeamShot(o) ring[shot.LineOfSight] = append(ring[shot.LineOfSight], &shot) n++ } } // because the laser only has enough power to vaporize one asteroid at a // time before continuing its rotation, the victims are sorted by distance // (closest first) for every shoot angle. for _, shots := range ring { sort.Slice(shots, func(i, j int) bool { return shots[i].Distance < shots[j].Distance }) } // build and sort the angles at which the laster is going to BeamShot. lines := make([]LineOfSight, 0, len(ring)) for k := range ring { lines = append(lines, k) } sort.Slice(lines, func(i, j int) bool { return lines[i].Angle() < lines[j].Angle() }) // vaporize the victims in order. We rotate through every BeamShot // angles and pick the closest Asteroid to be seen until there are none // left. for n > 0 { for _, l := range lines { if shots := ring[l]; len(shots) > 0 { victims <- shots[0].To ring[l] = shots[1:] n-- } } } }() return victims } // BestLocation find the asteroid which would be the best place to build a new // monitoring station. It returns the asteroid found to be the best, the count // of other asteroids in line of sight from it, and an error when asteroids is // empty. func BestLocation(asteroids []Asteroid) (Asteroid, int, error) { max := 0 loc := Asteroid{} if len(asteroids) == 0 { return loc, max, errors.New("empty slice argument") } for i, a := range asteroids { if n := a.Detect(asteroids); i == 0 || n > max { loc, max = a, n } } return loc, max, nil } // main find and display the best asteroid to build a new monitoring station // and the count of other asteroids in line of sight from it. func main() { asteroids, err := Parse(os.Stdin) if err != nil { log.Fatalf("input error: %s\n", err) } a, n, err := BestLocation(asteroids) if err != nil { log.Fatalf("BestLocation(): %s\n", err) } fmt.Printf("%d other asteroids can be detected from %v,\n", n, a) victims := Vaporize(a, asteroids) for i := 0; i < 199; i++ { if _, ok := <-victims; !ok { log.Fatalf("only %d asteroid(s) vaporized; expected at least 200\n", i) } } vaporized := <-victims // the 200th fmt.Printf("and the 200th asteroid to be vaporized is at %v.\n", vaporized) } // Parse the map of asteroid in the region. It returns the complete asteroid // list and any read or parsing error encountered. func Parse(r io.Reader) ([]Asteroid, error) { var asteroids []Asteroid scanner := bufio.NewScanner(r) scanner.Split(bufio.ScanBytes) x, y := 0, 0 for scanner.Scan() { switch c := scanner.Text(); c { case "#": asteroids = append(asteroids, Asteroid{x, y}) fallthrough case ".": x++ case "\n": y++ x = 0 default: return nil, fmt.Errorf("unexpected position at (%d,%d): %s", x, y, c) } } if err := scanner.Err(); err != nil { return nil, err } return asteroids, nil } // gcd compute and returns the greatest common divisor between a and b using // the Euclidean algorithm. // See https://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations func gcd(a, b int) int { for b != 0 { t := b b = a % b a = t } return a }
day10/main.go
0.703753
0.496887
main.go
starcoder
package leetcode func knightProbability(n int, k int, row int, column int) float64 { dp := make([]map[[2]int]float64, k+1) for i := range dp { dp[i] = make(map[[2]int]float64) } return dynamicProgramming(dp, n, k, row, column) } func dynamicProgramming(dp []map[[2]int]float64, n, k, r, c int) float64 { if !valid(n, r, c) { return 0.0 } // valid here, in chessboard, return 1.0 if k == 0 { return 1.0 } row := min(r, n-1-r) col := min(c, n-1-c) if row > col { row, col = col, row } // the chessboard is square, so we support row <= col if v, exist := dp[k][[2]int{row, col}]; exist { return v } probability := float64(0) probability += dynamicProgramming(dp, n, k-1, r-2, c-1) / 8 probability += dynamicProgramming(dp, n, k-1, r-1, c-2) / 8 probability += dynamicProgramming(dp, n, k-1, r+2, c+1) / 8 probability += dynamicProgramming(dp, n, k-1, r+1, c+2) / 8 probability += dynamicProgramming(dp, n, k-1, r+2, c-1) / 8 probability += dynamicProgramming(dp, n, k-1, r+1, c-2) / 8 probability += dynamicProgramming(dp, n, k-1, r-2, c+1) / 8 probability += dynamicProgramming(dp, n, k-1, r-1, c+2) / 8 dp[k][[2]int{row, col}] = probability return probability } func valid(size, row, column int) bool { if row < 0 || column < 0 || row >= size || column >= size { return false } return true } func min(values ...int) int { minValue := 2147483647 // 1<<31 - 1 for _, v := range values { if v < minValue { minValue = v } } return minValue } func prob(N int, K int, r int, c int, steps int, dp [][][]float64) float64 { x := []int{1, 2, -1, -2, 1, 2, -1, -2} y := []int{2, 1, 2, 1, -2, -1, -2, -1} if steps == K { return 1 } if dp[r][c][steps] > 0 { return dp[r][c][steps] } val := 0.0 for i := 0; i < 8; i++ { row := r + x[i] col := c + y[i] if row < 0 || row >= N || col < 0 || col >= N { continue } val += float64(0.125 * prob(N, K, row, col, steps+1, dp)) } dp[r][c][steps] = val return val } func knightProbability1(N int, K int, r int, c int) float64 { dp := make([][][]float64, N) for i := 0; i < N; i++ { dp[i] = make([][]float64, N) for j := 0; j < N; j++ { dp[i][j] = make([]float64, 101) } } return prob(N, K, r, c, 0, dp) } var dirs = []struct{ i, j int }{{-2, -1}, {-2, 1}, {2, -1}, {2, 1}, {-1, -2}, {-1, 2}, {1, -2}, {1, 2}} func knightProbability2(n, k, row, column int) float64 { per := make([][][]float64, k+1) for i := range per { per[i] = make([][]float64, n) for j := range per[i] { per[i][j] = make([]float64, n) } } return dfs(per, n, row, column, k) } func dfs(per [][][]float64, n, r, c, s int) float64 { if r < 0 || r >= n || c < 0 || c >= n || s < 0 { return 0 } if s == 0 { return 1.0 } if per[s][r][c] != 0 { return per[s][r][c] } for _, v := range dirs { nextR, nextC := r+v.i, c+v.j per[s][r][c] = per[s][r][c] + dfs(per, n, nextR, nextC, s-1)/8 } return per[s][r][c] }
leetcode/688.knight-probability-in-chessboard/knight_probability.go
0.700895
0.464112
knight_probability.go
starcoder
package ui import ( "github.com/Yeicor/sdfx-ui/internal" "github.com/deadsy/sdfx/sdf" "image" "image/color" "image/color/palette" "math" ) //----------------------------------------------------------------------------- // CONFIGURATION //----------------------------------------------------------------------------- // Opt2Cam sets the default camera for SDF2 (may grow to follow the aspect ratio of the screen). // WARNING: Need to run again the main renderer to apply a change of this option. func Opt2Cam(bb sdf.Box2) Option { return func(r *Renderer) { r.implState.Bb = bb } } // Opt2EvalRange skips the initial scan of the SDF2 to find the minimum and maximum value, and can also be used to // make the surface easier to see by setting them to a value close to 0. func Opt2EvalRange(min, max float64) Option { return func(r *Renderer) { if r2, ok := r.impl.(*renderer2); ok { r2.evalMin = min r2.evalMax = max } } } // Opt2EvalScanCells configures the initial scan of the SDF2 to find minimum and maximum values (defaults to 128x128 cells). func Opt2EvalScanCells(cells sdf.V2i) Option { return func(r *Renderer) { if r2, ok := r.impl.(*renderer2); ok { r2.evalScanCells = cells } } } // Opt2BBColor sets the bounding box colors for the different objects. func Opt2BBColor(getColor func(idx int) color.Color) Option { return func(r *Renderer) { if r2, ok := r.impl.(*renderer2); ok { r2.getBBColor = getColor } } } //----------------------------------------------------------------------------- // RENDERER //----------------------------------------------------------------------------- type renderer2 struct { s sdf.SDF2 // The SDF to render pixelsRand []int // Cached set of pixels in random order to avoid shuffling (reset on recompilation and resolution changes) evalMin, evalMax float64 // The pre-computed minimum and maximum of the whole surface (for stable colors and speed) evalScanCells sdf.V2i getBBColor func(idx int) color.Color } func newDevRenderer2(s sdf.SDF2) internal.DevRendererImpl { r := &renderer2{ s: s, evalScanCells: sdf.V2i{128, 128}, getBBColor: func(idx int) color.Color { return palette.WebSafe[((idx + 1) % len(palette.WebSafe))] }, } return r } func (r *renderer2) Dimensions() int { return 2 } func (r *renderer2) BoundingBox() sdf.Box3 { bb := r.s.BoundingBox() return sdf.Box3{Min: bb.Min.ToV3(0), Max: bb.Max.ToV3(0)} } func (r *renderer2) ReflectTree() *internal.ReflectTree { return internal.NewReflectionSDF(r.s).GetReflectSDFTree2() } func (r *renderer2) ColorModes() int { // 0: Gradient (useful for debugging sides) // 1: Black/white (clearer surface boundary) return 2 } func (r *renderer2) Render(args *internal.RenderArgs) error { if r.evalMin == 0 && r.evalMax == 0 { // First render (ignoring external cache) // Compute minimum and maximum evaluate values for a shared color scale for all blocks r.evalMin, r.evalMax = utilSdf2MinMax(r.s, r.s.BoundingBox(), r.evalScanCells) //log.Println("MIN:", r.evalMin, "MAX:", r.evalMax) } // Maintain Bb aspect ratio on ResInv change, increasing the sizeCorner as needed args.StateLock.Lock() fullRenderSize := args.FullRender.Bounds().Size() bbAspectRatio := args.State.Bb.Size().X / args.State.Bb.Size().Y screenAspectRatio := float64(fullRenderSize.X) / float64(fullRenderSize.Y) if math.Abs(bbAspectRatio-screenAspectRatio) > 1e-12 { if bbAspectRatio > screenAspectRatio { scaleYBy := bbAspectRatio / screenAspectRatio args.State.Bb = sdf.NewBox2(args.State.Bb.Center(), args.State.Bb.Size().Mul(sdf.V2{X: 1, Y: scaleYBy})) } else { scaleXBy := screenAspectRatio / bbAspectRatio args.State.Bb = sdf.NewBox2(args.State.Bb.Center(), args.State.Bb.Size().Mul(sdf.V2{X: scaleXBy, Y: 1})) } } args.StateLock.Unlock() // Apply color mode evalMin, evalMax := r.evalMin, r.evalMax if args.State.ColorMode == 1 { // Force black and white to see the surface better evalMin, evalMax = -1e-12, 1e-12 } // Perform the actual render err := implCommonRender(func(pixel sdf.V2i, pixel01 sdf.V2) interface{} { return nil }, func(pixel sdf.V2i, pixel01 sdf.V2, job interface{}) *jobResult { pixel01.Y = 1 - pixel01.Y // Inverted Y args.StateLock.RLock() pos := args.State.Bb.Min.Add(pixel01.Mul(args.State.Bb.Size())) args.StateLock.RUnlock() grayVal := imageColor2(r.s.Evaluate(pos), evalMin, evalMax) return &jobResult{ pixel: pixel, color: color.RGBA{R: uint8(grayVal * 255), G: uint8(grayVal * 255), B: uint8(grayVal * 255), A: 255}, } }, args, &r.pixelsRand) if err == nil && args.State.DrawBbs { // Draw bounding boxes over the image boxes2 := args.State.ReflectTree.GetBoundingBoxes2() for i, bb := range boxes2 { //log.Println("Draw", bb) pixel01Min := bb.Min.Sub(args.State.Bb.Min).Div(args.State.Bb.Size()) pixel01Max := bb.Max.Sub(args.State.Bb.Min).Div(args.State.Bb.Size()) fullRenderSizeV2 := sdf.V2{X: float64(fullRenderSize.X), Y: float64(fullRenderSize.Y)} posMin := pixel01Min.Mul(fullRenderSizeV2) posMax := pixel01Max.Mul(fullRenderSizeV2) drawRect(args.FullRender, int(posMin.X), fullRenderSize.Y-int(posMax.Y), int(posMax.X), fullRenderSize.Y-int(posMin.Y), r.getBBColor(i)) } } return err } // imageColor2 returns the grayscale color for the returned SDF2.Evaluate value, given the reference minimum and maximum // SDF2.Evaluate values. The returned value is in the range [0, 1]. func imageColor2(dist, dmin, dmax float64) float64 { // Clamp due to possibly forced min and max var val float64 // NOTE: This condition forces the surface to be close to 255/2 gray value, otherwise dmax >>> dmin or viceversa // could cause the surface to be visually displaced if dist >= 0 { val = math.Max(0.5, math.Min(1, 0.5+0.5*((dist)/(dmax)))) } else { // Force lower scale for inside surface val = math.Max(0, math.Min(0.5, 0.5*((dist-dmin)/(-dmin)))) } return val } // drawHLine draws a horizontal line func drawHLine(img *image.RGBA, x1, y, x2 int, col color.Color) { for ; x1 <= x2; x1++ { if x1 >= 0 && x1 < img.Bounds().Dx() && y >= 0 && y < img.Bounds().Dy() { img.Set(x1, y, col) } } } // drawVLine draws a veritcal line func drawVLine(img *image.RGBA, x, y1, y2 int, col color.Color) { for ; y1 <= y2; y1++ { if x >= 0 && x < img.Bounds().Dx() && y1 >= 0 && y1 < img.Bounds().Dy() { img.Set(x, y1, col) } } } // drawRect draws a rectangle utilizing drawHLine() and drawVLine() func drawRect(img *image.RGBA, x1, y1, x2, y2 int, col color.Color) { drawHLine(img, x1, y1, x2, col) drawHLine(img, x1, y2, x2, col) drawVLine(img, x1, y1, y2, col) drawVLine(img, x2, y1, y2, col) }
impl2.go
0.623721
0.447219
impl2.go
starcoder
package salience import ( "image" "image/color" "image/draw" "math" ) type Section struct { x, y int e float64 } // Crop crops an image to its most interesting area with the specified extents func Crop(img image.Image, cropWidth, cropHeight int) image.Image { r := img.Bounds() imageWidth := r.Max.X - r.Min.X imageHeight := r.Max.Y - r.Min.Y if cropWidth > imageWidth { cropWidth = imageWidth } if cropHeight > imageHeight { cropHeight = imageHeight } var x, y int sliceStep := imageWidth / 8 if imageHeight/8 < sliceStep { sliceStep = imageHeight / 8 } bestSection := Section{0, 0, 0.0} for x = 0; x < imageWidth-cropWidth; x += sliceStep { for y = 0; y < imageHeight-cropHeight; y += sliceStep { e := entropy(img, image.Rect(x, y, x+cropWidth, y+cropHeight)) if e > bestSection.e { bestSection.e = e bestSection.x = x bestSection.y = y } } } return crop(img, image.Rect(bestSection.x, bestSection.y, bestSection.x+cropWidth, bestSection.y+cropHeight)) } func crop(img image.Image, r image.Rectangle) image.Image { cropped := image.NewRGBA(image.Rect(0, 0, r.Dx(), r.Dy())) draw.Draw(cropped, cropped.Bounds(), img, r.Min, draw.Src) return cropped } // Calculate the entropy of a portion of an image // From http://www.astro.cornell.edu/research/projects/compression/entropy.html func entropy(img image.Image, r image.Rectangle) float64 { arraySize := 256*2 - 1 freq := make([]float64, arraySize) for x := r.Min.X; x < r.Max.X-1; x++ { for y := r.Min.Y; y < r.Max.Y; y++ { diff := greyvalue(img.At(x, y)) - greyvalue(img.At(x+1, y)) if -(arraySize+1)/2 < diff && diff < (arraySize+1)/2 { freq[diff+(arraySize-1)/2]++ } } } n := 0.0 for _, v := range freq { n += v } e := 0.0 for i := 0; i < len(freq); i++ { freq[i] = freq[i] / n if freq[i] != 0.0 { e -= freq[i] * math.Log2(freq[i]) } } return e } func greyvalue(c color.Color) int { r, g, b, _ := c.RGBA() return int((r*299 + g*587 + b*114) / 1000) }
vendor/github.com/iand/salience/salience.go
0.733356
0.526647
salience.go
starcoder
package zgeo import ( "math" "github.com/torlangballe/zutil/zmath" ) // Created by <NAME> on /21/10/15. type PathLineType int type PathPartType int const ( PathLineSquare PathLineType = iota PathLineRound PathLineButt ) const ( PathMove PathPartType = iota PathLine PathQuadCurve PathCurve PathClose ) type PathNode struct { Type PathPartType Points []Pos } type Path struct { Dashes []int nodes []PathNode } func PathNew() *Path { return new(Path) } func (p *Path) Copy() *Path { n := PathNew() n.nodes = append(n.nodes, p.nodes...) return n } func PathNewRect(rect Rect, corner Size) *Path { p := PathNew() p.AddRect(rect, corner) return p } func NewOvalPath(rect Rect) *Path { p := PathNew() p.AddOval(rect) return p } func (p *Path) Empty() { p.nodes = p.nodes[:] } func (p *Path) IsEmpty() bool { return len(p.nodes) == 0 } func (p *Path) NodeCount() int { return len(p.nodes) } func (p *Path) Rect() Rect { if p.IsEmpty() { return Rect{} } var box Rect first := true p.ForEachPart(func(part PathNode) { if first { box.Pos = part.Points[0] } else { if part.Type != PathClose { box.UnionWithPos(part.Points[0]) } } switch part.Type { case PathQuadCurve: box.UnionWithPos(part.Points[1]) case PathCurve: box.UnionWithPos(part.Points[1]) box.UnionWithPos(part.Points[2]) } first = false }) return box } func (p *Path) AddOval(inrect Rect) { } func (p *Path) GetPos() (Pos, bool) { l := len(p.nodes) if l != 0 { p := p.nodes[l-1].Points pl := len(p) if pl != 0 { return p[pl-1], true } } return Pos{}, false } func (p *Path) MoveOrLineTo(pos Pos) bool { plen := len(p.nodes) if plen == 0 || p.nodes[plen-1].Type == PathClose { p.MoveTo(pos) return false } p.LineTo(pos) return true } func (p *Path) MoveTo(pos Pos) { p.nodes = append(p.nodes, PathNode{PathMove, []Pos{pos}}) } func (p *Path) LineTo(pos Pos) { p.nodes = append(p.nodes, PathNode{PathLine, []Pos{pos}}) } func (p *Path) QuadCurveTo(a, b Pos) { p.nodes = append(p.nodes, PathNode{PathQuadCurve, []Pos{a, b}}) } func (p *Path) BezierTo(c1 Pos, c2 Pos, end Pos) { // zlog.Info("p.BezierTo") p.nodes = append(p.nodes, PathNode{PathCurve, []Pos{c1, c2, end}}) } func (p *Path) Close() { p.nodes = append(p.nodes, PathNode{PathClose, []Pos{}}) } func polarPoint(r float64, phi float64) Pos { s, c := math.Sincos(phi) return Pos{r * c, r * s} } func arcControlPoints(angle, delta float64) (Size, Size) { p0 := polarPoint(1, angle) p1 := polarPoint(1, angle+delta) n0 := Size{p0.Y, -p0.X} // rot 90 n1 := Size{-p1.Y, p1.X} // ccw 90 var s float64 if math.Abs(n0.W+n1.W) > math.Abs(n0.H+n1.H) { s = (float64(math.Cos(angle+delta/2)*2) - p0.X - p1.X) * (4 / 3.0) / (n0.W + n1.W) } else { s = (float64(math.Sin(angle+delta/2)*2) - p0.Y - p1.Y) * (4 / 3.0) / (n0.H + n1.H) } return Size{p0.X + n0.W*s, p0.Y + n0.H*s}, Size{p1.X + n1.W*s, p1.Y + n1.H*s} } func (p *Path) ArcTo(rect Rect, degStart, degDelta float64, clockwise bool) { circleCenter := rect.Center() circleRadius := rect.Size.W / 2 // zlog.Info("ArcTo:", circleRadius, degStart, degDelta, p.IsEmpty()) aStart := zmath.DegToRad(degStart - 90) aDelta := zmath.DegToRad(degDelta) p0 := polarPoint(circleRadius, aStart).Plus(circleCenter) needLineTo := false if p.IsEmpty() || p.nodes[len(p.nodes)-1].Type == PathClose { p.MoveTo(p0) needLineTo = true } else { p.LineTo(p0) } if degDelta == 0 || circleRadius <= 0 { if needLineTo { p.LineTo(p0) } return } n := math.Ceil(math.Abs(aDelta) / (math.Pi / 2)) rm := MatrixIdentity.RotatedAroundPos(circleCenter, aDelta/n) k0, k1 := arcControlPoints(aStart, aDelta/n) c0 := Pos{k0.W*circleRadius + circleCenter.X, k0.H*circleRadius + circleCenter.Y} c1 := Pos{k1.W*circleRadius + circleCenter.X, k1.H*circleRadius + circleCenter.Y} for i := 0; i < int(n); i++ { p0 = rm.MulPos(p0) p.BezierTo(c0, c1, p0) c0 = rm.MulPos(c0) c1 = rm.MulPos(c1) } } func (p *Path) Transformed(m *Matrix) (newPath *Path) { newPath = PathNew() for _, n := range p.nodes { nn := PathNode{} for _, p := range n.Points { nn.Points = append(n.Points, m.MulPos(p)) } newPath.nodes = append(newPath.nodes, nn) } return } func (p *Path) AddPath(addPath *Path, join bool, m *Matrix) { if m != nil { addPath = addPath.Transformed(m) } p.nodes = append(p.nodes, addPath.nodes...) } func (p *Path) Rotated(deg float64, origin *Pos) *Path { var pos = Pos{} if origin == nil { bounds := p.Rect() pos = bounds.Center() } else { pos = *origin } angle := zmath.DegToRad(deg) m := MatrixIdentity.RotatedAroundPos(pos, angle) return p.Transformed(&m) } func (p *Path) ForEachPart(forPart func(part PathNode)) { for _, ppt := range p.nodes { forPart(ppt) } } func (p *Path) AddRect(rect Rect, corner Size) { if !rect.Size.IsNull() { if corner.IsNull() || rect.Size.W == 0 || rect.Size.H == 0 { p.MoveTo(rect.TopLeft()) p.LineTo(rect.TopRight()) p.LineTo(rect.BottomRight()) p.LineTo(rect.BottomLeft()) p.Close() } else { min := rect.Min() max := rect.Max() p.MoveTo(Pos{min.X + corner.W, min.Y}) p.LineTo(Pos{max.X - corner.W, min.Y}) p.QuadCurveTo(Pos{max.X, min.Y}, Pos{max.X, min.Y + corner.H}) p.LineTo(Pos{max.X, max.Y - corner.H}) p.QuadCurveTo(Pos{max.X, max.Y}, Pos{max.X - corner.H, max.Y}) p.LineTo(Pos{min.X + corner.W, max.Y}) p.QuadCurveTo(Pos{min.X, max.Y}, Pos{min.X, max.Y - corner.H}) p.LineTo(Pos{min.X, min.Y + corner.H}) p.QuadCurveTo(Pos{min.X, min.Y}, Pos{min.X + corner.W, min.Y}) p.Close() } } } func (p *Path) AddStar(rect Rect, points int, inRatio float32) { c := rect.Center() delta := (rect.Size.W / 2) - 1 inAmount := (1 - inRatio) for i := 0; i < points*2; i++ { deg := float64(360*i+720) / float64(points*2) d := PosFromAngleDeg(deg).TimesD(delta) if i&1 != 0 { d.MultiplyD(float64(inAmount)) } pos := c.Plus(d) if i != 0 { p.LineTo(pos) } else { p.MoveTo(pos) } } p.Close() } func (p *Path) ArcDegFromCenter(center Pos, radius Size, degStart float64, degEnd float64) { clockwise := !(degStart > degEnd) rect := Rect{Size: radius.TimesD(2)}.Centered(center) rect = rect.ExpandedToInt() p.ArcTo(rect, degStart, degEnd-degStart, clockwise) } func (p *Path) Circle(center Pos, radius Size) { p.ArcDegFromCenter(center, radius, 0, 360) }
zgeo/path.go
0.576304
0.540196
path.go
starcoder
package config import "fmt" type array struct { storage map[string][]interface{} } func (a *array) String() string { return fmt.Sprintf("%v", a.storage) } func (a *array) Add(name string, value ...interface{}) { _, ok := a.storage[name] if !ok { a.storage[name] = make([]interface{}, 0) } a.storage[name] = append(a.storage[name], value...) } func (a *array) Get(name string) ([]interface{}, bool) { arr, ok := a.storage[name] return arr, ok } func (a *array) GetIndex(name string, index int) (interface{}, bool) { if arr, ok := a.storage[name]; ok && index < len(arr) { return arr[index], true } return nil, false } func (a *array) GetIndexBool(name string, index int) (bool, bool) { if arr, ok := a.storage[name]; ok && index < len(arr) { return arr[index].(bool), true } return false, false } func (a *array) GetIndexFloat64(name string, index int) (float64, bool) { if arr, ok := a.storage[name]; ok && index < len(arr) { return arr[index].(float64), true } return 0, false } func (a *array) GetIndexInt(name string, index int) (int, bool) { if arr, ok := a.storage[name]; ok && index < len(arr) { return arr[index].(int), true } return 0, false } func (a *array) GetIndexInt32(name string, index int) (int32, bool) { if arr, ok := a.storage[name]; ok && index < len(arr) { return arr[index].(int32), true } return 0, false } func (a *array) GetIndexInt64(name string, index int) (int64, bool) { if arr, ok := a.storage[name]; ok && index < len(arr) { return arr[index].(int64), true } return 0, false } func (a *array) GetIndexString(name string, index int) (string, bool) { if arr, ok := a.storage[name]; ok && index < len(arr) { return arr[index].(string), true } return "", false } func (a *array) GetIndexUint(name string, index int) (uint, bool) { if arr, ok := a.storage[name]; ok && index < len(arr) { return arr[index].(uint), true } return 0, false } func (a *array) GetIndexUint32(name string, index int) (uint32, bool) { if arr, ok := a.storage[name]; ok && index < len(arr) { return arr[index].(uint32), true } return 0, false } func (a *array) GetIndexUint64(name string, index int) (uint64, bool) { if arr, ok := a.storage[name]; ok && index < len(arr) { return arr[index].(uint64), true } return 0, false }
internal/config/array.go
0.538741
0.415254
array.go
starcoder
package vfilter import ( "image" "sync" "github.com/emer/etable/etensor" "github.com/emer/vision/nproc" ) // ConvDiff computes difference of two separate filter convolutions // (fltOn - fltOff) over two images into out. There are separate gain // multipliers for On and overall gain. // images *must* have border (padding) so that filters are // applied without any bounds checking -- wrapping etc is all // done in the padding process, which is much more efficient. // Computation is parallel in image lines. // img must be a 2D tensor of image values (grey or single components). // Everything must be organized row major as etensor default. // Output has 2 outer dims for positive vs. negative values, inner is Y, X func ConvDiff(geom *Geom, fltOn, fltOff *etensor.Float32, imgOn, imgOff, out *etensor.Float32, gain, gainOn float32) { fy := fltOn.Dim(0) fx := fltOn.Dim(1) geom.FiltSz = image.Point{fx, fy} geom.UpdtFilt() imgSz := image.Point{imgOn.Dim(1), imgOn.Dim(0)} geom.SetSize(imgSz) oshp := []int{2, int(geom.Out.Y), int(geom.Out.X)} if !etensor.EqualInts(oshp, out.Shp) { out.SetShape(oshp, nil, []string{"OnOff", "Y", "X"}) } ncpu := nproc.NumCPU() nthrs, nper, rmdr := nproc.ThreadNs(ncpu, geom.Out.Y) var wg sync.WaitGroup for th := 0; th < nthrs; th++ { wg.Add(1) yst := th * nper go convDiffThr(&wg, geom, yst, nper, fltOn, fltOff, imgOn, imgOff, out, gain, gainOn) } if rmdr > 0 { wg.Add(1) yst := nthrs * nper go convDiffThr(&wg, geom, yst, rmdr, fltOn, fltOff, imgOn, imgOff, out, gain, gainOn) } wg.Wait() } // convDiffThr is per-thread implementation func convDiffThr(wg *sync.WaitGroup, geom *Geom, yst, ny int, fltOn, fltOff *etensor.Float32, imgOn, imgOff, out *etensor.Float32, gain, gainOn float32) { ist := geom.Border.Sub(geom.FiltLt) for yi := 0; yi < ny; yi++ { y := yst + yi iy := int(ist.Y + y*geom.Spacing.Y) for x := 0; x < geom.Out.X; x++ { ix := ist.X + x*geom.Spacing.X var sumOn, sumOff float32 fi := 0 for fy := 0; fy < geom.FiltSz.Y; fy++ { for fx := 0; fx < geom.FiltSz.X; fx++ { idx := imgOn.Offset([]int{iy + fy, ix + fx}) sumOn += imgOn.Values[idx] * fltOn.Values[fi] sumOff += imgOff.Values[idx] * fltOff.Values[fi] fi++ } } diff := gain * (gainOn*sumOn - sumOff) if diff > 0 { out.Set([]int{0, y, x}, diff) out.Set([]int{1, y, x}, float32(0)) } else { out.Set([]int{0, y, x}, float32(0)) out.Set([]int{1, y, x}, -diff) } } } wg.Done() }
vfilter/convdiff.go
0.562417
0.461927
convdiff.go
starcoder
package mosaic import ( "errors" "fmt" "github.com/disintegration/imaging" "github.com/fogleman/gg" "github.com/gieseladev/mosaic/pkg/geom" "image" "math" "sync" ) var ( // ErrInvalidImageCount is the error returned, when an invalid amount of // images is passed to a composer. ErrInvalidImageCount = errors.New("invalid number of images") ) var ( circleCornerAngles = []float64{0, geom.HalfPi, math.Pi, 3 * geom.HalfPi} circleCornerPoints = []geom.Point{{1, 0}, {0, 1}, {-1, 0}, {0, -1}} ) func CirclesPie(dc *gg.Context, images ...image.Image) error { w := dc.Width() h := dc.Height() var s int if w > h { s = h } else { s = w } angle := geom.TwoPi / float64(len(images)) maskDC := gg.NewContext(w, h) radius := geom.InnerSquareRadius(float64(s)) centerPoint := geom.Pt(float64(w)/2, float64(h)/2) for i, img := range images { maskDC.Clear() startAngle := float64(i) * angle endAngle := startAngle + angle drawSlice(maskDC, centerPoint.X, centerPoint.Y, radius, startAngle, endAngle) maskDC.Fill() _ = dc.SetMask(maskDC.AsMask()) rect := geom.RectContainingPoints( centerPoint, geom.PtFromPolar(radius, startAngle).Add(centerPoint), geom.PtFromPolar(radius, endAngle).Add(centerPoint), ) // ensure the rect covers all of the circle for i, angle := range circleCornerAngles { if geom.AngleStrictlyBetween(angle, startAngle, endAngle) { pp := circleCornerPoints[i].Mul(radius).Add(centerPoint) rect = rect.GrowToContain(pp) } } img = imaging.Fill(img, int(math.Ceil(rect.Width())), int(math.Ceil(rect.Height())), imaging.Center, imaging.Lanczos) dc.DrawImage(img, int(rect.Min.X), int(rect.Min.Y)) } return nil } func TilesPerfect(dc *gg.Context, images ...image.Image) error { w := dc.Width() h := dc.Height() nH, nV := geom.FindBalancedFactors(len(images)) imgW := w / nH imgH := h / nV for i, img := range images { column := i % nH row := i / nH img = imaging.Fill(img, imgW, imgH, imaging.Center, imaging.Lanczos) dc.DrawImage(img, column*imgW, row*imgH) } return nil } func TilesFocused(dc *gg.Context, images ...image.Image) error { if len(images) < 2 { return ErrInvalidImageCount } w, h := dc.Width(), dc.Height() totalSize := geom.Pt(float64(w), float64(h)) evenDiff := len(images) % 2 evenImages := len(images) - evenDiff unevenImages := len(images) - (1 - evenDiff) horizontalRatio := float64(unevenImages-1) / float64(unevenImages+1) verticalRatio := float64(evenImages-2) / float64(evenImages) focusSize := totalSize.Scale(geom.Pt( horizontalRatio, verticalRatio, )) focusX, focusY := int(focusSize.X), int(focusSize.Y) otherSize := totalSize.Sub(focusSize) otherX, otherY := int(otherSize.X), int(otherSize.Y) focusImg := imaging.Fill(images[0], focusX, focusY, imaging.Center, imaging.Lanczos) dc.DrawImage(focusImg, 0, h-focusY) trImg := imaging.Fill(images[1], otherX, otherY, imaging.Center, imaging.Lanczos) dc.DrawImage(trImg, focusX, 0) i := 1 for imgI := 2; imgI < len(images); imgI += 2 { topImg := imaging.Fill(images[imgI], otherX, otherY, imaging.Center, imaging.Lanczos) dc.DrawImageAnchored(topImg, w-i*otherX, 0, 1, 0) rightI := imgI + 1 if rightI < len(images) { rightImg := imaging.Fill(images[rightI], otherX, otherY, imaging.Center, imaging.Lanczos) dc.DrawImage(rightImg, focusX, i*otherY) } i++ } return nil } func TilesDiamond(dc *gg.Context, images ...image.Image) error { if len(images) < 1 { return ErrInvalidImageCount } w, h := dc.Width(), dc.Height() sqSize := geom. RectWithSideLengths(geom.Pt(float64(w), float64(h))). InnerCenterSquare() center := sqSize.Center() diaSquare := sqSize.ScaleFromCenter(3 * math.Sqrt2 / (13 + math.Sqrt2)) diaPoly := diaSquare.RotateAroundCenter(geom.QuarterPi) diaBounds := diaPoly.BoundingRect() diaPolySize := int(diaBounds.Width()) img := imaging.Fill(images[0], diaPolySize, diaPolySize, imaging.Center, imaging.Lanczos) maskDC := gg.NewContext(w, h) drawPolygon(maskDC, diaPoly) maskDC.Fill() _ = dc.SetMask(maskDC.AsMask()) dc.DrawImageAnchored(img, w/2, h/2, .5, .5) if len(images) < 5 { return nil } var mut sync.Mutex var wg sync.WaitGroup defer wg.Wait() drawImages := func(images []image.Image, poly geom.Polygon, radius float64, startAngle float64) { maskDC := gg.NewContext(w, h) bounds := poly.BoundingRect() polyWidth := int(bounds.Width()) polyHeight := int(bounds.Height()) for i, img := range images { translation := geom.PtFromPolar(radius, startAngle+float64(i)*geom.HalfPi) pos := translation.Add(center) // no need to clear mask because images are far enough apart drawPolygon(maskDC, poly.Translate(translation)) maskDC.Fill() img = imaging.Fill(img, polyWidth, polyHeight, imaging.Center, imaging.Lanczos) mut.Lock() _ = dc.SetMask(maskDC.AsMask()) dc.DrawImageAnchored(img, int(pos.X), int(pos.Y), .5, .5) mut.Unlock() } wg.Done() } wg.Add(1) go drawImages(images[1:5], diaPoly, diaSquare.Width(), geom.QuarterPi) if len(images) < 9 { return nil } smallDiaPoly := diaPoly.ScaleFromCenter(2. / 3) smallDiaBounds := smallDiaPoly.BoundingRect() wg.Add(1) go drawImages(images[5:9], smallDiaPoly, (diaBounds.Width()+smallDiaBounds.Width())/2, 0) if len(images) < 13 { return nil } wg.Add(1) go drawImages(images[9:13], smallDiaPoly, diaSquare.Width()*11/6, geom.QuarterPi) return nil } func StripesVertical(dc *gg.Context, images ...image.Image) error { w := dc.Width() h := dc.Height() stripeWidth := float64(w) / float64(len(images)) maskDC := gg.NewContext(w, h) for i, img := range images { img = imaging.Fill(img, w, h, imaging.Center, imaging.Lanczos) iF64 := float64(i) maskDC.Clear() maskDC.DrawRectangle(iF64*stripeWidth, 0, stripeWidth, float64(h)) maskDC.Fill() _ = dc.SetMask(maskDC.AsMask()) dc.DrawImage(img, 0, 0) } return nil } func StripesVerticalMulti(dc *gg.Context, images ...image.Image) error { imgCountF := float64(len(images)) stripeCountF := math.Ceil(math.Sqrt(imgCountF)) stripeCount := int(stripeCountF) completeLevelsCountF := math.Floor(imgCountF / stripeCountF) completeLevelsCount := int(completeLevelsCountF) remainingImgCountF := imgCountF - stripeCountF*completeLevelsCountF remainingImgCount := int(remainingImgCountF) stripeImageCounts := make([]int, stripeCount) for i := 0; i < stripeCount; i++ { stripeImageCounts[i] = completeLevelsCount } // should we place an extra image in the middle? if remainingImgCount%2 != 0 && stripeCount%2 != 0 { midI := stripeCount / 2 stripeImageCounts[midI]++ remainingImgCount-- } for leftI := 0; leftI < remainingImgCount; leftI += 2 { stripeImageCounts[leftI]++ rightI := leftI + 1 if rightI < remainingImgCount { stripeImageCounts[len(stripeImageCounts)-rightI]++ } } stripeWidthF := float64(dc.Width()) / stripeCountF stripeWidth := int(stripeWidthF) var imgI int for stripeI, stripeImgCount := range stripeImageCounts { var yOffset int for i := 0; i < stripeImgCount; i++ { imgHeight := dc.Height() / stripeImgCount img := imaging.Fill(images[imgI], stripeWidth, imgHeight, imaging.Center, imaging.Lanczos) imgI++ dc.DrawImage(img, int(float64(stripeI)*stripeWidthF), yOffset) yOffset += imgHeight } } return nil } func init() { err := RegisterComposer( ComposerInfo{ Composer: ComposerFunc(CirclesPie), Id: "circles-pie", Name: "Pie (Circle)", RecommendedImageCounts: []int{3, 5}, }, ComposerInfo{ Composer: ComposerFunc(TilesPerfect), Id: "tiles-perfect", Name: "Perfect (Tile)", RecommendedImageCounts: []int{4, 6, 9, 12, 16}, }, ComposerInfo{ Composer: ComposerFunc(TilesFocused), Id: "tiles-focused", Name: "Focused (Tile)", ImageCountHuman: "more than two, optimally more than three", CheckImageCount: func(count int) bool { return count >= 2 }, RecommendedImageCounts: []int{4, 5, 6, 7, 8, 9}, }, ComposerInfo{ Composer: ComposerFunc(TilesDiamond), Id: "tiles-diamond", Name: "Diamond (Tile)", RecommendedImageCounts: []int{5, 9, 13}, }, ComposerInfo{ Composer: ComposerFunc(StripesVertical), Id: "stripes-vertical", Name: "Vertical (Stripes)", RecommendedImageCounts: []int{3, 4, 5}, }, ComposerInfo{ Composer: ComposerFunc(StripesVerticalMulti), Id: "stripes-vertical-multi", Name: "Vertical Multi (Stripes)", RecommendedImageCounts: []int{3, 5, 7}, }, ) if err != nil { panic(fmt.Sprintf("couldn't register all built-in composers: %v", err)) } }
composers.go
0.68437
0.416144
composers.go
starcoder
package bitslice import ( "strconv" ) // BitSlice is a bit array type BitSlice struct { // buf is the underlying byte slice storing the bits buf []byte // len is the number of bits stored in buf len int64 } // New creates a BitSlice with l zeroed bits with the capacity to store c bits, // rounded up to the nearest octet. Panics if l > c, l < 0, or c < 0. func New(l int64, c int64) BitSlice { return BitSlice{ // Round l and c up to nearest octet buf: make([]byte, (l+7)/8, (c+7)/8), len: l, } } // Len returns the number of bits stored in the BitSlice func (b BitSlice) Len() int64 { return b.len } // Cap returns the capacity of the BitSlice in bits func (b BitSlice) Cap() int64 { return int64(cap(b.buf)) * 8 } // Get returns the bit at position i. If i is out of range, it panics. func (b BitSlice) Get(i int64) bool { if i >= b.len { panic("index of out range [" + strconv.FormatInt(i, 10) + "] with length " + strconv.FormatInt(b.len, 10)) } var mask byte = 1 << (i % 8) return (b.buf[i/8] & mask) > 0 } // Set sets the bit at position i to v. If i is out of range, it panics. func (b BitSlice) Set(i int64, v bool) { if i >= b.len { panic("index of out range [" + strconv.FormatInt(i, 10) + "] with length " + strconv.FormatInt(b.len, 10)) } var mask byte = 1 << (i % 8) if v { b.buf[i/8] |= mask } else { b.buf[i/8] &= ^mask } } // Append adds bits to the end of the BitSlice much like the built-in append for // slices. If the BitSlice has sufficient capacity, the underlying buffer is // resliced to accommodate the new bits. If it does not, a new underlying array // will be allocated. Append returns the updated BitSlice. func (b BitSlice) Append(bits ...bool) BitSlice { bitsI := 0 // Index of next bit to be added var mask byte // Use `b.buf[bufI] |= mask` to set current bit bufI := int(b.len / 8) // Index of next byte in b to be written mask = 1 << (b.len % 8) if mask > 1 { // Fill last byte in b with bits for ; bitsI < len(bits) && mask > 0; bitsI++ { if bits[bitsI] { // Set bit b.buf[bufI] |= mask } mask <<= 1 } } // Iterate through each bit, appending bytes to b.buf until done var curByte byte if bitsI < len(bits) { for mask = 1; bitsI < len(bits); bitsI++ { if mask == 0 { // Append byte and reset b.buf = append(b.buf, curByte) curByte = 0 mask = 1 } if bits[bitsI] { curByte |= mask } mask <<= 1 } // Append partial byte b.buf = append(b.buf, curByte) } // Update BitSlice length and return b.len += int64(len(bits)) return b } // AppendBytes pads the last byte of the BitSlice with zeroes and appends bytes // to the end of the BitSlice func (b BitSlice) AppendBytes(bytes ...byte) BitSlice { b.buf = append(b.buf, bytes...) b.len = int64(len(b.buf)) * 8 return b } // Bytes returns the underlying byte slice storing the bits func (b BitSlice) Bytes() []byte { return b.buf }
bitslice.go
0.737914
0.563558
bitslice.go
starcoder
package msgpack import ( "encoding/binary" "fmt" "io" "math" "reflect" "time" xbytes "go.nanasi880.dev/x/bytes" xunsafe "go.nanasi880.dev/x/unsafe" ) // Unmarshaler is the interface implemented by types that // can unmarshal themselves into valid message pack. type Unmarshaler interface { UnmarshalMsgPack(d *Decoder) error } // Unmarshal is decode message pack data to any data. func Unmarshal(b []byte, v interface{}) error { return NewDecoderBytes(b).Decode(v) } // UnmarshalStringKey is decode message pack data to any data. func UnmarshalStringKey(b []byte, v interface{}) error { return NewDecoderBytes(b).SetStructKeyType(StructKeyTypeString).Decode(v) } // Decoder is message pack decoder. type Decoder struct { data []byte reader *xbytes.BinaryReader work []byte structKeyType StructKeyType arrayLengthTolerance ArrayLengthTolerance timeZone *time.Location } // NewDecoder is create decoder instance. func NewDecoder(r io.Reader) *Decoder { return &Decoder{ data: nil, reader: xbytes.NewBinaryReader(r), work: make([]byte, readBlockSize), structKeyType: StructKeyTypeInt, arrayLengthTolerance: ArrayLengthToleranceLessThanOrEqual, timeZone: nil, } } // NewDecoderBytes is create decoder instance. func NewDecoderBytes(in []byte) *Decoder { if in == nil { in = make([]byte, 0) } return &Decoder{ data: in, reader: nil, work: make([]byte, readBlockSize), structKeyType: StructKeyTypeInt, arrayLengthTolerance: ArrayLengthToleranceLessThanOrEqual, timeZone: nil, } } // Reset is reset decoder. However, the work buffer will not be reset. func (d *Decoder) Reset(r io.Reader) { *d = Decoder{ data: nil, reader: d.reader, work: d.work, structKeyType: StructKeyTypeInt, arrayLengthTolerance: ArrayLengthToleranceLessThanOrEqual, timeZone: nil, } if d.reader == nil { d.reader = xbytes.NewBinaryReader(r) } d.reader.Reset(r) } // ResetBytes is reset decoder. However, the work buffer will not be reset. func (d *Decoder) ResetBytes(in []byte) { if in == nil { in = make([]byte, 0) } *d = Decoder{ data: in, reader: d.reader, work: d.work, structKeyType: StructKeyTypeInt, arrayLengthTolerance: ArrayLengthToleranceLessThanOrEqual, timeZone: nil, } if d.reader != nil { d.reader.Reset(nil) } } // SetStructKeyType is set StructKeyType to Decoder. func (d *Decoder) SetStructKeyType(t StructKeyType) *Decoder { d.structKeyType = t return d } // SetArrayLengthTolerance is set ArrayLengthTolerance to Decoder. func (d *Decoder) SetArrayLengthTolerance(tolerance ArrayLengthTolerance) *Decoder { d.arrayLengthTolerance = tolerance return d } // SetTimeZone is set time zone to Decoder. // The decoder will set this time zone to the time when decoding. If loc is nil, use the UTC time. func (d *Decoder) SetTimeZone(loc *time.Location) *Decoder { d.timeZone = loc return d } // Decode is decode data from message pack. func (d *Decoder) Decode(v interface{}) (e error) { defer func() { r := recover() if r != nil { e = fmt.Errorf("%v", r) } }() if v == nil { return fmt.Errorf("nil") } rv := reflect.ValueOf(v) if rv.Kind() != reflect.Ptr { return fmt.Errorf("rv.kind() != reflect.Ptr") } return d.decodeValue(rv) } // DecodeFormat is decode format from message pack. func (d *Decoder) DecodeFormat() (Format, error) { name, raw, err := d.readFormat() return Format{ Name: name, Raw: raw, }, err } // DecodeInt64 is decode integer type as int64 from message pack. func (d *Decoder) DecodeInt64(format Format) (int64, error) { i, err := d.decodeIntBit(format.Name, format.Raw) return int64(i), err } // DecodeUint64 is decode integer type as uint64 from message pack. func (d *Decoder) DecodeUint64(format Format) (uint64, error) { return d.decodeIntBit(format.Name, format.Raw) } // DecodeFloat32 is decode float type as float32 from message pack. func (d *Decoder) DecodeFloat32(format Format) (float32, error) { switch format.Name { case Float32: val, err := d.read(4) if err != nil { return 0, err } return math.Float32frombits(binary.BigEndian.Uint32(val)), nil case Float64: val, err := d.read(8) if err != nil { return 0, err } return float32(math.Float64frombits(binary.BigEndian.Uint64(val))), nil default: return 0, fmt.Errorf("invalid format: %s", format.String()) } } // DecodeFloat64 is decode float type as float64 from message pack. func (d *Decoder) DecodeFloat64(format Format) (float64, error) { switch format.Name { case Float32: val, err := d.read(4) if err != nil { return 0, err } return float64(math.Float32frombits(binary.BigEndian.Uint32(val))), nil case Float64: val, err := d.read(8) if err != nil { return 0, err } return math.Float64frombits(binary.BigEndian.Uint64(val)), nil default: return 0, fmt.Errorf("invalid format: %s", format.String()) } } // DecodeString is decode string type or bin type as string from message pack. func (d *Decoder) DecodeString(format Format) (string, error) { var ( length int err error ) switch format.Name { case Bin8, Bin16, Bin32: length, err = d.decodeBinHeader(format.Name) case FixStr, Str8, Str16, Str32: length, err = d.decodeStringHeader(format.Name, format.Raw) default: return "", fmt.Errorf("invalid format: %s", format.String()) } if err != nil { return "", err } tmp, err := d.decodeBytes(length) if err != nil { return "", err } return xunsafe.BytesToString(tmp), nil } // DecodeTime is decode time from message pack. func (d *Decoder) DecodeTime(header ExtHeader) (time.Time, error) { return d.decodeTime(header.Length) } // DecodeExtHeader is decode ext header from message pack. func (d *Decoder) DecodeExtHeader(format Format) (ExtHeader, error) { typeCode, length, err := d.decodeExtHeader(format.Name) return ExtHeader{ Format: format, Type: typeCode, Length: length, }, err } // DecodeArrayHeader is decode array header from message pack. func (d *Decoder) DecodeArrayHeader(format Format) (ArrayHeader, error) { length, err := d.decodeArrayHeader(format.Name, format.Raw) return ArrayHeader{ Format: format, Length: length, }, err } // DecodeMapHeader is decode map header from message pack. func (d *Decoder) DecodeMapHeader(format Format) (MapHeader, error) { length, err := d.decodeMapHeader(format.Name, format.Raw) return MapHeader{ Format: format, Length: length, }, err } // SkipObject is seek current message pack object. func (d *Decoder) SkipObject(format Format) error { return d.skipObject(format.Name, format.Raw) }
encoding/msgpack/decoder.go
0.711732
0.433322
decoder.go
starcoder
package unique import "sort" // Types that implement unique.Interface can have duplicate elements removed by // the functionality in this package. type Interface interface { sort.Interface // Truncate reduces the length to the first n elements. Truncate(n int) } // Unique removes duplicate elements from data. It assumes sort.IsSorted(data). func Unique(data Interface) { data.Truncate(ToFront(data)) } // ToFront reports the number of unique elements of data which it moves to the // first n positions. It assumes sort.IsSorted(data). func ToFront(data sort.Interface) (n int) { n = data.Len() if n == 0 { return } k := 0 for i := 1; i < n; i++ { if data.Less(k, i) { k++ data.Swap(k, i) } } return k + 1 } // Sort sorts and removes duplicate entries from data. func Sort(data Interface) { sort.Sort(data) Unique(data) } // IsUniqued reports whether the elements in data are sorted and unique. func IsUniqued(data sort.Interface) bool { n := data.Len() for i := n - 1; i > 0; i-- { if !data.Less(i-1, i) { return false } } return true } // Float64Slice attaches the methods of Interface to []float64. type Float64Slice struct{ P *[]float64 } func (p Float64Slice) Len() int { return len(*p.P) } func (p Float64Slice) Swap(i, j int) { (*p.P)[i], (*p.P)[j] = (*p.P)[j], (*p.P)[i] } func (p Float64Slice) Less(i, j int) bool { return (*p.P)[i] < (*p.P)[j] } func (p Float64Slice) Truncate(n int) { *p.P = (*p.P)[:n] } // Float64s removes duplicate elements from a sorted slice of float64s. func Float64s(a *[]float64) { Unique(Float64Slice{a}) } // Float64sAreUnique tests whether a slice of float64s is sorted and its // elements are unique. func Float64sAreUnique(a []float64) bool { return IsUniqued(sort.Float64Slice(a)) } // IntSlice attaches the methods of Interface to []int. type IntSlice struct{ P *[]int } func (p IntSlice) Len() int { return len(*p.P) } func (p IntSlice) Swap(i, j int) { (*p.P)[i], (*p.P)[j] = (*p.P)[j], (*p.P)[i] } func (p IntSlice) Less(i, j int) bool { return (*p.P)[i] < (*p.P)[j] } func (p IntSlice) Truncate(n int) { *p.P = (*p.P)[:n] } // Ints removes duplicate elements from a sorted slice of ints. func Ints(a *[]int) { Unique(IntSlice{a}) } // IntsAreUnique tests whether a slice of ints is sorted and its elements are // unique. func IntsAreUnique(a []int) bool { return IsUniqued(sort.IntSlice(a)) } // StringSlice attaches the methods of Interface to []string. type StringSlice struct{ P *[]string } func (p StringSlice) Len() int { return len(*p.P) } func (p StringSlice) Swap(i, j int) { (*p.P)[i], (*p.P)[j] = (*p.P)[j], (*p.P)[i] } func (p StringSlice) Less(i, j int) bool { return (*p.P)[i] < (*p.P)[j] } func (p StringSlice) Truncate(n int) { *p.P = (*p.P)[:n] } // Strings removes duplicate elements from a sorted slice of strings. func Strings(a *[]string) { Unique(StringSlice{a}) } // StringsAreUnique tests whether a slice of strings is sorted and its elements // are unique. func StringsAreUnique(a []string) bool { return IsUniqued(sort.StringSlice(a)) }
vendor/github.com/mpvl/unique/unique.go
0.739799
0.558809
unique.go
starcoder
package square // Defines how discounts are automatically applied to a set of items that match the pricing rule during the active time period. type CatalogPricingRule struct { // User-defined name for the pricing rule. For example, \"Buy one get one free\" or \"10% off\". Name string `json:"name,omitempty"` // A list of unique IDs for the catalog time periods when this pricing rule is in effect. If left unset, the pricing rule is always in effect. TimePeriodIds []string `json:"time_period_ids,omitempty"` // Unique ID for the `CatalogDiscount` to take off the price of all matched items. DiscountId string `json:"discount_id,omitempty"` // Unique ID for the `CatalogProductSet` that will be matched by this rule. A match rule matches within the entire cart, and can match multiple times. This field will always be set. MatchProductsId string `json:"match_products_id,omitempty"` // __Deprecated__: Please use the `exclude_products_id` field to apply an exclude set instead. Exclude sets allow better control over quantity ranges and offer more flexibility for which matched items receive a discount. `CatalogProductSet` to apply the pricing to. An apply rule matches within the subset of the cart that fits the match rules (the match set). An apply rule can only match once in the match set. If not supplied, the pricing will be applied to all products in the match set. Other products retain their base price, or a price generated by other rules. ApplyProductsId string `json:"apply_products_id,omitempty"` // `CatalogProductSet` to exclude from the pricing rule. An exclude rule matches within the subset of the cart that fits the match rules (the match set). An exclude rule can only match once in the match set. If not supplied, the pricing will be applied to all products in the match set. Other products retain their base price, or a price generated by other rules. ExcludeProductsId string `json:"exclude_products_id,omitempty"` // Represents the date the Pricing Rule is valid from. Represented in RFC 3339 full-date format (YYYY-MM-DD). ValidFromDate string `json:"valid_from_date,omitempty"` // Represents the local time the pricing rule should be valid from. Represented in RFC 3339 partial-time format (HH:MM:SS). Partial seconds will be truncated. ValidFromLocalTime string `json:"valid_from_local_time,omitempty"` // Represents the date the Pricing Rule is valid until. Represented in RFC 3339 full-date format (YYYY-MM-DD). ValidUntilDate string `json:"valid_until_date,omitempty"` // Represents the local time the pricing rule should be valid until. Represented in RFC 3339 partial-time format (HH:MM:SS). Partial seconds will be truncated. ValidUntilLocalTime string `json:"valid_until_local_time,omitempty"` // If an `exclude_products_id` was given, controls which subset of matched products is excluded from any discounts. Default value: `LEAST_EXPENSIVE` See [ExcludeStrategy](#type-excludestrategy) for possible values ExcludeStrategy string `json:"exclude_strategy,omitempty"` }
square/model_catalog_pricing_rule.go
0.753376
0.519095
model_catalog_pricing_rule.go
starcoder
package resmgr import ( "fmt" "path" "path/filepath" "strings" logger "github.com/intel/cri-resource-manager/pkg/log" ) // Evaluable is the interface objects need to implement to be evaluable against Expressions. type Evaluable interface { Eval(string) interface{} } // Expression is used to describe a criteria to select objects within a domain. type Expression struct { Key string `json:"key"` // key to check values of/against Op Operator `json:"operator"` // operator to apply to value of Key and Values Values []string `json:"values,omitempty"` // value(s) for domain key } const ( KeyPod = "pod" KeyID = "id" KeyUID = "uid" KeyName = "name" KeyNamespace = "namespace" KeyQOSClass = "qosclass" KeyLabels = "labels" KeyTags = "tags" ) // Operator defines the possible operators for an Expression. type Operator string const ( // Equals tests for equality with a single value. Equals Operator = "Equals" // NotEqual test for inequality with a single value. NotEqual Operator = "NotEqual" // In tests if the key's value is one of the specified set. In Operator = "In" // NotIn tests if the key's value is not one of the specified set. NotIn Operator = "NotIn" // Exists evalutes to true if the named key exists. Exists Operator = "Exists" // NotExist evalutes to true if the named key does not exist. NotExist Operator = "NotExist" // AlwaysTrue always evaluates to true. AlwaysTrue = "AlwaysTrue" // Matches tests if the key value matches the only given globbing pattern. Matches = "Matches" // MatchesNot is true if Matches would be false for the same key and pattern. MatchesNot = "MatchesNot" // MatchesAny tests if the key value matches any of the given globbing patterns. MatchesAny = "MatchesAny" // MatchesNone is true if MatchesAny would be false for the same key and patterns. MatchesNone = "MatchesNone" ) // Our logger instance. var log = logger.NewLogger("expression") // Validate checks the expression for (obvious) invalidity. func (e *Expression) Validate() error { if e == nil { return exprError("nil expression") } switch e.Op { case Equals, NotEqual: if len(e.Values) != 1 { return exprError("invalid expression, '%s' requires a single value", e.Op) } case Matches, MatchesNot: if len(e.Values) != 1 { return exprError("invalid expression, '%s' requires a single value", e.Op) } case Exists, NotExist: if e.Values != nil && len(e.Values) != 0 { return exprError("invalid expression, '%s' does not take any values", e.Op) } case In, NotIn: case MatchesAny, MatchesNone: case AlwaysTrue: default: return exprError("invalid expression, unknown operator: %q", e.Op) } return nil } // Evaluate evaluates an expression against a container. func (e *Expression) Evaluate(subject Evaluable) bool { log.Debug("evaluating %q @ %s...", *e, subject) value, ok := e.KeyValue(subject) result := false switch e.Op { case Equals: result = ok && (value == e.Values[0] || e.Values[0] == "*") case NotEqual: result = !ok || value != e.Values[0] case Matches, MatchesNot: match := false if ok { match, _ = filepath.Match(e.Values[0], value) } result = ok && match if e.Op == MatchesNot { result = !result } case In, NotIn: if ok { for _, v := range e.Values { if value == v || v == "*" { result = true } } } if e.Op == NotIn { result = !result } case MatchesAny, MatchesNone: if ok { for _, pattern := range e.Values { if match, _ := filepath.Match(pattern, value); match { result = true break } } } if e.Op == MatchesNone { result = !result } case Exists: result = ok case NotExist: result = !ok case AlwaysTrue: result = true } log.Debug("%q @ %s => %v", *e, subject, result) return result } // KeyValue extracts the value of the expresssion key from a container. func (e *Expression) KeyValue(subject Evaluable) (string, bool) { log.Debug("looking up %q @ %s...", e.Key, subject) value := "" ok := false keys, vsep := splitKeys(e.Key) if len(keys) == 1 { value, ok, _ = ResolveRef(subject, keys[0]) } else { vals := make([]string, 0, len(keys)) for _, key := range keys { v, found, _ := ResolveRef(subject, key) vals = append(vals, v) ok = ok || found } value = strings.Join(vals, vsep) } log.Debug("%q @ %s => %q, %v", e.Key, subject, value, ok) return value, ok } func splitKeys(keys string) ([]string, string) { // joint key specs have two valid forms: // - ":keylist" (equivalent to ":::<colon-separated-keylist>") // - ":<ksep><vsep><ksep-separated-keylist>" if len(keys) < 4 || keys[0] != ':' { return []string{keys}, "" } keys = keys[1:] ksep := keys[0:1] vsep := keys[1:2] if validSeparator(ksep[0]) && validSeparator(vsep[0]) { keys = keys[2:] } else { ksep = ":" vsep = ":" } return strings.Split(keys, ksep), vsep } func validSeparator(b byte) bool { switch { case '0' <= b && b <= '9': return false case 'a' <= b && b <= 'z': return false case 'A' <= b && b <= 'Z': return false case b == '/', b == '.': return false } return true } // ResolveRef walks an object trying to resolve a reference to a value. func ResolveRef(subject Evaluable, spec string) (string, bool, error) { var obj interface{} log.Debug("resolving %q @ %s...", spec, subject) spec = path.Clean(spec) ref := strings.Split(spec, "/") if len(ref) == 1 { if strings.Index(spec, ".") != -1 { ref = []string{"labels", spec} } } obj = subject for len(ref) > 0 { key := ref[0] log.Debug("resolve walking %q @ %s...", key, obj) switch v := obj.(type) { case string: obj = v case map[string]string: value, ok := v[key] if !ok { return "", false, nil } obj = value case error: return "", false, exprError("%s: failed to resolve %q: %v", subject, spec, v) default: e, ok := obj.(Evaluable) if !ok { return "", false, exprError("%s: failed to resolve %q, unexpected type %T", subject, spec, obj) } obj = e.Eval(key) } ref = ref[1:] } str, ok := obj.(string) if !ok { return "", false, exprError("%s: reference %q resolved to non-string: %T", subject, spec, obj) } log.Debug("resolved %q @ %s => %s", spec, subject, str) return str, true, nil } // String returns the expression as a string. func (e *Expression) String() string { return fmt.Sprintf("<%s %s %s>", e.Key, e.Op, strings.Join(e.Values, ",")) } // DeepCopy creates a deep copy of the expression. func (e *Expression) DeepCopy() *Expression { out := &Expression{} e.DeepCopyInto(out) return out } // DeepCopyInto copies the expression into another one. func (e *Expression) DeepCopyInto(out *Expression) { out.Key = e.Key out.Op = e.Op out.Values = make([]string, len(e.Values)) copy(out.Values, e.Values) } // exprError returns a formatted error specific to expressions. func exprError(format string, args ...interface{}) error { return fmt.Errorf("expression: "+format, args...) }
pkg/apis/resmgr/expression.go
0.68679
0.438545
expression.go
starcoder
package retina import ( "fmt" "github.com/pkg/errors" "github.com/yaricom/goESHyperNEAT/eshyperneat" "strings" ) // DetectionSide the side of retina where VisualObject is valid to be detected type DetectionSide string const ( RightSide = DetectionSide("right") LeftSide = DetectionSide("left") BothSide = DetectionSide("both") ) func (s DetectionSide) String() string { return string(s) } // Environment holds the dataset and evaluation methods for the modular retina experiment type Environment struct { visualObjects []VisualObject inputSize int context *eshyperneat.ESHyperNEATContext } // NewRetinaEnvironment creates a new Retina Environment with a dataset of all possible Visual Object with specified // number of inputs to be acquired from provided objects func NewRetinaEnvironment(dataSet []VisualObject, inputSize int, context *eshyperneat.ESHyperNEATContext) (*Environment, error) { // check that provided visual objects has data points equal to the inputSize for _, o := range dataSet { if len(o.data) != inputSize { return nil, errors.Errorf( "all viasual objects expected to have %d data points, but found %d at %v", inputSize, len(o.data), o) } } return &Environment{visualObjects: dataSet, inputSize: inputSize, context: context}, nil } // VisualObject represents a left, right, or both, object classified by retina type VisualObject struct { Side DetectionSide // the side(-s) of retina where this visual object accepted as valid Config string // the configuration string // Inner computed values from visual objects configuration parsing data []float64 // the visual object is rectangular, it can be encoded as 1D array } // NewVisualObject creates a new VisualObject by first parsing the config string into a VisualObject func NewVisualObject(side DetectionSide, config string) VisualObject { // Setup visual object data multi-array from config string return VisualObject{ Side: side, Config: config, data: parseVisualObjectConfig(config), } } func (o *VisualObject) String() string { return fmt.Sprintf("%s\n%s", o.Side, o.Config) } // parseVisualObjectConfig parses config semantically in the format // (config = "x1 x2 \n x3 x4") to [ x1, x2, x3, x4 ] where if xi == "o" => xi = 1 func parseVisualObjectConfig(config string) []float64 { data := make([]float64, 0) lines := strings.Split(config, "\n") for _, line := range lines { chars := strings.Split(line, " ") for _, char := range chars { switch char { case "o": // pixel is ON data = append(data, 1.0) case ".": // pixel is OFF data = append(data, 0.0) default: panic(fmt.Sprintf("unsupported configuration character [%s]", char)) } } } return data }
experiments/retina/environment.go
0.715921
0.495484
environment.go
starcoder
package vm func DivFunc(left, right func(Context) (Value, error)) func(Context) (Value, error) { return func(ctx Context) (Value, error) { leftValue, err := left(ctx) if err != nil { return Null(), err } rightValue, err := right(ctx) if err != nil { return Null(), err } return Div(leftValue, rightValue) } } func Div(leftValue, rightValue Value) (Value, error) { switch rightValue.Type { case ValueNull: return Null(), NewArithmeticError("/", leftValue.Type.String(), rightValue.Type.String()) case ValueBool: return Null(), NewArithmeticError("/", leftValue.Type.String(), rightValue.Type.String()) case ValueString: return Null(), NewArithmeticError("/", leftValue.Type.String(), rightValue.Type.String()) case ValueInt64: return divInt(leftValue, rightValue.Int64) case ValueUint64: return divUint(leftValue, rightValue.Uint64) case ValueFloat64: return divFloat(leftValue, rightValue.Float64) // case ValueDatetime: // return divDatetime(leftValue, IntToDatetime(rightValue.Int64)) // case ValueInterval: // return divInterval(leftValue, IntToInterval(rightValue.Int64)) default: return Null(), NewArithmeticError("/", leftValue.Type.String(), rightValue.Type.String()) } } func divInt(left Value, right int64) (Value, error) { switch left.Type { case ValueNull: return Null(), NewArithmeticError("/", left.Type.String(), "int") case ValueBool: return Null(), NewArithmeticError("/", left.Type.String(), "int") case ValueString: return Null(), NewArithmeticError("/", left.Type.String(), "int") case ValueInt64: return FloatToValue(float64(left.Int64) / float64(right)), nil case ValueUint64: return FloatToValue(float64(left.Uint64) / float64(right)), nil case ValueFloat64: return FloatToValue(left.Float64 / float64(right)), nil default: return Null(), NewArithmeticError("/", left.Type.String(), "int") } } func divUint(left Value, right uint64) (Value, error) { switch left.Type { case ValueNull: return Null(), NewArithmeticError("/", left.Type.String(), "uint") case ValueBool: return Null(), NewArithmeticError("/", left.Type.String(), "uint") case ValueString: return Null(), NewArithmeticError("/", left.Type.String(), "uint") case ValueInt64: return FloatToValue(float64(left.Int64) / float64(right)), nil case ValueUint64: return FloatToValue(float64(left.Uint64) / float64(right)), nil case ValueFloat64: return FloatToValue(left.Float64 / float64(right)), nil default: return Null(), NewArithmeticError("/", left.Type.String(), "uint") } } func divFloat(left Value, right float64) (Value, error) { switch left.Type { case ValueNull: return Null(), NewArithmeticError("/", left.Type.String(), "float") case ValueBool: return Null(), NewArithmeticError("/", left.Type.String(), "float") case ValueString: return Null(), NewArithmeticError("/", left.Type.String(), "float") case ValueInt64: return FloatToValue(float64(left.Int64) / float64(right)), nil case ValueUint64: return FloatToValue(float64(left.Uint64) / float64(right)), nil case ValueFloat64: return FloatToValue(left.Float64 / right), nil default: return Null(), NewArithmeticError("/", left.Type.String(), "float") } } // func divDatetime(left Value, right time.Time) (Value, error) { // if left.Type != ValueDatetime { // return Null(), NewArithmeticError("/", left.Type.String(), "datetime") // } // t := IntToDatetime(left.Int64) // return IntervalToValue(t.Sub(right)), nil // } // func divInterval(left Value, right time.Duration) (Value, error) { // switch left.Type { // case ValueDatetime: // t := IntToDatetime(left.Int64) // return DatetimeToValue(t.Add(-right)), nil // case ValueInterval: // t := IntToInterval(left.Int64) // return IntervalToValue(t -right), nil // default: // return Null(), NewArithmeticError("/", left.Type.String(), "datetime") // } // }
vm/div.go
0.620047
0.649301
div.go
starcoder
package audio import "math" // IntMaxSignedValue returns the max value of an integer // based on its memory size func IntMaxSignedValue(b int) int { switch b { case 8: return 255 / 2 case 16: return 65535 / 2 case 24: return 16777215 / 2 case 32: return 4294967295 / 2 default: return 0 } } // IEEEFloatToInt converts a 10 byte IEEE float into an int. func IEEEFloatToInt(b [10]byte) int { var i uint32 // Negative number if (b[0] & 0x80) == 1 { return 0 } // Less than 1 if b[0] <= 0x3F { return 1 } // Too big if b[0] > 0x40 { return 67108864 } // Still too big if b[0] == 0x40 && b[1] > 0x1C { return 800000000 } i = (uint32(b[2]) << 23) | (uint32(b[3]) << 15) | (uint32(b[4]) << 7) | (uint32(b[5]) >> 1) i >>= (29 - uint32(b[1])) return int(i) } // IntToIEEEFloat converts an int into a 10 byte IEEE float. func IntToIEEEFloat(i int) [10]byte { b := [10]byte{} num := float64(i) var sign int var expon int var fMant, fsMant float64 var hiMant, loMant uint if num < 0 { sign = 0x8000 } else { sign = 0 } if num == 0 { expon = 0 hiMant = 0 loMant = 0 } else { fMant, expon = math.Frexp(num) if (expon > 16384) || !(fMant < 1) { /* Infinity or NaN */ expon = sign | 0x7FFF hiMant = 0 loMant = 0 /* infinity */ } else { /* Finite */ expon += 16382 if expon < 0 { /* denormalized */ fMant = math.Ldexp(fMant, expon) expon = 0 } expon |= sign fMant = math.Ldexp(fMant, 32) fsMant = math.Floor(fMant) hiMant = uint(fsMant) fMant = math.Ldexp(fMant-fsMant, 32) fsMant = math.Floor(fMant) loMant = uint(fsMant) } } b[0] = byte(expon >> 8) b[1] = byte(expon) b[2] = byte(hiMant >> 24) b[3] = byte(hiMant >> 16) b[4] = byte(hiMant >> 8) b[5] = byte(hiMant) b[6] = byte(loMant >> 24) b[7] = byte(loMant >> 16) b[8] = byte(loMant >> 8) b[9] = byte(loMant) return b } // Uint24to32 converts a 3 byte uint23 into a uint32 // BigEndian! func Uint24to32(bytes []byte) uint32 { var output uint32 output |= uint32(bytes[2]) << 0 output |= uint32(bytes[1]) << 8 output |= uint32(bytes[0]) << 16 return output } // Int24BETo32 converts an int24 value from 3 bytes into an int32 value func Int24BETo32(bytes []byte) int32 { if len(bytes) < 3 { return 0 } ss := int32(0xFF&bytes[0])<<16 | int32(0xFF&bytes[1])<<8 | int32(0xFF&bytes[2]) if (ss & 0x800000) > 0 { ss |= ^0xffffff } return ss } // Int24LETo32 converts an int24 value from 3 bytes into an int32 value func Int24LETo32(bytes []byte) int32 { if len(bytes) < 3 { return 0 } ss := int32(bytes[0]) | int32(bytes[1])<<8 | int32(bytes[2])<<16 if (ss & 0x800000) > 0 { ss |= ^0xffffff } return ss } // Uint32toUint24Bytes converts a uint32 into a 3 byte uint24 representation func Uint32toUint24Bytes(n uint32) []byte { bytes := make([]byte, 3) bytes[0] = byte(n >> 16) bytes[1] = byte(n >> 8) bytes[2] = byte(n >> 0) return bytes } // Int32toInt24LEBytes converts an int32 into a little endian 3 byte int24 representation func Int32toInt24LEBytes(n int32) []byte { bytes := make([]byte, 3) if (n & 0x800000) > 0 { n |= ^0xffffff } bytes[2] = byte(n >> 16) bytes[1] = byte(n >> 8) bytes[0] = byte(n >> 0) return bytes } // Int32toInt24BEBytes converts an int32 into a big endian 3 byte int24 representation func Int32toInt24BEBytes(n int32) []byte { bytes := make([]byte, 3) if (n & 0x800000) > 0 { n |= ^0xffffff } bytes[0] = byte(n >> 16) bytes[1] = byte(n >> 8) bytes[2] = byte(n >> 0) return bytes }
vendor/github.com/go-audio/audio/conv.go
0.682468
0.448306
conv.go
starcoder
package financial // Sma (simple moving average (SMA)) calculates the average of a selected range of prices, //usually closing prices, by the number of periods in that range. type Sma struct { MovingAverage } // Calculate SMA. Formula for SMA https://www.investopedia.com/terms/s/sma.asp // There are 3 cases: // - When we start in a timeline with only one candle, we can safely take the value of the close as SMA // - When the Window is bigger than the amount of Candles, for instance there are 5 Candles but the Window // is 20. For this case the best effort is to resize the Window to len(Candles) and calculate SMA. For the next iteration // if the scenario repeats (6 Candles, windows 20) the same methodology is applied. // - Lastly, calculate an ordinary SMA func (si *Sma) Calculate() float64 { si.current++ si.previous = si.value // The first time there is no value, no calculation is needed so taking the values as it is should be fine if si.value == 0 { // Make sure that there is only one time series, if this is not the case, there should be already // some SMA calculated if len(si.TS.Candles) == 1 { si.value = si.TS.LastCandle().ClosePrice } return si.value } // If we dont have enough Candles to satisfy the windows, we calculate with what we have // TODO: Find a way better than iterating through the whole array if si.Window > len(si.TS.Candles)-1 { si.value = sma(si.TS.Candles, si.Window) return si.value } // We have calculated the previous SMA and we have enough Candles to calculate future SMAs drop := si.TS.Candles[len(si.TS.Candles)-(si.Window+1)].ClosePrice si.value = si.value + ((si.TS.LastCandle().ClosePrice - drop) / float64(si.Window)) return si.value } // Calculate sma by reverse iterating the whole array func sma(candles []Candle, window int) (r float64) { sum := 0.0 if len(candles) < window { window = len(candles) } for i := len(candles) - 1; i >= len(candles)-window; i-- { sum += candles[i].ClosePrice } r = sum / float64(window) return }
business/strategies/financial/sma.go
0.670608
0.697995
sma.go
starcoder
package logic import ( "context" "fmt" "log" "net/http" "time" "cloud.google.com/go/firestore" "google.golang.org/api/iterator" "google.golang.org/genproto/googleapis/type/latlng" "github.com/tidwall/geojson" "github.com/tidwall/geojson/geometry" ) // the GPS has some jitter. In general, lets discount readings if we have moved below this amounr const PRECISION float64 = 50.0 // this is the structure of what the pi stores in the database. type coordinateValue struct { Altitude float64 `firestore:"altitude,omitempty"` Geostamp *latlng.LatLng `firestore:"geostamp,omitempty"` Satellites float64 `firestore:"satellites,omitempty"` Timestamp time.Time `firestore:"timestamp,omitempty"` TimeTo time.Time `firestore:"timestamp_to,omitempty"` } // this is the working geoJSON with timestamp type pointWithTime struct { p *geojson.Point Satellites float64 t_from time.Time t_to time.Time } func (pt *pointWithTime) separation(p2 *pointWithTime) float64 { return pt.p.DistancePoint(p2.p.Base()) } // stringer func to enable debugging func (pt *pointWithTime) String() string { return fmt.Sprintf( "{x: %v y: %v z: %v from_time: %v to_time: %v}", pt.p.Base().X, pt.p.Base().Y, pt.p.Z(), pt.t_from, pt.t_to, ) } func convertToGeoJson(cv *coordinateValue) *pointWithTime { x := cv.Geostamp.Longitude y := cv.Geostamp.Latitude z := cv.Altitude return &pointWithTime{ p: geojson.NewPointZ(geometry.Point{X: x, Y: y}, z), Satellites: cv.Satellites, t_from: cv.Timestamp, t_to: cv.Timestamp, } } func convertToFirestoreFormat(pt *pointWithTime) *coordinateValue { return &coordinateValue{ Altitude: pt.p.Z(), Geostamp: &latlng.LatLng{ Latitude: pt.p.Base().X, Longitude: pt.p.Base().Y, }, Satellites: pt.Satellites, Timestamp: pt.t_from, TimeTo: pt.t_to, } } func listToFirestoreFormat(lpt []*pointWithTime) []*coordinateValue { r := make([]*coordinateValue, len(lpt)) for i, pt := range lpt { r[i] = convertToFirestoreFormat(pt) } return r } func readCoords(client *firestore.Client, ctx context.Context) []*pointWithTime { // get the coords time ordered. Oldest first log.Println("Accessing coordindates records in Firestore") orderedCoords := client.Collection("coordinates").OrderBy("timestamp", firestore.Asc).Documents(ctx) coordsRef, err := orderedCoords.GetAll() if err != nil { log.Fatal(err) } log.Printf("Accessing %v records", len(coordsRef)) var coords []*pointWithTime for _, c := range coordsRef { // cast to known struct var cval *coordinateValue c.DataTo(&cval) // convert to geo package point := convertToGeoJson(cval) if len(coords) > 0 && point.separation(coords[len(coords)-1]) < PRECISION { // basically, we want to ignore periods where the van is sat doing nothing // e.g. on the driveway, or in a carpark coords[len(coords)-1].t_to = point.t_from continue } coords = append(coords, point) } log.Printf("processing complete, coords left: %v", len(coords)) return coords } func writeNewRecord(c []*pointWithTime, client *firestore.Client, ctx context.Context) { write := make(map[string]interface{}) write["formatted"] = listToFirestoreFormat(c) today := fmt.Sprintf("%v", time.Now().Unix()) log.Printf("Creating new record with ID: %v", today) _, err := client.Collection("daily-updates").Doc(today).Set(ctx, write) if err != nil { log.Fatal(err) } log.Printf("New record written") } func deleteCollection(ctx context.Context, client *firestore.Client, ref *firestore.CollectionRef, batchSize int) error { for { iter := ref.Limit(batchSize).Documents(ctx) numDeleted := 0 batch := client.Batch() for { doc, err := iter.Next() if err == iterator.Done { break } if err != nil { return err } batch.Delete(doc.Ref) numDeleted++ } if numDeleted == 0 { return nil } _, err := batch.Commit(ctx) if err != nil { return err } } } func removeOutdatedCoords(client *firestore.Client, ctx context.Context) { log.Println("Removing outdated coordindates records in Firestore") coords := client.Collection("coordinates") err := deleteCollection(ctx, client, coords, 100) if err != nil { log.Fatal(err) } return } func ProcessCoords(w http.ResponseWriter, r *http.Request, client *firestore.Client, ctx context.Context) { coords := readCoords(client, ctx) writeNewRecord(coords, client, ctx) removeOutdatedCoords(client, ctx) }
cloud-processing/process-gps-points/logic/processCoords.go
0.628407
0.419172
processCoords.go
starcoder
package muxgo import ( "encoding/json" ) // AssetNonStandardInputReasons An object containing one or more reasons the input file is non-standard. See [the guide on minimizing processing time](https://docs.mux.com/guides/video/minimize-processing-time) for more information on what a standard input is defined as. This object only exists on on-demand assets that have non-standard inputs, so if missing you can assume the input qualifies as standard. type AssetNonStandardInputReasons struct { // The video codec used on the input file. For example, the input file encoded with `hevc` video codec is non-standard and the value of this parameter is `hevc`. VideoCodec *string `json:"video_codec,omitempty"` // The audio codec used on the input file. Non-AAC audio codecs are non-standard. AudioCodec *string `json:"audio_codec,omitempty"` // The video key frame Interval (also called as Group of Picture or GOP) of the input file is `high`. This parameter is present when the gop is greater than 10 seconds. VideoGopSize *string `json:"video_gop_size,omitempty"` // The video frame rate of the input file. Video with average frames per second (fps) less than 10 or greater than 120 is non-standard. A `-1` frame rate value indicates Mux could not determine the frame rate of the video track. VideoFrameRate *string `json:"video_frame_rate,omitempty"` // The video resolution of the input file. Video resolution higher than 2048 pixels on any one dimension (height or width) is considered non-standard, The resolution value is presented as `width` x `height` in pixels. VideoResolution *string `json:"video_resolution,omitempty"` // The video pixel aspect ratio of the input file. PixelAspectRatio *string `json:"pixel_aspect_ratio,omitempty"` // Video Edit List reason indicates that the input file's video track contains a complex Edit Decision List. VideoEditList *string `json:"video_edit_list,omitempty"` // Audio Edit List reason indicates that the input file's audio track contains a complex Edit Decision List. AudioEditList *string `json:"audio_edit_list,omitempty"` // A catch-all reason when the input file in created with non-standard encoding parameters. UnexpectedMediaFileParameters *string `json:"unexpected_media_file_parameters,omitempty"` } // NewAssetNonStandardInputReasons instantiates a new AssetNonStandardInputReasons 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 NewAssetNonStandardInputReasons() *AssetNonStandardInputReasons { this := AssetNonStandardInputReasons{} return &this } // NewAssetNonStandardInputReasonsWithDefaults instantiates a new AssetNonStandardInputReasons 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 NewAssetNonStandardInputReasonsWithDefaults() *AssetNonStandardInputReasons { this := AssetNonStandardInputReasons{} return &this } // GetVideoCodec returns the VideoCodec field value if set, zero value otherwise. func (o *AssetNonStandardInputReasons) GetVideoCodec() string { if o == nil || o.VideoCodec == nil { var ret string return ret } return *o.VideoCodec } // GetVideoCodecOk returns a tuple with the VideoCodec field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AssetNonStandardInputReasons) GetVideoCodecOk() (*string, bool) { if o == nil || o.VideoCodec == nil { return nil, false } return o.VideoCodec, true } // HasVideoCodec returns a boolean if a field has been set. func (o *AssetNonStandardInputReasons) HasVideoCodec() bool { if o != nil && o.VideoCodec != nil { return true } return false } // SetVideoCodec gets a reference to the given string and assigns it to the VideoCodec field. func (o *AssetNonStandardInputReasons) SetVideoCodec(v string) { o.VideoCodec = &v } // GetAudioCodec returns the AudioCodec field value if set, zero value otherwise. func (o *AssetNonStandardInputReasons) GetAudioCodec() string { if o == nil || o.AudioCodec == nil { var ret string return ret } return *o.AudioCodec } // GetAudioCodecOk returns a tuple with the AudioCodec field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AssetNonStandardInputReasons) GetAudioCodecOk() (*string, bool) { if o == nil || o.AudioCodec == nil { return nil, false } return o.AudioCodec, true } // HasAudioCodec returns a boolean if a field has been set. func (o *AssetNonStandardInputReasons) HasAudioCodec() bool { if o != nil && o.AudioCodec != nil { return true } return false } // SetAudioCodec gets a reference to the given string and assigns it to the AudioCodec field. func (o *AssetNonStandardInputReasons) SetAudioCodec(v string) { o.AudioCodec = &v } // GetVideoGopSize returns the VideoGopSize field value if set, zero value otherwise. func (o *AssetNonStandardInputReasons) GetVideoGopSize() string { if o == nil || o.VideoGopSize == nil { var ret string return ret } return *o.VideoGopSize } // GetVideoGopSizeOk returns a tuple with the VideoGopSize field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AssetNonStandardInputReasons) GetVideoGopSizeOk() (*string, bool) { if o == nil || o.VideoGopSize == nil { return nil, false } return o.VideoGopSize, true } // HasVideoGopSize returns a boolean if a field has been set. func (o *AssetNonStandardInputReasons) HasVideoGopSize() bool { if o != nil && o.VideoGopSize != nil { return true } return false } // SetVideoGopSize gets a reference to the given string and assigns it to the VideoGopSize field. func (o *AssetNonStandardInputReasons) SetVideoGopSize(v string) { o.VideoGopSize = &v } // GetVideoFrameRate returns the VideoFrameRate field value if set, zero value otherwise. func (o *AssetNonStandardInputReasons) GetVideoFrameRate() string { if o == nil || o.VideoFrameRate == nil { var ret string return ret } return *o.VideoFrameRate } // GetVideoFrameRateOk returns a tuple with the VideoFrameRate field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AssetNonStandardInputReasons) GetVideoFrameRateOk() (*string, bool) { if o == nil || o.VideoFrameRate == nil { return nil, false } return o.VideoFrameRate, true } // HasVideoFrameRate returns a boolean if a field has been set. func (o *AssetNonStandardInputReasons) HasVideoFrameRate() bool { if o != nil && o.VideoFrameRate != nil { return true } return false } // SetVideoFrameRate gets a reference to the given string and assigns it to the VideoFrameRate field. func (o *AssetNonStandardInputReasons) SetVideoFrameRate(v string) { o.VideoFrameRate = &v } // GetVideoResolution returns the VideoResolution field value if set, zero value otherwise. func (o *AssetNonStandardInputReasons) GetVideoResolution() string { if o == nil || o.VideoResolution == nil { var ret string return ret } return *o.VideoResolution } // GetVideoResolutionOk returns a tuple with the VideoResolution field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AssetNonStandardInputReasons) GetVideoResolutionOk() (*string, bool) { if o == nil || o.VideoResolution == nil { return nil, false } return o.VideoResolution, true } // HasVideoResolution returns a boolean if a field has been set. func (o *AssetNonStandardInputReasons) HasVideoResolution() bool { if o != nil && o.VideoResolution != nil { return true } return false } // SetVideoResolution gets a reference to the given string and assigns it to the VideoResolution field. func (o *AssetNonStandardInputReasons) SetVideoResolution(v string) { o.VideoResolution = &v } // GetPixelAspectRatio returns the PixelAspectRatio field value if set, zero value otherwise. func (o *AssetNonStandardInputReasons) GetPixelAspectRatio() string { if o == nil || o.PixelAspectRatio == nil { var ret string return ret } return *o.PixelAspectRatio } // GetPixelAspectRatioOk returns a tuple with the PixelAspectRatio field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AssetNonStandardInputReasons) GetPixelAspectRatioOk() (*string, bool) { if o == nil || o.PixelAspectRatio == nil { return nil, false } return o.PixelAspectRatio, true } // HasPixelAspectRatio returns a boolean if a field has been set. func (o *AssetNonStandardInputReasons) HasPixelAspectRatio() bool { if o != nil && o.PixelAspectRatio != nil { return true } return false } // SetPixelAspectRatio gets a reference to the given string and assigns it to the PixelAspectRatio field. func (o *AssetNonStandardInputReasons) SetPixelAspectRatio(v string) { o.PixelAspectRatio = &v } // GetVideoEditList returns the VideoEditList field value if set, zero value otherwise. func (o *AssetNonStandardInputReasons) GetVideoEditList() string { if o == nil || o.VideoEditList == nil { var ret string return ret } return *o.VideoEditList } // GetVideoEditListOk returns a tuple with the VideoEditList field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AssetNonStandardInputReasons) GetVideoEditListOk() (*string, bool) { if o == nil || o.VideoEditList == nil { return nil, false } return o.VideoEditList, true } // HasVideoEditList returns a boolean if a field has been set. func (o *AssetNonStandardInputReasons) HasVideoEditList() bool { if o != nil && o.VideoEditList != nil { return true } return false } // SetVideoEditList gets a reference to the given string and assigns it to the VideoEditList field. func (o *AssetNonStandardInputReasons) SetVideoEditList(v string) { o.VideoEditList = &v } // GetAudioEditList returns the AudioEditList field value if set, zero value otherwise. func (o *AssetNonStandardInputReasons) GetAudioEditList() string { if o == nil || o.AudioEditList == nil { var ret string return ret } return *o.AudioEditList } // GetAudioEditListOk returns a tuple with the AudioEditList field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AssetNonStandardInputReasons) GetAudioEditListOk() (*string, bool) { if o == nil || o.AudioEditList == nil { return nil, false } return o.AudioEditList, true } // HasAudioEditList returns a boolean if a field has been set. func (o *AssetNonStandardInputReasons) HasAudioEditList() bool { if o != nil && o.AudioEditList != nil { return true } return false } // SetAudioEditList gets a reference to the given string and assigns it to the AudioEditList field. func (o *AssetNonStandardInputReasons) SetAudioEditList(v string) { o.AudioEditList = &v } // GetUnexpectedMediaFileParameters returns the UnexpectedMediaFileParameters field value if set, zero value otherwise. func (o *AssetNonStandardInputReasons) GetUnexpectedMediaFileParameters() string { if o == nil || o.UnexpectedMediaFileParameters == nil { var ret string return ret } return *o.UnexpectedMediaFileParameters } // GetUnexpectedMediaFileParametersOk returns a tuple with the UnexpectedMediaFileParameters field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *AssetNonStandardInputReasons) GetUnexpectedMediaFileParametersOk() (*string, bool) { if o == nil || o.UnexpectedMediaFileParameters == nil { return nil, false } return o.UnexpectedMediaFileParameters, true } // HasUnexpectedMediaFileParameters returns a boolean if a field has been set. func (o *AssetNonStandardInputReasons) HasUnexpectedMediaFileParameters() bool { if o != nil && o.UnexpectedMediaFileParameters != nil { return true } return false } // SetUnexpectedMediaFileParameters gets a reference to the given string and assigns it to the UnexpectedMediaFileParameters field. func (o *AssetNonStandardInputReasons) SetUnexpectedMediaFileParameters(v string) { o.UnexpectedMediaFileParameters = &v } func (o AssetNonStandardInputReasons) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.VideoCodec != nil { toSerialize["video_codec"] = o.VideoCodec } if o.AudioCodec != nil { toSerialize["audio_codec"] = o.AudioCodec } if o.VideoGopSize != nil { toSerialize["video_gop_size"] = o.VideoGopSize } if o.VideoFrameRate != nil { toSerialize["video_frame_rate"] = o.VideoFrameRate } if o.VideoResolution != nil { toSerialize["video_resolution"] = o.VideoResolution } if o.PixelAspectRatio != nil { toSerialize["pixel_aspect_ratio"] = o.PixelAspectRatio } if o.VideoEditList != nil { toSerialize["video_edit_list"] = o.VideoEditList } if o.AudioEditList != nil { toSerialize["audio_edit_list"] = o.AudioEditList } if o.UnexpectedMediaFileParameters != nil { toSerialize["unexpected_media_file_parameters"] = o.UnexpectedMediaFileParameters } return json.Marshal(toSerialize) } type NullableAssetNonStandardInputReasons struct { value *AssetNonStandardInputReasons isSet bool } func (v NullableAssetNonStandardInputReasons) Get() *AssetNonStandardInputReasons { return v.value } func (v *NullableAssetNonStandardInputReasons) Set(val *AssetNonStandardInputReasons) { v.value = val v.isSet = true } func (v NullableAssetNonStandardInputReasons) IsSet() bool { return v.isSet } func (v *NullableAssetNonStandardInputReasons) Unset() { v.value = nil v.isSet = false } func NewNullableAssetNonStandardInputReasons(val *AssetNonStandardInputReasons) *NullableAssetNonStandardInputReasons { return &NullableAssetNonStandardInputReasons{value: val, isSet: true} } func (v NullableAssetNonStandardInputReasons) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableAssetNonStandardInputReasons) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
model_asset_non_standard_input_reasons.go
0.852429
0.529081
model_asset_non_standard_input_reasons.go
starcoder
package rectangle import ( "github.com/gravestench/pho/geom/point" ) type RectangleNamespace interface { Contains(r *Rectangle, x, y float64) bool GetPoint(r *Rectangle, position float64, p *point.Point) *point.Point GetPoints(r *Rectangle, quantity int, stepRate float64, points []*point.Point) []*point.Point GetRandomPoint(r *Rectangle, p *point.Point) *point.Point ContainsPoint(r *Rectangle, p *point.Point) bool ContainsRectangle(r *Rectangle, other *Rectangle) bool Deconstruct(r *Rectangle, to []*point.Point) []*point.Point Equals(r *Rectangle, other *Rectangle) bool FitInside(r *Rectangle, other *Rectangle) *Rectangle Inflate(r *Rectangle, x, y float64) *Rectangle Intersection(r *Rectangle, other, intersect *Rectangle) *Rectangle MergePoints(r *Rectangle, points []*point.Point) *Rectangle MergeRectangle(r *Rectangle, other *Rectangle) *Rectangle MergeXY(r *Rectangle, x, y float64) *Rectangle Offset(r *Rectangle, x, y float64) *Rectangle OffsetPoint(r *Rectangle, p *point.Point) *Rectangle Overlaps(r *Rectangle, other *Rectangle) bool PerimeterPoint(r *Rectangle, angle float64, p *point.Point) *point.Point GetRandomPointOutside(r *Rectangle, other *Rectangle, out *point.Point) *point.Point SameDimensions(r *Rectangle, other *Rectangle) bool Scale(r *Rectangle, x, y float64) *Rectangle Union(r *Rectangle, other *Rectangle) *Rectangle } type Namespace struct{} // Contains checks if the given x, y is inside the Rectangle's bounds. func (*Namespace) Contains(r *Rectangle, x, y float64) bool { return Contains(r, x, y) } // GetPoint calculates the coordinates of a point at a certain `position` on the // Rectangle's perimeter, assigns to and returns the given point, or creates a point if nil. func (*Namespace) GetPoint(r *Rectangle, position float64, p *point.Point) *point.Point { return GetPoint(r, position, p) } // GetPoints returns a slice of points from the perimeter of the Rectangle, // each spaced out based on the quantity or step required. func (*Namespace) GetPoints(r *Rectangle, quantity int, stepRate float64, points []*point.Point) []*point.Point { return GetPoints(r, quantity, stepRate, points) } // GetRandomPoint returns a random point within the Rectangle's bounds. func (*Namespace) GetRandomPoint(r *Rectangle, p *point.Point) *point.Point { return GetRandomPoint(r, p) } // Ceil rounds a Rectangle's position up to the smallest integer greater than or equal to each // current coordinate. func (*Namespace) Ceil(r *Rectangle) *Rectangle { return Ceil(r) } // CeilAll rounds a Rectangle's position and size up to the smallest // integer greater than or equal to each respective value. func (*Namespace) CeilAll(r *Rectangle) *Rectangle { return CeilAll(r) } // ContainsPoint checks if a given point is inside a Rectangle's bounds. func (*Namespace) ContainsPoint(r *Rectangle, p *point.Point) bool { return Contains(r, p.X, p.Y) } // ContainsRect checks if a given point is inside a Rectangle's bounds. func (*Namespace) ContainsRectangle(r, other *Rectangle) bool { return ContainsRectangle(r, other) } // CopyFrom copies the values of the given rectangle. func (*Namespace) CopyFrom(target, source *Rectangle) *Rectangle { return CopyFrom(source, target) } // Deconstruct creates a slice of points for each corner of a Rectangle. // If a slice is specified, each point object will be added to the end of the slice, // otherwise a new slice will be created. func (*Namespace) Deconstruct(r *Rectangle, to []*point.Point) []*point.Point { return Deconstruct(r, to) } // Equals compares the `x`, `y`, `width` and `height` properties of two rectangles. func (*Namespace) Equals(a, b *Rectangle) bool { return Equals(a, b) } // Adjusts rectangle, changing its width, height and position, // so that it fits inside the area of the source rectangle, while maintaining its original // aspect ratio. func (*Namespace) FitInside(inner, outer *Rectangle) *Rectangle { return FitInside(inner, outer) } func (*Namespace) Inflate(r *Rectangle, x, y float64) *Rectangle { return Inflate(r, x, y) } // Takes two Rectangles and first checks to see if they intersect. // If they intersect it will return the area of intersection in the `out` Rectangle. // If they do not intersect, the `out` Rectangle will have a width and height of zero. // The given `intersect` rectangle will be assigned the intsersect values and returned. // A new rectangle will be created if `intersect` is nil. func (*Namespace) Intersection(r, other, intersect *Rectangle) *Rectangle { return Intersection(r, other, intersect) } // MergePoints adjusts this rectangle using a list of points by repositioning and/or resizing // it such that all points are located on or within its bounds. func (*Namespace) MergePoints(r *Rectangle, points []*point.Point) *Rectangle { return MergePoints(r, points) } // MergeRectangle merges the given rectangle into this rectangle and returns this rectangle. // Neither rectangle should have a negative width or height. func (*Namespace) MergeRectangle(r *Rectangle, other *Rectangle) *Rectangle { return MergeRectangle(r, other) } // MergeXY merges this rectangle with a point by repositioning and/or resizing it so that the // point is/on or/within its bounds. func (*Namespace) MergeXY(r *Rectangle, x, y float64) *Rectangle { return MergeXY(r, x, y) } // Offset nudges (translates) the top left corner of this Rectangle by a given offset. func (*Namespace) Offset(r *Rectangle, x, y float64) *Rectangle { return Offset(r, x, y) } // OffsetPoint nudges (translates) the top left corner of this Rectangle by the coordinates of a // point. func (*Namespace) OffsetPoint(r *Rectangle, p *point.Point) *Rectangle { return OffsetPoint(r, p) } // Checks if this Rectangle overlaps with another rectangle. func (*Namespace) Overlaps(r *Rectangle, other *Rectangle) bool { return Overlaps(r, other) } // PerimeterPoint returns a Point from the perimeter of the Rectangle based on the given angle. func (*Namespace) PerimeterPoint(r *Rectangle, angle float64, p *point.Point) *point.Point { return PerimeterPoint(r, angle, p) } // Calculates a random point that lies within the `outer` Rectangle, but outside of the `inner` // Rectangle. The inner Rectangle must be fully contained within the outer rectangle. func (*Namespace) GetRandomPointOutside(r, other *Rectangle, out *point.Point) *point.Point { var outer, inner *Rectangle if r.ContainsRectangle(other) { outer, inner = r, other } else { outer, inner = other, r } return GetRandomPointOutside(outer, inner, out) } // SameDimensions determines if the two objects (either Rectangles or Rectangle-like) have the same // width and height values under strict equality. func (*Namespace) SameDimensions(r, other *Rectangle) bool { return SameDimensions(r, other) } // Scale the width and height of this Rectangle by the given amounts. func (*Namespace) Scale(r *Rectangle, x, y float64) *Rectangle { return Scale(r, x, y) } // Union creates a new Rectangle or repositions and/or resizes an existing Rectangle so that it // encompasses the two given Rectangles, i.e. calculates their union. func (*Namespace) Union(r *Rectangle, other *Rectangle) *Rectangle { return Union(r, other, r) }
geom/rectangle/namespace.go
0.962594
0.764628
namespace.go
starcoder
package api import ( "encoding/json" ) // MeasurementSchemaList A list of measurement schemas returning summary information type MeasurementSchemaList struct { MeasurementSchemas []MeasurementSchema `json:"measurementSchemas" yaml:"measurementSchemas"` } // NewMeasurementSchemaList instantiates a new MeasurementSchemaList 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 NewMeasurementSchemaList(measurementSchemas []MeasurementSchema) *MeasurementSchemaList { this := MeasurementSchemaList{} this.MeasurementSchemas = measurementSchemas return &this } // NewMeasurementSchemaListWithDefaults instantiates a new MeasurementSchemaList 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 NewMeasurementSchemaListWithDefaults() *MeasurementSchemaList { this := MeasurementSchemaList{} return &this } // GetMeasurementSchemas returns the MeasurementSchemas field value func (o *MeasurementSchemaList) GetMeasurementSchemas() []MeasurementSchema { if o == nil { var ret []MeasurementSchema return ret } return o.MeasurementSchemas } // GetMeasurementSchemasOk returns a tuple with the MeasurementSchemas field value // and a boolean to check if the value has been set. func (o *MeasurementSchemaList) GetMeasurementSchemasOk() (*[]MeasurementSchema, bool) { if o == nil { return nil, false } return &o.MeasurementSchemas, true } // SetMeasurementSchemas sets field value func (o *MeasurementSchemaList) SetMeasurementSchemas(v []MeasurementSchema) { o.MeasurementSchemas = v } func (o MeasurementSchemaList) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["measurementSchemas"] = o.MeasurementSchemas } return json.Marshal(toSerialize) } type NullableMeasurementSchemaList struct { value *MeasurementSchemaList isSet bool } func (v NullableMeasurementSchemaList) Get() *MeasurementSchemaList { return v.value } func (v *NullableMeasurementSchemaList) Set(val *MeasurementSchemaList) { v.value = val v.isSet = true } func (v NullableMeasurementSchemaList) IsSet() bool { return v.isSet } func (v *NullableMeasurementSchemaList) Unset() { v.value = nil v.isSet = false } func NewNullableMeasurementSchemaList(val *MeasurementSchemaList) *NullableMeasurementSchemaList { return &NullableMeasurementSchemaList{value: val, isSet: true} } func (v NullableMeasurementSchemaList) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableMeasurementSchemaList) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
api/model_measurement_schema_list.gen.go
0.773131
0.407569
model_measurement_schema_list.gen.go
starcoder
package main import ( "sync" ) // JumpingLargestFreeAIJumpAtLessThanFree is the number of free cells connected at which the AI tries to jump. const JumpingLargestFreeAIJumpAtLessThanFree = 50 // JumpingLargestFreeAI behaves like LargestFreeAI but tries to jump out of small areas. type JumpingLargestFreeAI struct { l sync.Mutex i chan string largestfree AI jump AI freeCountingSlice []bool } // GetChannel receives the answer channel. func (jlf *JumpingLargestFreeAI) GetChannel(c chan string) { jlf.l.Lock() defer jlf.l.Unlock() jlf.i = c if jlf.largestfree != nil { jlf.largestfree.GetChannel(c) } if jlf.jump != nil { jlf.jump.GetChannel(c) } } // GetState gets the game state and computes an answer. func (jlf *JumpingLargestFreeAI) GetState(g *Game) { jlf.l.Lock() defer jlf.l.Unlock() if jlf.i == nil { return } if jlf.largestfree == nil { jlf.largestfree = new(LargestFreeAI) jlf.largestfree.GetChannel(jlf.i) } if g.Running && g.Players[g.You].Active { if jlf.freeSpaceConnected(g.Players[g.You].X, g.Players[g.You].Y, JumpingLargestFreeAIJumpAtLessThanFree+1, g) < JumpingLargestFreeAIJumpAtLessThanFree { if jlf.jump == nil { jlf.jump = new(JumpAI) jlf.jump.GetChannel(jlf.i) } jlf.jump.GetState(g) } else if g.Players[g.You].Speed > 1 { // Check slow_down var dostep func(x, y int) (int, int) possible := true x, y := g.Players[g.You].X, g.Players[g.You].Y switch g.Players[g.You].Direction { case DirectionUp: dostep = func(x, y int) (int, int) { return x, y - 1 } case DirectionDown: dostep = func(x, y int) (int, int) { return x, y + 1 } case DirectionLeft: dostep = func(x, y int) (int, int) { return x - 1, y } case DirectionRight: dostep = func(x, y int) (int, int) { return x + 1, y } } for i := 0; i < g.Players[g.You].Speed-1; i++ { x, y = dostep(x, y) if x < 0 || x >= g.Width || y < 0 || y >= g.Height || g.Cells[y][x] != 0 { possible = false break } } if possible { select { case jlf.i <- ActionSlower: default: } return } // Check turn_left possible = true x, y = g.Players[g.You].X, g.Players[g.You].Y switch g.Players[g.You].Direction { case DirectionLeft: dostep = func(x, y int) (int, int) { return x, y - 1 } case DirectionRight: dostep = func(x, y int) (int, int) { return x, y + 1 } case DirectionDown: dostep = func(x, y int) (int, int) { return x - 1, y } case DirectionUp: dostep = func(x, y int) (int, int) { return x + 1, y } } for i := 0; i < g.Players[g.You].Speed; i++ { x, y = dostep(x, y) if x < 0 || x >= g.Width || y < 0 || y >= g.Height || g.Cells[y][x] != 0 { possible = false break } } if possible { select { case jlf.i <- ActionTurnLeft: default: } return } // Check turn_right possible = true x, y = g.Players[g.You].X, g.Players[g.You].Y switch g.Players[g.You].Direction { case DirectionRight: dostep = func(x, y int) (int, int) { return x, y - 1 } case DirectionLeft: dostep = func(x, y int) (int, int) { return x, y + 1 } case DirectionUp: dostep = func(x, y int) (int, int) { return x - 1, y } case DirectionDown: dostep = func(x, y int) (int, int) { return x + 1, y } } for i := 0; i < g.Players[g.You].Speed; i++ { x, y = dostep(x, y) if x < 0 || x >= g.Width || y < 0 || y >= g.Height || g.Cells[y][x] != 0 { possible = false break } } if possible { select { case jlf.i <- ActionTurnRight: default: } return } // nothing to survive, so.... select { case jlf.i <- ActionSlower: default: } } else { jlf.jump = nil jlf.largestfree.GetState(g) } } } // Name returns the name of the AI. func (jlf *JumpingLargestFreeAI) Name() string { return "JumpingLargestFreeAI" } // freeSpaceConnected calculates the number of free space connected to given area. // It is not safe for concurrent usage on the same instance of JumpingLargestFreeAI. func (jlf *JumpingLargestFreeAI) freeSpaceConnected(x, y, cutoff int, g *Game) int { // cutoff -1 == no cutoff // Not concurrent safe if len(jlf.freeCountingSlice) != g.Height*g.Width { jlf.freeCountingSlice = make([]bool, g.Height*g.Width) } else { for i := range jlf.freeCountingSlice { jlf.freeCountingSlice[i] = false } } current := 0 current = jlf.freeSpaceConnectedInternal(x, y, cutoff, current, g) current = jlf.freeSpaceConnectedInternal(x-1, y, cutoff, current, g) current = jlf.freeSpaceConnectedInternal(x+1, y, cutoff, current, g) current = jlf.freeSpaceConnectedInternal(x, y-1, cutoff, current, g) current = jlf.freeSpaceConnectedInternal(x, y+1, cutoff, current, g) return current } func (jlf *JumpingLargestFreeAI) freeSpaceConnectedInternal(x, y, cutoff, current int, g *Game) int { if cutoff != -1 && current > cutoff { return current } if x < 0 || x >= g.Width || y < 0 || y >= g.Height { return current } cell := y*g.Width + x if jlf.freeCountingSlice[cell] { return current } jlf.freeCountingSlice[cell] = true if g.Cells[y][x] != 0 { return current } current++ current = jlf.freeSpaceConnectedInternal(x-1, y, cutoff, current, g) current = jlf.freeSpaceConnectedInternal(x+1, y, cutoff, current, g) current = jlf.freeSpaceConnectedInternal(x, y-1, cutoff, current, g) current = jlf.freeSpaceConnectedInternal(x, y+1, cutoff, current, g) return current }
ai_jumpinglargestfree.go
0.591251
0.463809
ai_jumpinglargestfree.go
starcoder
package main import ( "math" "github.com/fmi/go-homework/geom" ) // Triangle is an Intersectable which represents a triangle in the 3D space. type Triangle struct { a, b, c vector } // Intersect implements the geom.Intersecatble interface. It uses the // Möller–Trumbore ray-triangle intersection algorithm from 1997. Wiki link: // https://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm func (t *Triangle) Intersect(r geom.Ray) bool { ray := rayFromGeom(r) edge1 := t.b.Minus(t.a) edge2 := t.c.Minus(t.a) s1 := ray.Direction.Cross(edge2) divisor := edge1.Product(s1) // Not culling: if divisor > -epsilon && divisor < epsilon { return false } invDivisor := 1.0 / divisor s := ray.Origin.Minus(t.a) b1 := s.Product(s1) * invDivisor if b1 < 0.0 || b1 > 1.0 { return false } s2 := s.Cross(edge1) b2 := ray.Direction.Product(s2) * invDivisor if b2 < 0.0 || b1+b2 > 1.0 { return false } tt := edge2.Product(s2) * invDivisor if tt < 0 { return false } return true } // NewTriangle returns a new Triangle, defined with the points `a`, `b` and `c`. func NewTriangle(a, b, c geom.Vector) *Triangle { return &Triangle{ a: vectorFromGeom(a), b: vectorFromGeom(b), c: vectorFromGeom(c), } } // Quad is an Intersectable which represents a quadrilateral in the 3D space. type Quad struct { vertices [4]vector } // Intersect implements the geom.Intersecatble interface. It is based on the // <NAME> and <NAME> (2005) algorithm. func (q *Quad) Intersect(r geom.Ray) bool { ray := rayFromGeom(r) e01 := q.vertices[1].Minus(q.vertices[0]) e03 := q.vertices[3].Minus(q.vertices[0]) p := ray.Direction.Cross(e03) det := e01.Product(p) if det == 0 { return false } invDet := 1 / det t := ray.Origin.Minus(q.vertices[0]) alfa := t.Product(p) * invDet if alfa < 0 || alfa > 1 { return false } w := t.Cross(e01) beta := ray.Direction.Product(w) * invDet if beta < 0 || beta > 1 { return false } if alfa+beta > 1 { e21 := q.vertices[1].Minus(q.vertices[2]) e23 := q.vertices[3].Minus(q.vertices[2]) pp := ray.Direction.Cross(e21) detp := e23.Product(pp) if detp == 0 { return false } invDetp := 1 / detp tp := ray.Origin.Minus(q.vertices[2]) alfap := tp.Product(pp) * invDetp if alfap < 0 { return false } qp := tp.Cross(e23) betap := ray.Direction.Product(qp) * invDetp if betap < 0 { return false } } tDist := e03.Product(w) * invDet if tDist < 0 { return false } return true } // NewQuad returns a new Quad which is definied byt he four points `a`, `b`, `c` // and `d`. func NewQuad(a, b, c, d geom.Vector) *Quad { return &Quad{ vertices: [4]vector{ vectorFromGeom(a), vectorFromGeom(b), vectorFromGeom(c), vectorFromGeom(d), }, } } // Sphere is an Intersectable which represents a perfect sphere in the 3D space. type Sphere struct { o geom.Vector r float64 } // Intersect implements the geom.Intersecatble interface. func (s *Sphere) Intersect(ray geom.Ray) bool { var d = ray.Direction var o = ray.Origin // Normalize the direction so that we can later check whether the // intersection is behind the origin or in front of it. dl := 1.0 / math.Sqrt(d.X*d.X+d.Y*d.Y+d.Z*d.Z) d.X *= dl d.Y *= dl d.Z *= dl // To make calculations easier, change the coord system so that // the sphere center goes in 0,0,0. o.X -= s.o.X o.Y -= s.o.Y o.Z -= s.o.Z var a = d.X*d.X + d.Y*d.Y + d.Z*d.Z var b = 2 * (d.X*o.X + d.Y*o.Y + d.Z*o.Z) var c = o.X*o.X + o.Y*o.Y + o.Z*o.Z - s.r*s.r tNear, tFar, ok := quadratic(a, b, c) if !ok || (tNear < 0 && tFar < 0) { return false } var retdist = tNear if tNear < 0 { retdist = tFar } if retdist < 0 { return false } return true } // NewSphere returns a new Sphere with center `o` and radius `r`. func NewSphere(o geom.Vector, r float64) *Sphere { return &Sphere{o: o, r: r} } // vector is a algebraic vector which supports few algebraic operations with other // vectors. type vector struct { X, Y, Z float64 } func (v vector) Minus(other vector) vector { return vector{v.X - other.X, v.Y - other.Y, v.Z - other.Z} } func (v vector) Product(other vector) float64 { return v.X*other.X + v.Y*other.Y + v.Z*other.Z } func (v vector) Cross(other vector) vector { return vector{v.Y*other.Z - v.Z*other.Y, v.Z*other.X - v.X*other.Z, v.X*other.Y - v.Y*other.X} } // vectorFromGeom returns the `vector` which corresponds to `geom.Vector`. func vectorFromGeom(p geom.Vector) vector { return vector{X: p.X, Y: p.Y, Z: p.Z} } // ray is a similar to geo.Ray but it is using vector instead of geom.Vector // values. This makes calculations in this package easier. type ray struct { Direction vector Origin vector } // rayFromGeom returns a new `ray` which corresponds to the `geom.Ray`. func rayFromGeom(r geom.Ray) ray { return ray{ Direction: vectorFromGeom(r.Direction), Origin: vectorFromGeom(r.Origin), } } // quadratic solves a quadratic equation and returns the two solutions of there are any. // Its last return value is a boolean and true when there is a solution. The first two // values are the solutions. func quadratic(a, b, c float64) (float64, float64, bool) { discrim := b*b - 4*a*c if discrim <= 0 { return 0, 0, false } rootDiscrim := math.Sqrt(discrim) var q float64 if b < 0 { q = -0.5 * (b - rootDiscrim) } else { q = -0.5 * (b + rootDiscrim) } t0, t1 := q/a, c/q if t0 > t1 { t0, t1 = t1, t0 } return t0, t1, true } // epsilon is a very small number, indistinguishable from zero in the context of // calculations in this package. It can be used for defining the precision of // comparisons and calculations with float values. const epsilon = 1e-7
tasks/03/solution.go
0.882314
0.562837
solution.go
starcoder
package interval import ( g "github.com/zyedidia/generic" "github.com/zyedidia/generic/iter" ) type KV[V any] struct { Low, High int Val V } // intrvl represents an interval over [low, high). type intrvl struct { Low, High int } func overlaps(i1 intrvl, low, high int) bool { return i1.Low < high && i1.High > low } // Tree implements an interval tree. All intervals must have unique starting // positions. type Tree[V any] struct { root *node[V] } // New returns an empty interval tree. func New[V any]() *Tree[V] { return &Tree[V]{} } // Put associates the interval 'key' with 'value'. func (t *Tree[V]) Put(low, high int, value V) { t.root = t.root.add(intrvl{low, high}, value) } // Overlaps returns all values that overlap with the given range. func (t *Tree[V]) Overlaps(low, high int) []V { var result []V return t.root.overlaps(intrvl{low, high}, result) } // Remove deletes the interval starting at 'pos'. func (t *Tree[V]) Remove(pos int) { t.root = t.root.remove(pos) } // Get returns the value associated with the interval starting at 'pos', or // 'false' if no such value exists. func (t *Tree[V]) Get(pos int) (V, bool) { n := t.root.search(pos) if n == nil { var v V return v, false } return n.value, true } // Iter returns the tree iterator. func (t *Tree[V]) Iter() iter.Iter[KV[V]] { return t.root.iter() } // Height returns the height of the tree. func (t *Tree[V]) Height() int { return t.root.getHeight() } // Size returns the number of elements in the tree. func (t *Tree[V]) Size() int { return t.root.size() } type node[V any] struct { key intrvl value V max int height int left *node[V] right *node[V] } func (n *node[V]) add(key intrvl, value V) *node[V] { if n == nil { return &node[V]{ key: key, value: value, max: key.High, height: 1, left: nil, right: nil, } } if key.Low < n.key.Low { n.left = n.left.add(key, value) } else if key.Low > n.key.Low { n.right = n.right.add(key, value) } else { n.value = value } return n.rebalanceTree() } func (n *node[V]) updateMax() { if n != nil { if n.right != nil { n.max = g.Max(n.max, n.right.max) } if n.left != nil { n.max = g.Max(n.max, n.left.max) } } } func (n *node[V]) remove(pos int) *node[V] { if n == nil { return nil } if pos < n.key.Low { n.left = n.left.remove(pos) } else if pos > n.key.Low { n.right = n.right.remove(pos) } else { if n.left != nil && n.right != nil { rightMinNode := n.right.findSmallest() n.key = rightMinNode.key n.value = rightMinNode.value n.right = n.right.remove(rightMinNode.key.Low) } else if n.left != nil { n = n.left } else if n.right != nil { n = n.right } else { n = nil return n } } return n.rebalanceTree() } func (n *node[V]) search(pos int) *node[V] { if n == nil { return nil } if pos < n.key.Low { return n.left.search(pos) } else if pos > n.key.Low { return n.right.search(pos) } else { return n } } func (n *node[V]) overlaps(key intrvl, result []V) []V { if n == nil { return result } if key.Low >= n.max { return result } result = n.left.overlaps(key, result) if overlaps(n.key, key.Low, key.High) { result = append(result, n.value) } if key.High <= n.key.Low { return result } result = n.right.overlaps(key, result) return result } func (n *node[V]) iter() iter.Iter[KV[V]] { if n == nil { return func() (v KV[V], ok bool) { return v, false } } var didself bool left := n.left.iter() right := n.right.iter() return func() (KV[V], bool) { v, ok := left() if ok { return v, true } else if !didself { didself = true return KV[V]{ Low: n.key.Low, High: n.key.High, Val: n.value, }, true } return right() } } func (n *node[V]) getHeight() int { if n == nil { return 0 } return n.height } func (n *node[V]) recalculateHeight() { n.height = 1 + g.Max(n.left.getHeight(), n.right.getHeight()) } func (n *node[V]) rebalanceTree() *node[V] { if n == nil { return n } n.recalculateHeight() n.updateMax() balanceFactor := n.left.getHeight() - n.right.getHeight() if balanceFactor <= -2 { if n.right.left.getHeight() > n.right.right.getHeight() { n.right = n.right.rotateRight() } return n.rotateLeft() } else if balanceFactor >= 2 { if n.left.right.getHeight() > n.left.left.getHeight() { n.left = n.left.rotateLeft() } return n.rotateRight() } return n } func (n *node[V]) rotateLeft() *node[V] { newRoot := n.right n.right = newRoot.left newRoot.left = n n.recalculateHeight() n.updateMax() newRoot.recalculateHeight() newRoot.updateMax() return newRoot } func (n *node[V]) rotateRight() *node[V] { newRoot := n.left n.left = newRoot.right newRoot.right = n n.recalculateHeight() n.updateMax() newRoot.recalculateHeight() newRoot.updateMax() return newRoot } func (n *node[V]) findSmallest() *node[V] { if n.left != nil { return n.left.findSmallest() } else { return n } } func (n *node[V]) size() int { s := 1 if n.left != nil { s += n.left.size() } if n.right != nil { s += n.right.size() } return s }
interval/itree.go
0.849207
0.586878
itree.go
starcoder
package types import ( "fmt" "strconv" "time" ) // TimeframeUnit represents the unit for a timeframe type TimeframeUnit string const ( // TuSec second unit TuSec = TimeframeUnit("s") // TuMin minute unit TuMin = TimeframeUnit("m") // TuHour hour unit TuHour = TimeframeUnit("h") // TuDay day unit TuDay = TimeframeUnit("d") // TuWeek week unit TuWeek = TimeframeUnit("w") // TuMonth month unit TuMonth = TimeframeUnit("M") ) // Timeframe represents a timeframe on which to retrieve candles and execute the algorithm on type Timeframe struct { // Value of the timeframe Value int // Unit of the timeframe's value Unit TimeframeUnit } // NewTimeframe creates a new Timeframe instance func NewTimeframe(value int, unit TimeframeUnit) Timeframe { return Timeframe{ Value: value, Unit: unit, } } // NewTimeframeFromString creates a new Timeframe instance from its string representation func NewTimeframeFromString(in string) (tf Timeframe, err error) { var unitPart, valuePart string unitPart = in[len(in)-1:] valuePart = in[:len(in)-1] switch TimeframeUnit(unitPart) { case TuSec, TuMin, TuHour, TuDay, TuWeek, TuMonth: tf.Unit = TimeframeUnit(unitPart) default: err = fmt.Errorf("Invalid unit: %s", unitPart) return } if tf.Value, err = strconv.Atoi(valuePart); err != nil { return } return } // String returns the string version of the timeframe func (tf Timeframe) String() string { return fmt.Sprintf("%d%s", tf.Value, tf.Unit) } // NextOpen calculates the next open time base on the current open time func (tf Timeframe) NextOpen(currentOpen time.Time, currentClose time.Time) (nextOpen time.Time) { switch tf.Unit { case TuSec: nextOpen = currentOpen.Add(time.Second * time.Duration(tf.Value)) case TuMin: nextOpen = currentOpen.Add(time.Minute + time.Duration(tf.Value)) case TuHour: nextOpen = currentOpen.Add(time.Hour * time.Duration(tf.Value)) case TuDay: nextOpen = currentOpen.AddDate(0, 0, 1) case TuWeek: nextOpen = currentOpen.AddDate(0, 0, 7) case TuMonth: nextOpen = currentOpen.AddDate(0, 1, 0) default: nextOpen = currentClose } return }
types/timeframe.go
0.713432
0.452778
timeframe.go
starcoder
package display import ( "fmt" "github.com/go-gl/mathgl/mgl32" "github.com/ob-algdatii-20ss/leistungsnachweis-teammaze/common" ) func defaultCubeColor() mgl32.Vec4 { return mgl32.Vec4{0, 0.75, 0.75, 1} } func pathCubeColor() mgl32.Vec4 { return mgl32.Vec4{1, 0, 0, 1} } type LabyrinthVisualizer struct { mapView map[mgl32.Vec3]*Cube cubes []Cube highlightedPath []*Cube steps []common.Pair colorConverter StepColorConverter currentStep int } func NewLabyrinthVisualizer(lab *common.Labyrinth, constructor CubeConstructor) LabyrinthVisualizer { if lab == nil { panic("passed labyrinth has to be valid") } view := map[mgl32.Vec3]*Cube{} cubes := exploreLabyrinth(lab, constructor) vis := LabyrinthVisualizer{ cubes: cubes, highlightedPath: nil, currentStep: 0, mapView: view, } for i := range vis.cubes { view[vis.cubes[i].Transform.GetTranslation()] = &vis.cubes[i] } vis.mapView = view return vis } func (vis *LabyrinthVisualizer) GetCubeAt(vec3 mgl32.Vec3) *Cube { return vis.mapView[vec3] } func (vis *LabyrinthVisualizer) SetSteps(steps []common.Pair, converter StepColorConverter) { if vis.steps != nil && vis.colorConverter != nil { for _, step := range vis.steps { cube, _ := vis.colorConverter.StepToColor(step, vis) cube.info.color = defaultCubeColor() } } if steps == nil && converter == nil { return } vis.steps = steps vis.colorConverter = converter vis.currentStep = 0 } func (vis *LabyrinthVisualizer) DoStep() { if vis.steps == nil { panic("cannot do step: steps is nil") } if vis.colorConverter == nil { panic("cannot do step: color converter is nil") } if vis.currentStep > len(vis.steps) { for i := range vis.cubes { vis.cubes[i].info.color = defaultCubeColor() } vis.currentStep = 0 } else if vis.currentStep == len(vis.steps) { vis.currentStep++ return } cube, color := vis.colorConverter.StepToColor(vis.steps[vis.currentStep], vis) axes := []mgl32.Vec3{ {1, 0, 0}, {0, 1, 0}, {0, 0, 1}, {-1, 0, 0}, {0, -1, 0}, {0, 0, -1}, } for _, axis := range axes { neighbor := vis.GetCubeAt(cube.Transform.GetTranslation().Add(axis)) if neighbor != nil && neighbor.info.color == color { connection := vis.GetCubeAt(cube.Transform.GetTranslation().Add(axis.Mul(0.5))) //nolint:gomnd if connection != nil { connection.info.color = neighbor.info.color } } } cube.info.color = color vis.currentStep++ } func (vis *LabyrinthVisualizer) SetPath(path []common.Location) { for i := range vis.cubes { vis.cubes[i].info.color = defaultCubeColor() } if path == nil { return } for locationIndex, location := range path { x, y, z := location.As3DCoordinates() var nextLocation common.Location if locationIndex+1 < len(path) { nextLocation = path[locationIndex+1] } else { nextLocation = location } xNext, yNext, zNext := nextLocation.As3DCoordinates() connectorTranslation := mgl32.Vec3{float32(x+xNext) / 2, float32(y+yNext) / 2, float32(z+zNext) / 2} translation := mgl32.Vec3{float32(x), float32(y), float32(z)} cube := vis.GetCubeAt(translation) if cube != nil { cube.info.color = pathCubeColor() } cube = vis.GetCubeAt(connectorTranslation) if cube != nil { cube.info.color = pathCubeColor() } } } // This has to be 0.5 due to the way our grid works at the moment. const cubeSize float32 = 0.5 func (vis *LabyrinthVisualizer) IsValid() bool { return len(vis.cubes) > 0 } func makeConnection(loc common.Location, other common.Location, cubeConstructor CubeConstructor) Cube { locX, locY, locZ := loc.As3DCoordinates() locV := mgl32.Vec3{float32(locX), float32(locY), float32(locZ)} otherX, otherY, otherZ := other.As3DCoordinates() otherV := mgl32.Vec3{float32(otherX), float32(otherY), float32(otherZ)} // Disable anti-magic number linting here. This Expression calculates the middle point between two Locations by // adding half the distance to one of them. diffFactor := float32(0.5) //nolint:gomnd diffV := otherV.Sub(locV).Mul(diffFactor) if diffV.LenSqr() > diffFactor*diffFactor { panic("tried to make connection between non-adjacent locations") } centerV := locV.Add(diffV) diffV = diffV.Mul(cubeSize).Add(mgl32.Vec3{cubeSize / 2, cubeSize / 2, cubeSize / 2}) cube := cubeConstructor(centerV.X(), centerV.Y(), centerV.Z(), diffV.X(), diffV.Y(), diffV.Z()) cube.info.color = defaultCubeColor() return cube } func exploreLabyrinth(lab *common.Labyrinth, cubeConstructor CubeConstructor) []Cube { cubes := make([]Cube, 0) maxX, maxY, maxZ := (*lab).GetMaxLocation().As3DCoordinates() for x := uint(0); x <= maxX; x++ { for y := uint(0); y <= maxY; y++ { for z := uint(0); z <= maxZ; z++ { loc := common.NewLocation(x, y, z) cube := cubeConstructor(float32(x), float32(y), float32(z), cubeSize, cubeSize, cubeSize) cube.info.color = defaultCubeColor() cubes = append(cubes, cube) cubes = append(cubes, makeConnections(lab, loc, cubeConstructor)...) } } } return cubes } func makeConnections(lab *common.Labyrinth, loc common.Location, cubeConstructor CubeConstructor) []Cube { cubes := make([]Cube, 0) connected := (*lab).GetConnected(loc) x, y, z := loc.As3DCoordinates() for _, other := range connected { otherX, otherY, otherZ := other.As3DCoordinates() if otherX < x || otherY < y || otherZ < z { continue } cubes = append(cubes, makeConnection(loc, other, cubeConstructor)) } return cubes } func (vis LabyrinthVisualizer) String() string { return fmt.Sprintf("LabyrinthVisualizer {Cubes: %v, currentStep: %v}", vis.cubes, vis.currentStep) }
display/labyrinthVisualizer.go
0.676406
0.557364
labyrinthVisualizer.go
starcoder
package statictimeseries import ( "fmt" "sort" "strconv" "strings" "time" "github.com/grokify/gocharts/data/table" "github.com/grokify/gotilla/sort/sortutil" "github.com/grokify/gotilla/time/timeutil" tu "github.com/grokify/gotilla/time/timeutil" "github.com/grokify/gotilla/type/stringsutil" ) type DataSeriesSet struct { Name string Series map[string]DataSeries Times []time.Time Order []string IsFloat bool Interval timeutil.Interval } func NewDataSeriesSet() DataSeriesSet { return DataSeriesSet{ Series: map[string]DataSeries{}, Times: []time.Time{}, Order: []string{}} } func (set *DataSeriesSet) AddItems(items ...DataItem) { for _, item := range items { set.AddItem(item) } } func (set *DataSeriesSet) AddItem(item DataItem) { item.SeriesName = strings.TrimSpace(item.SeriesName) if _, ok := set.Series[item.SeriesName]; !ok { set.Series[item.SeriesName] = DataSeries{ SeriesName: item.SeriesName, ItemMap: map[string]DataItem{}} } series := set.Series[item.SeriesName] series.AddItem(item) set.Series[item.SeriesName] = series set.Times = append(set.Times, item.Time) } func (set *DataSeriesSet) AddDataSeries(ds DataSeries) { for _, item := range ds.ItemMap { if len(item.SeriesName) == 0 { item.SeriesName = ds.SeriesName } set.AddItem(item) } } func (set *DataSeriesSet) Inflate() { if len(set.Times) == 0 { set.Times = set.getTimes() } if len(set.Order) == 0 { order := []string{} for name := range set.Series { order = append(order, name) } sort.Strings(order) set.Order = order } } func (set *DataSeriesSet) SeriesNames() []string { seriesNames := []string{} for seriesName := range set.Series { seriesNames = append(seriesNames, seriesName) } sort.Strings(seriesNames) return seriesNames } func (set *DataSeriesSet) GetSeriesByIndex(index int) (DataSeries, error) { if len(set.Order) == 0 && len(set.Series) > 0 { set.Inflate() } if index < len(set.Order) { name := set.Order[index] if ds, ok := set.Series[name]; ok { return ds, nil } } return DataSeries{}, fmt.Errorf("E_CANNOT_FIND_INDEX_[%d]_SET_COUNT_[%d]", index, len(set.Order)) } func (set *DataSeriesSet) GetItem(seriesName, rfc3339 string) (DataItem, error) { di := DataItem{} dss, ok := set.Series[seriesName] if !ok { return di, fmt.Errorf("SeriesName not found [%s]", seriesName) } item, ok := dss.ItemMap[rfc3339] if !ok { return di, fmt.Errorf("SeriesName found [%s] Time not found [%s]", seriesName, rfc3339) } return item, nil } func (set *DataSeriesSet) getTimes() []time.Time { times := []time.Time{} for _, ds := range set.Series { for _, item := range ds.ItemMap { times = append(times, item.Time) } } return times } func (set *DataSeriesSet) TimeStrings() []string { times := []string{} for _, ds := range set.Series { for rfc3339 := range ds.ItemMap { times = append(times, rfc3339) } } return stringsutil.SliceCondenseSpace(times, true, true) } func (set *DataSeriesSet) MinMaxTimes() (time.Time, time.Time) { values := sortutil.TimeSlice{} for _, ds := range set.Series { min, max := ds.MinMaxTimes() values = append(values, min, max) } sort.Sort(values) return values[0], values[len(values)-1] } func (set *DataSeriesSet) MinMaxValues() (int64, int64) { values := sortutil.Int64Slice{} for _, ds := range set.Series { min, max := ds.MinMaxValues() values = append(values, min, max) } sort.Sort(values) return values[0], values[len(values)-1] } func (set *DataSeriesSet) MinMaxValuesFloat64() (float64, float64) { values := sort.Float64Slice{} for _, ds := range set.Series { min, max := ds.MinMaxValuesFloat64() values = append(values, min, max) } sort.Sort(values) return values[0], values[len(values)-1] } func (set *DataSeriesSet) ToMonth() DataSeriesSet { newDss := DataSeriesSet{ Name: set.Name, Series: map[string]DataSeries{}, Times: set.Times, Interval: timeutil.Month, Order: set.Order} for name, ds := range set.Series { newDss.Series[name] = ds.ToMonth() } newDss.Times = newDss.getTimes() return newDss } func (set *DataSeriesSet) ToMonthCumulative() (DataSeriesSet, error) { newDss := DataSeriesSet{ Name: set.Name, Series: map[string]DataSeries{}, Times: set.Times, Interval: timeutil.Month, Order: set.Order} for name, ds := range set.Series { newDs, err := ds.ToMonthCumulative(newDss.Times...) if err != nil { return newDss, err } newDss.Series[name] = newDs } newDss.Times = newDss.getTimes() return newDss, nil } type RowInt64 struct { Name string DisplayName string HavePlusOne bool ValuePlusOne int64 Values []int64 } func (row *RowInt64) Flatten(conv func(v int64) string) []string { strs := []string{row.Name} for _, v := range row.Values { strs = append(strs, conv(v)) } return strs } type RowFloat64 struct { Name string Values []float64 } func (row *RowFloat64) Flatten(conv func(v float64) string) []string { strs := []string{row.Name} for _, v := range row.Values { strs = append(strs, conv(v)) } return strs } // ReportAxisX generates data for use with `C3Chart.C3Axis.C3AxisX.Categories`. func ReportAxisX(dss DataSeriesSet, cols int, conv func(time.Time) string) []string { var times tu.TimeSlice if cols < len(dss.Times) { min := len(dss.Times) - cols times = dss.Times[min:] } else { // cols >= len(dss.Times) times = dss.Times } cats := []string{} for _, t := range times { cats = append(cats, conv(t)) } return cats } // Report generates data for use with `C3Chart.C3ChartData.Columns`. func Report(dss DataSeriesSet, cols int, lowFirst bool) []RowInt64 { rows := []RowInt64{} var times tu.TimeSlice var timePlus1 time.Time havePlus1 := false if cols < len(dss.Times) { min := len(dss.Times) - cols prev := min - 1 times = dss.Times[min:] timePlus1 = dss.Times[prev] havePlus1 = true } else { // cols >= len(dss.Times) times = dss.Times if cols > len(dss.Times) { timePlus1 = dss.Times[len(dss.Times)-cols-1] havePlus1 = true } } timePlus1Rfc := timePlus1.UTC().Format(time.RFC3339) if !lowFirst { times = sort.Reverse(times).(tu.TimeSlice) } for _, seriesName := range dss.Order { row := RowInt64{ Name: seriesName + " Count", HavePlusOne: havePlus1, } if ds, ok := dss.Series[seriesName]; !ok { for i := 0; i < cols; i++ { row.Values = append(row.Values, 0) } if havePlus1 { row.ValuePlusOne = 0 } } else { for _, t := range times { rfc := t.UTC().Format(time.RFC3339) if item, ok := ds.ItemMap[rfc]; ok { row.Values = append(row.Values, item.Value) } else { row.Values = append(row.Values, 0) } } if havePlus1 { if item, ok := ds.ItemMap[timePlus1Rfc]; ok { row.ValuePlusOne = item.Value } else { row.ValuePlusOne = 0 } } } rows = append(rows, row) } return rows } func ReportFunnelPct(rows []RowInt64) []RowFloat64 { pcts := []RowFloat64{} if len(rows) < 2 { return pcts } for i := 0; i < len(rows)-1; i++ { r := RowFloat64{Name: fmt.Sprintf("Success Pct #%v", i)} j := i + 1 for k := 0; k < len(rows[0].Values); k++ { v1 := rows[i].Values[k] v2 := rows[j].Values[k] pct := float64(v2) / float64(v1) r.Values = append(r.Values, pct) } pcts = append(pcts, r) } return pcts } func ReportGrowthPct(rows []RowInt64) []RowFloat64 { grows := []RowFloat64{} if len(rows) == 0 { return grows } for i := 0; i < len(rows); i++ { r := rows[i] grow := RowFloat64{Name: fmt.Sprintf("%v XoX", r.Name)} if r.HavePlusOne { pct := float64(r.Values[0]) / float64(r.ValuePlusOne) grow.Values = append(grow.Values, pct) } for j := 0; j < len(r.Values)-1; j++ { k := j + 1 pct := float64(r.Values[k]) / float64(r.Values[j]) grow.Values = append(grow.Values, pct) } grows = append(grows, grow) } return grows } // DS3ToTable returns a `DataSeriesSetSimple` as a // `table.TableData`. func DS3ToTable(ds3 DataSeriesSet, fmtTime func(time.Time) string) (table.TableData, error) { tbl := table.NewTableData() seriesNames := ds3.SeriesNames() tbl.Columns = []string{"Time"} tbl.Columns = append(tbl.Columns, seriesNames...) timeStrings := ds3.TimeStrings() for _, rfc3339 := range timeStrings { dt, err := time.Parse(time.RFC3339, rfc3339) if err != nil { return tbl, err } line := []string{fmtTime(dt)} for _, seriesName := range seriesNames { item, err := ds3.GetItem(seriesName, rfc3339) if err == nil { if item.IsFloat { line = append(line, fmt.Sprintf("%.10f", item.ValueFloat)) } else { line = append(line, strconv.Itoa(int(item.Value))) } } else { line = append(line, "0") } } tbl.Records = append(tbl.Records, line) } return tbl, nil } func WriteXLSX(filename string, ds3 DataSeriesSet, fmtTime func(time.Time) string) error { tbl, err := DS3ToTable(ds3, fmtTime) if err != nil { return err } tf := &table.TableFormatter{ Table: &tbl, Formatter: table.FormatStringAndFloats} return table.WriteXLSXFormatted(filename, tf) }
data/statictimeseries/data_series_set.go
0.562898
0.444384
data_series_set.go
starcoder
package image import ( "image" "image/draw" ) type Drawer interface { Draw(r image.Rectangle, src image.Image, sp image.Point) } type Writer struct { Drawer Drawer Point image.Point } func (w *Writer) SkipX(x int) { w.Point.X += x } func (w *Writer) WriteImages(img []image.Image) { for _, v := range img { w.Write(v) } } func (w *Writer) Write(img image.Image) { nb := normalize(img.Bounds()) bounds := nb.Add(w.Point).Sub(image.Point{Y: nb.Max.Y}) w.Drawer.Draw(bounds, img, img.Bounds().Min) w.Point.X = bounds.Max.X } func normalize(r image.Rectangle) image.Rectangle { return image.Rectangle{ Max: r.Max.Sub(r.Min), } } func getShift(r image.Rectangle) image.Point { shift := image.Point{} if r.Min.X < 0 { shift.X = r.Min.X } if r.Min.Y < 0 { shift.Y = r.Min.Y } return shift } func fix(r image.Rectangle) image.Rectangle { return r.Sub(getShift(r)) } type RecordDrawer struct { records []func(Drawer) } func (d *RecordDrawer) Repeat(x Drawer) { for _, v := range d.records { v(x) } } func (d *RecordDrawer) Draw(r image.Rectangle, src image.Image, sp image.Point) { d.records = append(d.records, func(d Drawer) { d.Draw(r, src, sp) }) } type ImageDrawer struct { Dest draw.Image } func (d *ImageDrawer) Draw(r image.Rectangle, src image.Image, sp image.Point) { draw.Over.Draw(d.Dest, r, src, sp) } type SizeDrawer struct { Bounds image.Rectangle } func (d *SizeDrawer) NewRGBA() draw.Image { return image.NewRGBA(d.Bounds) } func (d *SizeDrawer) Draw(r image.Rectangle, src image.Image, sp image.Point) { d.Bounds.Min = minPoint(r.Bounds().Min, d.Bounds.Min) d.Bounds.Max = maxPoint(r.Bounds().Max, d.Bounds.Max) } func min(a1, a2 int) int { if a1 < a2 { return a1 } return a2 } func minPoint(a1, a2 image.Point) image.Point { return image.Point{ X: min(a1.X, a2.X), Y: min(a1.Y, a2.Y), } } func max(a1, a2 int) int { if a1 > a2 { return a1 } return a2 } func maxPoint(a1, a2 image.Point) image.Point { return image.Point{ X: max(a1.X, a2.X), Y: max(a1.Y, a2.Y), } }
pkg/image/writer.go
0.771843
0.49707
writer.go
starcoder
package slicefn import ( "github.com/wearemojo/mojo-public-go/lib/merr" ) const ErrNotFound = merr.Code("not_found") func Map[T1, T2 any](slice []T1, fn func(T1) T2) []T2 { res := make([]T2, len(slice)) for i, v := range slice { res[i] = fn(v) } return res } func MapE[T1, T2 any](slice []T1, fn func(T1) (T2, error)) (res []T2, err error) { res = make([]T2, len(slice)) for i, v := range slice { res[i], err = fn(v) if err != nil { return nil, err } } return } func Filter[T any](slice []T, fn func(T) bool) []T { res := make([]T, 0, len(slice)) for _, v := range slice { if fn(v) { res = append(res, v) } } return res } func FilterE[T any](slice []T, fn func(T) (bool, error)) (res []T, err error) { res = make([]T, 0, len(slice)) for _, v := range slice { if ok, err := fn(v); err != nil { return nil, err } else if ok { res = append(res, v) } } return } func Reduce[T1, T2 any](slice []T1, fn func(acc T2, item T1) T2, initial T2) T2 { acc := initial for _, v := range slice { acc = fn(acc, v) } return acc } func ReduceE[T1, T2 any](slice []T1, fn func(acc T2, item T1) (T2, error), initial T2) (acc T2, err error) { acc = initial for _, v := range slice { acc, err = fn(acc, v) if err != nil { return } } return } func Some[T any](slice []T, fn func(T) bool) bool { for _, v := range slice { if fn(v) { return true } } return false } func SomeE[T any](slice []T, fn func(T) (bool, error)) (bool, error) { for _, v := range slice { if ok, err := fn(v); err != nil { return false, err } else if ok { return true, nil } } return false, nil } func Every[T any](slice []T, fn func(T) bool) bool { for _, v := range slice { if !fn(v) { return false } } return true } func EveryE[T any](slice []T, fn func(T) (bool, error)) (bool, error) { for _, v := range slice { if ok, err := fn(v); err != nil { return false, err } else if !ok { return false, nil } } return true, nil } func FindIndex[T any](slice []T, fn func(T) bool) int { for i, v := range slice { if fn(v) { return i } } return -1 } func FindIndexE[T any](slice []T, fn func(T) (bool, error)) (int, error) { for i, v := range slice { if ok, err := fn(v); err != nil { return -1, err } else if ok { return i, nil } } return -1, nil } func FindLastIndex[T any](slice []T, fn func(T) bool) int { for i := len(slice) - 1; i >= 0; i-- { if fn(slice[i]) { return i } } return -1 } func FindLastIndexE[T any](slice []T, fn func(T) (bool, error)) (int, error) { for i := len(slice) - 1; i >= 0; i-- { if ok, err := fn(slice[i]); err != nil { return -1, err } else if ok { return i, nil } } return -1, nil } func Find[T any](slice []T, fn func(T) bool) (res T, ok bool) { if i := FindIndex(slice, fn); i >= 0 { return slice[i], true } return } func FindE[T any](slice []T, fn func(T) (bool, error)) (res T, ok bool, err error) { i, err := FindIndexE(slice, fn) if err != nil { return } else if i >= 0 { return slice[i], true, nil } return } func FindPtr[T any](slice []T, fn func(T) bool) *T { if i := FindIndex(slice, fn); i >= 0 { return &slice[i] } return nil } func FindPtrE[T any](slice []T, fn func(T) (bool, error)) (*T, error) { i, err := FindIndexE(slice, fn) if err != nil { return nil, err } else if i >= 0 { return &slice[i], nil } return nil, ErrNotFound } func FindLast[T any](slice []T, fn func(T) bool) (res T, ok bool) { if i := FindLastIndex(slice, fn); i >= 0 { return slice[i], true } return } func FindLastE[T any](slice []T, fn func(T) (bool, error)) (res T, ok bool, err error) { i, err := FindLastIndexE(slice, fn) if err != nil { return } else if i >= 0 { return slice[i], true, nil } return } func FindLastPtr[T any](slice []T, fn func(T) bool) *T { if i := FindLastIndex(slice, fn); i >= 0 { return &slice[i] } return nil } func FindLastPtrE[T any](slice []T, fn func(T) (bool, error)) (*T, error) { i, err := FindLastIndexE(slice, fn) if err != nil { return nil, err } else if i >= 0 { return &slice[i], nil } return nil, ErrNotFound }
lib/slicefn/slicefn.go
0.632616
0.472197
slicefn.go
starcoder
package data import ( "math" "github.com/calummccain/coxeter/vector" ) const ( eVal33n = 5.1042993121 //math.Pi / math.Atan(Rt_2) pVal33n = 6.0 eVal33nTrunc = 5.1042993121 //math.Pi / math.Atan(Rt_2) pVal33nTrunc = 10.727915991 //math.Pi / math.Atan(Rt_11) eVal33nRect = 5.1042993121 //math.Pi / math.Atan(Rt_2) pVal33nRect = 1e100 //∞ ) func GoursatTetrahedron33n(n float64) GoursatTetrahedron { cot := 1.0 / math.Pow(math.Tan(math.Pi/n), 2.0) cf := 1.5 * cot / (1 + cot) ce := 0.5 * cot fe := (1.0 + cot) / 3.0 var cv, fv, ev float64 if n == pVal33n { cv = 3.0 fv = 8.0 / 3.0 ev = 2.0 } else { cv = 0.5 * cot / (3.0 - cot) fv = (1.0 + cot) / (3.0 * (3.0 - cot)) ev = 1.0 / (3.0 - cot) } return GoursatTetrahedron{ V: vector.Vec4{W: 1, X: 1, Y: 1, Z: 1}, E: vector.Vec4{W: 1, X: 1, Y: 0, Z: 0}, F: vector.Vec4{W: 3, X: 1, Y: 1, Z: -1}, C: vector.Vec4{W: 1, X: 0, Y: 0, Z: 0}, CFE: vector.Vec4{W: 0, X: 0, Y: 1, Z: 1}, CFV: vector.Vec4{W: 0, X: 1, Y: -1, Z: 0}, CEV: vector.Vec4{W: 0, X: 0, Y: 1, Z: -1}, FEV: vector.Vec4{W: cot - 2.0, X: cot, Y: cot, Z: -cot}, CF: cf, CE: ce, CV: cv, FE: fe, FV: fv, EV: ev, } } func Coxeter33n(n float64) Coxeter { cos := math.Pow(math.Cos(math.Pi/n), 2.0) sin := 1.0 - cos return Coxeter{ P: 3.0, Q: 3.0, R: n, A: func(v vector.Vec4) vector.Vec4 { return vector.Vec4{W: v.W, X: v.X, Y: -v.Z, Z: -v.Y} }, B: func(v vector.Vec4) vector.Vec4 { return vector.Vec4{W: v.W, X: v.Y, Y: v.X, Z: v.Z} }, C: func(v vector.Vec4) vector.Vec4 { return vector.Vec4{W: v.W, X: v.X, Y: v.Z, Z: v.Y} }, D: func(v vector.Vec4) vector.Vec4 { return vector.Vec4{ W: (3.0*sin-1.0)*(-v.W+v.X+v.Y-v.Z) + v.W, X: cos*(v.W-v.X-v.Y+v.Z) + v.X, Y: cos*(v.W-v.X-v.Y+v.Z) + v.Y, Z: cos*(-v.W+v.X+v.Y-v.Z) + v.Z, } }, FaceReflections: []string{"", "abc", "bc", "c"}, GoursatTetrahedron: GoursatTetrahedron33n(n), } } func Honeycomb33n(n float64) Honeycomb { cot := 1.0 / math.Pow(math.Tan(math.Pi/n), 2.0) space := Boundaries(n, eVal33n, pVal33n) var scale func(vector.Vec4) vector.Vec4 if space == 'p' { scale = func(v vector.Vec4) vector.Vec4 { return vector.Vec4{W: Rt3 * v.W, X: v.X, Y: v.Y, Z: v.Z} } } else if space == 'e' { scale = func(v vector.Vec4) vector.Vec4 { return vector.Vec4{W: v.W, X: v.X, Y: v.Y, Z: v.Z} } } else { scale = func(v vector.Vec4) vector.Vec4 { return vector.Vec4{ W: math.Sqrt(math.Abs(cot/(6.0-2.0*cot))) * v.W, X: math.Sqrt(math.Abs((cot-2.0)/(6.0-2.0*cot))) * v.X, Y: math.Sqrt(math.Abs((cot-2.0)/(6.0-2.0*cot))) * v.Y, Z: math.Sqrt(math.Abs((cot-2.0)/(6.0-2.0*cot))) * v.Z, } } } var innerProd func(vector.Vec4, vector.Vec4) float64 if space == 'p' { innerProd = func(a, b vector.Vec4) float64 { return 3.0*a.W*b.W - a.X*b.X - a.Y*b.Y - a.Z*b.Z } } else { innerProd = func(a, b vector.Vec4) float64 { return (cot*a.W*b.W - (cot-2.0)*(a.X*b.X+a.Y*b.Y+a.Z*b.Z)) / math.Abs(6.0-2.0*cot) } } return Honeycomb{ Coxeter: Coxeter33n(n), CellType: "spherical", Vertices: []vector.Vec4{ {W: 1, X: 1, Y: 1, Z: 1}, {W: 1, X: 1, Y: -1, Z: -1}, {W: 1, X: -1, Y: 1, Z: -1}, {W: 1, X: -1, Y: -1, Z: 1}, }, Edges: [][2]int{ {0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}, }, Faces: [][]int{ {0, 2, 1}, {1, 2, 3}, {2, 0, 3}, {3, 0, 1}, }, EVal: eVal33n, PVal: pVal33n, Space: space, Scale: scale, InnerProduct: innerProd, } } func Honeycomb33nTrunc(n float64) Honeycomb { cot := 1.0 / math.Pow(math.Tan(math.Pi/n), 2.0) third := 1.0 / 3.0 space := Boundaries(n, eVal33nTrunc, pVal33nTrunc) var scale func(vector.Vec4) vector.Vec4 if space == 'p' { scale = func(v vector.Vec4) vector.Vec4 { return vector.Vec4{W: Rt11 * v.W, X: 3.0 * v.X, Y: 3.0 * v.Y, Z: 3.0 * v.Z} } } else if space == 'e' { scale = func(v vector.Vec4) vector.Vec4 { return vector.Vec4{W: v.W, X: v.X, Y: v.Y, Z: v.Z} } } else { scale = func(v vector.Vec4) vector.Vec4 { return vector.Vec4{ W: 3.0 * math.Sqrt(math.Abs(cot/(22.0-2.0*cot))) * v.W, X: 3.0 * math.Sqrt(math.Abs((cot-2.0)/(22.0-2.0*cot))) * v.X, Y: 3.0 * math.Sqrt(math.Abs((cot-2.0)/(22.0-2.0*cot))) * v.Y, Z: 3.0 * math.Sqrt(math.Abs((cot-2.0)/(22.0-2.0*cot))) * v.Z, } } } var innerProd func(vector.Vec4, vector.Vec4) float64 if space == 'p' { innerProd = func(a, b vector.Vec4) float64 { return 11.0*a.W*b.W - 9.0*(a.X*b.X+a.Y*b.Y+a.Z*b.Z) } } else { innerProd = func(a, b vector.Vec4) float64 { return 9.0 * (cot*a.W*b.W - (cot-2.0)*(a.X*b.X+a.Y*b.Y+a.Z*b.Z)) / math.Abs(22.0-2.0*cot) } } return Honeycomb{ Coxeter: Coxeter33n(n), CellType: "spherical", Vertices: []vector.Vec4{ {W: 1, X: 1, Y: third, Z: third}, {W: 1, X: third, Y: 1, Z: third}, {W: 1, X: third, Y: third, Z: 1}, {W: 1, X: 1, Y: -third, Z: -third}, {W: 1, X: third, Y: -1, Z: -third}, {W: 1, X: third, Y: -third, Z: -1}, {W: 1, X: -1, Y: third, Z: -third}, {W: 1, X: -third, Y: 1, Z: -third}, {W: 1, X: -third, Y: third, Z: -1}, {W: 1, X: -1, Y: -third, Z: third}, {W: 1, X: -third, Y: -1, Z: third}, {W: 1, X: -third, Y: -third, Z: 1}, }, Edges: [][2]int{ {0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 7}, {2, 11}, {3, 4}, {3, 5}, {4, 5}, {4, 10}, {5, 8}, {6, 7}, {6, 8}, {6, 9}, {7, 8}, {9, 10}, {9, 11}, {10, 11}, }, Faces: [][]int{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, 11}, {0, 2, 11, 10, 4, 3}, {0, 1, 7, 8, 5, 3}, {1, 2, 11, 9, 6, 7}, {4, 5, 8, 6, 9, 10}, }, EVal: eVal33nTrunc, PVal: pVal33nTrunc, Space: space, Scale: scale, InnerProduct: innerProd, } } func Honeycomb33nRect(n float64) Honeycomb { cot := 1.0 / math.Pow(math.Tan(math.Pi/n), 2.0) space := Boundaries(n, eVal33nRect, pVal33nRect) var scale func(vector.Vec4) vector.Vec4 if space == 'e' { scale = func(v vector.Vec4) vector.Vec4 { return vector.Vec4{W: v.W, X: v.X, Y: v.Y, Z: v.Z} } } else { scale = func(v vector.Vec4) vector.Vec4 { return vector.Vec4{ W: math.Sqrt(math.Abs(cot/2.0)) * Rt3 * v.W, X: math.Sqrt(math.Abs((cot-2.0)/2.0)) * v.X, Y: math.Sqrt(math.Abs((cot-2.0)/2.0)) * v.Y, Z: math.Sqrt(math.Abs((cot-2.0)/2.0)) * v.Z, } } } innerProd := func(a, b vector.Vec4) float64 { return (cot*a.W*b.W - (cot-2.0)*(a.X*b.X+a.Y*b.Y+a.Z*b.Z)) / 2.0 } return Honeycomb{ Coxeter: Coxeter33n(n), CellType: "spherical", Vertices: []vector.Vec4{ {W: 1, X: 1, Y: 0, Z: 0}, {W: 1, X: -1, Y: 0, Z: 0}, {W: 1, X: 0, Y: 1, Z: 0}, {W: 1, X: 0, Y: -1, Z: 0}, {W: 1, X: 0, Y: 0, Z: 1}, {W: 1, X: 0, Y: 0, Z: -1}, }, Edges: [][2]int{ {0, 2}, {0, 3}, {0, 4}, {0, 5}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 4}, {4, 3}, {3, 5}, {5, 2}, }, Faces: [][]int{ {0, 2, 4}, {0, 5, 2}, {0, 4, 3}, {0, 3, 5}, {1, 4, 2}, {1, 2, 5}, {1, 3, 4}, {1, 5, 3}, }, EVal: eVal33nRect, PVal: pVal33nRect, Space: space, Scale: scale, InnerProduct: innerProd, } }
data/33n.go
0.587115
0.551695
33n.go
starcoder
package vo2percolation type PointSet struct { // The PointSet needs to be able to represent a Point as an int. convertFrom1D func(int) Point convertTo1D func(Point) int // data's keys are 1D coordinates covering the grid. When the value // associated with a key is true, that key is part of the point set. data map[int]bool } // Create a new point set with grid dimensions (Lx, Ly). func NewPointSet(convertFrom1D func(int) Point, convertTo1D func(Point) int) *PointSet { ps := new(PointSet) ps.convertFrom1D = convertFrom1D ps.convertTo1D = convertTo1D ps.data = make(map[int]bool) return ps } // Return an arbitary point in the set. // This may be inefficient! Depends on whether range ps.data is lazy or if it // builds a list of all possible (k, v). func (ps *PointSet) Point() Point { for k, v := range ps.data { if v { return ps.convertFrom1D(k) } } // there are no points in the set panic("requested a point from a set with none in it") } // Return the number of points in the set. func (ps *PointSet) Size() int { count := 0 for _, v := range ps.data { if v { count++ } } return count } // Return a slice of all points in the set. func (ps *PointSet) Elements() []Point { elements := []Point{} for k, v := range ps.data { if v { p := ps.convertFrom1D(k) elements = append(elements, p) } } return elements } // Return true if and only if ps and comp are equal point sets. func (ps *PointSet) Equals(comp *PointSet) bool { // different size sets can't be equal if ps.Size() != comp.Size() { return false } // check each element for _, point := range comp.Elements() { if !ps.Contains(point) { return false } } return true } // Return true if and only if (x, y) is in the point set. func (ps *PointSet) Contains(p Point) bool { value, ok := ps.data[ps.convertTo1D(p)] if ok { return value } return false } // Add a point to the set. func (ps *PointSet) Add(p Point) { ps.data[ps.convertTo1D(p)] = true } // Remove a point from the set. func (ps *PointSet) Remove(p Point) { // key is deleted from data delete(ps.data, ps.convertTo1D(p)) }
point_set.go
0.782247
0.649481
point_set.go
starcoder
package tetra3d import ( "image/color" "math" ) // Color represents a color, containing R, G, B, and A components, each expected to range from 0 to 1. type Color struct { R, G, B, A float32 } // NewColor returns a new Color, with the provided R, G, B, and A components expected to range from 0 to 1. func NewColor(r, g, b, a float32) *Color { return &Color{r, g, b, a} } // Clone returns a clone of the Color instance. func (color *Color) Clone() *Color { return NewColor(color.R, color.G, color.B, color.A) } // Set sets the RGBA components of the Color to the r, g, b, and a arguments provided. func (color *Color) Set(r, g, b, a float32) { color.R = r color.G = g color.B = b color.A = a } // AddRGBA adds the provided R, G, B, and A values to the color as provided. func (color *Color) AddRGBA(r, g, b, a float32) { color.R += r color.G += g color.B += b color.A += a } // Add adds the provided Color to the existing Color. func (color *Color) Add(other *Color) { color.AddRGBA(other.ToFloat32s()) } // MultiplyRGBA multiplies the color's RGBA channels by the provided R, G, B, and A scalar values. func (color *Color) MultiplyRGBA(scalarR, scalarG, scalarB, scalarA float32) { color.R *= scalarR color.G *= scalarG color.B *= scalarB color.A *= scalarA } // Multiply multiplies the existing Color by the provided Color. func (color *Color) Multiply(other *Color) { color.MultiplyRGBA(other.ToFloat32s()) } // ToFloat32s returns the Color as four float32 in the order R, G, B, and A. func (color *Color) ToFloat32s() (float32, float32, float32, float32) { return color.R, color.G, color.B, color.A } // ToFloat64s returns four float64 values for each channel in the Color in the order R, G, B, and A. func (color *Color) ToFloat64s() (float64, float64, float64, float64) { return float64(color.R), float64(color.G), float64(color.B), float64(color.A) } // ToRGBA64 converts a color to a color.RGBA64 instance. func (c *Color) ToRGBA64() color.RGBA64 { return color.RGBA64{ c.capRGBA64(c.R), c.capRGBA64(c.G), c.capRGBA64(c.B), c.capRGBA64(c.A), } } func (color *Color) capRGBA64(value float32) uint16 { if value > 1 { value = 1 } else if value < 0 { value = 0 } return uint16(value * math.MaxUint16) } // ConvertTosRGB() converts the color's R, G, and B components to the sRGB color space. This is used to convert // colors from their values in GLTF to how they should appear on the screen. See: https://en.wikipedia.org/wiki/SRGB func (color *Color) ConvertTosRGB() { if color.R <= 0.0031308 { color.R *= 12.92 } else { color.R = float32(1.055*math.Pow(float64(color.R), 1/2.4) - 0.055) } if color.G <= 0.0031308 { color.G *= 12.92 } else { color.G = float32(1.055*math.Pow(float64(color.G), 1/2.4) - 0.055) } if color.B <= 0.0031308 { color.B *= 12.92 } else { color.B = float32(1.055*math.Pow(float64(color.B), 1/2.4) - 0.055) } } // NewColorFromHSV returns a new color, using hue, saturation, and value numbers, each ranging from 0 to 1. A hue of // 0 is red, while 1 is also red, but on the other end of the spectrum. // Cribbed from: https://github.com/lucasb-eyer/go-colorful/blob/master/colors.go func NewColorFromHSV(h, s, v float64) *Color { for h > 1 { h-- } for h < 0 { h++ } h *= 360 if s > 1 { s = 1 } else if s < 0 { s = 0 } if v > 1 { v = 1 } else if v < 0 { v = 0 } Hp := h / 60.0 C := v * s X := C * (1.0 - math.Abs(math.Mod(Hp, 2.0)-1.0)) m := v - C r, g, b := 0.0, 0.0, 0.0 switch { case 0.0 <= Hp && Hp < 1.0: r = C g = X case 1.0 <= Hp && Hp < 2.0: r = X g = C case 2.0 <= Hp && Hp < 3.0: g = C b = X case 3.0 <= Hp && Hp < 4.0: g = X b = C case 4.0 <= Hp && Hp < 5.0: r = X b = C case 5.0 <= Hp && Hp < 6.0: r = C b = X } return &Color{float32(m + r), float32(m + g), float32(m + b), 1} } // HSV returns a color as a hue, saturation, and value (each ranging from 0 to 1). // Also cribbed from: https://github.com/lucasb-eyer/go-colorful/blob/master/colors.go func (color *Color) HSV() (float64, float64, float64) { r := float64(color.R) g := float64(color.G) b := float64(color.B) min := math.Min(math.Min(r, g), b) v := math.Max(math.Max(r, g), b) C := v - min s := 0.0 if v != 0.0 { s = C / v } h := 0.0 // We use 0 instead of undefined as in wp. if min != v { if v == r { h = math.Mod((g-b)/C, 6.0) } if v == g { h = (b-r)/C + 2.0 } if v == b { h = (r-g)/C + 4.0 } h *= 60.0 if h < 0.0 { h += 360.0 } } return h / 360, s, v }
color.go
0.916652
0.75069
color.go
starcoder
package Openapi import ( "encoding/json" ) // CartItem A cart item that represents a single cart line item for a transaction. Note that some optional properties are required for certain payment service providers. If no value is set for these properties, we will use their default value. If the total due to be paid for the item is required by the payment service provider, generally referred to as the \"total amount\", the formula below will usually be used to calculate this amount: `(unit_amount * quantity) - discount_amount + tax_amount` It's highly recommended that the total amount to pay for all items should match the transaction's amount to reduce the risk of the transaction being declined by the payment service provider. type CartItem struct { // The name of the cart item. The value you set for this property may be truncated if the maximum length accepted by a payment service provider is less than 255 characters. Name string `json:"name"` // The quantity of this item in the cart. This value cannot be negative or zero. Quantity int32 `json:"quantity"` // The amount for an individual item represented as a monetary amount in the smallest currency unit for the given currency, for example `1299` USD cents represents `$12.99`. UnitAmount int32 `json:"unit_amount"` // The amount discounted for this item represented as a monetary amount in the smallest currency unit for the given currency, for example `1299` USD cents represents `$12.99`. Important: this amount is for the total of the cart item and not for an individual item. For example, if the quantity is 5, this value should be the total discount amount for 5 of the cart item. DiscountAmount NullableInt32 `json:"discount_amount,omitempty"` // The tax amount for this item represented as a monetary amount in the smallest currency unit for the given currency, for example `1299` USD cents represents `$12.99`. Important: this amount is for the total of the cart item and not for an individual item. For example, if the quantity is 5, this value should be the total tax amount for 5 of the cart item. TaxAmount NullableInt32 `json:"tax_amount,omitempty"` // An external identifier for the cart item. This can be set to any value and is not sent to the payment service. ExternalIdentifier NullableString `json:"external_identifier,omitempty"` // The SKU for the item. Sku NullableString `json:"sku,omitempty"` // The product URL for the item. ProductUrl NullableString `json:"product_url,omitempty"` // The URL for the image of the item. ImageUrl NullableString `json:"image_url,omitempty"` // A list of strings containing product categories for the item. Max length per item: 50. Categories []string `json:"categories,omitempty"` // The product type of the cart item. ProductType NullableString `json:"product_type,omitempty"` } // NewCartItem instantiates a new CartItem 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 NewCartItem(name string, quantity int32, unitAmount int32) *CartItem { this := CartItem{} this.Name = name this.Quantity = quantity this.UnitAmount = unitAmount var discountAmount int32 = 0 this.DiscountAmount = *NewNullableInt32(&discountAmount) var taxAmount int32 = 0 this.TaxAmount = *NewNullableInt32(&taxAmount) return &this } // NewCartItemWithDefaults instantiates a new CartItem 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 NewCartItemWithDefaults() *CartItem { this := CartItem{} var discountAmount int32 = 0 this.DiscountAmount = *NewNullableInt32(&discountAmount) var taxAmount int32 = 0 this.TaxAmount = *NewNullableInt32(&taxAmount) return &this } // GetName returns the Name field value func (o *CartItem) GetName() string { if o == nil { var ret string return ret } return o.Name } // GetNameOk returns a tuple with the Name field value // and a boolean to check if the value has been set. func (o *CartItem) GetNameOk() (*string, bool) { if o == nil { return nil, false } return &o.Name, true } // SetName sets field value func (o *CartItem) SetName(v string) { o.Name = v } // GetQuantity returns the Quantity field value func (o *CartItem) GetQuantity() int32 { if o == nil { var ret int32 return ret } return o.Quantity } // GetQuantityOk returns a tuple with the Quantity field value // and a boolean to check if the value has been set. func (o *CartItem) GetQuantityOk() (*int32, bool) { if o == nil { return nil, false } return &o.Quantity, true } // SetQuantity sets field value func (o *CartItem) SetQuantity(v int32) { o.Quantity = v } // GetUnitAmount returns the UnitAmount field value func (o *CartItem) GetUnitAmount() int32 { if o == nil { var ret int32 return ret } return o.UnitAmount } // GetUnitAmountOk returns a tuple with the UnitAmount field value // and a boolean to check if the value has been set. func (o *CartItem) GetUnitAmountOk() (*int32, bool) { if o == nil { return nil, false } return &o.UnitAmount, true } // SetUnitAmount sets field value func (o *CartItem) SetUnitAmount(v int32) { o.UnitAmount = v } // GetDiscountAmount returns the DiscountAmount field value if set, zero value otherwise (both if not set or set to explicit null). func (o *CartItem) GetDiscountAmount() int32 { if o == nil || o.DiscountAmount.Get() == nil { var ret int32 return ret } return *o.DiscountAmount.Get() } // GetDiscountAmountOk returns a tuple with the DiscountAmount field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *CartItem) GetDiscountAmountOk() (*int32, bool) { if o == nil { return nil, false } return o.DiscountAmount.Get(), o.DiscountAmount.IsSet() } // HasDiscountAmount returns a boolean if a field has been set. func (o *CartItem) HasDiscountAmount() bool { if o != nil && o.DiscountAmount.IsSet() { return true } return false } // SetDiscountAmount gets a reference to the given NullableInt32 and assigns it to the DiscountAmount field. func (o *CartItem) SetDiscountAmount(v int32) { o.DiscountAmount.Set(&v) } // SetDiscountAmountNil sets the value for DiscountAmount to be an explicit nil func (o *CartItem) SetDiscountAmountNil() { o.DiscountAmount.Set(nil) } // UnsetDiscountAmount ensures that no value is present for DiscountAmount, not even an explicit nil func (o *CartItem) UnsetDiscountAmount() { o.DiscountAmount.Unset() } // GetTaxAmount returns the TaxAmount field value if set, zero value otherwise (both if not set or set to explicit null). func (o *CartItem) GetTaxAmount() int32 { if o == nil || o.TaxAmount.Get() == nil { var ret int32 return ret } return *o.TaxAmount.Get() } // GetTaxAmountOk returns a tuple with the TaxAmount field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *CartItem) GetTaxAmountOk() (*int32, bool) { if o == nil { return nil, false } return o.TaxAmount.Get(), o.TaxAmount.IsSet() } // HasTaxAmount returns a boolean if a field has been set. func (o *CartItem) HasTaxAmount() bool { if o != nil && o.TaxAmount.IsSet() { return true } return false } // SetTaxAmount gets a reference to the given NullableInt32 and assigns it to the TaxAmount field. func (o *CartItem) SetTaxAmount(v int32) { o.TaxAmount.Set(&v) } // SetTaxAmountNil sets the value for TaxAmount to be an explicit nil func (o *CartItem) SetTaxAmountNil() { o.TaxAmount.Set(nil) } // UnsetTaxAmount ensures that no value is present for TaxAmount, not even an explicit nil func (o *CartItem) UnsetTaxAmount() { o.TaxAmount.Unset() } // GetExternalIdentifier returns the ExternalIdentifier field value if set, zero value otherwise (both if not set or set to explicit null). func (o *CartItem) GetExternalIdentifier() string { if o == nil || o.ExternalIdentifier.Get() == nil { var ret string return ret } return *o.ExternalIdentifier.Get() } // GetExternalIdentifierOk returns a tuple with the ExternalIdentifier field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *CartItem) GetExternalIdentifierOk() (*string, bool) { if o == nil { return nil, false } return o.ExternalIdentifier.Get(), o.ExternalIdentifier.IsSet() } // HasExternalIdentifier returns a boolean if a field has been set. func (o *CartItem) HasExternalIdentifier() bool { if o != nil && o.ExternalIdentifier.IsSet() { return true } return false } // SetExternalIdentifier gets a reference to the given NullableString and assigns it to the ExternalIdentifier field. func (o *CartItem) SetExternalIdentifier(v string) { o.ExternalIdentifier.Set(&v) } // SetExternalIdentifierNil sets the value for ExternalIdentifier to be an explicit nil func (o *CartItem) SetExternalIdentifierNil() { o.ExternalIdentifier.Set(nil) } // UnsetExternalIdentifier ensures that no value is present for ExternalIdentifier, not even an explicit nil func (o *CartItem) UnsetExternalIdentifier() { o.ExternalIdentifier.Unset() } // GetSku returns the Sku field value if set, zero value otherwise (both if not set or set to explicit null). func (o *CartItem) GetSku() string { if o == nil || o.Sku.Get() == nil { var ret string return ret } return *o.Sku.Get() } // GetSkuOk returns a tuple with the Sku field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *CartItem) GetSkuOk() (*string, bool) { if o == nil { return nil, false } return o.Sku.Get(), o.Sku.IsSet() } // HasSku returns a boolean if a field has been set. func (o *CartItem) HasSku() bool { if o != nil && o.Sku.IsSet() { return true } return false } // SetSku gets a reference to the given NullableString and assigns it to the Sku field. func (o *CartItem) SetSku(v string) { o.Sku.Set(&v) } // SetSkuNil sets the value for Sku to be an explicit nil func (o *CartItem) SetSkuNil() { o.Sku.Set(nil) } // UnsetSku ensures that no value is present for Sku, not even an explicit nil func (o *CartItem) UnsetSku() { o.Sku.Unset() } // GetProductUrl returns the ProductUrl field value if set, zero value otherwise (both if not set or set to explicit null). func (o *CartItem) GetProductUrl() string { if o == nil || o.ProductUrl.Get() == nil { var ret string return ret } return *o.ProductUrl.Get() } // GetProductUrlOk returns a tuple with the ProductUrl field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *CartItem) GetProductUrlOk() (*string, bool) { if o == nil { return nil, false } return o.ProductUrl.Get(), o.ProductUrl.IsSet() } // HasProductUrl returns a boolean if a field has been set. func (o *CartItem) HasProductUrl() bool { if o != nil && o.ProductUrl.IsSet() { return true } return false } // SetProductUrl gets a reference to the given NullableString and assigns it to the ProductUrl field. func (o *CartItem) SetProductUrl(v string) { o.ProductUrl.Set(&v) } // SetProductUrlNil sets the value for ProductUrl to be an explicit nil func (o *CartItem) SetProductUrlNil() { o.ProductUrl.Set(nil) } // UnsetProductUrl ensures that no value is present for ProductUrl, not even an explicit nil func (o *CartItem) UnsetProductUrl() { o.ProductUrl.Unset() } // GetImageUrl returns the ImageUrl field value if set, zero value otherwise (both if not set or set to explicit null). func (o *CartItem) GetImageUrl() string { if o == nil || o.ImageUrl.Get() == nil { var ret string return ret } return *o.ImageUrl.Get() } // GetImageUrlOk returns a tuple with the ImageUrl field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *CartItem) GetImageUrlOk() (*string, bool) { if o == nil { return nil, false } return o.ImageUrl.Get(), o.ImageUrl.IsSet() } // HasImageUrl returns a boolean if a field has been set. func (o *CartItem) HasImageUrl() bool { if o != nil && o.ImageUrl.IsSet() { return true } return false } // SetImageUrl gets a reference to the given NullableString and assigns it to the ImageUrl field. func (o *CartItem) SetImageUrl(v string) { o.ImageUrl.Set(&v) } // SetImageUrlNil sets the value for ImageUrl to be an explicit nil func (o *CartItem) SetImageUrlNil() { o.ImageUrl.Set(nil) } // UnsetImageUrl ensures that no value is present for ImageUrl, not even an explicit nil func (o *CartItem) UnsetImageUrl() { o.ImageUrl.Unset() } // GetCategories returns the Categories field value if set, zero value otherwise (both if not set or set to explicit null). func (o *CartItem) GetCategories() []string { if o == nil { var ret []string return ret } return o.Categories } // GetCategoriesOk returns a tuple with the Categories field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *CartItem) GetCategoriesOk() (*[]string, bool) { if o == nil || o.Categories == nil { return nil, false } return &o.Categories, true } // HasCategories returns a boolean if a field has been set. func (o *CartItem) HasCategories() bool { if o != nil && o.Categories != nil { return true } return false } // SetCategories gets a reference to the given []string and assigns it to the Categories field. func (o *CartItem) SetCategories(v []string) { o.Categories = v } // GetProductType returns the ProductType field value if set, zero value otherwise (both if not set or set to explicit null). func (o *CartItem) GetProductType() string { if o == nil || o.ProductType.Get() == nil { var ret string return ret } return *o.ProductType.Get() } // GetProductTypeOk returns a tuple with the ProductType field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *CartItem) GetProductTypeOk() (*string, bool) { if o == nil { return nil, false } return o.ProductType.Get(), o.ProductType.IsSet() } // HasProductType returns a boolean if a field has been set. func (o *CartItem) HasProductType() bool { if o != nil && o.ProductType.IsSet() { return true } return false } // SetProductType gets a reference to the given NullableString and assigns it to the ProductType field. func (o *CartItem) SetProductType(v string) { o.ProductType.Set(&v) } // SetProductTypeNil sets the value for ProductType to be an explicit nil func (o *CartItem) SetProductTypeNil() { o.ProductType.Set(nil) } // UnsetProductType ensures that no value is present for ProductType, not even an explicit nil func (o *CartItem) UnsetProductType() { o.ProductType.Unset() } func (o CartItem) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if true { toSerialize["name"] = o.Name } if true { toSerialize["quantity"] = o.Quantity } if true { toSerialize["unit_amount"] = o.UnitAmount } if o.DiscountAmount.IsSet() { toSerialize["discount_amount"] = o.DiscountAmount.Get() } if o.TaxAmount.IsSet() { toSerialize["tax_amount"] = o.TaxAmount.Get() } if o.ExternalIdentifier.IsSet() { toSerialize["external_identifier"] = o.ExternalIdentifier.Get() } if o.Sku.IsSet() { toSerialize["sku"] = o.Sku.Get() } if o.ProductUrl.IsSet() { toSerialize["product_url"] = o.ProductUrl.Get() } if o.ImageUrl.IsSet() { toSerialize["image_url"] = o.ImageUrl.Get() } if o.Categories != nil { toSerialize["categories"] = o.Categories } if o.ProductType.IsSet() { toSerialize["product_type"] = o.ProductType.Get() } return json.Marshal(toSerialize) } type NullableCartItem struct { value *CartItem isSet bool } func (v NullableCartItem) Get() *CartItem { return v.value } func (v *NullableCartItem) Set(val *CartItem) { v.value = val v.isSet = true } func (v NullableCartItem) IsSet() bool { return v.isSet } func (v *NullableCartItem) Unset() { v.value = nil v.isSet = false } func NewNullableCartItem(val *CartItem) *NullableCartItem { return &NullableCartItem{value: val, isSet: true} } func (v NullableCartItem) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableCartItem) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
api/model_cart_item.go
0.907284
0.516656
model_cart_item.go
starcoder
package main import ( "fmt" "log" "github.com/razziel89/astar" ) // tag::solution[] const ( numNeigh = 4 replicas = 5 ) func gridToNodes(grid Grid) (map[*astar.Node]struct{}, *astar.Node, *astar.Node, error) { result := map[*astar.Node]struct{}{} var start, end *astar.Node // Remember which node belonged to which location. convertedNodes := map[Vec]*astar.Node{} // Our grid is not guaranteed to be square. Thus, we extract the expected positions this way and // error out if we cannot find them later on. startX, startY := grid.TopLeft() endX, endY := grid.BottomRight() startVec := Vec{startX, startY} endVec := Vec{endX, endY} // Process the nodes themselves. for vec, cost := range grid { if _, ok := convertedNodes[vec]; ok { err := fmt.Errorf("node already present") return result, start, end, err } node, err := astar.NewNode(fmt.Sprint(vec), cost, numNeigh, vec) if err != nil { return result, start, end, err } convertedNodes[vec] = node result[node] = struct{}{} if vec == startVec { start = node } if vec == endVec { end = node } } if start == nil || end == nil { err := fmt.Errorf("cannot find start or end node in grid") return result, start, end, err } // Add pairwise connections. This might take a while. for vec := range grid { node, ok := convertedNodes[vec] if !ok { err := fmt.Errorf("node not found") return result, start, end, err } for neigh := range pointEnv(vec) { if !grid.Has(neigh) { continue // Ignore nodes outside the grid. } neighNode, ok := convertedNodes[neigh] if !ok { err := fmt.Errorf("node not found") return result, start, end, err } // If a connection already exists, this is a no-op. node.AddConnection(neighNode) neighNode.AddConnection(node) } } return result, start, end, nil } //nolint: funlen func main() { grid, err := ReadLinesAsGrid() if err != nil { log.Fatal(err.Error()) } // Part 1. nodes, startNode, endNode, err := gridToNodes(grid) if err != nil { log.Fatal(err.Error()) } fastAlgorithm(nodes, startNode, endNode) startX, startY := grid.TopLeft() endX, endY := grid.BottomRight() // Part 2. // Replicate grid. Then, run the fast algorithm largeGrid := Grid{} for p := range grid { for xRep := 0; xRep < replicas; xRep++ { for yRep := 0; yRep < replicas; yRep++ { newPoint := Vec{ x: p.x + xRep*(endX-startX+1), y: p.y + yRep*(endY-startY+1), } newMarking := (grid.Count(p)-1+xRep+yRep)%9 + 1 //nolint:gomnd if largeGrid.Has(newPoint) { // Sanity check, we should never add a node twice. log.Fatal("node already there") } _ = largeGrid.Mark(newPoint, newMarking) } } } nodes, startNode, endNode, err = gridToNodes(largeGrid) if err != nil { log.Fatal(err.Error()) } fastAlgorithm(nodes, startNode, endNode) } // end::solution[]
day15/go/razziel89/solution.go
0.582491
0.518485
solution.go
starcoder
package aoc2021 import ( "strings" ) // contains 4 digits type Display struct { Digits []*Digit } type Helper struct { Zero *Pattern One *Pattern Two *Pattern Three *Pattern Four *Pattern Five *Pattern Six *Pattern Seven *Pattern Eight *Pattern Nine *Pattern } func NewHelper(data string) *Helper { lines := strings.Split(data, "\n") h := Helper{} for _, line := range lines { p := NewPattern(line) for _, ov := range p.OutputValue { value := p.DigitValue(ov) if value == 1 { h.One = p } else if value == 4 { h.Four = p } else if value == 7 { h.Seven = p } else if value == 8 { h.Eight = p } } } return &h } // a single digit type Digit struct { A bool B bool C bool D bool E bool F bool G bool } // returns number of segments switched on func (d *Digit) CountSegmentsOn() int { count := 0 if d.A { count++ } if d.B { count++ } if d.C { count++ } if d.D { count++ } if d.E { count++ } if d.F { count++ } if d.G { count++ } return count } func (d *Digit) Value() int { if d.A && d.B && d.C && !d.D && d.E && d.F && d.G { return 0 } else if !d.A && !d.B && d.C && !d.D && !d.E && d.F && !d.G { return 1 } else if d.A && !d.B && d.C && d.D && d.E && !d.F && d.G { return 2 } else if d.A && !d.B && d.C && d.D && !d.E && d.F && d.G { return 4 } else if d.A && d.B && !d.C && d.D && !d.E && d.F && d.G { return 5 } else if d.A && d.B && !d.C && d.D && d.E && d.F && d.G { return 6 } else if d.A && !d.B && d.C && !d.D && !d.E && d.F && !d.G { return 7 } else if d.A && d.B && d.C && d.D && d.E && d.F && d.G { return 8 } else if d.A && d.B && d.C && d.D && !d.E && d.F && d.G { return 9 } else { return -1 } } func (d *Digit) ValueFromCount() int { segments := d.CountSegmentsOn() if segments == 2 { return 1 } else if segments == 4 { return 4 } else if segments == 3 { return 7 } else if segments == 7 { return 8 } return -1 } type Pattern struct { // acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf Line string SignalPatterns []string OutputValue []string One string Two string Three string Four string Fives []string Sixes []string Seven string Eight string Nine string Zero string A string B string C string D string E string F string G string } func (p *Pattern) Reprogram(a string, b string, c string, d string, e string, f string, g string) { p.A = a p.B = b p.C = c p.D = d p.E = e p.F = f p.G = g } func (p *Pattern) GetValue(candidate string) int { zero := p.A + p.B + p.C + p.E + p.F + p.G one := p.C + p.F two := p.A + p.C + p.D + p.E + p.G three := p.A + p.C + p.D + p.F + p.G four := p.B + p.C + p.D + p.F five := p.A + p.B + p.D + p.F + p.G six := p.A + p.B + p.D + p.E + p.F + p.G seven := p.A + p.C + p.F eight := p.A + p.B + p.C + p.D + p.E + p.F + p.G nine := p.A + p.B + p.C + p.D + p.F + p.G // fmt.Printf("%v %v %v %v %v %v %v %v %v %v\n", zero, one, two, three, four, five, six, seven, eight, nine) if p.Subtract(candidate, one) == "" { return 1 } else if p.Subtract(candidate, seven) == "" { return 7 } else if p.Subtract(candidate, two) == "" { return 2 } else if p.Subtract(candidate, three) == "" { return 3 } else if p.Subtract(candidate, four) == "" { return 4 } else if p.Subtract(candidate, five) == "" { return 5 } else if p.Subtract(candidate, nine) == "" { return 9 } else if p.Subtract(candidate, six) == "" { return 6 } else if p.Subtract(candidate, zero) == "" { return 0 } else if p.Subtract(candidate, eight) == "" { return 8 } else { return -1 } } func (p *Pattern) DigitValue(v string) int { segments := len(v) if segments == 2 { return 1 } else if segments == 4 { return 4 } else if segments == 3 { return 7 } else if segments == 7 { return 8 } return -1 } // 1 = 2 // 4 = 4 // 7 = 3 // 8 = 7 func (p *Pattern) Subtract(signal1 string, signal2 string) string { // subtract signal2 from signal1 result := signal1 for index := 0; index < len(signal2); index++ { c := signal2[index : index+1] result = strings.ReplaceAll(result, c, "") } return result } func NewPattern(line string) *Pattern { p := Pattern{Line: line} splits := strings.Split(line, "|") s1 := strings.Trim(splits[0], " ") s2 := strings.Trim(splits[1], " ") p.SignalPatterns = strings.Split(s1, " ") p.OutputValue = strings.Split(s2, " ") for _, sp := range p.SignalPatterns { value := p.DigitValue(sp) if value == 1 { p.One = sp } else if value == 4 { p.Four = sp } else if value == 7 { p.Seven = sp } else if value == 8 { p.Eight = sp } if len(sp) == 5 { p.Fives = append(p.Fives, sp) } else if len(sp) == 6 { p.Sixes = append(p.Sixes, sp) } } return &p }
app/aoc2021/aoc2021_08_objects.go
0.628635
0.495484
aoc2021_08_objects.go
starcoder