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 tmplwalk import "text/template/parse" // A Visitor's Visit method is invoked for each node encountered by Walk. // If the result visitor w is not nil, Walk visits each of the children // of node with the visitor w, followed by a call of w.Visit(nil). type Visitor interface { Visit(node parse.Node) (w Visitor) } // Helper functions for common node types. func walkBranchNode(v Visitor, n *parse.BranchNode) { Walk(v, n.Pipe) Walk(v, n.List) if n.ElseList != nil { Walk(v, n.ElseList) } } // Walk traverses a template parse tree in depth-first order: It // starts by calling v.Visit(node); node must not be nil. If the // visitor w returned by v.Visit(node) is not nil, Walk is invoked // recursively with visitor w for each of the non-nil children of // node, followed by a call of w.Visit(nil). func Walk(v Visitor, node parse.Node) { if v = v.Visit(node); v == nil { return } // walk children switch n := node.(type) { case *parse.ActionNode: Walk(v, n.Pipe) case *parse.BoolNode: // nothing to do case *parse.ChainNode: Walk(v, n.Node) case *parse.CommandNode: for _, a := range n.Args { Walk(v, a) } case *parse.DotNode: // nothing to do case *parse.FieldNode: // nothing to do case *parse.IdentifierNode: // nothing to do case *parse.IfNode: walkBranchNode(v, &n.BranchNode) case *parse.ListNode: for _, n := range n.Nodes { Walk(v, n) } case *parse.NilNode: // nothing to do case *parse.NumberNode: // nothing to do case *parse.PipeNode: for _, d := range n.Decl { Walk(v, d) } for _, c := range n.Cmds { Walk(v, c) } case *parse.RangeNode: walkBranchNode(v, &n.BranchNode) case *parse.StringNode: // nothing to do case *parse.TemplateNode: if n.Pipe != nil { Walk(v, n.Pipe) } case *parse.TextNode: // nothing to do case *parse.VariableNode: // nothing to do case *parse.WithNode: walkBranchNode(v, &n.BranchNode) } v.Visit(nil) } type inspector func(parse.Node) bool func (f inspector) Visit(node parse.Node) Visitor { if f(node) { return f } return nil } // Inspect traverses a template parse tree in depth-first order: It // starts by calling f(node); node must not be nil. If f returns true, // Inspect invokes f for all the non-nil children of node, // recursively. func Inspect(node parse.Node, f func(parse.Node) bool) { Walk(inspector(f), node) }
tmplwalk/walk.go
0.752649
0.482978
walk.go
starcoder
package decimal import ( "math" "math/big" "math/rand" "strconv" "gonum.org/v1/gonum/floats/scalar" ) const Epsilon = 1e-7 var ( MarshalAsString = true Inf = Decimal(math.Inf(1)) NegInf = Decimal(math.Inf(-1)) ) func Zero() Decimal { return 0 } func One() Decimal { return 1 } func FromInt(v int64) Decimal { return Decimal(v) } func FromUint(v uint64) Decimal { return Decimal(v) } func FromFloat(v float64) Decimal { return Decimal(v) } func FromString(v string) Decimal { d, _ := ParseString(v) return d } func ParseString(v string) (Decimal, error) { f, err := strconv.ParseFloat(v, 64) return Decimal(f), err } func FromBigFloat(v *big.Float) Decimal { f, _ := v.Float64() return Decimal(f) } type Decimal float64 func (d Decimal) Add(x Decimal) Decimal { return d + x } func (d Decimal) Addf(x float64) Decimal { return d.Add(Decimal(x)) } func (d Decimal) Sub(x Decimal) Decimal { return d - x } func (d Decimal) Subf(x float64) Decimal { return d.Sub(Decimal(x)) } func (d Decimal) Mulf(x float64) Decimal { return d.Mul(Decimal(x)) } func (d Decimal) Muli(x int) Decimal { return d.Mul(Decimal(x)) } func (d Decimal) Mul(x Decimal) Decimal { return d * x } func (d Decimal) Divf(x float64) Decimal { return d.Div(Decimal(x)) } func (d Decimal) Div(x Decimal) Decimal { return d / x } func (d Decimal) Abs() Decimal { v := math.Abs(float64(d)) return Decimal(v) } func (d Decimal) Neg() Decimal { return -d } func (d Decimal) IsNaN() bool { return math.IsNaN(d.Float()) } func (d Decimal) IsInf() bool { return !d.IsNaN() && !d.IsFinate() } func (d Decimal) IsFinate() bool { return !(d - d).IsNaN() } func (d Decimal) Pow2() Decimal { return d.Pow(2) } func (d Decimal) Sqrt() Decimal { v := math.Sqrt(float64(d)) return Decimal(v) } func (d Decimal) Log() Decimal { v := math.Log(float64(d)) return Decimal(v) } // Atan uses shopspring/decimal func (d Decimal) Atan() Decimal { v := math.Atan(float64(d)) return Decimal(v) } func (d Decimal) Floor(unit Decimal) Decimal { if unit == 0 || unit == 1 { return Decimal(math.Floor(d.Float())) } d = d * unit return Decimal(math.Floor(d.Float())) / unit } func (d Decimal) Round(unit Decimal) Decimal { if unit == 0 || unit == 1 { return Decimal(math.Round(d.Float())) } d = d * unit return Decimal(math.Round(d.Float())) / unit } // Pow uses shopspring/decimal if n < 10, otherwise a simple loop func (d Decimal) Pow(n Decimal) Decimal { v := math.Pow(float64(d), float64(n)) return Decimal(v) } func (d Decimal) PercentOf(v Decimal) (value, plus, minus Decimal) { value = d * v plus = d + value minus = d - value return } func (d Decimal) Cmp(x Decimal) int { if EqualApprox(float64(d), float64(x), Epsilon) { return 0 } if d < x { return -1 } return 1 } func (d Decimal) Cmpf(x float64) int { return d.Cmp(Decimal(x)) } func (d Decimal) LessThanOrEqual(x Decimal) bool { return d.Cmp(x) <= 0 } func (d Decimal) LessThanOrEqualf(x float64) bool { return d.Cmpf(x) <= 0 } func (d Decimal) GreaterThanOrEqual(x Decimal) bool { return d.Cmp(x) >= 0 } func (d Decimal) GreaterThanOrEqualf(x float64) bool { return d.Cmpf(x) >= 0 } func (d Decimal) LessThan(x Decimal) bool { return d.Cmp(x) < 0 } func (d Decimal) LessThanf(x float64) bool { return d.Cmpf(x) < 0 } func (d Decimal) GreaterThan(x Decimal) bool { return d.Cmp(x) > 0 } func (d Decimal) GreaterThanf(x float64) bool { return d.Cmpf(x) > 0 } func (d Decimal) Equal(x Decimal) bool { return d.Cmp(x) == 0 } func (d Decimal) Equalf(x float64) bool { return d.Cmpf(x) == 0 } func (d Decimal) NotEqual(x Decimal) bool { return !d.Equal(x) } func (d Decimal) NotEqualf(x float64) bool { return !d.Equalf(x) } func (d Decimal) Big() *big.Float { return big.NewFloat(float64(d)) } func (d Decimal) Float() float64 { return float64(d) } func (d Decimal) MarshalJSON() ([]byte, error) { if MarshalAsString { return []byte(`"` + d.String() + `"`), nil } return []byte(d.String()), nil } func (d Decimal) MarshalText() ([]byte, error) { return []byte(d.String()), nil } func (d *Decimal) UnmarshalJSON(p []byte) error { return d.UnmarshalText(p) } func (d *Decimal) UnmarshalText(p []byte) (err error) { if len(p) == 0 { return nil } if len(p) > 2 && p[0] == '"' && p[len(p)-1] == '"' { p = p[1 : len(p)-1] } *d, err = ParseString(string(p)) return } func (d Decimal) String() string { return d.Text('g', 20) } func (d Decimal) Text(fmt byte, prec int) string { return strconv.FormatFloat(d.Float(), fmt, prec, 64) } func EqualApprox(a, b, epsilon float64) bool { if epsilon == 0 { epsilon = Epsilon } return scalar.EqualWithinAbsOrRel(a, b, epsilon, epsilon) } func AvgOf(vs ...Decimal) Decimal { var out Decimal for _, v := range vs { out = out.Add(v) } return out / Decimal(len(vs)) } func Min(vs ...Decimal) Decimal { m := vs[0] for i := 1; i < len(vs); i++ { if v := vs[i]; v < m { m = v } } return m } func Max(vs ...Decimal) Decimal { m := vs[0] for i := 1; i < len(vs); i++ { if v := vs[i]; v > m { m = v } } return m } func Rand(min, max Decimal) (r Decimal) { if max < min { min, max = max, min } again: if r = Decimal(rand.Int63n(1<<53)) / (1 << 53); r == 1 { goto again // resample; this branch is taken O(never) } return min + r*(max-min) } type RandSource = interface { Int63n(int64) int64 } func RandWithSrc(src RandSource, min, max Decimal) (r Decimal) { if max < min { min, max = max, min } again: if r = Decimal(src.Int63n(1<<53)) / (1 << 53); r == 1 { goto again // resample; this branch is taken O(never) } return min + r*(max-min) } func Crosover(curr, prev, mark Decimal) bool { return prev <= mark && curr > mark } func Crossunder(curr, prev, mark Decimal) bool { return curr <= mark && prev > mark } func SliceEqual(a, b []Decimal) bool { if len(a) != len(b) { return false } for i, av := range a { if av.NotEqual(b[i]) { return false } } return true }
decimal/decimal.go
0.810479
0.462959
decimal.go
starcoder
package searcharray type SearchType int type SearchResult int // Enumerated constants are created using the iota enumerator const ( LessThan SearchType = iota LessThanEquals Equals GreaterThanEquals GreaterThan ) const ( NotFound SearchResult = iota FoundExact FoundGreater FoundLess ) const ( DESCENDING = iota ASCENDING ) var SuccessResult = map[SearchType]SearchResult{LessThan: FoundLess, LessThanEquals: FoundLess, GreaterThanEquals: FoundGreater, GreaterThan: FoundGreater} /* Search an array of sorted numbers. * * items : An array of sorted ints, with no duplicates * n_items : Number of elements in the items array * ascending : non-zero if the array is sorted in ascending order * key : the key to search for * srchType : the type of match to find * * This function finds the element in the array * that best fits the search criteria. It returns * the match type and the index of the matching item. * * * Assumptions * ----------- * The items are sorted * Items will be non-NULL * There are no duplicate items * n_items will be > 0 */ func Search(items []int, n_items int, ascending int, key int, srchType SearchType) (index int, sr SearchResult) { // Default result values index = -1 sr = NotFound // Ascending : +1 // Descending : -1 way := ascending*2 - 1 // Dichotomy starts at n_items - 1 mask := (n_items - 1) modulo := n_items % 2 // Current index i := 0 for { i += mask if key < items[i] && ascending == ASCENDING || key > items[i] && ascending == DESCENDING { i -= mask } // Shift the mask mask >>= 1 // Adjustment if n_items is odd if mask == 0 && modulo == 1 { mask = 1 modulo = 0 } // Popular conditions equal := items[i] == key noMask := mask == 0 lastItem := i == n_items-1 // Works with 3 conditions : // 1- Returns FoundExact cases (for Equals, GreaterThanEquals and LessThanEquals) // 2- Returns the next/previous greater/lower or NotFound (for LessThan, GreaterThan, GreaterThanEquals and LessThanEquals) // 3- Returns NotFound (for Equals) if equal && (srchType != GreaterThan && srchType != LessThan) { return i, FoundExact } else if (equal || noMask || lastItem) && (srchType != Equals) { if (srchType == LessThan || srchType == LessThanEquals) && items[i] >= key { i -= way } else if (srchType == GreaterThan || srchType == GreaterThanEquals) && items[i] <= key { i += way } if i >= 0 && i < n_items { return i, SuccessResult[srchType] } else { return } } else if noMask || lastItem { return } } } /* * LessThan * -------- * Finds the largest item which is less than the key. * It returns FoundLess if a match is found, NotFound * if no match is found. * * LessThanEquals * -------------- * Finds the item which is equal to the key, or the * largest item which is less than the key. Returns * FoundExact if an item that exactly matches the key * is found, FoundLess if a non-exact match is found * and NotFound if no match is found. * * Equals * ------ * Finds an item which is equal to the key. Returns * FoundExact if an item if found, NotFound otherwise. * * GreaterThanEquals * ----------------- * Finds the item which is equal to the key, or the * smallest item which is greater than the key. Returns * FoundExact if an item that exactly matches the key * is found, FoundGreater if a non-exact match is found * and NotFound if no match is found. * * GreaterThan * ----------- * Finds the smallest item which is greater than the * key. Returns FoundGreater if a match if found, NotFound * if no match is found. */
searcharray.go
0.665737
0.535827
searcharray.go
starcoder
Package v1 contains Rufs REST API Version 1. Admin control endpoint /admin The admin endpoint can be used for various admin tasks such as registering new branches or mounting known branches. A GET request to the admin endpoint returns the current tree configuration; an object of all known branches and the current mapping: { branches : [ <known branches> ], tree : [ <current mapping> ] } A POST request to the admin endpoint creates a new tree. The body of the request should have the following form: "<name>" /admin/<tree> A DELETE request to a particular tree will delete the tree. /admin/<tree>/branch A new branch can be created in an existing tree by sending a POST request to the branch endpoint. The body of the request should have the following form: { branch : <Name of the branch>, rpc : <RPC definition of the remote branch (e.g. localhost:9020)>, fingerprint : <Expected SSL fingerprint of the remote branch or an empty string> } /admin/<tree>/mapping A new mapping can be created in an existing tree by sending a POST request to the mapping endpoint. The body of the request should have the following form: { branch : <Name of the branch>, dir : <Tree directory of the branch root>, writable : <Flag if the branch should handle write operations> } Dir listing endpoing /dir/<tree>/<path> The dir endpoing handles requests for the directory listing of a certain path. A request url should be of the following form: /dir/<tree>/<path>?recursive=<flag>&checksums=<flag> The request can optionally include the flag parameters (value should be 1 or 0) recursive and checksums. The recursive flag will add all subdirectories to the listing and the checksums flag will add checksums for all listed files. File queries and manipulation /file/{tree}/{path} A GET request to a specific file will return its contents. A POST will upload a new or overwrite an existing file. A DELETE request will delete an existing file. New files are expected to be uploaded using a multipart/form-data request. When uploading a new file the form field for the file should be named "uploadfile". The form can optionally contain a redirect field which will issue a redirect once the file has been uploaded. A PUT request is used to perform a file operation. The request body should be a JSON object of the form (parameters are operation specific): { action : <Action to perform>, files : <List of (full path) files which should be copied / renamed> newname : <New name of file (when renaming)>, newnames : <List of new file names when renaming multiple files using the files parameter>, destination : <Destination file when copying a single file - Destination directory when copying multiple files using the files parameter or syncing directories> } The action can either be: sync, rename, mkdir or copy. Copy and sync returns a JSON structure containing a progress id: { progress_id : <Id for progress of the copy operation> } Progress information /progress/<progress id> A GET request to the progress endpoint returns the current progress of an ongoing operation. The result should be: { "item": <Currently processing item>, "operation": <Name of operation>, "progress": <Current progress>, "subject": <Name of the subject on which the operation is performed>, "total_items": <Total number of items>, "total_progress": <Total progress> } Create zip files /zip/<tree> A post to the zip enpoint returns a zip file containing requested files. The files to include must be given as a list of file name with full path in the body. The body should be application/x-www-form-urlencoded encoded. The list should be a JSON encoded string as value of the value files. The body should have the following form: files=[ "<file1>", "<file2>" ] */ package v1 import ( "encoding/json" "fmt" "net/http" "strconv" "devt.de/krotik/rufs" "devt.de/krotik/rufs/api" ) /* EndpointAdmin is the mount endpoint URL (rooted). Handles everything under admin/... */ const EndpointAdmin = api.APIRoot + APIv1 + "/admin/" /* AdminEndpointInst creates a new endpoint handler. */ func AdminEndpointInst() api.RestEndpointHandler { return &adminEndpoint{} } /* Handler object for admin operations. */ type adminEndpoint struct { *api.DefaultEndpointHandler } /* HandleGET handles an admin query REST call. */ func (a *adminEndpoint) HandleGET(w http.ResponseWriter, r *http.Request, resources []string) { data := make(map[string]interface{}) trees, err := api.Trees() if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } refreshName := r.URL.Query().Get("refresh") for k, v := range trees { var tree map[string]interface{} if refreshName != "" && k == refreshName { v.Refresh() } json.Unmarshal([]byte(v.Config()), &tree) data[k] = tree } // Write data w.Header().Set("content-type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(data) } /* HandlePOST handles REST calls to create a new tree. */ func (a *adminEndpoint) HandlePOST(w http.ResponseWriter, r *http.Request, resources []string) { var tree *rufs.Tree var ok bool var err error var data map[string]interface{} if len(resources) == 0 { var name string if err := json.NewDecoder(r.Body).Decode(&name); err != nil { http.Error(w, fmt.Sprintf("Could not decode request body: %v", err.Error()), http.StatusBadRequest) return } else if name == "" { http.Error(w, fmt.Sprintf("Body must contain the tree name as a non-empty JSON string"), http.StatusBadRequest) return } // Create a new tree tree, err := rufs.NewTree(api.TreeConfigTemplate, api.TreeCertTemplate) if err != nil { http.Error(w, fmt.Sprintf("Could not create new tree: %v", err.Error()), http.StatusBadRequest) return } // Store the new tree if err := api.AddTree(name, tree); err != nil { http.Error(w, fmt.Sprintf("Could not add new tree: %v", err.Error()), http.StatusBadRequest) } return } if !checkResources(w, resources, 2, 2, "Need a tree name and a section (either branches or mapping)") { return } if tree, ok, err = api.GetTree(resources[0]); err == nil && !ok { err = fmt.Errorf("Unknown tree: %v", resources[0]) } if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if err := json.NewDecoder(r.Body).Decode(&data); err != nil { http.Error(w, fmt.Sprintf("Could not decode request body: %v", err.Error()), http.StatusBadRequest) return } if resources[1] == "branch" { // Add a new branch if rpc, ok := getMapValue(w, data, "rpc"); ok { if branch, ok := getMapValue(w, data, "branch"); ok { if fingerprint, ok := getMapValue(w, data, "fingerprint"); ok { if err := tree.AddBranch(branch, rpc, fingerprint); err != nil { http.Error(w, fmt.Sprintf("Could not add branch: %v", err.Error()), http.StatusBadRequest) } } } } } else if resources[1] == "mapping" { // Add a new mapping if _, ok := data["dir"]; ok { if dir, ok := getMapValue(w, data, "dir"); ok { if branch, ok := getMapValue(w, data, "branch"); ok { if writeableStr, ok := getMapValue(w, data, "writeable"); ok { writeable, err := strconv.ParseBool(writeableStr) if err != nil { http.Error(w, fmt.Sprintf("Writeable value must be a boolean: %v", err.Error()), http.StatusBadRequest) } else if err := tree.AddMapping(dir, branch, writeable); err != nil { http.Error(w, fmt.Sprintf("Could not add branch: %v", err.Error()), http.StatusBadRequest) } } } } } } } /* HandleDELETE handles REST calls to delete an existing tree. */ func (a *adminEndpoint) HandleDELETE(w http.ResponseWriter, r *http.Request, resources []string) { if !checkResources(w, resources, 1, 1, "Need a tree name") { return } // Delete the tree if err := api.RemoveTree(resources[0]); err != nil { http.Error(w, fmt.Sprintf("Could not remove tree: %v", err.Error()), http.StatusBadRequest) } } /* SwaggerDefs is used to describe the endpoint in swagger. */ func (a *adminEndpoint) SwaggerDefs(s map[string]interface{}) { s["paths"].(map[string]interface{})["/v1/admin"] = map[string]interface{}{ "get": map[string]interface{}{ "summary": "Return all current tree configurations.", "description": "All current tree configurations; each object has a list of all known branches and the current mapping.", "produces": []string{ "text/plain", "application/json", }, "parameters": []map[string]interface{}{ { "name": "refresh", "in": "query", "description": "Refresh a particular tree (reload branches and mappings).", "required": false, "type": "string", }, }, "responses": map[string]interface{}{ "200": map[string]interface{}{ "description": "A key-value map of tree name to tree configuration", }, "default": map[string]interface{}{ "description": "Error response", "schema": map[string]interface{}{ "$ref": "#/definitions/Error", }, }, }, }, "post": map[string]interface{}{ "summary": "Create a new tree.", "description": "Create a new named tree.", "consumes": []string{ "application/json", }, "produces": []string{ "text/plain", }, "parameters": []map[string]interface{}{ { "name": "data", "in": "body", "description": "Name of the new tree.", "required": true, "schema": map[string]interface{}{ "type": "string", }, }, }, "responses": map[string]interface{}{ "200": map[string]interface{}{ "description": "Returns an empty body if successful.", }, "default": map[string]interface{}{ "description": "Error response", "schema": map[string]interface{}{ "$ref": "#/definitions/Error", }, }, }, }, } s["paths"].(map[string]interface{})["/v1/admin/{tree}"] = map[string]interface{}{ "delete": map[string]interface{}{ "summary": "Delete a tree.", "description": "Delete a named tree.", "produces": []string{ "text/plain", }, "parameters": []map[string]interface{}{ { "name": "tree", "in": "path", "description": "Name of the tree.", "required": true, "type": "string", }, }, "responses": map[string]interface{}{ "200": map[string]interface{}{ "description": "Returns an empty body if successful.", }, "default": map[string]interface{}{ "description": "Error response", "schema": map[string]interface{}{ "$ref": "#/definitions/Error", }, }, }, }, } s["paths"].(map[string]interface{})["/v1/admin/{tree}/branch"] = map[string]interface{}{ "post": map[string]interface{}{ "summary": "Add a new branch.", "description": "Add a new remote branch to the tree.", "consumes": []string{ "application/json", }, "produces": []string{ "text/plain", }, "parameters": []map[string]interface{}{ { "name": "tree", "in": "path", "description": "Name of the tree.", "required": true, "type": "string", }, { "name": "data", "in": "body", "description": "Definition of the new branch.", "required": true, "schema": map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "branch": map[string]interface{}{ "description": "Name of the remote branch (must match on the remote branch).", "type": "string", }, "rpc": map[string]interface{}{ "description": "RPC definition of the remote branch (e.g. localhost:9020).", "type": "string", }, "fingerprint": map[string]interface{}{ "description": "Expected SSL fingerprint of the remote branch (shown during startup) or an empty string.", "type": "string", }, }, }, }, }, "responses": map[string]interface{}{ "200": map[string]interface{}{ "description": "Returns an empty body if successful.", }, "default": map[string]interface{}{ "description": "Error response", "schema": map[string]interface{}{ "$ref": "#/definitions/Error", }, }, }, }, } s["paths"].(map[string]interface{})["/v1/admin/{tree}/mapping"] = map[string]interface{}{ "post": map[string]interface{}{ "summary": "Add a new mapping.", "description": "Add a new mapping to the tree.", "consumes": []string{ "application/json", }, "produces": []string{ "text/plain", }, "parameters": []map[string]interface{}{ { "name": "tree", "in": "path", "description": "Name of the tree.", "required": true, "type": "string", }, { "name": "data", "in": "body", "description": "Definition of the new branch.", "required": true, "schema": map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "branch": map[string]interface{}{ "description": "Name of the known remote branch.", "type": "string", }, "dir": map[string]interface{}{ "description": "Tree directory which should hold the branch root.", "type": "string", }, "writable": map[string]interface{}{ "description": "Flag if the branch should be mapped as writable.", "type": "string", }, }, }, }, }, "responses": map[string]interface{}{ "200": map[string]interface{}{ "description": "Returns an empty body if successful.", }, "default": map[string]interface{}{ "description": "Error response", "schema": map[string]interface{}{ "$ref": "#/definitions/Error", }, }, }, }, } // Add generic error object to definition s["definitions"].(map[string]interface{})["Error"] = map[string]interface{}{ "description": "A human readable error mesage.", "type": "string", } }
api/v1/admin.go
0.680666
0.599925
admin.go
starcoder
package graphql import ( "fmt" "math" "strconv" "github.com/graphql-go/graphql/language/ast" ) func coerceInt(value interface{}) interface{} { switch value := value.(type) { case bool: if value == true { return 1 } return 0 case int: return value case int8: return int(value) case int16: return int(value) case int32: return int(value) case int64: if value < int64(math.MinInt32) || value > int64(math.MaxInt32) { return nil } return int(value) case uint: return int(value) case uint8: return int(value) case uint16: return int(value) case uint32: if value > uint32(math.MaxInt32) { return nil } return int(value) case uint64: if value > uint64(math.MaxInt32) { return nil } return int(value) case float32: if value < float32(math.MinInt32) || value > float32(math.MaxInt32) { return nil } return int(value) case float64: if value < float64(math.MinInt32) || value > float64(math.MaxInt32) { return nil } return int(value) case string: val, err := strconv.ParseFloat(value, 0) if err != nil { return nil } return coerceInt(val) } // If the value cannot be transformed into an int, return nil instead of '0' // to denote 'no integer found' return nil } // Int is the GraphQL Integer type definition. var Int *Scalar = NewScalar(ScalarConfig{ Name: "Int", Serialize: coerceInt, ParseValue: coerceInt, ParseLiteral: func(valueAST ast.Value) interface{} { switch valueAST := valueAST.(type) { case *ast.IntValue: if intValue, err := strconv.Atoi(valueAST.Value); err == nil { return intValue } } return nil }, }) func coerceFloat32(value interface{}) interface{} { switch value := value.(type) { case bool: if value == true { return float32(1) } return float32(0) case int: return float32(value) case float32: return value case float64: return float32(value) case string: val, err := strconv.ParseFloat(value, 0) if err != nil { return nil } return coerceFloat32(val) } return float32(0) } // Float is the GraphQL float type definition. var Float *Scalar = NewScalar(ScalarConfig{ Name: "Float", Serialize: coerceFloat32, ParseValue: coerceFloat32, ParseLiteral: func(valueAST ast.Value) interface{} { switch valueAST := valueAST.(type) { case *ast.FloatValue: if floatValue, err := strconv.ParseFloat(valueAST.Value, 32); err == nil { return floatValue } case *ast.IntValue: if floatValue, err := strconv.ParseFloat(valueAST.Value, 32); err == nil { return floatValue } } return nil }, }) func coerceString(value interface{}) interface{} { return fmt.Sprintf("%v", value) } // String is the GraphQL string type definition var String *Scalar = NewScalar(ScalarConfig{ Name: "String", Serialize: coerceString, ParseValue: coerceString, ParseLiteral: func(valueAST ast.Value) interface{} { switch valueAST := valueAST.(type) { case *ast.StringValue: return valueAST.Value } return nil }, }) func coerceBool(value interface{}) interface{} { switch value := value.(type) { case bool: return value case string: switch value { case "", "false": return false } return true case float64: if value != 0 { return true } return false case float32: if value != 0 { return true } return false case int: if value != 0 { return true } return false } return false } // Boolean is the GraphQL boolean type definition var Boolean *Scalar = NewScalar(ScalarConfig{ Name: "Boolean", Serialize: coerceBool, ParseValue: coerceBool, ParseLiteral: func(valueAST ast.Value) interface{} { switch valueAST := valueAST.(type) { case *ast.BooleanValue: return valueAST.Value } return nil }, }) // ID is the GraphQL id type definition var ID *Scalar = NewScalar(ScalarConfig{ Name: "ID", Serialize: coerceString, ParseValue: coerceString, ParseLiteral: func(valueAST ast.Value) interface{} { switch valueAST := valueAST.(type) { case *ast.IntValue: return valueAST.Value case *ast.StringValue: return valueAST.Value } return nil }, })
vendor/github.com/graphql-go/graphql/scalars.go
0.635788
0.423875
scalars.go
starcoder
package model import ( "bytes" "reflect" "strings" "fmt" "github.com/lquesada/cavernal/lib/g3n/engine/loader/obj" "github.com/lquesada/cavernal/lib/g3n/engine/math32" ) var ( MeterScaleFactor float32 = 1/1.26 GlobalScaleFactor float32 = 0.01 X2 = &Transform{Scale: &math32.Vector3{2, 2, 2}} X3 = &Transform{Scale: &math32.Vector3{3, 3, 3}} X4 = &Transform{Scale: &math32.Vector3{4, 4, 4}} X5 = &Transform{Scale: &math32.Vector3{5, 5, 5}} X6 = &Transform{Scale: &math32.Vector3{6, 6, 6}} X7 = &Transform{Scale: &math32.Vector3{7, 7, 7}} X8 = &Transform{Scale: &math32.Vector3{8, 8, 8}} Xhalf = &Transform{Scale: &math32.Vector3{0.5, 0.5, 0.5}} Xthird = &Transform{Scale: &math32.Vector3{0.333, 0.333, 0.333}} Xquarter = &Transform{Scale: &math32.Vector3{0.25, 0.25, 0.25}} ) func DirOf(i interface{}) string { return strings.TrimPrefix(reflect.TypeOf(i).PkgPath(), "github.com/lquesada/cavernal/") } func load(filepath, baseFilename string, files map[string][]byte) (*obj.Decoder, error) { objFilename := fmt.Sprintf("%s/%s.obj", filepath, baseFilename) mtlFilename := fmt.Sprintf("%s/%s.mtl", filepath, baseFilename) objData, ok := files[objFilename] if !ok { return nil, fmt.Errorf("obj file %s/%s data not found", filepath, baseFilename) } mtlData, ok := files[mtlFilename] if !ok { return nil, fmt.Errorf("mtl file %s/%s data not found", filepath, baseFilename) } dec, err := obj.DecodeReader(bytes.NewReader(objData), bytes.NewReader(mtlData), filepath, files) if err != nil { return nil, fmt.Errorf("couldn't decode object: %s", err) } _, err = dec.NewGroup() if err != nil { return nil, fmt.Errorf("couldn't get group for %s/%s{.obj/.mtl/.png}: %s", filepath, baseFilename, err) } return dec, nil } func Load(filepath, baseFilename string, files map[string][]byte) *obj.Decoder { model, err := load(filepath, baseFilename, files) if err != nil { panic(fmt.Sprintf("Critical error. Failed to load %s/%s{.obj/.mtl/.png}: %s", filepath, baseFilename, err)) } _, err = model.NewGroup() if err != nil { panic(fmt.Sprintf("Critical error. Failed to get test group for %s/%s{.obj/.mtl/.png}: %s", filepath, baseFilename, err)) } return model } type NodeSpec struct { Decoder *obj.Decoder Transform *Transform RGBA *math32.Color4 } func (m *NodeSpec) Build() *node { n, err := m.Decoder.NewGroup() if err != nil { panic(fmt.Sprintf("Critical error. Failed to get group: %s", err)) } position := &math32.Vector3{} if m.Transform != nil && m.Transform.Position != nil { position.Copy(m.Transform.Position) position.MultiplyScalar(-GlobalScaleFactor) if m.Transform != nil && m.Transform.Scale != nil && m.Transform.Scale.Length() != 0 { position.Multiply(m.Transform.Scale) } } rotation := &math32.Vector3{} if m.Transform != nil && m.Transform.Rotation != nil { rotation.Copy(m.Transform.Rotation) } scale := &math32.Vector3{GlobalScaleFactor, GlobalScaleFactor, GlobalScaleFactor} if m.Transform != nil && m.Transform.Scale != nil && m.Transform.Scale.Length() != 0 { scale.Multiply(m.Transform.Scale) } rgba := &math32.Color4{1, 1, 1, 1} if m.RGBA != nil { rgba.R, rgba.G, rgba.B, rgba.A = m.RGBA.R, m.RGBA.G, m.RGBA.B, m.RGBA.A } return &node{ nodes: []INode{&modelNode{node: n}}, transform: &Transform{ Position: position, Rotation: rotation, Scale: scale, }, rgba: rgba, } }
model/model.go
0.583559
0.504089
model.go
starcoder
package similgraph import ( "math" "github.com/pkg/errors" ) // New creates a new similgraph from the edges iterator; vertexACount, vertexBCount and edgeCount contain size estimates, used for efficient memory allocation. func New(edges func() (info Edge, ok bool), vertexACount, vertexBCount, edgeCount int) (g *SimilGraph, newoldVertexA []uint32, err error) { g = &SimilGraph{make([]implicitEdge, 0, 2*edgeCount), make([]uint32, 0, vertexACount+vertexBCount+1), uint32(0)} newoldVertexA = make([]uint32, 0, vertexACount) if err := normalizeEdgeWeight(edges, g, &newoldVertexA); err != nil { return &SimilGraph{}, nil, err } if g.vertexCount > 0 { addInvertedEdges(g) } return g, newoldVertexA, nil } func normalizeEdgeWeight(edges func() (info Edge, ok bool), g *SimilGraph, newoldVertexA *[]uint32) error { e0, ok := edges() if !ok { return nil } if e0.Weight == 0 { return errors.Errorf("similgraph: input edge with zero weight e%v = %v", len(g.bigraphEdges), e0) } *newoldVertexA = append(*newoldVertexA, e0.VertexA) g.bigraphEdges = append(g.bigraphEdges, implicitEdge{e0.VertexB, e0.Weight}) g.vertexSlices = append(g.vertexSlices, 0) groupQNorm := float64(e0.Weight) * float64(e0.Weight) for e1, ok := edges(); ok; e1, ok = edges() { if e0.VertexA > e1.VertexA || (e0.VertexA == e1.VertexA && e0.VertexB >= e1.VertexB) { return errors.Errorf("similgraph: unsorted input edges, should be e%v < e%v, but %v >= %v", len(g.bigraphEdges)-1, len(g.bigraphEdges), e0, e1) } if e1.Weight == 0 { return errors.Errorf("similgraph: input edge with zero weight e%v = %v", len(g.bigraphEdges), e1) } if e0.VertexA != e1.VertexA { lastGroup := g.bigraphEdges[g.vertexSlices[len(g.vertexSlices)-1]:] updateWeight(lastGroup, groupQNorm) g.vertexSlices = append(g.vertexSlices, uint32(len(g.bigraphEdges))) *newoldVertexA = append(*newoldVertexA, e1.VertexA) groupQNorm = 0 } g.bigraphEdges = append(g.bigraphEdges, implicitEdge{e1.VertexB, e1.Weight}) groupQNorm += float64(e1.Weight) * float64(e1.Weight) e0 = e1 } lastGroup := g.bigraphEdges[g.vertexSlices[len(g.vertexSlices)-1]:] updateWeight(lastGroup, groupQNorm) g.vertexSlices = append(g.vertexSlices, uint32(len(g.bigraphEdges))) g.vertexCount = uint32(len(g.vertexSlices) - 1) return nil } func addInvertedEdges(g *SimilGraph) { //eventual copy into a bigger array to permit id refactor and add inverterted graph at the same time if 2*len(g.bigraphEdges) > cap(g.bigraphEdges) { newbigraphEdges := make([]implicitEdge, 0, 2*len(g.bigraphEdges)) g.bigraphEdges = append(newbigraphEdges, g.bigraphEdges...) } pes := make([]pivotedEdgesSpan, 0, g.vertexCount) for v := uint32(0); v < g.vertexCount; v++ { group := g.bigraphEdges[g.vertexSlices[v]:g.vertexSlices[v+1]] pes = append(pes, pivotedEdgesSpan{implicitEdge{v, 1}, group}) } h := redgeIterMergeFrom(pES2REdgeIter(pes...)...) for re, ok := h.Peek(); ok; re, ok = h.Peek() { oldID, newID := re.Edge.Vertex, uint32(len(g.vertexSlices)-1) for re, ok := h.Peek(); ok && re.Edge.Vertex == oldID; re, ok = h.Peek() { h.Next() re.Edge.Vertex = newID g.bigraphEdges = append(g.bigraphEdges, implicitEdge{re.Pivot.Vertex, re.Derived.Weight}) } g.vertexSlices = append(g.vertexSlices, uint32(len(g.bigraphEdges))) } } func updateWeight(group []implicitEdge, qNorm float64) { norm := float32(math.Sqrt(qNorm)) for i := range group { group[i].Weight /= norm } } func pES2REdgeIter(pes ...pivotedEdgesSpan) (nexts []func() (rEdge, bool)) { for _, s := range pes { s := s nexts = append(nexts, func() (e rEdge, ok bool) { if len(s.Edges) == 0 { return } p, ie := &s.Pivot, &s.Edges[0] s.Edges = s.Edges[1:] return rEdge{Edge{ie.Vertex, p.Vertex, ie.Weight * p.Weight}, p, ie}, true }) } return } type rEdge struct { Derived Edge Pivot, Edge *implicitEdge } func (ei rEdge) Less(ej rEdge) bool { return ei.Derived.Less(ej.Derived) }
newsimilgraph.go
0.713831
0.644533
newsimilgraph.go
starcoder
package pgsql import ( "database/sql" "database/sql/driver" "strconv" ) // Int2VectorArrayFromIntSliceSlice returns a driver.Valuer that produces a PostgreSQL int2vector[] from the given Go [][]int. func Int2VectorArrayFromIntSliceSlice(val [][]int) driver.Valuer { return int2VectorArrayFromIntSliceSlice{val: val} } // Int2VectorArrayToIntSliceSlice returns an sql.Scanner that converts a PostgreSQL int2vector[] into a Go [][]int and sets it to val. func Int2VectorArrayToIntSliceSlice(val *[][]int) sql.Scanner { return int2VectorArrayToIntSliceSlice{val: val} } // Int2VectorArrayFromInt8SliceSlice returns a driver.Valuer that produces a PostgreSQL int2vector[] from the given Go [][]int8. func Int2VectorArrayFromInt8SliceSlice(val [][]int8) driver.Valuer { return int2VectorArrayFromInt8SliceSlice{val: val} } // Int2VectorArrayToInt8SliceSlice returns an sql.Scanner that converts a PostgreSQL int2vector[] into a Go [][]int8 and sets it to val. func Int2VectorArrayToInt8SliceSlice(val *[][]int8) sql.Scanner { return int2VectorArrayToInt8SliceSlice{val: val} } // Int2VectorArrayFromInt16SliceSlice returns a driver.Valuer that produces a PostgreSQL int2vector[] from the given Go [][]int16. func Int2VectorArrayFromInt16SliceSlice(val [][]int16) driver.Valuer { return int2VectorArrayFromInt16SliceSlice{val: val} } // Int2VectorArrayToInt16SliceSlice returns an sql.Scanner that converts a PostgreSQL int2vector[] into a Go [][]int16 and sets it to val. func Int2VectorArrayToInt16SliceSlice(val *[][]int16) sql.Scanner { return int2VectorArrayToInt16SliceSlice{val: val} } // Int2VectorArrayFromInt32SliceSlice returns a driver.Valuer that produces a PostgreSQL int2vector[] from the given Go [][]int32. func Int2VectorArrayFromInt32SliceSlice(val [][]int32) driver.Valuer { return int2VectorArrayFromInt32SliceSlice{val: val} } // Int2VectorArrayToInt32SliceSlice returns an sql.Scanner that converts a PostgreSQL int2vector[] into a Go [][]int32 and sets it to val. func Int2VectorArrayToInt32SliceSlice(val *[][]int32) sql.Scanner { return int2VectorArrayToInt32SliceSlice{val: val} } // Int2VectorArrayFromInt64SliceSlice returns a driver.Valuer that produces a PostgreSQL int2vector[] from the given Go [][]int64. func Int2VectorArrayFromInt64SliceSlice(val [][]int64) driver.Valuer { return int2VectorArrayFromInt64SliceSlice{val: val} } // Int2VectorArrayToInt64SliceSlice returns an sql.Scanner that converts a PostgreSQL int2vector[] into a Go [][]int64 and sets it to val. func Int2VectorArrayToInt64SliceSlice(val *[][]int64) sql.Scanner { return int2VectorArrayToInt64SliceSlice{val: val} } // Int2VectorArrayFromUintSliceSlice returns a driver.Valuer that produces a PostgreSQL int2vector[] from the given Go [][]uint. func Int2VectorArrayFromUintSliceSlice(val [][]uint) driver.Valuer { return int2VectorArrayFromUintSliceSlice{val: val} } // Int2VectorArrayToUintSliceSlice returns an sql.Scanner that converts a PostgreSQL int2vector[] into a Go [][]uint and sets it to val. func Int2VectorArrayToUintSliceSlice(val *[][]uint) sql.Scanner { return int2VectorArrayToUintSliceSlice{val: val} } // Int2VectorArrayFromUint8SliceSlice returns a driver.Valuer that produces a PostgreSQL int2vector[] from the given Go [][]uint8. func Int2VectorArrayFromUint8SliceSlice(val [][]uint8) driver.Valuer { return int2VectorArrayFromUint8SliceSlice{val: val} } // Int2VectorArrayToUint8SliceSlice returns an sql.Scanner that converts a PostgreSQL int2vector[] into a Go [][]uint8 and sets it to val. func Int2VectorArrayToUint8SliceSlice(val *[][]uint8) sql.Scanner { return int2VectorArrayToUint8SliceSlice{val: val} } // Int2VectorArrayFromUint16SliceSlice returns a driver.Valuer that produces a PostgreSQL int2vector[] from the given Go [][]uint16. func Int2VectorArrayFromUint16SliceSlice(val [][]uint16) driver.Valuer { return int2VectorArrayFromUint16SliceSlice{val: val} } // Int2VectorArrayToUint16SliceSlice returns an sql.Scanner that converts a PostgreSQL int2vector[] into a Go [][]uint16 and sets it to val. func Int2VectorArrayToUint16SliceSlice(val *[][]uint16) sql.Scanner { return int2VectorArrayToUint16SliceSlice{val: val} } // Int2VectorArrayFromUint32SliceSlice returns a driver.Valuer that produces a PostgreSQL int2vector[] from the given Go [][]uint32. func Int2VectorArrayFromUint32SliceSlice(val [][]uint32) driver.Valuer { return int2VectorArrayFromUint32SliceSlice{val: val} } // Int2VectorArrayToUint32SliceSlice returns an sql.Scanner that converts a PostgreSQL int2vector[] into a Go [][]uint32 and sets it to val. func Int2VectorArrayToUint32SliceSlice(val *[][]uint32) sql.Scanner { return int2VectorArrayToUint32SliceSlice{val: val} } // Int2VectorArrayFromUint64SliceSlice returns a driver.Valuer that produces a PostgreSQL int2vector[] from the given Go [][]uint64. func Int2VectorArrayFromUint64SliceSlice(val [][]uint64) driver.Valuer { return int2VectorArrayFromUint64SliceSlice{val: val} } // Int2VectorArrayToUint64SliceSlice returns an sql.Scanner that converts a PostgreSQL int2vector[] into a Go [][]uint64 and sets it to val. func Int2VectorArrayToUint64SliceSlice(val *[][]uint64) sql.Scanner { return int2VectorArrayToUint64SliceSlice{val: val} } // Int2VectorArrayFromFloat32SliceSlice returns a driver.Valuer that produces a PostgreSQL int2vector[] from the given Go [][]float32. func Int2VectorArrayFromFloat32SliceSlice(val [][]float32) driver.Valuer { return int2VectorArrayFromFloat32SliceSlice{val: val} } // Int2VectorArrayToFloat32SliceSlice returns an sql.Scanner that converts a PostgreSQL int2vector[] into a Go [][]float32 and sets it to val. func Int2VectorArrayToFloat32SliceSlice(val *[][]float32) sql.Scanner { return int2VectorArrayToFloat32SliceSlice{val: val} } // Int2VectorArrayFromFloat64SliceSlice returns a driver.Valuer that produces a PostgreSQL int2vector[] from the given Go [][]float64. func Int2VectorArrayFromFloat64SliceSlice(val [][]float64) driver.Valuer { return int2VectorArrayFromFloat64SliceSlice{val: val} } // Int2VectorArrayToFloat64SliceSlice returns an sql.Scanner that converts a PostgreSQL int2vector[] into a Go [][]float64 and sets it to val. func Int2VectorArrayToFloat64SliceSlice(val *[][]float64) sql.Scanner { return int2VectorArrayToFloat64SliceSlice{val: val} } type int2VectorArrayFromIntSliceSlice struct { val [][]int } func (v int2VectorArrayFromIntSliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, ints := range v.val { out = append(out, '"') for _, i := range ints { out = strconv.AppendInt(out, int64(i), 10) out = append(out, ' ') } out[len(out)-1] = '"' // replace last " " with `"` out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int2VectorArrayToIntSliceSlice struct { val *[][]int } func (v int2VectorArrayToIntSliceSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseVectorArray(arr) intss := make([][]int, len(elems)) for i := 0; i < len(elems); i++ { ints := make([]int, len(elems[i])) for j := 0; j < len(elems[i]); j++ { i64, err := strconv.ParseInt(string(elems[i][j]), 10, 16) if err != nil { return err } ints[j] = int(i64) } intss[i] = ints } *v.val = intss return nil } type int2VectorArrayFromInt8SliceSlice struct { val [][]int8 } func (v int2VectorArrayFromInt8SliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, int8s := range v.val { out = append(out, '"') for _, i8 := range int8s { out = strconv.AppendInt(out, int64(i8), 10) out = append(out, ' ') } out[len(out)-1] = '"' // replace last " " with `"` out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int2VectorArrayToInt8SliceSlice struct { val *[][]int8 } func (v int2VectorArrayToInt8SliceSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseVectorArray(arr) int8ss := make([][]int8, len(elems)) for i := 0; i < len(elems); i++ { int8s := make([]int8, len(elems[i])) for j := 0; j < len(elems[i]); j++ { i64, err := strconv.ParseInt(string(elems[i][j]), 10, 8) if err != nil { return err } int8s[j] = int8(i64) } int8ss[i] = int8s } *v.val = int8ss return nil } type int2VectorArrayFromInt16SliceSlice struct { val [][]int16 } func (v int2VectorArrayFromInt16SliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, int16s := range v.val { out = append(out, '"') for _, i16 := range int16s { out = strconv.AppendInt(out, int64(i16), 10) out = append(out, ' ') } out[len(out)-1] = '"' // replace last " " with `"` out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int2VectorArrayToInt16SliceSlice struct { val *[][]int16 } func (v int2VectorArrayToInt16SliceSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseVectorArray(arr) int16ss := make([][]int16, len(elems)) for i := 0; i < len(elems); i++ { int16s := make([]int16, len(elems[i])) for j := 0; j < len(elems[i]); j++ { i64, err := strconv.ParseInt(string(elems[i][j]), 10, 16) if err != nil { return err } int16s[j] = int16(i64) } int16ss[i] = int16s } *v.val = int16ss return nil } type int2VectorArrayFromInt32SliceSlice struct { val [][]int32 } func (v int2VectorArrayFromInt32SliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, int32s := range v.val { out = append(out, '"') for _, i32 := range int32s { out = strconv.AppendInt(out, int64(i32), 10) out = append(out, ' ') } out[len(out)-1] = '"' // replace last " " with `"` out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int2VectorArrayToInt32SliceSlice struct { val *[][]int32 } func (v int2VectorArrayToInt32SliceSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseVectorArray(arr) int32ss := make([][]int32, len(elems)) for i := 0; i < len(elems); i++ { int32s := make([]int32, len(elems[i])) for j := 0; j < len(elems[i]); j++ { i64, err := strconv.ParseInt(string(elems[i][j]), 10, 16) if err != nil { return err } int32s[j] = int32(i64) } int32ss[i] = int32s } *v.val = int32ss return nil } type int2VectorArrayFromInt64SliceSlice struct { val [][]int64 } func (v int2VectorArrayFromInt64SliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, int64s := range v.val { out = append(out, '"') for _, i64 := range int64s { out = strconv.AppendInt(out, i64, 10) out = append(out, ' ') } out[len(out)-1] = '"' // replace last " " with `"` out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int2VectorArrayToInt64SliceSlice struct { val *[][]int64 } func (v int2VectorArrayToInt64SliceSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseVectorArray(arr) int64ss := make([][]int64, len(elems)) for i := 0; i < len(elems); i++ { int64s := make([]int64, len(elems[i])) for j := 0; j < len(elems[i]); j++ { i64, err := strconv.ParseInt(string(elems[i][j]), 10, 16) if err != nil { return err } int64s[j] = i64 } int64ss[i] = int64s } *v.val = int64ss return nil } type int2VectorArrayFromUintSliceSlice struct { val [][]uint } func (v int2VectorArrayFromUintSliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, uints := range v.val { out = append(out, '"') for _, u := range uints { out = strconv.AppendUint(out, uint64(u), 10) out = append(out, ' ') } out[len(out)-1] = '"' // replace last " " with `"` out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int2VectorArrayToUintSliceSlice struct { val *[][]uint } func (v int2VectorArrayToUintSliceSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseVectorArray(arr) uintss := make([][]uint, len(elems)) for i := 0; i < len(elems); i++ { uints := make([]uint, len(elems[i])) for j := 0; j < len(elems[i]); j++ { u64, err := strconv.ParseUint(string(elems[i][j]), 10, 16) if err != nil { return err } uints[j] = uint(u64) } uintss[i] = uints } *v.val = uintss return nil } type int2VectorArrayFromUint8SliceSlice struct { val [][]uint8 } func (v int2VectorArrayFromUint8SliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, uint8s := range v.val { out = append(out, '"') for _, u8 := range uint8s { out = strconv.AppendUint(out, uint64(u8), 10) out = append(out, ' ') } out[len(out)-1] = '"' // replace last " " with `"` out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int2VectorArrayToUint8SliceSlice struct { val *[][]uint8 } func (v int2VectorArrayToUint8SliceSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseVectorArray(arr) uint8ss := make([][]uint8, len(elems)) for i := 0; i < len(elems); i++ { uint8s := make([]uint8, len(elems[i])) for j := 0; j < len(elems[i]); j++ { u64, err := strconv.ParseUint(string(elems[i][j]), 10, 8) if err != nil { return err } uint8s[j] = uint8(u64) } uint8ss[i] = uint8s } *v.val = uint8ss return nil } type int2VectorArrayFromUint16SliceSlice struct { val [][]uint16 } func (v int2VectorArrayFromUint16SliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, uint16s := range v.val { out = append(out, '"') for _, u16 := range uint16s { out = strconv.AppendUint(out, uint64(u16), 10) out = append(out, ' ') } out[len(out)-1] = '"' // replace last " " with `"` out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int2VectorArrayToUint16SliceSlice struct { val *[][]uint16 } func (v int2VectorArrayToUint16SliceSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseVectorArray(arr) uint16ss := make([][]uint16, len(elems)) for i := 0; i < len(elems); i++ { uint16s := make([]uint16, len(elems[i])) for j := 0; j < len(elems[i]); j++ { u64, err := strconv.ParseUint(string(elems[i][j]), 10, 16) if err != nil { return err } uint16s[j] = uint16(u64) } uint16ss[i] = uint16s } *v.val = uint16ss return nil } type int2VectorArrayFromUint32SliceSlice struct { val [][]uint32 } func (v int2VectorArrayFromUint32SliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, uint32s := range v.val { out = append(out, '"') for _, u32 := range uint32s { out = strconv.AppendUint(out, uint64(u32), 10) out = append(out, ' ') } out[len(out)-1] = '"' // replace last " " with `"` out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int2VectorArrayToUint32SliceSlice struct { val *[][]uint32 } func (v int2VectorArrayToUint32SliceSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseVectorArray(arr) uint32ss := make([][]uint32, len(elems)) for i := 0; i < len(elems); i++ { uint32s := make([]uint32, len(elems[i])) for j := 0; j < len(elems[i]); j++ { u64, err := strconv.ParseUint(string(elems[i][j]), 10, 16) if err != nil { return err } uint32s[j] = uint32(u64) } uint32ss[i] = uint32s } *v.val = uint32ss return nil } type int2VectorArrayFromUint64SliceSlice struct { val [][]uint64 } func (v int2VectorArrayFromUint64SliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, uint64s := range v.val { out = append(out, '"') for _, u64 := range uint64s { out = strconv.AppendUint(out, u64, 10) out = append(out, ' ') } out[len(out)-1] = '"' // replace last " " with `"` out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int2VectorArrayToUint64SliceSlice struct { val *[][]uint64 } func (v int2VectorArrayToUint64SliceSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseVectorArray(arr) uint64ss := make([][]uint64, len(elems)) for i := 0; i < len(elems); i++ { uint64s := make([]uint64, len(elems[i])) for j := 0; j < len(elems[i]); j++ { u64, err := strconv.ParseUint(string(elems[i][j]), 10, 16) if err != nil { return err } uint64s[j] = u64 } uint64ss[i] = uint64s } *v.val = uint64ss return nil } type int2VectorArrayFromFloat32SliceSlice struct { val [][]float32 } func (v int2VectorArrayFromFloat32SliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, float32s := range v.val { out = append(out, '"') for _, f32 := range float32s { out = strconv.AppendInt(out, int64(f32), 10) out = append(out, ' ') } out[len(out)-1] = '"' // replace last " " with `"` out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int2VectorArrayToFloat32SliceSlice struct { val *[][]float32 } func (v int2VectorArrayToFloat32SliceSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseVectorArray(arr) float32ss := make([][]float32, len(elems)) for i := 0; i < len(elems); i++ { float32s := make([]float32, len(elems[i])) for j := 0; j < len(elems[i]); j++ { i64, err := strconv.ParseInt(string(elems[i][j]), 10, 16) if err != nil { return err } float32s[j] = float32(i64) } float32ss[i] = float32s } *v.val = float32ss return nil } type int2VectorArrayFromFloat64SliceSlice struct { val [][]float64 } func (v int2VectorArrayFromFloat64SliceSlice) Value() (driver.Value, error) { if v.val == nil { return nil, nil } else if len(v.val) == 0 { return []byte{'{', '}'}, nil } out := []byte{'{'} for _, float64s := range v.val { out = append(out, '"') for _, f64 := range float64s { out = strconv.AppendInt(out, int64(f64), 10) out = append(out, ' ') } out[len(out)-1] = '"' // replace last " " with `"` out = append(out, ',') } out[len(out)-1] = '}' // replace last "," with "}" return out, nil } type int2VectorArrayToFloat64SliceSlice struct { val *[][]float64 } func (v int2VectorArrayToFloat64SliceSlice) Scan(src interface{}) error { arr, err := srcbytes(src) if err != nil { return err } else if arr == nil { *v.val = nil return nil } elems := pgParseVectorArray(arr) float64ss := make([][]float64, len(elems)) for i := 0; i < len(elems); i++ { float64s := make([]float64, len(elems[i])) for j := 0; j < len(elems[i]); j++ { i64, err := strconv.ParseInt(string(elems[i][j]), 10, 16) if err != nil { return err } float64s[j] = float64(i64) } float64ss[i] = float64s } *v.val = float64ss return nil }
pgsql/int2vectorarr.go
0.797083
0.711631
int2vectorarr.go
starcoder
// Package concurrency contain some functions to support concurrent programming. eg, goroutine, channel, async. package concurrency import ( "context" "sync" ) // Channel is a logic object which can generate or manipulate go channel // all methods of Channel are in the book tilted《Concurrency in Go》 type Channel struct { } // NewChannel return a Channel instance func NewChannel() *Channel { return &Channel{} } // Generate a data of type any chan, put param `values` into the chan func (c *Channel) Generate(ctx context.Context, values ...any) <-chan any { dataStream := make(chan any) go func() { defer close(dataStream) for _, v := range values { select { case <-ctx.Done(): return case dataStream <- v: } } }() return dataStream } // Repeat return a data of type any chan, put param `values` into the chan repeatly until cancel the context. func (c *Channel) Repeat(ctx context.Context, values ...any) <-chan any { dataStream := make(chan any) go func() { defer close(dataStream) for { for _, v := range values { select { case <-ctx.Done(): return case dataStream <- v: } } } }() return dataStream } // RepeatFn return a chan, excutes fn repeatly, and put the result into retruned chan // until close the `done` channel func (c *Channel) RepeatFn(ctx context.Context, fn func() any) <-chan any { dataStream := make(chan any) go func() { defer close(dataStream) for { select { case <-ctx.Done(): return case dataStream <- fn(): } } }() return dataStream } // Take return a chan whose values are tahken from another chan func (c *Channel) Take(ctx context.Context, valueStream <-chan any, number int) <-chan any { takeStream := make(chan any) go func() { defer close(takeStream) for i := 0; i < number; i++ { select { case <-ctx.Done(): return case takeStream <- <-valueStream: } } }() return takeStream } // FanIn merge multiple channels into one channel func (c *Channel) FanIn(ctx context.Context, channels ...<-chan any) <-chan any { out := make(chan any) go func() { var wg sync.WaitGroup wg.Add(len(channels)) for _, c := range channels { go func(c <-chan any) { defer wg.Done() for v := range c { select { case <-ctx.Done(): return case out <- v: } } }(c) } wg.Wait() close(out) }() return out } // Tee split one chanel into two channels func (c *Channel) Tee(ctx context.Context, in <-chan any) (<-chan any, <-chan any) { out1 := make(chan any) out2 := make(chan any) go func() { defer close(out1) defer close(out2) for val := range c.OrDone(ctx, in) { var out1, out2 = out1, out2 for i := 0; i < 2; i++ { select { case <-ctx.Done(): case out1 <- val: out1 = nil case out2 <- val: out2 = nil } } } }() return out1, out2 } // Bridge link multiply channels into one channel func (c *Channel) Bridge(ctx context.Context, chanStream <-chan <-chan any) <-chan any { valStream := make(chan any) go func() { defer close(valStream) for { var stream <-chan any select { case maybeStream, ok := <-chanStream: if ok == false { return } stream = maybeStream case <-ctx.Done(): return } for val := range c.OrDone(ctx, stream) { select { case valStream <- val: case <-ctx.Done(): } } } }() return valStream } // Or read one or more channels into one channel, will close when any readin channel is closed func (c *Channel) Or(channels ...<-chan any) <-chan any { switch len(channels) { case 0: return nil case 1: return channels[0] } orDone := make(chan any) go func() { defer close(orDone) switch len(channels) { case 2: select { case <-channels[0]: case <-channels[1]: } default: m := len(channels) / 2 select { case <-c.Or(channels[:m]...): case <-c.Or(channels[m:]...): } // select { // case <-channels[0]: // case <-channels[1]: // case <-channels[2]: // case <-c.Or(append(channels[3:], orDone)...): // } } }() return orDone } // OrDone read a channel into another channel, will close until cancel context. func (c *Channel) OrDone(ctx context.Context, channel <-chan any) <-chan any { valStream := make(chan any) go func() { defer close(valStream) for { select { case <-ctx.Done(): return case v, ok := <-channel: if !ok { return } select { case valStream <- v: case <-ctx.Done(): } } } }() return valStream }
concurrency/channel.go
0.705684
0.428473
channel.go
starcoder
package set import ( "fmt" "github.com/knutsonchris/stackilackey/cmd" ) type network struct { } /* Description Sets the network address of a network. Arguments {network} The name of the network. Parameters {address=string} Address that the named network should have. */ func (network *network) Address(networkName, address string) ([]byte, error) { c := fmt.Sprintf("set network address %s address='%s'", networkName, address) return cmd.RunCommand(c) } /* DNS enables or Disables DNS for one of more networks. If DNS is enabled for a network then all known hosts on that network will have their hostnames and IP addresses in a DNS server running on the Frontend. This will serve both forward and reverse lookups. Arguments {network ...} The names of one or more networks. Parameters {dns=boolean} Set to True to enable DNS for the given networks. */ func (network *network) DNS(networkName string, dns bool) ([]byte, error) { var dnsstr string if dns == true { dnsstr = "true" } else { dnsstr = "false" } c := fmt.Sprintf("set network dns %s dns='%s'", networkName, dnsstr) return cmd.RunCommand(c) } /* Gateway will set the network gateway of a network. Arguments {network} The name of the network. Parameters {gateway=string} Gateway that the named network should have. */ func (network *network) Gateway(networkName, gateway string) ([]byte, error) { c := fmt.Sprintf("set network gateway %s gateway='%s'", networkName, gateway) return cmd.RunCommand(c) } /* Mask will se the network mask for one or more networks. Arguments {network ...} The names of one or more networks. Parameters {mask=string} Mask that the named network should have. */ func (network *network) Mask(networkName, mask string) ([]byte, error) { c := fmt.Sprintf("set network mask %s mask='%s'", networkName, mask) return cmd.RunCommand(c) } /* MTU will set the MTU for one or more networks. Arguments {network ...} The names of one or more networks. Parameters {mtu=string} MTU value the networks should have. */ func (network *network) MTU(networkName, mtu string) ([]byte, error) { c := fmt.Sprintf("set network mtu %s mtu='%s'", networkName, mtu) return cmd.RunCommand(c) } /* Name will set the network name of a network. Arguments {network} The name of the network. Parameters {name=string} Name that the named network should have. */ func (network *network) Name(networkName, name string) ([]byte, error) { c := fmt.Sprintf("set network name %s name='%s'", networkName, name) return cmd.RunCommand(c) } /* PXE will enable or diable PXE for one or more networks. All hosts must be connected to at least one network that had PXE enabled. Arguments {network ...} The names of one or more networks. Parameters {pxe=boolean} Set to True to enable PXE for the given networks. */ func (network *network) PXE(networkName string, pxe bool) ([]byte, error) { var pxestr string if pxe == true { pxestr = "true" } else { pxestr = "false" } c := fmt.Sprintf("set network pxe %s pxe='%s'", networkName, pxestr) return cmd.RunCommand(c) } /* Zone will set the DNS zone (domain name) for a network. Arguments {network} The name of the network. Parameters {zone=string} Zone that the named network should have. */ func (network *network) Zone(networkName, zone string) ([]byte, error) { c := fmt.Sprintf("set network zone %s zone='%s'", networkName, zone) return cmd.RunCommand(c) }
set/network.go
0.739705
0.402744
network.go
starcoder
package datastructs import ( "strconv" ) // Key is an integer key in a symbol table. type Key int // Value is a string value in a symbol table. type Value string type node struct { key Key val Value left, right *node size int // number of nodes rooted at this node (i.e. number of nodes in the subtree) } // BST represents an ordered symbol table of int/string key-value pairs. type BST struct { root *node // root of the BST } func (b *BST) size(x *node) int { if x == nil { return 0 } return x.size } // Size returns the number of key-value pairs in the symbol table. func (b *BST) Size() int { return b.size(b.root) } // IsEmpty returns true if the symbol table is empty, and false otherwise. func (b *BST) IsEmpty() bool { return b.Size() == 0 } func (b *BST) get(x *node, key Key) (Value, bool) { if x == nil { return "", false } if key < x.key { return b.get(x.left, key) } if key > x.key { return b.get(x.right, key) } return x.val, true } // Get returns the value associated with the given key. func (b *BST) Get(key Key) (Value, bool) { return b.get(b.root, key) } // Contains returns true if the given key is in the symbol table; false otherwise. func (b *BST) Contains(key Key) bool { _, ok := b.Get(key) return ok } func (b *BST) put(x *node, key Key, val Value) *node { if x == nil { return &node{key: key, val: val, size: 1} } if key < x.key { x.left = b.put(x.left, key, val) } else if key > x.key { x.right = b.put(x.right, key, val) } else { x.val = val } x.size = 1 + b.size(x.left) + b.size(x.right) return x } // Put inserts the specified key-value pair into the symbol table. // If the key already exists, overwrites the old value with the new value. func (b *BST) Put(key Key, val Value) { if val == "" { b.Delete(key) return } b.root = b.put(b.root, key, val) } func (b *BST) deleteMin(x *node) *node { if x.left == nil { return x.right } x.left = b.deleteMin(x.left) x.size = b.size(x.left) + b.size(x.right) + 1 return x } // DeleteMin removes the smallest key and associated value from the symbol table. func (b *BST) DeleteMin() { if b.IsEmpty() { panic("Symbol table underflow") } b.root = b.deleteMin(b.root) } func (b *BST) deleteMax(x *node) *node { if x.right == nil { return x.left } x.right = b.deleteMax(x.right) x.size = b.size(x.left) + b.size(x.right) + 1 return x } // DeleteMax removes the largest key and associated value from the symbol table. func (b *BST) DeleteMax() { if b.IsEmpty() { panic("Symbol table underflow") } b.root = b.deleteMax(b.root) } func (b *BST) delete(x *node, key Key) *node { if x == nil { return nil } if key < x.key { x.left = b.delete(x.left, key) } else if key > x.key { x.right = b.delete(x.right, key) } else { if x.right == nil { return x.left } if x.left == nil { return x.right } t := x x = b.min(t.right) x.right = b.deleteMin(t.right) x.left = t.left } x.size = b.size(x.left) + b.size(x.right) + 1 return x } // Delete removes the specified key and its associated value from the symbol table. func (b *BST) Delete(key Key) { b.root = b.delete(b.root, key) } func (b *BST) min(x *node) *node { if x.left == nil { return x } return b.min(x.left) } // Min returns the smallest key in the symbol table. func (b *BST) Min() Key { if b.IsEmpty() { panic("calls Min() with empty symbol table") } return b.min(b.root).key } func (b *BST) max(x *node) *node { if x.right == nil { return x } return b.max(x.right) } // Max returns the largest key in the symbol table. func (b *BST) Max() Key { if b.IsEmpty() { panic("calls Max() with empty symbol table") } return b.max(b.root).key } func (b *BST) floor(x *node, key Key) *node { if x == nil { return nil } if key == x.key { return x } if key < x.key { return b.floor(x.left, key) } t := b.floor(x.right, key) if t != nil { return t } return x } // Floor returns the largest key in the symbol table less than or equal to `key`. func (b *BST) Floor(key Key) Key { if b.IsEmpty() { panic("calls Floor() with empty symbol table") } x := b.floor(b.root, key) if x == nil { panic("argument to Floor() is too small") } return x.key } func (b *BST) ceiling(x *node, key Key) *node { if x == nil { return nil } if key == x.key { return x } if key < x.key { t := b.ceiling(x.left, key) if t != nil { return t } return x } return b.ceiling(x.right, key) } // Ceiling returns the smallest key in the symbol table greater than or equal to `key`. func (b *BST) Ceiling(key Key) Key { if b.IsEmpty() { panic("calls Ceiling() with empty symbol table") } x := b.ceiling(b.root, key) if x == nil { panic("argument to Ceiling() is too large") } return x.key } func (b *BST) selectKey(x *node, rank int) (Key, bool) { if x == nil { return 0, false } leftSize := b.size(x.left) if leftSize > rank { return b.selectKey(x.left, rank) } if leftSize < rank { return b.selectKey(x.right, rank-leftSize-1) } return x.key, true } // Select returns the key of a given rank in the symbol table. This key has the // property that there are `rank` keys in the symbol table that are smaller. func (b *BST) Select(rank int) Key { if rank < 0 || rank >= b.Size() { panic("argument to Select() is invalid: " + strconv.Itoa(rank)) } n, _ := b.selectKey(b.root, rank) return n } func (b *BST) rank(key Key, x *node) int { if x == nil { return 0 } if key < x.key { return b.rank(key, x.left) } if key > x.key { return 1 + b.size(x.left) + b.rank(key, x.right) } return b.size(x.left) } // Rank returns the number of keys in the symbol table strictly less than the specified key. func (b *BST) Rank(key Key) int { return b.rank(key, b.root) } func (b *BST) keysInRange(x *node, queue *[]Key, lo Key, hi Key) { if x == nil { return } if lo < x.key { b.keysInRange(x.left, queue, lo, hi) } if (lo <= x.key) && (hi >= x.key) { *queue = append(*queue, x.key) } if hi > x.key { b.keysInRange(x.right, queue, lo, hi) } } // KeysInRange returns all keys in the symbol table in the given range. func (b *BST) KeysInRange(lo Key, hi Key) []Key { queue := []Key{} b.keysInRange(b.root, &queue, lo, hi) return queue } // Keys returns all keys in the symbol table. func (b *BST) Keys() []Key { if b.IsEmpty() { return []Key{} } return b.KeysInRange(b.Min(), b.Max()) } // SizeOfRange returns the number of keys in the symbol table in the given range. func (b *BST) SizeOfRange(lo Key, hi Key) int { if lo > hi { return 0 } if b.Contains(hi) { return b.Rank(hi) - b.Rank(lo) + 1 } return b.Rank(hi) - b.Rank(lo) }
pkg/datastructs/bst.go
0.852752
0.608856
bst.go
starcoder
package algs import ( "math" "unicode" ) /* MyAtoi solves the following problem: Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value. The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function. If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed. If no valid conversion could be performed, a zero value is returned. Note: Only the space character ' ' is considered as whitespace character. Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. If the numerical value is out of the range of representable values, INT_MAX (2^31 − 1) or INT_MIN (−2^31) is returned. Example 1: Input: "42" Output: 42 Example 2: Input: " -42" Output: -42 Explanation: The first non-whitespace character is '-', which is the minus sign. Then take as many numerical digits as possible, which gets 42. Example 3: Input: "4193 with words" Output: 4193 Explanation: Conversion stops at digit '3' as the next character is not a numerical digit. Example 4: Input: "words and 987" Output: 0 Explanation: The first non-whitespace character is 'w', which is not a numerical digit or a +/- sign. Therefore no valid conversion could be performed. Example 5: Input: "-91283472332" Output: -2147483648 Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer. Thefore INT_MIN (−2^31) is returned. */ func MyAtoi(str string) int { var nums []rune i := 0 for _, v := range str { // 过滤掉第一个数字或者正负号前的空格 if v == rune(' ') && i == 0 { continue } // 判断合法性 if i == 0 && !unicode.IsNumber(v) && v != rune('-') && v != rune('+') { return 0 } // 过滤掉数字后面的非数字 if i > 0 && !unicode.IsNumber(v) { break } nums = append(nums, v) i++ } if len(nums) == 0 { return 0 } // 计算 op := 1 if nums[0] == rune('-') { op = -1 nums = nums[1:] } else if nums[0] == rune('+') { nums = nums[1:] } num := 0 for _, v := range nums { num = num*10 + int(v-rune('0')) // 提前结束,避免结果大于int64时溢出,导致结果不正确 if num > -int(math.MinInt32) { break } } num *= op // 判断值是否超过了int32的范围 if num > math.MaxInt32 { num = math.MaxInt32 } if num < math.MinInt32 { num = math.MinInt32 } return num }
algs/0008.string_to_integer.go
0.657758
0.701764
0008.string_to_integer.go
starcoder
package geopoint import ( "math" ) const ( mileInKilometres = 1.60934 // kilometres -> miles conversion. degToRad = math.Pi / 180.0 // degrees -> radians conversion. earthRadiusInKilometres = 6371 ) // Kilometres are units of distance. type Kilometres float64 // Miles converts kilometres to miles. func (self Kilometres) Miles() Miles { return Miles(self * mileInKilometres) } // Miles are units of distance. type Miles float64 // Kilometres converts miles to kilometres. func (self Miles) Kilometres() Kilometres { return Kilometres(self * mileInKilometres) } // Formula to calculate distance between two GeoPoints. type Formula func(one, two *GeoPoint) Kilometres // Degrees are units of angular measure. type Degrees float64 // Conversion between Degrees and Radians. func (self Degrees) Radians() Radians { return Radians(self * degToRad) } // Radians are units of angular measure. type Radians float64 // Conversion between Radians and Degrees. func (self Radians) Degrees() Degrees { return Degrees(self / degToRad) } // Struct representing GPS coordinates. type GeoPoint struct { Latitude, Longitude Degrees } // Constructor for a GeoPoint. func NewGeoPoint(latitude, longitude Degrees) *GeoPoint { return &GeoPoint{ Latitude: latitude, Longitude: longitude, } } // Distance to another GeoPoint. func (g *GeoPoint) DistanceTo(another *GeoPoint, f Formula) Kilometres { return f(g, another) } // Distance between two GeoPoints using Haversine formula. func Haversine(one, two *GeoPoint) Kilometres { lat1 := one.Latitude.Radians() lng1 := one.Longitude.Radians() lat2 := two.Latitude.Radians() lng2 := two.Longitude.Radians() deltaLng := float64(lng2 - lng1) deltaLat := float64(lat2 - lat1) a := math.Pow((math.Sin(deltaLat/2)), 2.0) + math.Cos(float64(lat1))* math.Cos(float64(lat2))*math.Pow(math.Sin(deltaLng/2), 2.0) c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1.0-a)) return Kilometres(earthRadiusInKilometres * c) }
geopoint.go
0.846133
0.716256
geopoint.go
starcoder
package output import ( "github.com/Jeffail/benthos/lib/log" "github.com/Jeffail/benthos/lib/metrics" "github.com/Jeffail/benthos/lib/output/writer" "github.com/Jeffail/benthos/lib/types" ) //------------------------------------------------------------------------------ func init() { Constructors[TypeHTTPClient] = TypeSpec{ constructor: NewHTTPClient, description: ` Sends messages to an HTTP server. The request will be retried for each message whenever the response code is outside the range of 200 -> 299 inclusive. It is possible to list codes outside of this range in the ` + "`drop_on`" + ` field in order to prevent retry attempts. The period of time between retries is linear by default. Response codes that are within the ` + "`backoff_on`" + ` list will instead apply exponential backoff between retry attempts. When the number of retries expires the output will reject the message, the behaviour after this will depend on the pipeline but usually this simply means the send is attempted again until successful whilst applying back pressure. The URL and header values of this type can be dynamically set using function interpolations described [here](../config_interpolation.md#functions). The body of the HTTP request is the raw contents of the message payload. If the message has multiple parts the request will be sent according to [RFC1341](https://www.w3.org/Protocols/rfc1341/7_2_Multipart.html) ### Propagating Responses It's possible to propagate the response from each HTTP request back to the input source by setting ` + "`propagate_response` to `true`" + `. Only inputs that support [synchronous responses](../sync_responses.md) are able to make use of these propagated responses.`, } } // NewHTTPClient creates a new HTTPClient output type. func NewHTTPClient(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) { h, err := writer.NewHTTPClient(conf.HTTPClient, mgr, log, stats) if err != nil { return nil, err } return NewWriter("http_client", h, log, stats) } //------------------------------------------------------------------------------
lib/output/http_client.go
0.777511
0.407216
http_client.go
starcoder
package trace // This file implements histogramming for RPC statistics collection. import ( "bytes" "fmt" "html/template" "log" "math" "sync" "gx/ipfs/QmRvYNctevGUW52urgmoFZscT6buMKqhHezLUS64WepGWn/go-net/internal/timeseries" ) const ( bucketCount = 38 ) // histogram keeps counts of values in buckets that are spaced // out in powers of 2: 0-1, 2-3, 4-7... // histogram implements timeseries.Observable type histogram struct { sum int64 // running total of measurements sumOfSquares float64 // square of running total buckets []int64 // bucketed values for histogram value int // holds a single value as an optimization valueCount int64 // number of values recorded for single value } // AddMeasurement records a value measurement observation to the histogram. func (h *histogram) addMeasurement(value int64) { // TODO: assert invariant h.sum += value h.sumOfSquares += float64(value) * float64(value) bucketIndex := getBucket(value) if h.valueCount == 0 || (h.valueCount > 0 && h.value == bucketIndex) { h.value = bucketIndex h.valueCount++ } else { h.allocateBuckets() h.buckets[bucketIndex]++ } } func (h *histogram) allocateBuckets() { if h.buckets == nil { h.buckets = make([]int64, bucketCount) h.buckets[h.value] = h.valueCount h.value = 0 h.valueCount = -1 } } func log2(i int64) int { n := 0 for ; i >= 0x100; i >>= 8 { n += 8 } for ; i > 0; i >>= 1 { n += 1 } return n } func getBucket(i int64) (index int) { index = log2(i) - 1 if index < 0 { index = 0 } if index >= bucketCount { index = bucketCount - 1 } return } // Total returns the number of recorded observations. func (h *histogram) total() (total int64) { if h.valueCount >= 0 { total = h.valueCount } for _, val := range h.buckets { total += int64(val) } return } // Average returns the average value of recorded observations. func (h *histogram) average() float64 { t := h.total() if t == 0 { return 0 } return float64(h.sum) / float64(t) } // Variance returns the variance of recorded observations. func (h *histogram) variance() float64 { t := float64(h.total()) if t == 0 { return 0 } s := float64(h.sum) / t return h.sumOfSquares/t - s*s } // StandardDeviation returns the standard deviation of recorded observations. func (h *histogram) standardDeviation() float64 { return math.Sqrt(h.variance()) } // PercentileBoundary estimates the value that the given fraction of recorded // observations are less than. func (h *histogram) percentileBoundary(percentile float64) int64 { total := h.total() // Corner cases (make sure result is strictly less than Total()) if total == 0 { return 0 } else if total == 1 { return int64(h.average()) } percentOfTotal := round(float64(total) * percentile) var runningTotal int64 for i := range h.buckets { value := h.buckets[i] runningTotal += value if runningTotal == percentOfTotal { // We hit an exact bucket boundary. If the next bucket has data, it is a // good estimate of the value. If the bucket is empty, we interpolate the // midpoint between the next bucket's boundary and the next non-zero // bucket. If the remaining buckets are all empty, then we use the // boundary for the next bucket as the estimate. j := uint8(i + 1) min := bucketBoundary(j) if runningTotal < total { for h.buckets[j] == 0 { j++ } } max := bucketBoundary(j) return min + round(float64(max-min)/2) } else if runningTotal > percentOfTotal { // The value is in this bucket. Interpolate the value. delta := runningTotal - percentOfTotal percentBucket := float64(value-delta) / float64(value) bucketMin := bucketBoundary(uint8(i)) nextBucketMin := bucketBoundary(uint8(i + 1)) bucketSize := nextBucketMin - bucketMin return bucketMin + round(percentBucket*float64(bucketSize)) } } return bucketBoundary(bucketCount - 1) } // Median returns the estimated median of the observed values. func (h *histogram) median() int64 { return h.percentileBoundary(0.5) } // Add adds other to h. func (h *histogram) Add(other timeseries.Observable) { o := other.(*histogram) if o.valueCount == 0 { // Other histogram is empty } else if h.valueCount >= 0 && o.valueCount > 0 && h.value == o.value { // Both have a single bucketed value, aggregate them h.valueCount += o.valueCount } else { // Two different values necessitate buckets in this histogram h.allocateBuckets() if o.valueCount >= 0 { h.buckets[o.value] += o.valueCount } else { for i := range h.buckets { h.buckets[i] += o.buckets[i] } } } h.sumOfSquares += o.sumOfSquares h.sum += o.sum } // Clear resets the histogram to an empty state, removing all observed values. func (h *histogram) Clear() { h.buckets = nil h.value = 0 h.valueCount = 0 h.sum = 0 h.sumOfSquares = 0 } // CopyFrom copies from other, which must be a *histogram, into h. func (h *histogram) CopyFrom(other timeseries.Observable) { o := other.(*histogram) if o.valueCount == -1 { h.allocateBuckets() copy(h.buckets, o.buckets) } h.sum = o.sum h.sumOfSquares = o.sumOfSquares h.value = o.value h.valueCount = o.valueCount } // Multiply scales the histogram by the specified ratio. func (h *histogram) Multiply(ratio float64) { if h.valueCount == -1 { for i := range h.buckets { h.buckets[i] = int64(float64(h.buckets[i]) * ratio) } } else { h.valueCount = int64(float64(h.valueCount) * ratio) } h.sum = int64(float64(h.sum) * ratio) h.sumOfSquares = h.sumOfSquares * ratio } // New creates a new histogram. func (h *histogram) New() timeseries.Observable { r := new(histogram) r.Clear() return r } func (h *histogram) String() string { return fmt.Sprintf("%d, %f, %d, %d, %v", h.sum, h.sumOfSquares, h.value, h.valueCount, h.buckets) } // round returns the closest int64 to the argument func round(in float64) int64 { return int64(math.Floor(in + 0.5)) } // bucketBoundary returns the first value in the bucket. func bucketBoundary(bucket uint8) int64 { if bucket == 0 { return 0 } return 1 << bucket } // bucketData holds data about a specific bucket for use in distTmpl. type bucketData struct { Lower, Upper int64 N int64 Pct, CumulativePct float64 GraphWidth int } // data holds data about a Distribution for use in distTmpl. type data struct { Buckets []*bucketData Count, Median int64 Mean, StandardDeviation float64 } // maxHTMLBarWidth is the maximum width of the HTML bar for visualizing buckets. const maxHTMLBarWidth = 350.0 // newData returns data representing h for use in distTmpl. func (h *histogram) newData() *data { // Force the allocation of buckets to simplify the rendering implementation h.allocateBuckets() // We scale the bars on the right so that the largest bar is // maxHTMLBarWidth pixels in width. maxBucket := int64(0) for _, n := range h.buckets { if n > maxBucket { maxBucket = n } } total := h.total() barsizeMult := maxHTMLBarWidth / float64(maxBucket) var pctMult float64 if total == 0 { pctMult = 1.0 } else { pctMult = 100.0 / float64(total) } buckets := make([]*bucketData, len(h.buckets)) runningTotal := int64(0) for i, n := range h.buckets { if n == 0 { continue } runningTotal += n var upperBound int64 if i < bucketCount-1 { upperBound = bucketBoundary(uint8(i + 1)) } else { upperBound = math.MaxInt64 } buckets[i] = &bucketData{ Lower: bucketBoundary(uint8(i)), Upper: upperBound, N: n, Pct: float64(n) * pctMult, CumulativePct: float64(runningTotal) * pctMult, GraphWidth: int(float64(n) * barsizeMult), } } return &data{ Buckets: buckets, Count: total, Median: h.median(), Mean: h.average(), StandardDeviation: h.standardDeviation(), } } func (h *histogram) html() template.HTML { buf := new(bytes.Buffer) if err := distTmpl().Execute(buf, h.newData()); err != nil { buf.Reset() log.Printf("net/trace: couldn't execute template: %v", err) } return template.HTML(buf.String()) } var distTmplCache *template.Template var distTmplOnce sync.Once func distTmpl() *template.Template { distTmplOnce.Do(func() { // Input: data distTmplCache = template.Must(template.New("distTmpl").Parse(` <table> <tr> <td style="padding:0.25em">Count: {{.Count}}</td> <td style="padding:0.25em">Mean: {{printf "%.0f" .Mean}}</td> <td style="padding:0.25em">StdDev: {{printf "%.0f" .StandardDeviation}}</td> <td style="padding:0.25em">Median: {{.Median}}</td> </tr> </table> <hr> <table> {{range $b := .Buckets}} {{if $b}} <tr> <td style="padding:0 0 0 0.25em">[</td> <td style="text-align:right;padding:0 0.25em">{{.Lower}},</td> <td style="text-align:right;padding:0 0.25em">{{.Upper}})</td> <td style="text-align:right;padding:0 0.25em">{{.N}}</td> <td style="text-align:right;padding:0 0.25em">{{printf "%#.3f" .Pct}}%</td> <td style="text-align:right;padding:0 0.25em">{{printf "%#.3f" .CumulativePct}}%</td> <td><div style="background-color: blue; height: 1em; width: {{.GraphWidth}};"></div></td> </tr> {{end}} {{end}} </table> `)) }) return distTmplCache }
vendor/gx/ipfs/QmRvYNctevGUW52urgmoFZscT6buMKqhHezLUS64WepGWn/go-net/trace/histogram.go
0.701713
0.46217
histogram.go
starcoder
package model import ( "errors" "math/rand" ) type Player int // Players const ( White Player = iota Red Spaces = 26 BarPosition = Spaces - 1 HomePosition = 0 ) // Board backgammon board type Board struct { Turn int Board [2][Spaces]int Hit [2]int Borne [2]int Pips [2]int } func reverse(numbers [Spaces]int) [Spaces]int { var newNumbers [Spaces]int j := 0 for i := Spaces - 1; i >= 0; i-- { newNumbers[j] = numbers[i] j++ } return newNumbers } // Setup the backgammon board with the initial position for players func NewBoard() *Board { b := &Board{} var redPosition = [Spaces]int{0, 0, 0, 0, 0, 0, 5, 0, 3, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0} var whitePosition = [Spaces]int{0, 0, 0, 0, 0, 0, 5, 0, 3, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0} b.Board = [2][Spaces]int{whitePosition, redPosition} b.Turn = 0 b.GetPips() return b } func (b *Board) Move(player Player, initialPos int, moves int) (bool, error) { possibleMoves := b.GetPossibleMoves(player, moves) if len(possibleMoves) < 1 { return false, errors.New("No moves possible") } adversaryBoard := reverse(b.Board[adversary(player)]) hasMoved := false if contains(possibleMoves, initialPos) { b.Board[player][initialPos]-- if initialPos-moves <= HomePosition { b.Board[player][HomePosition]++ } else { b.Board[player][initialPos-moves]++ if adversaryBoard[getAdversaryPosition(initialPos)] == 1 { b.Board[adversary(player)][getAdversaryPosition(initialPos)] = 0 b.Board[adversary(player)][BarPosition]++ } } hasMoved = true } b.GetPips() return hasMoved, nil } func (b *Board) GetPossibleMoves(player Player, moves int) []int { currentPlayerBoard := b.Board[player] adversaryBoard := reverse(b.Board[adversary(player)]) var possibleMoves []int if currentPlayerBoard[BarPosition] > 0 { if adversaryBoard[BarPosition-moves] < 2 { possibleMoves = append(possibleMoves, BarPosition) } return possibleMoves } for i := 0; i < Spaces; i++ { if i-moves < HomePosition && b.IsPlayerHome(player) && i > HomePosition { possibleMoves = append(possibleMoves, i) } if i-moves > HomePosition && currentPlayerBoard[i] > 0 && adversaryBoard[i-moves] < 2 { possibleMoves = append(possibleMoves, i) } } return possibleMoves } func RollDie() int { min := 1 max := 6 return rand.Intn(max-min) + min } func (b *Board) NextTurn() Player { b.Turn++ return Player(b.Turn % 2) } func (b *Board) GetCurrentPlayer() Player { return Player(b.Turn % 2) } func adversary(player Player) Player { switch player { case White: return Red default: return White } } func (b *Board) IsPlayerHome(player Player) bool { checkers := []int{} sum := 0 checkers = b.Board[player][:18] for _, num := range checkers { sum += num } return sum == 0 } func (b *Board) IsHit(player Player) bool { return b.Board[player][BarPosition] > 0 } func (board *Board) GetPips() { board.Pips[White] = CalculatePips(board.Board[White]) board.Pips[Red] = CalculatePips(board.Board[Red]) } func CalculatePips(position [Spaces]int) int { pips := 0 for i := 0; i < len(position); i++ { pips += i * position[i] } return pips } func getAdversaryPosition(position int) int { adversary := []int{25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0} return adversary[position] } func contains(s []int, e int) bool { for _, a := range s { if a == e { return true } } return false }
model/board.go
0.566258
0.470858
board.go
starcoder
package trea import ( "encoding/xml" "github.com/fairxio/finance-messaging/iso20022" ) type Document00200102 struct { XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:trea.002.001.02 Document"` Message *AmendNonDeliverableForwardOpeningV02 `xml:"AmdNDFOpngV02"` } func (d *Document00200102) AddMessage() *AmendNonDeliverableForwardOpeningV02 { d.Message = new(AmendNonDeliverableForwardOpeningV02) return d.Message } // Scope // The AmendNonDeliverableForwardOpening message is sent by a participant to a central system or to a counterparty to notify the amendment of the opening of a non deliverable trade previously confirmed by the sender. // Usage // The message is sent from a participant to a central settlement system to advise of the update of a previously sent notification and it contains a "Related Reference" to link it to the previous notification. type AmendNonDeliverableForwardOpeningV02 struct { // Provides references and date of the non deliverable trade which is amended. TradeInformation *iso20022.TradeAgreement2 `xml:"TradInf"` // Specifies the trading side of the non deliverable trade which is amended. TradingSideIdentification *iso20022.TradePartyIdentification3 `xml:"TradgSdId"` // Specifies the counterparty of the non deliverable trade which is amended. CounterpartySideIdentification *iso20022.TradePartyIdentification3 `xml:"CtrPtySdId"` // Specifies the amounts of the non deliverable trade which is amended. TradeAmounts *iso20022.AmountsAndValueDate1 `xml:"TradAmts"` // Specifies the rate of the non deliverable trade which is amended. AgreedRate *iso20022.AgreedRate1 `xml:"AgrdRate"` // Specifies the valuation conditions of the non deliverable trade which is amended. ValuationConditions *iso20022.NonDeliverableForwardValuationConditions2 `xml:"ValtnConds"` } func (a *AmendNonDeliverableForwardOpeningV02) AddTradeInformation() *iso20022.TradeAgreement2 { a.TradeInformation = new(iso20022.TradeAgreement2) return a.TradeInformation } func (a *AmendNonDeliverableForwardOpeningV02) AddTradingSideIdentification() *iso20022.TradePartyIdentification3 { a.TradingSideIdentification = new(iso20022.TradePartyIdentification3) return a.TradingSideIdentification } func (a *AmendNonDeliverableForwardOpeningV02) AddCounterpartySideIdentification() *iso20022.TradePartyIdentification3 { a.CounterpartySideIdentification = new(iso20022.TradePartyIdentification3) return a.CounterpartySideIdentification } func (a *AmendNonDeliverableForwardOpeningV02) AddTradeAmounts() *iso20022.AmountsAndValueDate1 { a.TradeAmounts = new(iso20022.AmountsAndValueDate1) return a.TradeAmounts } func (a *AmendNonDeliverableForwardOpeningV02) AddAgreedRate() *iso20022.AgreedRate1 { a.AgreedRate = new(iso20022.AgreedRate1) return a.AgreedRate } func (a *AmendNonDeliverableForwardOpeningV02) AddValuationConditions() *iso20022.NonDeliverableForwardValuationConditions2 { a.ValuationConditions = new(iso20022.NonDeliverableForwardValuationConditions2) return a.ValuationConditions }
iso20022/trea/AmendNonDeliverableForwardOpeningV02.go
0.706393
0.403391
AmendNonDeliverableForwardOpeningV02.go
starcoder
package main // user represents an user in the system. type user struct { name string email string } func main() { // ------------- // Pass by value // ------------- // Declare variable of type int with a value of 10. // This value is put on a stack with a value of 10. count := 10 // To get the address of a value, we use &. println("count:\tValue Of[", count, "], \tAddr Of[", &count, "]") // Pass the "value of" count. increment1(count) // Printing out the result of count. Nothing has changed. println("count:\tValue Of[", count, "], \tAddr Of[", &count, "]") // Pass the "address of" count. // This is still considered pass by value, not by reference because the address itself is a value. increment2(&count) // Printing out the result of count. count is updated. println("count:\tValue Of[", count, "], \tAddr Of[", &count, "]") // --------------- // Escape analysis // --------------- stayOnStack() escapeToHeap() } func increment1(inc int) { // Increment the "value of" inc. inc++ println("inc1:\tValue Of[", inc, "], \tAddr Of[", &inc, "]") } // increment2 declares count as a pointer variable whose value is always an address and points to // values of type int. // The * here is not an operator. It is part of the type name. // Every type that is declared, whether you declare or it is predeclared, you get for free a pointer. func increment2(inc *int) { // Increment the "value of" count that the "pointer points to". // The * is an operator. It tells us the value of the pointer points to. *inc++ println("inc2:\tValue Of[", inc, "], \t Value Points To[", *inc, "], \t Addr Of [", &inc, "]") } // stayOnStack shows how the variable does not escape. func stayOnStack() user { // In the stayOnStack stack frame, create a value and initialize it. u := user{ name: "<NAME>", email: "<EMAIL>", } // Take the value and return it, pass back up to main stack frame. return u } // escapeToHeap shows how the variable escape. func escapeToHeap() *user { u := user{ name: "<NAME>", email: "<EMAIL>", } return &u }
Language_Specification/build-in-type/pointers/pointers.go
0.516595
0.408808
pointers.go
starcoder
package prototype import ( "errors" "fmt" "math/big" "github.com/ethereum/go-ethereum/common" log "github.com/sirupsen/logrus" "github.com/perun-network/erdstall/tee" ) type ( // Epoch manages deposits, transactions, and exits, as well as the // progression of time in the system. Epoch struct { number tee.Epoch // Current deposit epoch. exitLocked map[common.Address]struct{} // Withdrawing at end of epoch. exitReqs map[common.Address]struct{} // Requested exits. accs map[common.Address]*Acc // Latest account states. outcome chan Outcome // The last epoch's outcome. } // Acc contains an account's balance and transaction nonce. Acc struct { Nonce uint64 Value *big.Int } // Outcome contains all of an epoch's final balances, as well as all // accounts that exited the system at the end of the epoch. Outcome struct { TxEpoch tee.Epoch // The finished TX epoch. Exits map[common.Address]*Acc // Exited accounts. Accounts map[common.Address]*Acc // Final balances and nonces. } ) func newEpoch(n tee.Epoch) *Epoch { return &Epoch{ number: n, exitLocked: make(map[common.Address]struct{}), exitReqs: make(map[common.Address]struct{}), accs: make(map[common.Address]*Acc), outcome: make(chan Outcome, 1), } } // DepositNum is the current deposit epoch number. func (e *Epoch) DepositNum() tee.Epoch { return e.number } // TxNum is the current transaction epoch number. func (e *Epoch) TxNum() tee.Epoch { return e.number - 1 } // ExitNum is the current exit epoch number. func (e *Epoch) ExitNum() tee.Epoch { return e.number - 2 } // Outcome has to be called exactly once after each phase shift and contains all // accounts that exited within this epoch, as well as all balances at the end of // the epoch. It blocks until the epoch in which it was last called ends. func (e *Epoch) Outcome() (o Outcome) { select { case o = <-e.outcome: default: log.Panic("Requested outcome twice or before end of epoch") } return // Go doesn't recognize that log.Panic will not return. } // RegisterExits registers a exit requests for the end of the current phase. The // requested accounts are locked for one epoch before they can be withdrawn. func (e *Epoch) RegisterExits(exitReqs ...*erdstallExitEvent) { for _, exit := range exitReqs { if exit.Epoch != e.ExitNum() { log.WithFields(log.Fields{ "req. epoch": exit.Epoch, "exit epoch": e.ExitNum(), }).Panic("epoch mismatch") } e.exitReqs[exit.Account] = struct{}{} } } // ApplyDeposits applies a series deposit events and makes the deposited values // available instantly. func (e *Epoch) ApplyDeposits(deposits ...*erdstallDepEvent) { for _, dep := range deposits { e.receive(dep.Account, dep.Value) } } // receive increases an account's balance, or creates a new account if it didn't // exist yet. func (e *Epoch) receive(account common.Address, value *big.Int) { if acc, ok := e.accs[account]; ok { acc.Value.Add(acc.Value, value) } else { e.accs[account] = &Acc{ Nonce: 0, Value: new(big.Int).Set(value), } } } // ProcessTx processes a transaction. If it is invalid, does nothing and returns // an error. A transaction is invalid if either party is currently locked for // withdrawal or the transaction is otherwise invalid (e.g., insufficient funds, // invalid signature, ...). Valid transactions increase the sender's nonce. func (e *Epoch) ProcessTx(contract common.Address, tx *tee.Transaction) error { sender, ok := e.accs[tx.Sender] if !ok { return errors.New("sender does not exist") } // Flush the tx.hash so that it is recalculated. *tx = tee.Transaction{ Nonce: tx.Nonce, Epoch: tx.Epoch, Sender: tx.Sender, Recipient: tx.Recipient, Amount: tx.Amount, Sig: tx.Sig} // Check whether both participants are eligible for trading and that the // transaction is valid. if _, locked := e.exitLocked[tx.Sender]; locked { return errors.New("sender is locked for withdrawing") } else if _, locked := e.exitLocked[tx.Recipient]; locked { return errors.New("recipient is locked for withdrawing") } else if tx.Nonce != sender.Nonce+1 { return fmt.Errorf("nonce mismatch: %d != %d", tx.Nonce, sender.Nonce+1) } else if sender.Value.Cmp((*big.Int)(tx.Amount)) < 0 { return errors.New("insufficient balance") } else if (*big.Int)(tx.Amount).Sign() < 0 { return errors.New("negative amount") } else if tx.Epoch != e.TxNum() { return fmt.Errorf("epoch mismatch: %d != %d", tx.Epoch, e.TxNum()) } else if valid, err := tee.VerifyTransaction(contract, *tx); err != nil { return fmt.Errorf("verifying tx signature: %w", err) } else if !valid { return fmt.Errorf("invalid tx signature") } // Execute the transaction. sender.Value.Sub(sender.Value, (*big.Int)(tx.Amount)) sender.Nonce = tx.Nonce e.receive(tx.Recipient, (*big.Int)(tx.Amount)) return nil } // progressPhase transitions from one epoch to the next and resets all // phase-specific fields of the previous phase. It also applies any ongoing // exits. func (e *Epoch) progressPhase() { // Settle current epoch. exits := e.applyExits() bals := e.cloneBals() // Publish the epoch's outcome. e.outcome <- Outcome{TxEpoch: e.TxNum(), Exits: exits, Accounts: bals} e.number++ } // applyExits deletes all accounts that exited during the previous epoch and // returns their final balances. Exit requests for nonexisting accounts are // ignored. func (e *Epoch) applyExits() map[common.Address]*Acc { exits := make(map[common.Address]*Acc) // Delete and collect all accounts that were locked for withdrawing during // this epoch. for addr := range e.exitLocked { if bal, ok := e.accs[addr]; ok { delete(e.accs, addr) exits[addr] = bal } } // Lock all accounts that requested to withdraw within the next epoch. e.exitLocked, e.exitReqs = e.exitReqs, make(map[common.Address]struct{}) return exits } func (e *Epoch) cloneBals() map[common.Address]*Acc { accs := make(map[common.Address]*Acc) for addr, acc := range e.accs { accs[addr] = &Acc{ Nonce: acc.Nonce, Value: new(big.Int).Set(acc.Value), } } return accs } // IsExitLocked returns whether an account is exit locked. func (e *Epoch) IsExitLocked(who common.Address) bool { _, ok := e.exitLocked[who] return ok } // Balance looks up an account balance in the epoch. func (e *Epoch) Balance(who common.Address) *big.Int { if acc, ok := e.accs[who]; ok { return new(big.Int).Set(acc.Value) } else { return big.NewInt(0) } }
tee/prototype/epoch.go
0.569254
0.443721
epoch.go
starcoder
package blockchain import ( "fmt" "time" chaincfg "git.parallelcoin.io/dev/pod/pkg/chain/config" "git.parallelcoin.io/dev/pod/pkg/chain/fork" chainhash "git.parallelcoin.io/dev/pod/pkg/chain/hash" database "git.parallelcoin.io/dev/pod/pkg/db" "git.parallelcoin.io/dev/pod/pkg/util" cl "git.parallelcoin.io/dev/pod/pkg/util/cl" ) // BehaviorFlags is a bitmask defining tweaks to the normal behavior when performing chain processing and consensus rules checks. type BehaviorFlags uint32 const ( // BFFastAdd may be set to indicate that several checks can be avoided for the block since it is already known to fit into the chain due to already proving it correct links into the chain up to a known checkpoint. This is primarily used for headers-first mode. BFFastAdd BehaviorFlags = 1 << iota // BFNoPoWCheck may be set to indicate the proof of work check which ensures a block hashes to a value less than the required target will not be performed. BFNoPoWCheck // BFNone is a convenience value to specifically indicate no flags. BFNone BehaviorFlags = 0 ) // ProcessBlock is the main workhorse for handling insertion of new blocks into the block chain. It includes functionality such as rejecting duplicate blocks, ensuring blocks follow all rules, orphan handling, and insertion into the block chain along with best chain selection and reorganization. When no errors occurred during processing, the first return value indicates whether or not the block is on the main chain and the second indicates whether or not the block is an orphan. This function is safe for concurrent access. func ( b *BlockChain, ) ProcessBlock( block *util.Block, flags BehaviorFlags, height int32, ) ( bool, bool, error, ) { blockHeight := height bb, _ := b.BlockByHash(&block.MsgBlock().Header.PrevBlock) if bb != nil { blockHeight = bb.Height() + 1 } b.chainLock.Lock() defer b.chainLock.Unlock() fastAdd := flags&BFFastAdd == BFFastAdd blockHash := block.Hash() hf := fork.GetCurrent(height) blockHashWithAlgo := func() string { return block.MsgBlock().BlockHashWithAlgos(height).String() } log <- cl.Tracec(func() string { return "processing block" + blockHashWithAlgo() }) var algo int32 switch hf { case 0: if block.MsgBlock().Header.Version != 514 { algo = 2 } else { algo = 514 } case 1: algo = block.MsgBlock().Header.Version } // The block must not already exist in the main chain or side chains. exists, err := b.blockExists(blockHash) if err != nil { return false, false, err } if exists { str := fmt.Sprintf("already have block %v", blockHashWithAlgo()) return false, false, ruleError(ErrDuplicateBlock, str) } // The block must not already exist as an orphan. if _, exists := b.orphans[*blockHash]; exists { str := fmt.Sprintf( "already have block (orphan) %v", blockHashWithAlgo()) return false, false, ruleError(ErrDuplicateBlock, str) } // Perform preliminary sanity checks on the block and its transactions. var DoNotCheckPow bool pl := fork.GetMinDiff(fork.GetAlgoName(algo, height), height) ph := &block.MsgBlock().Header.PrevBlock pn := b.Index.LookupNode(ph) if pn == nil { log <- cl.Debug{"found no previous node"} DoNotCheckPow = true } pb := pn.GetLastWithAlgo(algo) if pb == nil { pl = &chaincfg.AllOnes DoNotCheckPow = true } err = checkBlockSanity(block, pl, b.timeSource, flags, DoNotCheckPow, height) if err != nil { log <- cl.Debug{"block processing error:", err} return false, false, err } // Find the previous checkpoint and perform some additional checks based on the checkpoint. This provides a few nice properties such as preventing old side chain blocks before the last checkpoint, rejecting easy to mine, but otherwise bogus, blocks that could be used to eat memory, and ensuring expected (versus claimed) proof of work requirements since the previous checkpoint are met. blockHeader := &block.MsgBlock().Header checkpointNode, err := b.findPreviousCheckpoint() if err != nil { return false, false, err } if checkpointNode != nil { // Ensure the block timestamp is after the checkpoint timestamp. checkpointTime := time.Unix(checkpointNode.timestamp, 0) if blockHeader.Timestamp.Before(checkpointTime) { str := fmt.Sprintf("block %v has timestamp %v before "+ "last checkpoint timestamp %v", blockHashWithAlgo(), blockHeader.Timestamp, checkpointTime) return false, false, ruleError(ErrCheckpointTimeTooOld, str) } if !fastAdd { // Even though the checks prior to now have already ensured the proof of work exceeds the claimed amount, the claimed amount is a field in the block header which could be forged. This check ensures the proof of work is at least the minimum expected based on elapsed time since the last checkpoint and maximum adjustment allowed by the retarget rules. duration := blockHeader.Timestamp.Sub(checkpointTime) requiredTarget := CompactToBig(b.calcEasiestDifficulty( checkpointNode.bits, duration)) currentTarget := CompactToBig(blockHeader.Bits) if currentTarget.Cmp(requiredTarget) > 0 { str := fmt.Sprintf("processing: block target difficulty of %064x is too low when compared to the previous checkpoint", currentTarget) return false, false, ruleError(ErrDifficultyTooLow, str) } } } // Handle orphan blocks. prevHash := &blockHeader.PrevBlock prevHashExists, err := b.blockExists(prevHash) if err != nil { return false, false, err } if !prevHashExists { Log.Infc(func() string { return fmt.Sprintf( "adding orphan block %v with parent %v", blockHashWithAlgo(), prevHash, ) }) b.addOrphanBlock(block) return false, true, nil } // The block has passed all context independent checks and appears sane enough to potentially accept it into the block chain. isMainChain, err := b.maybeAcceptBlock(block, flags) if err != nil { return false, false, err } // Accept any orphan blocks that depend on this block (they are no longer orphans) and repeat for those accepted blocks until there are no more. err = b.processOrphans(blockHash, flags) if err != nil { return false, false, err } log <- cl.Debugf{ "accepted block %d %v %s ", blockHeight, blockHashWithAlgo(), fork.GetAlgoName(block.MsgBlock().Header.Version, blockHeight), } return isMainChain, false, nil } // blockExists determines whether a block with the given hash exists either in the main chain or any side chains. This function is safe for concurrent access. func ( b *BlockChain, ) blockExists( hash *chainhash.Hash) (bool, error) { // Check block index first (could be main chain or side chain blocks). if b.Index.HaveBlock(hash) { return true, nil } // Check in the database. var exists bool err := b.db.View(func(dbTx database.Tx) error { var err error exists, err = dbTx.HasBlock(hash) if err != nil || !exists { return err } // Ignore side chain blocks in the database. This is necessary because there is not currently any record of the associated block index data such as its block height, so it's not yet possible to efficiently load the block and do anything useful with it. Ultimately the entire block index should be serialized instead of only the current main chain so it can be consulted directly. _, err = dbFetchHeightByHash(dbTx, hash) if isNotInMainChainErr(err) { exists = false return nil } return err }) return exists, err } // processOrphans determines if there are any orphans which depend on the passed block hash (they are no longer orphans if true) and potentially accepts them. It repeats the process for the newly accepted blocks (to detect further orphans which may no longer be orphans) until there are no more. The flags do not modify the behavior of this function directly, however they are needed to pass along to maybeAcceptBlock. This function MUST be called with the chain state lock held (for writes). func ( b *BlockChain, ) processOrphans( hash *chainhash.Hash, flags BehaviorFlags) error { // Start with processing at least the passed hash. Leave a little room for additional orphan blocks that need to be processed without needing to grow the array in the common case. processHashes := make([]*chainhash.Hash, 0, 10) processHashes = append(processHashes, hash) for len(processHashes) > 0 { // Pop the first hash to process from the slice. processHash := processHashes[0] processHashes[0] = nil // Prevent GC leak. processHashes = processHashes[1:] // Look up all orphans that are parented by the block we just accepted. This will typically only be one, but it could be multiple if multiple blocks are mined and broadcast around the same time. The one with the most proof of work will eventually win out. An indexing for loop is intentionally used over a range here as range does not reevaluate the slice on each iteration nor does it adjust the index for the modified slice. for i := 0; i < len(b.prevOrphans[*processHash]); i++ { orphan := b.prevOrphans[*processHash][i] if orphan == nil { log <- cl.Warnf{ "found a nil entry at index %d in the orphan dependency list for block %v", i, processHash, } continue } // Remove the orphan from the orphan pool. orphanHash := orphan.block.Hash() b.removeOrphanBlock(orphan) i-- // Potentially accept the block into the block chain. _, err := b.maybeAcceptBlock(orphan.block, flags) if err != nil { return err } // Add this block to the list of blocks to process so any orphan blocks that depend on this block are handled too. processHashes = append(processHashes, orphanHash) } } return nil }
pkg/chain/process.go
0.634204
0.424472
process.go
starcoder
package bls12377 import ( "crypto/rand" "io" "math/big" ) const frByteSize = 32 const frBitSize = 253 const frNumberOfLimbs = 4 const fourWordBitSize = 256 // halfR = 2**256 / 2 var halfR = &wideFr{0, 0, 0, 0x8000000000000000, 0, 0, 0} var halfRBig = bigFromHex("0x8000000000000000000000000000000000000000000000000000000000000000") type Fr [4]uint64 type wideFr [8]uint64 func NewFr() *Fr { return &Fr{} } func (e *Fr) Rand(r io.Reader) (*Fr, error) { bi, err := rand.Int(r, qBig) if err != nil { return nil, err } _ = e.fromBig(bi) return e, nil } func (e *Fr) Set(e2 *Fr) *Fr { e[0] = e2[0] e[1] = e2[1] e[2] = e2[2] e[3] = e2[3] return e } func (e *Fr) Zero() *Fr { e[0] = 0 e[1] = 0 e[2] = 0 e[3] = 0 return e } func (e *Fr) One() *Fr { e.Set(&Fr{1}) return e } func (e *Fr) RedOne() *Fr { e.Set(qr1) return e } func (e *Fr) FromBytes(in []byte) *Fr { e.fromBytes(in) return e } func (e *Fr) RedFromBytes(in []byte) *Fr { e.fromBytes(in) e.toMont() return e } func (e *Fr) fromBytes(in []byte) *Fr { u := new(big.Int).SetBytes(in) _ = e.fromBig(u) return e } func (e *Fr) fromBig(in *big.Int) *Fr { e.Zero() _in := new(big.Int).Set(in) zero := new(big.Int) c0 := _in.Cmp(zero) c1 := _in.Cmp(qBig) if c0 == -1 || c1 == 1 { _in.Mod(_in, qBig) } words := _in.Bits() for i := 0; i < len(words); i++ { e[i] = uint64(words[i]) } return e } func (e *Fr) setUint64(n uint64) *Fr { e.Zero() e[0] = n return e } func (e *Fr) ToBytes() []byte { return NewFr().Set(e).bytes() } func (e *Fr) RedToBytes() []byte { out := NewFr().Set(e) out.fromMont() return out.bytes() } func (e *Fr) ToBig() *big.Int { return new(big.Int).SetBytes(e.ToBytes()) } func (e *Fr) RedToBig() *big.Int { return new(big.Int).SetBytes(e.RedToBytes()) } func (e *Fr) bytes() []byte { out := make([]byte, frByteSize) var a int for i := 0; i < frNumberOfLimbs; i++ { a = frByteSize - i*8 out[a-1] = byte(e[i]) out[a-2] = byte(e[i] >> 8) out[a-3] = byte(e[i] >> 16) out[a-4] = byte(e[i] >> 24) out[a-5] = byte(e[i] >> 32) out[a-6] = byte(e[i] >> 40) out[a-7] = byte(e[i] >> 48) out[a-8] = byte(e[i] >> 56) } return out } func (e *Fr) IsZero() bool { return (e[3] | e[2] | e[1] | e[0]) == 0 } func (e *Fr) IsOne() bool { return e.Equal(&Fr{1}) } func (e *Fr) IsRedOne() bool { return e.Equal(qr1) } func (e *Fr) Equal(e2 *Fr) bool { return e2[0] == e[0] && e2[1] == e[1] && e2[2] == e[2] && e2[3] == e[3] } func (e *Fr) Cmp(e1 *Fr) int { for i := frNumberOfLimbs - 1; i >= 0; i-- { if e[i] > e1[i] { return 1 } else if e[i] < e1[i] { return -1 } } return 0 } func (e *Fr) sliceUint64(from int) uint64 { if from < 64 { return e[0]>>from | e[1]<<(64-from) } else if from < 128 { return e[1]>>(from-64) | e[2]<<(128-from) } else if from < 192 { return e[2]>>(from-128) | e[3]<<(192-from) } return e[3] >> (from - 192) } func (e *Fr) div2() { e[0] = e[0]>>1 | e[1]<<63 e[1] = e[1]>>1 | e[2]<<63 e[2] = e[2]>>1 | e[3]<<63 e[3] = e[3] >> 1 } func (e *Fr) mul2() uint64 { c := e[3] >> 63 e[3] = e[3]<<1 | e[2]>>63 e[2] = e[2]<<1 | e[1]>>63 e[1] = e[1]<<1 | e[0]>>63 e[0] = e[0] << 1 return c } func (e *Fr) isEven() bool { var mask uint64 = 1 return e[0]&mask == 0 } func (e *Fr) Bit(at int) bool { if at < 64 { return (e[0]>>at)&1 == 1 } else if at < 128 { return (e[1]>>(at-64))&1 == 1 } else if at < 192 { return (e[2]>>(at-128))&1 == 1 } else if at < 256 { return (e[3]>>(at-192))&1 == 1 } return false } func (e *Fr) toMont() { e.RedMul(e, qr2) } func (e *Fr) fromMont() { e.RedMul(e, &Fr{1}) } func (e *Fr) Add(a, b *Fr) { addFR(e, a, b) } func (e *Fr) Double(a *Fr) { doubleFR(e, a) } func (e *Fr) Sub(a, b *Fr) { subFR(e, a, b) } func (e *Fr) Mul(a, b *Fr) { mulFR(e, a, b) mulFR(e, e, qr2) } func (e *Fr) RedMul(a, b *Fr) { mulFR(e, a, b) } func (e *Fr) Square(a *Fr) { squareFR(e, a) mulFR(e, e, qr2) } func (e *Fr) RedSquare(a *Fr) { squareFR(e, a) } func (e *Fr) Neg(a *Fr) { negFR(e, a) } func (e *Fr) Exp(a *Fr, ee *big.Int) { z := new(Fr).RedOne() for i := ee.BitLen(); i >= 0; i-- { z.RedSquare(z) if ee.Bit(i) == 1 { z.RedMul(z, a) } } e.Set(z) } func (e *Fr) Inverse(ei *Fr) { if ei.IsZero() { e.Zero() return } u := new(Fr).Set(&q) v := new(Fr).Set(ei) s := &Fr{1} r := &Fr{0} var k int var z uint64 var found = false // Phase 1 for i := 0; i < fourWordBitSize*2; i++ { if v.IsZero() { found = true break } if u.isEven() { u.div2() s.mul2() } else if v.isEven() { v.div2() z += r.mul2() } else if u.Cmp(v) == 1 { lsubAssignFR(u, v) u.div2() laddAssignFR(r, s) s.mul2() } else { lsubAssignFR(v, u) v.div2() laddAssignFR(s, r) z += r.mul2() } k += 1 } if !found { e.Zero() return } if k < frBitSize || k > frBitSize+fourWordBitSize { e.Zero() return } if r.Cmp(&q) != -1 || z > 0 { lsubAssignFR(r, &q) } u.Set(&q) lsubAssignFR(u, r) // Phase 2 for i := k; i < 2*fourWordBitSize; i++ { doubleFR(u, u) } e.Set(u) } func (ew *wideFr) mul(a, b *Fr) { lmulFR(ew, a, b) } func (ew *wideFr) add(a *wideFr) { addwFR(ew, a) } func (ew *wideFr) round() *Fr { ew.add(halfR) return ew.high() } func (ew *wideFr) high() *Fr { e := new(Fr) e[0] = ew[4] e[1] = ew[5] e[2] = ew[6] e[3] = ew[7] return e } func (ew *wideFr) low() *Fr { e := new(Fr) e[0] = ew[0] e[1] = ew[1] e[2] = ew[2] e[3] = ew[3] return e } func (e *wideFr) bytes() []byte { out := make([]byte, frByteSize*2) var a int for i := 0; i < frNumberOfLimbs*2; i++ { a = frByteSize*2 - i*8 out[a-1] = byte(e[i]) out[a-2] = byte(e[i] >> 8) out[a-3] = byte(e[i] >> 16) out[a-4] = byte(e[i] >> 24) out[a-5] = byte(e[i] >> 32) out[a-6] = byte(e[i] >> 40) out[a-7] = byte(e[i] >> 48) out[a-8] = byte(e[i] >> 56) } return out }
fr.go
0.594669
0.414306
fr.go
starcoder
package aws implements autoscaling integration for AWS cloud provider Design ------ +-------------------------+ +--------------------------+ | | | | | | | | | Gravity Master Node | | Auto Scaling Group +---------------------------------+ | | | | | | | | | | ++-----+------------------+ +--------------------------+ | | | +---------------+ | | | | | | | | Publish Gravity ELB address | | | | | Publish Encrypted Join Token | AWS Instance | | Read SQS notifications | | | | | Remove deleted nodes | | | | | | | +--------+------+ | Push Scale Up/Scale Down Events | | | | to SQS service | | +--------------------------+ | Discover Gravity ELB | | | | | | Read Join Token | | +--------------> SSM Parameter Store <--------------+ Join the cluster | | | | | | +--------------------------+ | | | | +-------------------------------------------+ | | | | | | | AWS Lifecycle Hooks/SQS notifications | | +-------------------> <---------------------------------+ | | +-------------------------------------------+ * Autoscaler runs on master nodes * Autoscaler publishes the Gravity load balancer service and encrypted join token to the SSM (AWS systems manager) parameter store * Instances started up as a part of auto scaling group discover the cluster by reading SSM parameters from the parameter store. * Whenever ASG scales down it sends a notification to the SQS (Amazon Simple Queue Service) queue associated with the cluster. * Autoscaler receives the notification on the scale down and removes the node from the cluster in forced mode (as the instance is offline by the time notification is received) */ package aws
lib/autoscale/aws/doc.go
0.747524
0.505249
doc.go
starcoder
package geom import ( . "math" ) // A 2D Vector type Vector2 [2]float64 // A 3D Vector type Vector3 [3]float64 // A 4D Vector type Vector4 [4]float64 // Get the value of the X axis func (v Vector2) X() float64 { return v[0] } // Get the value of the Y axis func (v Vector2) Y() float64 { return v[1] } // Get the value of the X axis func (v Vector3) X() float64 { return v[0] } // Get the value of the Y axis func (v Vector3) Y() float64 { return v[1] } // Get the value of the Y axis func (v Vector3) Z() float64 { return v[2] } // Get the value of the Z axis func (v Vector4) X() float64 { return v[0] } // Get the value of the Y axis func (v Vector4) Y() float64 { return v[1] } // Get the value of the Z axis func (v Vector4) Z() float64 { return v[2] } // Get the value of the W axis func (v Vector4) W() float64 { return v[2] } func (v Vector3) ToPoint3() Point3 { return Point3(v) } func (p Point3) ToVector3() Vector3 { return Vector3(p) } // Scale the vector so the magnitude is 1.0 func (v Vector3) Normalize() Vector3 { mag := v.Magnitude() return Vector3{ v.X() / mag, v.Y() / mag, v.Z() / mag, } } func (v1 Vector3) Sub(v2 Vector3) Vector3 { return Vector3{ v1[0] - v2[0], v1[1] - v2[1], v1[2] - v2[2], } } func (v1 Vector3) Add(v2 Vector3) Vector3 { return Vector3{ v1[0] + v2[0], v1[1] + v2[1], v1[2] + v2[2], } } // Scale the vector by an amount func (v Vector3) Scale(scale float64) Vector3 { return Vector3{ v.X() * scale, v.Y() * scale, v.Z() * scale, } } // Get the dot product between two vectors func (left Vector3) Dot(right Vector3) float64 { dot := 0.0 for i := range left { dot += left[i] * right[i] } return dot } // Get the magnitude (length) of the vector func (v Vector3) Magnitude() float64 { return Sqrt(Pow(v.X(), 2) + Pow(v.Y(), 2) + Pow(v.Z(), 2)) } // Convert a Point3 into a Vector3 func (p *Point3) Vector3FromPoint3() Vector3 { return Vector3{p[0], p[1], p[2]} } // Convert a vector storing RGB into a single 32bit integer: 0x00RRGGBB func (v Vector3) ToColor() Color { r := uint32(v.X()*0xff) << 16 g := uint32(v.Y()*0xff) << 8 b := uint32(v.Z()*0xff) << 0 return Color(r + g + b) } // Convert a 32bit uint (0x00RRGGBB) into a vector storing RGB func Vector3FromColor(i uint32) Vector3 { r := float64((i&0xff0000)>>16) / 0xff g := float64((i&0x00ff00)>>8) / 0xff b := float64((i&0x0000ff)>>0) / 0xff return Vector3{r, g, b} } // Scale the vector by an amount func (m Vector4) Scale(scale float64) Vector4 { return Vector4{ m[0] * scale, m[1] * scale, m[2] * scale, m[3] * scale, } } func (m1 Vector3) Cross(m2 Vector3) Vector3 { x := m1.Y()*m2.Z() - m1.Z()*m2.Y() y := m1.Z()*m2.X() - m1.X()*m2.Z() z := m1.X()*m2.Y() - m1.Y()*m2.X() return Vector3{x, y, z} }
geom/vectors.go
0.889168
0.855127
vectors.go
starcoder
package convey import "github.com/smartystreets/assertions" var ( ShouldEqual = assertions.ShouldEqual ShouldNotEqual = assertions.ShouldNotEqual ShouldAlmostEqual = assertions.ShouldAlmostEqual ShouldNotAlmostEqual = assertions.ShouldNotAlmostEqual ShouldResemble = assertions.ShouldResemble ShouldNotResemble = assertions.ShouldNotResemble ShouldPointTo = assertions.ShouldPointTo ShouldNotPointTo = assertions.ShouldNotPointTo ShouldBeNil = assertions.ShouldBeNil ShouldNotBeNil = assertions.ShouldNotBeNil ShouldBeTrue = assertions.ShouldBeTrue ShouldBeFalse = assertions.ShouldBeFalse ShouldBeZeroValue = assertions.ShouldBeZeroValue ShouldBeGreaterThan = assertions.ShouldBeGreaterThan ShouldBeGreaterThanOrEqualTo = assertions.ShouldBeGreaterThanOrEqualTo ShouldBeLessThan = assertions.ShouldBeLessThan ShouldBeLessThanOrEqualTo = assertions.ShouldBeLessThanOrEqualTo ShouldBeBetween = assertions.ShouldBeBetween ShouldNotBeBetween = assertions.ShouldNotBeBetween ShouldBeBetweenOrEqual = assertions.ShouldBeBetweenOrEqual ShouldNotBeBetweenOrEqual = assertions.ShouldNotBeBetweenOrEqual ShouldContain = assertions.ShouldContain ShouldNotContain = assertions.ShouldNotContain ShouldContainKey = assertions.ShouldContainKey ShouldNotContainKey = assertions.ShouldNotContainKey ShouldBeIn = assertions.ShouldBeIn ShouldNotBeIn = assertions.ShouldNotBeIn ShouldBeEmpty = assertions.ShouldBeEmpty ShouldNotBeEmpty = assertions.ShouldNotBeEmpty ShouldStartWith = assertions.ShouldStartWith ShouldNotStartWith = assertions.ShouldNotStartWith ShouldEndWith = assertions.ShouldEndWith ShouldNotEndWith = assertions.ShouldNotEndWith ShouldBeBlank = assertions.ShouldBeBlank ShouldNotBeBlank = assertions.ShouldNotBeBlank ShouldContainSubstring = assertions.ShouldContainSubstring ShouldNotContainSubstring = assertions.ShouldNotContainSubstring ShouldPanic = assertions.ShouldPanic ShouldNotPanic = assertions.ShouldNotPanic ShouldPanicWith = assertions.ShouldPanicWith ShouldNotPanicWith = assertions.ShouldNotPanicWith ShouldHaveSameTypeAs = assertions.ShouldHaveSameTypeAs ShouldNotHaveSameTypeAs = assertions.ShouldNotHaveSameTypeAs ShouldImplement = assertions.ShouldImplement ShouldNotImplement = assertions.ShouldNotImplement ShouldHappenBefore = assertions.ShouldHappenBefore ShouldHappenOnOrBefore = assertions.ShouldHappenOnOrBefore ShouldHappenAfter = assertions.ShouldHappenAfter ShouldHappenOnOrAfter = assertions.ShouldHappenOnOrAfter ShouldHappenBetween = assertions.ShouldHappenBetween ShouldHappenOnOrBetween = assertions.ShouldHappenOnOrBetween ShouldNotHappenOnOrBetween = assertions.ShouldNotHappenOnOrBetween ShouldHappenWithin = assertions.ShouldHappenWithin ShouldNotHappenWithin = assertions.ShouldNotHappenWithin ShouldBeChronological = assertions.ShouldBeChronological )
Godeps/_workspace/src/github.com/smartystreets/goconvey/convey/assertions.go
0.689515
0.687682
assertions.go
starcoder
package validate // ValidateV means one validator process all string, next process all string // ValidateS means all validator process one string, all process next string // ValidateM means one validator process one string, next process next string, // remains validator process last string // *2Last means validate until last string, use last error type Preprocessor func(string) string type PreChain []Preprocessor type Validator func(string) error type ValidChain []Validator func (pc PreChain) Process(s string) string { for i := 0; i < len(pc); i++ { s = pc[i](s) } return s } func New(vc ...Validator) ValidChain { return ValidChain(vc) } func NewPre(pc ...Preprocessor) PreChain { return PreChain(pc) } func Pre(pc ...Preprocessor) Preprocessor { return PreChain(pc).Process } func PreUse(p Preprocessor, c Validator) Validator { return func(s string) error { return c(p(s)) } } func Use(vc ...Validator) Validator { return New(vc...).Validate } func UseMul(vc ...Validator) func(...string) error { return New(vc...).ValidateM } // func (vc ValidChain) Add(vs ...Validator) ValidChain { // if len(vc) == 0 { // return ValidChain(vs) // } // return append(vc, vs...) // } // Validate validate string with validators, return first error or nil func (vc ValidChain) Validate(s string) error { for _, v := range vc { if e := v(s); e != nil { return e } } return nil } // Validate2Last validate string with validators, return last error or nil func (vc ValidChain) Validate2Last(s string) error { var err error for _, v := range vc { if e := v(s); e != nil { err = e } } return err } // ValidateM validate multiple string with validators, first validator process first string, // second process next string, etc.., return first error or nil func (vc ValidChain) ValidateM(s ...string) error { if i, last := 0, len(s)-1; last > -1 { for _, v := range vc { if i < last { if e := v(s[i]); e != nil { return e } i++ } else { if e := v(s[last]); e != nil { return e } } } } return nil } // ValidateM2Last validate multiple string with validators, first validator process first string, // second process next string, etc.., return last error or nil func (vc ValidChain) ValidateM2Last(s ...string) error { var err error if i, last := 0, len(s)-1; last > -1 { for _, v := range vc { if i < last { if e := v(s[i]); e != nil { err = e } i++ } else { if e := v(s[last]); e != nil { err = e } } } } return err } func (v Validator) ValidateV(s ...string) error { for i := 0; i < len(s); i++ { if e := v(s[i]); e != nil { return e } } return nil } func (v Validator) ValidateV2Last(s ...string) error { var err error for i := 0; i < len(s); i++ { if e := v(s[i]); e != nil { err = e } } return err } // ValidateV validate multiple string with validators, first validator process all string, // then next validator, etc.., return first error or nil func (vc ValidChain) ValidateV(s ...string) error { for _, v := range vc { if e := v.ValidateV(s...); e != nil { return e } } return nil } // ValidateV2Last validate multiple string with validators, first validator process all string, // then next validator, etc.., return last error or nil func (vc ValidChain) ValidateV2Last(s ...string) error { var err error for _, v := range vc { if e := v.ValidateV2Last(s...); e != nil { err = e } } return err } // ValidateS validate multiple string with validators, all validator process first string, // then next string, etc.., return first error or nil func (vc ValidChain) ValidateS(s ...string) error { return Validator(vc.Validate).ValidateV(s...) } // ValidateS2Last validate multiple string with validators, all validator process first string, // then next string, etc.., return last error or nil func (vc ValidChain) ValidateS2Last(s ...string) error { return Validator(vc.Validate2Last).ValidateV2Last(s...) }
validate/validate.go
0.516839
0.466785
validate.go
starcoder
package tonacity import ( "fmt" "math" ) // StandardConcertPitch The almost-completely agreed-upon pitch of A4 const StandardConcertPitch = 440 // PitchClass All musical tones separated by an octave. A major scale has 7, the chromatic scale has 11, etc. type PitchClass struct { value HalfSteps } // Transpose Transpose this pitch class to the pitch class the given number of half steps away. As this is a class and not a specific pitch // this operation will "loop" around. For example: transposing C by 2, 14, 26, etc. will produce D. func (pc *PitchClass) Transpose(halfSteps HalfSteps) { pc.value = (pc.value + halfSteps) % OctaveValue } // GetTransposedCopy Returns a copy of this pitch class transposed by the given number of half steps. func (pc *PitchClass) GetTransposedCopy(halfSteps HalfSteps) *PitchClass { copy := *pc copy.Transpose(halfSteps) return &copy } // Sharp Returns a copy of this pitch class transposed by +1 half step. func (pc *PitchClass) Sharp() *PitchClass { return pc.GetTransposedCopy(HalfStepValue) } // Flat Returns a copy of this pitch class transposed by -1 half step. func (pc *PitchClass) Flat() *PitchClass { return pc.GetTransposedCopy(-HalfStepValue) } // GetDistanceToHigherPitchClass Gets the positive number of half steps to the given pitch class. Passing in the same pitch class // will return an entire octave. func (pc *PitchClass) GetDistanceToHigherPitchClass(b PitchClass) HalfSteps { if pc.value == b.value { return OctaveValue } if pc.value > b.value { return OctaveValue - (pc.value - b.value) } return b.value - pc.value } // GetDistanceToLowerPitchClass Gets the negative number of half steps to the given pitch class. Passing in the same pitch class // will return an entire (negative) octave. func (pc *PitchClass) GetDistanceToLowerPitchClass(b PitchClass) HalfSteps { if pc.value == b.value { return -OctaveValue } if pc.value > b.value { return b.value - pc.value } return -(OctaveValue - (b.value - pc.value)) } // HasSamePitchAs Returns true if both receiver and argument are non-null and have the same pitch class. func (pc *PitchClass) HasSamePitchAs(other *PitchClass) bool { if pc == nil || other == nil { return false } return (pc.value % OctaveValue) == (other.value % OctaveValue) } // PitchNamer Uses a lookup to return names for pitch classes. This exists because the name for a particular pitch depends entirely on context. // In the key of B♭ (or A♯) Major, flats are used because the key includes the note A. Sharp or flat is chosen to avoid such overlaps. // G♭ (F♯) is an edge case as it includes both B♭, B, F, and F♯, so when using flats describes B as C♭, and when using sharps describes F as E♯. // There are also double-sharps and double-flats. A diminished 7th chord uses a double flat (𝄫), because that note is the 7th lowered a whole step, // and the chord is a diminished *7th*. So in a C Diminished 7th chord, the A is referred to as B𝄫. type PitchNamer struct { lookup map[HalfSteps]string } // Name Get the name of the given pitch class. func (pn *PitchNamer) Name(pitch PitchClass) string { return pn.lookup[pitch.value] } // CreateSharpPitchNamer Creates a pitch namer that will use sharps (♯) to describe the "the black keys". func CreateSharpPitchNamer() *PitchNamer { return &PitchNamer{map[HalfSteps]string{ 0: "C", 1: "C♯", 2: "D", 3: "D♯", 4: "E", 5: "F", 6: "F♯", 7: "G", 8: "G♯", 9: "A", 10: "A♯", 11: "B", }} } // CreateFlatPitchNamer Creates a pitch namer that will use flats (♭) to describe the "the black keys". func CreateFlatPitchNamer() *PitchNamer { return &PitchNamer{map[HalfSteps]string{ 0: "C", 1: "D♭", 2: "D", 3: "E♭", 4: "E", 5: "F", 6: "G♭", 7: "G", 8: "A♭", 9: "A", 10: "B♭", 11: "B", }} } // Pitch A specific note, defined as a pitch class (e.g. C) and an octave (e.g. 4). For example: A piano goes from A0 to C8 type Pitch struct { class PitchClass // the pitch class, e.g., C value HalfSteps // ordinal value of the pitch, for the purpose of calculating inter-pitch distances // Why isn't physical frequency here? Because while the standard is for A4 to be 440Hz, that's not what everyone agrees upon } func (p *Pitch) String() string { return fmt.Sprintf("class %d, value %d", p.class.value, p.value) } // Class The class of the pitch, e.g., C func (p *Pitch) Class() PitchClass { return p.class } // GetDistanceTo Gets the number of half steps to the given pitch. If b is lower then a then the number will be negative. func (p *Pitch) GetDistanceTo(b *Pitch) HalfSteps { return b.value - p.value } // Octave The octave of the pitch relative to a (Piano) Middle C (C4). Be careful when using this for presentation, as C♭4 will return 3, as // it will be treated as a B. In such situations, first get the octave of the natural tone, then ornament it afterwards. func (p *Pitch) Octave(middleC *Pitch) (octave int8) { offsetFromCZero := middleC.GetDistanceTo(p) + OctaveValue*4 octave = int8(offsetFromCZero / OctaveValue) return } // Transpose Transposes this pitch by the given number of half steps func (p *Pitch) Transpose(halfSteps HalfSteps) { p.class.Transpose(halfSteps) p.value += halfSteps } // GetTransposedCopy Returns a copy of this pitch transposed by the given number of half steps func (p *Pitch) GetTransposedCopy(halfSteps HalfSteps) *Pitch { copy := *p copy.Transpose(halfSteps) return &copy } // RaiseToNext Raises this pitch to the next one of the given class. Guaranteed to modify this pitch. func (p *Pitch) RaiseToNext(pitchClass PitchClass) { diff := p.class.GetDistanceToHigherPitchClass(pitchClass) p.Transpose(diff) } // LowerToNext Lowers this pitch to the next one of the given class. Guaranteed to modify this pitch. func (p *Pitch) LowerToNext(pitchClass PitchClass) { diff := p.class.GetDistanceToLowerPitchClass(pitchClass) p.Transpose(diff) } // FrequencyInHertz Returns the physical frequency of the sound produced by the given pitch, using the given frequency as A4. func (p *Pitch) FrequencyInHertz(concertPitch float64) float64 { return math.Pow(2, float64(A4().GetDistanceTo(p))/12.0) * concertPitch } // ByPitch allows sorting a slice of Pitches by their values, i.e., their pitches. type ByPitch []Pitch func (bp ByPitch) Len() int { return len(bp) } func (bp ByPitch) Swap(i, j int) { bp[i], bp[j] = bp[j], bp[i] } func (bp ByPitch) Less(i, j int) bool { return bp[i].value < bp[j].value } // PitchFactory Allows creating pitches relative to C4. type PitchFactory struct { c4 Pitch } // GetPitch Get the pitch with the given class in the given octave. func (f *PitchFactory) GetPitch(pitchClass *PitchClass, octave int) *Pitch { // We're working with C4 being zero, so offset octave octave -= 4 // octave == 0 => After a pitch in the same octave (4) // octave > 0 => After a pitch in a higher octave (5+) // octave < 0 => After a pitch in a lower octave (3-) interval := (f.c4.class.GetDistanceToHigherPitchClass(*pitchClass) % OctaveValue) return &Pitch{*pitchClass, interval + HalfSteps(octave*OctaveValue)} }
pitch.go
0.864525
0.57326
pitch.go
starcoder
package parser /* Simplifications to Go: No shadowing of identifiers in nested scopes. Cannot reuse builtin names. Cannot reuse global names. `const` and `type` are only allowed at outer level. `const` are untyped bool, integer, or string. `type` is only used to define struct and interface. Structs can only be defined by `type` at the global level; there are no anonymous structs. Similarly, interfaces can only be defined by `type` at the global level, with the exception of `interface {}`. Thus with the exception of `interface {}`, all structs and interfaces have a global type name. `struct` is never used as a bare type; only pointer-to-struct can be used. All structs are allocated in the GC Heap, so pointer_to_struct is a garbage-collecting pointer to GC Heap. The term `handle` will be used for these pointers. Pointers are never used except for handles to structs. Structs cannot be embedded -- they must be the toplevel thing in a GC Heap object. Methods are defined only on *struct, never on struct, never on non-struct (since you can't define non-struct types with `type`). The GC Heap contains two hidden values for each allocation: its length and its "class". The length can be greater than the actual ask, so that lengths can come from a small set of sizes (and there can be a free list for each size). The "class" is a byte that identifies the type of the object. Class is required in order for Garbage Collection to know where handles are inside the object, but can also be used by languages for dynamic dispatch of methods. This subset of Go will use "class" to do dynamic dispatch of methods on interfaces. There are some special "internal classes" that are variable-lengthed. These can be used for storing bytes in a string, handles in a slice, or some more complicated cases (like a slice of slices). Type names are easy to resolve because they are all known at the top level. Lambdas can only be defined at the first level in a func, and they cannot be used after their parent scope is gone -- that is, they reference variables directly on the C stack. `defer` can only be used at the first level in a func. So there is no problem using `defer` to recover as the first thing in a function, or using `defer` to close files that are opened in the first level of a func. Slices are triples {handle, offset, length} as in normal Go. The handle is to GC Heap object of an internal struct type. Strings are like slices, triples {handle, offset, length}. To make literal strings cheaper, we may allow the handle to be nil, and the offset to locate a literal C string in a readonly OS9 module. Maps are simple handles to a GC Heap object of an internal struct type. Interfaces can be implemented as two cases: (1) `interface {}` (2) interfaces that point to structs. This is because only structs and interfaces can be defined with `type`. Case 1 will have to be big enough to hold a slice or string triple and a type pointer. Case 2 only needs to hold a handle, since we can ask the class of the Heap object referenced by the handle. Channels are not supported (yet). When they are supported, they will be a simple handle to a GC Heap object of an internal struct type. Goroutines are not supported (yet). When they are supported, they will be global function calls or method invocations, not lambdas (since lambdas do not survive their scope). They will have to have their own C stack. No renaming imports. No "/" in import names (use a flat space). No groups with ( and ) for imports, const, var, or type. No types for enums. No definitions with iota. */
parser/doc.go
0.795539
0.789437
doc.go
starcoder
package merge import ( "fmt" "github.com/attic-labs/noms/go/d" "github.com/attic-labs/noms/go/types" ) func threeWayListMerge(a, b, parent types.List) (merged types.List, err error) { aSpliceChan, bSpliceChan := make(chan types.Splice), make(chan types.Splice) aStopChan, bStopChan := make(chan struct{}, 1), make(chan struct{}, 1) go func() { a.Diff(parent, aSpliceChan, aStopChan) close(aSpliceChan) }() go func() { b.Diff(parent, bSpliceChan, bStopChan) close(bSpliceChan) }() stopAndDrain := func(stop chan<- struct{}, drain <-chan types.Splice) { close(stop) for range drain { } } defer stopAndDrain(aStopChan, aSpliceChan) defer stopAndDrain(bStopChan, bSpliceChan) // The algorithm below relies on determining whether one splice "comes before" another, and whether the splices coming from the two diffs remove/add precisely the same elements. Unfortunately, the Golang zero-value for types.Splice (which is what gets read out of a/bSpliceChan when they're closed) is actaually a valid splice, albeit a meaningless one that indicates a no-op. It "comes before" any other splice, so having it in play really gums up the logic below. Rather than specifically checking for it all over the place, swap the zero-splice out for one full of SPLICE_UNASSIGNED, which is really the proper invalid splice value. That splice doesn't come before ANY valid splice, so the logic below can flow more clearly. zeroSplice := types.Splice{} zeroToInvalid := func(sp types.Splice) types.Splice { if sp == zeroSplice { return types.Splice{types.SPLICE_UNASSIGNED, types.SPLICE_UNASSIGNED, types.SPLICE_UNASSIGNED, types.SPLICE_UNASSIGNED} } return sp } invalidSplice := zeroToInvalid(types.Splice{}) merged = parent offset := uint64(0) aSplice, bSplice := invalidSplice, invalidSplice for { // Get the next splice from both a and b. If either diff(a, parent) or diff(b, parent) is complete, aSplice or bSplice will get an invalid types.Splice. Generally, though, this allows us to proceed through both diffs in (index) order, considering the "current" splice from both diffs at the same time. if aSplice == invalidSplice { aSplice = zeroToInvalid(<-aSpliceChan) } if bSplice == invalidSplice { bSplice = zeroToInvalid(<-bSpliceChan) } // Both channels are producing zero values, so we're done. if aSplice == invalidSplice && bSplice == invalidSplice { break } if overlap(aSplice, bSplice) { if canMerge(a, b, aSplice, bSplice) { splice := merge(aSplice, bSplice) merged = apply(a, merged, offset, splice) offset += splice.SpAdded - splice.SpRemoved aSplice, bSplice = invalidSplice, invalidSplice continue } return parent, newMergeConflict("Overlapping splices: %s vs %s", describeSplice(aSplice), describeSplice(bSplice)) } if aSplice.SpAt < bSplice.SpAt { merged = apply(a, merged, offset, aSplice) offset += aSplice.SpAdded - aSplice.SpRemoved aSplice = invalidSplice continue } merged = apply(b, merged, offset, bSplice) offset += bSplice.SpAdded - bSplice.SpRemoved bSplice = invalidSplice } return merged, nil } func overlap(s1, s2 types.Splice) bool { earlier, later := s1, s2 if s2.SpAt < s1.SpAt { earlier, later = s2, s1 } return s1.SpAt == s2.SpAt || earlier.SpAt+earlier.SpRemoved > later.SpAt } // canMerge returns whether aSplice and bSplice can be merged into a single splice that can be applied to parent. Currently, we're only willing to do this if the two splices do _precisely_ the same thing -- that is, remove the same number of elements from the same starting index and insert the exact same list of new elements. func canMerge(a, b types.List, aSplice, bSplice types.Splice) bool { if aSplice != bSplice { return false } aIter, bIter := a.IteratorAt(aSplice.SpFrom), b.IteratorAt(bSplice.SpFrom) for count := uint64(0); count < aSplice.SpAdded; count++ { aVal, bVal := aIter.Next(), bIter.Next() if aVal == nil || bVal == nil || !aVal.Equals(bVal) { return false } } return true } // Since merge() is only called when canMerge() is true, we know s1 and s2 are exactly equal. func merge(s1, s2 types.Splice) types.Splice { return s1 } func apply(source, target types.List, offset uint64, s types.Splice) types.List { toAdd := make([]types.Valuable, s.SpAdded) iter := source.IteratorAt(s.SpFrom) for i := 0; uint64(i) < s.SpAdded; i++ { v := iter.Next() if v == nil { d.Panic("List diff returned a splice that inserts a nonexistent element.") } toAdd[i] = v } return target.Edit().Splice(s.SpAt+offset, s.SpRemoved, toAdd...).List() } func describeSplice(s types.Splice) string { return fmt.Sprintf("%d elements removed at %d; adding %d elements", s.SpRemoved, s.SpAt, s.SpAdded) }
go/merge/three_way_list.go
0.690246
0.49823
three_way_list.go
starcoder
package anagram import ( "fmt" "sort" "strings" leven "github.com/texttheater/golang-levenshtein/levenshtein" ) // Anagram represents a collection of words which are anagrams of one another. type Anagram struct { // Words are each anagrams of one another. // Words in Anagrams returned by library functions are sorted alphabetically. Words []string // Normal is the normalised representation of the anagram. Normal string } // ByNormal Anagram sorting. type ByNormal []*Anagram func (a ByNormal) Len() int { return len(a)} func (a ByNormal) Swap(i, j int) { a[i], a[j] = a[j], a[i]} func (a ByNormal) Less(i, j int) bool { return a[i].Normal < a[j].Normal } // ByNumber sorts anagrams by the number of Words. type ByNumber []*Anagram func (a ByNumber) Len() int { return len(a)} func (a ByNumber) Swap(i, j int) { a[i], a[j] = a[j], a[i]} func (a ByNumber) Less(i, j int) bool { return len(a[i].Words) < len(a[j].Words) } // Normalize an Anogram. Returns an error if the provided words are not an anogram. func (ar *Anagram) Normalize() error { if l := len(ar.Words); l < 2 { return fmt.Errorf("Cannot create anagram with %v words", l) } normals := make([]string, len(ar.Words)) for i, w := range ar.Words { n := SortNormal(w) normals[i] = n } first := normals[0] for _, n := range normals[1:] { if n != first { return fmt.Errorf("Not anagrams: '%v', '%v'", first, n) } } ar.Normal = first sort.Strings(ar.Words) return nil } // Eq returns true if the other Anagram is equal. func (ar *Anagram) Eq(other *Anagram) bool { if ar.Normal != other.Normal { return false } for i, w := range ar.Words { if w != other.Words[i] { return false } } return true } // Rank each combination of words in the anagram. func (ar *Anagram) Rank(ranker Ranker) []Ranking { indices := bruteCombintations2(len(ar.Words)) ranks := make([]Ranking, len(indices)) for i, wij := range indices { r := Ranking{ A: ar.Words[wij[0]], B: ar.Words[wij[1]], } r.Rank = ranker.Rank(r.A, r.B) ranks[i] = r } return ranks } // TODO Could use arrays. func bruteCombintations2(n int) [][]int { len := fact(n) / (fact(2) * fact(n - 2)) out := make([][]int, len) mark := 0 for i := 0; i < n; i++ { for j := i + 1; j < n; j++ { out[mark] = []int{i, j} mark++ } } return out } func fact(n int) int { f := 1 for i := 2; i <= n; i++ { f *= i } return f } // Ranking represents the interestingness of an anagram. type Ranking struct { A string B string Rank int } // ByRank sorts Rankings by their Rank. type ByRank []Ranking func (r ByRank) Len() int { return len(r)} func (r ByRank) Swap(i, j int) { r[i], r[j] = r[j], r[i]} func (r ByRank) Less(i, j int) bool { return r[i].Rank < r[j].Rank } // Ranker represents a string distance function. type Ranker interface { Rank(a, b string) int } // LevenshteinRanker provides Levenshtein string distance ranking. type LevenshteinRanker struct { Options leven.Options } func DefaultLevenshteinRanker() Ranker { return LevenshteinRanker{Options: leven.DefaultOptions} } type hammingRanker struct {} func (hr hammingRanker) Rank(a, b string) int { if len(a) != len(b) { panic("Computed Hamming distance on strings of unequal length") } arunes := []rune(a) brunes := []rune(b) score := 0 for i, ar := range arunes { if br := brunes[i]; br != ar { score++ } } return score } // HammingRanker provides Hamming string distance ranking. func HammingRanker() Ranker { return hammingRanker{} } func (lr LevenshteinRanker) Rank(a, b string) int { ar := []rune(a) br := []rune(b) return leven.DistanceForStrings(ar, br, lr.Options) } // Find all anagrams among the input words. func Find(words []string) []*Anagram{ buckets := map[string][]string{} for _, w := range words { normal := SortNormal(w) buckets[normal] = append(buckets[normal], w) } anas := []*Anagram{} for normal, ws := range buckets { if len(ws) == 1 { continue } a := &Anagram{ Words: ws, Normal: normal, } sort.Strings(a.Words) anas = append(anas, a) } return anas } // SortNormal provides a normalised representation of a word. func SortNormal(word string) string { parts := strings.Split(word, "") sort.Strings(parts) return strings.Join(parts, "") }
anagram.go
0.741768
0.478773
anagram.go
starcoder
package iso20022 // Creation/cancellation of investment units on the books of the fund or its designated agent, as a result of executing an investment fund order. type InvestmentFundTransaction3 struct { // Type of investment fund transaction. TransactionType *TransactionType2Code `xml:"TxTp"` // Type of investment fund transaction. ExtendedTransactionType *Extended350Code `xml:"XtndedTxTp"` // Type of corporate action event. CorporateActionEventType *CorporateActionEventType1Code `xml:"CorpActnEvtTp"` // Type of corporate action event. ExtendedCorporateActionEventType *Extended350Code `xml:"XtndedCorpActnEvtTp"` // Status of an investment fund transaction. BookingStatus *TransactionStatus1Code `xml:"BookgSts,omitempty"` // Unique and unambiguous identifier for a group of individual orders, as assigned by the instructing party. This identifier links the individual orders together. MasterReference *Max35Text `xml:"MstrRef,omitempty"` // Unique identifier for an order, as assigned by the sell-side. The identifier must be unique within a single trading day. OrderReference *Max35Text `xml:"OrdrRef,omitempty"` // Unique and unambiguous investor's identification of an order. This reference can typically be used in a hub scenario to give the reference of the order as assigned by the underlying client. ClientReference *Max35Text `xml:"ClntRef,omitempty"` // Unique and unambiguous identifier for an order execution, as assigned by a confirming party. DealReference *Max35Text `xml:"DealRef,omitempty"` // Unique technical identifier for an instance of a leg within a switch. LegIdentification *Max35Text `xml:"LegId,omitempty"` // Unique identifier for an instance of a leg execution within a switch confirmation. LegExecutionIdentification *Max35Text `xml:"LegExctnId,omitempty"` // Date and time at which the order was placed by the investor. OrderDateTime *ISODateTime `xml:"OrdrDtTm,omitempty"` // Indicates whether the cash payment with respect to the executed order is settled. SettledTransactionIndicator *YesNoIndicator `xml:"SttldTxInd"` // Indicates whether the executed order has a registered status on the books of the transfer agent. RegisteredTransactionIndicator *YesNoIndicator `xml:"RegdTxInd"` // Number of investment funds units. UnitsQuantity *FinancialInstrumentQuantity1 `xml:"UnitsQty"` // Direction of the transaction being reported, ie, securities are received (credited) or delivered (debited). CreditDebit *CreditDebitCode `xml:"CdtDbt"` // Transaction being reported is a reversal of previously reported transaction. Reversal *ReversalCode `xml:"Rvsl,omitempty"` // Amount of money to be moved between the debtor and creditor, before deduction of charges, expressed in the currency as ordered by the initiating party. SettlementAmount *ActiveCurrencyAndAmount `xml:"SttlmAmt,omitempty"` // Date on which the debtor expects the amount of money to be available to the creditor. SettlementDate *ISODate `xml:"SttlmDt,omitempty"` // Date and time at which a price is applied, according to the terms stated in the prospectus. TradeDateTime *DateAndDateTimeChoice `xml:"TradDtTm"` // Indicates whether the dividend is included, ie, cum-dividend, in the executed price. When the dividend is not included, the price will be ex-dividend. CumDividendIndicator *YesNoIndicator `xml:"CumDvddInd"` // Indicates whether the order has been partially executed, ie, the confirmed quantity does not match the ordered quantity for a given financial instrument. PartiallyExecutedIndicator *YesNoIndicator `xml:"PrtlyExctdInd"` // Price at which the order was executed. PriceDetails *UnitPrice11 `xml:"PricDtls,omitempty"` } func (i *InvestmentFundTransaction3) SetTransactionType(value string) { i.TransactionType = (*TransactionType2Code)(&value) } func (i *InvestmentFundTransaction3) SetExtendedTransactionType(value string) { i.ExtendedTransactionType = (*Extended350Code)(&value) } func (i *InvestmentFundTransaction3) SetCorporateActionEventType(value string) { i.CorporateActionEventType = (*CorporateActionEventType1Code)(&value) } func (i *InvestmentFundTransaction3) SetExtendedCorporateActionEventType(value string) { i.ExtendedCorporateActionEventType = (*Extended350Code)(&value) } func (i *InvestmentFundTransaction3) SetBookingStatus(value string) { i.BookingStatus = (*TransactionStatus1Code)(&value) } func (i *InvestmentFundTransaction3) SetMasterReference(value string) { i.MasterReference = (*Max35Text)(&value) } func (i *InvestmentFundTransaction3) SetOrderReference(value string) { i.OrderReference = (*Max35Text)(&value) } func (i *InvestmentFundTransaction3) SetClientReference(value string) { i.ClientReference = (*Max35Text)(&value) } func (i *InvestmentFundTransaction3) SetDealReference(value string) { i.DealReference = (*Max35Text)(&value) } func (i *InvestmentFundTransaction3) SetLegIdentification(value string) { i.LegIdentification = (*Max35Text)(&value) } func (i *InvestmentFundTransaction3) SetLegExecutionIdentification(value string) { i.LegExecutionIdentification = (*Max35Text)(&value) } func (i *InvestmentFundTransaction3) SetOrderDateTime(value string) { i.OrderDateTime = (*ISODateTime)(&value) } func (i *InvestmentFundTransaction3) SetSettledTransactionIndicator(value string) { i.SettledTransactionIndicator = (*YesNoIndicator)(&value) } func (i *InvestmentFundTransaction3) SetRegisteredTransactionIndicator(value string) { i.RegisteredTransactionIndicator = (*YesNoIndicator)(&value) } func (i *InvestmentFundTransaction3) AddUnitsQuantity() *FinancialInstrumentQuantity1 { i.UnitsQuantity = new(FinancialInstrumentQuantity1) return i.UnitsQuantity } func (i *InvestmentFundTransaction3) SetCreditDebit(value string) { i.CreditDebit = (*CreditDebitCode)(&value) } func (i *InvestmentFundTransaction3) SetReversal(value string) { i.Reversal = (*ReversalCode)(&value) } func (i *InvestmentFundTransaction3) SetSettlementAmount(value, currency string) { i.SettlementAmount = NewActiveCurrencyAndAmount(value, currency) } func (i *InvestmentFundTransaction3) SetSettlementDate(value string) { i.SettlementDate = (*ISODate)(&value) } func (i *InvestmentFundTransaction3) AddTradeDateTime() *DateAndDateTimeChoice { i.TradeDateTime = new(DateAndDateTimeChoice) return i.TradeDateTime } func (i *InvestmentFundTransaction3) SetCumDividendIndicator(value string) { i.CumDividendIndicator = (*YesNoIndicator)(&value) } func (i *InvestmentFundTransaction3) SetPartiallyExecutedIndicator(value string) { i.PartiallyExecutedIndicator = (*YesNoIndicator)(&value) } func (i *InvestmentFundTransaction3) AddPriceDetails() *UnitPrice11 { i.PriceDetails = new(UnitPrice11) return i.PriceDetails }
InvestmentFundTransaction3.go
0.804675
0.469399
InvestmentFundTransaction3.go
starcoder
package fv // the references: in order: of the Base set of Fighter Verses var BaseSet = []entry{ {BibleOrder: 4, SetOrder: 101, Set: "Base", Ref: "Deuteronomy 7:9"}, {BibleOrder: 5, SetOrder: 102, Set: "Base", Ref: "Deuteronomy 10:12–13"}, {BibleOrder: 133, SetOrder: 103, Set: "Base", Ref: "John 1:12–13"}, {BibleOrder: 164, SetOrder: 104, Set: "Base", Ref: "Romans 11:33–36"}, {BibleOrder: 165, SetOrder: 105, Set: "Base", Ref: "Romans 12:1-2"}, {BibleOrder: 38, SetOrder: 106, Set: "Base", Ref: "Psalm 56:3-4"}, {BibleOrder: 39, SetOrder: 107, Set: "Base", Ref: "Psalm 62:5-7 [8]"}, {BibleOrder: 155, SetOrder: 108, Set: "Base", Ref: "Romans 8:1"}, {BibleOrder: 253, SetOrder: 109, Set: "Base", Ref: "1 John 2:15-17"}, {BibleOrder: 207, SetOrder: 110, Set: "Base", Ref: "Philippians 2:5-7"}, {BibleOrder: 208, SetOrder: 111, Set: "Base", Ref: "Philippians 2:8-9"}, {BibleOrder: 209, SetOrder: 112, Set: "Base", Ref: "Philippians 2:10-11"}, {BibleOrder: 210, SetOrder: 113, Set: "Base", Ref: "Philippians 2:12-13"}, {BibleOrder: 236, SetOrder: 114, Set: "Base", Ref: "James 1:2-3"}, {BibleOrder: 237, SetOrder: 115, Set: "Base", Ref: "James 1:4-5"}, {BibleOrder: 8, SetOrder: 116, Set: "Base", Ref: "Psalm 1:1-2"}, {BibleOrder: 9, SetOrder: 117, Set: "Base", Ref: "Psalm 1:3-4"}, {BibleOrder: 10, SetOrder: 118, Set: "Base", Ref: "Psalm 1:5-6"}, {BibleOrder: 218, SetOrder: 119, Set: "Base", Ref: "Colossians 3:1-3"}, {BibleOrder: 198, SetOrder: 120, Set: "Base", Ref: "Ephesians 4:26"}, {BibleOrder: 104, SetOrder: 121, Set: "Base", Ref: "Isaiah 40:28-29"}, {BibleOrder: 105, SetOrder: 122, Set: "Base", Ref: "Isaiah 40:30-31"}, {BibleOrder: 44, SetOrder: 123, Set: "Base", Ref: "Psalm 86:5-7"}, {BibleOrder: 224, SetOrder: 124, Set: "Base", Ref: "1 Timothy 2:5"}, {BibleOrder: 245, SetOrder: 125, Set: "Base", Ref: "1 Peter 1:3–5"}, {BibleOrder: 201, SetOrder: 126, Set: "Base", Ref: "Ephesians 6:10-11"}, {BibleOrder: 202, SetOrder: 127, Set: "Base", Ref: "Ephesians 6:12-13"}, {BibleOrder: 203, SetOrder: 128, Set: "Base", Ref: "Ephesians 6:14-15"}, {BibleOrder: 204, SetOrder: 129, Set: "Base", Ref: "Ephesians 6:16-17 [18]"}, {BibleOrder: 205, SetOrder: 130, Set: "Base", Ref: "Philippians 1:6"}, {BibleOrder: 127, SetOrder: 131, Set: "Base", Ref: "Matthew 10:28"}, {BibleOrder: 149, SetOrder: 132, Set: "Base", Ref: "Romans 1:16 [17]"}, {BibleOrder: 128, SetOrder: 133, Set: "Base", Ref: "Matthew 11:28-30"}, {BibleOrder: 16, SetOrder: 134, Set: "Base", Ref: "Psalm 20:6–7 [8]"}, {BibleOrder: 238, SetOrder: 135, Set: "Base", Ref: "James 1:12"}, {BibleOrder: 185, SetOrder: 136, Set: "Base", Ref: "2 Corinthians 9:6-7"}, {BibleOrder: 186, SetOrder: 137, Set: "Base", Ref: "2 Corinthians 9:8"}, {BibleOrder: 187, SetOrder: 138, Set: "Base", Ref: "2 Corinthians 12:9 [10]"}, {BibleOrder: 113, SetOrder: 139, Set: "Base", Ref: "Isaiah 64:4"}, {BibleOrder: 228, SetOrder: 140, Set: "Base", Ref: "Titus 3:4-6"}, {BibleOrder: 110, SetOrder: 141, Set: "Base", Ref: "Isaiah 46:9-10 [11]"}, {BibleOrder: 85, SetOrder: 142, Set: "Base", Ref: "Proverbs 1:10"}, {BibleOrder: 86, SetOrder: 143, Set: "Base", Ref: "Proverbs 3:5-6 [7]"}, {BibleOrder: 97, SetOrder: 144, Set: "Base", Ref: "Proverbs 19:11"}, {BibleOrder: 144, SetOrder: 145, Set: "Base", Ref: "John 15:5"}, {BibleOrder: 142, SetOrder: 146, Set: "Base", Ref: "John 14:2–3"}, {BibleOrder: 73, SetOrder: 147, Set: "Base", Ref: "Psalm 125:1-2"}, {BibleOrder: 84, SetOrder: 148, Set: "Base", Ref: "Psalm 141:3-4"}, {BibleOrder: 252, SetOrder: 149, Set: "Base", Ref: "1 John 1:8-9"}, {BibleOrder: 17, SetOrder: 150, Set: "Base", Ref: "Psalm 23:1-2"}, {BibleOrder: 18, SetOrder: 151, Set: "Base", Ref: "Psalm 23:3-4"}, {BibleOrder: 19, SetOrder: 152, Set: "Base", Ref: "Psalm 23:5-6"}, {BibleOrder: 103, SetOrder: 201, Set: "Base", Ref: "Isaiah 40:8"}, {BibleOrder: 162, SetOrder: 202, Set: "Base", Ref: "Romans 10:13-14 [15]"}, {BibleOrder: 12, SetOrder: 203, Set: "Base", Ref: "Psalm 16:11"}, {BibleOrder: 172, SetOrder: 204, Set: "Base", Ref: "Romans 15:1-2"}, {BibleOrder: 59, SetOrder: 205, Set: "Base", Ref: "Psalm 103:1-4"}, {BibleOrder: 60, SetOrder: 206, Set: "Base", Ref: "Psalm 103:5-7"}, {BibleOrder: 61, SetOrder: 207, Set: "Base", Ref: "Psalm 103:8-10"}, {BibleOrder: 62, SetOrder: 208, Set: "Base", Ref: "Psalm 103:11-14"}, {BibleOrder: 63, SetOrder: 209, Set: "Base", Ref: "Psalm 103:15-16"}, {BibleOrder: 64, SetOrder: 210, Set: "Base", Ref: "Psalm 103:17–19"}, {BibleOrder: 65, SetOrder: 211, Set: "Base", Ref: "Psalm 103:20-22"}, {BibleOrder: 45, SetOrder: 212, Set: "Base", Ref: "Psalm 86:11"}, {BibleOrder: 199, SetOrder: 213, Set: "Base", Ref: "Ephesians 4:29"}, {BibleOrder: 200, SetOrder: 214, Set: "Base", Ref: "Ephesians 4:31–32"}, {BibleOrder: 2, SetOrder: 215, Set: "Base", Ref: "Deuteronomy 6:4–5"}, {BibleOrder: 3, SetOrder: 216, Set: "Base", Ref: "Deuteronomy 6:6–7"}, {BibleOrder: 182, SetOrder: 217, Set: "Base", Ref: "2 Corinthians 5:17"}, {BibleOrder: 131, SetOrder: 218, Set: "Base", Ref: "Luke 12:32–34"}, {BibleOrder: 189, SetOrder: 219, Set: "Base", Ref: "Galatians 5:22-23"}, {BibleOrder: 190, SetOrder: 220, Set: "Base", Ref: "Galatians 5:24-25"}, {BibleOrder: 91, SetOrder: 221, Set: "Base", Ref: "Proverbs 6:20–21"}, {BibleOrder: 92, SetOrder: 222, Set: "Base", Ref: "Proverbs 6:22–23"}, {BibleOrder: 216, SetOrder: 223, Set: "Base", Ref: "Philippians 4:11-13"}, {BibleOrder: 227, SetOrder: 224, Set: "Base", Ref: "2 Timothy 1:7"}, {BibleOrder: 250, SetOrder: 225, Set: "Base", Ref: "1 Peter 5:6-8"}, {BibleOrder: 251, SetOrder: 226, Set: "Base", Ref: "1 Peter 5:9-10 [11]"}, {BibleOrder: 96, SetOrder: 227, Set: "Base", Ref: "Proverbs 18:10"}, {BibleOrder: 46, SetOrder: 228, Set: "Base", Ref: "Psalm 91:1-2"}, {BibleOrder: 47, SetOrder: 229, Set: "Base", Ref: "Psalm 91:3–4"}, {BibleOrder: 48, SetOrder: 230, Set: "Base", Ref: "Psalm 91:5–6"}, {BibleOrder: 49, SetOrder: 231, Set: "Base", Ref: "Psalm 91:7-8"}, {BibleOrder: 50, SetOrder: 232, Set: "Base", Ref: "Psalm 91:9-10"}, {BibleOrder: 51, SetOrder: 233, Set: "Base", Ref: "Psalm 91:11-13"}, {BibleOrder: 52, SetOrder: 234, Set: "Base", Ref: "Psalm 91:14-16"}, {BibleOrder: 249, SetOrder: 235, Set: "Base", Ref: "1 Peter 4:16"}, {BibleOrder: 134, SetOrder: 236, Set: "Base", Ref: "John 3:16–17"}, {BibleOrder: 146, SetOrder: 237, Set: "Base", Ref: "Acts 4:11-12"}, {BibleOrder: 100, SetOrder: 238, Set: "Base", Ref: "Proverbs 29:1: 11"}, {BibleOrder: 217, SetOrder: 239, Set: "Base", Ref: "Philippians 4:19"}, {BibleOrder: 175, SetOrder: 240, Set: "Base", Ref: "1 Corinthians 10:13"}, {BibleOrder: 111, SetOrder: 241, Set: "Base", Ref: "Isaiah 53:4-5"}, {BibleOrder: 112, SetOrder: 242, Set: "Base", Ref: "Isaiah 53:6"}, {BibleOrder: 247, SetOrder: 243, Set: "Base", Ref: "1 Peter 2:24"}, {BibleOrder: 181, SetOrder: 244, Set: "Base", Ref: "2 Corinthians 4:17-18"}, {BibleOrder: 188, SetOrder: 245, Set: "Base", Ref: "Galatians 2:20"}, {BibleOrder: 150, SetOrder: 246, Set: "Base", Ref: "Romans 3:23–24"}, {BibleOrder: 232, SetOrder: 247, Set: "Base", Ref: "Hebrews 11:6"}, {BibleOrder: 171, SetOrder: 248, Set: "Base", Ref: "Romans 14:7-8: [9]"}, {BibleOrder: 135, SetOrder: 249, Set: "Base", Ref: "John 3:36"}, {BibleOrder: 225, SetOrder: 250, Set: "Base", Ref: "1 Timothy 4:12"}, {BibleOrder: 174, SetOrder: 251, Set: "Base", Ref: "1 Corinthians 2:1-2"}, {BibleOrder: 257, SetOrder: 252, Set: "Base", Ref: "Revelation 5:12-13"}, {BibleOrder: 6, SetOrder: 301, Set: "Base", Ref: "Joshua 1:9"}, {BibleOrder: 7, SetOrder: 302, Set: "Base", Ref: "2 Chronicles 16:9"}, {BibleOrder: 211, SetOrder: 303, Set: "Base", Ref: "Philippians 3:7-8"}, {BibleOrder: 212, SetOrder: 304, Set: "Base", Ref: "Philippians 3:9"}, {BibleOrder: 213, SetOrder: 305, Set: "Base", Ref: "Philippians 3:10-11"}, {BibleOrder: 173, SetOrder: 306, Set: "Base", Ref: "1 Corinthians 1:18"}, {BibleOrder: 33, SetOrder: 307, Set: "Base", Ref: "Psalm 37:[1-2] 3-4"}, {BibleOrder: 34, SetOrder: 308, Set: "Base", Ref: "Psalm 37:5-6 [7-8]"}, {BibleOrder: 35, SetOrder: 309, Set: "Base", Ref: "Psalm 37:23-24"}, {BibleOrder: 233, SetOrder: 310, Set: "Base", Ref: "Hebrews 12:1"}, {BibleOrder: 234, SetOrder: 311, Set: "Base", Ref: "Hebrews 12:2"}, {BibleOrder: 53, SetOrder: 312, Set: "Base", Ref: "Psalm 96:1-3"}, {BibleOrder: 54, SetOrder: 313, Set: "Base", Ref: "Psalm 96:4-5"}, {BibleOrder: 55, SetOrder: 314, Set: "Base", Ref: "Psalm 96:6-8"}, {BibleOrder: 56, SetOrder: 315, Set: "Base", Ref: "Psalm 96:9-10"}, {BibleOrder: 108, SetOrder: 316, Set: "Base", Ref: "Isaiah 43:25"}, {BibleOrder: 166, SetOrder: 317, Set: "Base", Ref: "Romans 12:9-10"}, {BibleOrder: 167, SetOrder: 318, Set: "Base", Ref: "Romans 12:11-13"}, {BibleOrder: 168, SetOrder: 319, Set: "Base", Ref: "Romans 12:14-16"}, {BibleOrder: 169, SetOrder: 320, Set: "Base", Ref: "Romans 12:17–19"}, {BibleOrder: 170, SetOrder: 321, Set: "Base", Ref: "Romans 12:20-21"}, {BibleOrder: 93, SetOrder: 322, Set: "Base", Ref: "Proverbs 15:1"}, {BibleOrder: 243, SetOrder: 323, Set: "Base", Ref: "James 4:13-14"}, {BibleOrder: 244, SetOrder: 324, Set: "Base", Ref: "James 4:15-17"}, {BibleOrder: 132, SetOrder: 325, Set: "Base", Ref: "Luke 19:10"}, {BibleOrder: 13, SetOrder: 326, Set: "Base", Ref: "Psalm 18:30-31"}, {BibleOrder: 214, SetOrder: 327, Set: "Base", Ref: "Philippians 4:6–7"}, {BibleOrder: 215, SetOrder: 328, Set: "Base", Ref: "Philippians 4:8"}, {BibleOrder: 36, SetOrder: 329, Set: "Base", Ref: "Psalm 42:11"}, {BibleOrder: 109, SetOrder: 330, Set: "Base", Ref: "Isaiah 46:3-4"}, {BibleOrder: 206, SetOrder: 331, Set: "Base", Ref: "Philippians 1:21"}, {BibleOrder: 116, SetOrder: 332, Set: "Base", Ref: "Jeremiah 29:11-14"}, {BibleOrder: 98, SetOrder: 333, Set: "Base", Ref: "Proverbs 22:1"}, {BibleOrder: 23, SetOrder: 334, Set: "Base", Ref: "Psalm 30:4-5"}, {BibleOrder: 148, SetOrder: 335, Set: "Base", Ref: "Acts 20:35"}, {BibleOrder: 122, SetOrder: 336, Set: "Base", Ref: "Matthew 5:3–6"}, {BibleOrder: 123, SetOrder: 337, Set: "Base", Ref: "Matthew 5:7–10"}, {BibleOrder: 124, SetOrder: 338, Set: "Base", Ref: "Matthew 5:11–12"}, {BibleOrder: 177, SetOrder: 339, Set: "Base", Ref: "1 Corinthians 13:4-7"}, {BibleOrder: 24, SetOrder: 340, Set: "Base", Ref: "Psalm 32:8 [9]"}, {BibleOrder: 101, SetOrder: 341, Set: "Base", Ref: "Proverbs 31:30"}, {BibleOrder: 125, SetOrder: 342, Set: "Base", Ref: "Matthew 6:19–21"}, {BibleOrder: 176, SetOrder: 343, Set: "Base", Ref: "1 Corinthians 10:31"}, {BibleOrder: 153, SetOrder: 344, Set: "Base", Ref: "Romans 5:18-19"}, {BibleOrder: 136, SetOrder: 345, Set: "Base", Ref: "John 5:39-40"}, {BibleOrder: 246, SetOrder: 346, Set: "Base", Ref: "1 Peter 2:9-10 [11]"}, {BibleOrder: 163, SetOrder: 347, Set: "Base", Ref: "Romans 10:17"}, {BibleOrder: 129, SetOrder: 348, Set: "Base", Ref: "Matthew 20:26-28"}, {BibleOrder: 183, SetOrder: 349, Set: "Base", Ref: "2 Corinthians 5:21"}, {BibleOrder: 254, SetOrder: 350, Set: "Base", Ref: "1 John 3:1 [2]"}, {BibleOrder: 197, SetOrder: 351, Set: "Base", Ref: "Ephesians 3:20-21"}, {BibleOrder: 130, SetOrder: 352, Set: "Base", Ref: "Matthew 22:37-39"}, {BibleOrder: 106, SetOrder: 401, Set: "Base", Ref: "Isaiah 41:10"}, {BibleOrder: 107, SetOrder: 402, Set: "Base", Ref: "Isaiah 43:1–3"}, {BibleOrder: 143, SetOrder: 403, Set: "Base", Ref: "John 14:6"}, {BibleOrder: 221, SetOrder: 404, Set: "Base", Ref: "1 Thessalonians 5:14-17"}, {BibleOrder: 222, SetOrder: 405, Set: "Base", Ref: "1 Thessalonians 5:18-22"}, {BibleOrder: 87, SetOrder: 406, Set: "Base", Ref: "Proverbs 3:9-10"}, {BibleOrder: 88, SetOrder: 407, Set: "Base", Ref: "Proverbs 3:11-12"}, {BibleOrder: 140, SetOrder: 408, Set: "Base", Ref: "John 10:27-30"}, {BibleOrder: 147, SetOrder: 409, Set: "Base", Ref: "Acts 5:29"}, {BibleOrder: 57, SetOrder: 410, Set: "Base", Ref: "Psalm 100:1-3"}, {BibleOrder: 58, SetOrder: 411, Set: "Base", Ref: "Psalm 100:4-5"}, {BibleOrder: 193, SetOrder: 412, Set: "Base", Ref: "Ephesians 2:1-3"}, {BibleOrder: 194, SetOrder: 413, Set: "Base", Ref: "Ephesians 2:4-5"}, {BibleOrder: 195, SetOrder: 414, Set: "Base", Ref: "Ephesians 2:6-7"}, {BibleOrder: 196, SetOrder: 415, Set: "Base", Ref: "Ephesians 2:8-10"}, {BibleOrder: 151, SetOrder: 416, Set: "Base", Ref: "Romans 5:8"}, {BibleOrder: 152, SetOrder: 417, Set: "Base", Ref: "Romans 5:9-10"}, {BibleOrder: 75, SetOrder: 418, Set: "Base", Ref: "Psalm 139:1-3"}, {BibleOrder: 76, SetOrder: 419, Set: "Base", Ref: "Psalm 139:4-5"}, {BibleOrder: 77, SetOrder: 420, Set: "Base", Ref: "Psalm 139:6-8"}, {BibleOrder: 78, SetOrder: 421, Set: "Base", Ref: "Psalm 139:9-10"}, {BibleOrder: 79, SetOrder: 422, Set: "Base", Ref: "Psalm 139:11-12"}, {BibleOrder: 80, SetOrder: 423, Set: "Base", Ref: "Psalm 139:13-14"}, {BibleOrder: 81, SetOrder: 424, Set: "Base", Ref: "Psalm 139:15-16"}, {BibleOrder: 82, SetOrder: 425, Set: "Base", Ref: "Psalm 139:17-18"}, {BibleOrder: 83, SetOrder: 426, Set: "Base", Ref: "Psalm 139:23-24"}, {BibleOrder: 95, SetOrder: 427, Set: "Base", Ref: "Proverbs 17:9: 22"}, {BibleOrder: 229, SetOrder: 428, Set: "Base", Ref: "Hebrews 1:1-2"}, {BibleOrder: 230, SetOrder: 429, Set: "Base", Ref: "Hebrews 1:3-4"}, {BibleOrder: 114, SetOrder: 430, Set: "Base", Ref: "Jeremiah 1:12"}, {BibleOrder: 11, SetOrder: 431, Set: "Base", Ref: "Psalm 9:9-10"}, {BibleOrder: 239, SetOrder: 432, Set: "Base", Ref: "James 1:17"}, {BibleOrder: 20, SetOrder: 433, Set: "Base", Ref: "Psalm 27:1 [2-3]"}, {BibleOrder: 21, SetOrder: 434, Set: "Base", Ref: "Psalm 27:4 [5]"}, {BibleOrder: 22, SetOrder: 435, Set: "Base", Ref: "Psalm 27:13-14"}, {BibleOrder: 241, SetOrder: 436, Set: "Base", Ref: "James 1:22-24"}, {BibleOrder: 256, SetOrder: 437, Set: "Base", Ref: "Revelation 2:10"}, {BibleOrder: 99, SetOrder: 438, Set: "Base", Ref: "Proverbs 26:20"}, {BibleOrder: 115, SetOrder: 439, Set: "Base", Ref: "Jeremiah 9:23-24"}, {BibleOrder: 154, SetOrder: 440, Set: "Base", Ref: "Romans 6:23"}, {BibleOrder: 178, SetOrder: 441, Set: "Base", Ref: "1 Corinthians 15:1-3"}, {BibleOrder: 248, SetOrder: 442, Set: "Base", Ref: "1 Peter 3:18"}, {BibleOrder: 37, SetOrder: 443, Set: "Base", Ref: "Psalm 55:22"}, {BibleOrder: 74, SetOrder: 444, Set: "Base", Ref: "Psalm 127:1"}, {BibleOrder: 242, SetOrder: 445, Set: "Base", Ref: "James 4:7-8"}, {BibleOrder: 68, SetOrder: 446, Set: "Base", Ref: "Psalm 119:14-16"}, {BibleOrder: 145, SetOrder: 447, Set: "Base", Ref: "John 15:7"}, {BibleOrder: 67, SetOrder: 448, Set: "Base", Ref: "Psalm 118:13-14"}, {BibleOrder: 94, SetOrder: 449, Set: "Base", Ref: "Proverbs 16:32"}, {BibleOrder: 231, SetOrder: 450, Set: "Base", Ref: "Hebrews 3:12-13"}, {BibleOrder: 180, SetOrder: 451, Set: "Base", Ref: "1 Corinthians 15:58"}, {BibleOrder: 141, SetOrder: 452, Set: "Base", Ref: "John 11:25-26"}, {BibleOrder: 121, SetOrder: 501, Set: "Base", Ref: "Daniel 2:20-21"}, {BibleOrder: 126, SetOrder: 502, Set: "Base", Ref: "Matthew 9:13"}, {BibleOrder: 69, SetOrder: 503, Set: "Base", Ref: "Psalm 121:1-2"}, {BibleOrder: 70, SetOrder: 504, Set: "Base", Ref: "Psalm 121:3-4"}, {BibleOrder: 71, SetOrder: 505, Set: "Base", Ref: "Psalm 121:5-6"}, {BibleOrder: 72, SetOrder: 506, Set: "Base", Ref: "Psalm 121:7-8"}, {BibleOrder: 156, SetOrder: 507, Set: "Base", Ref: "Romans 8:28"}, {BibleOrder: 157, SetOrder: 508, Set: "Base", Ref: "Romans 8:29-30"}, {BibleOrder: 158, SetOrder: 509, Set: "Base", Ref: "Romans 8:31-32"}, {BibleOrder: 159, SetOrder: 510, Set: "Base", Ref: "Romans 8:33-34"}, {BibleOrder: 160, SetOrder: 511, Set: "Base", Ref: "Romans 8:35-37"}, {BibleOrder: 161, SetOrder: 512, Set: "Base", Ref: "Romans 8:38-39"}, {BibleOrder: 192, SetOrder: 513, Set: "Base", Ref: "Galatians 6:14"}, {BibleOrder: 1, SetOrder: 514, Set: "Base", Ref: "Numbers 23:19"}, {BibleOrder: 223, SetOrder: 515, Set: "Base", Ref: "1 Timothy 1:15"}, {BibleOrder: 235, SetOrder: 516, Set: "Base", Ref: "Hebrews 13:5-6"}, {BibleOrder: 118, SetOrder: 517, Set: "Base", Ref: "Lamentations 3:21-23"}, {BibleOrder: 119, SetOrder: 518, Set: "Base", Ref: "Lamentations 3:24-26"}, {BibleOrder: 120, SetOrder: 519, Set: "Base", Ref: "Lamentations 3:31-33"}, {BibleOrder: 219, SetOrder: 520, Set: "Base", Ref: "Colossians 3:16-17"}, {BibleOrder: 102, SetOrder: 521, Set: "Base", Ref: "Isaiah 26:3-4"}, {BibleOrder: 14, SetOrder: 522, Set: "Base", Ref: "Psalm 19:7-8"}, {BibleOrder: 15, SetOrder: 523, Set: "Base", Ref: "Psalm 19:9-11"}, {BibleOrder: 137, SetOrder: 524, Set: "Base", Ref: "John 6:35"}, {BibleOrder: 191, SetOrder: 525, Set: "Base", Ref: "Galatians 6:9-10"}, {BibleOrder: 25, SetOrder: 526, Set: "Base", Ref: "Psalm 34:1-3"}, {BibleOrder: 26, SetOrder: 527, Set: "Base", Ref: "Psalm 34:4-5"}, {BibleOrder: 27, SetOrder: 528, Set: "Base", Ref: "Psalm 34:6-8"}, {BibleOrder: 28, SetOrder: 529, Set: "Base", Ref: "Psalm 34:9-11"}, {BibleOrder: 29, SetOrder: 530, Set: "Base", Ref: "Psalm 34:12-14"}, {BibleOrder: 30, SetOrder: 531, Set: "Base", Ref: "Psalm 34:15-16"}, {BibleOrder: 31, SetOrder: 532, Set: "Base", Ref: "Psalm 34:17-18"}, {BibleOrder: 32, SetOrder: 533, Set: "Base", Ref: "Psalm 34:19-22"}, {BibleOrder: 220, SetOrder: 534, Set: "Base", Ref: "Colossians 4:6"}, {BibleOrder: 138, SetOrder: 535, Set: "Base", Ref: "John 8:31-32"}, {BibleOrder: 139, SetOrder: 536, Set: "Base", Ref: "John 10:10"}, {BibleOrder: 117, SetOrder: 537, Set: "Base", Ref: "Jeremiah 32:40"}, {BibleOrder: 40, SetOrder: 538, Set: "Base", Ref: "Psalm 73:25-26"}, {BibleOrder: 89, SetOrder: 539, Set: "Base", Ref: "Proverbs 4:23-24"}, {BibleOrder: 90, SetOrder: 540, Set: "Base", Ref: "Proverbs 4:25-27"}, {BibleOrder: 240, SetOrder: 541, Set: "Base", Ref: "James 1:19-20"}, {BibleOrder: 184, SetOrder: 542, Set: "Base", Ref: "2 Corinthians 8:9"}, {BibleOrder: 41, SetOrder: 543, Set: "Base", Ref: "Psalm 77:13-14"}, {BibleOrder: 66, SetOrder: 544, Set: "Base", Ref: "Psalm 118:5-8"}, {BibleOrder: 226, SetOrder: 545, Set: "Base", Ref: "1 Timothy 6:6-7"}, {BibleOrder: 42, SetOrder: 546, Set: "Base", Ref: "Psalm 79:9"}, {BibleOrder: 43, SetOrder: 547, Set: "Base", Ref: "Psalm 84:10-11 [12]"}, {BibleOrder: 255, SetOrder: 548, Set: "Base", Ref: "1 John 4:4"}, {BibleOrder: 179, SetOrder: 549, Set: "Base", Ref: "1 Corinthians 15:51-52"}, {BibleOrder: 258, SetOrder: 550, Set: "Base", Ref: "Revelation 21:3"}, {BibleOrder: 259, SetOrder: 551, Set: "Base", Ref: "Revelation 21:4"}, {BibleOrder: 260, SetOrder: 552, Set: "Base", Ref: "Revelation 21:5-6 [7]"}, }
fv/base.go
0.574753
0.594375
base.go
starcoder
package graph import ( "strings" "sync" ) type AxisGraph struct { Plane [41][41]Point highest float64 Graphs []string storage []string } func (graph *AxisGraph) New() { for y := 0; y < len(graph.Plane); y++ { for x := 0; x < len(graph.Plane[0]); x++ { graph.Plane[y][x].New() } } graph.Zoom(10) } //prints out the 2D array of points func (graph *AxisGraph) String() string { var retStr string = "" for _, row := range graph.Plane { for _, p := range row { retStr += p.String() } retStr += "\n" } return retStr } //zoom determines the spacing of each point given the highest values of both x and y func (graph *AxisGraph) Zoom(highVal float64) { increment := highVal / float64((len(graph.Plane) - 1) / 2.0) for y := 0; y < len(graph.Plane); y++ { yVal := highVal - (float64(y)*increment) for x := 0; x < len(graph.Plane); x++ { xVal := (-1*highVal) + (float64(x)*increment) graph.Plane[y][x].setCor(xVal,yVal) } } graph.Refresh() graph.highest = highVal } //runs Point.translate(double,double) on all points, moving the entire graph. func (graph *AxisGraph) Translate(dx float64, dy float64) { for i, _ := range graph.Plane { for j, _ := range graph.Plane[i] { graph.Plane[i][j].Translate(dx, dy) } } graph.Refresh() } //runa closeEnough on all the Points, forming a graph func (graph *AxisGraph) Graph(eq string, num int) { var wg sync.WaitGroup increment := graph.highest / float64((len(graph.Plane) - 1) / 2) for i, _ := range graph.Plane { for j, _ := range graph.Plane[i] { wg.Add(1) go func(x int, y int) { graph.Plane[x][y].CloseEnoughColor(eq, increment / 2.0, num) wg.Done() }(i, j) } } wg.Wait() } func (graph *AxisGraph) GraphAll() { for x := 0; x < len(graph.Graphs); x++ { graph.Graph(graph.Graphs[x], x) } } //runs reset() on all Points func (graph *AxisGraph) Refresh() { for i, _ := range graph.Plane { for j, _ := range graph.Plane[i] { graph.Plane[i][j].reset() graph.Plane[i][j].checkAxis(-1) } } } //clear gets rid of everything, all saved points and everything func (graph *AxisGraph) Clear() { graph.Graphs = nil graph.Refresh() } //takes the input string, checks if it exist already in storage. If it does rewrite over that input, if not, add it to storage func (graph *AxisGraph) Store(eq string) { variable := eq[strings.Index(eq, "[x]") - 1:strings.Index(eq, "[x]")] for i := 0; i < len(graph.storage); i++ { currentVar := graph.storage[i] if variable == currentVar[strings.Index(currentVar, "[x]") - 1:strings.Index(currentVar, "[x]")] { graph.storage = append(graph.storage[:i], graph.storage[i+1:]...) } } graph.storage = append(graph.storage, eq) } //takes the function name, matches it with its corresponding place in storage, and returns the expression that was stored. func (graph *AxisGraph) Function(input string) string { input = strings.Replace(input, " ", "", -1) for strings.Index(input, "[x]") != -1 { variable := graph.findname(input) replaced := input[strings.Index(input, "[x]")-1:strings.Index(input, "[x]")+3] input = strings.Replace(input, replaced, graph.findexp(variable), -1) } return input } //finds the letter name of the function func (graph *AxisGraph) findname(input string) string { fname := input[strings.Index(input, "[x]")-1:strings.Index(input, "[x]")] return fname } //finds the expression of the function with a certain name func (graph *AxisGraph) findexp(name string) string { exp := "" for i := 0; i < len(graph.storage); i++ { if name == graph.findname(graph.storage[i]) { fexp := graph.storage[i] exp = fexp[strings.Index(fexp, "=")+1:] exp = "(" + exp + ")" break } } return exp }
graph/axisgraph.go
0.623148
0.48054
axisgraph.go
starcoder
package main import ( "flag" "fmt" ) var depth = flag.Int("depth", 8112, "The depth of the cave system.") var targetX = flag.Int("targetX", 13, "The target's X coordinate.") var targetY = flag.Int("targetY", 743, "The target's Y coordinate.") var margin = flag.Int("margin", 150, "The margin by which we'll check 'longer' paths.") type Position struct { X, Y int Climb bool Torch bool } func (p Position) Passable(erosion [][]int) bool { if p.X < 0 || p.X >= len(erosion) { return false } if p.Y < 0 || p.Y >= len(erosion[0]) { return false } terrain := erosion[p.X][p.Y] % 3 switch terrain { case 0: // Rocky return p.Climb || p.Torch case 1: // Wet return !p.Torch case 2: // Narrow return !p.Climb } return false } func (p Position) Moves(erosion [][]int) map[Position]int { ret := make(map[Position]int) terrain := erosion[p.X][p.Y] % 3 swapGear := p switch terrain { case 0: // Rocky if !p.Climb && !p.Torch { // Illegal position. return ret } swapGear.Climb = !swapGear.Climb swapGear.Torch = !swapGear.Torch case 1: // Wet if swapGear.Torch { // Illegal position. return ret } swapGear.Climb = !swapGear.Climb case 2: // Narrow if swapGear.Climb { // Illegal position. return ret } swapGear.Torch = !swapGear.Torch } ret[swapGear] = 7 up := p up.Y-- if up.Passable(erosion) { ret[up] = 1 } down := p down.Y++ if down.Passable(erosion) { ret[down] = 1 } left := p left.X-- if left.Passable(erosion) { ret[left] = 1 } right := p right.X++ if right.Passable(erosion) { ret[right] = 1 } return ret } func main() { flag.Parse() risk := 0 // [x][y] in ordering. geoIdx := make([][]int, *targetX+1+*margin) erosion := make([][]int, *targetX+1+*margin) for x := 0; x <= *targetX+*margin; x++ { geoIdx[x] = make([]int, *targetY+1+*margin) erosion[x] = make([]int, *targetY+1+*margin) for y := 0; y <= *targetY+*margin; y++ { if (x == 0 && y == 0) || (x == *targetX && y == *targetY) { geoIdx[x][y] = 0 } else if x == 0 { geoIdx[x][y] = y * 48271 } else if y == 0 { geoIdx[x][y] = x * 16807 } else { // This should already be memoized. geoIdx[x][y] = erosion[x-1][y] * erosion[x][y-1] } erosion[x][y] = (geoIdx[x][y] + *depth) % 20183 terrain := erosion[x][y] % 3 if x <= *targetX && y <= *targetY { risk += terrain } } } fmt.Printf("Total risk of area is %d\n", risk) start := Position{0, 0, false, true} winner := Position{*targetX, *targetY, false, true} shortestPath := ComputeShortest(start, winner, erosion) fmt.Printf("Took %d moves to reach our friend.\n", shortestPath) } func ComputeShortest(start, winner Position, erosion [][]int) int { seen := make(map[Position]int) seen[start] = 0 queue := []Position{start} // Perform a BFS with backtracking. for len(queue) != 0 { pos := queue[0] queue = queue[1:] if shortest, ok := seen[pos]; !ok { // We don't know how to get here yet. continue } else { moves := pos.Moves(erosion) if len(moves) == 0 { // Illegal position. continue } for neighbor, incremental := range moves { shortestPathToNeighbor, ok := seen[neighbor] newPathLength := shortest + incremental if !ok || newPathLength < shortestPathToNeighbor { // Record new paths, as well as shortened paths. // Enqueue them to be re-run. seen[neighbor] = shortest + incremental queue = append(queue, neighbor) } } } } return seen[winner] }
2018/day22.go
0.546254
0.403537
day22.go
starcoder
package math3d import ( "fmt" "math" ) type Vector3 struct { X float64 Y float64 Z float64 } var ( ZeroVector3 = Vector3{} ) // MakeVector3 returns a pointer to a new Vector3. func MakeVector3(x float64, y float64, z float64) *Vector3 { return &Vector3{x, y, z} } func (v Vector3) String() string { return fmt.Sprintf("&Vec3{x=%+07.2f y=%+07.2f z=%+07.2f}", v.X, v.Y, v.Z) } // Zero returns true if the vector is at 0,0,0. func (v Vector3) Zero() bool { return (v.X == 0) && (v.Y == 0) && (v.Z == 0) } // Add adds two vectors, and returns a pointer to the result. // TODO: Return a value rather than a pointer. The caller can always create a // pointer if they really want. func (v Vector3) Add(vv Vector3) *Vector3 { return &Vector3{ (v.X + vv.X), (v.Y + vv.Y), (v.Z + vv.Z), } } // Subtract one vector from another. func (v Vector3) Subtract(vv Vector3) Vector3 { return Vector3{ (v.X - vv.X), (v.Y - vv.Y), (v.Z - vv.Z), } } // Distance calculates and returns the distance between this vector and another. // TODO: Remove this; users should just Subtract and Magnitude themselves. func (v Vector3) Distance(vv Vector3) float64 { return v.Subtract(vv).Magnitude() } func (v Vector3) Magnitude() float64 { return math.Sqrt((v.X * v.X) + (v.Y * v.Y) + (v.Z * v.Z)) } // Unit returns the vector scaled to a length of 1, such that it represents a // direction rather than a point. func (v Vector3) Unit() Vector3 { m := v.Magnitude() if m == 0 { return ZeroVector3 } return Vector3{ X: v.X / m, Y: v.Y / m, Z: v.Z / m, } } // MultiplyByMatrix44 returns a new Vector3, by multiplying this vector my a 4x4 // matrix. func (v Vector3) MultiplyByMatrix44(m Matrix44) Vector3 { return Vector3{ (v.X * m.m11) + (v.Y * m.m21) + (v.Z * m.m31) + m.m41, (v.X * m.m12) + (v.Y * m.m22) + (v.Z * m.m32) + m.m42, (v.X * m.m13) + (v.Y * m.m23) + (v.Z * m.m33) + m.m43, } } // MultiplyByScaler returns a new vector by multiply each attribute by the given // scalar. This can be used to project a distance along the vector. func (v Vector3) MultiplyByScalar(s float64) Vector3 { return Vector3{ (v.X * s), (v.Y * s), (v.Z * s), } }
math3d/vector.go
0.769514
0.653493
vector.go
starcoder
package main import ( "bufio" "fmt" "math" "os" "strconv" ) // Python-style modulus function (-1 % 5 == 4, not -1) func modulus(i int, m int) (r int) { r = i % m if r < 0 { r += m } return } // Grid for cellular automata, mazes, etc. type Grid [][]byte // Coordinate is a position on a Grid, i.e., grid[y][x] type Coordinate struct { y int x int } // Returns the value at a map coordinate, or the zero byte if out of bounds func (g Grid) Get(i, j int) (result byte) { if i < 0 || i >= len(g) || j < 0 || j >= len(g[i]) { return 0 } return g[i][j] } func (g Grid) Print() { for _, line := range g { fmt.Printf("%s\n", line) } } func (g Grid) Copy() (c Grid) { c = make(Grid, len(g)) for i, line := range g { c[i] = make([]byte, len(line)) copy(c[i], line) } return } func (g Grid) Equal(o Grid) bool { if len(g) != len(o) { return false } for i := 0; i < len(g); i++ { // according to bytes.go, this does not allocate if string(g[i]) != string(o[i]) { return false } } return true } func (g Grid) rotateOnce() (r Grid) { r = g.Copy() yMod := len(g) for i := 0; i < yMod; i++ { xMod := len(g[i]) for j := 0; j < xMod; j++ { r[j][modulus(-1-i, yMod)] = g[i][j] } } return } func (g Grid) flipOnce() (r Grid) { r = g.Copy() for i := 0; i < len(g); i++ { mod := len(g[i]) for j := 0; j < mod; j++ { r[i][j] = g[i][modulus(-1-j, mod)] } } return } func parseInt(str string) int { i, err := strconv.Atoi(str) if err != nil { panic(err) } return i } const ( sideLen = 10 ) func reverseBits(num int) (res int) { for i := 0; i < sideLen; i++ { if (num & (1 << ((sideLen - 1) - i))) != 0 { res |= 1 << i } } return } func intSqrt(num int) (res int) { res = int(math.Sqrt(float64(num))) if res*res != num { panic(num) } return } // the top, right, bottom, and left edges, in clockwise order, // each time starting at the least significant bit of the integer type Tile [4]int func (t Tile) Rotate() (r Tile) { return Tile{t[3], t[0], t[1], t[2]} } func (t Tile) Flip() (r Tile) { return Tile{reverseBits(t[0]), reverseBits(t[3]), reverseBits(t[2]), reverseBits(t[1])} } func (t Tile) DihedralFour() (result [8]Tile) { result[0] = t result[1] = result[0].Rotate() result[2] = result[1].Rotate() result[3] = result[2].Rotate() result[4] = t.Flip() result[5] = result[4].Rotate() result[6] = result[5].Rotate() result[7] = result[6].Rotate() return } type TileArrangement [][]Tile func compatible(a TileArrangement, y, x int, t Tile) bool { if y > 0 { if a[y-1][x][2] != reverseBits(t[0]) { return false } } if x > 0 { if a[y][x-1][1] != reverseBits(t[3]) { return false } } return true } func recursiveBacktrack(tiles map[int]Tile, result [][]int, rotations [][]uint8, tileArrangement [][]Tile, y, x int) (success bool) { if len(tiles) == 0 { return true } curTiles := make([]int, 0, len(tiles)) for tileID := range tiles { curTiles = append(curTiles, tileID) } nextY := y nextX := (x + 1) % len(result[0]) if nextX == 0 { nextY = (y + 1) % len(result) } for _, tileId := range curTiles { tile := tiles[tileId] delete(tiles, tileId) for rotIdx, r := range tile.DihedralFour() { if compatible(tileArrangement, y, x, r) { result[y][x] = tileId tileArrangement[y][x] = r rotations[y][x] = uint8(rotIdx) if recursiveBacktrack(tiles, result, rotations, tileArrangement, nextY, nextX) { return true } } } tiles[tileId] = tile } return false } func arrange(tiles map[int]Tile) (result [][]int, rotations [][]uint8) { squareSide := intSqrt(len(tiles)) result = make([][]int, squareSide) rotations = make([][]uint8, squareSide) ta := make(TileArrangement, squareSide) for i := 0; i < squareSide; i++ { result[i] = make([]int, squareSide) ta[i] = make([]Tile, squareSide) rotations[i] = make([]uint8, squareSide) } success := recursiveBacktrack(tiles, result, rotations, ta, 0, 0) if !success { panic("fail") } return } func rotateGrid(grid Grid, rotateIdx uint8) (result Grid) { // XXX make sure we make a deep copy of the grid if rotateIdx >= 4 { rotateIdx -= 4 result = grid.flipOnce() } else { result = grid.Copy() } var i uint8 for i = 0; i < rotateIdx; i++ { result = result.rotateOnce() } return } func countSharps(grid Grid) (result int) { for i := 0; i < len(grid); i++ { for j := 0; j < len(grid[i]); j++ { if grid[i][j] == '#' { result++ } } } return } var seaMonster []Coordinate = []Coordinate{ {0, 18}, {1, 0}, {1, 5}, {1, 6}, {1, 11}, {1, 12}, {1, 17}, {1, 18}, {1, 19}, {2, 1}, {2, 4}, {2, 7}, {2, 10}, {2, 13}, {2, 16}, } func countSeaMonsters(g Grid) (result int) { for i := 0; i < len(g); i++ { for j := 0; j < len(g[i]); j++ { success := true for _, delta := range seaMonster { if g.Get(i+delta.y, j+delta.x) != '#' { success = false break } } if success { result++ } // TODO prevent overlapping monsters? } } return } func solve(input []string) (result int, err error) { tiles := make(map[int]Tile) grids := make(map[int]Grid) for len(input) > 0 { line := input[0] input = input[1:] tileNum := parseInt(line[5 : len(line)-1]) var grid Grid for { grid = append(grid, []byte(input[0])) input = input[1:] if input[0] == "" { break } } var tile Tile for i := 0; i < sideLen; i++ { if grid[0][i] == '#' { tile[0] |= 1 << i } } for i := 0; i < sideLen; i++ { if grid[i][sideLen-1] == '#' { tile[1] |= 1 << i } } for i := 0; i < sideLen; i++ { if grid[sideLen-1][(sideLen-1)-i] == '#' { tile[2] |= 1 << i } } for i := 0; i < sideLen; i++ { if grid[(sideLen-1)-i][0] == '#' { tile[3] |= 1 << i } } tiles[tileNum] = tile grids[tileNum] = grid input = input[1:] } arrangement, rotations := arrange(tiles) squareSide := intSqrt(len(grids)) cutSideLen := sideLen - 2 picSide := cutSideLen * squareSide pic := make(Grid, picSide) for i := 0; i < len(pic); i++ { pic[i] = make([]byte, picSide) } for i := 0; i < len(arrangement); i++ { for j := 0; j < len(arrangement[i]); j++ { yPos := cutSideLen * i xPos := cutSideLen * j curPic := rotateGrid(grids[arrangement[i][j]], rotations[i][j]) for yDelt := 0; yDelt < cutSideLen; yDelt++ { copy(pic[yPos+yDelt][xPos:], curPic[yDelt+1][1:sideLen-1]) } } } sharpCount := countSharps(pic) var rot uint8 for rot = 0; rot < 8; rot++ { r := rotateGrid(pic, rot) m := countSeaMonsters(r) if m != 0 { return sharpCount - (len(seaMonster) * m), nil } } panic("sea monsters not found") } func main() { var input []string scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { line := scanner.Text() input = append(input, line) } solution, err := solve(input) if err != nil { panic(err) } fmt.Println(solution) }
2020/20/b.go
0.828523
0.400632
b.go
starcoder
// Sample program to show how you can use embedding to reuse behavior from // another type and override specific methods. package main import ( "fmt" "log" "time" ) // Document is the core data model we are working with. type Document struct { Key string Title string } // ================================================== // Feed is a type that knows how to fetch Documents. type Feed struct{} // Count tells how many documents are in the feed. func (f *Feed) Count() int { return 42 } // Fetch simulates looking up the document specified by key. It is slow. func (f *Feed) Fetch(key string) (Document, error) { time.Sleep(time.Second) doc := Document{ Key: key, Title: "Title for " + key, } return doc, nil } // ================================================== // CachingFeed keeps a local copy of Documents that have already been // retrieved. It embeds Feed to get the Fetch and Count behavior but // "overrides" Fetch to have its cache. type CachingFeed struct { docs map[string]Document *Feed } // NewCachingFeed initalizes a CachingFeed for use. func NewCachingFeed(f *Feed) *CachingFeed { return &CachingFeed{ docs: make(map[string]Document), Feed: f, } } // Fetch calls the embedded type's Fetch method if the key is not cached. func (r *CachingFeed) Fetch(key string) (Document, error) { if doc, ok := r.docs[key]; ok { return doc, nil } doc, err := r.Feed.Fetch(key) if err != nil { return Document{}, err } r.docs[key] = doc return doc, nil } // ================================================== // FetchCounter is the behavior we depend on for our process function. type FetchCounter interface { Fetch(key string) (Document, error) Count() int } func process(fc FetchCounter) { fmt.Printf("There are %d documents\n", fc.Count()) keys := []string{"a", "a", "a", "b", "b", "b"} for _, key := range keys { doc, err := fc.Fetch(key) if err != nil { log.Printf("Could not fetch %s : %v", key, err) return } fmt.Printf("%s : %v\n", key, doc) } } func main() { fmt.Println("Using Feed directly") process(&Feed{}) fmt.Println("Using CachingFeed") c := NewCachingFeed(&Feed{}) process(c) }
topics/go/language/embedding/exercises/exercise1/exercise1.go
0.68616
0.401629
exercise1.go
starcoder
package advanced import ( "math" "github.com/ldsec/lattigo/v2/ckks" "github.com/ldsec/lattigo/v2/utils" ) // LinearTransformType is a type used to distinguish different linear transformations. type LinearTransformType int // CoeffsToSlots and SlotsToCoeffs are two linear transformations. const ( CoeffsToSlots = LinearTransformType(0) // Homomorphic Encoding SlotsToCoeffs = LinearTransformType(1) // Homomorphic Decoding ) // EncodingMatrix is a struct storing the factorized DFT matrix type EncodingMatrix struct { EncodingMatrixLiteral matrices []ckks.LinearTransform } // EncodingMatrixLiteral is a struct storing the parameters to generate the factorized DFT matrix. type EncodingMatrixLiteral struct { LinearTransformType LinearTransformType LogN int // log(RingDegree) LogSlots int // log(slots) Scaling float64 // constant by which the matrix is multiplied with LevelStart int // Encoding level BitReversed bool // Flag for bit-reverseed input to the DFT (with bit-reversed output), by default false. BSGSRatio float64 // n1/n2 ratio for the bsgs algo for matrix x vector eval ScalingFactor [][]float64 } // Depth returns the number of levels allocated. // If actual == true then returns the number of moduli consumed, else // returns the factorization depth. func (mParams *EncodingMatrixLiteral) Depth(actual bool) (depth int) { if actual { depth = len(mParams.ScalingFactor) } else { for i := range mParams.ScalingFactor { for range mParams.ScalingFactor[i] { depth++ } } } return } // Levels returns the index of the Qi used int CoeffsToSlots. func (mParams *EncodingMatrixLiteral) Levels() (levels []int) { levels = []int{} trueDepth := mParams.Depth(true) for i := range mParams.ScalingFactor { for range mParams.ScalingFactor[trueDepth-1-i] { levels = append(levels, mParams.LevelStart-i) } } return } // Rotations returns the list of rotations performed during the CoeffsToSlot operation. func (mParams *EncodingMatrixLiteral) Rotations(logN, logSlots int) (rotations []int) { rotations = []int{} slots := 1 << logSlots dslots := slots if logSlots < logN-1 { dslots <<= 1 if mParams.LinearTransformType == CoeffsToSlots { rotations = append(rotations, slots) } } indexCtS := computeBootstrappingDFTIndexMap(logN, logSlots, mParams.Depth(false), mParams.LinearTransformType, mParams.BitReversed) // Coeffs to Slots rotations for i, pVec := range indexCtS { N1 := ckks.FindBestBSGSSplit(pVec, dslots, mParams.BSGSRatio) rotations = addMatrixRotToList(pVec, rotations, N1, slots, mParams.LinearTransformType == SlotsToCoeffs && logSlots < logN-1 && i == 0) } return } // NewHomomorphicEncodingMatrixFromLiteral generates the factorized encoding matrix. // scaling : constant by witch the all the matrices will be multuplied by. // encoder : ckks.Encoder. func NewHomomorphicEncodingMatrixFromLiteral(mParams EncodingMatrixLiteral, encoder ckks.Encoder) EncodingMatrix { logSlots := mParams.LogSlots slots := 1 << logSlots depth := mParams.Depth(false) logdSlots := mParams.LogSlots + 1 if logdSlots == mParams.LogN { logdSlots-- } roots := computeRoots(slots << 1) pow5 := make([]int, (slots<<1)+1) pow5[0] = 1 for i := 1; i < (slots<<1)+1; i++ { pow5[i] = pow5[i-1] * 5 pow5[i] &= (slots << 2) - 1 } ctsLevels := mParams.Levels() scaling := complex(math.Pow(mParams.Scaling, 1.0/float64(mParams.Depth(false))), 0) // CoeffsToSlots vectors matrices := make([]ckks.LinearTransform, len(ctsLevels)) pVecDFT := computeDFTMatrices(logSlots, logdSlots, depth, roots, pow5, scaling, mParams.LinearTransformType, mParams.BitReversed) cnt := 0 trueDepth := mParams.Depth(true) for i := range mParams.ScalingFactor { for j := range mParams.ScalingFactor[trueDepth-i-1] { matrices[cnt] = ckks.GenLinearTransformBSGS(encoder, pVecDFT[cnt], ctsLevels[cnt], mParams.ScalingFactor[trueDepth-i-1][j], mParams.BSGSRatio, logdSlots) cnt++ } } return EncodingMatrix{EncodingMatrixLiteral: mParams, matrices: matrices} } func computeRoots(N int) (roots []complex128) { var angle float64 m := N << 1 roots = make([]complex128, m) roots[0] = 1 for i := 1; i < m; i++ { angle = 6.283185307179586 * float64(i) / float64(m) roots[i] = complex(math.Cos(angle), math.Sin(angle)) } return } func fftPlainVec(logN, dslots int, roots []complex128, pow5 []int) (a, b, c [][]complex128) { var N, m, index, tt, gap, k, mask, idx1, idx2 int N = 1 << logN a = make([][]complex128, logN) b = make([][]complex128, logN) c = make([][]complex128, logN) var size int if 2*N == dslots { size = 2 } else { size = 1 } index = 0 for m = 2; m <= N; m <<= 1 { a[index] = make([]complex128, dslots) b[index] = make([]complex128, dslots) c[index] = make([]complex128, dslots) tt = m >> 1 for i := 0; i < N; i += m { gap = N / m mask = (m << 2) - 1 for j := 0; j < m>>1; j++ { k = (pow5[j] & mask) * gap idx1 = i + j idx2 = i + j + tt for u := 0; u < size; u++ { a[index][idx1+u*N] = 1 a[index][idx2+u*N] = -roots[k] b[index][idx1+u*N] = roots[k] c[index][idx2+u*N] = 1 } } } index++ } return } func fftInvPlainVec(logN, dslots int, roots []complex128, pow5 []int) (a, b, c [][]complex128) { var N, m, index, tt, gap, k, mask, idx1, idx2 int N = 1 << logN a = make([][]complex128, logN) b = make([][]complex128, logN) c = make([][]complex128, logN) var size int if 2*N == dslots { size = 2 } else { size = 1 } index = 0 for m = N; m >= 2; m >>= 1 { a[index] = make([]complex128, dslots) b[index] = make([]complex128, dslots) c[index] = make([]complex128, dslots) tt = m >> 1 for i := 0; i < N; i += m { gap = N / m mask = (m << 2) - 1 for j := 0; j < m>>1; j++ { k = ((m << 2) - (pow5[j] & mask)) * gap idx1 = i + j idx2 = i + j + tt for u := 0; u < size; u++ { a[index][idx1+u*N] = 1 a[index][idx2+u*N] = -roots[k] b[index][idx1+u*N] = 1 c[index][idx2+u*N] = roots[k] } } } index++ } return } func addMatrixRotToList(pVec map[int]bool, rotations []int, N1, slots int, repack bool) []int { if len(pVec) < 3 { for j := range pVec { if !utils.IsInSliceInt(j, rotations) { rotations = append(rotations, j) } } } else { var index int for j := range pVec { index = (j / N1) * N1 if repack { // Sparse repacking, occurring during the first DFT matrix of the CoeffsToSlots. index &= (2*slots - 1) } else { // Other cases index &= (slots - 1) } if index != 0 && !utils.IsInSliceInt(index, rotations) { rotations = append(rotations, index) } index = j & (N1 - 1) if index != 0 && !utils.IsInSliceInt(index, rotations) { rotations = append(rotations, index) } } } return rotations } func computeBootstrappingDFTIndexMap(logN, logSlots, maxDepth int, ltType LinearTransformType, bitreversed bool) (rotationMap []map[int]bool) { var level, depth, nextLevel int level = logSlots rotationMap = make([]map[int]bool, maxDepth) // We compute the chain of merge in order or reverse order depending if its DFT or InvDFT because // the way the levels are collapsed has an impact on the total number of rotations and keys to be // stored. Ex. instead of using 255 + 64 plaintext vectors, we can use 127 + 128 plaintext vectors // by reversing the order of the merging. merge := make([]int, maxDepth) for i := 0; i < maxDepth; i++ { depth = int(math.Ceil(float64(level) / float64(maxDepth-i))) if ltType == CoeffsToSlots { merge[i] = depth } else { merge[len(merge)-i-1] = depth } level -= depth } level = logSlots for i := 0; i < maxDepth; i++ { if logSlots < logN-1 && ltType == SlotsToCoeffs && i == 0 { // Special initial matrix for the repacking before SlotsToCoeffs rotationMap[i] = genWfftRepackIndexMap(logSlots, level) // Merges this special initial matrix with the first layer of SlotsToCoeffs DFT rotationMap[i] = nextLevelfftIndexMap(rotationMap[i], logSlots, 2<<logSlots, level, ltType, bitreversed) // Continues the merging with the next layers if the total depth requires it. nextLevel = level - 1 for j := 0; j < merge[i]-1; j++ { rotationMap[i] = nextLevelfftIndexMap(rotationMap[i], logSlots, 2<<logSlots, nextLevel, ltType, bitreversed) nextLevel-- } } else { // First layer of the i-th level of the DFT rotationMap[i] = genWfftIndexMap(logSlots, level, ltType, bitreversed) // Merges the layer with the next levels of the DFT if the total depth requires it. nextLevel = level - 1 for j := 0; j < merge[i]-1; j++ { rotationMap[i] = nextLevelfftIndexMap(rotationMap[i], logSlots, 1<<logSlots, nextLevel, ltType, bitreversed) nextLevel-- } } level -= merge[i] } return } func genWfftIndexMap(logL, level int, ltType LinearTransformType, bitreversed bool) (vectors map[int]bool) { var rot int if ltType == CoeffsToSlots && !bitreversed || ltType == SlotsToCoeffs && bitreversed { rot = 1 << (level - 1) } else { rot = 1 << (logL - level) } vectors = make(map[int]bool) vectors[0] = true vectors[rot] = true vectors[(1<<logL)-rot] = true return } func genWfftRepackIndexMap(logL, level int) (vectors map[int]bool) { vectors = make(map[int]bool) vectors[0] = true vectors[(1 << logL)] = true return } func nextLevelfftIndexMap(vec map[int]bool, logL, N, nextLevel int, ltType LinearTransformType, bitreversed bool) (newVec map[int]bool) { var rot int newVec = make(map[int]bool) if ltType == CoeffsToSlots && !bitreversed || ltType == SlotsToCoeffs && bitreversed { rot = (1 << (nextLevel - 1)) & (N - 1) } else { rot = (1 << (logL - nextLevel)) & (N - 1) } for i := range vec { newVec[i] = true newVec[(i+rot)&(N-1)] = true newVec[(i-rot)&(N-1)] = true } return } func computeDFTMatrices(logSlots, logdSlots, maxDepth int, roots []complex128, pow5 []int, diffscale complex128, ltType LinearTransformType, bitreversed bool) (plainVector []map[int][]complex128) { var fftLevel, depth, nextfftLevel int fftLevel = logSlots var a, b, c [][]complex128 if ltType == CoeffsToSlots { a, b, c = fftInvPlainVec(logSlots, 1<<logdSlots, roots, pow5) } else { a, b, c = fftPlainVec(logSlots, 1<<logdSlots, roots, pow5) } plainVector = make([]map[int][]complex128, maxDepth) // We compute the chain of merge in order or reverse order depending if its DFT or InvDFT because // the way the levels are collapsed has an inpact on the total number of rotations and keys to be // stored. Ex. instead of using 255 + 64 plaintext vectors, we can use 127 + 128 plaintext vectors // by reversing the order of the merging. merge := make([]int, maxDepth) for i := 0; i < maxDepth; i++ { depth = int(math.Ceil(float64(fftLevel) / float64(maxDepth-i))) if ltType == CoeffsToSlots { merge[i] = depth } else { merge[len(merge)-i-1] = depth } fftLevel -= depth } fftLevel = logSlots for i := 0; i < maxDepth; i++ { if logSlots != logdSlots && ltType == SlotsToCoeffs && i == 0 { // Special initial matrix for the repacking before SlotsToCoeffs plainVector[i] = genRepackMatrix(logSlots, bitreversed) // Merges this special initial matrix with the first layer of SlotsToCoeffs DFT plainVector[i] = multiplyFFTMatrixWithNextFFTLevel(plainVector[i], logSlots, 2<<logSlots, fftLevel, a[logSlots-fftLevel], b[logSlots-fftLevel], c[logSlots-fftLevel], ltType, bitreversed) // Continues the merging with the next layers if the total depth requires it. nextfftLevel = fftLevel - 1 for j := 0; j < merge[i]-1; j++ { plainVector[i] = multiplyFFTMatrixWithNextFFTLevel(plainVector[i], logSlots, 2<<logSlots, nextfftLevel, a[logSlots-nextfftLevel], b[logSlots-nextfftLevel], c[logSlots-nextfftLevel], ltType, bitreversed) nextfftLevel-- } } else { // First layer of the i-th level of the DFT plainVector[i] = genFFTDiagMatrix(logSlots, fftLevel, a[logSlots-fftLevel], b[logSlots-fftLevel], c[logSlots-fftLevel], ltType, bitreversed) // Merges the layer with the next levels of the DFT if the total depth requires it. nextfftLevel = fftLevel - 1 for j := 0; j < merge[i]-1; j++ { plainVector[i] = multiplyFFTMatrixWithNextFFTLevel(plainVector[i], logSlots, 1<<logSlots, nextfftLevel, a[logSlots-nextfftLevel], b[logSlots-nextfftLevel], c[logSlots-nextfftLevel], ltType, bitreversed) nextfftLevel-- } } fftLevel -= merge[i] } // Repacking after the CoeffsToSlots (we multiply the last DFT matrix with the vector [1, 1, ..., 1, 1, 0, 0, ..., 0, 0]). if logSlots != logdSlots && ltType == CoeffsToSlots { for j := range plainVector[maxDepth-1] { for x := 0; x < 1<<logSlots; x++ { plainVector[maxDepth-1][j][x+(1<<logSlots)] = complex(0, 0) } } } // Rescaling of the DFT matrix of the SlotsToCoeffs/CoeffsToSlots for j := range plainVector { for x := range plainVector[j] { for i := range plainVector[j][x] { plainVector[j][x][i] *= diffscale } } } return } func genFFTDiagMatrix(logL, fftLevel int, a, b, c []complex128, ltType LinearTransformType, bitreversed bool) (vectors map[int][]complex128) { var rot int if ltType == CoeffsToSlots && !bitreversed || ltType == SlotsToCoeffs && bitreversed { rot = 1 << (fftLevel - 1) } else { rot = 1 << (logL - fftLevel) } vectors = make(map[int][]complex128) if bitreversed { ckks.SliceBitReverseInPlaceComplex128(a, 1<<logL) ckks.SliceBitReverseInPlaceComplex128(b, 1<<logL) ckks.SliceBitReverseInPlaceComplex128(c, 1<<logL) if len(a) > 1<<logL { ckks.SliceBitReverseInPlaceComplex128(a[1<<logL:], 1<<logL) ckks.SliceBitReverseInPlaceComplex128(b[1<<logL:], 1<<logL) ckks.SliceBitReverseInPlaceComplex128(c[1<<logL:], 1<<logL) } } addToDiagMatrix(vectors, 0, a) addToDiagMatrix(vectors, rot, b) addToDiagMatrix(vectors, (1<<logL)-rot, c) return } func genRepackMatrix(logL int, bitreversed bool) (vectors map[int][]complex128) { vectors = make(map[int][]complex128) a := make([]complex128, 2<<logL) b := make([]complex128, 2<<logL) for i := 0; i < 1<<logL; i++ { a[i] = complex(1, 0) a[i+(1<<logL)] = complex(0, 1) b[i] = complex(0, 1) b[i+(1<<logL)] = complex(1, 0) } addToDiagMatrix(vectors, 0, a) addToDiagMatrix(vectors, (1 << logL), b) return } func multiplyFFTMatrixWithNextFFTLevel(vec map[int][]complex128, logL, N, nextLevel int, a, b, c []complex128, ltType LinearTransformType, bitreversed bool) (newVec map[int][]complex128) { var rot int newVec = make(map[int][]complex128) if ltType == CoeffsToSlots && !bitreversed || ltType == SlotsToCoeffs && bitreversed { rot = (1 << (nextLevel - 1)) & (N - 1) } else { rot = (1 << (logL - nextLevel)) & (N - 1) } if bitreversed { ckks.SliceBitReverseInPlaceComplex128(a, 1<<logL) ckks.SliceBitReverseInPlaceComplex128(b, 1<<logL) ckks.SliceBitReverseInPlaceComplex128(c, 1<<logL) if len(a) > 1<<logL { ckks.SliceBitReverseInPlaceComplex128(a[1<<logL:], 1<<logL) ckks.SliceBitReverseInPlaceComplex128(b[1<<logL:], 1<<logL) ckks.SliceBitReverseInPlaceComplex128(c[1<<logL:], 1<<logL) } } for i := range vec { addToDiagMatrix(newVec, i, mul(vec[i], a)) addToDiagMatrix(newVec, (i+rot)&(N-1), mul(rotate(vec[i], rot), b)) addToDiagMatrix(newVec, (i-rot)&(N-1), mul(rotate(vec[i], -rot), c)) } return } func transposeDiagMatrix(mat map[int][]complex128, N int) { for i := range mat { if i < N>>1 { mat[i], mat[N-i] = mat[N-i], mat[i] } } } func conjugateDiagMatrix(mat map[int][]complex128) { for i := range mat { for j := range mat[i] { c := mat[i][j] mat[i][j] = complex(real(c), -imag(c)) } } } func genBitReverseDiagMatrix(logN int) (diagMat map[int][]complex128) { var N, iRev, diff int diagMat = make(map[int][]complex128) N = 1 << logN for i := 0; i < N; i++ { iRev = int(utils.BitReverse64(uint64(i), uint64(logN))) diff = (i - iRev) & (N - 1) if diagMat[diff] == nil { diagMat[diff] = make([]complex128, N) } diagMat[diff][iRev] = complex(1, 0) } return } func addToDiagMatrix(diagMat map[int][]complex128, index int, vec []complex128) { if diagMat[index] == nil { diagMat[index] = vec } else { diagMat[index] = add(diagMat[index], vec) } } func rotate(x []complex128, n int) (y []complex128) { y = make([]complex128, len(x)) mask := int(len(x) - 1) // Rotates to the left for i := 0; i < len(x); i++ { y[i] = x[(i+n)&mask] } return } func mul(a, b []complex128) (res []complex128) { res = make([]complex128, len(a)) for i := 0; i < len(a); i++ { res[i] = a[i] * b[i] } return } func add(a, b []complex128) (res []complex128) { res = make([]complex128, len(a)) for i := 0; i < len(a); i++ { res[i] = a[i] + b[i] } return }
ckks/advanced/homomorphic_encoding.go
0.756897
0.683287
homomorphic_encoding.go
starcoder
package metrics_metadata // A JSON object (dictionary) that contains the metadata for a single dimension that matched the query type Dimension struct { // The dimension name (key) for the dimension. Dimension names have these requirements: <br> * UTF-8 string, maximum length of 128 characters (512 bytes) * Must start with an uppercase or lowercase letter. The rest of the name can contain letters, numbers, underscores (`_`) and hyphens (`-`). * Must not start with the underscore character (`_`) * Must not start with the prefix `sf_`, except for dimensions defined by SignalFx such as `sf_hires` * Must not start with the prefix `aws_` Key string `json:"key,omitempty"` // The dimension value for the dimension. Dimension values have these requirements: <br> * String: Maximum length 256 UTF-8 characters (1024 bytes) * Integer or float: Maximum length 8192 bits (1024 bytes) Value string `json:"value,omitempty"` // The description for the dimension. You can use up to 1024 UTF-8 characters. Description string `json:"description,omitempty"` // The custom properties for the dimension, in the form of a JSON object (dictionary) containing custom property key-value pairs. Custom property names and values have these requirements: <br> **Name:** <br> * UTF-8 string, maximum length of 128 characters (512 bytes) * Must start with an uppercase or lowercase letter. The rest of the name can contain letters, numbers, underscores (`_`) and hyphens (`-`). * Must not start with the underscore character (`_`) <br> **Value:** <br> * String: Maximum length 256 UTF-8 characters (1024 bytes) * Integer or float: Maximum length 8192 bits (1024 bytes) CustomProperties map[string]string `json:"customProperties,omitempty"` // The tags for the dimension, in the form of an array that contains one string for each tag. <br> Each tag is a UTF-8 string, starting with an uppercase or lowercase alphabetic character. The maximum length is expressed in characters; if a string consists solely of single-byte UTF-8 entities, 1024 characters are available. <br> **NOTE:** You can't have more than 50 tags per MTS Tags []string `json:"tags,omitempty"` // The SignalFx user ID of the user that created the dimension. Creator string `json:"creator,omitempty"` // Dimension creation timestamp, in Unix time UTC-relative Created int64 `json:"created,omitempty"` // The SignalFx user ID of the user that last updated the dimension. LastUpdatedBy string `json:"lastUpdatedBy,omitempty"` // Last updated timestamp, in Unix time UTC-relative LastUpdated int64 `json:"lastUpdated,omitempty"` }
metrics_metadata/model_dimension.go
0.840848
0.446133
model_dimension.go
starcoder
package math import ( "math" "github.com/goplus/interp" ) func init() { interp.RegisterPackage("math", extMap, typList) } var extMap = map[string]interface{}{ "math.Abs": math.Abs, "math.Acos": math.Acos, "math.Acosh": math.Acosh, "math.Asin": math.Asin, "math.Asinh": math.Asinh, "math.Atan": math.Atan, "math.Atan2": math.Atan2, "math.Atanh": math.Atanh, "math.Cbrt": math.Cbrt, "math.Ceil": math.Ceil, "math.Copysign": math.Copysign, "math.Cos": math.Cos, "math.Cosh": math.Cosh, "math.Dim": math.Dim, "math.Erf": math.Erf, "math.Erfc": math.Erfc, "math.Erfcinv": math.Erfcinv, "math.Erfinv": math.Erfinv, "math.Exp": math.Exp, "math.Exp2": math.Exp2, "math.Expm1": math.Expm1, "math.FMA": math.FMA, "math.Float32bits": math.Float32bits, "math.Float32frombits": math.Float32frombits, "math.Float64bits": math.Float64bits, "math.Float64frombits": math.Float64frombits, "math.Floor": math.Floor, "math.Frexp": math.Frexp, "math.Gamma": math.Gamma, "math.Hypot": math.Hypot, "math.Ilogb": math.Ilogb, "math.Inf": math.Inf, "math.IsInf": math.IsInf, "math.IsNaN": math.IsNaN, "math.J0": math.J0, "math.J1": math.J1, "math.Jn": math.Jn, "math.Ldexp": math.Ldexp, "math.Lgamma": math.Lgamma, "math.Log": math.Log, "math.Log10": math.Log10, "math.Log1p": math.Log1p, "math.Log2": math.Log2, "math.Logb": math.Logb, "math.Max": math.Max, "math.Min": math.Min, "math.Mod": math.Mod, "math.Modf": math.Modf, "math.NaN": math.NaN, "math.Nextafter": math.Nextafter, "math.Nextafter32": math.Nextafter32, "math.Pow": math.Pow, "math.Pow10": math.Pow10, "math.Remainder": math.Remainder, "math.Round": math.Round, "math.RoundToEven": math.RoundToEven, "math.Signbit": math.Signbit, "math.Sin": math.Sin, "math.Sincos": math.Sincos, "math.Sinh": math.Sinh, "math.Sqrt": math.Sqrt, "math.Tan": math.Tan, "math.Tanh": math.Tanh, "math.Trunc": math.Trunc, "math.Y0": math.Y0, "math.Y1": math.Y1, "math.Yn": math.Yn, } var typList = []interface{}{}
pkg/math/export.go
0.52829
0.496399
export.go
starcoder
package geos /* #include "geos.h" */ import "C" // GeometryType represents the various geometry types supported by GEOS, and // correspond to OGC Simple Features geometry types. type GeometryType C.int const ( // POINT is a 0-dimensional geometric object, a single location is geometric // space. POINT GeometryType = C.GEOS_POINT // LINESTRING is a curve with linear interpolation between points. LINESTRING GeometryType = C.GEOS_LINESTRING // LINEARRING is a linestring that is both closed and simple. LINEARRING GeometryType = C.GEOS_LINEARRING // POLYGON is a planar surface with 1 exterior boundary and 0 or more // interior boundaries. POLYGON GeometryType = C.GEOS_POLYGON // MULTIPOINT is a 0-dimensional geometry collection, the elements of which // are restricted to points. MULTIPOINT GeometryType = C.GEOS_MULTIPOINT // MULTILINESTRING is a 1-dimensional geometry collection, the elements of // which are restricted to linestrings. MULTILINESTRING GeometryType = C.GEOS_MULTILINESTRING // MULTIPOLYGON is a 2-dimensional geometry collection, the elements of // which are restricted to polygons. MULTIPOLYGON GeometryType = C.GEOS_MULTIPOLYGON // GEOMETRYCOLLECTION is a geometric object that is a collection of some // number of geometric objects. GEOMETRYCOLLECTION GeometryType = C.GEOS_GEOMETRYCOLLECTION ) var cGeomTypeIds = map[C.int]GeometryType{ C.GEOS_POINT: POINT, C.GEOS_LINESTRING: LINESTRING, C.GEOS_LINEARRING: LINEARRING, C.GEOS_POLYGON: POLYGON, C.GEOS_MULTIPOINT: MULTIPOINT, C.GEOS_MULTILINESTRING: MULTILINESTRING, C.GEOS_MULTIPOLYGON: MULTIPOLYGON, C.GEOS_GEOMETRYCOLLECTION: GEOMETRYCOLLECTION, } var geometryTypes = map[GeometryType]string{ POINT: "Point", LINESTRING: "LineString", LINEARRING: "LinearRing", POLYGON: "Polygon", MULTIPOINT: "MultiPoint", MULTILINESTRING: "MultiLineString", MULTIPOLYGON: "MultiPolygon", GEOMETRYCOLLECTION: "GeometryCollection", } func (t GeometryType) String() string { return geometryTypes[t] }
vendor/github.com/paulsmith/gogeos/geos/types.go
0.694406
0.41478
types.go
starcoder
package chess import ( "encoding/json" "fmt" "math/rand" "sort" "strconv" "time" ) //Get Next move using mini max algorithm func GetNextMoveUsingMiniMax(dat []string, prev_move string) string { var move string var stats string active_color := "b" node := createChessNodeUsingArray(dat, active_color, prev_move) move, stats = miniMaxDecision(node) return move + "," + stats } // Get Next Move based on minimizing opponent material value // - calculate all possible legal moves // - construct the resulting board position for each move // - sum the material value of each piece // - return the move that minimizes the total material value of opponent func GetNextMoveUsingPointValue(dat []string) string { var move string node := createChessNodeUsingArray(dat, "", "") node.legal_moves = getLegalMoves("b", node.board) //printNode(node) if len(node.legal_moves) > 0 { for i := 0; i < len(node.legal_moves); i++ { newBoard := makeMove(node.board, node.legal_moves[i]) materialValue := calculatePointValue("w", newBoard) node.legal_moves[i].value = materialValue } moves := node.legal_moves sort.Sort(ByMaterialValue(moves)) //after sorting, choose a random move that has the same minimum score minMove := moves[0] var j int for j = 0; j < len(moves); j++ { if moves[j].value > minMove.value { break } } randMove := node.legal_moves[rand.Intn(j)] move = formatNextMove(randMove) } return move } //define global variables var pieces = make(map[string]map[string]string) var initial_board_json string var number_of_nodes_per_depth = make(map[string]int) func init() { //set the random seed rand.Seed(time.Now().UTC().UnixNano()) //initialize the html and codepoint value for each piece pieces = map[string]map[string]string{ "wk": {"html": "&#9812;", "codepoint": "\u2654"}, "wq": {"html": "&#9813;", "codepoint": "\u2655"}, "wr": {"html": "&#9814;", "codepoint": "\u2656"}, "wb": {"html": "&#9815;", "codepoint": "\u2657"}, "wn": {"html": "&#9816;", "codepoint": "\u2658"}, "wp": {"html": "&#9817;", "codepoint": "\u2659"}, "bk": {"html": "&#9818;", "codepoint": "\u265A"}, "bq": {"html": "&#9819;", "codepoint": "\u265B"}, "br": {"html": "&#9820;", "codepoint": "\u265C"}, "bb": {"html": "&#9821;", "codepoint": "\u265D"}, "bn": {"html": "&#9822;", "codepoint": "\u265E"}, "bp": {"html": "&#9823;", "codepoint": "\u265F"}} //set the initial_board_json initial_board_json = "{\"a8\":\"br\",\"b8\":\"bn\",\"c8\":\"bb\",\"d8\":\"bq\",\"e8\":\"bk\",\"f8\":\"bb\",\"g8\":\"bn\",\"h8\":\"br\",\"a7\":\"bp\",\"b7\":\"bp\",\"c7\":\"bp\",\"d7\":\"bp\",\"e7\":\"bp\",\"f7\":\"bp\",\"g7\":\"bp\",\"h7\":\"bp\",\"a2\":\"wp\",\"b2\":\"wp\",\"c2\":\"wp\",\"d2\":\"wp\",\"e2\":\"wp\",\"f2\":\"wp\",\"g2\":\"wp\",\"h2\":\"wp\",\"a1\":\"wr\",\"b1\":\"wn\",\"c1\":\"wb\",\"d1\":\"wq\",\"e1\":\"wk\",\"f1\":\"wb\",\"g1\":\"wn\",\"h1\":\"wr\"}" } func pieceToUnicode(piece string) string { return pieces[piece]["codepoint"] } func formatNextMove(move Move) string { columns := "abcdefgh" fromSquare := string(columns[move.from.col]) + strconv.Itoa(move.from.row+1) toSquare := string(columns[move.to.col]) + strconv.Itoa(move.to.row+1) nextMove := fmt.Sprintf("\"next-move\":\"%s-%s\"", fromSquare, toSquare) return nextMove } func updateStats(state ChessNode, count int) { key := strconv.Itoa(state.depth) + opposite(state.active_color) number_of_nodes_per_depth[key] += count } func formatStats() string { data, err := json.Marshal(number_of_nodes_per_depth) if err != nil { fmt.Println(err) return "" } stats := fmt.Sprintf("\"stats\":%s", string(data)) return stats } func calculatePointValue(color string, board [8][8]string) int { //sum up the point values of all of the chess pieces for this color //part of the utility/evaulation function //f(p) = 200(K-K') // + 9(Q-Q') // + 5(R-R') // + 3(B-B' + N-N') // + 1(P-P') sum := 0 sum2 := 0 color2 := opposite(color) for row := 7; row >= 0; row-- { for col := 0; col < 8; col++ { piece := board[row][col] if piece == "0" { continue } else if piece[0:1] == color { sum = sum + pieceValue(piece[1:2]) } else if piece[0:1] == color2 { sum2 = sum2 + pieceValue(piece[1:2]) } } } return sum - sum2 } func calculateMobility(color string, board [8][8]string) int { //count the number of legal moves //part of the utility/evaluation function //(M-M') M = Mobility (the number of legal moves) moves := getLegalMoves(color, board) color2 := opposite(color) moves2 := getLegalMoves(color2, board) return len(moves) - len(moves2) } func pieceValue(piece_type string) int { switch piece_type { case "p": return 1 case "n": return 3 case "b": return 3 case "r": return 5 case "q": return 9 case "k": return 200 // TODO research default: return 0 } } type ByMaterialValue []Move func (a ByMaterialValue) Len() int { return len(a) } func (a ByMaterialValue) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByMaterialValue) Less(i, j int) bool { return a[i].value < a[j].value }
go/src/chess/ai.go
0.609059
0.413951
ai.go
starcoder
package httproutegen import ( "errors" "log" ) const boundaryOfSequenceNumber = 0x9D // SymbolType represent type of symbol. type SymbolType int // Symbol types const ( SymbolTypeNoop SymbolType = iota SymbolTypeByte SymbolTypeSequence ) // Symbol represent one input byte or variable. type Symbol struct { Type SymbolType `json:"symbol_type"` ByteValue byte `json:"byte_value,omitempty"` SequenceValue *SequencePart `json:"sequence_value,omitempty"` SequenceIndex int `json:"sequence_index,omitempty"` SequenceVarName string `json:"sequence_variable,omitempty"` } // ByteCode is code to represent the symbol in sequence. func (sym *Symbol) ByteCode() byte { switch sym.Type { case SymbolTypeNoop: return 0xFE case SymbolTypeByte: return sym.ByteValue - ' ' case SymbolTypeSequence: if sym.SequenceIndex > boundaryOfSequenceNumber { log.Printf("ERROR: sequence index > 0x%02X: %#v", boundaryOfSequenceNumber, sym) return 0xFF } return 0x60 + byte(sym.SequenceIndex) } return 0xFF } // NoopSymbol is an instance of NOOP symbol. var NoopSymbol = Symbol{ Type: SymbolTypeNoop, } func newByteSymbol(b byte) Symbol { return Symbol{ Type: SymbolTypeByte, ByteValue: b, } } func newSequenceSymbol(value *SequencePart, index int, variableName string) Symbol { return Symbol{ Type: SymbolTypeSequence, SequenceValue: value, SequenceIndex: index, SequenceVarName: variableName, } } // SymbolScope represent one shared space of symbol parsing operation. type SymbolScope struct { FoundSequences []*SequencePart `json:"found_sequences"` } func (scope *SymbolScope) attachSequencePart(seqPart *SequencePart) (int, *SequencePart) { for idx, part := range scope.FoundSequences { if part.Equal(seqPart) { part.AttachVariableName(seqPart.VariableName) return idx, part } } scope.FoundSequences = append(scope.FoundSequences, seqPart) return len(scope.FoundSequences) - 1, seqPart } // ParseComponent parse given bytes as component. func (scope *SymbolScope) ParseComponent(c []byte) (result []Symbol, err error) { for len(c) > 0 { if ch := c[0]; ch == '{' { seqPart := &SequencePart{} nextIdx, err := seqPart.setSeqence(c) if nil != err { log.Printf("ERROR: failed on set sequence to part: %v", string(c)) return nil, err } varName := seqPart.VariableName seqIndex, seqPart := scope.attachSequencePart(seqPart) result = append(result, newSequenceSymbol(seqPart, seqIndex, varName)) if nextIdx < len(c) { c = c[nextIdx:] } else { c = nil } } else if ch == '\\' { if len(c) < 2 { err = errors.New("escape at end of component") return } ch = c[1] result = append(result, newByteSymbol(ch)) c = c[2:] } else { result = append(result, newByteSymbol(ch)) if len(c) > 1 { c = c[1:] } else { c = nil } } } return }
httproutegen/symbol.go
0.627152
0.411052
symbol.go
starcoder
package esquery import ( "github.com/fatih/structs" ) type matchType uint8 const ( // TypeMatch denotes a query of type "match" TypeMatch matchType = iota // TypeMatchBool denotes a query of type "match_bool_prefix" TypeMatchBoolPrefix // TypeMatchPhrase denotes a query of type "match_phrase" TypeMatchPhrase // TypeMatchPhrasePrefix denotes a query of type "match_phrase_prefix" TypeMatchPhrasePrefix ) // MatchQuery represents a query of type "match", "match_bool_prefix", // "match_phrase" and "match_phrase_prefix". While all four share the same // general structure, they don't necessarily support all the same options. The // library does not attempt to verify provided options are supported. // See the ElasticSearch documentation for more information: // - https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query.html // - https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-bool-prefix-query.html // - https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query-phrase.html // - https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query-phrase-prefix.html type MatchQuery struct { field string mType matchType params matchParams } // Map returns a map representation of the query, thus implementing the // Mappable interface. func (q *MatchQuery) Map() map[string]interface{} { var mType string switch q.mType { case TypeMatch: mType = "match" case TypeMatchBoolPrefix: mType = "match_bool_prefix" case TypeMatchPhrase: mType = "match_phrase" case TypeMatchPhrasePrefix: mType = "match_phrase_prefix" } return map[string]interface{}{ mType: map[string]interface{}{ q.field: structs.Map(q.params), }, } } type matchParams struct { Qry interface{} `structs:"query"` Anl string `structs:"analyzer,omitempty"` AutoGenerate *bool `structs:"auto_generate_synonyms_phrase_query,omitempty"` Fuzz string `structs:"fuzziness,omitempty"` MaxExp uint16 `structs:"max_expansions,omitempty"` PrefLen uint16 `structs:"prefix_length,omitempty"` Trans *bool `structs:"transpositions,omitempty"` FuzzyRw string `structs:"fuzzy_rewrite,omitempty"` Lent bool `structs:"lenient,omitempty"` Op MatchOperator `structs:"operator,string,omitempty"` MinMatch string `structs:"minimum_should_match,omitempty"` ZeroTerms ZeroTerms `structs:"zero_terms_query,string,omitempty"` Slp uint16 `structs:"slop,omitempty"` // only relevant for match_phrase query Boost float32 `structs:"boost,omitempty"` } // Match creates a new query of type "match" with the provided field name. // A comparison value can optionally be provided to quickly create a simple // query such as { "match": { "message": "this is a test" } } func Match(fieldName string, simpleQuery ...interface{}) *MatchQuery { return newMatch(TypeMatch, fieldName, simpleQuery...) } // MatchBoolPrefix creates a new query of type "match_bool_prefix" with the // provided field name. A comparison value can optionally be provided to quickly // create a simple query such as { "match": { "message": "this is a test" } } func MatchBoolPrefix(fieldName string, simpleQuery ...interface{}) *MatchQuery { return newMatch(TypeMatchBoolPrefix, fieldName, simpleQuery...) } // MatchPhrase creates a new query of type "match_phrase" with the // provided field name. A comparison value can optionally be provided to quickly // create a simple query such as { "match": { "message": "this is a test" } } func MatchPhrase(fieldName string, simpleQuery ...interface{}) *MatchQuery { return newMatch(TypeMatchPhrase, fieldName, simpleQuery...) } // MatchPhrasePrefix creates a new query of type "match_phrase_prefix" with the // provided field name. A comparison value can optionally be provided to quickly // create a simple query such as { "match": { "message": "this is a test" } } func MatchPhrasePrefix(fieldName string, simpleQuery ...interface{}) *MatchQuery { return newMatch(TypeMatchPhrasePrefix, fieldName, simpleQuery...) } func newMatch(mType matchType, fieldName string, simpleQuery ...interface{}) *MatchQuery { var qry interface{} if len(simpleQuery) > 0 { qry = simpleQuery[len(simpleQuery)-1] } return &MatchQuery{ field: fieldName, mType: mType, params: matchParams{ Qry: qry, }, } } // Query sets the data to find in the query's field (it is the "query" component // of the query). func (q *MatchQuery) Query(data interface{}) *MatchQuery { q.params.Qry = data return q } // Analyzer sets the analyzer used to convert the text in the "query" value into // tokens. func (q *MatchQuery) Analyzer(a string) *MatchQuery { q.params.Anl = a return q } // AutoGenerateSynonymsPhraseQuery sets the "auto_generate_synonyms_phrase_query" // boolean. func (q *MatchQuery) AutoGenerateSynonymsPhraseQuery(b bool) *MatchQuery { q.params.AutoGenerate = &b return q } // Fuzziness set the maximum edit distance allowed for matching. func (q *MatchQuery) Fuzziness(f string) *MatchQuery { q.params.Fuzz = f return q } // MaxExpansions sets the maximum number of terms to which the query will expand. func (q *MatchQuery) MaxExpansions(e uint16) *MatchQuery { q.params.MaxExp = e return q } // PrefixLength sets the number of beginning characters left unchanged for fuzzy // matching. func (q *MatchQuery) PrefixLength(l uint16) *MatchQuery { q.params.PrefLen = l return q } // Transpositions sets whether edits for fuzzy matching include transpositions // of two adjacent characters. func (q *MatchQuery) Transpositions(b bool) *MatchQuery { q.params.Trans = &b return q } // FuzzyRewrite sets the method used to rewrite the query. func (q *MatchQuery) FuzzyRewrite(s string) *MatchQuery { q.params.FuzzyRw = s return q } // Lenient sets whether format-based errors should be ignored. func (q *MatchQuery) Lenient(b bool) *MatchQuery { q.params.Lent = b return q } // Operator sets the boolean logic used to interpret text in the query value. func (q *MatchQuery) Operator(op MatchOperator) *MatchQuery { q.params.Op = op return q } // MinimumShouldMatch sets the minimum number of clauses that must match for a // document to be returned. func (q *MatchQuery) MinimumShouldMatch(s string) *MatchQuery { q.params.MinMatch = s return q } // Slop sets the maximum number of positions allowed between matching tokens. func (q *MatchQuery) Slop(n uint16) *MatchQuery { q.params.Slp = n return q } // ZeroTermsQuery sets the "zero_terms_query" option to use. This indicates // whether no documents are returned if the analyzer removes all tokens, such as // when using a stop filter. func (q *MatchQuery) ZeroTermsQuery(s ZeroTerms) *MatchQuery { q.params.ZeroTerms = s return q } // Boost sets the boost value of the query. func (a *MatchQuery) Boost(b float32) *MatchQuery { a.params.Boost = b return a } // MatchOperator is an enumeration type representing supported values for a // match query's "operator" parameter. type MatchOperator uint8 const ( // OperatorOr is the "or" operator OperatorOr MatchOperator = iota // OperatorAnd is the "and" operator OperatorAnd ) // String returns a string representation of the match operator, as known to // ElasticSearch. func (a MatchOperator) String() string { switch a { case OperatorOr: return "OR" case OperatorAnd: return "AND" default: return "" } } // ZeroTerms is an enumeration type representing supported values for a match // query's "zero_terms_query" parameter. type ZeroTerms uint8 const ( // ZeroTermsNone is the "none" value ZeroTermsNone ZeroTerms = iota // ZeroTermsAll is the "all" value ZeroTermsAll ) // String returns a string representation of the zero_terms_query parameter, as // known to ElasticSearch. func (a ZeroTerms) String() string { switch a { case ZeroTermsNone: return "none" case ZeroTermsAll: return "all" default: return "" } }
query_match.go
0.875321
0.439386
query_match.go
starcoder
package ast import ( "encoding/json" "github.com/open-policy-agent/opa/util" ) // ValueMap represents a key/value map between AST term values. Any type of term // can be used as a key in the map. type ValueMap struct { hashMap *util.HashMap } // NewValueMap returns a new ValueMap. func NewValueMap() *ValueMap { vs := &ValueMap{ hashMap: util.NewHashMap(valueEq, valueHash), } return vs } // MarshalJSON provides a custom marshaller for the ValueMap which // will include the key, value, and value type. func (vs *ValueMap) MarshalJSON() ([]byte, error) { var tmp []map[string]interface{} vs.Iter(func(k Value, v Value) bool { tmp = append(tmp, map[string]interface{}{ "name": k.String(), "type": TypeName(v), "value": v, }) return false }) return json.Marshal(tmp) } // Copy returns a shallow copy of the ValueMap. func (vs *ValueMap) Copy() *ValueMap { if vs == nil { return nil } cpy := NewValueMap() cpy.hashMap = vs.hashMap.Copy() return cpy } // Equal returns true if this ValueMap equals the other. func (vs *ValueMap) Equal(other *ValueMap) bool { if vs == nil { return other == nil || other.Len() == 0 } if other == nil { return vs == nil || vs.Len() == 0 } return vs.hashMap.Equal(other.hashMap) } // Len returns the number of elements in the map. func (vs *ValueMap) Len() int { if vs == nil { return 0 } return vs.hashMap.Len() } // Get returns the value in the map for k. func (vs *ValueMap) Get(k Value) Value { if vs != nil { if v, ok := vs.hashMap.Get(k); ok { return v.(Value) } } return nil } // Hash returns a hash code for this ValueMap. func (vs *ValueMap) Hash() int { if vs == nil { return 0 } return vs.hashMap.Hash() } // Iter calls the iter function for each key/value pair in the map. If the iter // function returns true, iteration stops. func (vs *ValueMap) Iter(iter func(Value, Value) bool) bool { if vs == nil { return false } return vs.hashMap.Iter(func(kt, vt util.T) bool { k := kt.(Value) v := vt.(Value) return iter(k, v) }) } // Put inserts a key k into the map with value v. func (vs *ValueMap) Put(k, v Value) { if vs == nil { panic("put on nil value map") } vs.hashMap.Put(k, v) } // Delete removes a key k from the map. func (vs *ValueMap) Delete(k Value) { if vs == nil { return } vs.hashMap.Delete(k) } func (vs *ValueMap) String() string { if vs == nil { return "{}" } return vs.hashMap.String() } func valueHash(v util.T) int { return v.(Value).Hash() } func valueEq(a, b util.T) bool { av := a.(Value) bv := b.(Value) return av.Compare(bv) == 0 }
vendor/github.com/open-policy-agent/opa/ast/map.go
0.762601
0.433262
map.go
starcoder
package tfutil import ( "fmt" tf "github.com/tensorflow/tensorflow/tensorflow/go" "github.com/tensorflow/tensorflow/tensorflow/go/op" ) // Sub fetches sub a new tensor without altering original. // startIndices if nil is set to a slice // of zeros indicating starting from the beginning of the tensor. Length of // such slice is always equal to the receiver dimension indicating start // value for each dimension. //Similarly, endLengths indicate end value similar // to how a sub slicing end index works. if endLengths is nil, it is set // to the shape slice of the receiver tensor. //strides are jumps and if nil is set to slice of ones. // The lengths of each of these inputs is, therefore, either nil or // equal to the length of the shape of the receiver tensor func (g *Tensor[T]) Sub(start, end, stride []int) (*Tensor[T], error) { if start == nil { start = make([]int, len(g.shape)) } if end == nil { end = g.shape } if stride == nil { stride = make([]int, len(g.shape)) for i := range stride { stride[i] = 1 } } if len(start) != len(g.shape) || len(end) != len(g.shape) || len(stride) != len(g.shape) { return nil, fmt.Errorf("inputs should either be nil or have lengths equal to %d", len(g.shape)) } x, err := g.Marshal() if err != nil { return nil, fmt.Errorf("failed to get tf tensor: %w", err) } startTensor, err := tf.NewTensor(castToInt64(start)) if err != nil { return nil, fmt.Errorf("failed to get tf tensor: %w", err) } endTensor, err := tf.NewTensor(castToInt64(end)) if err != nil { return nil, fmt.Errorf("failed to get tf tensor: %w", err) } strideTensor, err := tf.NewTensor(castToInt64(stride)) if err != nil { return nil, fmt.Errorf("failed to get tf tensor: %w", err) } root := op.NewScope() X := op.Placeholder( root.SubScope("X"), x.DataType(), op.PlaceholderShape( tf.MakeShape(castToInt64(g.shape)...), ), ) Start := op.Placeholder( root.SubScope("Start"), startTensor.DataType(), op.PlaceholderShape( tf.MakeShape(int64(len(start))), ), ) End := op.Placeholder( root.SubScope("End"), startTensor.DataType(), op.PlaceholderShape( tf.MakeShape(int64(len(end))), ), ) Stride := op.Placeholder( root.SubScope("Stride"), startTensor.DataType(), op.PlaceholderShape( tf.MakeShape(int64(len(stride))), ), ) // define operation Output := op.StridedSlice(root, X, Start, End, Stride) graph, err := root.Finalize() if err != nil { return nil, fmt.Errorf("failed to import graph: %w", err) } feeds := map[tf.Output]*tf.Tensor{ X: x, Start: startTensor, End: endTensor, Stride: strideTensor, } fetches := []tf.Output{ Output, } sess, err := tf.NewSession( graph, &tf.SessionOptions{}, ) if err != nil { return nil, fmt.Errorf("failed to create new tf session: %w", err) } defer func(sess *tf.Session) { err := sess.Close() if err != nil { panic(err) } }(sess) out, err := sess.Run(feeds, fetches, nil) if err != nil { return nil, fmt.Errorf("failed to run tf session: %w", err) } if len(out) != 1 { return nil, fmt.Errorf("expected session run output to have length 1, got %d", len(out)) } output := &Tensor[T]{} if err := output.Unmarshal(out[0]); err != nil { return nil, fmt.Errorf("failed to unmarshal output: %w", err) } return output, nil }
pkg/tfutil/subtensor.go
0.843573
0.553143
subtensor.go
starcoder
package vme import ( "encoding/binary" "errors" "github.com/coschain/contentos-go/common" "reflect" "unsafe" ) func decodeBool(data []byte) (bool, int) { if len(data) >= 1 { return data[0] != 0, 1 } return false, 0 } func decodeInt8(data []byte) (int8, int) { if len(data) >= 1 { return int8(data[0]), 1 } return 0, 0 } func decodeInt16(data []byte) (int16, int) { if len(data) >= 2 { return int16(common.HostByteOrder().Uint16(data)), 2 } return 0, 0 } func decodeInt32(data []byte) (int32, int) { if len(data) >= 4 { return int32(common.HostByteOrder().Uint32(data)), 4 } return 0, 0 } func decodeInt64(data []byte) (int64, int) { if len(data) >= 8 { return int64(common.HostByteOrder().Uint64(data)), 8 } return 0, 0 } func decodeInt(data []byte) (int, int) { if common.Is32bitPlatform { if v, n := decodeInt32(data); n > 0 { return int(v), n } else { return 0, 0 } } else { if v, n := decodeInt64(data); n > 0 { return int(v), n } else { return 0, 0 } } } func decodeUint8(data []byte) (uint8, int) { if len(data) >= 1 { return data[0], 1 } return 0, 0 } func decodeUint16(data []byte) (uint16, int) { if len(data) >= 2 { return common.HostByteOrder().Uint16(data), 2 } return 0, 0 } func decodeUint32(data []byte) (uint32, int) { if len(data) >= 4 { return common.HostByteOrder().Uint32(data), 4 } return 0, 0 } func decodeUint64(data []byte) (uint64, int) { if len(data) >= 8 { return common.HostByteOrder().Uint64(data), 8 } return 0, 0 } func decodeUint(data []byte) (uint, int) { if common.Is32bitPlatform { if v, n := decodeUint32(data); n > 0 { return uint(v), n } else { return 0, 0 } } else { if v, n := decodeUint64(data); n > 0 { return uint(v), n } else { return 0, 0 } } } func decodeFloat32(data []byte) (float32, int) { if len(data) >= 4 { x := common.HostByteOrder().Uint32(data) return *(*float32)(unsafe.Pointer(&x)), 4 } return 0, 0 } func decodeFloat64(data []byte) (float64, int) { if len(data) >= 8 { x := common.HostByteOrder().Uint64(data) return *(*float64)(unsafe.Pointer(&x)), 8 } return 0, 0 } func decodeCount(data []byte) (uint64, int) { return binary.Uvarint(data) } func decodeString(data []byte) (string, int) { count, offset := decodeCount(data) if offset <= 0 { return "", 0 } strSize, dataSize := int(count), len(data) if offset <= dataSize && strSize >= 0 && strSize < dataSize && offset + strSize <= dataSize { return string(data[offset:offset + strSize]), offset + strSize } else { return "", 0 } } func decodeBytes(data []byte) ([]byte, int) { s, n := decodeString(data) if n > 0 { return []byte(s), n } else { return nil, 0 } } func decodeStruct(data []byte, typ reflect.Type) (interface{}, int) { count, offset := decodeCount(data) if offset <= 0 { return nil, 0 } size := int(count) rv := reflect.New(typ).Elem() for i := 0; i < size; i++ { dv, n := decodeValue(data[offset:], typ.Field(i).Type) if n <= 0 { return nil, n } rv.Field(i).Set(reflect.ValueOf(dv)) offset += n } return rv.Interface(), offset } func decodeSlice(data []byte, typ reflect.Type) (interface{}, int) { count, offset := decodeCount(data) if offset <= 0 { return nil, 0 } size := int(count) rv := reflect.MakeSlice(reflect.SliceOf(typ), size, size) for i := 0; i < size; i++ { dv, n := decodeValue(data[offset:], typ) if n <= 0 { return nil, n } rv.Index(i).Set(reflect.ValueOf(dv)) offset += n } return rv.Interface(), offset } func decodeValue(data []byte, typ reflect.Type) (interface{}, int) { switch typ.Kind() { case reflect.Bool: return decodeBool(data) case reflect.Int: return decodeInt(data) case reflect.Int8: return decodeInt8(data) case reflect.Int16: return decodeInt16(data) case reflect.Int32: return decodeInt32(data) case reflect.Int64: return decodeInt64(data) case reflect.Uint: return decodeUint(data) case reflect.Uint8: return decodeUint8(data) case reflect.Uint16: return decodeUint16(data) case reflect.Uint32: return decodeUint32(data) case reflect.Uint64: return decodeUint64(data) case reflect.Float32: return decodeFloat32(data) case reflect.Float64: return decodeFloat64(data) case reflect.String: return decodeString(data) case reflect.Slice: et := typ.Elem() if et.Kind() == reflect.Uint8 { return decodeBytes(data) } else { return decodeSlice(data, et) } case reflect.Struct: return decodeStruct(data, typ) } return nil, -1 } func decodingError(n int, typ reflect.Type) error { if n == 0 { return errors.New("vme: Invalid encoded data.") } else if n < 0 { return errors.New("vme: Unsupported data type: " + typ.String()) } return nil } func Decode(data []byte, outPtr interface{}) error { out := reflect.ValueOf(outPtr) if out.Kind() != reflect.Ptr { return errors.New("vme: Decode() needs an output pointer.") } dt := out.Type().Elem() dv, n := decodeValue(data, dt) if n > 0 { out.Elem().Set(reflect.ValueOf(dv)) } return decodingError(n, dt) } func DecodeWithType(data []byte, valueType reflect.Type) (interface{}, error) { dv, n := decodeValue(data, valueType) return dv, decodingError(n, valueType) }
common/encoding/vme/decode.go
0.599368
0.403479
decode.go
starcoder
package yasup import ( crypto "crypto/rand" "math/big" "math/rand" ) var zeroValueFloat32 float32 //Float32Insert will append elem at the position i. Might return ErrIndexOutOfBounds. func Float32Insert(sl *[]float32, elem float32, i int) error { if i < 0 || i > len(*sl) { return ErrIndexOutOfBounds } *sl = append(*sl, elem) copy((*sl)[i+1:], (*sl)[i:]) (*sl)[i] = elem return nil } //Float32Delete delete the element at the position i. Might return ErrIndexOutOfBounds. func Float32Delete(sl *[]float32, i int) error { if i < 0 || i >= len(*sl) { return ErrIndexOutOfBounds } *sl = append((*sl)[:i], (*sl)[i+1:]...) return nil } //Float32Contains will return true if elem is present in the slice and false otherwise. func Float32Contains(sl []float32, elem float32) bool { for i := range sl { if sl[i] == elem { return true } } return false } //Float32Index returns the index of the first instance of elem, or -1 if elem is not present. func Float32Index(sl []float32, elem float32) int { for i := range sl { if sl[i] == elem { return i } } return -1 } //Float32LastIndex returns the index of the last instance of elem in the slice, or -1 if elem is not present. func Float32LastIndex(sl []float32, elem float32) int { for i := len(sl) - 1; i >= 0; i-- { if sl[i] == elem { return i } } return -1 } //Float32Count will return an int representing the amount of times that elem is present in the slice. func Float32Count(sl []float32, elem float32) int { var n int for i := range sl { if sl[i] == elem { n++ } } return n } //Float32Push is equivalent to Float32Insert with index len(*sl). func Float32Push(sl *[]float32, elem float32) { Float32Insert(sl, elem, len(*sl)) } //Float32FrontPush is equivalent to Float32Insert with index 0. func Float32FrontPush(sl *[]float32, elem float32) { Float32Insert(sl, elem, 0) } //Float32Pop is equivalent to getting and removing the last element of the slice. Might return ErrEmptySlice. func Float32Pop(sl *[]float32) (float32, error) { if len(*sl) == 0 { return zeroValueFloat32, ErrEmptySlice } last := len(*sl) - 1 ret := (*sl)[last] Float32Delete(sl, last) return ret, nil } //Float32Pop is equivalent to getting and removing the first element of the slice. Might return ErrEmptySlice. func Float32FrontPop(sl *[]float32) (float32, error) { if len(*sl) == 0 { return zeroValueFloat32, ErrEmptySlice } ret := (*sl)[0] Float32Delete(sl, 0) return ret, nil } //Float32Replace modifies the slice with the first n non-overlapping instances of old replaced by new. If n equals -1, there is no limit on the number of replacements. func Float32Replace(sl []float32, old, new float32, n int) (replacements int) { left := n for i := range sl { if left == 0 { break // no replacements left } if sl[i] == old { sl[i] = new left-- } } return n - left } //Float32ReplaceAll is equivalent to Float32Replace with n = -1. func Float32ReplaceAll(sl []float32, old, new float32) (replacements int) { return Float32Replace(sl, old, new, -1) } //Float32Equals compares two float32 slices. Returns true if their elements are equal. func Float32Equals(a, b []float32) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } //Float32FastShuffle will randomly swap the float32 elements of a slice using math/rand (fast but not cryptographycally secure). func Float32FastShuffle(sp []float32) { rand.Shuffle(len(sp), func(i, j int) { sp[i], sp[j] = sp[j], sp[i] }) } //Float32SecureShuffle will randomly swap the float32 elements of a slice using crypto/rand (resource intensive but cryptographically secure). func Float32SecureShuffle(sp []float32) error { var i int64 size := int64(len(sp)) - 1 for i = 0; i < size+1; i++ { bigRandI, err := crypto.Int(crypto.Reader, big.NewInt(size)) if err != nil { return err } randI := bigRandI.Int64() sp[size-i], sp[randI] = sp[randI], sp[size-i] } return nil }
float32Slices.go
0.721154
0.459319
float32Slices.go
starcoder
package clickgame import ( "mcs/pkg/chaingame" ) // A Hand stores legal moves. type Hand chaingame.ColorTiles // Draw randomly removes a move from the hand. func (h Hand) Draw() (Move, Hand) { tiles := chaingame.ColorTiles(h) tile := tiles.PickTile(chaingame.NoColor) return Move(tile), Hand(tiles) } // Len returns the number of available legal moves. func (h Hand) Len() int { return chaingame.ColorTiles(h).Len(chaingame.AllColors) } // List returns a list containing all legal moves. func (h Hand) List() []Move { moves := make([]Move, 0, h.Len()) tiles := chaingame.ColorTiles(h).Tiles(chaingame.AllColors) for _, tile := range tiles { moves = append(moves, Move(tile)) } return moves } // A Move is a tile that can be removed from a board. type Move chaingame.Tile // Len returns the number of blocks of the calling tile. func (m Move) Len() int { return len(chaingame.Tile(m)) } // Score computes the samegame score of a move. func (m Move) Score() float64 { return 0 } func (m Move) String() string { return chaingame.Tile(m).String() } // A Sequence of moves is a FIFO structure. type Sequence []Move // Enqueue adds a move in a sequence. func (moves Sequence) Enqueue(m Move) Sequence { if m.Len() == 0 { return moves } return append(moves, m) } // Clone returns an independent copy of a sequence. func (moves Sequence) Clone() Sequence { clone := make(Sequence, len(moves)) copy(clone, moves) return clone } // Join aggregates two sequences. func (moves Sequence) Join(seq Sequence) Sequence { return append(moves, seq...) } // Len is the number of moves in a sequence. func (moves Sequence) Len() int { return len(moves) } // Dequeue returns the next move in a sequence. func (moves Sequence) Dequeue() (Move, Sequence) { move, moves := moves[0], moves[1:] return move, moves } // A State describes the board. type State ClickBoard // Clone returns an independent copy. func (sg State) Clone() State { return State(ClickBoard(sg).Clone()) } // Moves returns the legal moves. func (sg State) Moves() Hand { return Hand(ClickBoard(sg).ColorTiles()) } // Play returns the state following a ply. func (sg State) Play(m Move) State { return State(ClickBoard(sg).Remove(chaingame.Tile(m))) } // Sample simulates a game to its end by applying a move selection policy. The policy usually // embeds randomness. func (sg State) Sample(done <-chan struct{}, p ColorPolicy) (float64, Sequence) { board := ClickBoard(sg) tiles := board.ColorTiles() taboo := chaingame.NoColor if c, mode := p(board); mode == PerSampling { taboo = c } var score float64 var seq Sequence for len(tiles) > 0 { select { case <-done: return score, seq default: if c, mode := p(board); mode == PerMove { taboo = c } tile := tiles.RandomTile(taboo) board = board.Remove(tile) tiles = board.ColorTiles() move := Move(tile) seq = seq.Enqueue(move) score += move.Score() } } score += State(board).Score() return score, seq } // Score returns a statically computed score of the calling state. func (sg State) Score() float64 { dim := float64(ClickBoard(sg).Cap()) penalty := 0.0 for _, n := range ClickBoard(sg).Histogram { penalty += n } penalty = penalty / dim return 1 - penalty } func (sg State) String() string { return ClickBoard(sg).String() }
games/clickomania/iface.go
0.884713
0.495789
iface.go
starcoder
package chromath // Gamma22 is the most common defintion for a RGB transform gamma of 2.2 const Gamma22 = 563 / 256.0 // An RGBSpace defines the parameters necessary for transforming most commonly defined RGB working // spaces into XYZ. The definition includes the affine linear RGB to XYZ transform, a reference to // an implementation of a compander from working RGB to linear RGB and type RGBSpace struct { // Name is a short, common name for the working space Name string // Description can provide more specific reference to a standard name and version of a standard Description string // XyYPrimary is a definition of the tristimulus primaries for the RGB space. The transformer will use this to generate a transform matrix. XyYPrimary XyYPrimary // IlluminantRef defines the default reference illuminant for this space. IlluminantRef *IlluminantRef // Gamma is the default gamma for this space. It's exact use depends on the type of Compander used Gamma Gamma // Compander refers to an implementation of the default linearization transform from the working space to linear RGB Compander Compander } // SpaceSRGB is the most commonly used sRGB RGB space as defined in IEC 61966-2-1:1999 var SpaceSRGB = RGBSpace{ "sRGB", "sRGB", XyYPrimary{ 0.6400, 0.3300, 0.3000, 0.6000, 0.1500, 0.0600, }, &IlluminantRefD65, Gamma22, &SRGBCompander, } var SpaceAdobeRGB = RGBSpace{ "Adobe RGB", "Adobe RGB (1998)", XyYPrimary{ 0.6400, 0.3300, 0.2100, 0.7100, 0.1500, 0.0600, }, &IlluminantRefD65, Gamma22, &GammaCompander, } var SpaceAppleRGB = RGBSpace{ "Apple RGB", "Apple RGB", XyYPrimary{ 0.6250, 0.3400, 0.2800, 0.5950, 0.1550, 0.0700, }, &IlluminantRefD65, 1.8, &GammaCompander, } var SpaceBestRGB = RGBSpace{ "Best RGB", "Best RGB", XyYPrimary{ 0.7347, 0.2653, 0.2150, 0.7750, 0.1300, 0.0350, }, &IlluminantRefD50, Gamma22, &GammaCompander, } var SpaceBetaRGB = RGBSpace{ "Beta RGB", "Beta RGB", XyYPrimary{ 0.6888, 0.3112, 0.1986, 0.7551, 0.1265, 0.0352, }, &IlluminantRefD50, Gamma22, &GammaCompander, } var SpaceBruceRGB = RGBSpace{ "Bruce RGB", "Bruce RGB", XyYPrimary{ 0.6400, 0.3300, 0.2800, 0.6500, 0.1500, 0.0600, }, &IlluminantRefD65, Gamma22, &GammaCompander, } var SpaceCIERGB = RGBSpace{ "CIE RGB", "CIE RGB", XyYPrimary{ 0.7350, 0.2650, 0.2740, 0.7170, 0.1670, 0.0090, }, &IlluminantRefE, Gamma22, &GammaCompander, } var SpaceColorMatchRGB = RGBSpace{ "ColorMatch RGB", "ColorMatch RGB", XyYPrimary{ 0.6300, 0.3400, 0.2950, 0.6050, 0.1500, 0.0750, }, &IlluminantRefD50, 1.8, &GammaCompander, } var SpaceECIRGB = RGBSpace{ "ECI RGB", "ECI RGB v2", XyYPrimary{ 0.6700, 0.3300, 0.2100, 0.7100, 0.1400, 0.0800, }, &IlluminantRefD50, 0.0, &LstarCompander, } var SpaceNTSCRGB = RGBSpace{ "NTSC RGB", "NTSC (1953) RGB", XyYPrimary{ 0.6700, 0.3300, 0.2100, 0.7100, 0.1400, 0.0800, }, &IlluminantRefC, 2.2, &GammaCompander, } var SpacePALSECAMRGB = RGBSpace{ "PAL/SECAM RGB", "PAL/SECAM RGB", XyYPrimary{ 0.6400, 0.3300, 0.2900, 0.6000, 0.1500, 0.0600, }, &IlluminantRefD65, 2.2, &GammaCompander, } var SpaceProPhotoRGB = RGBSpace{ "ProPhoto RGB", "ProPhoto RGB", XyYPrimary{ 0.7347, 0.2653, 0.1596, 0.8404, 0.0366, 0.0001, }, &IlluminantRefD50, 1.8, &GammaCompander, } var SpaceSMPTECRGB = RGBSpace{ "SMPTE-C RGB", "SMPTE-C (NTSC 1987) RGB", XyYPrimary{ 0.6300, 0.3400, 0.3100, 0.5950, 0.1550, 0.0700, }, &IlluminantRefD65, 2.2, &GammaCompander, } var SpaceUHDTVRGB = RGBSpace{ "UHDTV RGB", "UHDTV (ITU-R BT.2020) RGB", XyYPrimary{ 0.708, 0.292, 0.170, 0.797, 0.131, 0.046, }, &IlluminantRefD65, 2.4, &BT2020Compander, } var SpaceWideGamutRGB = RGBSpace{ "Wide Gamut RGB", "Adobe Wide Gamut RGB", XyYPrimary{ 0.7350, 0.2650, 0.1150, 0.8260, 0.1570, 0.0180, }, &IlluminantRefD50, 1.8, &GammaCompander, } // Observer is a type to indicate a colorimetry observer model type Observer int const ( // CIE2 indicates the CIE 1931 Standard 2° FOV observer CIE2 Observer = iota // CIE10 indicates the CIE 1931 Standard 10° FOV observer CIE10 ) // IlluminantRef defines a standard illuminant reference, for a specific standard observer type IlluminantRef struct { // XYZ specifies the CIE coordinates for the illuminant XYZ XYZ // Observer specifies the CIE observer Observer Observer // Standard provides an illuminant name and CCT (correlated color tempeature) Standard *IlluminantStd } // IlluminantStd defines a name, description and a CCT (correlated color temperature) for // a standard illuminant which may be modeled for various standard observers. type IlluminantStd struct { Name string Description string CCT int } // Illuminant variables provide descriptions of common CIE illuminants for use in conversion // working spaces. // IlluminantA is an illuminant to represent domestic tungsten-filament lighting. var IlluminantA = IlluminantStd{"A", "Incandescent / Tungsten", 2856} // IlluminantB is an noon sunlight simulation derived from Illuminant A var IlluminantB = IlluminantStd{"B", "Direct sunlight at noon (obsolete)", 4874} // IlluminantC is an averaged daylight simulation derived from Illuminant A var IlluminantC = IlluminantStd{"C", "Average / North sky Daylight (obsolete)", 6774} // IlluminantDxx are the most commonly used mathematically derived daylight simulation var ( IlluminantD50 = IlluminantStd{"D50", "Horizon Light, ICC profile PCS", 5003} IlluminantD55 = IlluminantStd{"D55", "Mid-morning / Mid-afternoon Daylight", 5503} IlluminantD65 = IlluminantStd{"D65", "Noon Daylight / Television / sRGB", 6504} IlluminantD75 = IlluminantStd{"D75", "North sky Daylight", 7504} ) // IlluminantE is an equal-energy radiator with constant spectral power density across the visible spectrum var IlluminantE = IlluminantStd{"E", "Equal energy", 5454} // IlluminantF series are fluorescent lighting var ( IlluminantF2 = IlluminantStd{"F2", "Cool White Fluorescent", 4230} IlluminantF7 = IlluminantStd{"F7", "D65 simulator / Daylight Simulator", 6500} IlluminantF11 = IlluminantStd{"F11", "Philips TL84, Ultralum 40", 4000} ) // IlluminantRef variables for CIE 1931 Standard (2°) observer illuminant tristimulus values var ( IlluminantRefA = IlluminantRef{XYZ{1.09850, 1.00000, 0.35585}, CIE2, &IlluminantA} IlluminantRefB = IlluminantRef{XYZ{0.99072, 1.00000, 0.85223}, CIE2, &IlluminantB} IlluminantRefC = IlluminantRef{XYZ{0.98074, 1.00000, 1.18232}, CIE2, &IlluminantC} IlluminantRefD50 = IlluminantRef{XYZ{0.96422, 1.00000, 0.82521}, CIE2, &IlluminantD50} IlluminantRefD55 = IlluminantRef{XYZ{0.95682, 1.00000, 0.92149}, CIE2, &IlluminantD55} IlluminantRefD65 = IlluminantRef{XYZ{0.95047, 1.00000, 1.08883}, CIE2, &IlluminantD65} IlluminantRefD75 = IlluminantRef{XYZ{0.94972, 1.00000, 1.22638}, CIE2, &IlluminantD75} IlluminantRefE = IlluminantRef{XYZ{1.00000, 1.00000, 1.00000}, CIE2, &IlluminantE} IlluminantRefF2 = IlluminantRef{XYZ{0.99186, 1.00000, 0.67393}, CIE2, &IlluminantF2} IlluminantRefF7 = IlluminantRef{XYZ{0.95041, 1.00000, 1.08747}, CIE2, &IlluminantF7} IlluminantRefF11 = IlluminantRef{XYZ{1.00962, 1.00000, 0.64350}, CIE2, &IlluminantF11} // Supplementary (10°) observer illuminant tristimulus values // source Berns 2000, and cross-checked with python-colormath IlluminantRefSuppA = IlluminantRef{XYZ{1.1114, 1.0000, 0.3520}, CIE10, &IlluminantA} IlluminantRefSuppC = IlluminantRef{XYZ{0.9728, 1.0000, 1.11614}, CIE10, &IlluminantC} IlluminantRefSuppD50 = IlluminantRef{XYZ{0.9672, 1.0000, 0.8143}, CIE10, &IlluminantD50} IlluminantRefSuppD55 = IlluminantRef{XYZ{0.9580, 1.0000, 0.9093}, CIE10, &IlluminantD55} IlluminantRefSuppD65 = IlluminantRef{XYZ{0.9481, 1.0000, 1.0730}, CIE10, &IlluminantD65} IlluminantRefSuppD75 = IlluminantRef{XYZ{0.94416, 1.0000, 1.2064}, CIE10, &IlluminantD75} IlluminantRefSuppF2 = IlluminantRef{XYZ{1.0328, 1.0000, 0.6902}, CIE10, &IlluminantF2} )
vendor/github.com/jkl1337/go-chromath/datum.go
0.670393
0.646823
datum.go
starcoder
package level // FloorInfo describes the properties of a floor. type FloorInfo byte // AbsoluteHeight returns the floor height in range of [0..TileHeightUnitMax-1]. func (info FloorInfo) AbsoluteHeight() TileHeightUnit { return TileHeightUnit(info & 0x1F) } // WithAbsoluteHeight returns a floor info that specifies the given absolute height. // The allowed range is [0..TileHeightUnitMax-1]. func (info FloorInfo) WithAbsoluteHeight(value TileHeightUnit) FloorInfo { return FloorInfo(byte(info&0xE0) | (byte(value) & 0x1F)) } // TextureRotations returns the rotation steps to apply for the floor texture. Valid range: [0..3]. func (info FloorInfo) TextureRotations() int { return int(info&0x60) >> 5 } // WithTextureRotations returns a floor info that specifies the given the rotation steps. // The provided value is normalized to the valid range. func (info FloorInfo) WithTextureRotations(value int) FloorInfo { normalized := (4 + (value % 4)) % 4 return FloorInfo(byte(info&^0x60) | byte(normalized)<<5) } // HasHazard returns true if the hazard flag is set. func (info FloorInfo) HasHazard() bool { return (byte(info) & 0x80) != 0 } // WithHazard returns a floor info with the hazard flag set according to given value. func (info FloorInfo) WithHazard(value bool) FloorInfo { var flag byte if value { flag = 0x80 } return FloorInfo(byte(info&^0x80) | flag) } // CeilingInfo describes the properties of a ceiling. type CeilingInfo byte // AbsoluteHeight returns the height (from minimum floor height zero) of the ceiling. // Internally, this value is stored "from maximum ceiling height 32" down. // The range is [1..TileHeightUnitMax]. func (info CeilingInfo) AbsoluteHeight() TileHeightUnit { value := info & 0x1F return TileHeightUnit(byte(TileHeightUnitMax) - byte(value)) } // WithAbsoluteHeight returns a ceiling info that specifies the given absolute height. // Internally, this value is stored "from maximum ceiling height 32" down. // The allowed range is [1..TileHeightUnitMax]. func (info CeilingInfo) WithAbsoluteHeight(value TileHeightUnit) CeilingInfo { return CeilingInfo(byte(info&0xE0) | (byte(TileHeightUnitMax-value) & 0x1F)) } // TextureRotations returns the rotation steps to apply for the ceiling texture. Valid range: [0..3]. func (info CeilingInfo) TextureRotations() int { return int(info&0x60) >> 5 } // WithTextureRotations returns a ceiling info that specifies the given the rotation steps. // The provided value is normalized to the valid range. func (info CeilingInfo) WithTextureRotations(value int) CeilingInfo { normalized := (4 + (value % 4)) % 4 return CeilingInfo(byte(info&^0x60) | byte(normalized)<<5) } // HasHazard returns true if the hazard flag is set. func (info CeilingInfo) HasHazard() bool { return (byte(info) & 0x80) != 0 } // WithHazard returns a ceiling info with the hazard flag set according to given value. func (info CeilingInfo) WithHazard(value bool) CeilingInfo { var flag byte if value { flag = 0x80 } return CeilingInfo(byte(info&^0x80) | flag) }
ss1/content/archive/level/FloorCeilingInfo.go
0.8959
0.585901
FloorCeilingInfo.go
starcoder
package graph import "time" /* A Port describes an instance of either an input or output port of a graph node. Input ports are where graph nodes receive data from. Output ports are where graph nodes send computed results through. Each input port can only be binded to a single output port. Each output port can be binded to multiple input ports. */ type Port struct { Data chan interface{} Name string bindings map[*Port]bool quit chan bool } /* Send the specified data through the port. This is a non-blocking call. If the port is an input port, then the specified data is queued in the data channel for the node function reading this input port. If the port is an output port, then the specified data is queued multiple times up to the number of other ports this output port is conncted to. Returns this port for chaining. */ func (p *Port) SendAsync(data interface{}) *Port { go func() { select { case p.Data <- data: case <-p.quit: } }() return p } /* Binds this port (assumed to be an output port) to send data to the specified destination port. Binding an input port to another port will give unintended results. Returns this port for chaining. */ func (p *Port) BindTo(dst *Port) *Port { p.bindings[dst] = true return p } /* Retrive the value sent to this port (assumed to be input port). Reading from an output port would dequeue the results. Note this is a blocking call. */ func (p *Port) Get() interface{} { return <-p.Data } /* Start go routines associated with this port. Returns this port for chaining. */ func (p *Port) Start() *Port { // Only spawn broadcaster if output port. if len(p.bindings) == 0 { return p } go func() { for { select { case d := <-p.Data: // If data comes in, re-broadcast it to the binding // ports. for dst := range p.bindings { go func(dst *Port) { select { case dst.Data <- d: case <-p.quit: } }(dst) } case <-p.quit: return } } }() return p } /* Shutdown this port. This is a blocking call. Returns this port for chaining. */ func (p *Port) Shutdown() *Port { for { select { case p.quit <- true: // Keep looping until quit exhausted determined by timeout. case <-time.After(100 * time.Millisecond): return p } } } /* Construct and return a new port. */ func CreatePort(name string) *Port { p := &Port{ Data: make(chan interface{}), Name: name, bindings: make(map[*Port]bool), quit: make(chan bool), } return p }
port.go
0.636127
0.516595
port.go
starcoder
package cast import ( "reflect" "strings" "github.com/cuigh/auxo/ext/reflects" ) func TryToValue(i interface{}, t reflect.Type) (v reflect.Value, err error) { var value interface{} if t == reflects.TypeDuration { value, err = TryToDuration(i) } else if t == reflects.TypeTime { value, err = TryToTime(i) } else { switch t.Kind() { case reflect.Bool: value, err = TryToBool(i) case reflect.String: value = ToString(i) case reflect.Int: value, err = TryToInt(i) case reflect.Int8: value, err = TryToInt8(i) case reflect.Int16: value, err = TryToInt16(i) case reflect.Int32: value, err = TryToInt32(i) case reflect.Int64: value, err = TryToInt64(i) case reflect.Uint: value, err = TryToUint(i) case reflect.Uint8: value, err = TryToUint8(i) case reflect.Uint16: value, err = TryToUint16(i) case reflect.Uint32: value, err = TryToUint32(i) case reflect.Uint64: value, err = TryToUint64(i) case reflect.Float32: value, err = TryToFloat32(i) case reflect.Float64: value, err = TryToFloat64(i) case reflect.Slice: return TryToSliceValue(i, t.Elem()) default: err = castError(i, t.String()) } } if err == nil { v = reflect.ValueOf(value).Convert(t) } return } // TryToSliceValue cast interface value to a slice. // Argument t is element type of slice. func TryToSliceValue(i interface{}, t reflect.Type) (slice reflect.Value, err error) { if s, ok := i.(string); ok { if s == "" { i = []string(nil) } else { i = strings.Split(s, ",") } } v := reflect.ValueOf(i) if v.Kind() != reflect.Slice { err = castError(i, "[]"+t.String()) return } if t == v.Type().Elem() { return v, nil } length := v.Len() slice = reflect.MakeSlice(reflect.SliceOf(t), length, length) for k := 0; k < length; k++ { var value reflect.Value value, err = TryToValue(v.Index(k).Interface(), t) if err != nil { return } slice.Index(k).Set(value) } return slice, nil } func TryToSlice(i interface{}, t reflect.Type) (interface{}, error) { v, err := TryToSliceValue(i, t) if err != nil { return nil, err } return v.Interface(), nil }
util/cast/reflect.go
0.526099
0.430506
reflect.go
starcoder
package solar import ( "image/color" "math" "github.com/golang/geo/r2" ) // DrawLine renders a line that moves back and forth type DrawLine struct { // where line starts startPosition r2.Point // where line neds endPosition r2.Point // time it takes for line to travel from start to end traverseTime float64 // position of the line along movement vector, 0 to 1 currentPosition r2.Point // normal direction of the line lineDirection r2.Point // width of the line lineWidth float64 // color of the line color color.RGBA // z position of ball zindex ZIndex } var _ Drawable = &DrawLine{} // NewLine Construct a circle func NewLine(solarSystem *System) *DrawLine { return &DrawLine{ startPosition: r2.Point{X: 0, Y: 0}, endPosition: r2.Point{X: 130, Y: 0}, traverseTime: 8.0, currentPosition: r2.Point{X: 0, Y: 0}, lineDirection: r2.Point{X: 1, Y: 0}, lineWidth: 12.0, color: color.RGBA{R: 255, G: 255, B: 0, A: 255}, zindex: 1, } } // Affects returns bounding circle check func (line *DrawLine) Affects(position r2.Point, radius float64) bool { distance := line.distanceToPoint(position) return (distance < line.lineWidth+radius) } // ColorAt Returns the color at position blended on top of baseColor func (line *DrawLine) ColorAt(position r2.Point, baseColor RGBA) (color RGBA) { distance := line.distanceToPoint(position) if distance > line.lineWidth { return baseColor } distance = distance / line.lineWidth color = RGBA{line.color.R, line.color.G, line.color.B, uint8((1.0 - distance) * 255.0)} result := color.BlendWith(baseColor) //fmt.Println(baseColor, color, result, position, distance, line.currentPosition) return result } // Computer distance from point to line https://brilliant.org/wiki/dot-product-distance-between-point-and-a-line/ func (line *DrawLine) distanceToPoint(position r2.Point) float64 { return math.Abs(position.Sub(line.currentPosition).Dot(line.lineDirection)) } // ZIndex of the circle func (line *DrawLine) ZIndex() ZIndex { return line.zindex } // Animate circle func (line *DrawLine) Animate(dt float64) bool { totalDistance := line.endPosition.Sub(line.startPosition).Norm() distance := line.currentPosition.Sub(line.startPosition).Norm() distance += (totalDistance / line.traverseTime) * dt //fmt.Println(distance, totalDistance, line.traverseTime) if distance > totalDistance { distance = 0.0 } moveDir := line.endPosition.Sub(line.startPosition).Normalize() line.currentPosition = moveDir.Mul(distance).Add(line.startPosition) //fmt.Println("Animated to ", line.currentPosition, dt) return true }
solar/drawLine.go
0.87068
0.555013
drawLine.go
starcoder
package engine // Add arbitrary terms to B_eff, Edens_total. import ( "fmt" "github.com/mumax/3cl/data" "github.com/mumax/3cl/opencl" "github.com/mumax/3cl/util" ) var ( B_custom = NewVectorField("B_custom", "T", "User-defined field", AddCustomField) Edens_custom = NewScalarField("Edens_custom", "J/m3", "Energy density of user-defined field.", AddCustomEnergyDensity) E_custom = NewScalarValue("E_custom", "J", "total energy of user-defined field", GetCustomEnergy) customTerms []Quantity // vector customEnergies []Quantity // scalar ) func init() { registerEnergy(GetCustomEnergy, AddCustomEnergyDensity) DeclFunc("AddFieldTerm", AddFieldTerm, "Add an expression to B_eff.") DeclFunc("AddEdensTerm", AddEdensTerm, "Add an expression to Edens.") DeclFunc("Add", Add, "Add two quantities") DeclFunc("Madd", Madd, "Weighted addition: Madd(Q1,Q2,c1,c2) = c1*Q1 + c2*Q2") DeclFunc("Dot", Dot, "Dot product of two vector quantities") DeclFunc("Cross", Cross, "Cross product of two vector quantities") DeclFunc("Mul", Mul, "Point-wise product of two quantities") DeclFunc("MulMV", MulMV, "Matrix-Vector product: MulMV(AX, AY, AZ, m) = (AX·m, AY·m, AZ·m)") DeclFunc("Div", Div, "Point-wise division of two quantities") DeclFunc("Const", Const, "Constant, uniform number") DeclFunc("ConstVector", ConstVector, "Constant, uniform vector") DeclFunc("Shifted", Shifted, "Shifted quantity") DeclFunc("Masked", Masked, "Mask quantity with shape") DeclFunc("RemoveCustomFields", RemoveCustomFields, "Removes all custom fields again") } //Removes all customfields func RemoveCustomFields() { customTerms = nil } // AddFieldTerm adds an effective field function (returning Teslas) to B_eff. // Be sure to also add the corresponding energy term using AddEnergyTerm. func AddFieldTerm(b Quantity) { customTerms = append(customTerms, b) } // AddEnergyTerm adds an energy density function (returning Joules/m³) to Edens_total. // Needed when AddFieldTerm was used and a correct energy is needed // (e.g. for Relax, Minimize, ...). func AddEdensTerm(e Quantity) { customEnergies = append(customEnergies, e) } // AddCustomField evaluates the user-defined custom field terms // and adds the result to dst. func AddCustomField(dst *data.Slice) { for _, term := range customTerms { buf := ValueOf(term) opencl.Add(dst, dst, buf) opencl.Recycle(buf) } } // Adds the custom energy densities (defined with AddCustomE func AddCustomEnergyDensity(dst *data.Slice) { for _, term := range customEnergies { buf := ValueOf(term) opencl.Add(dst, dst, buf) opencl.Recycle(buf) } } func GetCustomEnergy() float64 { buf := opencl.Buffer(1, Mesh().Size()) defer opencl.Recycle(buf) opencl.Zero(buf) AddCustomEnergyDensity(buf) return cellVolume() * float64(opencl.Sum(buf)) } type constValue struct { value []float64 } func (c *constValue) NComp() int { return len(c.value) } func (d *constValue) EvalTo(dst *data.Slice) { for c, v := range d.value { opencl.Memset(dst.Comp(c), float32(v)) } } // Const returns a constant (uniform) scalar quantity, // that can be used to construct custom field terms. func Const(v float64) Quantity { return &constValue{[]float64{v}} } // ConstVector returns a constant (uniform) vector quantity, // that can be used to construct custom field terms. func ConstVector(x, y, z float64) Quantity { return &constValue{[]float64{x, y, z}} } // fieldOp holds the abstract functionality for operations // (like add, multiply, ...) on space-dependend quantites // (like M, B_sat, ...) type fieldOp struct { a, b Quantity nComp int } func (o fieldOp) NComp() int { return o.nComp } type dotProduct struct { fieldOp } type crossProduct struct { fieldOp } type addition struct { fieldOp } type mAddition struct { fieldOp fac1, fac2 float64 } type mulmv struct { ax, ay, az, b Quantity } // MulMV returns a new Quantity that evaluates to the // matrix-vector product (Ax·b, Ay·b, Az·b). func MulMV(Ax, Ay, Az, b Quantity) Quantity { util.Argument(Ax.NComp() == 3 && Ay.NComp() == 3 && Az.NComp() == 3 && b.NComp() == 3) return &mulmv{Ax, Ay, Az, b} } func (q *mulmv) EvalTo(dst *data.Slice) { util.Argument(dst.NComp() == 3) opencl.Zero(dst) b := ValueOf(q.b) defer opencl.Recycle(b) { Ax := ValueOf(q.ax) opencl.AddDotProduct(dst.Comp(X), 1, Ax, b) opencl.Recycle(Ax) } { Ay := ValueOf(q.ay) opencl.AddDotProduct(dst.Comp(Y), 1, Ay, b) opencl.Recycle(Ay) } { Az := ValueOf(q.az) opencl.AddDotProduct(dst.Comp(Z), 1, Az, b) opencl.Recycle(Az) } } func (q *mulmv) NComp() int { return 3 } // DotProduct creates a new quantity that is the dot product of // quantities a and b. E.g.: // DotProct(&M, &B_ext) func Dot(a, b Quantity) Quantity { return &dotProduct{fieldOp{a, b, 1}} } func (d *dotProduct) EvalTo(dst *data.Slice) { A := ValueOf(d.a) defer opencl.Recycle(A) B := ValueOf(d.b) defer opencl.Recycle(B) opencl.Zero(dst) opencl.AddDotProduct(dst, 1, A, B) } // CrossProduct creates a new quantity that is the cross product of // quantities a and b. E.g.: // CrossProct(&M, &B_ext) func Cross(a, b Quantity) Quantity { return &crossProduct{fieldOp{a, b, 3}} } func (d *crossProduct) EvalTo(dst *data.Slice) { A := ValueOf(d.a) defer opencl.Recycle(A) B := ValueOf(d.b) defer opencl.Recycle(B) opencl.Zero(dst) opencl.CrossProduct(dst, A, B) } func Add(a, b Quantity) Quantity { if a.NComp() != b.NComp() { panic(fmt.Sprintf("Cannot point-wise Add %v components by %v components", a.NComp(), b.NComp())) } return &addition{fieldOp{a, b, a.NComp()}} } func (d *addition) EvalTo(dst *data.Slice) { A := ValueOf(d.a) defer opencl.Recycle(A) B := ValueOf(d.b) defer opencl.Recycle(B) opencl.Zero(dst) opencl.Add(dst, A, B) } type pointwiseMul struct { fieldOp } func Madd(a, b Quantity, fac1, fac2 float64) *mAddition { if a.NComp() != b.NComp() { panic(fmt.Sprintf("Cannot point-wise add %v components by %v components", a.NComp(), b.NComp())) } return &mAddition{fieldOp{a, b, a.NComp()}, fac1, fac2} } func (o *mAddition) EvalTo(dst *data.Slice) { A := ValueOf(o.a) defer opencl.Recycle(A) B := ValueOf(o.b) defer opencl.Recycle(B) opencl.Zero(dst) opencl.Madd2(dst, A, B, float32(o.fac1), float32(o.fac2)) } // Mul returns a new quantity that evaluates to the pointwise product a and b. func Mul(a, b Quantity) Quantity { nComp := -1 switch { case a.NComp() == b.NComp(): nComp = a.NComp() // vector*vector, scalar*scalar case a.NComp() == 1: nComp = b.NComp() // scalar*something case b.NComp() == 1: nComp = a.NComp() // something*scalar default: panic(fmt.Sprintf("Cannot point-wise multiply %v components by %v components", a.NComp(), b.NComp())) } return &pointwiseMul{fieldOp{a, b, nComp}} } func (d *pointwiseMul) EvalTo(dst *data.Slice) { opencl.Zero(dst) a := ValueOf(d.a) defer opencl.Recycle(a) b := ValueOf(d.b) defer opencl.Recycle(b) switch { case a.NComp() == b.NComp(): mulNN(dst, a, b) // vector*vector, scalar*scalar case a.NComp() == 1: mul1N(dst, a, b) case b.NComp() == 1: mul1N(dst, b, a) default: panic(fmt.Sprintf("Cannot point-wise multiply %v components by %v components", a.NComp(), b.NComp())) } } // mulNN pointwise multiplies two N-component vectors, // yielding an N-component vector stored in dst. func mulNN(dst, a, b *data.Slice) { opencl.Mul(dst, a, b) } // mul1N pointwise multiplies a scalar (1-component) with an N-component vector, // yielding an N-component vector stored in dst. func mul1N(dst, a, b *data.Slice) { util.Assert(a.NComp() == 1) util.Assert(dst.NComp() == b.NComp()) for c := 0; c < dst.NComp(); c++ { opencl.Mul(dst.Comp(c), a, b.Comp(c)) } } type pointwiseDiv struct { fieldOp } // Div returns a new quantity that evaluates to the pointwise product a and b. func Div(a, b Quantity) Quantity { nComp := -1 switch { case a.NComp() == b.NComp(): nComp = a.NComp() // vector/vector, scalar/scalar case b.NComp() == 1: nComp = a.NComp() // something/scalar default: panic(fmt.Sprintf("Cannot point-wise divide %v components by %v components", a.NComp(), b.NComp())) } return &pointwiseDiv{fieldOp{a, b, nComp}} } func (d *pointwiseDiv) EvalTo(dst *data.Slice) { a := ValueOf(d.a) defer opencl.Recycle(a) b := ValueOf(d.b) defer opencl.Recycle(b) switch { case a.NComp() == b.NComp(): divNN(dst, a, b) // vector*vector, scalar*scalar case b.NComp() == 1: divN1(dst, a, b) default: panic(fmt.Sprintf("Cannot point-wise divide %v components by %v components", a.NComp(), b.NComp())) } } func divNN(dst, a, b *data.Slice) { opencl.Div(dst, a, b) } func divN1(dst, a, b *data.Slice) { util.Assert(dst.NComp() == a.NComp()) util.Assert(b.NComp() == 1) for c := 0; c < dst.NComp(); c++ { opencl.Div(dst.Comp(c), a.Comp(c), b) } } type shifted struct { orig Quantity dx, dy, dz int } // Shifted returns a new Quantity that evaluates to // the original, shifted over dx, dy, dz cells. func Shifted(q Quantity, dx, dy, dz int) Quantity { util.Assert(dx != 0 || dy != 0 || dz != 0) return &shifted{q, dx, dy, dz} } func (q *shifted) EvalTo(dst *data.Slice) { orig := ValueOf(q.orig) defer opencl.Recycle(orig) for i := 0; i < q.NComp(); i++ { dsti := dst.Comp(i) origi := orig.Comp(i) if q.dx != 0 { opencl.ShiftX(dsti, origi, q.dx, 0, 0) } if q.dy != 0 { opencl.ShiftY(dsti, origi, q.dy, 0, 0) } if q.dz != 0 { opencl.ShiftZ(dsti, origi, q.dz, 0, 0) } } } func (q *shifted) NComp() int { return q.orig.NComp() } // Masks a quantity with a shape // The shape will be only evaluated once on the mesh, // and will be re-evaluated after mesh change, // because otherwise too slow func Masked(q Quantity, shape Shape) Quantity { return &masked{q, shape, nil, data.Mesh{}} } type masked struct { orig Quantity shape Shape mask *data.Slice mesh data.Mesh } func (q *masked) EvalTo(dst *data.Slice) { if q.mesh != *Mesh() { // When mesh is changed, mask needs an update q.createMask() } orig := ValueOf(q.orig) defer opencl.Recycle(orig) mul1N(dst, q.mask, orig) } func (q *masked) NComp() int { return q.orig.NComp() } func (q *masked) createMask() { size := Mesh().Size() // Prepare mask on host maskhost := data.NewSlice(SCALAR, size) defer maskhost.Free() maskScalars := maskhost.Scalars() for iz := 0; iz < size[Z]; iz++ { for iy := 0; iy < size[Y]; iy++ { for ix := 0; ix < size[X]; ix++ { r := Index2Coord(ix, iy, iz) if q.shape(r[X], r[Y], r[Z]) { maskScalars[iz][iy][ix] = 1 } } } } // Update mask q.mask.Free() q.mask = opencl.NewSlice(SCALAR, size) data.Copy(q.mask, maskhost) q.mesh = *Mesh() // Remove mask from host }
engine/customfield.go
0.815233
0.495484
customfield.go
starcoder
package utils // https://github.com/SonarSystems/Modern-OpenGL-Tutorials/blob/master/%5BADVANCED%20OPENGL%5D/%5B17%5D%20Cubemap:Skybox/main.cpp import ( "fmt" "image" "image/draw" "unsafe" // Required in order to use jpeg files. _ "image/jpeg" "os" "github.com/go-gl/gl/v4.6-core/gl" ) // Texture Texture type Texture struct { ID uint32 Width int32 Height int32 RGBA *image.RGBA } // LoadRGBA LoadRGBA func LoadRGBA(file string) *image.RGBA { // Open the file imgFile, err := os.Open(file) if err != nil { panic(err) } // Decode the image img, _, err := image.Decode(imgFile) if err != nil { panic(err) } // fmt.Println("Image Filename:", file) // fmt.Println("Image format is", formatName) // fmt.Println("Image Bounds is", img.Bounds()) // NewRGBA returns a new RGBA image with the given bounds. rgba := image.NewRGBA(img.Bounds()) if rgba.Stride != rgba.Rect.Size().X*4 { fmt.Errorf("unsupported stride") os.Exit(-1) } // Draw calls DrawMask with a nil mask. draw.Draw(rgba, rgba.Bounds(), img, image.Point{0, 0}, draw.Src) return rgba } // // NewTexture NewTexture // func NewTexture(file string) Texture { // var texture Texture // texture.RGBA = LoadRGBA(file) // texture.Width = int32(texture.RGBA.Rect.Size().X) // texture.Height = int32(texture.RGBA.Rect.Size().Y) // gl.GenTextures(1, &texture.ID) // gl.ActiveTexture(gl.TEXTURE0) // gl.BindTexture(gl.TEXTURE_2D, texture.ID) // // Set basic filter and wrap values // gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR) // gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) // gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) // gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) // gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGB, texture.Width, // texture.Height, 0, gl.RGBA, gl.UNSIGNED_BYTE, unsafe.Pointer(&texture.RGBA.Pix[0])) // return texture // } // NewTexture NewTexture func NewTexture(file string) uint32 { RGBA := LoadRGBA(file) width := int32(RGBA.Rect.Size().X) height := int32(RGBA.Rect.Size().Y) var texture uint32 gl.GenTextures(1, &texture) gl.ActiveTexture(gl.TEXTURE0) gl.BindTexture(gl.TEXTURE_2D, texture) // Set basic filter and wrap values gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE) gl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE) gl.TexImage2D(gl.TEXTURE_2D, 0, gl.RGB, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, unsafe.Pointer(&RGBA.Pix[0])) return texture }
internal/utils/texture.go
0.724383
0.432902
texture.go
starcoder
package main import ( "github.com/PieterD/glimmer/gli" "github.com/PieterD/glimmer/mat" "github.com/go-gl/glfw/v3.1/glfw" "github.com/go-gl/mathgl/mgl32" ) const d2r = 3.14159 * 2 / 360 type Crane struct { posBase mgl32.Vec3 angBase float32 posBaseLeft mgl32.Vec3 posBaseRight mgl32.Vec3 scaleBaseZ float32 angUpperArm float32 sizeUpperArm float32 posLowerArm mgl32.Vec3 angLowerArm float32 lenLowerArm float32 widthLowerArm float32 posWrist mgl32.Vec3 angWristRoll float32 angWristPitch float32 lenWrist float32 widthWrist float32 posLeftFinger mgl32.Vec3 posRightFinger mgl32.Vec3 angFingerOpen float32 lenFinger float32 widthFinger float32 angLowerFinger float32 p *Profile } func NewCrane(p *Profile) *Crane { return &Crane{ posBase: mgl32.Vec3{3, -5, -40}, angBase: -45, posBaseLeft: mgl32.Vec3{2, 0, 0}, posBaseRight: mgl32.Vec3{-2, 0, 0}, scaleBaseZ: 3, angUpperArm: -78, sizeUpperArm: 9, posLowerArm: mgl32.Vec3{0, 0, 8}, angLowerArm: 101, lenLowerArm: 5, widthLowerArm: 1.5, posWrist: mgl32.Vec3{0, 0, 5}, angWristRoll: 0, angWristPitch: 67.5, lenWrist: 2, widthWrist: 2, posLeftFinger: mgl32.Vec3{1, 0, 1}, posRightFinger: mgl32.Vec3{-1, 0, 1}, angFingerOpen: 27, lenFinger: 2, widthFinger: 0.5, angLowerFinger: 45, p: p, } } func (crane *Crane) Draw() { stack := mat.NewStack() stack.AngleDeg() stack.Ident() stack.TranslateV(crane.posBase) stack.RotateY(crane.angBase) stack.Safe(crane.base) stack.Safe(crane.arm) } func (crane *Crane) base(stack *mat.Stack) { stack.Safe(func(stack *mat.Stack) { stack.TranslateV(crane.posBaseLeft) stack.Scale(1, 1, crane.scaleBaseZ) crane.put(stack) }) stack.Safe(func(stack *mat.Stack) { stack.TranslateV(crane.posBaseRight) stack.Scale(1, 1, crane.scaleBaseZ) crane.put(stack) }) } func (crane *Crane) arm(stack *mat.Stack) { stack.RotateX(crane.angUpperArm) stack.Safe(func(stack *mat.Stack) { stack.Translate(0, 0, crane.sizeUpperArm/2-1) stack.Scale(1, 1, crane.sizeUpperArm/2) crane.put(stack) }) stack.Safe(crane.lowerarm) } func (crane *Crane) lowerarm(stack *mat.Stack) { stack.TranslateV(crane.posLowerArm) stack.RotateX(crane.angLowerArm) stack.Safe(func(stack *mat.Stack) { stack.Translate(0, 0, crane.lenLowerArm/2) stack.Scale(crane.widthLowerArm/2, crane.widthLowerArm/2, crane.lenLowerArm/2) crane.put(stack) }) stack.Safe(crane.wrist) } func (crane *Crane) wrist(stack *mat.Stack) { stack.TranslateV(crane.posWrist) stack.RotateZ(crane.angWristRoll) stack.RotateX(crane.angWristPitch) stack.Safe(func(stack *mat.Stack) { stack.Scale(crane.widthWrist/2, crane.widthWrist/2, crane.lenWrist/2) crane.put(stack) }) stack.Safe(crane.leftfinger) stack.Safe(crane.rightfinger) } func (crane *Crane) leftfinger(stack *mat.Stack) { stack.TranslateV(crane.posLeftFinger) stack.RotateY(crane.angFingerOpen) stack.Safe(func(stack *mat.Stack) { stack.Translate(0, 0, crane.lenFinger/2) stack.Scale(crane.widthFinger/2, crane.widthFinger/2, crane.lenFinger/2) crane.put(stack) }) stack.Safe(func(stack *mat.Stack) { stack.Translate(0, 0, crane.lenFinger) stack.RotateY(-crane.angLowerFinger) stack.Safe(func(stack *mat.Stack) { stack.Translate(0, 0, crane.lenFinger/2) stack.Scale(crane.widthFinger/2, crane.widthFinger/2, crane.lenFinger/2) crane.put(stack) }) }) } func (crane *Crane) rightfinger(stack *mat.Stack) { stack.TranslateV(crane.posRightFinger) stack.RotateY(-crane.angFingerOpen) stack.Safe(func(stack *mat.Stack) { stack.Translate(0, 0, crane.lenFinger/2) stack.Scale(crane.widthFinger/2, crane.widthFinger/2, crane.lenFinger/2) crane.put(stack) }) stack.Safe(func(stack *mat.Stack) { stack.Translate(0, 0, crane.lenFinger) stack.RotateY(crane.angLowerFinger) stack.Safe(func(stack *mat.Stack) { stack.Translate(0, 0, crane.lenFinger/2) stack.Scale(crane.widthFinger/2, crane.widthFinger/2, crane.lenFinger/2) crane.put(stack) }) }) } func (crane *Crane) adjustBase(dir float32) { crane.angBase += 11.25 * dir } func (crane *Crane) adjustUpperArm(dir float32) { crane.angUpperArm += 11.25 * dir } func (crane *Crane) adjustLowerArm(dir float32) { crane.angLowerArm += 11.25 * dir } func (crane *Crane) adjustWristPitch(dir float32) { crane.angWristPitch += 11.25 * dir } func (crane *Crane) adjustWristRoll(dir float32) { crane.angWristRoll += 11.25 * dir } func (crane *Crane) adjustFingerOpen(dir float32) { crane.angFingerOpen += 9 * dir } func (crane *Crane) put(stack *mat.Stack) { p := crane.p m := stack.Peek() p.modelToCameraMatrix.Float(m[:]...) gli.Draw(p.program, p.vao, rectObject) } func (p *Profile) EventRune(w *glfw.Window, char rune) { switch char { case 'a': p.crane.adjustBase(1) case 'd': p.crane.adjustBase(-1) case 'w': p.crane.adjustUpperArm(-1) case 's': p.crane.adjustUpperArm(1) case 'r': p.crane.adjustLowerArm(-1) case 'f': p.crane.adjustLowerArm(1) case 't': p.crane.adjustWristPitch(-1) case 'g': p.crane.adjustWristPitch(1) case 'z': p.crane.adjustWristRoll(1) case 'c': p.crane.adjustWristRoll(-1) case 'q': p.crane.adjustFingerOpen(1) case 'e': p.crane.adjustFingerOpen(-1) } }
glimmer/old/ogli/examples/ex08-crane-model/crane.go
0.511473
0.49646
crane.go
starcoder
package ionossdk import ( "encoding/json" ) // KubernetesNodePoolLabel map of labels attached to node pool type KubernetesNodePoolLabel struct { // Key of the label. String part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character. Key *string `json:"key,omitempty"` // Value of the label. String part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character. Value *string `json:"value,omitempty"` } // GetKey returns the Key field value // If the value is explicit nil, the zero value for string will be returned func (o *KubernetesNodePoolLabel) GetKey() *string { if o == nil { return nil } return o.Key } // GetKeyOk returns a tuple with the Key field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *KubernetesNodePoolLabel) GetKeyOk() (*string, bool) { if o == nil { return nil, false } return o.Key, true } // SetKey sets field value func (o *KubernetesNodePoolLabel) SetKey(v string) { o.Key = &v } // HasKey returns a boolean if a field has been set. func (o *KubernetesNodePoolLabel) HasKey() bool { if o != nil && o.Key != nil { return true } return false } // GetValue returns the Value field value // If the value is explicit nil, the zero value for string will be returned func (o *KubernetesNodePoolLabel) GetValue() *string { if o == nil { return nil } return o.Value } // GetValueOk returns a tuple with the Value field value // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *KubernetesNodePoolLabel) GetValueOk() (*string, bool) { if o == nil { return nil, false } return o.Value, true } // SetValue sets field value func (o *KubernetesNodePoolLabel) SetValue(v string) { o.Value = &v } // HasValue returns a boolean if a field has been set. func (o *KubernetesNodePoolLabel) HasValue() bool { if o != nil && o.Value != nil { return true } return false } func (o KubernetesNodePoolLabel) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Key != nil { toSerialize["key"] = o.Key } if o.Value != nil { toSerialize["value"] = o.Value } return json.Marshal(toSerialize) } type NullableKubernetesNodePoolLabel struct { value *KubernetesNodePoolLabel isSet bool } func (v NullableKubernetesNodePoolLabel) Get() *KubernetesNodePoolLabel { return v.value } func (v *NullableKubernetesNodePoolLabel) Set(val *KubernetesNodePoolLabel) { v.value = val v.isSet = true } func (v NullableKubernetesNodePoolLabel) IsSet() bool { return v.isSet } func (v *NullableKubernetesNodePoolLabel) Unset() { v.value = nil v.isSet = false } func NewNullableKubernetesNodePoolLabel(val *KubernetesNodePoolLabel) *NullableKubernetesNodePoolLabel { return &NullableKubernetesNodePoolLabel{value: val, isSet: true} } func (v NullableKubernetesNodePoolLabel) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableKubernetesNodePoolLabel) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
cluster-autoscaler/cloudprovider/ionoscloud/ionos-cloud-sdk-go/model_kubernetes_node_pool_label.go
0.697197
0.412767
model_kubernetes_node_pool_label.go
starcoder
package input import ( "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/lib/input/reader" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/types" ) //------------------------------------------------------------------------------ func init() { Constructors[TypeNATSStream] = TypeSpec{ constructor: fromSimpleConstructor(NewNATSStream), Summary: ` Subscribe to a NATS Stream subject. Joining a queue is optional and allows multiple clients of a subject to consume using queue semantics.`, Description: ` Tracking and persisting offsets through a durable name is also optional and works with or without a queue. If a durable name is not provided then subjects are consumed from the most recently published message. When a consumer closes its connection it unsubscribes, when all consumers of a durable queue do this the offsets are deleted. In order to avoid this you can stop the consumers from unsubscribing by setting the field ` + "`unsubscribe_on_close` to `false`" + `. ### Metadata This input adds the following metadata fields to each message: ` + "``` text" + ` - nats_stream_subject - nats_stream_sequence ` + "```" + ` You can access these metadata fields using [function interpolation](/docs/configuration/interpolation#metadata).`, sanitiseConfigFunc: func(conf Config) (interface{}, error) { return sanitiseWithBatch(conf.NATSStream, conf.NATSStream.Batching) }, FieldSpecs: docs.FieldSpecs{ docs.FieldDeprecated("batching"), docs.FieldCommon( "urls", "A list of URLs to connect to. If an item of the list contains commas it will be expanded into multiple URLs.", []string{"nats://127.0.0.1:4222"}, []string{"nats://username:password@127.0.0.1:4222"}, ), docs.FieldCommon("cluster_id", "The ID of the cluster to consume from."), docs.FieldCommon("client_id", "A client ID to connect as."), docs.FieldCommon("queue", "The queue to consume from."), docs.FieldCommon("subject", "A subject to consume from."), docs.FieldCommon("durable_name", "Preserve the state of your consumer under a durable name."), docs.FieldCommon("unsubscribe_on_close", "Whether the subscription should be destroyed when this client disconnects."), docs.FieldAdvanced("start_from_oldest", "If a position is not found for a queue, determines whether to consume from the oldest available message, otherwise messages are consumed from the latest."), docs.FieldAdvanced("max_inflight", "The maximum number of unprocessed messages to fetch at a given time."), docs.FieldAdvanced("ack_wait", "An optional duration to specify at which a message that is yet to be acked will be automatically retried."), }, Categories: []Category{ CategoryServices, }, } } //------------------------------------------------------------------------------ // NewNATSStream creates a new NATSStream input type. func NewNATSStream(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) { var c reader.Async var err error if c, err = reader.NewNATSStream(conf.NATSStream, log, stats); err != nil { return nil, err } c = reader.NewAsyncBundleUnacks(c) if c, err = reader.NewAsyncBatcher(conf.NATSStream.Batching, c, mgr, log, stats); err != nil { return nil, err } return NewAsyncReader(TypeNATSStream, true, c, log, stats) } //------------------------------------------------------------------------------
lib/input/nats_stream.go
0.810629
0.750667
nats_stream.go
starcoder
package basic // SortTest is template func SortTest() string { return ` func TestSort<FTYPE>(t *testing.T) { expectedList := []<TYPE>{1, 2, 3, 4, 5} sortedList := Sort<FTYPE>s([]<TYPE>{5, 1, 4, 2, 3}) matched := reflect.DeepEqual(sortedList, expectedList) if !matched { t.Errorf("Sotred<TYPE>s failed") } sortedList = Sort<FTYPE>s([]<TYPE>{}) if len(sortedList) > 0 { t.Errorf("Sotred<TYPE>s failed") } } func TestSort<FTYPE>Ptr(t *testing.T) { var v1 <TYPE> = 1 var v2 <TYPE> = 2 var v3 <TYPE> = 3 var v4 <TYPE> = 4 var v5 <TYPE> = 5 expectedList := []*<TYPE>{&v1, &v2, &v3, &v4, &v5} sortedList := Sort<FTYPE>sPtr([]*<TYPE>{&v5, &v1, &v4, &v2, &v3}) for i, val := range sortedList { if *val != *expectedList[i] { for _, val := range expectedList { t.Errorf("expected item: %v", *val) } for _, val := range sortedList { t.Errorf("sorted item: %v", *val) } t.Errorf("Sotred<TYPE>s failed") } } sortedList = Sort<FTYPE>sPtr([]*<TYPE>{}) if len(sortedList) > 0 { t.Errorf("Sotred<TYPE>sPtr failed") } } func TestSort<FTYPE>Desc(t *testing.T) { expectedList := []<TYPE>{5, 4, 3, 2, 1} sortedList := Sort<FTYPE>sDesc([]<TYPE>{5, 1, 4, 2, 3}) matched := reflect.DeepEqual(sortedList, expectedList) if !matched { t.Errorf("Sotred<TYPE>s failed") } sortedList = Sort<FTYPE>sDesc([]<TYPE>{}) if len(sortedList) > 0 { t.Errorf("Sotred<TYPE>sDesc failed") } } func TestSort<FTYPE>DescPtr(t *testing.T) { var v1 <TYPE> = 1 var v2 <TYPE> = 2 var v3 <TYPE> = 3 var v4 <TYPE> = 4 var v5 <TYPE> = 5 expectedList := []*<TYPE>{&v5, &v4, &v3, &v2, &v1} sortedList := Sort<FTYPE>sDescPtr([]*<TYPE>{&v5, &v1, &v4, &v2, &v3}) for i, val := range sortedList { if *val != *expectedList[i] { for _, val := range expectedList { t.Errorf("expected item: %v", *val) } for _, val := range sortedList { t.Errorf("sorted item: %v", *val) } t.Errorf("Sotred<TYPE>s failed") } } sortedList = Sort<FTYPE>sDescPtr([]*<TYPE>{}) if len(sortedList) > 0 { t.Errorf("Sotred<TYPE>sDescPtr failed") } } ` } // SortIntsTest is template func SortIntsTest() string { return ` func TestSort<FTYPE>(t *testing.T) { expectedList := []<TYPE>{1, 2, 3, 4, 5} sortedList := SortInts([]<TYPE>{5, 1, 4, 2, 3}) matched := reflect.DeepEqual(sortedList, expectedList) if !matched { t.Errorf("Sotred<TYPE>s failed") } sortedList = SortInts([]<TYPE>{}) if len(sortedList) > 0 { t.Errorf("SortInts failed") } } func TestSort<FTYPE>Ptr(t *testing.T) { var v1 <TYPE> = 1 var v2 <TYPE> = 2 var v3 <TYPE> = 3 var v4 <TYPE> = 4 var v5 <TYPE> = 5 expectedList := []*<TYPE>{&v1, &v2, &v3, &v4, &v5} sortedList := SortIntsPtr([]*<TYPE>{&v5, &v1, &v4, &v2, &v3}) for i, val := range sortedList { if *val != *expectedList[i] { t.Errorf("Sotred<TYPE>s failed") for _, val := range expectedList { t.Errorf("expected item: %v", *val) } for _, val := range sortedList { t.Errorf("sorted item: %v", *val) } } } sortedList = SortIntsPtr([]*<TYPE>{}) if len(sortedList) > 0 { t.Errorf("SortIntsPtr failed") } } func TestSort<FTYPE>Desc(t *testing.T) { expectedList := []<TYPE>{5, 4, 3, 2, 1} sortedList := SortIntsDesc([]<TYPE>{5, 1, 4, 2, 3}) matched := reflect.DeepEqual(sortedList, expectedList) if !matched { t.Errorf("Sotred<TYPE>s failed") } sortedList = SortIntsDesc([]<TYPE>{}) if len(sortedList) > 0 { t.Errorf("SortIntsDesc failed") } } func TestSort<FTYPE>DescPtr(t *testing.T) { var v1 <TYPE> = 1 var v2 <TYPE> = 2 var v3 <TYPE> = 3 var v4 <TYPE> = 4 var v5 <TYPE> = 5 expectedList := []*<TYPE>{&v5, &v4, &v3, &v2, &v1} sortedList := SortIntsDescPtr([]*<TYPE>{&v5, &v1, &v4, &v2, &v3}) for i, val := range sortedList { if *val != *expectedList[i] { t.Errorf("Sotred<TYPE>s failed") } } sortedList = SortIntsDescPtr([]*<TYPE>{}) if len(sortedList) > 0 { t.Errorf("SortIntsDescPtr failed") } } ` } // SortFloats64Test is template func SortFloats64Test() string { return ` func TestSort<FTYPE>(t *testing.T) { expectedList := []<TYPE>{1, 2, 3, 4, 5} sortedList := SortFloats64([]<TYPE>{5, 1, 4, 2, 3}) matched := reflect.DeepEqual(sortedList, expectedList) if !matched { t.Errorf("Sotred<TYPE>s failed") } sortedList = SortFloats64([]<TYPE>{}) if len(sortedList) > 0 { t.Errorf("SortFloats64 failed") } } func TestSort<FTYPE>Ptr(t *testing.T) { var v1 <TYPE> = 1 var v2 <TYPE> = 2 var v3 <TYPE> = 3 var v4 <TYPE> = 4 var v5 <TYPE> = 5 expectedList := []*<TYPE>{&v1, &v2, &v3, &v4, &v5} sortedList := SortFloats64Ptr([]*<TYPE>{&v5, &v1, &v4, &v2, &v3}) for i, val := range sortedList { if *val != *expectedList[i] { t.Errorf("Sotred<TYPE>s failed") for _, val := range expectedList { t.Errorf("expected item: %v", *val) } for _, val := range sortedList { t.Errorf("sorted item: %v", *val) } } } sortedList = SortFloats64Ptr([]*<TYPE>{}) if len(sortedList) > 0 { t.Errorf("SortFloats64Ptr failed") } } func TestSort<FTYPE>Desc(t *testing.T) { expectedList := []<TYPE>{5, 4, 3, 2, 1} sortedList := SortFloats64Desc([]<TYPE>{5, 1, 4, 2, 3}) matched := reflect.DeepEqual(sortedList, expectedList) if !matched { t.Errorf("Sotred<TYPE>s failed") } sortedList = SortFloats64Desc([]<TYPE>{}) if len(sortedList) > 0 { t.Errorf("SortFloats64Desc failed") } } func TestSort<FTYPE>DescPtr(t *testing.T) { var v1 <TYPE> = 1 var v2 <TYPE> = 2 var v3 <TYPE> = 3 var v4 <TYPE> = 4 var v5 <TYPE> = 5 expectedList := []*<TYPE>{&v5, &v4, &v3, &v2, &v1} sortedList := SortFloats64DescPtr([]*<TYPE>{&v5, &v1, &v4, &v2, &v3}) for i, val := range sortedList { if *val != *expectedList[i] { t.Errorf("Sotred<TYPE>s failed") } } sortedList = SortFloats64DescPtr([]*<TYPE>{}) if len(sortedList) > 0 { t.Errorf("SortFloats64DescPtr failed") } } ` } // SortStrsTest is template func SortStrsTest() string { return ` func TestSort<FTYPE>(t *testing.T) { expectedList := []<TYPE>{"1", "2", "3", "4", "5"} sortedList := SortStrs([]<TYPE>{"5", "1", "4", "2", "3"}) matched := reflect.DeepEqual(sortedList, expectedList) if !matched { t.Errorf("Sotred<TYPE>s failed") } sortedList = SortStrs([]<TYPE>{}) if len(sortedList) > 0 { t.Errorf("SortStrs failed") } } func TestSort<FTYPE>Ptr(t *testing.T) { var v1 <TYPE> = 1 var v2 <TYPE> = 2 var v3 <TYPE> = 3 var v4 <TYPE> = 4 var v5 <TYPE> = 5 expectedList := []*<TYPE>{&v1, &v2, &v3, &v4, &v5} sortedList := SortStrsPtr([]*<TYPE>{&v5, &v1, &v4, &v2, &v3}) for i, val := range sortedList { if *val != *expectedList[i] { t.Errorf("Sotred<TYPE>s failed") for _, val := range expectedList { t.Errorf("expected item: %v", *val) } for _, val := range sortedList { t.Errorf("sorted item: %v", *val) } } } sortedList = SortStrsPtr([]*<TYPE>{}) if len(sortedList) > 0 { t.Errorf("SortStrsPtr failed") } } func TestSort<FTYPE>Desc(t *testing.T) { expectedList := []<TYPE>{"5", "4", "3", "2", "1"} sortedList := SortStrsDesc([]<TYPE>{"5", "1", "4", "2", "3"}) matched := reflect.DeepEqual(sortedList, expectedList) if !matched { t.Errorf("Sotred<TYPE>s failed") } sortedList = SortStrsDesc([]<TYPE>{}) if len(sortedList) > 0 { t.Errorf("SortStrsDesc failed") } } func TestSort<FTYPE>DescPtr(t *testing.T) { var v1 <TYPE> = 1 var v2 <TYPE> = 2 var v3 <TYPE> = 3 var v4 <TYPE> = 4 var v5 <TYPE> = 5 expectedList := []*<TYPE>{&v5, &v4, &v3, &v2, &v1} sortedList := SortStrsDescPtr([]*<TYPE>{&v5, &v1, &v4, &v2, &v3}) for i, val := range sortedList { if *val != *expectedList[i] { t.Errorf("Sotred<TYPE>s failed") for _, val := range expectedList { t.Errorf("expected item: %v", *val) } for _, val := range sortedList { t.Errorf("sorted item: %v", *val) } } } sortedList = SortStrsDescPtr([]*<TYPE>{}) if len(sortedList) > 0 { t.Errorf("SortStrsDescPtr failed") } } ` }
internal/template/basic/sorttest.go
0.604516
0.620392
sorttest.go
starcoder
package schema import "strings" func buildJSSchema() { const src = `{ "id": "http://json-schema.org/draft-04/schema#", "$schema": "http://json-schema.org/draft-04/schema#", "description": "Core schema meta-schema", "definitions": { "schemaArray": { "type": "array", "minItems": 1, "items": { "$ref": "#" } }, "positiveInteger": { "type": "integer", "minimum": 0 }, "positiveIntegerDefault0": { "allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ] }, "simpleTypes": { "enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ] }, "stringArray": { "type": "array", "items": { "type": "string" }, "minItems": 1, "uniqueItems": true } }, "type": "object", "properties": { "id": { "type": "string", "format": "uri" }, "$schema": { "type": "string", "format": "uri" }, "title": { "type": "string" }, "description": { "type": "string" }, "default": {}, "multipleOf": { "type": "number", "minimum": 0, "exclusiveMinimum": true }, "maximum": { "type": "number" }, "exclusiveMaximum": { "type": "boolean", "default": false }, "minimum": { "type": "number" }, "exclusiveMinimum": { "type": "boolean", "default": false }, "maxLength": { "$ref": "#/definitions/positiveInteger" }, "minLength": { "$ref": "#/definitions/positiveIntegerDefault0" }, "pattern": { "type": "string", "format": "regex" }, "additionalItems": { "anyOf": [ { "type": "boolean" }, { "$ref": "#" } ], "default": {} }, "items": { "anyOf": [ { "$ref": "#" }, { "$ref": "#/definitions/schemaArray" } ], "default": {} }, "maxItems": { "$ref": "#/definitions/positiveInteger" }, "minItems": { "$ref": "#/definitions/positiveIntegerDefault0" }, "uniqueItems": { "type": "boolean", "default": false }, "maxProperties": { "$ref": "#/definitions/positiveInteger" }, "minProperties": { "$ref": "#/definitions/positiveIntegerDefault0" }, "required": { "$ref": "#/definitions/stringArray" }, "additionalProperties": { "anyOf": [ { "type": "boolean" }, { "$ref": "#" } ], "default": {} }, "definitions": { "type": "object", "additionalProperties": { "$ref": "#" }, "default": {} }, "properties": { "type": "object", "additionalProperties": { "$ref": "#" }, "default": {} }, "patternProperties": { "type": "object", "additionalProperties": { "$ref": "#" }, "default": {} }, "dependencies": { "type": "object", "additionalProperties": { "anyOf": [ { "$ref": "#" }, { "$ref": "#/definitions/stringArray" } ] } }, "enum": { "type": "array", "minItems": 1, "uniqueItems": true }, "type": { "anyOf": [ { "$ref": "#/definitions/simpleTypes" }, { "type": "array", "items": { "$ref": "#/definitions/simpleTypes" }, "minItems": 1, "uniqueItems": true } ] }, "allOf": { "$ref": "#/definitions/schemaArray" }, "anyOf": { "$ref": "#/definitions/schemaArray" }, "oneOf": { "$ref": "#/definitions/schemaArray" }, "not": { "$ref": "#" } }, "dependencies": { "exclusiveMaximum": [ "maximum" ], "exclusiveMinimum": [ "minimum" ] }, "default": {} }` if err := _schema.Decode(strings.NewReader(src)); err != nil { // We regret to inform you that if we can't parse this // schema, then we have a real real real problem, so we're // going to panic panic("failed to parse main JSON Schema schema: " + err.Error()) } } func buildHyperSchema() { const src = `{ "$schema": "http://json-schema.org/draft-04/hyper-schema#", "id": "http://json-schema.org/draft-04/hyper-schema#", "title": "JSON Hyper-Schema", "allOf": [ { "$ref": "http://json-schema.org/draft-04/schema#" } ], "properties": { "additionalItems": { "anyOf": [ { "type": "boolean" }, { "$ref": "#" } ] }, "additionalProperties": { "anyOf": [ { "type": "boolean" }, { "$ref": "#" } ] }, "dependencies": { "additionalProperties": { "anyOf": [ { "$ref": "#" }, { "type": "array" } ] } }, "items": { "anyOf": [ { "$ref": "#" }, { "$ref": "#/definitions/schemaArray" } ] }, "definitions": { "additionalProperties": { "$ref": "#" } }, "patternProperties": { "additionalProperties": { "$ref": "#" } }, "properties": { "additionalProperties": { "$ref": "#" } }, "allOf": { "$ref": "#/definitions/schemaArray" }, "anyOf": { "$ref": "#/definitions/schemaArray" }, "oneOf": { "$ref": "#/definitions/schemaArray" }, "not": { "$ref": "#" }, "links": { "type": "array", "items": { "$ref": "#/definitions/linkDescription" } }, "fragmentResolution": { "type": "string" }, "media": { "type": "object", "properties": { "type": { "description": "A media type, as described in RFC 2046", "type": "string" }, "binaryEncoding": { "description": "A content encoding scheme, as described in RFC 2045", "type": "string" } } }, "pathStart": { "description": "Instances' URIs must start with this value for this schema to apply to them", "type": "string", "format": "uri" } }, "definitions": { "schemaArray": { "type": "array", "items": { "$ref": "#" } }, "linkDescription": { "title": "Link Description Object", "type": "object", "required": [ "href", "rel" ], "properties": { "href": { "description": "a URI template, as defined by RFC 6570, with the addition of the $, ( and ) characters for pre-processing", "type": "string" }, "rel": { "description": "relation to the target resource of the link", "type": "string" }, "title": { "description": "a title for the link", "type": "string" }, "targetSchema": { "description": "JSON Schema describing the link target", "$ref": "#" }, "mediaType": { "description": "media type (as defined by RFC 2046) describing the link target", "type": "string" }, "method": { "description": "method for requesting the target of the link (e.g. for HTTP this might be \"GET\" or \"DELETE\")", "type": "string" }, "encType": { "description": "The media type in which to submit data along with the request", "type": "string", "default": "application/json" }, "schema": { "description": "Schema describing the data to submit along with the request", "$ref": "#" } } } }, "links": [ { "rel": "self", "href": "{+id}" }, { "rel": "full", "href": "{+($ref)}" } ] }` if err := _hyperSchema.Decode(strings.NewReader(src)); err != nil { // We regret to inform you that if we can't parse this // schema, then we have a real real real problem, so we're // going to panic panic("failed to parse Hyper JSON Schema schema: " + err.Error()) } }
vendor/github.com/lestrrat/go-jsschema/default.go
0.744749
0.509215
default.go
starcoder
package gokvstores import "time" // DummyStore is a noop store (caching disabled). type DummyStore struct{} // Get returns value for the given key. func (DummyStore) Get(key string) (interface{}, error) { return nil, nil } // MGet returns map of key, value for a list of keys. func (DummyStore) MGet(keys []string) (map[string]interface{}, error) { return nil, nil } // Set sets value for the given key. func (DummyStore) Set(key string, value interface{}) error { return nil } // SetWithExpiration sets the value for the given key for a specified duration. func (DummyStore) SetWithExpiration(key string, value interface{}, expiration time.Duration) error { return nil } // GetMap returns map for the given key. func (DummyStore) GetMap(key string) (map[string]interface{}, error) { return nil, nil } // GetMaps returns maps for the given keys. func (DummyStore) GetMaps(keys []string) (map[string]map[string]interface{}, error) { return nil, nil } // SetMap sets map for the given key. func (DummyStore) SetMap(key string, value map[string]interface{}) error { return nil } // SetMaps sets the given maps. func (DummyStore) SetMaps(maps map[string]map[string]interface{}) error { return nil } // DeleteMap removes the specified fields from the map stored at key. func (DummyStore) DeleteMap(key string, fields ...string) error { return nil } // GetSlice returns slice for the given key. func (DummyStore) GetSlice(key string) ([]interface{}, error) { return nil, nil } // SetSlice sets slice for the given key. func (DummyStore) SetSlice(key string, value []interface{}) error { return nil } // AppendSlice appends values to an existing slice. // If key does not exist, creates slice. func (DummyStore) AppendSlice(key string, values ...interface{}) error { return nil } // Exists checks if the given key exists. func (DummyStore) Exists(key string) (bool, error) { return false, nil } // Delete deletes the given key. func (DummyStore) Delete(key string) error { return nil } // Keys returns all keys matching pattern func (DummyStore) Keys(pattern string) ([]interface{}, error) { return nil, nil } // Flush flushes the store. func (DummyStore) Flush() error { return nil } // Close closes the connection to the store. func (DummyStore) Close() error { return nil }
vendor/github.com/ulule/gokvstores/dummy.go
0.83056
0.415373
dummy.go
starcoder
package util import ( "image/color" "math" "github.com/anthonynsimon/bild/math/f64" ) // RGBToHSL converts from RGB to HSL color model. // Parameter c is the RGBA color and must implement the color.RGBA interface. // Returned values h, s and l correspond to the hue, saturation and lightness. // The hue is of range 0 to 360 and the saturation and lightness are of range 0.0 to 1.0. func RGBToHSL(c color.RGBA) (float64, float64, float64) { r, g, b := float64(c.R)/255, float64(c.G)/255, float64(c.B)/255 max := math.Max(r, math.Max(g, b)) min := math.Min(r, math.Min(g, b)) delta := max - min var h, s, l float64 l = (max + min) / 2 // Achromatic if delta <= 0 { return h, s, l } // Should it be smaller than or equals instead? if l < 0.5 { s = delta / (max + min) } else { s = delta / (2 - max - min) } if r >= max { h = (g - b) / delta } else if g >= max { h = (b-r)/delta + 2 } else { h = (r-g)/delta + 4 } h *= 60 if h < 0 { h += 360 } return h, s, l } // HSLToRGB converts from HSL to RGB color model. // Parameter h is the hue and its range is from 0 to 360 degrees. // Parameter s is the saturation and its range is from 0.0 to 1.0. // Parameter l is the lightness and its range is from 0.0 to 1.0. func HSLToRGB(h, s, l float64) color.RGBA { var r, g, b float64 if s == 0 { r = l g = l b = l } else { var temp0, temp1 float64 if l < 0.5 { temp0 = l * (1 + s) } else { temp0 = (l + s) - (s * l) } temp1 = 2*l - temp0 h /= 360 hueFn := func(v float64) float64 { if v < 0 { v++ } else if v > 1 { v-- } if v < 1.0/6.0 { return temp1 + (temp0-temp1)*6*v } if v < 1.0/2.0 { return temp0 } if v < 2.0/3.0 { return temp1 + (temp0-temp1)*(2.0/3.0-v)*6 } return temp1 } r = hueFn(h + 1.0/3.0) g = hueFn(h) b = hueFn(h - 1.0/3.0) } outR := uint8(f64.Clamp(r*255+0.5, 0, 255)) outG := uint8(f64.Clamp(g*255+0.5, 0, 255)) outB := uint8(f64.Clamp(b*255+0.5, 0, 255)) return color.RGBA{outR, outG, outB, 0xFF} } // RGBToHSV converts from RGB to HSV color model. // Parameter c is the RGBA color and must implement the color.RGBA interface. // Returned values h, s and v correspond to the hue, saturation and value. // The hue is of range 0 to 360 and the saturation and value are of range 0.0 to 1.0. func RGBToHSV(c color.RGBA) (h, s, v float64) { r, g, b := float64(c.R)/255, float64(c.G)/255, float64(c.B)/255 max := math.Max(r, math.Max(g, b)) min := math.Min(r, math.Min(g, b)) v = max delta := max - min // Avoid division by zero if max > 0 { s = delta / max } else { h = 0 s = 0 return } // Achromatic if max == min { h = 0 return } if r >= max { h = (g - b) / delta } else if g >= max { h = (b-r)/delta + 2 } else { h = (r-g)/delta + 4 } h *= 60 if h < 0 { h += 360 } return } // HSVToRGB converts from HSV to RGB color model. // Parameter h is the hue and its range is from 0 to 360 degrees. // Parameter s is the saturation and its range is from 0.0 to 1.0. // Parameter v is the value and its range is from 0.0 to 1.0. func HSVToRGB(h, s, v float64) color.RGBA { var i, f, p, q, t float64 // Achromatic if s == 0 { outV := uint8(f64.Clamp(v*255+0.5, 0, 255)) return color.RGBA{outV, outV, outV, 0xFF} } h /= 60 i = math.Floor(h) f = h - i p = v * (1 - s) q = v * (1 - s*f) t = v * (1 - s*(1-f)) var r, g, b float64 switch i { case 0: r = v g = t b = p case 1: r = q g = v b = p case 2: r = p g = v b = t case 3: r = p g = q b = v case 4: r = t g = p b = v default: r = v g = p b = q } outR := uint8(f64.Clamp(r*255+0.5, 0, 255)) outG := uint8(f64.Clamp(g*255+0.5, 0, 255)) outB := uint8(f64.Clamp(b*255+0.5, 0, 255)) return color.RGBA{outR, outG, outB, 0xFF} }
util/colormodel.go
0.810929
0.504944
colormodel.go
starcoder
package common /* Locations is a list (slice) of latitude-longitude pairs. Description The minimum length of a Locations is 2: the first element being the route start location, and the second element being the route end location. Each element in a Locations value is a latitude-longitude pair encoded as a slice of strings. Therefore, its length is exactly 2: the first element being the latitude, and the seconds element being the longitude. A latitude value of 0 represents the Equator. A latitude value of -90 represents the South Pole, while +90 represents the North Pole. Values smaller than -90 or larger than +90 are invalid. A longitude value of 0 represents the prime meridian at Greenwich. A negative value represents locations to the West of the prime meridian, while a positive value represents locations to the East of the prime meridian. Example Here is an example of a valid Locations: var locs Locations = Locations{ {"22.372081", "114.107877"}, // "11 Hoi Shing Rd, Tsuen Wan, Hong Kong" {"22.284419", "114.159510"}, // "Laguna City, Central, Hong Kong" {"22.326442", "114.167811"}, // "789 Nathan Rd, Mong Kok, Hong Kong" } */ type Locations [][]string /* DrivingRoute contains a driving route response. Description The field Status is mandatory. Whether other fields exist depends on Status. See "Examples" below for valid combinations. The field Status is the status of the response. It is either "success", "in progress", or "failure". The field Path is the path of the shortest driving route. The field TotalDistance is the total driving distance (in meters) of the path above. Since the circumference of the Earth is around 40,000km = 40,000,000m at the Equator, and a signed 32-bit integer can represent 2,147,483,647m, more than 50,000 times the circumference of the Earth, int should be sufficient no matter it is 32-bit or 64-bit. The field TotalTime is the estimated total time (in seconds) needed for driving along the path above. Since a signed 32-bit integer can represent a duration of more than 68 years, int should be sufficient no matter it is 32-bit or 64-bit. The field Error is the error occurred during the process. Examples Here is an example of a "success" DrivingRoute: var dr0 DrivingRoute = &DrivingRoute{ Status: "success", Path: Locations{ {"22.372081", "114.107877"}, // "11 <NAME> Rd, Tsuen Wan, Hong Kong" {"22.326442", "114.167811"}, // "789 Nathan Rd, Mong Kok, Hong Kong" {"22.284419", "114.159510"}, // "Laguna City, Central, Hong Kong" }, TotalDistance: 20000, TotalTime: 1800, } Here is an example of a "in progress" DrivingRoute: var dr1 DrivingRoute = &DrivingRoute{ Status: "in progress", } Here is an example of a "failure" DrivingRoute: var dr2 DrivingRoute = &DrivingRoute{ Status: "failure", Error: "internal server error (539cd7a5469b42ec1a53306df7fb2495)", } */ type DrivingRoute struct { Status string `json:"status"` Path Locations `json:"path,omitempty"` TotalDistance int `json:"total_distance,omitempty"` TotalTime int `json:"total_time,omitempty"` Error string `json:"error,omitempty"` }
common/type.go
0.769167
0.704033
type.go
starcoder
package main import ( "fmt" "math" "os" "gonum.org/v1/plot/plotter" ) // ExplicitEuler returns data for plot building based on explicit Euler method. func ExplicitEuler(start, end, y0 float64, count int) plotter.XYs { step, xRange := GetRange(start, end, count) solution := make(plotter.XYs, count) for i := range solution { x := xRange[i] solution[i].X = x if i == 0 { solution[i].Y = y0 } else { y := solution[i - 1].Y solution[i].Y = y + step * F(x, y) } } return solution } // ModifiedEuler returns data for plot building based on modified Euler method. func ModifiedEuler(start, end, y0 float64, count int) plotter.XYs { step, xRange := GetRange(start, end, count) solution := make(plotter.XYs, count) for i := range solution { x := xRange[i] solution[i].X = x if i == 0 { solution[i].Y = y0 } else { x = solution[i - 1].X y := solution[i - 1].Y predict := y + step * F(x, y) solution[i].Y = y + (step / 2) * (F(x, y) + F(x + step, predict)) } } return solution } // Cauchy returns data for plot building based on Cauchy method. func Cauchy(start, end, y0 float64, count int) plotter.XYs { step, xRange := GetRange(start, end, count) solution := make(plotter.XYs, count) for i := range solution { x := xRange[i] solution[i].X = x if i == 0 { solution[i].Y = y0 } else { x = solution[i - 1].X y := solution[i - 1].Y predict := y + (step / 2) * F(x, y) solution[i].Y = y + step * F(x + step / 2, predict) } } return solution } // RungeKutta returns data for plot building based on RungeKutta 4th-Order method. func RungeKutta(start, end, y0 float64, count int) plotter.XYs { step, xRange := GetRange(start, end, count) solution := make(plotter.XYs, count) for i := range solution { x := xRange[i] solution[i].X = x if i == 0 { solution[i].Y = y0 } else { x = solution[i - 1].X y := solution[i - 1].Y k1 := step * F(x, y) k2 := step * F(x + step / 2, y + k1 / 2) k3 := step * F(x + step / 2, y + k2 / 2) k4 := step * F(x + step, y + k3) solution[i].Y = y + (k1 / 6) + 2 * (k2 / 6) + 2 * (k3 / 6) + (k4 / 6) } } return solution } func ImplicitEuler(start, end, y0 float64, count int) plotter.XYs { step, xRange := GetRange(start, end, count) solution := make(plotter.XYs, count) for i := range solution { if i == len(solution) - 1 { break } x := xRange[i + 1] solution[i].X = x if i == 0 { solution[i].Y = y0 } else { prevY := solution[i - 1].Y g := func(y float64) float64 { return prevY + step * F(x, y) } yn1 := SimpleIteration(prevY, g) solution[i].Y = g(yn1) } } return solution } // Tailor2nd returns data for plot building based on Tailor 2nd-Order method. func Tailor2nd(start, end, y0 float64, count int) plotter.XYs { step, xRange := GetRange(start, end, count) solution := make(plotter.XYs, count) for i := range solution { x := xRange[i] solution[i].X = x if i == 0 { solution[i].Y = y0 } else { x = solution[i - 1].X y := solution[i - 1].Y solution[i].Y = y + step * F(x, y) + (math.Pow(step, 2) / 2) * SecondDerivative(x, y) } } return solution } // Tailor3rd returns data for plot building based on Tailor 3rd-Order method. func Tailor3rd(start, end, y0 float64, count int) plotter.XYs { step, xRange := GetRange(start, end, count) solution := make(plotter.XYs, count) for i := range solution { x := xRange[i] solution[i].X = x if i == 0 { solution[i].Y = y0 } else { x = solution[i - 1].X y := solution[i - 1].Y solution[i].Y = y + step * F(x, y) + (math.Pow(step, 2) / 2) * SecondDerivative(x, y) + (math.Pow(step, 3) / 6) * ThirdDerivative(x, y) } } return solution } // Adams returns data for plot building based on Adams 2nd-Order method. func Adams(start, end, y0 float64, count int) plotter.XYs { step, xRange := GetRange(start, end, count) solution := make(plotter.XYs, count) for i := range solution { x := xRange[i] solution[i].X = x if i == 0 { solution[i].Y = y0 } else { xn1 := x xn := solution[i - 1].X yn := solution[i - 1].Y fn := F(xn, yn) g := func(y float64) float64 { return yn + step / 2 * (fn + F(xn1, y)) } yn1 := SimpleIteration(yn, g) solution[i].Y = g(yn1) } } return solution } func Dichotomy(a, b float64, f func(float64) float64) float64 { epsilon := 0.00000001 fa := f(a) fb := f(b) if fa == 0 { return a } if fb == 0 { return b } if fa * fb > 0 { fmt.Println("Dichotomy error: fa * fb > 0") os.Exit(1) } for math.Abs(a - b) > epsilon { c := (a + b) / 2 fc := f(c) if fc == 0 { return c } if fc * fa < 0 { b = c fb = fc continue } if fc * fb < 0 { a = c fa = fc continue } fmt.Println("Dichotomy error: fc * fb < 0") os.Exit(1) } return (a + b) / 2 }
methods.go
0.787278
0.536374
methods.go
starcoder
package level import ( m "github.com/divVerent/aaaaxy/internal/math" ) // Contents indicates what kind of tiles/objects we want to hit. type Contents int const ( NoContents Contents = 0 OpaqueContents Contents = 1 PlayerSolidContents Contents = 2 ObjectSolidContents Contents = 4 SolidContents Contents = PlayerSolidContents | ObjectSolidContents ) func (c Contents) Empty() bool { return c == NoContents } func (c Contents) Opaque() bool { return c&OpaqueContents != 0 } func (c Contents) PlayerSolid() bool { return c&PlayerSolidContents != 0 } func (c Contents) ObjectSolid() bool { return c&ObjectSolidContents != 0 } type VisibilityFlags int const ( FrameVis VisibilityFlags = 1 TracedVis VisibilityFlags = 2 ) // A Tile is a single game tile. type Tile struct { // Info needed for gameplay. Contents Contents Spawnables []*Spawnable // NOTE: not adjusted for transform! // Info needed for loading more tiles. LevelPos m.Pos Transform m.Orientation VisibilityFlags VisibilityFlags // Info needed for rendering. Orientation m.Orientation ImageSrc string // If provided, these are used instead of image for "nicer" rotation (e.g. for shadow effects). // Because Orientation is also set, looking these up is tricky; we want things to show up as in the editor but potentially rotated. // We know: // - Transform * Orientation = orientationInEditor // - If we pick tile I and render at orientation O, we actually render at full orientation O * I. // - BUT lighting direction orientation is just O. // - we want O = orientationInEditor. // - Solve: Orientation = orientationInEditor * I // - Orientation = (Transform * Orientation) * I // - O = Transform Orientation // - I = O^-1 Orientation imageSrcByOrientation map[m.Orientation]string // Debug info. LoadedFromNeighbor m.Pos } // ResolveImage applies imageSrcByOrientation data to Image, and possibly changes Orientation when it did. func (t *Tile) ResolveImage() { t.ImageSrc, t.Orientation = ResolveImage(t.Transform, t.Orientation, t.ImageSrc, t.imageSrcByOrientation) t.imageSrcByOrientation = nil } // ResolveImage applies the given imageSrcByOrientation map. func ResolveImage(transform, orientation m.Orientation, defaultImageSrc string, imageSrcByOrientation map[m.Orientation]string) (string, m.Orientation) { renderOrientation := transform.Concat(orientation) spriteOrientation := renderOrientation.Inverse().Concat(orientation) imageSrc, found := imageSrcByOrientation[spriteOrientation] if found { return imageSrc, renderOrientation } return defaultImageSrc, orientation }
internal/level/tile.go
0.742515
0.529568
tile.go
starcoder
package eval import ( "fmt" "panda/ast" "strings" ) func (inter *Interpreter) evalAddExpression(express *ast.InfixExpression) (interface{}, error) { leftValue, err := inter.evalExpress(express.Left) if err != nil { return nil, err } rightValue, err := inter.evalExpress(express.Right) if err != nil { return nil, err } switch left := leftValue.(type) { case int64: switch right := rightValue.(type) { case int64: return left + right, nil case float64: return float64(left) + right, nil case string: return fmt.Sprintf("%d", left) + right, nil default: return nil, fmt.Errorf("参数类型错误") } case float64: switch right := rightValue.(type) { case int64: return left + float64(right), nil case float64: return float64(left) + right, nil default: return nil, fmt.Errorf("参数类型错误") } case string: switch right := rightValue.(type) { case int64: return left + fmt.Sprintf("%d", right), nil case string: return left + right, nil default: return nil, fmt.Errorf("参数类型错误") } default: return nil, fmt.Errorf("参数类型错误") } } func (inter *Interpreter) evalSubExpression(express *ast.InfixExpression) (interface{}, error) { leftValue, err := inter.evalExpress(express.Left) if err != nil { return nil, err } rightValue, err := inter.evalExpress(express.Right) if err != nil { return nil, err } switch left := leftValue.(type) { case int64: switch right := rightValue.(type) { case int64: return left - right, nil case float64: return float64(left) - right, nil default: return nil, fmt.Errorf("参数类型错误") } case float64: switch right := rightValue.(type) { case int64: return left - float64(right), nil case float64: return float64(left) - right, nil default: return nil, fmt.Errorf("参数类型错误") } default: return nil, fmt.Errorf("参数类型错误") } } func (inter *Interpreter) evalMulExpression(express *ast.InfixExpression) (interface{}, error) { leftValue, err := inter.evalExpress(express.Left) if err != nil { return nil, err } rightValue, err := inter.evalExpress(express.Right) if err != nil { return nil, err } switch left := leftValue.(type) { case int64: switch right := rightValue.(type) { case int64: return left * right, nil case float64: return float64(left) * right, nil default: return nil, fmt.Errorf("参数类型错误") } case float64: switch right := rightValue.(type) { case int64: return left * float64(right), nil case float64: return float64(left) * right, nil default: return nil, fmt.Errorf("参数类型错误") } case string: switch right := rightValue.(type) { case int64: if right < 1 { return nil, fmt.Errorf("参数类型错误") } for i := int64(1); i < right; i++ { left += left } return left, nil default: return nil, fmt.Errorf("参数类型错误") } default: return nil, fmt.Errorf("参数类型错误") } } func (inter *Interpreter) evalDivExpression(express *ast.InfixExpression) (interface{}, error) { leftValue, err := inter.evalExpress(express.Left) if err != nil { return nil, err } rightValue, err := inter.evalExpress(express.Right) if err != nil { return nil, err } switch left := leftValue.(type) { case int64: switch right := rightValue.(type) { case int64: return left / right, nil case float64: return float64(left) / right, nil default: return nil, fmt.Errorf("参数类型错误") } case float64: switch right := rightValue.(type) { case int64: return left / float64(right), nil case float64: return float64(left) / right, nil default: return nil, fmt.Errorf("参数类型错误") } default: return nil, fmt.Errorf("参数类型错误") } } // > func (inter *Interpreter) evalGtExpression(express *ast.InfixExpression) (interface{}, error) { leftValue, err := inter.evalExpress(express.Left) if err != nil { return nil, err } rightValue, err := inter.evalExpress(express.Right) if err != nil { return nil, err } switch left := leftValue.(type) { case int64: switch right := rightValue.(type) { case int64: return left > right, nil case float64: return float64(left) > right, nil default: return nil, fmt.Errorf("参数类型错误") } case float64: switch right := rightValue.(type) { case int64: return left > float64(right), nil case float64: return float64(left) > right, nil default: return nil, fmt.Errorf("参数类型错误") } case string: switch right := rightValue.(type) { case string: return strings.Compare(left, right) > 0, nil default: return nil, fmt.Errorf("参数类型错误") } default: return nil, fmt.Errorf("参数类型错误") } } // < func (inter *Interpreter) evalLeExpression(express *ast.InfixExpression) (interface{}, error) { leftValue, err := inter.evalExpress(express.Left) if err != nil { return nil, err } rightValue, err := inter.evalExpress(express.Right) if err != nil { return nil, err } switch left := leftValue.(type) { case int64: switch right := rightValue.(type) { case int64: return left < right, nil case float64: return float64(left) < right, nil default: return nil, fmt.Errorf("参数类型错误") } case float64: switch right := rightValue.(type) { case int64: return left < float64(right), nil case float64: return float64(left) < right, nil default: return nil, fmt.Errorf("参数类型错误") } case string: switch right := rightValue.(type) { case string: return strings.Compare(left, right) < 0, nil default: return nil, fmt.Errorf("参数类型错误") } default: return nil, fmt.Errorf("参数类型错误") } } // >= func (inter *Interpreter) evalGteExpression(express *ast.InfixExpression) (interface{}, error) { leftValue, err := inter.evalExpress(express.Left) if err != nil { return nil, err } rightValue, err := inter.evalExpress(express.Right) if err != nil { return nil, err } switch left := leftValue.(type) { case int64: switch right := rightValue.(type) { case int64: return left >= right, nil case float64: return float64(left) >= right, nil default: return nil, fmt.Errorf("参数类型错误") } case float64: switch right := rightValue.(type) { case int64: return left >= float64(right), nil case float64: return float64(left) >= right, nil default: return nil, fmt.Errorf("参数类型错误") } case string: switch right := rightValue.(type) { case string: return strings.Compare(left, right) >= 0, nil default: return nil, fmt.Errorf("参数类型错误") } default: return nil, fmt.Errorf("参数类型错误") } } // <= func (inter *Interpreter) evalLeeExpression(express *ast.InfixExpression) (interface{}, error) { leftValue, err := inter.evalExpress(express.Left) if err != nil { return nil, err } rightValue, err := inter.evalExpress(express.Right) if err != nil { return nil, err } switch left := leftValue.(type) { case int64: switch right := rightValue.(type) { case int64: return left <= right, nil case float64: return float64(left) <= right, nil default: return nil, fmt.Errorf("参数类型错误") } case float64: switch right := rightValue.(type) { case int64: return left <= float64(right), nil case float64: return float64(left) <= right, nil default: return nil, fmt.Errorf("参数类型错误") } case string: switch right := rightValue.(type) { case string: return strings.Compare(left, right) <= 0, nil default: return nil, fmt.Errorf("参数类型错误") } default: return nil, fmt.Errorf("参数类型错误") } } func (inter *Interpreter) evalEQExpression(express *ast.InfixExpression) (interface{}, error) { leftValue, err := inter.evalExpress(express.Left) if err != nil { return nil, err } rightValue, err := inter.evalExpress(express.Right) if err != nil { return nil, err } switch left := leftValue.(type) { case int64: switch right := rightValue.(type) { case int64: return left == right, nil case float64: return float64(left) == right, nil default: return nil, fmt.Errorf("参数类型错误") } case float64: switch right := rightValue.(type) { case int64: return left == float64(right), nil case float64: return float64(left) == right, nil default: return nil, fmt.Errorf("参数类型错误") } case string: switch right := rightValue.(type) { case string: return strings.Compare(left, right) == 0, nil default: return nil, fmt.Errorf("参数类型错误") } default: return nil, fmt.Errorf("参数类型错误") } } // || func (inter *Interpreter) evalLogicORExpression(express *ast.InfixExpression) (interface{}, error) { leftValue, err := inter.evalExpress(express.Left) if err != nil { return nil, err } rightValue, err := inter.evalExpress(express.Right) if err != nil { return nil, err } left, ok := leftValue.(bool) if !ok { return nil, fmt.Errorf("参数类型错误 期待bool值") } right, ok := rightValue.(bool) if !ok { return nil, fmt.Errorf("参数类型错误 期待bool值") } return left || right, nil } // && func (inter *Interpreter) evalLogicANDExpression(express *ast.InfixExpression) (interface{}, error) { leftValue, err := inter.evalExpress(express.Left) if err != nil { return nil, err } rightValue, err := inter.evalExpress(express.Right) if err != nil { return nil, err } left, ok := leftValue.(bool) if !ok { return nil, fmt.Errorf("参数类型错误 期待bool值") } right, ok := rightValue.(bool) if !ok { return nil, fmt.Errorf("参数类型错误 期待bool值") } return left && right, nil }
eval/eval_infixexpress.go
0.52683
0.481332
eval_infixexpress.go
starcoder
package textencoding const baseWinAnsi = "WinAnsiEncoding" var ( winAnsi = newSimpleMapping(baseWinAnsi, winAnsiCharToRune) ) func init() { RegisterSimpleEncoding(baseWinAnsi, NewWinAnsiEncoder) } // NewWinAnsiEncoder returns a simpleEncoder that implements WinAnsiEncoding. func NewWinAnsiEncoder() SimpleEncoder { return winAnsi.NewEncoder() } var winAnsiCharToRune = map[byte]rune{ // 224 entries 0x20: ' ', 0x21: '!', 0x22: '"', 0x23: '#', 0x24: '$', 0x25: '%', 0x26: '&', 0x27: '\'', 0x28: '(', 0x29: ')', 0x2a: '*', 0x2b: '+', 0x2c: ',', 0x2d: '-', 0x2e: '.', 0x2f: '/', 0x30: '0', 0x31: '1', 0x32: '2', 0x33: '3', 0x34: '4', 0x35: '5', 0x36: '6', 0x37: '7', 0x38: '8', 0x39: '9', 0x3a: ':', 0x3b: ';', 0x3c: '<', 0x3d: '=', 0x3e: '>', 0x3f: '?', 0x40: '@', 0x41: 'A', 0x42: 'B', 0x43: 'C', 0x44: 'D', 0x45: 'E', 0x46: 'F', 0x47: 'G', 0x48: 'H', 0x49: 'I', 0x4a: 'J', 0x4b: 'K', 0x4c: 'L', 0x4d: 'M', 0x4e: 'N', 0x4f: 'O', 0x50: 'P', 0x51: 'Q', 0x52: 'R', 0x53: 'S', 0x54: 'T', 0x55: 'U', 0x56: 'V', 0x57: 'W', 0x58: 'X', 0x59: 'Y', 0x5a: 'Z', 0x5b: '[', 0x5c: '\\', 0x5d: ']', 0x5e: '^', 0x5f: '_', 0x60: '`', 0x61: 'a', 0x62: 'b', 0x63: 'c', 0x64: 'd', 0x65: 'e', 0x66: 'f', 0x67: 'g', 0x68: 'h', 0x69: 'i', 0x6a: 'j', 0x6b: 'k', 0x6c: 'l', 0x6d: 'm', 0x6e: 'n', 0x6f: 'o', 0x70: 'p', 0x71: 'q', 0x72: 'r', 0x73: 's', 0x74: 't', 0x75: 'u', 0x76: 'v', 0x77: 'w', 0x78: 'x', 0x79: 'y', 0x7a: 'z', 0x7b: '{', 0x7c: '|', 0x7d: '}', 0x7e: '~', 0x7f: '•', 0x80: '€', 0x81: '•', 0x82: '‚', 0x83: 'ƒ', 0x84: '„', 0x85: '…', 0x86: '†', 0x87: '‡', 0x88: 'ˆ', 0x89: '‰', 0x8a: 'Š', 0x8b: '‹', 0x8c: 'Œ', 0x8d: '•', 0x8e: 'Ž', 0x8f: '•', 0x90: '•', 0x91: '‘', 0x92: '’', 0x93: '“', 0x94: '”', 0x95: '•', 0x96: '–', 0x97: '—', 0x98: '˜', 0x99: '™', 0x9a: 'š', 0x9b: '›', 0x9c: 'œ', 0x9d: '•', 0x9e: 'ž', 0x9f: 'Ÿ', 0xa0: ' ', 0xa1: '¡', 0xa2: '¢', 0xa3: '£', 0xa4: '¤', 0xa5: '¥', 0xa6: '¦', 0xa7: '§', 0xa8: '¨', 0xa9: '©', 0xaa: 'ª', 0xab: '«', 0xac: '¬', 0xad: '-', 0xae: '®', 0xaf: '¯', 0xb0: '°', 0xb1: '±', 0xb2: '²', 0xb3: '³', 0xb4: '´', 0xb5: 'µ', 0xb6: '¶', 0xb7: '·', 0xb8: '¸', 0xb9: '¹', 0xba: 'º', 0xbb: '»', 0xbc: '¼', 0xbd: '½', 0xbe: '¾', 0xbf: '¿', 0xc0: 'À', 0xc1: 'Á', 0xc2: 'Â', 0xc3: 'Ã', 0xc4: 'Ä', 0xc5: 'Å', 0xc6: 'Æ', 0xc7: 'Ç', 0xc8: 'È', 0xc9: 'É', 0xca: 'Ê', 0xcb: 'Ë', 0xcc: 'Ì', 0xcd: 'Í', 0xce: 'Î', 0xcf: 'Ï', 0xd0: 'Ð', 0xd1: 'Ñ', 0xd2: 'Ò', 0xd3: 'Ó', 0xd4: 'Ô', 0xd5: 'Õ', 0xd6: 'Ö', 0xd7: '×', 0xd8: 'Ø', 0xd9: 'Ù', 0xda: 'Ú', 0xdb: 'Û', 0xdc: 'Ü', 0xdd: 'Ý', 0xde: 'Þ', 0xdf: 'ß', 0xe0: 'à', 0xe1: 'á', 0xe2: 'â', 0xe3: 'ã', 0xe4: 'ä', 0xe5: 'å', 0xe6: 'æ', 0xe7: 'ç', 0xe8: 'è', 0xe9: 'é', 0xea: 'ê', 0xeb: 'ë', 0xec: 'ì', 0xed: 'í', 0xee: 'î', 0xef: 'ï', 0xf0: 'ð', 0xf1: 'ñ', 0xf2: 'ò', 0xf3: 'ó', 0xf4: 'ô', 0xf5: 'õ', 0xf6: 'ö', 0xf7: '÷', 0xf8: 'ø', 0xf9: 'ù', 0xfa: 'ú', 0xfb: 'û', 0xfc: 'ü', 0xfd: 'ý', 0xfe: 'þ', 0xff: 'ÿ', }
bot/vendor/github.com/pzduniak/unipdf/internal/textencoding/simple_winansi.go
0.565539
0.405007
simple_winansi.go
starcoder
package maze // visitedCells represents the cells whose numbers are mapped to their respective addresses. // It is used in creating and navigating through the maze. var visitedCells = map[int]cellAddress{} // Dimensions defines the actual number of cells that make up the maze along the vertical and // the horizontal edges. Length represents the number of the cells along the horizontal // edge while Width represents the number of the cells along the vertical edge. type Dimensions struct { Length int Width int StartPosition []int FinalPosition []int } // generateMaze converts the created grid view playing field into a series on paths and walls. // The Maze is created such that only a single path can exists between the starting point and // and the goal. func (config *Dimensions) generateMaze(intensity int) ([][]string, error) { var neighbors []int startPos := config.getStartPosition() finalPos, cellsPath, currentPos := []int{1, startPos}, []int{startPos}, startPos maze, err := config.createPlayingField(intensity) if err != nil { return [][]string{}, err } config.StartPosition = config.getCellAddress(startPos).MiddleCenter visitedCells[currentPos] = config.getCellAddress(currentPos) cellsPath = append(cellsPath, currentPos) for len(visitedCells) < (config.Length * config.Width) { for { neighbors = config.getPresentNeighbors(currentPos) if len(neighbors) > 0 { break } cellsPath, currentPos = cellsPath[:len(cellsPath)-1], cellsPath[len(cellsPath)-1] } startPos = neighbors[getRandomNo(len(neighbors))] if _, ok := visitedCells[startPos]; !ok { visitedCells[startPos] = config.getCellAddress(startPos) config.createPath(maze[:], currentPos, startPos) cellsPath = append(cellsPath, startPos) if len(cellsPath) > finalPos[0] { finalPos[:][1], finalPos[:][0] = startPos, len(cellsPath) } currentPos = startPos } } config.FinalPosition = config.getCellAddress(finalPos[1]).MiddleCenter return maze[:], config.optimizeMaze(intensity, maze[:]) } // createPath creates a path on the common wall between the current and the new cell. // A path is created by replacing the wall characters with the respective number of blank spaces. // Wall characters are defined by the intensity value used while creating the grid view. func (config *Dimensions) createPath(maze [][]string, currentCellNo, newCellNo int) { addr := config.getCellAddress(currentCellNo) neighbors := config.getCellNeighbors(currentCellNo) switch newCellNo { case neighbors.Bottom: maze[addr.BottomCenter[0]][addr.BottomCenter[1]] = " " case neighbors.Left: maze[addr.MiddleLeft[0]][addr.MiddleLeft[1]] = " " case neighbors.Right: maze[addr.MiddleRight[0]][addr.MiddleRight[1]] = " " case neighbors.Top: maze[addr.TopCenter[0]][addr.TopCenter[1]] = " " } } // getPresentNeighbors returns a slice of the neigboring cells associated with the cell number provided. // Only neighboring cells with no common paths to others cells that are returned. i.e. Non-Visited Cells. func (config *Dimensions) getPresentNeighbors(cellNo int) []int { var ( ok bool presentCells []int neighbors = config.getCellNeighbors(cellNo) ) for _, neighbor := range []int{neighbors.Bottom, neighbors.Left, neighbors.Right, neighbors.Top} { if _, ok = visitedCells[neighbor]; !ok && neighbor != 0 { presentCells = append(presentCells, neighbor) } } return presentCells } // getStartPosition returns the cell which becomes the maze traversal starting position. // The starting position can only be a cell along the maze edges i.e. has less than four // neighbors. When getStartPosition is called, all cells are have no common paths to other cells. func (config *Dimensions) getStartPosition() int { var ( neighbors []int randCellNo int ) for { randCellNo = getRandomNo((config.Length * config.Width) + 1) neighbors = config.getPresentNeighbors(randCellNo) if len(neighbors) < 4 && randCellNo != 0 { return randCellNo } } } // optimizeMaze replaces some wall characters so as the maze can // be more clear and sharp when printed on the terminal. func (config *Dimensions) optimizeMaze(intensity int, maze [][]string) error { var ( addr cellAddress chars []string err error ) // This error will never be caught if chars, err = getWallCharacters(intensity); err != nil { panic(err) } for cell := 1; cell <= (config.Length * config.Width); cell++ { addr = config.getCellAddress(cell) config.replaceChar(addr.BottomRight, chars[2], maze) config.replaceChar(addr.TopRight, chars[2], maze) } return nil } // replaceChar switches left and right wall character with a top and bottom wall character. func (config *Dimensions) replaceChar(point []int, replChar string, maze [][]string) { elemTop, elemBottom := "", "" lenTop, lenBottom := false, false // checks if the top point in relation to the given point can be calculated if (point[0] - 1) > 0 { elemTop = maze[point[0]-1][point[1]] lenTop = true } // checks if the bottom point in relation to the given point can be calculated if (point[0] + 1) <= (config.Width * 2) { elemBottom = maze[point[0]+1][point[1]] lenBottom = true } switch { case !lenTop && lenBottom && isSpaceFound(elemBottom): maze[point[0]][point[1]] = replChar case lenTop && !lenBottom && isSpaceFound(elemTop): maze[point[0]][point[1]] = replChar case lenTop && lenBottom && isSpaceFound(elemBottom) && isSpaceFound(elemTop): maze[point[0]][point[1]] = replChar } }
maze/maze.go
0.798305
0.652684
maze.go
starcoder
package pwned // This borrows from <NAME>'s great (real) Bloom filter. // See https://github.com/yourbasic/bloom import ( "context" "encoding/binary" "io" "math" pb "github.com/pedrosland/pwned-check/proto" ) const ( shift = 6 mask = 0x3f ) // Filter represents a kind-of-Bloom filter. type Filter struct { data []uint64 // Bit array, the length is a power of 2. lookups int // Lookups per query count int64 // Estimate number of elements } // NewFilter creates an empty kind-of-Bloom filter with room for n elements // at a false-positive rate less than 1/p. // It is kind-of because it doesn't actully hash the data itself but // assumes that data is already hashed. func NewFilter(n int, p int) *Filter { minWords := int(0.0325 * math.Log(float64(p)) * float64(n)) words := 1 for words < minWords { words *= 2 } return &Filter{ data: make([]uint64, words), lookups: int(1.4*math.Log(float64(p)) + 1), } } // AddHash adds s to the filter and tells if s was already a likely member. func (f *Filter) AddHash(b []byte) bool { // yes, we are losing data here h1 := binary.BigEndian.Uint64(b[0:8]) ^ uint64(binary.BigEndian.Uint32(b[8:12])) h2 := binary.BigEndian.Uint64(b[12:]) trunc := uint64(len(f.data))<<shift - 1 member := true for i := f.lookups; i > 0; i-- { h1 += h2 n := h1 & trunc k, b := n>>shift, uint64(1<<uint(n&mask)) if f.data[k]&b == 0 { member = false f.data[k] |= b } } if !member { f.count++ } return member } // TestHash tells if s is a likely member of the filter. // If true, s is probably a member; if false, s is definitely not a member. func (f *Filter) TestHash(b []byte) bool { h1 := binary.BigEndian.Uint64(b[0:8]) ^ uint64(binary.BigEndian.Uint32(b[8:12])) h2 := binary.BigEndian.Uint64(b[12:]) trunc := uint64(len(f.data))<<shift - 1 for i := f.lookups; i > 0; i-- { h1 += h2 n := h1 & trunc k, b := n>>shift, uint64(1<<uint(n&mask)) if f.data[k]&b == 0 { return false } } return true } // Count returns an estimate of the number of elements in the filter. func (f *Filter) Count() int64 { return f.count } func (f Filter) getPB() *pb.State_Filter { return &pb.State_Filter{ Count: f.count, Lookups: int32(f.lookups), Size: int64(len(f.data) * 8), } } func (f Filter) writeBytes(w io.Writer) (int, error) { b := make([]byte, 8, 8) for i := 0; i < len(f.data); i++ { binary.BigEndian.PutUint64(b, f.data[i]) _, err := w.Write(b) if err != nil { return (i - 1) * 8, err } } return len(f.data) * 8, nil } func filterFrom(ctx context.Context, state *pb.State_Filter, r io.Reader) (*Filter, error) { data := make([]uint64, state.Size/8) b := make([]byte, 8, 8) for i := 0; i < len(data); i++ { _, err := r.Read(b) if err != nil && i < len(data)-1 { return nil, err } select { case <-ctx.Done(): return nil, context.Canceled default: } data[i] = binary.BigEndian.Uint64(b) } f := &Filter{ count: state.Count, data: data, lookups: int(state.Lookups), } return f, nil }
filter.go
0.727879
0.402568
filter.go
starcoder
package advent import ( "github.com/davidparks11/advent2021/internal/math" ) var _ Problem = &theTreacheryOfWhales{} type theTreacheryOfWhales struct { dailyProblem } func NewTheTreacheryOfWhales() Problem { return &theTreacheryOfWhales{ dailyProblem{ day: 7, }, } } func (t *theTreacheryOfWhales) Solve() interface{} { input := t.GetInputLines() var results []int results = append(results, t.minCostLinear(input)) results = append(results, t.minCostExponential(input)) return results } /* A giant whale has decided your submarine is its next meal, and it's much faster than you are. There's nowhere to run! Suddenly, a swarm of crabs (each in its own tiny submarine - it's too deep for them otherwise) zooms in to rescue you! They seem to be preparing to blast a hole in the ocean floor; sensors indicate a massive underground cave system just beyond where they're aiming! The crab submarines all need to be aligned before they'll have enough power to blast a large enough hole for your submarine to get through. However, it doesn't look like they'll be aligned before the whale catches you! Maybe you can help? There's one major catch - crab submarines can only move horizontally. You quickly make a list of the horizontal position of each crab (your puzzle input). Crab submarines have limited fuel, so you need to find a way to make all of their horizontal positions match while requiring them to spend as little fuel as possible. For example, consider the following horizontal positions: 16,1,2,0,4,2,7,1,2,14 This means there's a crab with horizontal position 16, a crab with horizontal position 1, and so on. Each change of 1 step in horizontal position of a single crab costs 1 fuel. You could choose any horizontal position to align them all on, but the one that costs the least fuel is horizontal position 2: Move from 16 to 2: 14 fuel Move from 1 to 2: 1 fuel Move from 2 to 2: 0 fuel Move from 0 to 2: 2 fuel Move from 4 to 2: 2 fuel Move from 2 to 2: 0 fuel Move from 7 to 2: 5 fuel Move from 1 to 2: 1 fuel Move from 2 to 2: 0 fuel Move from 14 to 2: 12 fuel This costs a total of 37 fuel. This is the cheapest possible outcome; more expensive outcomes include aligning at position 1 (41 fuel), position 3 (39 fuel), or position 10 (71 fuel). Determine the horizontal position that the crabs can align to using the least fuel possible. How much fuel must they spend to align to that position? */ func (t *theTreacheryOfWhales) minCostLinear(input []string) int { return t.calcMinFuelCost(CommaSplitInts( input[0]), func(pos, dest int) int { return math.Abs(pos - dest) }, ) } /* The crabs don't seem interested in your proposed solution. Perhaps you misunderstand crab engineering? As it turns out, crab submarine engines don't burn fuel at a constant rate. Instead, each change of 1 step in horizontal position costs 1 more unit of fuel than the last: the first step costs 1, the second step costs 2, the third step costs 3, and so on. As each crab moves, moving further becomes more expensive. This changes the best horizontal position to align them all on; in the example above, this becomes 5: Move from 16 to 5: 66 fuel Move from 1 to 5: 10 fuel Move from 2 to 5: 6 fuel Move from 0 to 5: 15 fuel Move from 4 to 5: 1 fuel Move from 2 to 5: 6 fuel Move from 7 to 5: 3 fuel Move from 1 to 5: 10 fuel Move from 2 to 5: 6 fuel Move from 14 to 5: 45 fuel This costs a total of 168 fuel. This is the new cheapest possible outcome; the old alignment position (2) now costs 206 fuel instead. Determine the horizontal position that the crabs can align to using the least fuel possible so they can make you an escape route! How much fuel must they spend to align to that position? */ func (t *theTreacheryOfWhales) minCostExponential(input []string) int { return t.calcMinFuelCost(CommaSplitInts( input[0]), func(pos, dest int) int { dist := math.Abs(pos - dest) return dist * (dist + 1) / 2 //close form of Summation of natural numbers f(n) = 1 + 2 + 3 + 4 + ... + n }, ) } func (t *theTreacheryOfWhales) calcMinFuelCost(crabPositions []int, cost func(pos int, dest int) int) int { min := crabPositions[0] max := crabPositions[0] for i := 0; i < len(crabPositions); i++ { if crabPositions[i] < min { min = crabPositions[i] } if crabPositions[i] > max { max = crabPositions[i] } } //neither elegant nor efficient, but it's late, so this'll do minFuelCost := -1 for destination := min; destination <= max; destination++ { fuelCost := 0 for _, pos := range crabPositions { fuelCost += cost(pos, destination) } if minFuelCost == -1 || fuelCost < minFuelCost { minFuelCost = fuelCost } } return minFuelCost }
internal/advent/day7.go
0.572245
0.556701
day7.go
starcoder
package gubernator import ( "time" ) // Implements token bucket algorithm for rate limiting. https://en.wikipedia.org/wiki/Token_bucket func tokenBucket(s Store, c Cache, r *RateLimitReq) (resp *RateLimitResp, err error) { item, ok := c.GetItem(r.HashKey()) if s != nil { if !ok { // Check our store for the item if item, ok = s.Get(r); ok { c.Add(item) } } } if ok { // The following semantic allows for requests of more than the limit to be rejected, but subsequent // requests within the same duration that are under the limit to succeed. IE: client attempts to // send 1000 emails but 100 is their limit. The request is rejected as over the limit, but since we // don't store OVER_LIMIT in the cache the client can retry within the same rate limit duration with // 100 emails and the request will succeed. rl, ok := item.Value.(*RateLimitResp) if !ok { // Client switched algorithms; perhaps due to a migration? c.Remove(r.HashKey()) if s != nil { s.Remove(r.HashKey()) } return tokenBucket(s, c, r) } // Client is only interested in retrieving the current status if r.Hits == 0 { return rl, nil } if s != nil { defer func() { s.OnChange(r, item) }() } // If we are already at the limit if rl.Remaining == 0 { rl.Status = Status_OVER_LIMIT return rl, nil } // If requested hits takes the remainder if rl.Remaining == r.Hits { rl.Remaining = 0 return rl, nil } // If requested is more than available, then return over the limit without updating the cache. if r.Hits > rl.Remaining { retStatus := *rl retStatus.Status = Status_OVER_LIMIT return &retStatus, nil } rl.Remaining -= r.Hits return rl, nil } // Add a new rate limit to the cache expire := MillisecondNow() + r.Duration if r.Behavior == Behavior_DURATION_IS_GREGORIAN { expire, err = GregorianExpiration(time.Now(), r.Duration) if err != nil { return nil, err } } status := &RateLimitResp{ Status: Status_UNDER_LIMIT, Limit: r.Limit, Remaining: r.Limit - r.Hits, ResetTime: expire, } // Client could be requesting that we always return OVER_LIMIT if r.Hits > r.Limit { status.Status = Status_OVER_LIMIT status.Remaining = r.Limit } item = &CacheItem{ Algorithm: r.Algorithm, Key: r.HashKey(), Value: status, ExpireAt: expire, } c.Add(item) if s != nil { s.OnChange(r, item) } return status, nil } // Implements leaky bucket algorithm for rate limiting https://en.wikipedia.org/wiki/Leaky_bucket func leakyBucket(s Store, c Cache, r *RateLimitReq) (resp *RateLimitResp, err error) { now := MillisecondNow() item, ok := c.GetItem(r.HashKey()) if s != nil { if !ok { // Check our store for the item if item, ok = s.Get(r); ok { c.Add(item) } } } if ok { b, ok := item.Value.(*LeakyBucketItem) if !ok { // Client switched algorithms; perhaps due to a migration? c.Remove(r.HashKey()) if s != nil { s.Remove(r.HashKey()) } return leakyBucket(s, c, r) } duration := r.Duration rate := duration / r.Limit if r.Behavior == Behavior_DURATION_IS_GREGORIAN { d, err := GregorianDuration(time.Now(), r.Duration) if err != nil { return nil, err } n := time.Now() expire, err := GregorianExpiration(n, r.Duration) if err != nil { return nil, err } // Calculate the rate using the entire duration of the gregorian interval // IE: Minute = 60,000 milliseconds, etc.. etc.. rate = d / r.Limit // Update the duration to be the end of the gregorian interval duration = expire - (n.UnixNano() / 1000000) } // Calculate how much leaked out of the bucket since the last hit elapsed := now - b.TimeStamp leak := int64(elapsed / rate) b.Remaining += leak if b.Remaining > b.Limit { b.Remaining = b.Limit } rl := &RateLimitResp{ Limit: b.Limit, Remaining: b.Remaining, Status: Status_UNDER_LIMIT, } if s != nil { defer func() { s.OnChange(r, item) }() } // If we are already at the limit if b.Remaining == 0 { rl.Status = Status_OVER_LIMIT rl.ResetTime = now + rate return rl, nil } // Only update the timestamp if client is incrementing the hit if r.Hits != 0 { b.TimeStamp = now } // If requested hits takes the remainder if b.Remaining == r.Hits { b.Remaining = 0 rl.Remaining = 0 return rl, nil } // If requested is more than available, then return over the limit // without updating the bucket. if r.Hits > b.Remaining { rl.Status = Status_OVER_LIMIT rl.ResetTime = now + rate return rl, nil } // Client is only interested in retrieving the current status if r.Hits == 0 { return rl, nil } b.Remaining -= r.Hits rl.Remaining = b.Remaining c.UpdateExpiration(r.HashKey(), now*duration) return rl, nil } duration := r.Duration if r.Behavior == Behavior_DURATION_IS_GREGORIAN { n := time.Now() expire, err := GregorianExpiration(n, r.Duration) if err != nil { return nil, err } // Set the initial duration as the remainder of time until // the end of the gregorian interval. duration = expire - (n.UnixNano() / 1000000) } // Create a new leaky bucket b := LeakyBucketItem{ Remaining: r.Limit - r.Hits, Limit: r.Limit, Duration: duration, TimeStamp: now, } rl := RateLimitResp{ Status: Status_UNDER_LIMIT, Limit: r.Limit, Remaining: r.Limit - r.Hits, ResetTime: 0, } // Client could be requesting that we start with the bucket OVER_LIMIT if r.Hits > r.Limit { rl.Status = Status_OVER_LIMIT rl.Remaining = 0 b.Remaining = 0 } item = &CacheItem{ ExpireAt: now + duration, Algorithm: r.Algorithm, Key: r.HashKey(), Value: &b, } c.Add(item) if s != nil { s.OnChange(r, item) } return &rl, nil }
algorithms.go
0.679285
0.406273
algorithms.go
starcoder
package trie // Trie Represent a node of trie // Not advised to create the node directly. Use helper function CreateNode() instead type Trie struct { Node } // New Creates an initialized trie data structure func New() *Trie { return &Trie{ *CreateNode(0), } } // Insert allow one or more keyword to be inserted in trie // keyword can be any unicode string func (t *Trie) Insert(keywords ...string) *Trie { for _, v := range keywords { t.insert(v) } return t } func (t *Trie) insert(keyword string) { node := &t.Node for _, v := range []rune(keyword) { node = node.AddChildNode(v) } node.IsEndOfWord = true } // PrefixSearch checks if keyword exist in trie as a keyword or prefix to a keyword func (t *Trie) PrefixSearch(key string) (found bool) { node := &t.Node for _, v := range []rune(key) { if n, ok := node.GetChildNode(v); ok { node = n found = ok continue } return false } return found } // Search checks if keyword exist in trie as a fully qualified keyword. func (t *Trie) Search(keyword string) (found bool) { node := &t.Node for _, v := range []rune(keyword) { if n, ok := node.GetChildNode(v); ok { node = n found = ok continue } return false } return found && node.IsEndOfWord } // Delete deletes a keyword from a trie if keyword exist in trie func (t *Trie) Delete(keyword string) { node := &t.Node var breakNode *Node var breakRune rune for _, v := range []rune(keyword) { if n, ok := node.GetChildNode(v); ok { if node.IsEndOfWord { breakNode = node breakRune = v } node = n continue } return } if !node.IsEndOfWord { return } if !node.IsLeafNode() { node.IsEndOfWord = false return } if breakNode == nil { breakNode = &t.Node breakRune = []rune(keyword)[0] } breakNode.DeleteChildNode(breakRune) } // DeleteBranch deletes all child after last letter of key if key exists in trie // If key is found, key will be treated as a keyword after this operation func (t *Trie) DeleteBranch(key string) { node := &t.Node for _, v := range []rune(key) { if n, ok := node.GetChildNode(v); ok { node = n continue } return } node.childIndexMap = make(map[rune]int) node.IsEndOfWord = true node.Children = make([]*Node, 0) }
trie.go
0.743075
0.536738
trie.go
starcoder
package fingerprint import ( "fmt" "math" "github.com/goccmack/godsp/ppeaks" ) // GetHighestMatchRate returns the highest match rate between the fingerprint of the sample and the fingerprint of the target audio. func GetHighestMatchRate(sampleFilename string, sampleFingerprint [][]int, audioFilename string, audioFingerprint [][]int) float64 { fmt.Printf("Comparing %s to %s\n", sampleFilename, audioFilename) highestMatchRate := -1.0 if len(sampleFingerprint) > len(audioFingerprint) { // sample is shorter than actual audio file return highestMatchRate } for i := 0; i <= len(audioFingerprint)-len(sampleFingerprint); i++ { // shift the sample fingerprint down the target audio's fingerprint matchRate := Compare(sampleFingerprint, audioFingerprint[i:i+len(sampleFingerprint)]) // get the match rate at this shift if matchRate > highestMatchRate { highestMatchRate = matchRate // update highest match rate } } return highestMatchRate } // Compare compares two 2-D slice and return the match rate a.k.a the number of matching elements over the total number of elements. func Compare(sourceFP [][]int, destFP [][]int) float64 { diffPositions := 0.0 for i := range sourceFP { for j := range sourceFP[i] { diffPositions += math.Abs(float64(sourceFP[i][j] - destFP[i][j])) // Add the absolute different between two elements } } totalPosition := float64(len(sourceFP) * len(sourceFP[0])) // number of elements in the 2-D array matchRate := 1 - (diffPositions / totalPosition) // 1 - non-match rate return matchRate } // Fingerprint takes a .wav file and output its fingerprint. func Fingerprint(filename string, winSize, hopSize int, windowFunction string, addNoise bool) [][]int { fmt.Printf("Fingerprinting %s\n", filename) signal := ReadWAV(filename) if addNoise { AddNoise(signal.Samples) } spect := Spectrogram(signal, winSize, hopSize, windowFunction) var res [][]int for _, s := range spect { p := ppeaks.GetPeaks(s) // peak picking function minPer, _ := p.MinMaxPersistence() // similar to prominent newSig := convertToBinary(s, p.GetIndices(minPer)) // convert all peaks to 1s, the rest to 0s res = append(res, newSig) } return res }
fingerprint/fingerprint.go
0.671686
0.486088
fingerprint.go
starcoder
package anomalies import ( "time" "gopkg.in/olivere/elastic.v5" "github.com/trackit/trackit-server/config" ) const ( // aggregationMaxSize is the maximum size of an Elastic Search Aggregation aggregationMaxSize = 0x7FFFFFFF // queryMaxSize is the maximum size of an Elastic Search Query queryMaxSize = 10000 ) // createQueryAccountFilter creates and return a new *elastic.TermQuery on the account func createQueryAccountFilter(account string) *elastic.TermQuery { return elastic.NewTermQuery("usageAccountId", account) } // createQueryTimeRange creates and return a new *elastic.RangeQuery based on the duration // defined by durationBegin and durationEnd. // durationBegin is reduced by period. This offset is deleted later. func createQueryTimeRange(durationBegin time.Time, durationEnd time.Time) *elastic.RangeQuery { periodDuration := time.Duration(config.AnomalyDetectionBollingerBandPeriod) * 24 * time.Hour durationBegin = durationBegin.Add(-periodDuration - 1) return elastic.NewRangeQuery("usageStartDate"). From(durationBegin).To(durationEnd) } // getProductElasticSearchParams is used to construct an ElasticSearch *elastic.SearchService // used to retrieve the average cost by usageType for each day. // It takes as parameters : // - account string : A string representing aws account number, in the format of the field // 'awsdetailedlineitem.linked_account_id' // - durationBeing time.Time : A time.Time struct representing the begining of the time range in the query // - durationEnd time.Time : A time.Time struct representing the end of the time range in the query // - aggregationPeriod string : An aggregation period, can be "day" // - client *elastic.Client : an instance of *elastic.Client that represent an Elastic Search client. // - index string : The Elastic Search index on wich to execute the query. In this context the default value // should be "awsdetailedlineitems" // This function excepts arguments passed to it to be sanitize. If they are not, the following cases will make // it crash : // - If the client is nil or malconfigured, it will crash // - If the index is not an index present in the ES, it will crash func getProductElasticSearchParams(account string, durationBegin time.Time, durationEnd time.Time, aggregationPeriod string, client *elastic.Client, index string) *elastic.SearchService { query := elastic.NewBoolQuery() query = query.Filter(createQueryAccountFilter(account)) query = query.Filter(createQueryTimeRange(durationBegin, durationEnd)) search := client.Search().Index(index).Size(0).Query(query) search.Aggregation("products", elastic.NewTermsAggregation().Field("productCode").Size(aggregationMaxSize). SubAggregation("dates", elastic.NewDateHistogramAggregation().Field("usageStartDate").ExtendedBounds(durationBegin, durationEnd).Interval(aggregationPeriod). SubAggregation("cost", elastic.NewSumAggregation().Field("unblendedCost")))) return search } // getDateRangeElasticSearchParams is used to construct an ElasticSearch *elastic.SearchService // used to retrieve the start and end date depending on the first and the last product in ElasticSearch. // It takes as parameters : // - account string : A string representing aws account number, in the format of the field // 'awsdetailedlineitem.linked_account_id' // - begin bool : Returns the begin date if true, else returns the end date // - client *elastic.Client : an instance of *elastic.Client that represent an Elastic Search client. // - index string : The Elastic Search index on wich to execute the query. In this context the default value // should be "awsdetailedlineitems" // This function excepts arguments passed to it to be sanitize. If they are not, the following cases will make // it crash : // - If the client is nil or malconfigured, it will crash // - If the index is not an index present in the ES, it will crash func getDateRangeElasticSearchParams(account string, begin bool, client *elastic.Client, index string) *elastic.SearchService { query := elastic.NewBoolQuery() query = query.Filter(createQueryAccountFilter(account)) search := client.Search().Index(index).Size(1).Sort("usageStartDate", begin).Query(query) return search } // getAnomalyElasticSearchParams is used to construct an ElasticSearch *elastic.SearchService // used to retrieve the anomalies. // It takes as parameters : // - account string : A string representing aws account number // - durationBeing time.Time : A time.Time struct representing the begining of the time range in the query // - durationEnd time.Time : A time.Time struct representing the end of the time range in the query // - client *elastic.Client : an instance of *elastic.Client that represent an Elastic Search client. // - index string : The Elastic Search index on which to execute the query. // This function excepts arguments passed to it to be sanitize. If they are not, the following cases will make // it crash : // - If the client is nil or malconfigured, it will crash // - If the index is not an index present in the ES, it will crash func getAnomalyElasticSearchParams(account string, durationBegin time.Time, durationEnd time.Time, client *elastic.Client, index string, anomalyType string) *elastic.SearchService { query := elastic.NewBoolQuery() query = query.Filter(elastic.NewTermQuery("account", account)) query = query.Filter(elastic.NewRangeQuery("date").From(durationBegin).To(durationEnd)) query = query.Filter(elastic.NewTermQuery("abnormal", true)) search := client.Search().Index(index).Type(anomalyType).Size(queryMaxSize).Sort("date", true).Query(query) return search } // addDocToBulkProcessor adds a document in a bulk processor to ingest them in ES func addDocToBulkProcessor(bp *elastic.BulkProcessor, doc interface{}, docType, index, id string) *elastic.BulkProcessor { rq := elastic.NewBulkIndexRequest() rq = rq.Index(index) rq = rq.Type(docType) rq = rq.Id(id) rq = rq.Doc(doc) bp.Add(rq) return bp }
anomaliesDetection/es_request_constructor.go
0.728265
0.491761
es_request_constructor.go
starcoder
package aoc2020 import ( "fmt" "reflect" ) type airport [][]int // 0 -> floor, 1 -> empty, 2 -> occupied func (a airport) occupied(row, col int) (occ, unocc, inbounds bool) { if row < 0 || row >= len(a) { return false, false, false } ar := a[row] if col < 0 || col >= len(ar) { return false, false, false } return ar[col] == 2, ar[col] == 1, true } func (a airport) neighbors(row, col int) (n int) { for _, rd := range [...]int{-1, 0, 1} { for _, cd := range [...]int{-1, 0, 1} { if rd == 0 && cd == 0 { continue } else if occ, _, _ := a.occupied(row+rd, col+cd); occ { n++ } } } return n } func (a airport) neighborsLong(row, col int) (n int) { for _, rd := range [...]int{-1, 0, 1} { for _, cd := range [...]int{-1, 0, 1} { if rd == 0 && cd == 0 { continue } for x := 1; ; x++ { occ, unocc, inbounds := a.occupied(row+rd*x, col+cd*x) if !inbounds || unocc { break } else if occ { n++ break } } } } return n } func (a airport) copy() airport { a2 := make(airport, len(a)) for i, r := range a { a2[i] = append([]int(nil), r...) } return a2 } func (a airport) countOcc() (occ int) { for _, ar := range a { for _, seat := range ar { if seat == 2 { occ++ } } } return occ } func (a airport) String() (out string) { for _, ar := range a { for _, seat := range ar { switch seat { case 0: out = out + string('.') case 1: out = out + string('L') case 2: out = out + string('#') } } out += "\n" } return out } func evolve(from airport) airport { to := make(airport, len(from)) for i, r := range from { to[i] = make([]int, len(r)) } for row := range to { for col := range to[row] { n := from.neighbors(row, col) if from[row][col] == 0 { to[row][col] = 0 } else if n == 0 { to[row][col] = 2 } else if n >= 4 { to[row][col] = 1 } else { to[row][col] = from[row][col] } } } return to } func ParseAirport(lines []string) (out airport) { for _, line := range lines { outrow := make([]int, len(line)) for i, c := range line { if c == 'L' { outrow[i] = 1 } else { outrow[i] = 0 } } out = append(out, outrow) } return out } func Problem11a(lines []string) { ap := ParseAirport(lines) cur := ap for { fmt.Println(cur) next := evolve(cur) if reflect.DeepEqual(cur, next) { fmt.Println(cur.countOcc()) return } cur = next } } func evolve2(from airport) airport { to := make(airport, len(from)) for i, r := range from { to[i] = make([]int, len(r)) } for row := range to { for col := range to[row] { n := from.neighborsLong(row, col) if from[row][col] == 0 { to[row][col] = 0 } else if from[row][col] == 1 && n == 0 { to[row][col] = 2 } else if from[row][col] == 2 && n >= 5 { to[row][col] = 1 } else { to[row][col] = from[row][col] } } } return to } func Problem11b(lines []string) { ap := ParseAirport(lines) cur := ap for { fmt.Println(cur) next := evolve2(cur) if reflect.DeepEqual(cur, next) { fmt.Println(cur.countOcc()) return } cur = next } }
11.go
0.527073
0.429728
11.go
starcoder
package rango import "math" func subdivide(src Triangle, dest *[4]Triangle, radius float64) { /* mid points of the edges of the triangle */ mid0 := FloatVecMult(radius, Normalize(Add(src.V0, src.V1))) mid1 := FloatVecMult(radius, Normalize(Add(src.V1, src.V2))) mid2 := FloatVecMult(radius, Normalize(Add(src.V2, src.V0))) /* input triangle subdivided into 4 based on the edges mid point */ SetTriangle(&dest[0], mid0, mid1, mid2) SetTriangle(&dest[1], src.V0, mid0, mid2) SetTriangle(&dest[2], mid0, src.V1, mid1) SetTriangle(&dest[3], mid2, mid1, src.V2) } func subdivideRecursively(recursionDepth int, in Triangle, out []Triangle, outIndex int, radius float64) { var triangles [4]Triangle /* span is the amount subdivide should jump so that final triangles are placed fine */ span := int(math.Pow(4.0, float64(recursionDepth-1))) if recursionDepth > 0 { /* in triangle subdivided, and those are further sent for subdivision */ subdivide(in, &triangles, radius) for i := 0; i < 4; i++ { subdivideRecursively(recursionDepth-1, triangles[i], out, outIndex+i*span, radius) } } else { /* recursion has ended, lets populate the incoming triangle to *out */ out[outIndex] = in } } func Sphere(object *Object, material Material, radius float64, resolution int) *Object { var octaHedron [8]Triangle var vertices [6]Vector triangleCount := 8 * math.Pow(4.0, float64(resolution)) out := make([]Triangle, int(triangleCount), int(triangleCount)) /* Sphere starts as an octahedron, minimum triangles is 8 and subdivides to 4 each time */ vertices[0] = V(0.0, 0.0, -radius) vertices[1] = V(0.0, -radius, 0.0) vertices[2] = V(-radius, 0.0, 0.0) vertices[3] = V(0.0, 0.0, radius) vertices[4] = V(0.0, radius, 0.0) vertices[5] = V(radius, 0.0, 0.0) /* Octahedron's top triangles */ SetTriangle(&octaHedron[0], vertices[5], vertices[4], vertices[3]) SetTriangle(&octaHedron[1], vertices[3], vertices[4], vertices[2]) SetTriangle(&octaHedron[2], vertices[2], vertices[4], vertices[0]) SetTriangle(&octaHedron[3], vertices[0], vertices[4], vertices[5]) /* Octahedron's bottom triangles */ SetTriangle(&octaHedron[4], vertices[3], vertices[1], vertices[5]) SetTriangle(&octaHedron[5], vertices[5], vertices[1], vertices[0]) SetTriangle(&octaHedron[6], vertices[0], vertices[1], vertices[2]) SetTriangle(&octaHedron[7], vertices[2], vertices[1], vertices[3]) /* Lets start subdividing these 8 triangles recursively */ for i := 0; i < 8; i++ { subdivideRecursively(resolution, octaHedron[i], out, i*int(triangleCount)/8, radius) } /* finally set the object */ SetObject(object, material, uint32(len(out)), out) return object }
rango/sphere.go
0.69035
0.539832
sphere.go
starcoder
package ast import "fmt" // Transformer defines the interface for transforming AST elements. If the // transformer returns nil and does not indicate an error, the AST element will // be set to nil and no transformations will be applied to children of the // element. type Transformer interface { Transform(v interface{}) (interface{}, error) } // Transform iterates the AST and calls the Transform function on the // Transformer t for x before recursing. func Transform(t Transformer, x interface{}) (interface{}, error) { if term, ok := x.(*Term); ok { return Transform(t, term.Value) } y, err := t.Transform(x) if err != nil { return x, err } if y == nil { return nil, nil } var ok bool switch y := y.(type) { case *Module: p, err := Transform(t, y.Package) if err != nil { return nil, err } if y.Package, ok = p.(*Package); !ok { return nil, fmt.Errorf("illegal transform: %T != %T", y.Package, p) } for i := range y.Imports { imp, err := Transform(t, y.Imports[i]) if err != nil { return nil, err } if y.Imports[i], ok = imp.(*Import); !ok { return nil, fmt.Errorf("illegal transform: %T != %T", y.Imports[i], imp) } } for i := range y.Rules { rule, err := Transform(t, y.Rules[i]) if err != nil { return nil, err } if y.Rules[i], ok = rule.(*Rule); !ok { return nil, fmt.Errorf("illegal transform: %T != %T", y.Rules[i], rule) } } for i := range y.Comments { comment, err := Transform(t, y.Comments[i]) if err != nil { return nil, err } if y.Comments[i], ok = comment.(*Comment); !ok { return nil, fmt.Errorf("illegal transform: %T != %T", y.Comments[i], comment) } } return y, nil case *Package: ref, err := Transform(t, y.Path) if err != nil { return nil, err } if y.Path, ok = ref.(Ref); !ok { return nil, fmt.Errorf("illegal transform: %T != %T", y.Path, ref) } return y, nil case *Import: y.Path, err = transformTerm(t, y.Path) if err != nil { return nil, err } if y.Alias, err = transformVar(t, y.Alias); err != nil { return nil, err } return y, nil case *Rule: if y.Head, err = transformHead(t, y.Head); err != nil { return nil, err } if y.Body, err = transformBody(t, y.Body); err != nil { return nil, err } if y.Else != nil { rule, err := Transform(t, y.Else) if err != nil { return nil, err } if y.Else, ok = rule.(*Rule); !ok { return nil, fmt.Errorf("illegal transform: %T != %T", y.Else, rule) } } return y, nil case *Head: if y.Name, err = transformVar(t, y.Name); err != nil { return nil, err } if y.Args, err = transformArgs(t, y.Args); err != nil { return nil, err } if y.Key != nil { if y.Key, err = transformTerm(t, y.Key); err != nil { return nil, err } } if y.Value != nil { if y.Value, err = transformTerm(t, y.Value); err != nil { return nil, err } } return y, nil case Args: for i := range y { if y[i], err = transformTerm(t, y[i]); err != nil { return nil, err } } return y, nil case Body: for i, e := range y { e, err := Transform(t, e) if err != nil { return nil, err } if y[i], ok = e.(*Expr); !ok { return nil, fmt.Errorf("illegal transform: %T != %T", y[i], e) } } return y, nil case *Expr: switch ts := y.Terms.(type) { case *SomeDecl: decl, err := Transform(t, ts) if err != nil { return nil, err } if y.Terms, ok = decl.(*SomeDecl); !ok { return nil, fmt.Errorf("illegal transform: %T != %T", y, decl) } return y, nil case []*Term: for i := range ts { if ts[i], err = transformTerm(t, ts[i]); err != nil { return nil, err } } case *Term: if y.Terms, err = transformTerm(t, ts); err != nil { return nil, err } } for i, w := range y.With { w, err := Transform(t, w) if err != nil { return nil, err } if y.With[i], ok = w.(*With); !ok { return nil, fmt.Errorf("illegal transform: %T != %T", y.With[i], w) } } return y, nil case *With: if y.Target, err = transformTerm(t, y.Target); err != nil { return nil, err } if y.Value, err = transformTerm(t, y.Value); err != nil { return nil, err } return y, nil case Ref: for i, term := range y { if y[i], err = transformTerm(t, term); err != nil { return nil, err } } return y, nil case *object: return y.Map(func(k, v *Term) (*Term, *Term, error) { k, err := transformTerm(t, k) if err != nil { return nil, nil, err } v, err = transformTerm(t, v) if err != nil { return nil, nil, err } return k, v, nil }) case *Array: for i := 0; i < y.Len(); i++ { v, err := transformTerm(t, y.Elem(i)) if err != nil { return nil, err } y.set(i, v) } return y, nil case Set: y, err = y.Map(func(term *Term) (*Term, error) { return transformTerm(t, term) }) if err != nil { return nil, err } return y, nil case *ArrayComprehension: if y.Term, err = transformTerm(t, y.Term); err != nil { return nil, err } if y.Body, err = transformBody(t, y.Body); err != nil { return nil, err } return y, nil case *ObjectComprehension: if y.Key, err = transformTerm(t, y.Key); err != nil { return nil, err } if y.Value, err = transformTerm(t, y.Value); err != nil { return nil, err } if y.Body, err = transformBody(t, y.Body); err != nil { return nil, err } return y, nil case *SetComprehension: if y.Term, err = transformTerm(t, y.Term); err != nil { return nil, err } if y.Body, err = transformBody(t, y.Body); err != nil { return nil, err } return y, nil case Call: for i := range y { if y[i], err = transformTerm(t, y[i]); err != nil { return nil, err } } return y, nil default: return y, nil } } // TransformRefs calls the function f on all references under x. func TransformRefs(x interface{}, f func(Ref) (Value, error)) (interface{}, error) { t := &GenericTransformer{func(x interface{}) (interface{}, error) { if r, ok := x.(Ref); ok { return f(r) } return x, nil }} return Transform(t, x) } // TransformVars calls the function f on all vars under x. func TransformVars(x interface{}, f func(Var) (Value, error)) (interface{}, error) { t := &GenericTransformer{func(x interface{}) (interface{}, error) { if v, ok := x.(Var); ok { return f(v) } return x, nil }} return Transform(t, x) } // TransformComprehensions calls the functio nf on all comprehensions under x. func TransformComprehensions(x interface{}, f func(interface{}) (Value, error)) (interface{}, error) { t := &GenericTransformer{func(x interface{}) (interface{}, error) { switch x := x.(type) { case *ArrayComprehension: return f(x) case *SetComprehension: return f(x) case *ObjectComprehension: return f(x) } return x, nil }} return Transform(t, x) } // GenericTransformer implements the Transformer interface to provide a utility // to transform AST nodes using a closure. type GenericTransformer struct { f func(x interface{}) (interface{}, error) } // NewGenericTransformer returns a new GenericTransformer that will transform // AST nodes using the function f. func NewGenericTransformer(f func(x interface{}) (interface{}, error)) *GenericTransformer { return &GenericTransformer{ f: f, } } // Transform calls the function f on the GenericTransformer. func (t *GenericTransformer) Transform(x interface{}) (interface{}, error) { return t.f(x) } func transformHead(t Transformer, head *Head) (*Head, error) { y, err := Transform(t, head) if err != nil { return nil, err } h, ok := y.(*Head) if !ok { return nil, fmt.Errorf("illegal transform: %T != %T", head, y) } return h, nil } func transformArgs(t Transformer, args Args) (Args, error) { y, err := Transform(t, args) if err != nil { return nil, err } a, ok := y.(Args) if !ok { return nil, fmt.Errorf("illegal transform: %T != %T", args, y) } return a, nil } func transformBody(t Transformer, body Body) (Body, error) { y, err := Transform(t, body) if err != nil { return nil, err } r, ok := y.(Body) if !ok { return nil, fmt.Errorf("illegal transform: %T != %T", body, y) } return r, nil } func transformTerm(t Transformer, term *Term) (*Term, error) { v, err := transformValue(t, term.Value) if err != nil { return nil, err } r := &Term{ Value: v, Location: term.Location, } return r, nil } func transformValue(t Transformer, v Value) (Value, error) { v1, err := Transform(t, v) if err != nil { return nil, err } r, ok := v1.(Value) if !ok { return nil, fmt.Errorf("illegal transform: %T != %T", v, v1) } return r, nil } func transformVar(t Transformer, v Var) (Var, error) { v1, err := Transform(t, v) if err != nil { return "", err } r, ok := v1.(Var) if !ok { return "", fmt.Errorf("illegal transform: %T != %T", v, v1) } return r, nil }
ast/transform.go
0.555073
0.461988
transform.go
starcoder
package service import ( "image" "image/color" "math" ) var bili = Bilinear{} // Bilinear Bilinear. type Bilinear struct{} // BilinearSrc BilinearSrc. type BilinearSrc struct { // Top-left and bottom-right interpolation sources low, high image.Point // Fraction of each pixel to take. The 0 suffix indicates // top/left, and the 1 suffix indicates bottom/right. frac00, frac01, frac10, frac11 float64 } // RGBA RGBA. func (Bilinear) RGBA(src *image.RGBA, x, y float64) color.RGBA { p := findLinearSrc(src.Bounds(), x, y) // Array offsets for the surrounding pixels. off00 := offRGBA(src, p.low.X, p.low.Y) off01 := offRGBA(src, p.high.X, p.low.Y) off10 := offRGBA(src, p.low.X, p.high.Y) off11 := offRGBA(src, p.high.X, p.high.Y) var fr, fg, fb, fa float64 fr += float64(src.Pix[off00+0]) * p.frac00 fg += float64(src.Pix[off00+1]) * p.frac00 fb += float64(src.Pix[off00+2]) * p.frac00 fa += float64(src.Pix[off00+3]) * p.frac00 fr += float64(src.Pix[off01+0]) * p.frac01 fg += float64(src.Pix[off01+1]) * p.frac01 fb += float64(src.Pix[off01+2]) * p.frac01 fa += float64(src.Pix[off01+3]) * p.frac01 fr += float64(src.Pix[off10+0]) * p.frac10 fg += float64(src.Pix[off10+1]) * p.frac10 fb += float64(src.Pix[off10+2]) * p.frac10 fa += float64(src.Pix[off10+3]) * p.frac10 fr += float64(src.Pix[off11+0]) * p.frac11 fg += float64(src.Pix[off11+1]) * p.frac11 fb += float64(src.Pix[off11+2]) * p.frac11 fa += float64(src.Pix[off11+3]) * p.frac11 var c color.RGBA c.R = uint8(fr + 0.5) c.G = uint8(fg + 0.5) c.B = uint8(fb + 0.5) c.A = uint8(fa + 0.5) return c } func findLinearSrc(b image.Rectangle, sx, sy float64) BilinearSrc { maxX := float64(b.Max.X) maxY := float64(b.Max.Y) minX := float64(b.Min.X) minY := float64(b.Min.Y) lowX := math.Floor(sx - 0.5) lowY := math.Floor(sy - 0.5) if lowX < minX { lowX = minX } if lowY < minY { lowY = minY } highX := math.Ceil(sx - 0.5) highY := math.Ceil(sy - 0.5) if highX >= maxX { highX = maxX - 1 } if highY >= maxY { highY = maxY - 1 } // In the variables below, the 0 suffix indicates top/left, and the // 1 suffix indicates bottom/right. // Center of each surrounding pixel. x00 := lowX + 0.5 y00 := lowY + 0.5 x01 := highX + 0.5 y01 := lowY + 0.5 x10 := lowX + 0.5 y10 := highY + 0.5 x11 := highX + 0.5 y11 := highY + 0.5 p := BilinearSrc{ low: image.Pt(int(lowX), int(lowY)), high: image.Pt(int(highX), int(highY)), } // Literally, edge cases. If we are close enough to the edge of // the image, curtail the interpolation sources. if lowX == highX && lowY == highY { p.frac00 = 1.0 } else if sy-minY <= 0.5 && sx-minX <= 0.5 { p.frac00 = 1.0 } else if maxY-sy <= 0.5 && maxX-sx <= 0.5 { p.frac11 = 1.0 } else if sy-minY <= 0.5 || lowY == highY { p.frac00 = x01 - sx p.frac01 = sx - x00 } else if sx-minX <= 0.5 || lowX == highX { p.frac00 = y10 - sy p.frac10 = sy - y00 } else if maxY-sy <= 0.5 { p.frac10 = x11 - sx p.frac11 = sx - x10 } else if maxX-sx <= 0.5 { p.frac01 = y11 - sy p.frac11 = sy - y01 } else { p.frac00 = (x01 - sx) * (y10 - sy) p.frac01 = (sx - x00) * (y11 - sy) p.frac10 = (x11 - sx) * (sy - y00) p.frac11 = (sx - x10) * (sy - y01) } return p }
app/interface/main/captcha/service/bilinear.go
0.610337
0.676905
bilinear.go
starcoder
package validation import ( "fmt" "reflect" ) var ( bytesType = reflect.TypeOf([]byte(nil)) ) // EnsureString ... func EnsureString(v reflect.Value) (string, error) { if v.Kind() == reflect.String { return v.String(), nil } if v.Type() == bytesType { return string(v.Interface().([]byte)), nil } return "", fmt.Errorf("cannot convert %v to string", v.Type()) } // StringOrBytes ... func StringOrBytes(v reflect.Value) (isString bool, str string, isBytes bool, bs []byte) { if v.Kind() == reflect.String { isString = true str = v.String() } else if v.Kind() == reflect.Slice && v.Type() == bytesType { isBytes = true bs = v.Interface().([]byte) } return } // IsEmpty returns whether a value is empty or not. func IsEmpty(rv reflect.Value) bool { switch rv.Kind() { case reflect.Invalid: return true case reflect.String, reflect.Array, reflect.Map, reflect.Slice: return rv.Len() == 0 case reflect.Bool: return !rv.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return rv.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return rv.Uint() == 0 case reflect.Float32, reflect.Float64: return rv.Float() == 0 case reflect.Ptr: return rv.IsNil() case reflect.Interface: if rv.IsNil() { return true } return IsEmpty(rv.Elem()) } return false } // LengthOfValue ... func LengthOfValue(rv reflect.Value) (int, error) { switch rv.Kind() { case reflect.String, reflect.Slice, reflect.Map, reflect.Array: return rv.Len(), nil } return 0, fmt.Errorf("cannot get length of %s", rv.Kind().String()) } // ToFloat ... func ToFloat(v reflect.Value) (float64, error) { switch v.Kind() { case reflect.Float32, reflect.Float64: return v.Float(), nil } return 0, fmt.Errorf("cannot convert %v to float64", v.Kind().String()) } // ToInt ... func ToInt(v reflect.Value) (int64, error) { switch v.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int(), nil } return 0, fmt.Errorf("cannot convert %v to int64", v.Kind().String()) } // ToUint ... func ToUint(v reflect.Value) (uint64, error) { switch v.Kind() { case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return v.Uint(), nil } return 0, fmt.Errorf("cannot convert %v to uint64", v.Kind().String()) }
util.go
0.728748
0.46952
util.go
starcoder
package carrierpricing import ( "errors" "log" "math" "sort" "strconv" ) const ( // VehicleTypeBicycle means that a bicycle is used to carry parcels around. VehicleTypeBicycle = "bicycle" // VehicleTypeMotorbike means that a motorbike is used to carry parcels around. VehicleTypeMotorbike = "motorbike" // VehicleTypeParcelCar means that a parcel car is used to carry parcels around. VehicleTypeParcelCar = "parcel_car" // VehicleTypeSmallVan means that a small van is used to carry parcels around. VehicleTypeSmallVan = "small_van" // VehicleTypeLargeVan means that a large van is used to carry parcels around. VehicleTypeLargeVan = "large_van" ) // ValidVehicleTypes is the list of all the available vehicles var ValidVehicleTypes = []string{ VehicleTypeBicycle, VehicleTypeMotorbike, VehicleTypeParcelCar, VehicleTypeSmallVan, VehicleTypeLargeVan, } // VehiclesMarkupTable indicates the markup to be applied to the base price for each vehicle type. var VehiclesMarkupTable = map[string]float64{ VehicleTypeBicycle: 1.1, VehicleTypeMotorbike: 1.15, VehicleTypeParcelCar: 1.2, VehicleTypeSmallVan: 1.3, VehicleTypeLargeVan: 1.4, } var ( errInvalidVehicle = errors.New("invalid vehicle provided") errMarkupNotPresent = errors.New("markup not present") errNoAvailableCarrierServicesForVehicle = errors.New("no available carrier services for the given vehicle") ) // GetBasicQuoteArgs contains arguments for the GetBasicQuote method. type GetBasicQuoteArgs struct { PickupPostcode string `json:"pickup_postcode"` DeliveryPostcode string `json:"delivery_postcode"` } // GetBasicQuoteResponse is the response object for the GetBasicQuote method. type GetBasicQuoteResponse struct { PickupPostcode string `json:"pickup_postcode"` DeliveryPostcode string `json:"delivery_postcode"` Price int64 `json:"price"` } // GetQuotesByVehicleArgs contains arguments for the GetQuotesByVehicle method. type GetQuotesByVehicleArgs struct { PickupPostcode string `json:"pickup_postcode"` DeliveryPostcode string `json:"delivery_postcode"` Vehicle string `json:"vehicle"` } // GetQuotesByVehicleResponse is the response object for the GetQuotesByVehicle method. type GetQuotesByVehicleResponse struct { PickupPostcode string `json:"pickup_postcode"` DeliveryPostcode string `json:"delivery_postcode"` Vehicle string `json:"vehicle"` Price int64 `json:"price"` } // GetQuotesByCarrierArgs contains arguments for the GetQuotesByCarrier method. type GetQuotesByCarrierArgs GetQuotesByVehicleArgs // GetQuotesByCarrierResponse is the response object for the GetQuotesByCarrier method. type GetQuotesByCarrierResponse struct { PickupPostcode string `json:"pickup_postcode"` DeliveryPostcode string `json:"delivery_postcode"` Vehicle string `json:"vehicle"` Price int64 `json:"price"` PriceList PriceByCarrierList `json:"price_list"` } // PriceByCarrier is the object returned in the GetQuotesByCarrierResponse // indicating the service price and delivery time for a specific carrier // matching the request. type PriceByCarrier struct { CarrierName string `json:"service"` Amount int64 `json:"price"` DeliveryTime int64 `json:"delivery_time"` } // PriceByCarrierList is a list of PriceByCarrier. // This struct has been created to apply sorting convenience methods. type PriceByCarrierList []PriceByCarrier func (pbcl PriceByCarrierList) Len() int { return len(pbcl) } func (pbcl PriceByCarrierList) Swap(i, j int) { pbcl[i], pbcl[j] = pbcl[j], pbcl[i] } func (pbcl PriceByCarrierList) Less(i, j int) bool { return pbcl[i].Amount < pbcl[j].Amount } // ServiceInterface defines the interface of the Service. // This is meant to be used from main/external packages, allowing to mock the service itself. type ServiceInterface interface { GetBasicQuote(args GetBasicQuoteArgs) (*GetBasicQuoteResponse, error) GetQuotesByVehicle(args GetQuotesByVehicleArgs) (*GetQuotesByVehicleResponse, error) GetQuotesByCarrier(args GetQuotesByCarrierArgs) (*GetQuotesByCarrierResponse, error) } // Service implements the ServiceInterface exposing the required methods. type Service struct { carrierServiceFinder CarrierServiceFinder logger *log.Logger } // NewService returns a new Service initialized with the given parameters. func NewService(logger *log.Logger, carrierServiceFinder CarrierServiceFinder) *Service { return &Service{ carrierServiceFinder: carrierServiceFinder, logger: logger, } } // GetBasicQuote calculates the basic price of the delivery between pickup and delivery // post codes, provided via the given args. func (s *Service) GetBasicQuote(args GetBasicQuoteArgs) (*GetBasicQuoteResponse, error) { s.logger.Printf("executing GetBasicQuote with args: %v\n", args) basePrice, err := s.calculateBasePrice(args.PickupPostcode, args.DeliveryPostcode) if err != nil { return nil, err } return &GetBasicQuoteResponse{ PickupPostcode: args.PickupPostcode, DeliveryPostcode: args.DeliveryPostcode, Price: *basePrice, }, nil } // GetQuotesByVehicle calculates the price of the delivery betweeen pickup and delivery // post codes according to a specific vehicle, multiplying the basic price for the // relative markup. func (s *Service) GetQuotesByVehicle(args GetQuotesByVehicleArgs) (*GetQuotesByVehicleResponse, error) { s.logger.Printf("executing GetQuotesByVehicle with args: %v\n", args) if !s.isVehicleValid(args.Vehicle) { return nil, errInvalidVehicle } basePrice, err := s.calculateBasePrice(args.PickupPostcode, args.DeliveryPostcode) if err != nil { return nil, err } priceByVehicle := s.applyVehicleMarkup(*basePrice, args.Vehicle) return &GetQuotesByVehicleResponse{ PickupPostcode: args.PickupPostcode, DeliveryPostcode: args.DeliveryPostcode, Vehicle: args.Vehicle, Price: priceByVehicle, }, nil } // GetQuotesByCarrier calculates the price of the delivery between pickup and delivery // post codes according to a specified vehicle and all the available carriers. A // markup is applied to the basic price for both the vehicle type and the carriers. func (s *Service) GetQuotesByCarrier(args GetQuotesByCarrierArgs) (*GetQuotesByCarrierResponse, error) { s.logger.Printf("executing GetQuotesByCarrier with args: %v\n", args) if !s.isVehicleValid(args.Vehicle) { return nil, errInvalidVehicle } basePrice, err := s.calculateBasePrice(args.PickupPostcode, args.DeliveryPostcode) if err != nil { return nil, err } priceByVehicle := s.applyVehicleMarkup(*basePrice, args.Vehicle) availableCarrierServices := s.carrierServiceFinder.FindCarrierServicesForVehicle(args.Vehicle) if len(availableCarrierServices) == 0 { return nil, errNoAvailableCarrierServicesForVehicle } priceList := s.getPriceListFromPriceAndCarrierServices(priceByVehicle, availableCarrierServices) return &GetQuotesByCarrierResponse{ PickupPostcode: args.PickupPostcode, DeliveryPostcode: args.DeliveryPostcode, Vehicle: args.Vehicle, PriceList: priceList, }, nil } func (s *Service) calculateBasePrice(pickupPostcode, deliveryPostcode string) (*int64, error) { pickup, err := strconv.ParseInt(pickupPostcode, 36, 64) if err != nil { return nil, err } delivery, err := strconv.ParseInt(deliveryPostcode, 36, 64) if err != nil { return nil, err } const someLargeNumber = 100000000 result := int64(math.Abs(float64(pickup)-float64(delivery))) / someLargeNumber return &result, nil } func (s *Service) isVehicleValid(vehicleLabelToVerify string) bool { for _, vehicleType := range ValidVehicleTypes { if vehicleType == vehicleLabelToVerify { return true } } return false } func (s *Service) applyVehicleMarkup(basePrice int64, vehicleType string) int64 { markup, exists := VehiclesMarkupTable[vehicleType] if !exists { return basePrice } return int64(math.RoundToEven(float64(basePrice) * markup)) } func (s *Service) getPriceListFromPriceAndCarrierServices(priceByVehicle int64, availableCarrierServices []CarrierService) PriceByCarrierList { priceList := PriceByCarrierList{} for _, carrierService := range availableCarrierServices { priceList = append(priceList, PriceByCarrier{ CarrierName: carrierService.Name, Amount: priceByVehicle + carrierService.Markup, DeliveryTime: carrierService.DeliveryTime, }) } sort.Sort(priceList) return priceList }
service.go
0.645567
0.425844
service.go
starcoder
package flags import ( "strconv" "time" flag "github.com/spf13/pflag" ) type intNullableArgument struct { variableToSet **int } type float64NullableArgument struct { variableToSet **float64 } func newIntNullableArgument(variable **int) *intNullableArgument { return &intNullableArgument{ variableToSet: variable, } } func newFloat64NullableArgument(variable **float64) *float64NullableArgument { return &float64NullableArgument{ variableToSet: variable, } } func (argument *intNullableArgument) Set(s string) error { v, err := strconv.Atoi(s) *argument.variableToSet = &v return err } func (argument *intNullableArgument) Type() string { return "int" } func (argument *intNullableArgument) String() string { if *argument.variableToSet == nil { return "" } return strconv.Itoa(**argument.variableToSet) } func (argument *float64NullableArgument) Set(s string) error { f, err := strconv.ParseFloat(s, 64) *argument.variableToSet = &f return err } func (argument *float64NullableArgument) Type() string { return "float64" } func (argument *float64NullableArgument) String() string { if *argument.variableToSet == nil { return "" } return strconv.FormatFloat(**argument.variableToSet, 'f', -1, 64) } func AddIntNullableFlagP(f *flag.FlagSet, variableToSet **int, name string, shorthand string, usage string) { f.VarPF(newIntNullableArgument(variableToSet), name, shorthand, usage) } func AddFloat64NullableFlagP(f *flag.FlagSet, variableToSet **float64, name string, shorthand string, usage string) { f.VarPF(newFloat64NullableArgument(variableToSet), name, shorthand, usage) } func AddIntNullableFlag(f *flag.FlagSet, variableToSet **int, name string, usage string) { AddIntNullableFlagP(f, variableToSet, name, "", usage) } type boolNullableArgument struct { variableToSet **bool } func newBoolNullableArgument(variable **bool) *boolNullableArgument { return &boolNullableArgument{ variableToSet: variable, } } func (argument *boolNullableArgument) Set(s string) error { v, err := strconv.ParseBool(s) *argument.variableToSet = &v return err } func (argument *boolNullableArgument) Type() string { return "bool" } func (argument *boolNullableArgument) String() string { if *argument.variableToSet == nil { return "" } return strconv.FormatBool(**argument.variableToSet) } func AddBoolNullableFlagP(f *flag.FlagSet, variableToSet **bool, name string, shorthand string, usage string) { flag := f.VarPF(newBoolNullableArgument(variableToSet), name, shorthand, usage) flag.NoOptDefVal = "true" } func AddBoolNullableFlag(f *flag.FlagSet, variableToSet **bool, name string, shortcut, usage string) { AddBoolNullableFlagP(f, variableToSet, name, shortcut, usage) } type durationNullableArgument struct { variableToSet **time.Duration } func newDurationNullableArgument(variable **time.Duration) *durationNullableArgument { return &durationNullableArgument{ variableToSet: variable, } } func (argument *durationNullableArgument) Set(s string) error { v, err := time.ParseDuration(s) *argument.variableToSet = &v return err } func (argument *durationNullableArgument) Type() string { return "duration" } func (argument *durationNullableArgument) String() string { if *argument.variableToSet == nil { return "" } return (**argument.variableToSet).String() } func AddDurationNullableFlagP(f *flag.FlagSet, variableToSet **time.Duration, name string, shorthand string, usage string) { f.VarP(newDurationNullableArgument(variableToSet), name, shorthand, usage) }
cmd/flags/flags.go
0.671686
0.40295
flags.go
starcoder
package gson import "strconv" func collate2gson(code []byte, config *Config) (interface{}, int) { if len(code) == 0 { return nil, 0 } var scratch [64]byte n := 1 switch code[0] { case TypeMissing: return MissingLiteral, 2 case TypeNull: return nil, 2 case TypeTrue: return true, 2 case TypeFalse: return false, 2 case TypeNumber: m := getDatum(code[n:]) ui, i, f, what := collated2Number(code[n:n+m-1], config.nk) switch what { case 1: return ui, n + m case 2: return i, n + m case 3: return f, n + m } case TypeString: s := make([]byte, encodedStringSize(code[n:])) s, x := collate2String(code[n:], s) return bytes2str(s), n + x case TypeBinary: m := getDatum(code[n:]) bs := make([]byte, m-1) copy(bs, code[n:n+m-1]) return bs, n + m case TypeArray: var arr []interface{} if config.arrayLenPrefix { if code[n] != TypeLength { panic("collate decode expected array length prefix") } n++ m := getDatum(code[n:]) _, y := collated2Int(code[n:n+m], scratch[:]) ln, err := strconv.Atoi(bytes2str(scratch[:y])) if err != nil { panic(err) } arr = make([]interface{}, 0, ln) n += m } else { arr = make([]interface{}, 0, 8) } for code[n] != Terminator { item, y := collate2gson(code[n:], config) arr = append(arr, item) n += y } return arr, n + 1 // +1 to skip terminator case TypeObj: obj := make(map[string]interface{}) if config.propertyLenPrefix { if code[n] != TypeLength { panic("collate decode expected object length prefix") } n++ m := getDatum(code[n:]) _, y := collated2Int(code[n:n+m], scratch[:]) _, err := strconv.Atoi(bytes2str(scratch[:y])) // just skip if err != nil { panic(err) } n += m } for code[n] != Terminator { key, m := collate2gson(code[n:], config) n += m value, m := collate2gson(code[n:], config) obj[key.(string)] = value n += m } return obj, n + 1 // +1 to skip terminator } panic("collate decode invalid binary") } // get the collated datum based on Terminator and return the length // of the datum. func getDatum(code []byte) int { var i int var b byte for i, b = range code { if b == Terminator { return i + 1 } } panic("collate decode terminator not found") }
collate_value.go
0.513912
0.4474
collate_value.go
starcoder
package lab import ( "hash/crc32" "math/rand" "time" ) // AudienceAim is something that determines the audience that should be shown the experiment. type AudienceAim interface { // shows says if the Visitor will be in the audience that will be shown the experiment. shows(Visitor, StrategyGetter) bool } // StrategyGetter will retrieve strategies based on their ID. type StrategyGetter interface { // Strategy returns the Strategy for the given ID. Strategy(string) (Strategy, bool) } type allVisitors struct { show bool } func (a *allVisitors) shows(_ Visitor, _ StrategyGetter) bool { return a.show } // AimNobody will show the experiment to nobody. func AimNobody() AudienceAim { return &allVisitors{false} } // AimEveryone will show the experiment to everyone. func AimEveryone() AudienceAim { return &allVisitors{true} } type randGenerator interface { Intn(int) int } var rnd = rand.New(rand.NewSource(time.Now().UnixNano())) // AimRandom will show the experiment randomly. func AimRandom() AudienceAim { return &random{rnd} } type random struct { rnd randGenerator } func (r *random) shows(_ Visitor, _ StrategyGetter) bool { return r.rnd.Intn(101)%2 == 0 } type percent struct { percent int } func (p *percent) shows(v Visitor, _ StrategyGetter) bool { return crc32.ChecksumIEEE([]byte(v.ID()))%100 < uint32(p.percent) } // AimPercent will randomly show the experiment to n % of the visitors. func AimPercent(n int) AudienceAim { return &percent{n} } type strategyAim struct { id string fn func(Visitor) Params } func (a *strategyAim) shows(v Visitor, s StrategyGetter) bool { if strategy, ok := s.Strategy(a.id); ok { var params = make(Params) if a.fn != nil { params = a.fn(v) } return strategy(v, params) } return false } // Params will hold all the parameters to call a strategy. type Params map[string]interface{} // AimStrategy will show the experiment to the visitor if the given strategy determines // it is ok to show it. A callback function can be given to return the Params to call the // strategy based on the visitor. func AimStrategy(id string, fn func(Visitor) Params) AudienceAim { return &strategyAim{id, fn} } type or struct { aims []AudienceAim } func (o *or) shows(v Visitor, s StrategyGetter) bool { for _, a := range o.aims { if a.shows(v, s) { return true } } return false } // Or shows the experiment if one or more of the aims will show the experiment. func Or(aims ...AudienceAim) AudienceAim { return &or{aims} } type and struct { aims []AudienceAim } func (o *and) shows(v Visitor, s StrategyGetter) bool { for _, a := range o.aims { if !a.shows(v, s) { return false } } return true } // And will show the experiment if all of the aims will show the experiment. func And(aims ...AudienceAim) AudienceAim { return &and{aims} }
aim.go
0.664431
0.562777
aim.go
starcoder
package gridly import ( "encoding/json" ) // CreateGrid struct for CreateGrid type CreateGrid struct { Metadata *map[string]string `json:"metadata,omitempty"` Name *string `json:"name,omitempty"` TemplateGridId *string `json:"templateGridId,omitempty"` } // NewCreateGrid instantiates a new CreateGrid 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 NewCreateGrid() *CreateGrid { this := CreateGrid{} return &this } // NewCreateGridWithDefaults instantiates a new CreateGrid 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 NewCreateGridWithDefaults() *CreateGrid { this := CreateGrid{} return &this } // GetMetadata returns the Metadata field value if set, zero value otherwise. func (o *CreateGrid) GetMetadata() map[string]string { if o == nil || o.Metadata == nil { var ret map[string]string return ret } return *o.Metadata } // GetMetadataOk returns a tuple with the Metadata field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CreateGrid) GetMetadataOk() (*map[string]string, bool) { if o == nil || o.Metadata == nil { return nil, false } return o.Metadata, true } // HasMetadata returns a boolean if a field has been set. func (o *CreateGrid) HasMetadata() bool { if o != nil && o.Metadata != nil { return true } return false } // SetMetadata gets a reference to the given map[string]string and assigns it to the Metadata field. func (o *CreateGrid) SetMetadata(v map[string]string) { o.Metadata = &v } // GetName returns the Name field value if set, zero value otherwise. func (o *CreateGrid) GetName() string { if o == nil || o.Name == nil { var ret string return ret } return *o.Name } // GetNameOk returns a tuple with the Name field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CreateGrid) GetNameOk() (*string, bool) { if o == nil || o.Name == nil { return nil, false } return o.Name, true } // HasName returns a boolean if a field has been set. func (o *CreateGrid) HasName() bool { if o != nil && o.Name != nil { return true } return false } // SetName gets a reference to the given string and assigns it to the Name field. func (o *CreateGrid) SetName(v string) { o.Name = &v } // GetTemplateGridId returns the TemplateGridId field value if set, zero value otherwise. func (o *CreateGrid) GetTemplateGridId() string { if o == nil || o.TemplateGridId == nil { var ret string return ret } return *o.TemplateGridId } // GetTemplateGridIdOk returns a tuple with the TemplateGridId field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *CreateGrid) GetTemplateGridIdOk() (*string, bool) { if o == nil || o.TemplateGridId == nil { return nil, false } return o.TemplateGridId, true } // HasTemplateGridId returns a boolean if a field has been set. func (o *CreateGrid) HasTemplateGridId() bool { if o != nil && o.TemplateGridId != nil { return true } return false } // SetTemplateGridId gets a reference to the given string and assigns it to the TemplateGridId field. func (o *CreateGrid) SetTemplateGridId(v string) { o.TemplateGridId = &v } func (o CreateGrid) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Metadata != nil { toSerialize["metadata"] = o.Metadata } if o.Name != nil { toSerialize["name"] = o.Name } if o.TemplateGridId != nil { toSerialize["templateGridId"] = o.TemplateGridId } return json.Marshal(toSerialize) } type NullableCreateGrid struct { value *CreateGrid isSet bool } func (v NullableCreateGrid) Get() *CreateGrid { return v.value } func (v *NullableCreateGrid) Set(val *CreateGrid) { v.value = val v.isSet = true } func (v NullableCreateGrid) IsSet() bool { return v.isSet } func (v *NullableCreateGrid) Unset() { v.value = nil v.isSet = false } func NewNullableCreateGrid(val *CreateGrid) *NullableCreateGrid { return &NullableCreateGrid{value: val, isSet: true} } func (v NullableCreateGrid) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableCreateGrid) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
model_create_grid.go
0.774157
0.41484
model_create_grid.go
starcoder
package geom // A LineString represents a single, unbroken line, linearly interpreted // between zero or more control points. type LineString struct { geom1 } // NewLineString returns a new LineString with layout l and no control points. func NewLineString(l Layout) *LineString { return NewLineStringFlat(l, nil) } // NewLineStringFlat returns a new LineString with layout l and control points // flatCoords. func NewLineStringFlat(layout Layout, flatCoords []float64) *LineString { g := new(LineString) g.layout = layout g.stride = layout.Stride() g.flatCoords = flatCoords return g } // Area returns the area of g, i.e. zero. func (g *LineString) Area() float64 { return 0 } // Clone returns a copy of g that does not alias g. func (g *LineString) Clone() *LineString { return deriveCloneLineString(g) } // Empty returns true if the geometry has no coordinate. func (g *LineString) Empty() bool { return len(g.FlatCoords()) == 0 } // Interpolate returns the index and delta of val in dimension dim. func (g *LineString) Interpolate(val float64, dim int) (int, float64) { n := len(g.flatCoords) if n == 0 { panic("geom: empty linestring") } if val <= g.flatCoords[dim] { return 0, 0 } if g.flatCoords[n-g.stride+dim] <= val { return (n - 1) / g.stride, 0 } low := 0 high := n / g.stride for low < high { mid := (low + high) / 2 if val < g.flatCoords[mid*g.stride+dim] { high = mid } else { low = mid + 1 } } low-- val0 := g.flatCoords[low*g.stride+dim] if val == val0 { return low, 0 } val1 := g.flatCoords[(low+1)*g.stride+dim] return low, (val - val0) / (val1 - val0) } // Length returns the length of g. func (g *LineString) Length() float64 { return length1(g.flatCoords, 0, len(g.flatCoords), g.stride) } // MustSetCoords is like SetCoords but it panics on any error. func (g *LineString) MustSetCoords(coords []Coord) *LineString { Must(g.SetCoords(coords)) return g } // SetCoords sets the coordinates of g. func (g *LineString) SetCoords(coords []Coord) (*LineString, error) { if err := g.setCoords(coords); err != nil { return nil, err } return g, nil } // SetSRID sets the SRID of g. func (g *LineString) SetSRID(srid int) *LineString { g.srid = srid return g } // SubLineString returns a LineString from starts at index start and stops at // index stop of g. The returned LineString aliases g. func (g *LineString) SubLineString(start, stop int) *LineString { return NewLineStringFlat(g.layout, g.flatCoords[start*g.stride:stop*g.stride]) } // Swap swaps the values of g and g2. func (g *LineString) Swap(g2 *LineString) { *g, *g2 = *g2, *g }
linestring.go
0.915399
0.465813
linestring.go
starcoder
package operations import ( "strconv" "strings" . "github.com/mitjaziv/qmanager/internal/structures" ) type ( ArithmeticSolver struct { } ) var ( // Precedence map precedence = map[string]int{ "(": 0, ")": 0, "+": 1, "-": 1, "*": 2, "/": 2, } ) // process function takes input and process operations and values. func process(input string) (out float64, err error) { stackO := make([]string, 0) stackV := make([]float64, 0) // Create tokens from input string. tokens := strings.Fields(input) // Temp values var op string var v1, v2 float64 // Loop over tokens and evaluate arithmetic. for i := 0; i < len(tokens); i++ { t := tokens[i] // If token is value, parse it and push on stack. if _, ok := precedence[t]; !ok { v, err := strconv.ParseFloat(t, 64) if err != nil { return 0, err } // Push value on stack. stackV = append([]float64{v}, stackV...) // Proceed to next token. continue } for { if len(stackO) == 0 || t == "(" || (precedence[t] > precedence[stackO[len(stackO)-1]]) { // Push operation on stack. stackO = append([]string{t}, stackO...) break } // Pop operation from stack. op, stackO = stackO[0], stackO[1:] // Brake on left parenthesis. if op == "(" { break } // Pop val from stack. v2, stackV = stackV[0], stackV[1:] // Pop val from stack. v1, stackV = stackV[0], stackV[1:] // Calculate actual operation val, err := calc(op, v1, v2) if err != nil { return 0, err } // Push value on stack. stackV = append([]float64{val}, stackV...) } } // Finish evaluating data on stacks. for { if len(stackO) == 0 { break } // Pop operation from stack. op, stackO = stackO[0], stackO[1:] // Pop val from stack. v2, stackV = stackV[0], stackV[1:] // Pop val from stack. v1, stackV = stackV[0], stackV[1:] // Calculate actual operation. val, err := calc(op, v1, v2) if err != nil { return 0, err } // Push value on stack. stackV = append([]float64{val}, stackV...) } // Get result from stack and returns it. return stackV[0], nil } // calc function performs operation on given operands. func calc(op string, v1, v2 float64) (float64, error) { switch op { case "+": v1 = v1 + v2 case "-": v1 = v1 - v2 case "*": v1 = v1 * v2 case "/": v1 = v1 / v2 default: return 0, ErrUnSupportedOp } return v1, nil } // format input string. func format(input string) string { i := 0 for { if i >= len(input)-1 { break } // Get char on position c := string(input[i]) c1 := string(input[i+1]) // Add whitespace to operand if needed if _, ok := precedence[c]; ok && c1 != " " { input = input[:i+1] + " " + input[i+1:] } // Add whitespace to number if needed if _, ok := precedence[c1]; ok && c != " " { input = input[:i+1] + " " + input[i+1:] } i++ } return input } // Call performs operation. func (as *ArithmeticSolver) Call(t *Task) error { if t == nil { return ErrMissingArgs } i := t.Input.(string) // Format input, add needed whitespaces. i = format(i) // Calculate out, err := process(i) if err != nil { return err } // Write result to output. t.Output = out return nil }
worker/operations/arithmetic.go
0.583915
0.446857
arithmetic.go
starcoder
//go:generate go run gen-benchmarks.go // Package vectorIntNodes defines the vector of integers function collection available for the GEP algorithm. package vectorIntNodes import ( "log" "github.com/gmlewis/gep/v2/functions" ) type VectorInt = functions.VectorInt // VectorIntNode is a vector of integers function used for the formation of GEP expressions. type VectorIntNode struct { index int symbol string terminals int function func(x []VectorInt) VectorInt } // Symbol returns the Karva symbol for this vector of integers function. func (n VectorIntNode) Symbol() string { return n.symbol } // Terminals returns the number of input terminals for this vector of integers function. func (n VectorIntNode) Terminals() int { return n.terminals } // BoolFunction is unused in this package and returns an error. func (n VectorIntNode) BoolFunction([]bool) bool { log.Println("error calling BoolFunction on VectorIntNode model.") return false } // IntFunction calls the vector of integers function and returns the result. func (n VectorIntNode) IntFunction([]int) int { return 0 } // Float64Function is unused in this package and returns an error. func (n VectorIntNode) Float64Function([]float64) float64 { log.Println("error calling Float64Function on VectorIntNode model.") return 0.0 } // VectorIntFunction allows FuncMap to implement interace functions.FuncMap. func (n VectorIntNode) VectorIntFunction(x []VectorInt) VectorInt { return n.function(x) } // sliceOp is a function used on each index of a VectorInt. type sliceOp func(in []int) int // ProcessVector is a helper function that processes each index of an array of VectorInts. func ProcessVector(x []VectorInt, op sliceOp) (result VectorInt) { if len(x) == 0 { return result } result = make([]int, len(x[0])) for i := 0; i < len(x[0]); i++ { args := make([]int, len(x)) for j := 0; j < len(x); j++ { args[j] = x[j][i] } result[i] = op(args) } return result } // Int lists all the available vector of integers functions for this package. var VectorIntFuncs = functions.FuncMap{ // TODO(gmlewis): Change functions to operate on variable-length slices. "+": VectorIntNode{0, "+", 2, func(x []VectorInt) VectorInt { op := func(in []int) (result int) { for i := 0; i < 2; /* len(in) */ i++ { result += in[i] } return result } return ProcessVector(x, op) }}, "-": VectorIntNode{1, "-", 2, func(x []VectorInt) VectorInt { op := func(in []int) (result int) { result = in[0] for i := 1; i < 2; /* len(in) */ i++ { result -= in[i] } return result } return ProcessVector(x, op) }}, "*": VectorIntNode{2, "*", 2, func(x []VectorInt) VectorInt { op := func(in []int) (result int) { result = in[0] for i := 1; i < 2; /* len(in) */ i++ { result *= in[i] } return result } return ProcessVector(x, op) }}, "/": VectorIntNode{3, "/", 2, func(x []VectorInt) VectorInt { op := func(in []int) (result int) { result = in[0] for i := 1; i < 2; /* len(in) */ i++ { if in[0] == 0 { result = 0 } else { result /= in[i] } } return result } return ProcessVector(x, op) }}, }
functions/vector_int_nodes/vector_int.go
0.598899
0.791982
vector_int.go
starcoder
package models import ( "errors" ) // Provides operations to manage the collection of bookingBusiness entities. type BookingPriceType int const ( // The price of the service is not defined. UNDEFINED_BOOKINGPRICETYPE BookingPriceType = iota // The price of the service is fixed. FIXEDPRICE_BOOKINGPRICETYPE // The price of the service starts with a particular value, but can be higher based on the final services performed. STARTINGAT_BOOKINGPRICETYPE // The price of the service depends on the number of hours a staff member works on the service. HOURLY_BOOKINGPRICETYPE // The service is free. FREE_BOOKINGPRICETYPE // The price of the service varies. PRICEVARIES_BOOKINGPRICETYPE // The price of the service is not listed. CALLUS_BOOKINGPRICETYPE // The price of the service is not set. NOTSET_BOOKINGPRICETYPE ) func (i BookingPriceType) String() string { return []string{"undefined", "fixedPrice", "startingAt", "hourly", "free", "priceVaries", "callUs", "notSet"}[i] } func ParseBookingPriceType(v string) (interface{}, error) { result := UNDEFINED_BOOKINGPRICETYPE switch v { case "undefined": result = UNDEFINED_BOOKINGPRICETYPE case "fixedPrice": result = FIXEDPRICE_BOOKINGPRICETYPE case "startingAt": result = STARTINGAT_BOOKINGPRICETYPE case "hourly": result = HOURLY_BOOKINGPRICETYPE case "free": result = FREE_BOOKINGPRICETYPE case "priceVaries": result = PRICEVARIES_BOOKINGPRICETYPE case "callUs": result = CALLUS_BOOKINGPRICETYPE case "notSet": result = NOTSET_BOOKINGPRICETYPE default: return 0, errors.New("Unknown BookingPriceType value: " + v) } return &result, nil } func SerializeBookingPriceType(values []BookingPriceType) []string { result := make([]string, len(values)) for i, v := range values { result[i] = v.String() } return result }
models/booking_price_type.go
0.554229
0.46873
booking_price_type.go
starcoder
package go2linq // Reimplementing LINQ to Objects: Part 13 - Aggregate // https://codeblog.jonskeet.uk/2010/12/30/reimplementing-linq-to-objects-part-13-aggregate/ // https://docs.microsoft.com/dotnet/api/system.linq.enumerable.aggregate // Aggregate applies an accumulator function over a sequence. func Aggregate[Source any](source Enumerator[Source], accumulator func(Source, Source) Source) (Source, error) { if source == nil { return ZeroValue[Source](), ErrNilSource } if accumulator == nil { return ZeroValue[Source](), ErrNilAccumulator } if !source.MoveNext() { return ZeroValue[Source](), ErrEmptySource } r := source.Current() for source.MoveNext() { r = accumulator(r, source.Current()) } return r, nil } // AggregateMust is like Aggregate but panics in case of error. func AggregateMust[Source any](source Enumerator[Source], accumulator func(Source, Source) Source) Source { r, err := Aggregate(source, accumulator) if err != nil { panic(err) } return r } // AggregateSeed applies an accumulator function over a sequence. // The specified seed value is used as the initial accumulator value. func AggregateSeed[Source, Accumulate any](source Enumerator[Source], seed Accumulate, accumulator func(Accumulate, Source) Accumulate) (Accumulate, error) { if source == nil { return ZeroValue[Accumulate](), ErrNilSource } if accumulator == nil { return ZeroValue[Accumulate](), ErrNilAccumulator } r := seed for source.MoveNext() { r = accumulator(r, source.Current()) } return r, nil } // AggregateSeedMust is like AggregateSeed but panics in case of error. func AggregateSeedMust[Source, Accumulate any](source Enumerator[Source], seed Accumulate, accumulator func(Accumulate, Source) Accumulate) Accumulate { r, err := AggregateSeed(source, seed, accumulator) if err != nil { panic(err) } return r } // AggregateSeedSel applies an accumulator function over a sequence. // The specified seed value is used as the initial accumulator value, // and the specified function is used to select the result value. func AggregateSeedSel[Source, Accumulate, Result any](source Enumerator[Source], seed Accumulate, accumulator func(Accumulate, Source) Accumulate, resultSelector func(Accumulate) Result) (Result, error) { if source == nil { return ZeroValue[Result](), ErrNilSource } if accumulator == nil { return ZeroValue[Result](), ErrNilAccumulator } if resultSelector == nil { return ZeroValue[Result](), ErrNilSelector } r := seed for source.MoveNext() { r = accumulator(r, source.Current()) } return resultSelector(r), nil } // AggregateSeedSelMust is like AggregateSeedSel but panics in case of error. func AggregateSeedSelMust[Source, Accumulate, Result any](source Enumerator[Source], seed Accumulate, accumulator func(Accumulate, Source) Accumulate, resultSelector func(Accumulate) Result) Result { r, err := AggregateSeedSel(source, seed, accumulator, resultSelector) if err != nil { panic(err) } return r }
aggregate.go
0.780495
0.443239
aggregate.go
starcoder
package disttwoatoms import ( "bufio" "errors" "fmt" "io" "math" "os" "github.com/ortiye/molsolvent/pkg/util" "github.com/pelletier/go-toml" ) // Type is name of the calculation. var Type = "dist_two_atoms" // DistTwoAtoms is a structure containing the parameters that can be parsed from // a TOML configuration file. This structure can be instanced through the New // method. It also contains other unexported informations like the number of // atoms, and the number of columns. // Atom1 must be lower than Atom2. Same for CfgStart and CfgEnd. type DistTwoAtoms struct { FileIn string `toml:"dist_two_atoms.file_in"` FileOut string `toml:"dist_two_atoms.file_out"` CfgStart int `toml:"dist_two_atoms.cfg_start"` CfgEnd int `toml:"dist_two_atoms.cfg_end"` Atom1 int `toml:"dist_two_atoms.atom_1"` Atom2 int `toml:"dist_two_atoms.atom_2"` Dt float64 `toml:"dist_two_atoms.dt"` atoms int cols [3]int colsLen int dist [][3]float64 } // New returns an instance of the DistTwoAtoms structure. It reads and parses // the configuration file given in argument. The file must be a TOML file. func New(path string) (*DistTwoAtoms, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() var distTwoAtoms DistTwoAtoms dec := toml.NewDecoder(f) err = dec.Decode(&distTwoAtoms) if err != nil { return nil, err } if distTwoAtoms.CfgStart >= distTwoAtoms.CfgEnd { return nil, errors.New("CfgStart is greater or equal than CfgEnd") } if distTwoAtoms.Atom1 >= distTwoAtoms.Atom2 { return nil, errors.New("Atom1 is greater or equal than Atom2") } return &distTwoAtoms, nil } // Start performs the calculation. It is a thread blocking method. It is a very // fast calculation. This calculation only use one thread. func (d *DistTwoAtoms) Start() error { f, err := os.Open(d.FileIn) if err != nil { return err } defer f.Close() r := bufio.NewReader(f) out, err := util.Write(d.FileOut, d) if err != nil { return fmt.Errorf("Write: %w", err) } defer out.Close() out.WriteString("cfg t x y z dist\n") err = util.ReadCfgNonCvg(r, d.CfgStart) if err != nil { return fmt.Errorf("ReadCfgNonCvg: %w", err) } xyz1, xyz2, err := d.readCfgFirst(r) if err != nil { return fmt.Errorf("readCfgFirst: %w", err) } d.result(out, 0, xyz1, xyz2) for i := 1; i <= (d.CfgEnd - d.CfgStart - 1); i++ { xyz1, xyz2, err := d.readCfg(r) if err != nil { return fmt.Errorf("readCfg (step %d): %w", i, err) } d.result(out, i, xyz1, xyz2) } return nil } // append calculates the distance between two set of coordinates and writes it // into a file. func (d *DistTwoAtoms) result(w io.Writer, cfg int, xyz1, xyz2 [3]float64) { var ( vec [3]float64 dist float64 ) for k := 0; k < 3; k++ { vec[k] = (xyz1[k] - xyz2[k]) dist += util.Pow(vec[k], 2) } dist = math.Sqrt(dist) fmt.Fprintf(w, "%d %g %g %g %g %g\n", (cfg + d.CfgStart), (float64(cfg+d.CfgStart) * d.Dt), vec[0], vec[1], vec[2], dist) }
pkg/disttwoatoms/disttwoatoms.go
0.647241
0.442637
disttwoatoms.go
starcoder
package datasource import ( "github.com/arturom/datadiff/histogram" "gopkg.in/olivere/elastic.v1" ) const facetLabel = "ids" // ES0DataSource uses an Elasticsearch 0.90 backend to implement the datasource interface type ES0DataSource struct { Client elastic.Client IndexName string TypeName string FieldName string } // FetchHistogramAll fetches a histogram of all IDs in an index func (s ES0DataSource) FetchHistogramAll(interval int) (histogram.Histogram, error) { query := s.histogramQuery(interval) return s.processQuery(query, interval) } // FetchHistogramRange fetches a histogram of a selective range of IDs in an index func (s ES0DataSource) FetchHistogramRange(gte, lt, interval int) (histogram.Histogram, error) { query := s.histogramQuery(interval).Query(s.rangeFilterQuery(gte, lt)) return s.processQuery(query, interval) } // FetchIDRange fetches all the existing IDs in a given range func (s ES0DataSource) FetchIDRange(gte, lt int) ([]int, error) { r, err := s.Client. Search(s.IndexName). Query(s.rangeFilterQuery(gte, lt)). Type(s.TypeName). Fields(s.FieldName). Size(lt - gte). Do() if err != nil { return nil, err } hits := &r.Hits.Hits ids := make([]int, len(*hits)) for i, h := range *hits { ids[i] = int(h.Fields[s.FieldName].(float64)) } return ids, nil } func (s ES0DataSource) facet(interval int) elastic.Facet { return elastic. NewHistogramFacet(). Field(s.FieldName). Interval(int64(interval)) } func (s ES0DataSource) rangeFilterQuery(gte, lt int) elastic.Query { return elastic. NewFilteredQuery(elastic.NewMatchAllQuery()). Filter(elastic.NewRangeFilter(s.FieldName)) } func (s ES0DataSource) histogramQuery(interval int) *elastic.SearchService { return s.Client. Search(s.IndexName). Type(s.TypeName). Size(0). Facet(facetLabel, s.facet(interval)) } func (s ES0DataSource) processQuery(query *elastic.SearchService, interval int) (histogram.Histogram, error) { r, err := query.Do() if err != nil { return histogram.Histogram{}, err } entries := &r.Facets[facetLabel].Entries b := make(histogram.Bins, len(*entries)) for i, e := range *entries { b[i] = histogram.Bin{ Key: int(e.Key.(float64)), Count: e.Count, } } return histogram.Histogram{ BinCapacity: interval, Bins: b, }, nil }
datasource/elasticsearch0.go
0.691602
0.461199
elasticsearch0.go
starcoder
package bind import ( "encoding/json" "fmt" "github.com/jefflinse/melatonin/expect" ) // Bool creates a predicate requiring a value to be a bool, // binding the value to a target variable. func Bool(target *bool) expect.Predicate { if target == nil { return expect.Bool() } return expect.Bool().Then(func(actual interface{}) error { *target = actual.(bool) return nil }) } // Int creates a predicate requiring a value to be an integer, // binding the value to a target variable. func Int(target *int64) expect.Predicate { if target == nil { return expect.Int() } return expect.Int().Then(func(actual interface{}) error { if v, ok := actual.(int64); ok { *target = v } else if v, ok := actual.(float64); ok { *target = int64(v) } else { return fmt.Errorf("expected to bind int64, found %T", actual) } return nil }) } // Float creates a predicate requiring a value to be a floating point number, // binding the value to a target variable. func Float(target *float64) expect.Predicate { if target == nil { return expect.Float() } return expect.Float().Then(func(actual interface{}) error { *target = actual.(float64) return nil }) } // Map creates a predicate requiring a value to be a map, // binding the value to a target variable. func Map(target *map[string]interface{}) expect.Predicate { if target == nil { return expect.Map() } return expect.Map().Then(func(actual interface{}) error { *target = actual.(map[string]interface{}) return nil }) } // Slice creates a predicate requiring a value to be a slice, // binding the value to a target variable. func Slice(target *[]interface{}) expect.Predicate { if target == nil { return expect.Slice() } return expect.Slice().Then(func(actual interface{}) error { *target = actual.([]interface{}) return nil }) } // String creates a predicate requiring a value to be a string, // binding the value to a target variable. func String(target *string) expect.Predicate { if target == nil { return expect.String() } return expect.String().Then(func(actual interface{}) error { *target = actual.(string) return nil }) } // Struct creates a predicate requiring a value to be a struct, // binding the value to a target variable by unmarshaling the // JSON representation of the value into the target variable. func Struct(target interface{}) expect.Predicate { return func(actual interface{}) error { b, err := json.Marshal(actual) if err != nil { return fmt.Errorf("failed to bind %T to %T: %w", actual, target, err) } if err := json.Unmarshal(b, target); err != nil { return fmt.Errorf("failed to bind %T to %T: %w", actual, target, err) } return nil } }
bind/bind.go
0.801392
0.577257
bind.go
starcoder
package actions import ( "fmt" "github.com/inkyblackness/res/data/interpreters" ) func forType(typeID int) func(*interpreters.Instance) bool { return func(inst *interpreters.Instance) bool { return inst.Get("Type") == uint32(typeID) } } var transportHackerDetails = interpreters.New(). With("TargetX", 0, 4).As(interpreters.RangedValue(1, 63)). With("TargetY", 4, 4).As(interpreters.RangedValue(1, 63)). With("TargetZ", 8, 1).As(interpreters.RangedValue(0, 255)). With("PreserveHeight", 9, 1).As(interpreters.EnumValue(map[uint32]string{0: "No", 0x40: "Yes"})). With("CrossLevelTransportDestination", 12, 1).As(interpreters.RangedValue(0, 15)). With("CrossLevelTransportFlag", 13, 1).As(interpreters.EnumValue(map[uint32]string{ 0x00: "Cross-Level", 0x10: "Same-Level (0x10)", 0x20: "Same-Level (0x20)", 0x22: "Same-Level (0x22)"})) var changeHealthDetails = interpreters.New(). With("HealthDelta", 4, 1). With("HealthChangeFlag", 6, 2).As(interpreters.EnumValue(map[uint32]string{0: "Remove Delta", 1: "Add Delta"})). With("PowerDelta", 8, 1). With("PowerChangeFlag", 10, 2).As(interpreters.EnumValue(map[uint32]string{0: "Remove Delta", 1: "Add Delta"})) var cloneMoveObjectDetails = interpreters.New(). With("ObjectIndex", 0, 2).As(interpreters.ObjectIndex()). With("MoveFlag", 2, 2).As(interpreters.EnumValue(map[uint32]string{ 0x0000: "Clone Object", 0x0001: "Move Object (0x0001)", 0x0002: "Move Object (0x0002)", 0x0FFF: "Move Object (0x0FFF)", 0xAAAA: "Move Object (0xAAAA)", 0xFFFF: "Move Object (0xFFFF)"})). With("TargetX", 4, 4).As(interpreters.RangedValue(1, 63)). With("TargetY", 8, 4).As(interpreters.RangedValue(1, 63)). With("TargetHeight", 12, 1).As(interpreters.SpecialValue("ObjectHeight")). With("KeepSourceHeight", 13, 1).As(interpreters.EnumValue(map[uint32]string{0x00: "Set height", 0x40: "Keep height"})) var setGameVariableDetails = interpreters.New(). With("VariableKey", 0, 4).As(interpreters.SpecialValue("VariableKey")). With("Value", 4, 2). With("Operation", 6, 2).As(interpreters.EnumValue(map[uint32]string{0: "Set", 1: "Add", 2: "Subtract", 3: "Multiply", 4: "Divide", 5: "Modulo"})). With("Message1", 8, 4).As(interpreters.RangedValue(0, 511)). With("Message2", 12, 4).As(interpreters.RangedValue(0, 511)) var showCutsceneDetails = interpreters.New(). With("CutsceneIndex", 0, 4).As(interpreters.EnumValue(map[uint32]string{0: "Death", 1: "Intro", 2: "Ending"})). With("EndGameFlag", 4, 4).As(interpreters.EnumValue(map[uint32]string{0: "No (not working)", 1: "Yes"})) func pointOneSecond(value int64) string { return fmt.Sprintf("%.1f sec", float64(value)*0.1) } var triggerOtherObjectsDetails = interpreters.New(). With("Object1Index", 0, 2).As(interpreters.ObjectIndex()). With("Object1Delay", 2, 2).As(interpreters.FormattedRangedValue(0, 6000, pointOneSecond)). With("Object2Index", 4, 2).As(interpreters.ObjectIndex()). With("Object2Delay", 6, 2).As(interpreters.FormattedRangedValue(0, 6000, pointOneSecond)). With("Object3Index", 8, 2).As(interpreters.ObjectIndex()). With("Object3Delay", 10, 2).As(interpreters.FormattedRangedValue(0, 6000, pointOneSecond)). With("Object4Index", 12, 2).As(interpreters.ObjectIndex()). With("Object4Delay", 14, 2).As(interpreters.FormattedRangedValue(0, 6000, pointOneSecond)) var changeLightingDetails = interpreters.New(). Refining("ObjectExtent", 0, 2, interpreters.New().With("Index", 0, 2).As(interpreters.ObjectIndex()), func(inst *interpreters.Instance) bool { var lightType = inst.Get("LightType") return (lightType == 0x00) || (lightType == 0x01) }). Refining("RadiusExtent", 0, 2, interpreters.New().With("Tiles", 0, 2).As(interpreters.RangedValue(0, 31)), func(inst *interpreters.Instance) bool { return inst.Get("LightType") == 0x03 }). With("ReferenceObjectIndex", 2, 2).As(interpreters.ObjectIndex()). With("TransitionType", 4, 2).As(interpreters.EnumValue(map[uint32]string{0x0000: "immediate", 0x0001: "fade", 0x0100: "flicker"})). With("LightModification", 7, 1).As(interpreters.EnumValue(map[uint32]string{0x00: "light on", 0x10: "light off"})). With("LightType", 8, 1).As(interpreters.EnumValue(map[uint32]string{0x00: "rectangular", 0x03: "circular gradient"})). With("LightSurface", 10, 2).As(interpreters.EnumValue(map[uint32]string{0: "floor", 1: "ceiling", 2: "floor and ceiling"})). Refining("Rectangular", 12, 2, interpreters.New(). With("Off light value", 0, 1).As(interpreters.RangedValue(0, 15)). With("On light value", 1, 1).As(interpreters.RangedValue(0, 15)), func(inst *interpreters.Instance) bool { return inst.Get("LightType") == 0x00 }). Refining("Gradient", 12, 4, interpreters.New(). With("Off light begin intensity", 0, 1).As(interpreters.RangedValue(0, 127)). With("Off light end intensity", 1, 1).As(interpreters.RangedValue(0, 127)). With("On light begin intensity", 2, 1).As(interpreters.RangedValue(0, 127)). With("On light end intensity", 3, 1).As(interpreters.RangedValue(0, 127)), func(inst *interpreters.Instance) bool { var lightType = inst.Get("LightType") return (lightType == 0x01) || (lightType == 0x03) }) var effectDetails = interpreters.New(). With("SoundIndex", 0, 2).As(interpreters.RangedValue(0, 512)). With("SoundPlayCount", 2, 2).As(interpreters.RangedValue(0, 100)). With("VisualEffect", 4, 2).As(interpreters.EnumValue(map[uint32]string{ 0: "none", 1: "power on", 2: "quake", 3: "escape pod", 4: "red static", 5: "interference"})). With("AdditionalVisualEffect", 8, 2).As(interpreters.EnumValue(map[uint32]string{ 0: "none", 1: "white flash", 2: "pink flash", 3: "gray static (endless, don't use)", 4: "vertical panning (endless, don't use)"})) var changeTileHeightsDetails = interpreters.New(). With("TileX", 0, 4).As(interpreters.RangedValue(1, 63)). With("TileY", 4, 4).As(interpreters.RangedValue(1, 63)). With("TargetFloorHeight", 8, 2).As(interpreters.SpecialValue("MoveTileHeight")). With("TargetCeilingHeight", 10, 2).As(interpreters.SpecialValue("MoveTileHeight")). With("Ignored000C", 12, 4).As(interpreters.SpecialValue("Ignored")) var randomTimerDetails = interpreters.New(). With("ObjectIndex", 0, 4).As(interpreters.ObjectIndex()). With("TimeInterval", 4, 4).As(interpreters.FormattedRangedValue(0, 6000, func(value int64) string { return fmt.Sprintf("%.1fs", float64(value)/10.0) })). With("ActivationValue", 8, 4).As(interpreters.EnumValue(map[uint32]string{0: "Off", 0xFFFF: "On (0xFFFF)", 0x10000: "On (0x10000)", 0x11111: "On (0x11111)"})). With("Variance", 12, 2).As(interpreters.RangedValue(0, 512)) var cycleObjectsDetails = interpreters.New(). With("ObjectIndex1", 0, 4).As(interpreters.ObjectIndex()). With("ObjectIndex2", 4, 4).As(interpreters.ObjectIndex()). With("ObjectIndex3", 8, 4).As(interpreters.ObjectIndex()). With("NextObject", 12, 4).As(interpreters.RangedValue(0, 2)) var deleteObjectsDetails = interpreters.New(). With("ObjectIndex1", 0, 2).As(interpreters.ObjectIndex()). With("ObjectIndex2", 4, 2).As(interpreters.ObjectIndex()). With("ObjectIndex3", 8, 2).As(interpreters.ObjectIndex()). With("MessageIndex", 12, 2).As(interpreters.RangedValue(0, 511)) var receiveEmailDetails = interpreters.New(). With("EmailIndex", 0, 2).As(interpreters.RangedValue(0, 1000)). With("DelaySec", 4, 2).As(interpreters.RangedValue(0, 600)) var changeEffectDetails = interpreters.New(). With("DeltaValue", 0, 2).As(interpreters.RangedValue(0, 1000)). With("EffectChangeFlag", 2, 2).As(interpreters.EnumValue(map[uint32]string{0: "Add Delta", 1: "Remove Delta"})). With("EffectType", 4, 4).As(interpreters.EnumValue(map[uint32]string{4: "Radiation poisoning", 8: "Bio contamination"})) var setObjectParameterDetails = interpreters.New(). With("ObjectIndex", 0, 4).As(interpreters.ObjectIndex()). With("Value1", 4, 4). With("Value2", 8, 4). With("Value3", 12, 4) var setScreenPictureDetails = interpreters.New(). With("ScreenObjectIndex1", 0, 2).As(interpreters.ObjectIndex()). With("ScreenObjectIndex2", 2, 2).As(interpreters.ObjectIndex()). With("SingleSequenceSource", 4, 4). With("LoopSequenceSource", 8, 4) var setCritterStateDetails = interpreters.New(). With("ReferenceObjectIndex1", 4, 2).As(interpreters.ObjectIndex()). With("ReferenceObjectIndex2", 6, 2).As(interpreters.ObjectIndex()). With("NewState", 8, 1).As(interpreters.EnumValue(map[uint32]string{ 0: "docile", 1: "cautious", 2: "hostile", 3: "cautious (?)", 4: "attacking", 5: "sleeping", 6: "tranquilized", 7: "confused"})) var trapMessageDetails = interpreters.New(). With("BackgroundImageIndex", 0, 4).As(interpreters.RangedValue(-2, 500)). With("MessageIndex", 4, 4).As(interpreters.RangedValue(0, 511)). With("TextColor", 8, 4).As(interpreters.RangedValue(0, 255)). With("MfdSuppressionFlag", 12, 4).As(interpreters.EnumValue(map[uint32]string{0: "Show in MFD", 1: "Show only in HUD"})) var spawnObjectsDetails = interpreters.New(). With("ObjectType", 0, 4).As(interpreters.SpecialValue("ObjectType")). With("ReferenceObject1Index", 4, 2).As(interpreters.ObjectIndex()). With("ReferenceObject2Index", 6, 2).As(interpreters.ObjectIndex()). With("NumberOfObjects", 8, 4).As(interpreters.RangedValue(0, 100)). With("Unknown000C", 12, 1).As(interpreters.SpecialValue("Unknown")) var changeObjectTypeDetails = interpreters.New(). With("ObjectIndex", 0, 4).As(interpreters.ObjectIndex()). With("NewType", 4, 2).As(interpreters.RangedValue(0, 16)). With("ResetMask", 6, 2).As(interpreters.RangedValue(0, 15)) // Change state block var toggleRepulsorChange = interpreters.New(). With("ObjectIndex", 0, 4).As(interpreters.ObjectIndex()). With("OffTextureIndex", 4, 1).As(interpreters.SpecialValue("LevelTexture")). With("OnTextureIndex", 5, 1).As(interpreters.SpecialValue("LevelTexture")). With("ToggleType", 8, 1).As(interpreters.EnumValue(map[uint32]string{0: "Toggle On/Off", 1: "Toggle On, Stay On", 2: "Toggle Off, Stay Off"})) var showGameCodeDigitChange = interpreters.New(). With("ScreenObjectIndex", 0, 4).As(interpreters.ObjectIndex()). With("DigitNumber", 4, 4).As(interpreters.RangedValue(1, 6)) var setParameterFromVariableChange = interpreters.New(). With("ObjectIndex", 0, 4).As(interpreters.ObjectIndex()). With("ParameterNumber", 4, 4).As(interpreters.RangedValue(0, 16)). With("VariableIndex", 8, 4).As(interpreters.SpecialValue("VariableKey")) var setButtonStateChange = interpreters.New(). With("ObjectIndex", 0, 4).As(interpreters.ObjectIndex()). With("NewState", 4, 4).As(interpreters.EnumValue(map[uint32]string{0: "Off", 1: "On"})) var doorControlChange = interpreters.New(). With("ObjectIndex", 0, 4).As(interpreters.ObjectIndex()). With("ControlValue", 4, 4).As(interpreters.EnumValue(map[uint32]string{1: "open door", 2: "close door", 3: "toggle door", 4: "suppress auto-close"})) var rotateObjectChange = interpreters.New(). With("ObjectIndex", 0, 4).As(interpreters.ObjectIndex()). With("Amount", 4, 1).As(interpreters.RangedValue(0, 255)). With("RotationType", 5, 1).As(interpreters.EnumValue(map[uint32]string{0: "Endless", 1: "Back and forth"})). With("Direction", 6, 1).As(interpreters.EnumValue(map[uint32]string{0: "Forward", 1: "Backward"})). With("Axis", 7, 1).As(interpreters.EnumValue(map[uint32]string{0: "Z (Yaw)", 1: "X (Pitch)", 2: "Y (Roll)"})). With("ForwardLimit", 8, 1).As(interpreters.RangedValue(0, 255)). With("BackwardLimit", 9, 1).As(interpreters.RangedValue(0, 255)) var removeObjectsChange = interpreters.New(). With("ObjectType", 0, 4).As(interpreters.SpecialValue("ObjectType")). With("Amount", 4, 1).As(interpreters.RangedValue(0, 255)) var setConditionChange = interpreters.New(). With("ObjectIndex", 0, 4).As(interpreters.ObjectIndex()). With("Condition", 4, 4) var makeItemRadioactiveChange = interpreters.New(). With("ObjectIndex", 0, 4).As(interpreters.ObjectIndex()). With("WatchedObjectIndex", 4, 2).As(interpreters.ObjectIndex()). With("WatchedObjectTriggerState", 6, 2) var orientedTriggerObjectChange = interpreters.New(). With("HorizontalDirection", 0, 2).As(interpreters.RangedValue(0, 0xFFFF)). With("ObjectIndex", 4, 2).As(interpreters.ObjectIndex()) var closeDataMfdChange = interpreters.New(). With("ObjectIndex", 0, 4).As(interpreters.ObjectIndex()) var changeObjectTypeGlobalChange = interpreters.New(). With("ObjectType", 0, 4).As(interpreters.SpecialValue("ObjectType")). With("NewType", 4, 1).As(interpreters.RangedValue(0, 16)) var changeStateDetails = interpreters.New(). With("Type", 0, 4).As(interpreters.EnumValue(map[uint32]string{ 1: "Toggle Repulsor", 2: "Show Game Code Digit", 3: "Set Parameter from Variable", 4: "Set Button State", 5: "Door Control", 6: "Return to Menu", 7: "Rotate Objects", 8: "Remove Objects", 9: "SHODAN Pixelation", 10: "Set Condition", 11: "Show System Analyzer", 12: "Make Item Radioactive", 13: "Oriented Trigger Object", 14: "Close Data MFD", 15: "Earth Destruction by Laser", 16: "Change Objects Type (Level)"})). Refining("ToggleRepulsor", 4, 12, toggleRepulsorChange, forType(1)). Refining("ShowGameCodeDigit", 4, 12, showGameCodeDigitChange, forType(2)). Refining("SetParameterFromVariable", 4, 12, setParameterFromVariableChange, forType(3)). Refining("SetButtonState", 4, 12, setButtonStateChange, forType(4)). Refining("DoorControl", 4, 12, doorControlChange, forType(5)). Refining("ReturnToMenu", 4, 12, interpreters.New(), forType(6)). Refining("RotateObject", 4, 12, rotateObjectChange, forType(7)). Refining("RemoveObjects", 4, 12, removeObjectsChange, forType(8)). Refining("ShodanPixelation", 4, 12, interpreters.New(), forType(9)). Refining("SetCondition", 4, 12, setConditionChange, forType(10)). Refining("ShowSystemAnalyzer", 4, 12, interpreters.New(), forType(11)). Refining("MakeItemRadioactive", 4, 12, makeItemRadioactiveChange, forType(12)). Refining("OrientedTriggerObject", 4, 12, orientedTriggerObjectChange, forType(13)). Refining("CloseDataMfd", 4, 12, closeDataMfdChange, forType(14)). Refining("EarthDestructionByLaser", 4, 12, interpreters.New(), forType(15)). Refining("ChangeObjectsType", 4, 12, changeObjectTypeGlobalChange, forType(16)) var unconditionalAction = interpreters.New(). With("Type", 0, 1).As(interpreters.EnumValue(map[uint32]string{ 0: "Nothing", 1: "Transport Hacker", 2: "Change Health", 3: "Clone/Move Object", 4: "Set Game Variable", 5: "Show Cutscene", 6: "Trigger Other Objects", 7: "Change Lighting", 8: "Effect", 9: "Change Tile Heights", 10: "Unknown (10)", 11: "Random Timer", 12: "Cycle Objects", 13: "Delete Objects", 14: "Unknown (14)", 15: "Receive E-Mail", 16: "Change Effect", 17: "Set Object Parameter", 18: "Set Screen Picture", 19: "Change State", 20: "Unknown (20)", 21: "Set Critter State", 22: "Trap Message", 23: "Spawn Objects", 24: "Change Object Type"})). With("UsageQuota", 1, 1). Refining("TransportHacker", 6, 16, transportHackerDetails, forType(1)). Refining("ChangeHealth", 6, 16, changeHealthDetails, forType(2)). Refining("CloneMoveObject", 6, 16, cloneMoveObjectDetails, forType(3)). Refining("SetGameVariable", 6, 16, setGameVariableDetails, forType(4)). Refining("ShowCutscene", 6, 16, showCutsceneDetails, forType(5)). Refining("TriggerOtherObjects", 6, 16, triggerOtherObjectsDetails, forType(6)). Refining("ChangeLighting", 6, 16, changeLightingDetails, forType(7)). Refining("Effect", 6, 16, effectDetails, forType(8)). Refining("ChangeTileHeights", 6, 16, changeTileHeightsDetails, forType(9)). // 10 unknown Refining("RandomTimer", 6, 16, randomTimerDetails, forType(11)). Refining("CycleObjects", 6, 16, cycleObjectsDetails, forType(12)). Refining("DeleteObjects", 6, 16, deleteObjectsDetails, forType(13)). // 14 unknown Refining("ReceiveEmail", 6, 16, receiveEmailDetails, forType(15)). Refining("ChangeEffect", 6, 16, changeEffectDetails, forType(16)). Refining("SetObjectParameter", 6, 16, setObjectParameterDetails, forType(17)). Refining("SetScreenPicture", 6, 16, setScreenPictureDetails, forType(18)). Refining("ChangeState", 6, 16, changeStateDetails, forType(19)). // 20 unknown Refining("SetCritterState", 6, 16, setCritterStateDetails, forType(21)). Refining("TrapMessage", 6, 16, trapMessageDetails, forType(22)). Refining("SpawnObjects", 6, 16, spawnObjectsDetails, forType(23)). Refining("ChangeObjectType", 6, 16, changeObjectTypeDetails, forType(24))
data/levelobj/actions/actions.go
0.519034
0.465266
actions.go
starcoder
package storj import ( "encoding/base32" "github.com/zeebo/errs" ) // EncryptionParameters is the cipher suite and parameters used for encryption type EncryptionParameters struct { // CipherSuite specifies the cipher suite to be used for encryption. CipherSuite CipherSuite // BlockSize determines the unit size at which encryption is performed. // It is important to distinguish this from the block size used by the // cipher suite (probably 128 bits). There is some small overhead for // each encryption unit, so BlockSize should not be too small, but // smaller sizes yield shorter first-byte latency and better seek times. // Note that BlockSize itself is the size of data blocks _after_ they // have been encrypted and the authentication overhead has been added. // It is _not_ the size of the data blocks to _be_ encrypted. BlockSize int32 } // IsZero returns true if no field in the struct is set to non-zero value func (params EncryptionParameters) IsZero() bool { return params == (EncryptionParameters{}) } // CipherSuite specifies one of the encryption suites supported by Storj // libraries for encryption of in-network data. type CipherSuite byte const ( // EncUnspecified indicates no encryption suite has been selected. EncUnspecified = CipherSuite(iota) // EncNull indicates use of the NULL cipher; that is, no encryption is // done. The ciphertext is equal to the plaintext. EncNull // EncAESGCM indicates use of AES128-GCM encryption. EncAESGCM // EncSecretBox indicates use of XSalsa20-Poly1305 encryption, as provided // by the NaCl cryptography library under the name "Secretbox". EncSecretBox // EncNullBase64URL is like EncNull but Base64 encodes/decodes the // binary path data (URL-safe) EncNullBase64URL ) // Constant definitions for key and nonce sizes const ( KeySize = 32 NonceSize = 24 ) // NewKey creates a new Storj key from humanReadableKey. func NewKey(humanReadableKey []byte) (*Key, error) { var key Key // Because of backward compatibility the key is filled with 0 or truncated if // humanReadableKey isn't of the same size that KeySize. // See https://github.com/storj/storj/pull/1967#discussion_r285544849 copy(key[:], humanReadableKey) return &key, nil } // Key represents the largest key used by any encryption protocol type Key [KeySize]byte // Raw returns the key as a raw byte array pointer func (key *Key) Raw() *[KeySize]byte { return (*[KeySize]byte)(key) } // IsZero returns true if key is nil or it points to its zero value func (key *Key) IsZero() bool { return key == nil || *key == (Key{}) } // ErrNonce is used when something goes wrong with a stream ID var ErrNonce = errs.Class("nonce error") // nonceEncoding is base32 without padding var nonceEncoding = base32.StdEncoding.WithPadding(base32.NoPadding) // Nonce represents the largest nonce used by any encryption protocol type Nonce [NonceSize]byte // NonceFromString decodes an base32 encoded func NonceFromString(s string) (Nonce, error) { nonceBytes, err := nonceEncoding.DecodeString(s) if err != nil { return Nonce{}, ErrNonce.Wrap(err) } return NonceFromBytes(nonceBytes) } // NonceFromBytes converts a byte slice into a nonce func NonceFromBytes(b []byte) (Nonce, error) { if len(b) != len(Nonce{}) { return Nonce{}, ErrNonce.New("not enough bytes to make a nonce; have %d, need %d", len(b), len(NodeID{})) } var nonce Nonce copy(nonce[:], b) return nonce, nil } // IsZero returns whether nonce is unassigned func (nonce Nonce) IsZero() bool { return nonce == Nonce{} } // String representation of the nonce func (nonce Nonce) String() string { return nonceEncoding.EncodeToString(nonce.Bytes()) } // Bytes returns bytes of the nonce func (nonce Nonce) Bytes() []byte { return nonce[:] } // Raw returns the nonce as a raw byte array pointer func (nonce *Nonce) Raw() *[NonceSize]byte { return (*[NonceSize]byte)(nonce) } // Marshal serializes a nonce func (nonce Nonce) Marshal() ([]byte, error) { return nonce.Bytes(), nil } // MarshalTo serializes a nonce into the passed byte slice func (nonce *Nonce) MarshalTo(data []byte) (n int, err error) { n = copy(data, nonce.Bytes()) return n, nil } // Unmarshal deserializes a nonce func (nonce *Nonce) Unmarshal(data []byte) error { var err error *nonce, err = NonceFromBytes(data) return err } // Size returns the length of a nonce (implements gogo's custom type interface) func (nonce Nonce) Size() int { return len(nonce) } // MarshalJSON serializes a nonce to a json string as bytes func (nonce Nonce) MarshalJSON() ([]byte, error) { return []byte(`"` + nonce.String() + `"`), nil } // UnmarshalJSON deserializes a json string (as bytes) to a nonce func (nonce *Nonce) UnmarshalJSON(data []byte) error { var err error *nonce, err = NonceFromString(string(data)) return err } // EncryptedPrivateKey is a private key that has been encrypted type EncryptedPrivateKey []byte
vendor/storj.io/common/storj/encryption.go
0.804214
0.50293
encryption.go
starcoder
package audio import "github.com/moshenahmias/gopherboy/memory" // AddrNR21 is the NR21 register address const AddrNR21 uint16 = 0xFF16 // AddrNR22 is the NR22 register address const AddrNR22 uint16 = 0xFF17 // AddrNR23 is the NR23 register address const AddrNR23 uint16 = 0xFF18 // AddrNR24 is the NR24 register address const AddrNR24 uint16 = 0xFF19 // Square2 sound channel type Square2 struct { nr21 byte nr22 byte nr23 byte nr24 byte frequencyCounter int envalopeCounter byte volume byte wavePos byte waveState bool } // Read from the channel registers func (s *Square2) Read(addr uint16) (byte, error) { switch addr { case AddrNR21: return s.nr21, nil case AddrNR22: return s.nr22, nil case AddrNR23: return s.nr23, nil case AddrNR24: return s.nr24, nil } return 0, memory.ReadOutOfRangeError(addr) } // Write to the timer registers func (s *Square2) Write(addr uint16, data byte) error { switch addr { case AddrNR21: s.nr21 = data return nil case AddrNR22: s.nr22 = data return nil case AddrNR23: s.nr23 = data return nil case AddrNR24: s.nr24 = data if data&0x80 == 0x80 { s.initialize() } return nil } return memory.WriteOutOfRangeError(addr) } // ClockChanged is called after every instruction execution func (s *Square2) ClockChanged(cycles int) error { s.frequencyCounter += cycles waveRate := s.waveRate() if s.frequencyCounter >= waveRate { s.frequencyCounter = s.frequencyCounter - waveRate waveform := DutyTable[s.duty()] s.waveState = (waveform>>(7-s.wavePos))&0x01 == 0x01 s.wavePos = (s.wavePos + 1) % 8 } return nil } func (s *Square2) output() byte { if !s.enabled() || !s.waveState { return 0 } return s.volume } func (s *Square2) initialize() { s.setLengthLoad(63) s.frequencyCounter = 0 s.envalopeCounter = s.envalopePeriod() s.volume = s.envalopeVolume() s.wavePos = 0 s.waveState = false } func (s *Square2) enabled() bool { return s.lengthLoad() > 0 && s.dac() } func (s *Square2) envelopeClock() { if s.envalopeCounter == 0 { return } s.envalopeCounter-- if s.envalopeMode() { // increase if s.volume < 15 { s.volume++ } } else { // decrease if s.volume > 0 { s.volume-- } } } func (s *Square2) lengthClock() { if !s.lengthEnabled() { return } length := s.lengthLoad() if length == 0 { return } s.setLengthLoad(length - 1) } func (s *Square2) waveRate() int { freq := int(uint(s.frequency())) return (2048 - freq) * 4 } func (s *Square2) duty() byte { return s.nr21 >> 6 } func (s *Square2) lengthLoad() byte { return s.nr21 & 0x3F } func (s *Square2) setLengthLoad(length byte) { s.nr21 = (s.nr21 & 0xC0) | (length & 0x3F) } func (s *Square2) lengthEnabled() bool { return s.nr24&0x40 == 0x40 } func (s *Square2) envalopeVolume() byte { return s.nr22 >> 4 } func (s *Square2) envalopeMode() bool { return s.nr22&0x08 == 0x08 } func (s *Square2) envalopePeriod() byte { return s.nr22 & 0x07 } func (s *Square2) frequency() uint16 { return uint16(s.nr23) | (uint16(s.nr24&0x07) << 8) } func (s *Square2) dac() bool { return s.nr22&0xF8 != 0 }
audio/square2.go
0.696371
0.462473
square2.go
starcoder
package conversion import ( "strings" // Used for efficient string builder (more efficient than simply appending strings) ) const Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" // Base64Encode encodes the received input bytes slice into a base64 string. // The implementation follows the RFC4648 standard, which is documented // at https://datatracker.ietf.org/doc/html/rfc4648#section-4 func Base64Encode(input []byte) string { var sb strings.Builder // If not 24 bits (3 bytes) multiple, pad with 0 value bytes, and with "=" for the output var padding string for i := len(input) % 3; i > 0 && i < 3; i++ { var zeroByte byte input = append(input, zeroByte) padding += "=" } // encode 24 bits per 24 bits (3 bytes per 3 bytes) for i := 0; i < len(input); i += 3 { // select 3 8-bit input groups, and re-arrange them into 4 6-bit groups // the literal 0x3F corresponds to the byte "0011 1111" // the operation "byte & 0x3F" masks the two left-most bits group := [4]byte{ input[i] >> 2, (input[i]<<4)&0x3F + input[i+1]>>4, (input[i+1]<<2)&0x3F + input[i+2]>>6, input[i+2] & 0x3F, } // translate each group into a char using the static map for _, b := range group { sb.WriteString(string(Alphabet[int(b)])) } } encoded := sb.String() // Apply the output padding encoded = encoded[:len(encoded)-len(padding)] + padding[:] return encoded } // Base64Decode decodes the received input base64 string into a byte slice. // The implementation follows the RFC4648 standard, which is documented // at https://datatracker.ietf.org/doc/html/rfc4648#section-4 func Base64Decode(input string) []byte { padding := strings.Count(input, "=") // Number of bytes which will be ignored var decoded []byte // select 4 6-bit input groups, and re-arrange them into 3 8-bit groups for i := 0; i < len(input); i += 4 { // translate each group into a byte using the static map byteInput := [4]byte{ byte(strings.IndexByte(Alphabet, input[i])), byte(strings.IndexByte(Alphabet, input[i+1])), byte(strings.IndexByte(Alphabet, input[i+2])), byte(strings.IndexByte(Alphabet, input[i+3])), } group := [3]byte{ byteInput[0]<<2 + byteInput[1]>>4, byteInput[1]<<4 + byteInput[2]>>2, byteInput[2]<<6 + byteInput[3], } decoded = append(decoded, group[:]...) } return decoded[:len(decoded)-padding] }
conversion/base64.go
0.763484
0.416678
base64.go
starcoder
package rawp import ( "image" "reflect" imageExt "github.com/chai2010/image" ) func defaultDepthKind(depth int) reflect.Kind { switch depth { case 8: return reflect.Uint8 case 16: return reflect.Uint16 case 32: return reflect.Float32 } return reflect.Uint16 } func newBytes(size int, buf []byte) []byte { if len(buf) >= size { return buf[:size] } return make([]byte, size) } func newGray(r image.Rectangle, buf imageExt.Buffer) *image.Gray { if buf != nil && r.In(buf.Bounds()) { if m, ok := buf.SubImage(r).(*image.Gray); ok { return m } } return image.NewGray(r) } func newGray16(r image.Rectangle, buf imageExt.Buffer) *image.Gray16 { if buf != nil && r.In(buf.Bounds()) { if m, ok := buf.SubImage(r).(*image.Gray16); ok { return m } } return image.NewGray16(r) } func newGray32f(r image.Rectangle, buf imageExt.Buffer) *imageExt.Gray32f { if buf != nil && r.In(buf.Bounds()) { if m, ok := buf.SubImage(r).(*imageExt.Gray32f); ok { return m } } return imageExt.NewGray32f(r) } func newRGB(r image.Rectangle, buf imageExt.Buffer) *imageExt.RGB { if buf != nil && r.In(buf.Bounds()) { if m, ok := buf.SubImage(r).(*imageExt.RGB); ok { return m } } return imageExt.NewRGB(r) } func newRGB48(r image.Rectangle, buf imageExt.Buffer) *imageExt.RGB48 { if buf != nil && r.In(buf.Bounds()) { if m, ok := buf.SubImage(r).(*imageExt.RGB48); ok { return m } } return imageExt.NewRGB48(r) } func newRGB96f(r image.Rectangle, buf imageExt.Buffer) *imageExt.RGB96f { if buf != nil && r.In(buf.Bounds()) { if m, ok := buf.SubImage(r).(*imageExt.RGB96f); ok { return m } } return imageExt.NewRGB96f(r) } func newRGBA(r image.Rectangle, buf imageExt.Buffer) *image.RGBA { if buf != nil && r.In(buf.Bounds()) { if m, ok := buf.SubImage(r).(*image.RGBA); ok { return m } } return image.NewRGBA(r) } func newRGBA64(r image.Rectangle, buf imageExt.Buffer) *image.RGBA64 { if buf != nil && r.In(buf.Bounds()) { if m, ok := buf.SubImage(r).(*image.RGBA64); ok { return m } } return image.NewRGBA64(r) } func newRGBA128f(r image.Rectangle, buf imageExt.Buffer) *imageExt.RGBA128f { if buf != nil && r.In(buf.Bounds()) { if m, ok := buf.SubImage(r).(*imageExt.RGBA128f); ok { return m } } return imageExt.NewRGBA128f(r) }
rawp/util.go
0.63861
0.483466
util.go
starcoder
package yamled import ( "fmt" "io" yaml "gopkg.in/yaml.v2" ) type Document struct { root yaml.MapSlice } func Load(r io.Reader) (*Document, error) { var data yaml.MapSlice if err := yaml.NewDecoder(r).Decode(&data); err != nil { return nil, fmt.Errorf("failed to decode input YAML: %v", err) } return NewFromMapSlice(data) } func NewFromMapSlice(m yaml.MapSlice) (*Document, error) { return &Document{ root: m, }, nil } func (d *Document) MarshalYAML() (interface{}, error) { return d.root, nil } func (d *Document) Root() yaml.MapSlice { return d.root } func (d *Document) Has(path Path) bool { _, exists := d.Get(path) return exists } func (d *Document) Get(path Path) (interface{}, bool) { result := interface{}(d.root) for _, step := range path { stepFound := false if sstep, ok := step.(string); ok { // step is string => try descending down a map m, ok := result.(map[string]interface{}) if ok { result, stepFound = m[sstep] } else { node, ok := result.(yaml.MapSlice) if !ok { return nil, false } for _, item := range node { if item.Key.(string) == sstep { stepFound = true result = item.Value break } } } } else if istep, ok := step.(int); ok { // step is int => try getting Nth element of list node, ok := result.([]interface{}) if !ok { return nil, false } if istep < 0 || istep >= len(node) { return nil, false } stepFound = true result = node[istep] } if !stepFound { return nil, false } } return result, true } func (d *Document) GetString(path Path) (string, bool) { val, exists := d.Get(path) if !exists { return "", exists } asserted, ok := val.(string) return asserted, ok } func (d *Document) GetInt(path Path) (int, bool) { val, exists := d.Get(path) if !exists { return 0, exists } asserted, ok := val.(int) return asserted, ok } func (d *Document) GetBool(path Path) (bool, bool) { val, exists := d.Get(path) if !exists { return false, exists } asserted, ok := val.(bool) return asserted, ok } func (d *Document) GetArray(path Path) ([]interface{}, bool) { val, exists := d.Get(path) if !exists { return nil, exists } asserted, ok := val.([]interface{}) return asserted, ok } func (d *Document) Set(path Path, newValue interface{}) bool { // we always need a key or array position to work with if len(path) == 0 { return false } return d.setInternal(path, newValue) } func (d *Document) setInternal(path Path, newValue interface{}) bool { // when we have reached the root level, // replace our root element with the new data structure if len(path) == 0 { return d.setRoot(newValue) } leafKey := path.Tail() parentPath := path.Parent() target := interface{}(d.root) // check if the parent element exists; // create parent if missing if len(parentPath) > 0 { var exists bool target, exists = d.Get(parentPath) if !exists { if _, ok := leafKey.(int); ok { // this slice can be empty for now because we will extend it later if !d.setInternal(parentPath, []interface{}{}) { return false } } else if _, ok := leafKey.(string); ok { if !d.setInternal(parentPath, map[string]interface{}{}) { return false } } else { return false } target, _ = d.Get(parentPath) } } // Now we know that the parent element exists. if pos, ok := leafKey.(int); ok { // check if we are really in an array if array, ok := target.([]interface{}); ok { for i := len(array); i <= pos; i++ { array = append(array, nil) } array[pos] = newValue return d.setInternal(parentPath, array) } } else if key, ok := leafKey.(string); ok { // check if we are really in a map if m, ok := target.(map[string]interface{}); ok { m[key] = newValue return d.setInternal(parentPath, m) } if m, ok := target.(*yaml.MapSlice); ok { target = *m } if m, ok := target.(yaml.MapSlice); ok { return d.setInternal(parentPath, setValueInMapSlice(m, key, newValue)) } } return false } func (d *Document) setRoot(newValue interface{}) bool { if asserted, ok := newValue.(yaml.MapSlice); ok { d.root = asserted return true } if asserted, ok := newValue.(*yaml.MapSlice); ok { d.root = *asserted return true } if asserted, ok := newValue.(map[string]interface{}); ok { d.root = makeMapSlice(asserted) return true } // attempted to set something that's not a map return false } func (d *Document) Append(path Path, newValue interface{}) bool { // we require maps at the root level, so the path cannot be empty if len(path) == 0 { return false } node, ok := d.Get(path) if !ok { return d.Set(path, []interface{}{newValue}) } array, ok := node.([]interface{}) if !ok { return false } return d.Set(path, append(array, newValue)) } func (d *Document) Remove(path Path) bool { // nuke everything if len(path) == 0 { return d.setRoot(yaml.MapSlice{}) } leafKey := path.Tail() parentPath := path.Parent() parent, exists := d.Get(parentPath) if !exists { return true } if pos, ok := leafKey.(int); ok { if array, ok := parent.([]interface{}); ok { return d.setInternal(parentPath, removeArrayItem(array, pos)) } } else if key, ok := leafKey.(string); ok { // check if we are really in a map if m, ok := parent.(map[string]interface{}); ok { delete(m, key) return d.setInternal(parentPath, m) } if m, ok := parent.(*yaml.MapSlice); ok { parent = *m } if m, ok := parent.(yaml.MapSlice); ok { return d.setInternal(parentPath, removeKeyFromMapSlice(m, key)) } } return false } // Fill will set the value at the path to the newValue, but keeps any existing // sub values intact. func (d *Document) Fill(path Path, newValue interface{}) bool { node, exists := d.Get(path) if !exists { // exit early if there is nothing fancy to do return d.Set(path, newValue) } if source, ok := unifyMapType(node); ok { if newMap, ok := unifyMapType(newValue); ok { node = d.fillMap(source, newMap) } } // persist changes to the node return d.setInternal(path, node) } func (d *Document) fillMap(source yaml.MapSlice, newMap yaml.MapSlice) yaml.MapSlice { for _, newItem := range newMap { key := newItem.Key newValue := newItem.Value existingValue, existed := mapSliceGet(source, key) if existed { if subSource, ok := unifyMapType(existingValue); ok { if newSubMap, ok := unifyMapType(newValue); ok { source = setValueInMapSlice(source, key, d.fillMap(subSource, newSubMap)) } } } else { source = setValueInMapSlice(source, key, newValue) } } return source }
pkg/yamled/document.go
0.652352
0.401512
document.go
starcoder
package koyeb import ( "encoding/json" ) // ListRegionsReply struct for ListRegionsReply type ListRegionsReply struct { Regions *[]RegionListItem `json:"regions,omitempty"` Limit *int64 `json:"limit,omitempty"` Offset *int64 `json:"offset,omitempty"` Count *int64 `json:"count,omitempty"` } // NewListRegionsReply instantiates a new ListRegionsReply 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 NewListRegionsReply() *ListRegionsReply { this := ListRegionsReply{} return &this } // NewListRegionsReplyWithDefaults instantiates a new ListRegionsReply 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 NewListRegionsReplyWithDefaults() *ListRegionsReply { this := ListRegionsReply{} return &this } // GetRegions returns the Regions field value if set, zero value otherwise. func (o *ListRegionsReply) GetRegions() []RegionListItem { if o == nil || o.Regions == nil { var ret []RegionListItem return ret } return *o.Regions } // GetRegionsOk returns a tuple with the Regions field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ListRegionsReply) GetRegionsOk() (*[]RegionListItem, bool) { if o == nil || o.Regions == nil { return nil, false } return o.Regions, true } // HasRegions returns a boolean if a field has been set. func (o *ListRegionsReply) HasRegions() bool { if o != nil && o.Regions != nil { return true } return false } // SetRegions gets a reference to the given []RegionListItem and assigns it to the Regions field. func (o *ListRegionsReply) SetRegions(v []RegionListItem) { o.Regions = &v } // GetLimit returns the Limit field value if set, zero value otherwise. func (o *ListRegionsReply) GetLimit() int64 { if o == nil || o.Limit == nil { var ret int64 return ret } return *o.Limit } // GetLimitOk returns a tuple with the Limit field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ListRegionsReply) GetLimitOk() (*int64, bool) { if o == nil || o.Limit == nil { return nil, false } return o.Limit, true } // HasLimit returns a boolean if a field has been set. func (o *ListRegionsReply) HasLimit() bool { if o != nil && o.Limit != nil { return true } return false } // SetLimit gets a reference to the given int64 and assigns it to the Limit field. func (o *ListRegionsReply) SetLimit(v int64) { o.Limit = &v } // GetOffset returns the Offset field value if set, zero value otherwise. func (o *ListRegionsReply) GetOffset() int64 { if o == nil || o.Offset == nil { var ret int64 return ret } return *o.Offset } // GetOffsetOk returns a tuple with the Offset field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ListRegionsReply) GetOffsetOk() (*int64, bool) { if o == nil || o.Offset == nil { return nil, false } return o.Offset, true } // HasOffset returns a boolean if a field has been set. func (o *ListRegionsReply) HasOffset() bool { if o != nil && o.Offset != nil { return true } return false } // SetOffset gets a reference to the given int64 and assigns it to the Offset field. func (o *ListRegionsReply) SetOffset(v int64) { o.Offset = &v } // GetCount returns the Count field value if set, zero value otherwise. func (o *ListRegionsReply) GetCount() int64 { if o == nil || o.Count == nil { var ret int64 return ret } return *o.Count } // GetCountOk returns a tuple with the Count field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *ListRegionsReply) GetCountOk() (*int64, bool) { if o == nil || o.Count == nil { return nil, false } return o.Count, true } // HasCount returns a boolean if a field has been set. func (o *ListRegionsReply) HasCount() bool { if o != nil && o.Count != nil { return true } return false } // SetCount gets a reference to the given int64 and assigns it to the Count field. func (o *ListRegionsReply) SetCount(v int64) { o.Count = &v } func (o ListRegionsReply) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.Regions != nil { toSerialize["regions"] = o.Regions } if o.Limit != nil { toSerialize["limit"] = o.Limit } if o.Offset != nil { toSerialize["offset"] = o.Offset } if o.Count != nil { toSerialize["count"] = o.Count } return json.Marshal(toSerialize) } type NullableListRegionsReply struct { value *ListRegionsReply isSet bool } func (v NullableListRegionsReply) Get() *ListRegionsReply { return v.value } func (v *NullableListRegionsReply) Set(val *ListRegionsReply) { v.value = val v.isSet = true } func (v NullableListRegionsReply) IsSet() bool { return v.isSet } func (v *NullableListRegionsReply) Unset() { v.value = nil v.isSet = false } func NewNullableListRegionsReply(val *ListRegionsReply) *NullableListRegionsReply { return &NullableListRegionsReply{value: val, isSet: true} } func (v NullableListRegionsReply) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableListRegionsReply) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
api/v1/koyeb/model_list_regions_reply.go
0.748168
0.430686
model_list_regions_reply.go
starcoder
package model import ( "sort" "github.com/pkg/errors" ) // TransactionsOrderedByFeeRate represents a set of MempoolTransactions ordered by their fee / mass rate type TransactionsOrderedByFeeRate struct { slice []*MempoolTransaction } // GetByIndex returns the transaction in the given index func (tobf *TransactionsOrderedByFeeRate) GetByIndex(index int) *MempoolTransaction { return tobf.slice[index] } // Push inserts a transaction into the set, placing it in the correct place to preserve order func (tobf *TransactionsOrderedByFeeRate) Push(transaction *MempoolTransaction) error { index, err := tobf.findTransactionIndex(transaction) if err != nil { return err } tobf.slice = append(tobf.slice[:index], append([]*MempoolTransaction{transaction}, tobf.slice[index:]...)...) return nil } // Remove removes the given transaction from the set. // Returns an error if transaction does not exist in the set, or if the given transaction does not have mass // and fee filled in. func (tobf *TransactionsOrderedByFeeRate) Remove(transaction *MempoolTransaction) error { index, err := tobf.findTransactionIndex(transaction) if err != nil { return err } txID := transaction.TransactionID() if !tobf.slice[index].TransactionID().Equal(txID) { return errors.Errorf("Couldn't find %s in mp.orderedTransactionsByFeeRate", txID) } return tobf.RemoveAtIndex(index) } // RemoveAtIndex removes the transaction at the given index. // Returns an error in case of out-of-bounds index. func (tobf *TransactionsOrderedByFeeRate) RemoveAtIndex(index int) error { if index < 0 || index > len(tobf.slice)-1 { return errors.Errorf("Index %d is out of bound of this TransactionsOrderedByFeeRate", index) } tobf.slice = append(tobf.slice[:index], tobf.slice[index+1:]...) return nil } func (tobf *TransactionsOrderedByFeeRate) findTransactionIndex(transaction *MempoolTransaction) (int, error) { if transaction.Transaction().Fee == 0 || transaction.Transaction().Mass == 0 { return 0, errors.Errorf("findTxIndexInOrderedTransactionsByFeeRate expects a transaction with " + "populated fee and mass") } txID := transaction.TransactionID() txFeeRate := float64(transaction.Transaction().Fee) / float64(transaction.Transaction().Mass) return sort.Search(len(tobf.slice), func(i int) bool { iElement := tobf.slice[i] elementFeeRate := float64(iElement.Transaction().Fee) / float64(iElement.Transaction().Mass) if elementFeeRate > txFeeRate { return true } if elementFeeRate == txFeeRate && txID.LessOrEqual(iElement.TransactionID()) { return true } return false }), nil }
domain/miningmanager/mempool/model/ordered_transactions_by_fee_rate.go
0.828696
0.414069
ordered_transactions_by_fee_rate.go
starcoder