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 docs import "github.com/swaggo/swag" const docTemplate = `{ "schemes": {{ marshal .Schemes }}, "swagger": "2.0", "info": { "description": "{{escape .Description}}", "title": "{{.Title}}", "termsOfService": "http://swagger.io/terms/", "contact": {}, "license": { "name": "Apache 2.0", "url": "http://www.apache.org/licenses/LICENSE-2.0.html" }, "version": "{{.Version}}" }, "host": "{{.Host}}", "basePath": "{{.BasePath}}", "paths": { "/login": { "post": { "description": "Login to create a new access token.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "login" ], "summary": "Login to create a new access token", "parameters": [ { "description": "Username", "name": "username", "in": "body", "required": true, "schema": { "$ref": "#/definitions/models.User" } } ], "responses": { "200": { "description": "ok", "schema": { "type": "string" } }, "403": { "description": "forbidden", "schema": { "type": "string" } } } } }, "/quote": { "post": { "security": [ { "ApiKeyAuth": [] } ], "description": "Save a new quote into the database.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "quotes" ], "summary": "Save a new quote", "parameters": [ { "description": "Quote to be created, id and created_date can be ignored", "name": "quote", "in": "body", "required": true, "schema": { "$ref": "#/definitions/models.Quote" } } ], "responses": { "200": { "description": "OK", "schema": { "type": "string" } }, "429": { "description": "Too Many Requests", "schema": { "type": "string" } } } } }, "/quote/{id}": { "get": { "security": [ { "ApiKeyAuth": [] } ], "description": "Get a quote by ID.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "quotes" ], "summary": "Get a quote by ID", "parameters": [ { "type": "string", "description": "Quote ID", "name": "id", "in": "path", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "$ref": "#/definitions/models.Quote" } }, "429": { "description": "Too Many Requests", "schema": { "type": "string" } } } }, "post": { "security": [ { "ApiKeyAuth": [] } ], "description": "Update a quote in the database.", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "quotes" ], "summary": "Update a quote", "parameters": [ { "type": "string", "description": "Quote ID", "name": "id", "in": "path", "required": true }, { "description": "Quote to be created, id and created_date can be ignored", "name": "quote", "in": "body", "required": true, "schema": { "$ref": "#/definitions/models.Quote" } } ], "responses": { "200": { "description": "OK", "schema": { "type": "string" } }, "429": { "description": "Too Many Requests", "schema": { "type": "string" } } } } }, "/quotes/{page}": { "get": { "description": "Get all quotes (paginated in batches of 10, default start at page 1).", "consumes": [ "application/json" ], "produces": [ "application/json" ], "tags": [ "quotes" ], "summary": "Get all the quote", "parameters": [ { "type": "integer", "default": 1, "description": "Page of quotes", "name": "page", "in": "path", "required": true } ], "responses": { "200": { "description": "OK", "schema": { "type": "array", "items": { "$ref": "#/definitions/models.Quote" } } }, "429": { "description": "Too Many Requests", "schema": { "type": "string" } } } } } }, "definitions": { "models.Quote": { "type": "object", "required": [ "quote", "tags", "work" ], "properties": { "act": { "type": "string" }, "created_date": { "type": "string" }, "id": { "type": "string" }, "quote": { "type": "string" }, "scene": { "type": "string" }, "tags": { "type": "array", "items": { "type": "string" } }, "work": { "type": "string" } } }, "models.User": { "type": "object", "properties": { "username": { "type": "string" } } } }, "securityDefinitions": { "ApiKeyAuth": { "type": "apiKey", "name": "Authorization", "in": "header" } } }` // SwaggerInfo holds exported Swagger Info so clients can modify it var SwaggerInfo = &swag.Spec{ Version: "1.0", Host: "shakespeare.onrender.com", BasePath: "/api/v1", Schemes: []string{}, Title: "Shakespeare Quotes", Description: "API to save and retrieve Shakespeare quotes", InfoInstanceName: "swagger", SwaggerTemplate: docTemplate, } func init() { swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo) }
docs/docs.go
0.57344
0.404449
docs.go
starcoder
package verdeps import ( "fmt" "sort" ) type bytesDiff struct { bytes []byte exclusiveTo int inclusiveFrom int } type bytesDiffs []bytesDiff func (bd bytesDiffs) Len() int { return len(bd) } func (bd bytesDiffs) Less(i, j int) bool { return bd[i].inclusiveFrom >= bd[j].exclusiveTo } func (bd bytesDiffs) Swap(i, j int) { oldI := bd[i] bd[i] = bd[j] bd[j] = oldI } // sortBytesDiffs returns a last-to-first-sorted slice of bytes diffs. func sortBytesDiffs(diffs []bytesDiff) []bytesDiff { sort.Sort(bytesDiffs(diffs)) return diffs } // sortBytesDiffs returns a last-to-first-sorted slice of bytes diffs. func calcBytesDiffsDelta(diffs []bytesDiff) int { delta := 0 for _, diff := range diffs { delta = delta + (len(diff.bytes) - (diff.exclusiveTo - diff.inclusiveFrom)) } return delta } // isBytesDiffValid returns true if diff is valid. func isBytesDiffValid(diff bytesDiff) bool { return diff.exclusiveTo > diff.inclusiveFrom } // cursorsInBounds returns true if the bytesCursor and newBytesCursor are both // within the bounds of slices of size bytesLen and newBytesLen respectively. func cursorsInBounds( bytesLen, newBytesLen, bytesCursor, newBytesCursor int) bool { return bytesCursor >= 0 && newBytesCursor >= 0 && bytesCursor <= bytesLen && newBytesCursor <= newBytesLen } // composeBytesDiffs takes a collection of diffs, sorts them in reverse order, // and applies them to a copy of bytes. Afterwards, the bytes copy is returned. // If any of the diffs are out of bounds, then an error is returned. func composeBytesDiffs(bytes []byte, diffs []bytesDiff) ([]byte, error) { var ( i int diff bytesDiff diffsLen int bytesCursor int newBytesCursor int nextBytesCursor int nextNewBytesCursor int ) // If there are no diffs, then bytes is already correct. if diffsLen = len(diffs); diffsLen < 1 { return bytes, nil } // Make sure that we have a correctly sorted set of diffs. if diffsLen > 1 { diffs = sortBytesDiffs(diffs) } // Perform state initialziation. var ( bytesLen = len(bytes) newBytesLen = len(bytes) + calcBytesDiffsDelta(diffs) newBytes = make([]byte, newBytesLen) ) // Start the cursors at the back. bytesCursor = bytesLen newBytesCursor = newBytesLen // Apply all of the diffs in order. for i, diff = range diffs { // First, validate the diff. if !isBytesDiffValid(diff) { return nil, fmt.Errorf("A bytes diff was invalid: %v.", diff) } // Copy all the stuff in between the previous diff and this one. nextBytesCursor = diff.exclusiveTo nextNewBytesCursor = newBytesCursor - (bytesCursor - nextBytesCursor) // Check that we're in bounds. if !cursorsInBounds(bytesLen, newBytesLen, nextBytesCursor, nextNewBytesCursor) { return nil, fmt.Errorf("A byte diffs was out of bounds: %v.", diff) } // Perform the copy. copy(newBytes[nextNewBytesCursor:newBytesCursor], bytes[nextBytesCursor:bytesCursor]) // Advance the cursors. bytesCursor = nextBytesCursor newBytesCursor = nextNewBytesCursor // Use the cursors to continue copying. nextBytesCursor = bytesCursor - (diff.exclusiveTo - diff.inclusiveFrom) nextNewBytesCursor = newBytesCursor - len(diff.bytes) // Check that we're in bounds. if !cursorsInBounds(bytesLen, newBytesLen, nextBytesCursor, nextNewBytesCursor) { return nil, fmt.Errorf("A byte diffs was out of bounds: %v.", diff) } // Perform the copy. copy(newBytes[nextNewBytesCursor:newBytesCursor], diff.bytes[:]) // Advance the cursors. bytesCursor = nextBytesCursor newBytesCursor = nextNewBytesCursor // If this is the last diff, then we have to copy the bytes in front of // all the diffs. This means the bytes at the _beginning_ of the slice // (due to the sort direction). if i == (diffsLen - 1) { // Perform the copy. copy(newBytes[:bytesCursor], bytes[:newBytesCursor]) } } return newBytes, nil }
lib/verdeps/bytes_diffs.go
0.765067
0.413063
bytes_diffs.go
starcoder
package imageoutput // CoordinateThreshold looks at a CoordinateCollection and determines which coordinates will be kept. type CoordinateThreshold interface { FilterAndMarkMappedCoordinateCollection(collection *CoordinateCollection) } // RectangularCoordinateThreshold defines a rectangular range in which coordinates will be kept. type RectangularCoordinateThreshold struct { minimumX float64 maximumX float64 minimumY float64 maximumY float64 } // MinimumX returns the minimum transformedX value for the filter. func (c *RectangularCoordinateThreshold) MinimumX() float64 { return c.minimumX } // MaximumX returns the maximum transformedX value for the filter. func (c *RectangularCoordinateThreshold) MaximumX() float64 { return c.maximumX } // MinimumY returns the minimum transformedY value for the filter. func (c *RectangularCoordinateThreshold) MinimumY() float64 { return c.minimumY } // MaximumY returns the maximum transformedY value for the filter. func (c *RectangularCoordinateThreshold) MaximumY() float64 { return c.maximumY } // filterAndMarkMappedCoordinate checks if the coordinate satisfies the filter. // Then it marks the coordinate if it satisfied the filtered out. func (c *RectangularCoordinateThreshold) filterAndMarkMappedCoordinate(coordinate *MappedCoordinate) { if !coordinate.CanBeCompared() { return } if coordinate.TransformedX() < c.MinimumX() { return } if coordinate.TransformedX() > c.MaximumX() { return } if coordinate.TransformedY() < c.MinimumY() { return } if coordinate.TransformedY() > c.MaximumY() { return } coordinate.MarkAsSatisfyingFilter() } // FilterAndMarkMappedCoordinateCollection checks all coordinates against the filter. // Then it marks each coordinate if it satisfied the filter. func (c *RectangularCoordinateThreshold) FilterAndMarkMappedCoordinateCollection(collection *CoordinateCollection) { for _, coordinateToFiler := range *collection.Coordinates() { c.filterAndMarkMappedCoordinate(coordinateToFiler) } }
entities/imageoutput/coordinatethreshold.go
0.936959
0.565299
coordinatethreshold.go
starcoder
// Package buffer contains helper functions for writing and reading basic // types into and out of byte slices. package buffer // Stdlib imports. import ( "errors" ) // Data type sizes. const ( BYTE_SIZE = 1 UINT8_SIZE = 1 UINT16_SIZE = 2 UINT32_SIZE = 4 UINT64_SIZE = 8 ) // Common errors. var ( errExceedBounds = errors.New( "Index exceeds capacity of slice/array", ) ) // LenByte returns the encoded length of a byte value. func LenByte() int { return BYTE_SIZE } // LenString returns the encoded length of a given string, including // the extra bytes required to encode its size. func LenString(val string) int { return len(val) + LenUint32() } // LenUint8 returns the lengh of a uint32 value. func LenUint8() int { return UINT8_SIZE } // LenUint16 returns the lengh of a uint32 value. func LenUint16() int { return UINT16_SIZE } // LenUint32 returns the lengh of a uint32 value. func LenUint32() int { return UINT32_SIZE } // LenUint64 returns the encoded length of a uint64 value. func LenUint64() int { return UINT64_SIZE } // ReadByte reads 1 byte value from the given buffer, starting at // the given offset, and increments teh supplied cursor by the length // of the encoded value. func ReadByte(buffer []byte, cursor *int) (byte, error) { if *cursor + BYTE_SIZE > len(buffer) { *cursor = len(buffer) return 0, errExceedBounds } val := buffer[*cursor] *cursor++ return val, nil } // ReadString reads 1 string value from the given buffer, starting at // the given offset, and increments teh supplied cursor by the length // of the encoded value. func ReadString(buffer []byte, cursor *int) (string, error) { size, err := ReadUint32(buffer, cursor) if err != nil { return "", err } if *cursor + int(size) > len(buffer) { *cursor = len(buffer) return "", errExceedBounds } val := string(buffer[*cursor:*cursor + int(size)]) *cursor += len(val) return val, nil } // ReadUint32 reads 1 uint32 value from the given buffer, starting at // the given offset, and increments teh supplied cursor by the length // of the encoded value. func ReadUint32(buffer []byte, cursor *int) (uint32, error) { if *cursor + UINT32_SIZE > len(buffer) { *cursor = len(buffer) return 0, errExceedBounds } val := uint32(buffer[*cursor]) << 24 | uint32(buffer[*cursor + 1]) << 16 | uint32(buffer[*cursor + 2]) << 8 | uint32(buffer[*cursor + 3]) *cursor += UINT32_SIZE return val, nil } // ReadUint64 reads 1 uint64 value from the given buffer, starting at // the given offset, and increments teh supplied cursor by the length // of the encoded value. func ReadUint64(buffer []byte, cursor *int) (uint64, error) { if *cursor + UINT64_SIZE > len(buffer) { *cursor = len(buffer) return 0, errExceedBounds } val := uint64(buffer[*cursor]) << 56 | uint64(buffer[*cursor + 1]) << 48 | uint64(buffer[*cursor + 2]) << 40 | uint64(buffer[*cursor + 3]) << 32 | uint64(buffer[*cursor + 4]) << 24 | uint64(buffer[*cursor + 5]) << 16 | uint64(buffer[*cursor + 6]) << 8 | uint64(buffer[*cursor + 7]) *cursor += UINT64_SIZE return val, nil } // WriteByte writes the given byte value into a buffer at the given // offset and increments the supplied cursor by the length of the encoded // value. func WriteByte(val byte, buffer []byte, cursor *int) { buffer[*cursor] = val *cursor++ } // WriteString writes the given string value into a buffer starting at // the given offset, and increments the supplied counter by the length // of that encoded string. func WriteString(val string, buffer []byte, cursor *int) { WriteUint32(uint32(len(val)), buffer, cursor) count := copy(buffer[*cursor:], []byte(val)) *cursor += count } // WriteUint32 writes the given uint32 value into a buffer at the given // offset and increments the supplied cursor by the lengh of the encoded // value. func WriteUint32(val uint32, buffer []byte, cursor *int) { buffer[*cursor] = byte(val >> 24); *cursor++ buffer[*cursor] = byte(val >> 16); *cursor++ buffer[*cursor] = byte(val >> 8); *cursor++ buffer[*cursor] = byte(val); *cursor++ } // WriteUint64 writes the given uint64 value into a buffer at the given // offset and increments teh supplied cursor by the length of the encoded // value. func WriteUint64(val uint64, buffer []byte, cursor *int) { buffer[*cursor] = byte(val >> 56); *cursor++ buffer[*cursor] = byte(val >> 48); *cursor++ buffer[*cursor] = byte(val >> 40); *cursor++ buffer[*cursor] = byte(val >> 32); *cursor++ buffer[*cursor] = byte(val >> 24); *cursor++ buffer[*cursor] = byte(val >> 16); *cursor++ buffer[*cursor] = byte(val >> 8); *cursor++ buffer[*cursor] = byte(val); *cursor++ }
lib/buffer/buffer.go
0.745584
0.553867
buffer.go
starcoder
package vector import ( "math" ) var EPSILON = math.Nextafter(1, 2) - 1 func min(a, b int) int { if a < b { return a } return b } func New(size int) Vector { return make(Vector, size) } func NewWithValues(values []float64) Vector { v := make(Vector, len(values)) copy(v, values) return v } // Sums of two vectors, returns the resulting vector. func Add(v1, v2 Vector) Vector { length := min(len(v1), len(v2)) result := make(Vector, length) for i := 0; i < length; i++ { result[i] = v1[i] + v2[i] } return result } // Difference of two vectors, returns the resulting vector. func Subtract(v1, v2 Vector) Vector { length := min(len(v1), len(v2)) result := make(Vector, length) for i := 0; i < length; i++ { result[i] = v1[i] - v2[i] } return result } // Dot products of two vectors. func Dot(v1, v2 Vector) (float64, error) { if len(v1) != len(v2) { return 0.0, ErrVectorNotSameSize } length := len(v1) result := 0.0 for i := 0; i < length; i++ { result += v1[i] * v2[i] } return result, nil } // Cross products of two vectors. // Vector dimensionality has to be 3. func Cross(v1, v2 Vector) (Vector, error) { // Early error check to prevent redundant cloning if len(v1) != 3 || len(v2) != 3 { return nil, ErrVectorInvalidDimension } result := make(Vector, 3) result[0] = v1[1]*v2[2] - v1[2]*v2[1] result[1] = v1[2]*v2[0] - v1[0]*v2[2] result[2] = v1[0]*v2[1] - v1[1]*v2[0] return result, nil } func Unit(v Vector) Vector { magRec := 1.0 / v.Magnitude() unit := v.Clone() for i, _ := range unit { unit[i] *= magRec } return unit } func Hadamard(v1, v2 Vector) (Vector, error) { if len(v1) != len(v2) { return nil, ErrVectorInvalidDimension } length := len(v1) result := make(Vector, length) for i := 0; i < length; i++ { result[i] = v1[i] * v2[i] } return result, nil } func Det(v1, v2 Vector) float64 { return v1[0]*v2[1] - v1[1]*v2[0] } func LeftOf(v1, v2, v3 Vector) float64 { return Det(Subtract(v1, v3), Subtract(v2, v1)) }
package.go
0.828904
0.526586
package.go
starcoder
package heuristic import ( "fmt" "github.com/gnames/gnfinder/ent/token" "github.com/gnames/gnfinder/io/dict" ) // TagTokens is important for both heuristic and Bayes approaches. It analyses // tokens and sets up token's indices. Indices determine if a token is a // potential unimonial, binomial or trinomial. Then if fills out signfificant // number of features pertained to the token. func TagTokens(ts []token.TokenSN, d *dict.Dictionary) { l := len(ts) for i := range ts { if !ts[i].Features().IsCapitalized { continue } nameTs := ts[i:token.UpperIndex(i, l)] token.SetIndices(nameTs, d) exploreNameCandidate(nameTs, d) } } func exploreNameCandidate(ts []token.TokenSN, d *dict.Dictionary) bool { u := ts[0] if u.Features().UninomialDict == dict.WhiteUninomial || (u.Indices().Species == 0 && u.Features().UninomialDict == dict.WhiteGenus) { u.SetDecision(token.Uninomial) return true } if u.Indices().Species == 0 || u.Features().UninomialDict == dict.BlackUninomial { return false } if ok := checkAsGenusSpecies(ts, d); !ok { return false } if u.Decision().In(token.Binomial, token.PossibleBinomial, token.BayesBinomial) { checkInfraspecies(ts, d) } return true } func checkAsSpecies(t token.TokenSN, d *dict.Dictionary) bool { if !t.Features().IsCapitalized && (t.Features().SpeciesDict == dict.WhiteSpecies || t.Features().SpeciesDict == dict.GreySpecies) { return true } return false } func checkAsGenusSpecies(ts []token.TokenSN, d *dict.Dictionary) bool { g := ts[0] s := ts[g.Indices().Species] if !checkAsSpecies(s, d) { if g.Features().UninomialDict == dict.WhiteGenus { g.SetDecision(token.Uninomial) return true } return false } if g.Features().UninomialDict == dict.WhiteGenus { g.SetDecision(token.Binomial) return true } if checkGreyGeneraSp(g, s, d) { g.SetDecision(token.Binomial) return true } if s.Features().SpeciesDict == dict.WhiteSpecies && !s.Features().IsCapitalized { g.SetDecision(token.PossibleBinomial) return true } return false } func checkGreyGeneraSp( g token.TokenSN, s token.TokenSN, d *dict.Dictionary, ) bool { sp := fmt.Sprintf("%s %s", g.Cleaned(), s.Cleaned()) if _, ok := d.GreyGeneraSp[sp]; ok { g.Features().GenSpGreyDict += 1 return true } return false } func checkGreyGeneraIsp( g, s, isp token.TokenSN, d *dict.Dictionary, ) bool { name := fmt.Sprintf("%s %s %s", g.Cleaned(), s.Cleaned(), isp.Cleaned()) if _, ok := d.GreyGeneraSp[name]; ok { g.Features().GenSpGreyDict += 1 return true } return false } func checkInfraspecies(ts []token.TokenSN, d *dict.Dictionary) { i := ts[0].Indices().Infraspecies if i == 0 { return } g := ts[0] s := ts[ts[0].Indices().Species] isp := ts[i] if checkGreyGeneraIsp(g, s, isp, d) || checkAsSpecies(ts[i], d) { ts[0].SetDecision(token.Trinomial) } }
ent/heuristic/heuristic.go
0.651355
0.453625
heuristic.go
starcoder
package source import ( "go/ast" "github.com/go-services/annotation" "github.com/allar/code" ) type Node interface { Exported() bool Code() code.Code String() string Name() string Begin() int End() int } type NodeWithInner interface { Node InnerBegin() int InnerEnd() int } // Import represents an import type Import struct { ast ast.Decl // code representation of import code code.Import // the package name of the import // e.x some/import/path does not guaranty the package name to be `path` we need // a way to get that package name when using import in types pkg string } type StructureField struct { exported bool // code representation of the struct field code code.StructField // annotations of the struct field annotations []annotation.Annotation // the beginning and end positions of the struct field definition // corresponds to the Pos() and End() of the ast declaration begin, end int } // Structure represents a parsed structure type Structure struct { exported bool ast ast.Decl // code representation of the struct code code.Struct // the structure fields fields []StructureField // annotations of the struct annotations []annotation.Annotation // the beginning and end positions of the struct definition // corresponds to the Pos() and End() of the ast declaration begin, end int // the beginning and end positions of the struct brackets // this is used to determine where to put structure fields innerBegin, innerEnd int } type InterfaceMethod struct { exported bool // code representation of the interface method code code.InterfaceMethod // annotations of the interface method annotations []annotation.Annotation // the beginning and end positions of the interface method definition // corresponds to the Pos() and End() of the ast declaration begin, end int } // Interface represents a parsed interface type Interface struct { exported bool ast ast.Decl // code representation of the interface code code.Interface // the interface methods methods []InterfaceMethod // annotations of the interface annotations []annotation.Annotation // the beginning and end positions of the interface definition // corresponds to the Pos() and End() of the ast declaration begin, end int // the beginning and end positions of the interface brackets // this is used to determine where to put interface methods innerBegin, innerEnd int } type Function struct { exported bool ast ast.Decl // code representation of the function code code.Function // annotations of the interface annotations []annotation.Annotation // the beginning and end positions of the function definition // corresponds to the Pos() and End() of the ast declaration begin, end int // the beginning and end positions of the function brackets // this is used to determine where to put function code innerBegin, innerEnd int // the beginning and end positions of the function parameters paramBegin, paramEnd int // the beginning and end positions of the function parameters resultBegin, resultEnd int } // file represents a parsed file. type file struct { pkg string src string ast *ast.File imports []Import structures map[string]Structure interfaces map[string]Interface functions map[string]Function } func newFile(pkg, src string, ast *ast.File) *file { return &file{ pkg: pkg, src: src, ast: ast, structures: map[string]Structure{}, interfaces: map[string]Interface{}, functions: map[string]Function{}, } } func (s Structure) Name() string { return s.code.Name } func (s Structure) Begin() int { return s.begin } func (s Structure) End() int { return s.end } func (s Structure) InnerBegin() int { return s.innerBegin } func (s Structure) InnerEnd() int { return s.innerEnd } func (s Structure) Code() code.Code { return &s.code } func (s Structure) Struct() *code.Struct { return &s.code } func (s Structure) String() string { return s.code.String() } func (s Structure) Fields() []StructureField { return s.fields } func (s Structure) Annotations() []annotation.Annotation { return s.annotations } func (s *Structure) Annotate(force bool) error { a, err := annotate(&s.code, force) s.annotations = append(s.annotations, a...) return err } func (s Structure) Exported() bool { return s.exported } func (i Interface) Name() string { return i.code.Name } func (i Interface) Begin() int { return i.begin } func (i Interface) End() int { return i.end } func (i Interface) InnerBegin() int { return i.innerBegin } func (i Interface) InnerEnd() int { return i.innerEnd } func (i Interface) Code() code.Code { return &i.code } func (i Interface) Interface() code.Interface { return i.code } func (i Interface) String() string { return i.code.String() } func (i Interface) Methods() []InterfaceMethod { return i.methods } func (i Interface) Annotations() []annotation.Annotation { return i.annotations } func (i *Interface) Annotate(force bool) error { a, err := annotate(&i.code, force) i.annotations = append(i.annotations, a...) return err } func (i Interface) Exported() bool { return i.exported } func (f Function) Name() string { return f.code.Name } func (f Function) Begin() int { return f.begin } func (f Function) End() int { return f.end } func (f Function) InnerBegin() int { return f.innerBegin } func (f Function) InnerEnd() int { return f.innerEnd } func (f Function) ParamBegin() int { return f.paramBegin } func (f Function) ParamEnd() int { return f.paramEnd } func (f Function) Code() code.Code { return &f.code } func (f Function) Func() code.Function { return f.code } func (f Function) String() string { return f.code.String() } func (f Function) Params() []code.Parameter { return f.code.Params } func (f Function) Results() []code.Parameter { return f.code.Results } func (f Function) Receiver() *code.Parameter { return f.code.Recv } func (f Function) Annotations() []annotation.Annotation { return f.annotations } func (f *Function) Annotate(force bool) error { a, err := annotate(&f.code, force) f.annotations = append(f.annotations, a...) return err } func (f Function) Exported() bool { return f.exported } func (f StructureField) Name() string { return f.code.Name } func (f StructureField) String() string { return f.code.String() } func (f StructureField) Code() code.Code { return &f.code } func (f StructureField) Field() code.StructField { return f.code } func (f StructureField) Tags() map[string]string { return *f.code.Tags } func (f StructureField) Begin() int { return f.begin } func (f StructureField) End() int { return f.end } func (f StructureField) Annotations() []annotation.Annotation { return f.annotations } func (f *StructureField) Annotate(force bool) error { a, err := annotate(&f.code, force) f.annotations = append(f.annotations, a...) return err } func (f StructureField) Exported() bool { return f.exported } func (f InterfaceMethod) Name() string { return f.code.Name } func (f InterfaceMethod) String() string { return f.code.String() } func (f InterfaceMethod) Code() code.Code { return &f.code } func (f InterfaceMethod) InterfaceMethod() code.InterfaceMethod { return f.code } func (f InterfaceMethod) Params() []code.Parameter { return f.code.Params } func (f InterfaceMethod) Results() []code.Parameter { return f.code.Results } func (f InterfaceMethod) Annotations() []annotation.Annotation { return f.annotations } func (f *InterfaceMethod) Annotate(force bool) error { a, err := annotate(&f.code, force) f.annotations = append(f.annotations, a...) return err } func (f InterfaceMethod) Begin() int { return f.begin } func (f InterfaceMethod) End() int { return f.end } func (f InterfaceMethod) Exported() bool { return f.exported }
file.go
0.710226
0.431285
file.go
starcoder
package typ import ( "xelf.org/xelf/knd" ) var ( Void = Type{Kind: knd.Void} None = Type{Kind: knd.None} Bool = Type{Kind: knd.Bool} Num = Type{Kind: knd.Num} Int = Type{Kind: knd.Int} Real = Type{Kind: knd.Real} Char = Type{Kind: knd.Char} Str = Type{Kind: knd.Str} Raw = Type{Kind: knd.Raw} UUID = Type{Kind: knd.UUID} Time = Type{Kind: knd.Time} Span = Type{Kind: knd.Span} Lit = Type{Kind: knd.Lit} Typ = Type{Kind: knd.Typ} Sym = Type{Kind: knd.Sym} Tag = Type{Kind: knd.Tag} Tupl = Type{Kind: knd.Tupl} Call = Type{Kind: knd.Call} Exp = Type{Kind: knd.Exp} Idxr = Type{Kind: knd.Idxr} Keyr = Type{Kind: knd.Keyr} List = Type{Kind: knd.List} Dict = Type{Kind: knd.Dict} Data = Type{Kind: knd.Data} Spec = Type{Kind: knd.Spec} Any = Type{Kind: knd.Any} ) func Opt(t Type) Type { t.Kind |= knd.None return t } func Deopt(t Type) Type { t.Kind &^= knd.None return t } func WithID(id int32, t Type) Type { t.ID = id return t } func Var(id int32, t Type) Type { t.Kind |= knd.Var t.ID = id return t } func Ref(name string) Type { return Type{knd.Ref, 0, &RefBody{Ref: name}} } func Sel(sel string) Type { return Type{knd.Sel, 0, &SelBody{Path: sel}} } func Rec(ps ...Param) Type { return Type{knd.Rec, 0, &ParamBody{Params: ps}} } func Obj(n string, ps []Param) Type { return Type{knd.Obj, 0, &ParamBody{Name: n, Params: ps}} } func elType(k knd.Kind, el Type) Type { if el == Void { return Type{Kind: k} } return Type{k, 0, &ElBody{El: el}} } func TypOf(t Type) Type { return elType(knd.Typ, t) } func LitOf(t Type) Type { return elType(knd.Lit, t) } func SymOf(t Type) Type { return elType(knd.Sym, t) } func TagOf(t Type) Type { return elType(knd.Tag, t) } func CallOf(t Type) Type { return elType(knd.Call, t) } func ListOf(t Type) Type { return elType(knd.List, t) } func DictOf(t Type) Type { return elType(knd.Dict, t) } func IdxrOf(t Type) Type { return elType(knd.Idxr, t) } func KeyrOf(t Type) Type { return elType(knd.Keyr, t) } func ElemTupl(t Type) Type { return Type{knd.Tupl, 0, &ElBody{El: t}} } func ParamTupl(ps ...Param) Type { return Type{knd.Tupl, 0, &ParamBody{Params: ps}} } func Func(name string, ps ...Param) Type { return Type{knd.Func, 0, &ParamBody{name, ps}} } func Form(name string, ps ...Param) Type { return Type{knd.Form, 0, &ParamBody{name, ps}} } func El(t Type) Type { if b, ok := t.Body.(*ElBody); ok && b.El.Kind != knd.Void { return b.El } return Void } func ResEl(t Type) Type { if t.Kind&(knd.Lit|knd.Exp) != 0 { if r := El(t); r != Void { return r } return Any } return t } func ContEl(t Type) Type { if t.Kind&knd.Cont != 0 { if r := El(t); r != Void { return r } return Any } return t } func TuplEl(t Type) (Type, int) { switch b := t.Body.(type) { case *ElBody: return b.El, 1 case *ParamBody: if n := len(b.Params); n > 0 { return t, n } } return Any, 0 } // Last returns the last element type if t is a list or dict type otherwise t is returned as is. func Last(t Type) Type { for { b, ok := t.Body.(*ElBody) if !ok { break } t = b.El if t == Void { return Any } } return t } func Name(t Type) string { if t.Kind&(knd.Schm|knd.Spec|knd.Ref) != 0 { switch b := t.Body.(type) { case *ParamBody: return b.Name case *ConstBody: return b.Name case *RefBody: return b.Ref } } return "" }
typ/decl.go
0.513912
0.546678
decl.go
starcoder
package profanity import ( "log" "regexp" "strings" ) /** RemoveWords: Function removes input words from the dictionary of bad words. Input : wordsToBeRemoved ([]string) the words to be removed Output : wordsToBeRemoved ([]string) words that re removed err (error) golang error object **/ func RemoveWords(wordsToBeRemoved []string) ([]string, error) { if wordsToBeRemoved != nil { for _, value := range wordsToBeRemoved { delete(profanityWords, strings.ToLower(value)) } return wordsToBeRemoved, nil } return wordsToBeRemoved, INPUT_NOT_FOUND } /** AddWords: Function adds given words to the dictionary of bad words. Input : words ([]string) the words to be added to the dictionary of bad words Output : words ([]string) words that have been successfully added to the dictionary err (error) golang error object **/ func AddWords(words []string) ([]string, error) { if words != nil { for _, value := range words { if word := wordExistsInDictionary(value); word { profanityWords[strings.ToLower(strings.TrimSpace(value))] = 1 } } return words, nil } return words, INPUT_NOT_FOUND } /** IsStringDirty: Function checks if the given string has a bad word or not. Input : words (string) the string to be checked Output : words (bool) boolean result **/ func IsStringDirty(message string) bool { messageList := strings.Fields(message) isDirty := false for _, value := range messageList { if _, exists := profanityWords[strings.ToLower(value)]; exists { isDirty = true break } } return isDirty } /** MaskProfanity: Function masks bad words present in the input string with masking char. Input : message (string) the string to be masked maskWith (string) the masking character. eg * Output : words (bool) boolean result **/ func MaskProfanity(message string, maskWith string, keepCharactersAroundMask int) string { result := message for _, value := range strings.Fields(message) { punctuationRegex := "[,:;]" cleanedValue := cleanPunctuations(value, punctuationRegex, "") if exists := wordExistsInDictionary(cleanedValue); exists { replacement := "" for i := 0; i < len(cleanedValue); i++ { if len(cleanedValue) > keepCharactersAroundMask * 2 && (i < keepCharactersAroundMask || len(cleanedValue) - i <= keepCharactersAroundMask) { replacement += string(cleanedValue[i]) } else { replacement += maskWith } } result = strings.Replace(result, cleanedValue, replacement, -1) } } return result } func MaskProfanityWithoutKeepingSpaceTypes(message string, maskWith string, keepCharactersAroundMask int) string { result := "" for w, value := range strings.Fields(message) { if w != 0 { result += " " } newWord := value punctuationRegex := "[,:;]" cleanedValue := cleanPunctuations(value, punctuationRegex, "") if exists := wordExistsInDictionary(cleanedValue); exists { replacement := "" for i := 0; i < len(cleanedValue); i++ { if len(cleanedValue) > keepCharactersAroundMask * 2 && (i < keepCharactersAroundMask || len(cleanedValue) - i <= keepCharactersAroundMask) { replacement += string(cleanedValue[i]) } else { replacement += maskWith } } newWord = strings.Replace(newWord, cleanedValue, replacement, -1) } result += newWord } return result } /** cleanPunctuations: Function removes punctuation for the given input string Input : word (string) the word to be checked Output : result (string) cleaned string **/ func cleanPunctuations(word string, punctuationRegex string, replacement string) string { reg, err := regexp.Compile(punctuationRegex) if err != nil { log.Fatal(err) } return reg.ReplaceAllString(word, replacement) } /** wordExistsInDictionary: Function checks if a given word is present in the dictionary of bad words. Input : word (string) the word to be checked Output : exists (boolean) boolean response **/ func wordExistsInDictionary(word string) bool { _, exists := profanityWords[strings.ToLower(word)] return exists }
profanity.go
0.569853
0.402656
profanity.go
starcoder
package raycaster import ( "francoisgergaud/3dGame/common/environment/world" innerMath "francoisgergaud/3dGame/common/math" "math" ) //RayCaster provides the function to cast a ray. type RayCaster interface { CastRay(origin *innerMath.Point2D, world world.WorldMap, angle float64, maxDistance float64) *innerMath.Point2D } //RayCasterImpl implements the RayCast interface. type RayCasterImpl struct { } //CastRay casts a ray from the origin, with a given angle, on the worldmap, until a wall is found, or the ray's length is greater than visibility. func (raycaster *RayCasterImpl) CastRay(origin *innerMath.Point2D, world world.WorldMap, angle float64, maxDistance float64) *innerMath.Point2D { //Digital Diferential Analyzer // get the point's coordinate of the ray and the first obstacle on the map. // on vertical-intersection with the grid: verticalIntersectStep.Y is how much is increased Y everytime verticalIntersectStep.X is incremented/decremented by 1 // on horizontal-intersection with the grid, horizontalIntersectStep.X is how much is increased X everytime horizontalIntersectStep.Y is incremented/decremented by 1 var verticalIntersectStep, horizontalIntersectStep innerMath.Point2D // calculate the ray's steps from its angle switch { case angle < 0.25: verticalIntersectStep.Y = math.Tan(angle * math.Pi) verticalIntersectStep.X = 1 horizontalIntersectStep.X = 1 / verticalIntersectStep.Y horizontalIntersectStep.Y = 1 case angle < 0.75: horizontalIntersectStep.X = math.Tan((0.5 - angle) * math.Pi) horizontalIntersectStep.Y = 1 if angle < 0.5 { verticalIntersectStep.X = 1 verticalIntersectStep.Y = 1 / horizontalIntersectStep.X } else { verticalIntersectStep.X = -1 verticalIntersectStep.Y = -1 / horizontalIntersectStep.X } case angle < 1.25: verticalIntersectStep.Y = math.Tan((1 - angle) * math.Pi) verticalIntersectStep.X = -1 if angle < 1 { horizontalIntersectStep.Y = 1 horizontalIntersectStep.X = -1 / verticalIntersectStep.Y } else { horizontalIntersectStep.Y = -1 horizontalIntersectStep.X = 1 / verticalIntersectStep.Y } case angle < 1.75: horizontalIntersectStep.X = math.Tan((angle - 1.5) * math.Pi) horizontalIntersectStep.Y = -1 if angle < 1.5 { verticalIntersectStep.X = -1 verticalIntersectStep.Y = 1 / horizontalIntersectStep.X } else { verticalIntersectStep.X = 1 verticalIntersectStep.Y = -1 / horizontalIntersectStep.X } case angle <= 2: verticalIntersectStep.Y = math.Tan(angle * math.Pi) verticalIntersectStep.X = 1 horizontalIntersectStep.X = -1 / verticalIntersectStep.Y horizontalIntersectStep.Y = -1 } //calculate the first horizontal an vertical intersections //TODO: double-check what happens when origin is negative var verticalIntersect, horizontalIntersect innerMath.Point2D verticalIntersect.X = float64(int(origin.X)) if verticalIntersectStep.X > 0 { verticalIntersect.X++ } verticalIntersect.Y = ((verticalIntersect.X - origin.X) * math.Tan(angle*math.Pi)) + origin.Y horizontalIntersect.Y = float64(int(origin.Y)) if verticalIntersectStep.Y > 0 { horizontalIntersect.Y++ } horizontalIntersect.X = ((horizontalIntersect.Y - origin.Y) / math.Tan(angle*math.Pi)) + origin.X var rayLength float64 var result *innerMath.Point2D for rayLength < maxDistance { verticalIntersectDistance := origin.Distance(&verticalIntersect) horizontalIntersectDistance := origin.Distance(&horizontalIntersect) if verticalIntersectDistance > horizontalIntersectDistance { if raycaster.checkHorizontalCollision(world, &horizontalIntersect, horizontalIntersectStep.Y) { result = &horizontalIntersect break } else { horizontalIntersect.X += horizontalIntersectStep.X horizontalIntersect.Y += horizontalIntersectStep.Y rayLength = horizontalIntersectDistance } } else { if raycaster.checkVerticalCollision(world, &verticalIntersect, verticalIntersectStep.X) { result = &verticalIntersect break } else { verticalIntersect.X += verticalIntersectStep.X verticalIntersect.Y += verticalIntersectStep.Y rayLength = verticalIntersectDistance } } } return result } //checkHorizontalCollision check if a point on a horizontal-line on the grid is hitting a wall given the ray's vertical-direction. func (*RayCasterImpl) checkHorizontalCollision(world world.WorldMap, horizontalIntersect *innerMath.Point2D, horizontalIntersectStepY float64) bool { result := false if horizontalIntersectStepY > 0 { if world.GetCellValue(int(horizontalIntersect.X), int(horizontalIntersect.Y)) == 1 { result = true } } else { if world.GetCellValue(int(horizontalIntersect.X), int(horizontalIntersect.Y)-1) == 1 { result = true } } return result } //checkVerticalCollision check if a point on a vertical-line on the grid is hitting a wall given the ray's horizontal-direction. func (*RayCasterImpl) checkVerticalCollision(world world.WorldMap, verticalIntersect *innerMath.Point2D, verticalIntersectStepX float64) bool { result := false if verticalIntersectStepX > 0 { if world.GetCellValue(int(verticalIntersect.X), int(verticalIntersect.Y)) == 1 { result = true } } else { if world.GetCellValue(int(verticalIntersect.X)-1, int(verticalIntersect.Y)) == 1 { result = true } } return result }
common/math/raycaster/raycaster.go
0.675229
0.65933
raycaster.go
starcoder
package parametric2d import ( "github.com/gmlewis/go-poly2tri" "github.com/gmlewis/go3d/float64/vec2" "github.com/gmlewis/go3d/float64/vec3" ) // T represents a parametric 2D segment. type T interface { // BBox returns the bounds of the segment. BBox() vec2.Rect // At interpolates along the segment and returns the 2D point. At(t float64) vec2.T // Tangent interpolates along the segment and returns the un-normalized tangent at that point. Tangent(t float64) vec2.T // NTangent interpolates along the segment and returns the normalized tangent at that point. NTangent(t float64) vec2.T // Normal interpolates along the segment and returns the un-normalized normal at that point. Normal(t float64) vec2.T // NNormal interpolates along the segment and returns the normalized normal at that point. NNormal(t float64) vec2.T // Wall returns a triangularized vertical extrusion of the 2D segment of the given height. // It subdivides the segment into as many vertical slices (making 2 triangles out of each slice) // such that the maximum angle between adjacent angles is 'maxDegrees'. // flipNormals determines if the normals are flipped from their default orientation. Wall(height, maxDegrees float64, flipNormals bool) ([]Triangle3D, poly2tri.PointArray) // Bevel returns a triangularized angled extrusion of the 2D segment starting at the given height. // It subdivides the segment in the same manner as Wall(). // 'offset' specifies the horizontal distance to offset the original segment. // 'deg' specifies the angle (in degrees, where 0 is horizontally flat) to place the bevel. // flipNormals determines if the normals are flipped from their default orientation. // prevNN is the previous segment's normalized normal at its t=1 endpoint. // nextNN is the next segment's normalized normal at its t=0 endpoint.. Bevel(height, offset, deg, maxDegrees float64, flipNormals bool, prevNN, nextNN *vec2.T) ([]Triangle3D, poly2tri.PointArray) // IsLine returns true if this segment is a simple line segment IsLine() bool } // Triangle3D represents a 3D triangle. type Triangle3D []vec3.T // TriangleWriter writes a triangle to some output. type TriangleWriter interface { WriteTriangle3D(t Triangle3D) error }
parametric2d.go
0.780955
0.641984
parametric2d.go
starcoder
package tinymt32 const ( mat1 = 0x8f7011ee mat2 = 0xfc78ff1f tmat = 0x3793fdff ) // A Source represents a source of uniformly-distributed pseudo-random uint32 values in the range [0, 1<<32). type Source struct { status [4]uint32 mat1 uint32 mat2 uint32 tmat uint32 } // NewSource returns a new pseudo-random Source seeded with the given value. This source is not safe for concurrent use by multiple goroutines. func NewSource(seed uint32) *Source { const minLoop = 8 const preLoop = 8 r := &Source{ status: [...]uint32{seed, mat1, mat2, tmat}, mat1: mat1, mat2: mat2, tmat: tmat, } for i := uint32(1); i < minLoop; i++ { r.status[i&3] ^= i + 1812433253*(r.status[(i-1)&3]^(r.status[(i-1)&3]>>30)) } /* * NB: The parameter set of this specification warrants * that none of the possible 2^^32 seeds leads to an * all-zero 127-bit internal state. Therefore, the * period_certification() function of the original * TinyMT32 source code has been safely removed. If * another parameter set is used, this function will * have to be reintroduced here. */ for i := 0; i < preLoop; i++ { r.nextState() } return r } // Uint32 returns a non-negative pseudo-random 32-bit integer as an uint32. func (r *Source) Uint32() uint32 { r.nextState() return r.temper() } // Internal tinymt32 constants. const ( sh0 = 1 sh1 = 10 sh8 = 8 mask = 0x7fffffff ) func (r *Source) nextState() { y := r.status[3] x := (r.status[0] & mask) ^ r.status[1] ^ r.status[2] x ^= (x << sh0) y ^= (y >> sh0) ^ x r.status[0] = r.status[1] r.status[1] = r.status[2] r.status[2] = x ^ (y << sh1) r.status[3] = y /* * The if (y & 1) {...} block below replaces: * r.status[1] ^= -((int32_t)(y & 1)) & r.mat1; * r.status[2] ^= -((int32_t)(y & 1)) & r.mat2; * The adopted code is equivalent to the original code * but does not depend on the representation of negative * integers by 2's complements. It is therefore more * portable but includes an if branch, which may slow * down the generation speed. */ if y&1 != 0 { r.status[1] ^= r.mat1 r.status[2] ^= r.mat2 } } func (r *Source) temper() uint32 { t0 := r.status[3] t1 := r.status[0] + (r.status[2] >> sh8) t0 ^= t1 /* * The if (t1 & 1) {...} block below replaces: * t0 ^= -((int32_t)(t1 & 1)) & r.tmat; * The adopted code is equivalent to the original code * but does not depend on the representation of negative * integers by 2's complements. It is therefore more * portable but includes an if branch, which may slow * down the generation speed. */ if t1&1 != 0 { t0 ^= r.tmat } return t0 }
tinymt32.go
0.625209
0.518729
tinymt32.go
starcoder
package gbq import "cloud.google.com/go/bigquery" // GetViolationsSchema defines violations table schema func GetViolationsSchema() bigquery.Schema { return bigquery.Schema{ { Name: "nonCompliance", Type: bigquery.RecordFieldType, Description: "The violation information, aka why it is not compliant", Schema: bigquery.Schema{ {Name: "message", Required: true, Type: bigquery.StringFieldType}, {Name: "metadata", Required: false, Type: bigquery.StringFieldType}, }, }, { Name: "functionConfig", Type: bigquery.RecordFieldType, Description: "The settings of the cloud function hosting the rule check", Schema: bigquery.Schema{ {Name: "functionName", Required: true, Type: bigquery.StringFieldType}, {Name: "deploymentTime", Required: true, Type: bigquery.TimestampFieldType}, {Name: "projectID", Required: false, Type: bigquery.StringFieldType}, {Name: "environment", Required: false, Type: bigquery.StringFieldType}, }, }, { Name: "constraintConfig", Type: bigquery.RecordFieldType, Description: "The settings of the constraint used in conjonction with the rego template to assess the rule", Schema: bigquery.Schema{ {Name: "kind", Required: false, Type: bigquery.StringFieldType}, { Name: "metadata", Type: bigquery.RecordFieldType, Schema: bigquery.Schema{ {Name: "name", Required: false, Type: bigquery.StringFieldType}, {Name: "annotation", Required: false, Type: bigquery.StringFieldType}, }, }, { Name: "spec", Type: bigquery.RecordFieldType, Schema: bigquery.Schema{ {Name: "severity", Required: false, Type: bigquery.StringFieldType}, {Name: "match", Required: false, Type: bigquery.StringFieldType}, {Name: "parameters", Required: false, Type: bigquery.StringFieldType}, }, }, }, }, { Name: "feedMessage", Type: bigquery.RecordFieldType, Description: "The message from Cloud Asset Inventory in realtime or from split dump in batch", Schema: bigquery.Schema{ { Name: "asset", Type: bigquery.RecordFieldType, Schema: bigquery.Schema{ {Name: "name", Required: true, Type: bigquery.StringFieldType}, {Name: "owner", Required: false, Type: bigquery.StringFieldType}, {Name: "violationResolver", Required: false, Type: bigquery.StringFieldType}, {Name: "ancestryPathDisplayName", Required: false, Type: bigquery.StringFieldType}, {Name: "ancestryPath", Required: false, Type: bigquery.StringFieldType}, {Name: "ancestorsDisplayName", Required: false, Type: bigquery.StringFieldType}, {Name: "ancestors", Required: false, Type: bigquery.StringFieldType}, {Name: "assetType", Required: true, Type: bigquery.StringFieldType}, {Name: "iamPolicy", Required: false, Type: bigquery.StringFieldType}, {Name: "resource", Required: false, Type: bigquery.StringFieldType}, }, }, { Name: "window", Type: bigquery.RecordFieldType, Schema: bigquery.Schema{ {Name: "startTime", Required: true, Type: bigquery.TimestampFieldType}, }, }, {Name: "origin", Required: false, Type: bigquery.StringFieldType}, }, }, {Name: "regoModules", Required: false, Type: bigquery.StringFieldType, Description: "The rego code, including the rule template used to assess the rule as a JSON document"}, } }
utilities/gbq/func_getviolationsschema.go
0.509276
0.509642
func_getviolationsschema.go
starcoder
package money import ( "database/sql/driver" "errors" "fmt" "regexp" "strings" "github.com/FoxComm/money/currency" "github.com/shopspring/decimal" ) var parseRegex = regexp.MustCompile(`[+-]?[0-9]*[.]?[0-9]*`) // Money represents an amount of a specific currency as an immutable value type Money struct { amount decimal.Decimal currency currency.Currency } // ErrDifferentCurrency is used for functions which take another money/currency // whereby the Money's currency != other currency type ErrDifferentCurrency struct { Actual currency.Currency Expected currency.Currency } func (e *ErrDifferentCurrency) Error() string { return fmt.Sprintf("expected currency %s got %s", e.Expected.Code, e.Actual.Code) } // Make is the Federal Reserve func Make(amount decimal.Decimal, c currency.Currency) Money { return Money{amount, c} } // MakeFromString is the Federal Reserve func MakeFromString(amount string, c currency.Currency) (Money, error) { d, err := decimal.NewFromString(amount) if err != nil { return Zero(c), err } return Money{d, c}, nil } // Zero returns Money with a zero amount func Zero(c currency.Currency) Money { return Make(decimal.New(0, 0), c) } // Parse parses a money.String() into Money func Parse(str string) (money Money, err error) { var c currency.Currency var ok bool if len(str) < 4 { err = fmt.Errorf("'%s' cannot be parsed", str) return } parsed := parseRegex.FindStringSubmatch(str[4:]) if len(parsed) == 0 { err = fmt.Errorf("'%s' cannot be parsed", str) return } if c, ok = currency.Table[str[0:3]]; !ok { err = fmt.Errorf("could not find currency %s", str[0:3]) return } amountStr := strings.Replace(parsed[0], string(c.Delimiter), "", 0) if amount, err := decimal.NewFromString(amountStr); err != nil { return money, err } else { return Make(amount, c), nil } } // Amount is the monetary value in its major unit func (m Money) Amount() decimal.Decimal { return m.amount } // Amount is the monetary value in its minor unit func (m Money) AmountMinor() decimal.Decimal { return decimal.Decimal{} } // String represents the amount in a currency context. e.g., for US: "USD 10.00" func (m Money) String() string { amt := m.Amount().String() if !strings.Contains(amt, string(m.currency.Decimal)) { amt += fmt.Sprintf("%s00", string(m.currency.Decimal)) } return fmt.Sprintf("%s %s", m.currency.Code, amt) } // Equals is true if other Money is the same amount and currency func (m Money) Equals(other Money) bool { return m.currency.Equals(other.currency) && m.Amount().Equals(other.Amount()) } // Currency returns the set Currency func (m Money) Currency() currency.Currency { return m.currency } // WithCurrency transforms this Money to a different Currency func (m Money) WithCurrency(c currency.Currency) Money { return Make(m.amount, c) } func (m Money) panicIfDifferentCurrency(c currency.Currency) { if !m.currency.Equals(c) { panic(fmt.Errorf("expected currency %s, got %s", m.currency.Code, c.Code)) } } // Math, aka, here be dragons // Cmp comparies monies. errors if currency is different. func (m Money) Cmp(other Money) (int, error) { if !m.currency.Equals(other.currency) { return 0, &ErrDifferentCurrency{m.currency, other.currency} } return m.amount.Cmp(other.amount), nil } // Abs returns |amount| func (m Money) Abs() decimal.Decimal { return m.amount.Abs() } // Negate negates the sign of the amount func (m Money) Negate() Money { d := decimal.New(-1, 0) return Make(m.amount.Mul(d), m.currency) } // IsPositive returns true if the amount i > 0 func (m Money) IsPositive() bool { zero := decimal.New(0, 0) return m.amount.Cmp(zero) == 1 } // IsPositive returns true if the amount i > 0 func (m Money) IsNegative() bool { zero := decimal.New(0, 0) return m.amount.Cmp(zero) == -1 } // IsZero returns true if the amount i == 0 func (m Money) IsZero() bool { return m.amount.Equals(decimal.New(0, 0)) } // Add adds monies. errors if currency is different. func (m Money) Add(other Money) (Money, error) { if !m.currency.Equals(other.currency) { return Zero(m.currency), &ErrDifferentCurrency{m.currency, other.currency} } return Make(m.amount.Add(other.amount), m.currency), nil } // Sub subtracts monies. errors if currency is different. func (m Money) Sub(other Money) (Money, error) { if !m.currency.Equals(other.currency) { return Zero(m.currency), &ErrDifferentCurrency{m.currency, other.currency} } return Make(m.amount.Sub(other.amount), m.currency), nil } // Div divides monies. errors if currency is different. func (m Money) Div(other Money) (Money, error) { if !m.currency.Equals(other.currency) { return Zero(m.currency), &ErrDifferentCurrency{m.currency, other.currency} } return Make(m.amount.Div(other.amount), m.currency), nil } // Mul multiplies monies. errors if currency is different. func (m Money) Mul(other Money) (Money, error) { if !m.currency.Equals(other.currency) { return Zero(m.currency), &ErrDifferentCurrency{m.currency, other.currency} } return Make(m.amount.Mul(other.amount), m.currency), nil } // UnmarshalJSON implements the json.Unmarshaler interface. func (m *Money) UnmarshalJSON(data []byte) (err error) { *m, err = Parse(strings.Trim(string(data), `"`)) return } // MarshalJSON implements the json.Marshaler interface. func (m Money) MarshalJSON() ([]byte, error) { return []byte(`"` + m.String() + `"`), nil } // Scan implements the sql.Scanner interface for database deserialization. func (m *Money) Scan(value interface{}) (err error) { asBytes, ok := value.([]byte) if !ok { return errors.New("scan value was not []byte") } *m, err = Parse(string(asBytes)) return err } // Value implements the driver.Valuer interface for database serialization. func (m Money) Value() (driver.Value, error) { return m.String(), nil } // UnmarshalText implements the encoding.TextUnmarshaler interface for XML // deserialization. func (m *Money) UnmarshalText(text []byte) (err error) { *m, err = Parse(string(text)) return } // MarshalText implements the encoding.TextMarshaler interface for XML // serialization. func (m Money) MarshalText() ([]byte, error) { return []byte(m.String()), nil }
money.go
0.80038
0.428233
money.go
starcoder
package comp // Search a type that combines the capabilities of a mock and an interface // that is almost fully compatible with gorm. type Search struct { // Mock fields definition Foundation // Gorm fields definition Unscoped bool } // Where implementation of gorm interface. func (r *Search) Where(query interface{}, values ...interface{}) (o *Search) { return r.HandlerOther(r, "Where", o, query, values).(*Search) } // Not implementation of gorm interface. func (r *Search) Not(query interface{}, values ...interface{}) (o *Search) { return r.HandlerOther(r, "Not", o, query, values).(*Search) } // Or implementation of gorm interface. func (r *Search) Or(query interface{}, values ...interface{}) (o *Search) { return r.HandlerOther(r, "Or", o, query, values).(*Search) } // Attrs implementation of gorm interface. func (r *Search) Attrs(attrs ...interface{}) (o *Search) { return r.HandlerOther(r, "Attrs", o, attrs).(*Search) } // Assign implementation of gorm interface. func (r *Search) Assign(attrs ...interface{}) (o *Search) { return r.HandlerOther(r, "Assign", o, attrs).(*Search) } // Order implementation of gorm interface. func (r *Search) Order(value interface{}, reorder ...bool) (o *Search) { return r.HandlerOther(r, "Order", o, value, reorder).(*Search) } // Select implementation of gorm interface. func (r *Search) Select(query interface{}, args ...interface{}) (o *Search) { return r.HandlerOther(r, "Select", o, query, args).(*Search) } // Omit implementation of gorm interface. func (r *Search) Omit(columns ...string) (o *Search) { return r.HandlerOther(r, "Omit", o, columns).(*Search) } // Limit implementation of gorm interface. func (r *Search) Limit(limit interface{}) (o *Search) { return r.HandlerOther(r, "Limit", o, limit).(*Search) } // Offset implementation of gorm interface. func (r *Search) Offset(offset interface{}) (o *Search) { return r.HandlerOther(r, "Offset", o, offset).(*Search) } // Group implementation of gorm interface. func (r *Search) Group(query string) (o *Search) { return r.HandlerOther(r, "Group", o, query).(*Search) } // Having implementation of gorm interface. func (r *Search) Having(query interface{}, values ...interface{}) (o *Search) { return r.HandlerOther(r, "Having", o, query, values).(*Search) } // Joins implementation of gorm interface. func (r *Search) Joins(query string, values ...interface{}) (o *Search) { return r.HandlerOther(r, "Joins", o, query, values).(*Search) } // Preload implementation of gorm interface. func (r *Search) Preload(schema string, values ...interface{}) (o *Search) { return r.HandlerOther(r, "Preload", o, schema, values).(*Search) } // Raw implementation of gorm interface. func (r *Search) Raw(b bool) (o *Search) { return r.HandlerOther(r, "Raw", o, b).(*Search) } // Table implementation of gorm interface. func (r *Search) Table(name string) (o *Search) { return r.HandlerOther(r, "Table", o, name).(*Search) }
comp/search.go
0.813201
0.434941
search.go
starcoder
// Package tensorflow provides implementation of Go API for extract data to vector package tensorflow import ( tf "github.com/tensorflow/tensorflow/tensorflow/go" "github.com/vdaas/vald/internal/errors" "github.com/vdaas/vald/internal/io" ) // SessionOptions is a type alias for tensorflow.SessionOptions. type SessionOptions = tf.SessionOptions // Operation is a type alias for tensorflow.Operation. type Operation = tf.Operation // Closer is a type alias io.Closer. type Closer = io.Closer // TF represents a tensorflow interface. type TF interface { GetVector(inputs ...string) ([]float64, error) GetValue(inputs ...string) (interface{}, error) GetValues(inputs ...string) (values []interface{}, err error) Closer } type session interface { Run(feeds map[tf.Output]*tf.Tensor, fetches []tf.Output, operations []*Operation) ([]*tf.Tensor, error) Closer } type tensorflow struct { exportDir string tags []string loadFunc func(exportDir string, tags []string, options *SessionOptions) (*tf.SavedModel, error) feeds []OutputSpec fetches []OutputSpec operations []*Operation options *SessionOptions graph *tf.Graph session session warmupInputs []string ndim uint8 } // OutputSpec is the specification of an feed/fetch. type OutputSpec struct { operationName string outputIndex int } const ( twoDim uint8 = iota + 2 threeDim ) // New load a tensorlfow model and returns a new tensorflow struct. func New(opts ...Option) (TF, error) { t := new(tensorflow) for _, opt := range append(defaultOptions, opts...) { opt(t) } model, err := t.loadFunc(t.exportDir, t.tags, t.options) if err != nil { return nil, err } t.graph = model.Graph t.session = model.Session err = t.warmup() if err != nil { return nil, err } return t, nil } func (t *tensorflow) warmup() error { if t.warmupInputs != nil { _, err := t.run(t.warmupInputs...) if err != nil { return err } } return nil } func (t *tensorflow) Close() error { return t.session.Close() } func (t *tensorflow) run(inputs ...string) ([]*tf.Tensor, error) { if len(inputs) != len(t.feeds) { return nil, errors.ErrInputLength(len(inputs), len(t.feeds)) } feeds := make(map[tf.Output]*tf.Tensor, len(inputs)) for i, val := range inputs { inputTensor, err := tf.NewTensor(val) if err != nil { return nil, err } feeds[t.graph.Operation(t.feeds[i].operationName).Output(t.feeds[i].outputIndex)] = inputTensor } fetches := make([]tf.Output, 0, len(t.fetches)) for _, fetch := range t.fetches { fetches = append(fetches, t.graph.Operation(fetch.operationName).Output(fetch.outputIndex)) } return t.session.Run(feeds, fetches, t.operations) } func (t *tensorflow) GetVector(inputs ...string) ([]float64, error) { tensors, err := t.run(inputs...) if err != nil { return nil, err } if len(tensors) == 0 || tensors[0] == nil || tensors[0].Value() == nil { return nil, errors.ErrNilTensorTF(tensors) } switch t.ndim { case twoDim: value, ok := tensors[0].Value().([][]float64) if ok { if value == nil { return nil, errors.ErrNilTensorValueTF(value) } return value[0], nil } return nil, errors.ErrFailedToCastTF(tensors[0].Value()) case threeDim: value, ok := tensors[0].Value().([][][]float64) if ok { if len(value) == 0 || value[0] == nil { return nil, errors.ErrNilTensorValueTF(value) } return value[0][0], nil } return nil, errors.ErrFailedToCastTF(tensors[0].Value()) default: value, ok := tensors[0].Value().([]float64) if ok { return value, nil } return nil, errors.ErrFailedToCastTF(tensors[0].Value()) } } func (t *tensorflow) GetValue(inputs ...string) (interface{}, error) { tensors, err := t.run(inputs...) if err != nil { return nil, err } if len(tensors) == 0 || tensors[0] == nil { return nil, errors.ErrNilTensorTF(tensors) } return tensors[0].Value(), nil } func (t *tensorflow) GetValues(inputs ...string) (values []interface{}, err error) { tensors, err := t.run(inputs...) if err != nil { return nil, err } values = make([]interface{}, 0, len(tensors)) for _, tensor := range tensors { values = append(values, tensor.Value()) } return values, nil }
internal/core/converter/tensorflow/tensorflow.go
0.774498
0.478773
tensorflow.go
starcoder
package ubigraph type VertexID int type VertexStyleID int // NewVertex creates a vertex on the graph. // It returns an Ubigraph server selected vertex ID on success. func (g *Graph) NewVertex() (VertexID, error) { method := "ubigraph.new_vertex" status, err := g.serverCall(method, nil) if err != nil { return 0, err } return VertexID(status), nil } // RemoveVertex deletes the vertex with the identifier matching the argument. func (g *Graph) RemoveVertex(id VertexID) error { method := "ubigraph.remove_vertex" status, err := g.serverCall(method, &struct{ Arg1 int }{int(id)}) if err != nil { return err } if status != 0 { return ubigraphError(method, status) } return nil } // NewVertexWithID creates a vertex on the graph with a chosen identifier. func (g *Graph) NewVertexWithID(id VertexID) error { method := "ubigraph.new_vertex_w_id" status, err := g.serverCall(method, &struct{ Arg1 int }{int(id)}) if err != nil { return err } if status != 0 { return ubigraphError(method, status) } return nil } // NewVertexStyle creates a vertex style based on an existing style. // It returns an Ubigraph server selected style ID on success. func (g *Graph) NewVertexStyle(parentStyle VertexStyleID) (VertexStyleID, error) { method := "ubigraph.new_vertex_style" status, err := g.serverCall(method, &struct{ Arg1 int }{int(parentStyle)}) if err != nil { return 0, err } return VertexStyleID(status), nil } // NewVertexStyleWithID creates a vertex style with a chosen identifier based on an existing style. func (g *Graph) NewVertexStyleWithID(id, parentStyle VertexStyleID) error { method := "ubigraph.new_vertex_style_w_id" status, err := g.serverCall(method, &struct{ Arg1, Arg2 int }{int(id), int(parentStyle)}) if err != nil { return err } if status != 0 { return ubigraphError(method, status) } return nil } // ChangeVertexStyle changes the identified vertex's style. func (g *Graph) ChangeVertexStyle(vertex VertexID, style VertexStyleID) error { method := "ubigraph.change_vertex_style" status, err := g.serverCall(method, &struct{ Arg1, Arg2 int }{int(vertex), int(style)}) if err != nil { return err } if status != 0 { return ubigraphError(method, status) } return nil } // SetVertexAttribute modifies the attributes of the identified vertex. func (g *Graph) SetVertexAttribute(id VertexID, attribute, value string) error { method := "ubigraph.set_vertex_attribute" status, err := g.serverCall(method, &struct { Arg1 int Arg2, Arg3 string }{int(id), attribute, value}) if err != nil { return err } if status != 0 { return ubigraphError(method, status) } return nil } // SetVertexStyleAttribute modifies the attributes of the identified vertex style. func (g *Graph) SetVertexStyleAttribute(id VertexStyleID, attribute, value string) error { method := "ubigraph.set_vertex_style_attribute" status, err := g.serverCall(method, &struct { Arg1 int Arg2, Arg3 string }{int(id), attribute, value}) if err != nil { return err } if status != 0 { return ubigraphError(method, status) } return nil }
ubigraph/vertices.go
0.818592
0.422505
vertices.go
starcoder
package hopfield import ( "fmt" "image" "image/draw" "math/rand" "gonum.org/v1/gonum/mat" ) // Pattern is a data pattern type Pattern struct { // v is a vector which stores binary data v *mat.VecDense } // String implements Stringer interface func (p *Pattern) String() string { fa := mat.Formatted(p.v, mat.Prefix(""), mat.Squeeze()) return fmt.Sprintf("%v", fa) } // Vec returns internal data vector func (p *Pattern) Vec() *mat.VecDense { return p.v } // RawData returns pattern raw data func (p *Pattern) RawData() []float64 { return p.v.RawVector().Data } // At returns valir of patttern on position i func (p *Pattern) At(i int) float64 { return p.v.RawVector().Data[i] } // Set sets value on position i func (p *Pattern) Set(i int, val float64) error { if i > p.v.Len() { return fmt.Errorf("invalid index: %d", i) } // we transform vals to +1/-1 if val <= 0.0 { p.v.RawVector().Data[i] = -1.0 } else { p.v.RawVector().Data[i] = 1.0 } return nil } // Len returns the length of the pattern func (p *Pattern) Len() int { if p.v == nil { return 0 } return p.v.Len() } // Encode encodes data to a pattern of values: +1/-1. Non-positive data items are set to -1, positive ones are set to +1 // Encode modifies the data slice in place and returns pointer to Pattern. func Encode(data []float64) *Pattern { for i := 0; i < len(data); i++ { if data[i] <= 0.0 { data[i] = -1.0 } else { data[i] = 1.0 } } v := mat.NewVecDense(len(data), data) return &Pattern{ v: v, } } // AddNoise adds random noise to pattern p and returns it. Noise is added by flipping the sign of existing pattern value. // It allows to specify the percentage of noise via pcnt parameter. AddNoise modifies the pattern p in place. func AddNoise(p *Pattern, pcnt int) *Pattern { n, _ := p.v.Dims() for i := 0; i < n; i++ { if i > (pcnt*n)/100 { break } j := rand.Intn(n) p.v.SetVec(j, -p.v.At(j, 0)) } return p } // Image2Pattern transforms img raw data into binary encoded pattern that can be used in Hopfield Network // It first turns the image into a Grey scaled image and then encodes its pixels into binary values of -1/+1 func Image2Pattern(img image.Image) *Pattern { // convert image to Gray scaled image imGray := image.NewGray(image.Rect(0, 0, img.Bounds().Dx(), img.Bounds().Dy())) draw.Draw(imGray, imGray.Bounds(), img, img.Bounds().Min, draw.Src) // convert pixels into floats pattern := make([]float64, len(imGray.Pix)) for i := range imGray.Pix { pattern[i] = float64(imGray.Pix[i]) } return Encode(pattern) } // Pattern2Image turns pattern p to a *lossy* Gray scaled image. // Data to pixel transformation is lossy: non-positive elements are transformed to 0, otherwise 255 func Pattern2Image(p *Pattern, r image.Rectangle) image.Image { // pix is a slice that contains pixels pix := make([]byte, len(p.v.RawVector().Data)) for i := range pix { if p.v.At(i, 0) <= 0.0 { pix[i] = 0 } else { pix[i] = 255 } } // create new Gray image from data img := image.NewGray(r) copy(img.Pix, pix) return img }
hopfield/pattern.go
0.855066
0.503235
pattern.go
starcoder
package challenge import ( "math" "sort" ) // KeyLength is the assumed length of a key. const KeyLength = 16 // EqualKeys returns true if the given []byte are equal. func EqualKeys(firstKey, secondKey []byte) bool { if len(firstKey) != len(secondKey) { return false } for i, byt := range firstKey { if byt != secondKey[i] { return false } } return true } // NextKey takes key []byte which is a key of length KeyLength and // returns the next key by incrementing the 0th byte and making any // necessary carries. The maximum key is [255, 255, ..., 255], and if // NextKey is called on this, then it returns [0, 0, ..., 0] and // false. func NextKey(key []byte) ([]byte, bool) { if len(key) != KeyLength { return key, false } for i := 0; i < KeyLength; i++ { if key[i] < MaxByte { key[i]++ return key, true } key[i] = 0 } return key, false } // FrequencySignature takes a map[byte]float64 containing a map of // bytes to their relative frequencies in a text represented as // float64 where 0 means the charcter doesn't occur, and 1 means that // every character in the text is this character, and returns a list // of frequencies in descending order which can be used to match // against character frequencies in a specific language to tell if the // original text was written in that language. func FrequencySignature(charFreq map[byte]float64) []float64 { sig := []float64{} for _, freq := range charFreq { sig = append(sig, freq) } // sort into descending order sort.Sort(sort.Reverse(sort.Float64Slice(sig))) return sig } // CompareFrequencySignatures returns the difference between two // frequency signatures. func CompareFrequencySignatures(freq1, freq2 []float64) float64 { if len(freq1) > len(freq2) { freq1, freq2 = freq2, freq1 } var diff float64 // can assume freq2 is longer for i, freq := range freq1 { diff += math.Abs(freq - freq2[i]) } for i := len(freq1); i < len(freq2); i++ { diff += freq2[i] } return diff } // ComputeCharacterFrequencies takes an input []byte and returns // map[byte]float64 which represents the relative frequencies of each // byte in the input []byte as a float64 where 0 represents the // character doesn't occur at all, and 1 represents that every // character in the text is this character. func ComputeCharacterFrequencies(input []byte) map[byte]float64 { freq := make(map[byte]float64) for _, byt := range input { freq[byt] += 1 / float64(len(input)) } return freq } // CrackAES128ECB takes []byte which is English text encrypted using // AES-128 in EBC mode, and returns a score of how likely the text is // to be English, the most probable key, and the most probable // plaintext. func CrackAES128ECB(input []byte) (float64, []byte, string, error) { var ( bestScore float64 = math.Inf(-1) bestKey []byte bestPlaintext string key = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} valid = true ) for valid { plaintext, err := DecryptAes128Ecb(input, key) if err != nil { return bestScore, bestKey, bestPlaintext, err } score := Score(plaintext) if score > bestScore { bestScore = score bestKey = key bestPlaintext = string(plaintext) } key, valid = NextKey(key) } return bestScore, bestKey, bestPlaintext, nil }
set/1/challenge/8.go
0.853989
0.432063
8.go
starcoder
package ipaddr const ( upperAdjustment = 8 // These are for the flags. // A standard string is a string showing only the lower value of a segment, in lowercase. // A standard range string shows both values, low to high, with the standard separator. keyWildcard uint32 = 0x10000 keySingleWildcard uint32 = 0x20000 keyStandardStr uint32 = 0x40000 keyStandardRangeStr uint32 = 0x80000 keyRangeWildcard uint32 = 0x100000 keyInferredLowerBoundary uint32 = 0x200000 keyInferredUpperBoundary uint32 = 0x400000 keyMergedMixed uint32 = 0x800000 keyRadix uint32 = 0x00ff keyBitSize uint32 = 0xff00 bitSizeShift = 8 // the flags, radix and bit size are stored in the same int, the radix takes the low byte, // the bit size the next byte, the remaining 16 bits are available for flags. keyLowerRadixIndex = 0 keyBitSizeIndex = keyLowerRadixIndex flagsIndex = keyLowerRadixIndex keyUpperRadixIndex = keyLowerRadixIndex + upperAdjustment // these are for the segment values - they must be even-numbered keyLower = 2 keyExtendedLower = 4 keyUpper = keyLower + upperAdjustment keyExtendedUpper = keyExtendedLower + upperAdjustment // these are for the indices keyLowerStrDigitsIndex = 1 keyLowerStrStartIndex = 6 keyLowerStrEndIndex = 7 keyUpperStrDigitsIndex = keyLowerStrDigitsIndex + upperAdjustment keyUpperStrStartIndex = keyLowerStrStartIndex + upperAdjustment keyUpperStrEndIndex = keyLowerStrEndIndex + upperAdjustment segmentDataSize = 16 segmentIndexShift = 4 ipv4SegmentDataSize = segmentDataSize * 4 ipv6SegmentDataSize = segmentDataSize * 8 ) type addressParseData struct { segmentData []uint32 segmentCount int anyWildcard, isEmpty, isAllVal, isSingleSegmentVal bool // these are indices into the original string used while parsing consecutiveSepIndex, consecutiveSepSegmentIndex, addressEndIndex int str string } func (parseData *addressParseData) init(str string) { parseData.consecutiveSepIndex = -1 parseData.consecutiveSepSegmentIndex = -1 parseData.str = str } func (parseData *addressParseData) getString() string { return parseData.str } func (parseData *addressParseData) initSegmentData(segmentCapacity int) { dataSize := 0 if segmentCapacity == 4 { dataSize = ipv4SegmentDataSize } else if segmentCapacity == 8 { dataSize = ipv6SegmentDataSize } else if segmentCapacity == 1 { dataSize = segmentDataSize // segmentDataSize * segmentCapacity } else { dataSize = segmentCapacity * segmentDataSize } parseData.segmentData = make([]uint32, dataSize) } func (parseData *addressParseData) getSegmentData() []uint32 { return parseData.segmentData } func (parseData *addressParseData) incrementSegmentCount() { parseData.segmentCount++ } func (parseData *addressParseData) getSegmentCount() int { return parseData.segmentCount } func (parseData *addressParseData) getConsecutiveSeparatorSegmentIndex() int { return parseData.consecutiveSepSegmentIndex } func (parseData *addressParseData) setConsecutiveSeparatorSegmentIndex(val int) { parseData.consecutiveSepSegmentIndex = val } func (parseData *addressParseData) getConsecutiveSeparatorIndex() int { return parseData.consecutiveSepIndex } func (parseData *addressParseData) setConsecutiveSeparatorIndex(val int) { parseData.consecutiveSepIndex = val } func (parseData *addressParseData) isProvidingEmpty() bool { return parseData.isEmpty } func (parseData *addressParseData) setEmpty(val bool) { parseData.isEmpty = val } func (parseData *addressParseData) isAll() bool { return parseData.isAllVal } func (parseData *addressParseData) setAll() { parseData.isAllVal = true } func (parseData *addressParseData) getAddressEndIndex() int { return parseData.addressEndIndex } func (parseData *addressParseData) setAddressEndIndex(val int) { parseData.addressEndIndex = val } func (parseData *addressParseData) isSingleSegment() bool { return parseData.isSingleSegmentVal } func (parseData *addressParseData) setSingleSegment() { parseData.isSingleSegmentVal = true } func (parseData *addressParseData) hasWildcard() bool { return parseData.anyWildcard } func (parseData *addressParseData) setHasWildcard() { parseData.anyWildcard = true } func (parseData *addressParseData) unsetFlag(segmentIndex int, flagIndicator uint32) { index := (segmentIndex << segmentIndexShift) | flagsIndex segmentData := parseData.getSegmentData() segmentData[index] &= uint32(0xffff) ^ flagIndicator // segmentData[index] &= ~flagIndicator } func (parseData *addressParseData) getFlag(segmentIndex int, flagIndicator uint32) bool { segmentData := parseData.getSegmentData() return (segmentData[(segmentIndex<<segmentIndexShift)|flagsIndex] & flagIndicator) != 0 } func (parseData *addressParseData) hasEitherFlag(segmentIndex int, flagIndicator1, flagIndicator2 uint32) bool { return parseData.getFlag(segmentIndex, flagIndicator1|flagIndicator2) } func (parseData *addressParseData) getRadix(segmentIndex, indexIndicator int) uint32 { segmentData := parseData.getSegmentData() radix := segmentData[(segmentIndex<<segmentIndexShift)|indexIndicator] & keyRadix if radix == 0 { return IPv6DefaultTextualRadix // 16 is the default, we only set the radix if not 16 } return radix } func (parseData *addressParseData) getBitLength(segmentIndex int) BitCount { segmentData := parseData.getSegmentData() bitLength := (segmentData[(segmentIndex<<segmentIndexShift)|keyBitSizeIndex] & keyBitSize) >> bitSizeShift return BitCount(bitLength) } func (parseData *addressParseData) setBitLength(segmentIndex int, length BitCount) { segmentData := parseData.getSegmentData() segmentData[(segmentIndex<<segmentIndexShift)|keyBitSizeIndex] |= (uint32(length) << bitSizeShift) & keyBitSize } func (parseData *addressParseData) setIndex(segmentIndex, indexIndicator0 int, value0 uint32, indexIndicator1 int, value1 uint32, indexIndicator2 int, value2 uint32, indexIndicator3 int, value3 uint32, indexIndicator4 int, value4 uint32, indexIndicator5 int, value5 uint32) { baseIndex := segmentIndex << segmentIndexShift segmentData := parseData.getSegmentData() segmentData[baseIndex|indexIndicator0] = value0 segmentData[baseIndex|indexIndicator1] = value1 segmentData[baseIndex|indexIndicator2] = value2 segmentData[baseIndex|indexIndicator3] = value3 segmentData[baseIndex|indexIndicator4] = value4 segmentData[baseIndex|indexIndicator5] = value5 } func (parseData *addressParseData) getIndex(segmentIndex, indexIndicator int) int { return getIndexFromData(segmentIndex, indexIndicator, parseData.getSegmentData()) } func getIndexFromData(segmentIndex, indexIndicator int, segmentData []uint32) int { return int(segmentData[(segmentIndex<<segmentIndexShift)|indexIndicator]) } func (parseData *addressParseData) set7IndexFlags(segmentIndex, indexIndicator0 int, value0 uint32, indexIndicator1 int, value1 uint32, indexIndicator2 int, value2 uint32, indexIndicator3 int, value3 uint32, indexIndicator4 int, value4 uint32, indexIndicator5 int, value5 uint32, indexIndicator6 int, value6 uint32) { baseIndex := segmentIndex << segmentIndexShift segmentData := parseData.getSegmentData() segmentData[baseIndex|indexIndicator0] = value0 segmentData[baseIndex|indexIndicator1] = value1 segmentData[baseIndex|indexIndicator2] = value2 segmentData[baseIndex|indexIndicator3] = value3 segmentData[baseIndex|indexIndicator4] = value4 segmentData[baseIndex|indexIndicator5] = value5 segmentData[baseIndex|indexIndicator6] = value6 } func (parseData *addressParseData) set8IndexFlags(segmentIndex, indexIndicator0 int, value0 uint32, indexIndicator1 int, value1 uint32, indexIndicator2 int, value2 uint32, indexIndicator3 int, value3 uint32, indexIndicator4 int, value4 uint32, indexIndicator5 int, value5 uint32, indexIndicator6 int, value6 uint32, indexIndicator7 int, value7 uint32) { baseIndex := segmentIndex << segmentIndexShift segmentData := parseData.getSegmentData() segmentData[baseIndex|indexIndicator0] = value0 segmentData[baseIndex|indexIndicator1] = value1 segmentData[baseIndex|indexIndicator2] = value2 segmentData[baseIndex|indexIndicator3] = value3 segmentData[baseIndex|indexIndicator4] = value4 segmentData[baseIndex|indexIndicator5] = value5 segmentData[baseIndex|indexIndicator6] = value6 segmentData[baseIndex|indexIndicator7] = value7 } func (parseData *addressParseData) set8Index4ValuesFlags(segmentIndex, indexIndicator0 int, value0 uint32, indexIndicator1 int, value1 uint32, indexIndicator2 int, value2 uint32, indexIndicator3 int, value3 uint32, indexIndicator4 int, value4 uint32, indexIndicator5 int, value5 uint32, indexIndicator6 int, value6 uint32, indexIndicator7 int, value7 uint32, indexIndicator8 int, value8 uint64, indexIndicator9 int, value9 uint64, indexIndicator10 int, value10 uint64, indexIndicator11 int, value11 uint64) { baseIndex := segmentIndex << segmentIndexShift segmentData := parseData.getSegmentData() setIndexValuesFlags(baseIndex, segmentData, indexIndicator0, value0, indexIndicator1, value1, indexIndicator2, value2, indexIndicator3, value3, indexIndicator4, value4, indexIndicator5, value5, indexIndicator6, value6, indexIndicator8, value8, indexIndicator9, value9) segmentData[baseIndex|indexIndicator7] = value7 index := baseIndex | indexIndicator10 segmentData[index] = uint32(value10 >> 32) segmentData[index|1] = uint32(value10 & 0xffffffff) index = baseIndex | indexIndicator11 segmentData[index] = uint32(value11 >> 32) segmentData[index|1] = uint32(value11 & 0xffffffff) } func (parseData *addressParseData) set7Index4ValuesFlags(segmentIndex, indexIndicator0 int, value0 uint32, indexIndicator1 int, value1 uint32, indexIndicator2 int, value2 uint32, indexIndicator3 int, value3 uint32, indexIndicator4 int, value4 uint32, indexIndicator5 int, value5 uint32, indexIndicator6 int, value6 uint32, indexIndicator7 int, value7 uint64, indexIndicator8 int, value8 uint64, indexIndicator9 int, value9 uint64, indexIndicator10 int, value10 uint64) { baseIndex := segmentIndex << segmentIndexShift segmentData := parseData.getSegmentData() setIndexValuesFlags(baseIndex, segmentData, indexIndicator0, value0, indexIndicator1, value1, indexIndicator2, value2, indexIndicator3, value3, indexIndicator4, value4, indexIndicator5, value5, indexIndicator6, value6, indexIndicator7, value7, indexIndicator8, value8) index := baseIndex | indexIndicator9 segmentData[index] = uint32(value9 >> 32) segmentData[index|1] = uint32(value9 & 0xffffffff) index = baseIndex | indexIndicator10 segmentData[index] = uint32(value10 >> 32) segmentData[index|1] = uint32(value10 & 0xffffffff) } func (parseData *addressParseData) set8Index2ValuesFlags(segmentIndex, indexIndicator0 int, value0 uint32, indexIndicator1 int, value1 uint32, indexIndicator2 int, value2 uint32, indexIndicator3 int, value3 uint32, indexIndicator4 int, value4 uint32, indexIndicator5 int, value5 uint32, indexIndicator6 int, value6 uint32, indexIndicator7 int, value7 uint32, indexIndicator8 int, value8 uint64, indexIndicator9 int, value9 uint64) { baseIndex := segmentIndex << segmentIndexShift segmentData := parseData.getSegmentData() setIndexValuesFlags(baseIndex, segmentData, indexIndicator0, value0, indexIndicator1, value1, indexIndicator2, value2, indexIndicator3, value3, indexIndicator4, value4, indexIndicator5, value5, indexIndicator6, value6, indexIndicator8, value8, indexIndicator9, value9) segmentData[baseIndex|indexIndicator7] = value7 } func (parseData *addressParseData) set7Index2ValuesFlags(segmentIndex, indexIndicator0 int, value0 uint32, indexIndicator1 int, value1 uint32, indexIndicator2 int, value2 uint32, indexIndicator3 int, value3 uint32, indexIndicator4 int, value4 uint32, indexIndicator5 int, value5 uint32, indexIndicator6 int, value6 uint32, indexIndicator7 int, value7 uint64, indexIndicator8 int, value8 uint64) { baseIndex := segmentIndex << segmentIndexShift segmentData := parseData.getSegmentData() setIndexValuesFlags(baseIndex, segmentData, indexIndicator0, value0, indexIndicator1, value1, indexIndicator2, value2, indexIndicator3, value3, indexIndicator4, value4, indexIndicator5, value5, indexIndicator6, value6, indexIndicator7, value7, indexIndicator8, value8) } func setIndexValuesFlags( baseIndex int, segmentData []uint32, indexIndicator0 int, value0 uint32, indexIndicator1 int, value1 uint32, indexIndicator2 int, value2 uint32, indexIndicator3 int, value3 uint32, indexIndicator4 int, value4 uint32, indexIndicator5 int, value5 uint32, indexIndicator6 int, value6 uint32, indexIndicator7 int, value7 uint64, indexIndicator8 int, value8 uint64) { segmentData[baseIndex|indexIndicator0] = value0 segmentData[baseIndex|indexIndicator1] = value1 segmentData[baseIndex|indexIndicator2] = value2 segmentData[baseIndex|indexIndicator3] = value3 segmentData[baseIndex|indexIndicator4] = value4 segmentData[baseIndex|indexIndicator5] = value5 segmentData[baseIndex|indexIndicator6] = value6 index := baseIndex | indexIndicator7 segmentData[index] = uint32(value7 >> 32) segmentData[index|1] = uint32(value7 & 0xffffffff) index = baseIndex | indexIndicator8 segmentData[index] = uint32(value8 >> 32) segmentData[index|1] = uint32(value8 & 0xffffffff) } func (parseData *addressParseData) setValue(segmentIndex, indexIndicator int, value uint64) { index := (segmentIndex << segmentIndexShift) | indexIndicator upperValue := uint32(value >> 32) lowerValue := uint32(value & 0xffffffff) segmentData := parseData.getSegmentData() segmentData[index] = upperValue segmentData[index|1] = lowerValue } func (parseData *addressParseData) getValue(segmentIndex, indexIndicator int) uint64 { return getValueFromData(segmentIndex, indexIndicator, parseData.getSegmentData()) } func getValueFromData(segmentIndex, indexIndicator int, segmentData []uint32) uint64 { index := (segmentIndex << segmentIndexShift) | indexIndicator upperValue := uint64(segmentData[index]) lowerValue := 0xffffffff & uint64(segmentData[index|1]) value := (upperValue << 32) | lowerValue return value } func (parseData *addressParseData) isMergedMixed(segmentIndex int) bool { return parseData.getFlag(segmentIndex, keyMergedMixed) } func (parseData *addressParseData) isWildcard(segmentIndex int) bool { return parseData.getFlag(segmentIndex, keyWildcard) } func (parseData *addressParseData) hasRange(segmentIndex int) bool { return parseData.hasEitherFlag(segmentIndex, keySingleWildcard, keyRangeWildcard) } func (parseData *addressParseData) isInferredUpperBoundary(segmentIndex int) bool { return parseData.getFlag(segmentIndex, keyInferredUpperBoundary) } type ipAddressParseData struct { addressParseData qualifier parsedHostIdentifierStringQualifier qualifierIndex int hasPrefixSeparatorVal, isZonedVal bool ipVersion IPVersion is_inet_aton_joined_val bool has_inet_aton_value_val bool // either octal 01 or hex 0x1 hasIPv4LeadingZerosVal, isBinaryVal bool isBase85, isBase85ZonedVal bool mixedParsedAddress *parsedIPAddress } func (parseData *ipAddressParseData) init(str string) { parseData.qualifierIndex = -1 parseData.addressParseData.init(str) } func (parseData *ipAddressParseData) getAddressParseData() *addressParseData { return &parseData.addressParseData } func (parseData *ipAddressParseData) getProviderIPVersion() IPVersion { return parseData.ipVersion } func (parseData *ipAddressParseData) setVersion(version IPVersion) { parseData.ipVersion = version } func (parseData *ipAddressParseData) isProvidingIPv6() bool { version := parseData.getProviderIPVersion() return version.IsIPv6() } func (parseData *ipAddressParseData) isProvidingIPv4() bool { version := parseData.getProviderIPVersion() return version.IsIPv4() } func (parseData *ipAddressParseData) is_inet_aton_joined() bool { return parseData.is_inet_aton_joined_val } func (parseData *ipAddressParseData) set_inet_aton_joined(val bool) { parseData.is_inet_aton_joined_val = val } func (parseData *ipAddressParseData) has_inet_aton_value() bool { return parseData.has_inet_aton_value_val } func (parseData *ipAddressParseData) set_has_inet_aton_value(val bool) { parseData.has_inet_aton_value_val = val } func (parseData *ipAddressParseData) hasIPv4LeadingZeros() bool { return parseData.hasIPv4LeadingZerosVal } func (parseData *ipAddressParseData) setHasIPv4LeadingZeros(val bool) { parseData.hasIPv4LeadingZerosVal = val } func (parseData *ipAddressParseData) hasBinaryDigits() bool { return parseData.isBinaryVal } func (parseData *ipAddressParseData) setHasBinaryDigits(val bool) { parseData.isBinaryVal = val } func (parseData *ipAddressParseData) getQualifier() *parsedHostIdentifierStringQualifier { return &parseData.qualifier } func (parseData *ipAddressParseData) getQualifierIndex() int { return parseData.qualifierIndex } func (parseData *ipAddressParseData) clearQualifier() { parseData.qualifierIndex = -1 parseData.isZonedVal = false parseData.isBase85ZonedVal = false parseData.hasPrefixSeparatorVal = false parseData.qualifier = parsedHostIdentifierStringQualifier{} } func (parseData *ipAddressParseData) setQualifierIndex(index int) { parseData.qualifierIndex = index } func (parseData *ipAddressParseData) isZoned() bool { return parseData.isZonedVal } func (parseData *ipAddressParseData) setZoned(val bool) { parseData.isZonedVal = val } func (parseData *ipAddressParseData) hasPrefixSeparator() bool { return parseData.hasPrefixSeparatorVal } func (parseData *ipAddressParseData) setHasPrefixSeparator(val bool) { parseData.hasPrefixSeparatorVal = val } func (parseData *ipAddressParseData) isProvidingBase85IPv6() bool { return parseData.isBase85 } func (parseData *ipAddressParseData) setBase85(val bool) { parseData.isBase85 = val } func (parseData *ipAddressParseData) isBase85Zoned() bool { return parseData.isBase85ZonedVal } func (parseData *ipAddressParseData) setBase85Zoned(val bool) { parseData.isBase85ZonedVal = val } func (parseData *ipAddressParseData) isCompressed() bool { return parseData.addressParseData.getConsecutiveSeparatorIndex() >= 0 } func (parseData *ipAddressParseData) segIsCompressed(index int, segmentData []uint32) bool { end := getIndexFromData(index, keyUpperStrEndIndex, segmentData) start := getIndexFromData(index, keyLowerStrStartIndex, segmentData) return start == end } func (parseData *ipAddressParseData) segmentIsCompressed(index int) bool { return parseData.segIsCompressed(index, parseData.addressParseData.getSegmentData()) } func (parseData *ipAddressParseData) isProvidingMixedIPv6() bool { return parseData.mixedParsedAddress != nil } func (parseData *ipAddressParseData) setMixedParsedAddress(val *parsedIPAddress) { parseData.mixedParsedAddress = val } type macFormat *byte const ( dash = '-' colon = ':' space = ' ' dot = '.' ) var ( dashedByte byte = dash colonByte byte = colon spaceByte byte = space dotByte byte = dot dashed macFormat = &dashedByte colonDelimited macFormat = &colonByte dotted macFormat = &dotByte spaceDelimited macFormat = &spaceByte unknownFormat macFormat ) type macAddressParseData struct { addressParseData isDoubleSegmentVal, isExtendedVal bool format macFormat } func (parseData *macAddressParseData) init(str string) { parseData.addressParseData.init(str) } func (parseData *macAddressParseData) getAddressParseData() *addressParseData { return &parseData.addressParseData } func (parseData *macAddressParseData) getFormat() macFormat { return parseData.format } func (parseData *macAddressParseData) setFormat(format macFormat) { parseData.format = format } func (parseData *macAddressParseData) isDoubleSegment() bool { return parseData.isExtendedVal } func (parseData *macAddressParseData) setDoubleSegment(val bool) { parseData.isExtendedVal = val } func (parseData *macAddressParseData) isExtended() bool { return parseData.isDoubleSegmentVal } func (parseData *macAddressParseData) setExtended(val bool) { parseData.isDoubleSegmentVal = val }
ipaddr/parsedata.go
0.652241
0.442094
parsedata.go
starcoder
package main import ( "math" "math/rand" "sync" "fmt" "time" ) // Pixels represents the array of pixels (in packed RGB value) to Render and/or save type Pixels []uint32 // Scene represents the scene to Render. // raysPerPixel is an array because the Render algorithm is split in multiple passes so that a result can be // available as soon as possible type Scene struct { width, height int raysPerPixel []int camera Camera world Hitable } // pixel is an internal type which represents the pixel to be processed // x,y are the coordinates // k is the index in the Pixels array // color is the color that has been computed by casting raysPerPixel through x/y coordinates (not normalized to avoid accumulating rounding errors) type pixel struct { x, y, k int color Color raysPerPixel int } // split is a util function which split an array into an array of array with count elements each (the last one may hold less...) func split(buf []*pixel, count int) [][]*pixel { var chunk []*pixel chunks := make([][]*pixel, 0, len(buf)/count+1) for len(buf) >= count { chunk, buf = buf[:count], buf[count:] chunks = append(chunks, chunk) } if len(buf) > 0 { chunks = append(chunks, buf) } return chunks } // render works on a single pixels, casting raysPerPixel through it and accumulating the color // returns the normalized and gamma corrected value so far (for immediate display) while // updating the pixel for further ray casting func (scene *Scene) render(rnd Rnd, pixel *pixel, raysPerPixel int) uint32 { c := pixel.color for s := 0; s < raysPerPixel; s++ { u := (float64(pixel.x) + rnd.Float64()) / float64(scene.width) v := (float64(pixel.y) + rnd.Float64()) / float64(scene.height) r := scene.camera.ray(rnd, u, v) c = c.Add(color(r, scene.world, 0)) } pixel.color = c pixel.raysPerPixel += raysPerPixel // normalize the color (average of all the rays cast so far) c = c.Scale(1.0 / float64(pixel.raysPerPixel)) // gamma correction c = Color{R: math.Sqrt(c.R), G: math.Sqrt(c.G), B: math.Sqrt(c.B)} return c.PixelValue() } // Render is the main method of a scene. It is non blocking and returns right away with the array of pixels // that will be computed asynchronously and a channel to indicate when the processing is complete. Note that // no synchronization is required on the array of pixels since it is an array of 32 bits values. // The image (width x height) will be split in lines each one processed in a separate goroutine (parallelCount // of them). The image will be progressively rendered using the passes defined in raysPerPixel func (scene *Scene) Render(parallelCount int) (Pixels, chan struct{}) { pixels := make([]uint32, scene.width*scene.height) completed := make(chan struct{}) go func() { allPixelsToProcess := make([]*pixel, scene.width*scene.height) // initializes the pixels to generate (start with black color) k := 0 for j := scene.height - 1; j >= 0; j-- { for i := 0; i < scene.width; i++ { allPixelsToProcess[k] = &pixel{x: i, y: j, k: k} k++ } } // split in lines lines := split(allPixelsToProcess, scene.width) // compute the total numbers of rays to cast (used for computing estimated remaining time) totalRaysPerPixel := 0 for _, rpp := range scene.raysPerPixel { totalRaysPerPixel += rpp } totalStart := time.Now() accumulatedRaysPerPixel := 0 // loop for each phase for _, rpp := range scene.raysPerPixel { loopStart := time.Now() // creates a channel which will be used to dispatch the line to process to each go routine pixelsToProcess := make(chan []*pixel) // asynchronously dispatch the lines to process go func() { for _, p := range lines { pixelsToProcess <- p } // done... signal the end close(pixelsToProcess) }() // create a wait group to wait until all goroutine completes wg := sync.WaitGroup{} // create parallelCount goroutines for c := 0; c < parallelCount; c++ { wg.Add(1) go func() { // due to high contention on global rand, each goroutine uses its own random number generator // thus avoiding massive slowdown rnd := rand.New(rand.NewSource(rand.Int63())) // process a bunch of pixels (in this case a line) for ps := range pixelsToProcess { // redisplay the line without gamma correction => make it darker to be more visible for _, p := range ps { if p.raysPerPixel > 0 { col := p.color.Scale(1.0 / float64(p.raysPerPixel)) pixels[p.k] = col.PixelValue() } } // render every pixel in the line for _, p := range ps { pixels[p.k] = scene.render(rnd, p, rpp) } } wg.Done() }() } // wait for the pass to be completed wg.Wait() // compute stats for the pass accumulatedRaysPerPixel += rpp loopEnd := time.Now() totalTimeSoFar := loopEnd.Sub(totalStart) estimatedTotalTime := time.Duration(float64(totalTimeSoFar) * float64(totalRaysPerPixel) / float64(accumulatedRaysPerPixel)) erm := estimatedTotalTime - totalTimeSoFar fmt.Printf("Processed %v rays per pixel in %v. Total %v in %v. ERM %v\n", rpp, time.Now().Sub(loopStart), accumulatedRaysPerPixel, totalTimeSoFar, erm) } // signal completion completed <- struct{}{} }() return pixels, completed } // color computes the color of the ray by checking which hitable gets hit and scattering // more rays (recursive) depending on material func color(r *Ray, world Hitable, depth int) Color { if hit, hr := world.hit(r, 0.001, math.MaxFloat64); hit { if depth >= 50 { return Black } if wasScattered, attenuation, scattered := hr.material.scatter(r, hr); wasScattered { return attenuation.Mult(color(scattered, world, depth+1)) } else { return Black } } unitDirection := r.Direction.Unit() t := 0.5 * (unitDirection.Y + 1.0) return White.Scale(1.0 - t).Add(Color{0.5, 0.7, 1.0}.Scale(t)) }
scene.go
0.767254
0.547404
scene.go
starcoder
package operators import ( bs "github.com/sharnoff/badstudent" "math" ) // **************************************** // Logistic // **************************************** type logistic int8 // Logistic returns an elementwise application of the logistic (or sigmoid) function that // implements badstudent.Operator. func Logistic() logistic { return logistic(0) } func (t logistic) TypeString() string { return "logistic" } func (t logistic) Finalize(n *bs.Node) error { // We don't need to check number of values because badstudent main does it for // us return nil } func (t logistic) Value(in float64, index int) float64 { // the logistic function can be rephrased as: return 0.5 + 0.5*math.Tanh(0.5*in) } func (t logistic) Deriv(n *bs.Node, index int) float64 { return n.Value(index) * (1 - n.Value(index)) } // **************************************** // Tanh // **************************************** type tanh int8 // Tanh returns an Operator that performs an element-wise application of the tanh() function. func Tanh() tanh { return tanh(0) } func (t tanh) TypeString() string { return "tanh" } func (t tanh) Finalize(n *bs.Node) error { return nil } func (t tanh) Value(in float64, index int) float64 { return math.Tanh(in) } func (t tanh) Deriv(n *bs.Node, index int) float64 { // it's cheaper to multiply it by itself than to use math.Pow() return 1 - (n.Value(index) * n.Value(index)) } // **************************************** // Softsign // **************************************** type softsign int8 // Softsign (not to be confused with softplus) returns the Softsign activation function. It is // similar in shape to Tanh and Logistic. func Softsign() softsign { return softsign(0) } func (t softsign) TypeString() string { return "softsign" } func (t softsign) Finalize(n *bs.Node) error { return nil } func (t softsign) Value(in float64, index int) float64 { return in / (math.Abs(in) + 1) } func (t softsign) Deriv(n *bs.Node, index int) float64 { // 1 / (|in| + 1)^2 return math.Pow(math.Abs(n.InputValue(index))+1, 2) }
operators/logistics.go
0.803444
0.407216
logistics.go
starcoder
package reducers import ( "github.com/paulmach/go.geo" ) type distanceFunc func(*geo.Point, *geo.Point) float64 // A RadialReducer wraps the Radial function // to fulfill the geo.Reducer and geo.GeoReducer interfaces. type RadialReducer struct { Threshold float64 // euclidean distance } // NewRadialReducer creates a new RadialReducer. func NewRadialReducer(threshold float64) *RadialReducer { return &RadialReducer{ Threshold: threshold, } } // Reduce runs the Radial reduction using the threshold of the RadialReducer. func (r RadialReducer) Reduce(path *geo.Path) *geo.Path { return Radial(path, r.Threshold) } // GeoReduce runs the RadialGeo reduction. The path should be in lng/lat (EPSG:4326). // The threshold is expected to be in meters. func (r RadialReducer) GeoReduce(path *geo.Path) *geo.Path { return RadialGeo(path, r.Threshold) } // A RadialGeoReducer wraps the RadialGeo function // to fulfill the geo.Reducer and geo.GeoReducer interfaces. type RadialGeoReducer struct { Threshold float64 // meters } // NewRadialGeoReducer creates a new RadialGeoReducer. // This reducer should be used with EPSG:4326 (lng/lat) paths. func NewRadialGeoReducer(meters float64) *RadialGeoReducer { return &RadialGeoReducer{ Threshold: meters, } } // Reduce runs the RadialGeo reduction using the threshold of the RadialGeoReducer. // The threshold is expected to be in meters. func (r RadialGeoReducer) Reduce(path *geo.Path) *geo.Path { return RadialGeo(path, r.Threshold) } // GeoReduce runs the RadialGeo reduction. The path should be in lng/lat (EPSG:4326). // The threshold is expected to be in meters. func (r RadialGeoReducer) GeoReduce(path *geo.Path) *geo.Path { return RadialGeo(path, r.Threshold) } // Radial peforms a radial distance polyline simplification using a standard euclidean distance. // Returns a new path and DOES NOT modify the original. func Radial(path *geo.Path, meters float64) *geo.Path { p, _ := radialCore(path, meters*meters, squaredDistance, false) return p } // RadialIndexMap is similar to Radial but returns an array that maps // each new path index to its original path index. // Returns a new path and DOES NOT modify the original. func RadialIndexMap(path *geo.Path, meters float64) (*geo.Path, []int) { return radialCore(path, meters*meters, squaredDistance, true) } // RadialGeo peforms a radial distance polyline simplification using the GeoDistance. // ie. the path points must be lng/lat points otherwise the behavior of this function is undefined. // Returns a new path and DOES NOT modify the original. func RadialGeo(path *geo.Path, meters float64) *geo.Path { p, _ := radialCore(path, meters, geoDistance, false) return p } // RadialGeoIndexMap is similar to RadialGeo but returns an array that maps // each new path index to its original path index. // Returns a new path and DOES NOT modify the original. func RadialGeoIndexMap(path *geo.Path, meters float64) (*geo.Path, []int) { return radialCore(path, meters, geoDistance, true) } func radialCore( path *geo.Path, meters float64, dist distanceFunc, needIndexMap bool, ) (*geo.Path, []int) { // initial sanity checks if path.Length() == 0 { return path.Clone(), []int{} } if path.Length() == 1 { return path.Clone(), []int{0} } if path.Length() == 2 { return path.Clone(), []int{0, 1} } var newPoints []geo.Point var indexMap []int points := path.Points() newPoints = append(newPoints, points[0]) if needIndexMap { indexMap = append(indexMap, 0) } // split it up this way because I think it's faster // TODO: test this assumption currentIndex := 0 if needIndexMap { for i := 1; i < len(points); i++ { if dist(&points[currentIndex], &points[i]) > meters { currentIndex = i indexMap = append(indexMap, currentIndex) newPoints = append(newPoints, points[i]) } } } else { for i := 1; i < len(points); i++ { if dist(&points[currentIndex], &points[i]) > meters { currentIndex = i newPoints = append(newPoints, points[i]) } } } if currentIndex != len(points)-1 { newPoints = append(newPoints, points[len(points)-1]) if needIndexMap { indexMap = append(indexMap, len(points)-1) } } p := &geo.Path{} return p.SetPoints(newPoints), indexMap } func squaredDistance(p1, p2 *geo.Point) float64 { return p1.SquaredDistanceFrom(p2) } func geoDistance(p1, p2 *geo.Point) float64 { return p1.GeoDistanceFrom(p2) }
lab138/vendor/github.com/paulmach/go.geo/reducers/radial.go
0.885272
0.580441
radial.go
starcoder
package main import ( "fmt" "net" "strconv" ) /** Usage Go's interfaces let you use duck typing like you would in a purely dynamic language like Python but still have the compiler catch obvious mistakes like passing an int where an object with a Read method was expected, or like calling the Read method with the wrong number of arguments. To use interfaces, first define the interface type (say, ReadCloser): */ type ReadCloser interface { Read(b []byte) (n int, err net.Error) Close() } // and then define your new function as taking a ReadCloser. For example, this function calls Read repeatedly to get all the data that was requested and then calls Close: func ReadAndClose(r ReadCloser, buf []byte) (n int, err net.Error) { for len(buf) > 0 && err == nil { var nr int nr, err = r.Read(buf) n += nr buf = buf[nr:] } r.Close() return } // The code that calls ReadAndClose can pass a value of any type as long as it has Read and Close methods with the right signatures. And, unlike in languages like Python, if you pass a value with the wrong type, you get an error at compile time, not run time. //Interfaces aren't restricted to static checking, though. You can check dynamically whether a particular interface value has an additional method. For example: type Stringer interface { String() string } func ToString(any interface{}) string { if v, ok := any.(Stringer); ok { return v.String() } switch v := any.(type) { case int: return strconv.Itoa(v) case float64: return strconv.FormatFloat(v, 'g', 5, 32) } return "???" } // The value any has static type interface{}, meaning no guarantee of any methods at all: it could contain any type. The “comma ok” assignment inside the if statement asks whether it is possible to convert any to an interface value of type Stringer, which has the method String. If so, the body of that statement calls the method to obtain a string to return. Otherwise, the switch picks off a few basic types before giving up. This is basically a stripped down version of what the fmt package does. (The if could be replaced by adding case Stringer: at the top of the switch, but I used a separate statement to draw attention to the check.) // As a simple example, let's consider a 64-bit integer type with a String method that prints the value in binary and a trivial Get method: type Binary uint64 func (i Binary) String() string { return strconv.FormatUint(i.Get(), 2) } func (i Binary) Get() uint64 { return uint64(i) } // A value of type Binary can be passed to ToString, which will format it using the String method, even though the program never says that Binary intends to implement Stringer. There's no need: the runtime can see that Binary has a String method, so it implements Stringer, even if the author of Binary has never heard of Stringer. // These examples show that even though all the implicit conversions are checked at compile time, explicit interface-to-interface conversions can inquire about method sets at run time. “Effective Go” has more details about and examples of how interface values can be used. func main() { b := Binary(200) s := Stringer(b) fmt.Println(s.String()) } // Interface Values // Languages with methods typically fall into one of two camps: prepare tables for all the method calls statically (as in C++ and Java), or do a method lookup at each call (as in Smalltalk and its many imitators, JavaScript and Python included) and add fancy caching to make that call efficient. Go sits halfway between the two: it has method tables but computes them at run time. I don't know whether Go is the first language to use this technique, but it's certainly not a common one. (I'd be interested to hear about earlier examples; leave a comment below.) // As a warmup, a value of type Binary is just a 64-bit integer made up of two 32-bit words (like in the last post, we'll assume a 32-bit machine; this time memory grows down instead of to the right): // Interface values are represented as a two-word pair giving a pointer to information about the type stored in the interface and a pointer to the associated data. Assigning b to an interface value of type Stringer sets both words of the interface value. // (The pointers contained in the interface value are gray to emphasize that they are implicit, not directly exposed to Go programs.) // The first word in the interface value points at what I call an interface table or itable (pronounced i-table; in the runtime sources, the C implementation name is Itab). The itable begins with some metadata about the types involved and then becomes a list of function pointers. Note that the itable corresponds to the interface type, not the dynamic type. In terms of our example, the itable for Stringer holding type Binary lists the methods used to satisfy Stringer, which is just String: Binary's other methods (Get) make no appearance in the itable. // The second word in the interface value points at the actual data, in this case a copy of b. The assignment var s Stringer = b makes a copy of b rather than point at b for the same reason that var c uint64 = b makes a copy: if b later changes, s and c are supposed to have the original value, not the new one. Values stored in interfaces might be arbitrarily large, but only one word is dedicated to holding the value in the interface structure, so the assignment allocates a chunk of memory on the heap and records the pointer in the one-word slot. (There's an obvious optimization when the value does fit in the slot; we'll get to that later.) // To check whether an interface value holds a particular type, as in the type switch above, the Go compiler generates code equivalent to the C expression s.tab->type to obtain the type pointer and check it against the desired type. If the types match, the value can be copied by by dereferencing s.data. // To call s.String(), the Go compiler generates code that does the equivalent of the C expression s.tab->fun[0](s.data): it calls the appropriate function pointer from the itable, passing the interface value's data word as the function's first (in this example, only) argument. You can see this code if you run 8g -S x.go (details at the bottom of this post). Note that the function in the itable is being passed the 32-bit pointer from the second word of the interface value, not the 64-bit value it points at. In general, the interface call site doesn't know the meaning of this word nor how much data it points at. Instead, the interface code arranges that the function pointers in the itable expect the 32-bit representation stored in the interface values. Thus the function pointer in this example is (*Binary).String not Binary.String. // The example we're considering is an interface with just one method. An interface with more methods would have more entries in the fun list at the bottom of the itable. // Computing the Itable // Now we know what the itables look like, but where do they come from? Go's dynamic type conversions mean that it isn't reasonable for the compiler or linker to precompute all possible itables: there are too many (interface type, concrete type) pairs, and most won't be needed. Instead, the compiler generates a type description structure for each concrete type like Binary or int or func(map[int]string). Among other metadata, the type description structure contains a list of the methods implemented by that type. Similarly, the compiler generates a (different) type description structure for each interface type like Stringer; it too contains a method list. The interface runtime computes the itable by looking for each method listed in the interface type's method table in the concrete type's method table. The runtime caches the itable after generating it, so that this correspondence need only be computed once. // In our simple example, the method table for Stringer has one method, while the table for Binary has two methods. In general there might be ni methods for the interface type and nt methods for the concrete type. The obvious search to find the mapping from interface methods to concrete methods would take O(ni × nt) time, but we can do better. By sorting the two method tables and walking them simultaneously, we can build the mapping in O(ni + nt) time instead. // Memory Optimizations // The space used by the implementation described above can be optimized in two complementary ways. // First, if the interface type involved is empty—it has no methods—then the itable serves no purpose except to hold the pointer to the original type. In this case, the itable can be dropped and the value can point at the type directly: // Whether an interface type has methods is a static property—either the type in the source code says interface{} or it says interace{ methods... }—so the compiler knows which representation is in use at each point in the program. // Second, if the value associated with the interface value can fit in a single machine word, there's no need to introduce the indirection or the heap allocation. If we define Binary32 to be like Binary but implemented as a uint32, it could be stored in an interface value by keeping the actual value in the second word: // Whether the actual value is being pointed at or inlined depends on the size of the type. The compiler arranges for the functions listed in the type's method table (which get copied into the itables) to do the right thing with the word that gets passed in. If the receiver type fits in a word, it is used directly; if not, it is dereferenced. The diagrams show this: in the Binary version far above, the method in the itable is (*Binary).String, while in the Binary32 example, the method in the itable is Binary32.String not (*Binary32).String. // Of course, empty interfaces holding word-sized (or smaller) values can take advantage of both optimizations: // Method Lookup Performance // Smalltalk and the many dynamic systems that have followed it perform a method lookup every time a method gets called. For speed, many implementations use a simple one-entry cache at each call site, often in the instruction stream itself. In a multithreaded program, these caches must be managed carefully, since multiple threads could be at the same call site simultaneously. Even once the races have been avoided, the caches would end up being a source of memory contention. // Because Go has the hint of static typing to go along with the dynamic method lookups, it can move the lookups back from the call sites to the point when the value is stored in the interface. For example, consider this code snippet: func init() { var any interface{} // initialized elsewhere s := any.(Stringer) // dynamic conversion for i := 0; i < 100; i++ { fmt.Println(s.String()) } } // In Go, the itable gets computed (or found in a cache) during the assignment on line 2; the dispatch for the s.String() call executed on line 4 is a couple of memory fetches and a single indirect call instruction. // In contrast, the implementation of this program in a dynamic language like Smalltalk (or JavaScript, or Python, or ...) would do the method lookup at line 4, which in a loop repeats needless work. The cache mentioned earlier makes this less expensive than it might be, but it's still more expensive than a single indirect call instruction. // Of course, this being a blog post, I don't have any numbers to back up this discussion, but it certainly seems like the lack of memory contention would be a big win in a heavily parallel program, as is being able to move the method lookup out of tight loops. Also, I'm talking about the general architecture, not the specifics o the implementation: the latter probably has a few constant factor optimizations still available. // More Information // The interface runtime support is in $GOROOT/src/pkg/runtime/iface.c. There's much more to say about interfaces (we haven't even seen an example of a pointer receiver yet) and the type descriptors (they power reflection in addition to the interface runtime) but those will have to wait for future posts. // Selected output of 8g -S x.go: //0045 (x.go:25) LEAL s+-24(SP),BX //0046 (x.go:25) MOVL 4(BX),BP //0047 (x.go:25) MOVL BP,(SP) //0048 (x.go:25) MOVL (BX),BX //0049 (x.go:25) MOVL 20(BX),BX //0050 (x.go:25) CALL ,BX // The LEAL loads the address of s into the register BX. (The notation n(SP) describes the word in memory at SP+n. 0(SP) can be shortened to (SP).) The next two MOVL instructions fetch the value from the second word in the interface and store it as the first function call argument, 0(SP). The final two MOVL instructions fetch the itable and then the function pointer from the itable, in preparation for calling that function.
01 | Go by Example/internal/20_Interfaces/ref/Go Data Structures: Interfaces /x.go
0.78842
0.51946
x.go
starcoder
package schema // Decl describes an interface for a declaration. type Decl interface { Pos() Pos validate(r errorReporter) } // Package holds the data of an mprot package declaration. type Package struct { pos Pos Name string } // Pos implements the Decl interface. func (p *Package) Pos() Pos { return p.pos } func (p *Package) validate(r errorReporter) { // do nothing } // Import holds information about an mprot import declaration. type Import struct { pos Pos Path string Name string } // Pos implements the Decl interface. func (i *Import) Pos() Pos { return i.pos } func (i *Import) validate(r errorReporter) { // do nothing } // Const holds the data of an mprot constant. type Const struct { pos Pos Doc []string Name string Type Type Value string } // Pos implements the Decl interface. func (c *Const) Pos() Pos { return c.pos } func (c *Const) validate(r errorReporter) { // The correct types are already handled by the parser. } // Enumerator holds the data of an enumerator value. type Enumerator struct { Name string Value int64 Tags Tags } // Enum holds the data of an mprot enumeration. type Enum struct { pos Pos Doc []string Name string Enumerators []Enumerator } // Pos implements the Decl interface. func (e *Enum) Pos() Pos { return e.pos } func (e *Enum) validate(r errorReporter) { enumerators := make(map[string]struct{}, len(e.Enumerators)) for _, en := range e.Enumerators { if _, has := enumerators[en.Name]; has { r.errorf("duplicate enumerator %s in enum %s", en.Name, e.Name) } enumerators[en.Name] = struct{}{} } } // Field holds the data of a struct field. type Field struct { Name string Type Type Ordinal int64 Tags Tags } // Struct holds the data of an mprot struct. type Struct struct { pos Pos Doc []string Name string Fields []Field } // Pos implements the Decl interface. func (s *Struct) Pos() Pos { return s.pos } func (s *Struct) validate(r errorReporter) { fields := make(map[string]struct{}, len(s.Fields)) ordinals := make(map[int64]struct{}, len(s.Fields)) for _, f := range s.Fields { if _, has := fields[f.Name]; has { r.errorf("duplicate field %s in struct %s", f.Name, s.Name) } else if _, has := ordinals[f.Ordinal]; has && f.Ordinal != 0 { r.errorf("duplicate ordinal %d for field %s in struct %s", f.Ordinal, f.Name, s.Name) } if isService(f.Type) { r.errorf("service field %s in struct %s", f.Name, s.Name) } fields[f.Name] = struct{}{} ordinals[f.Ordinal] = struct{}{} } } // Branch holds the data for a union branch. type Branch struct { Type Type Ordinal int64 Tags Tags } // Union holds the data of an mprot union. type Union struct { pos Pos Doc []string Name string Branches []Branch } // Pos implements the Decl interface. func (u *Union) Pos() Pos { return u.pos } func (u *Union) validate(r errorReporter) { if len(u.Branches) == 0 { r.errorf("union %s does not contain a branch", u.Name) return } branches := make(map[string]struct{}, len(u.Branches)) ordinals := make(map[int64]struct{}, len(u.Branches)) hasNumericBranch := false for _, b := range u.Branches { typeid := b.Type.typeid() switch typ := b.Type.(type) { case *Pointer: r.errorf("pointer branch %s in union %s", typ.Name(), u.Name) case *Int: if hasNumericBranch { r.errorf("duplicate numeric branch %s in union %s", typ.Name(), u.Name) } hasNumericBranch = true case *Float: if hasNumericBranch { r.errorf("duplicate numeric branch %s in union %s", typ.Name(), u.Name) } hasNumericBranch = true case *Raw: r.errorf("raw branch in union %s", u.Name) case *DefinedType: if _, has := branches[typeid]; has { r.errorf("duplicate branch %s in union %s", typeid, u.Name) } else { switch typ.Decl.(type) { case *Enum: if hasNumericBranch { r.errorf("duplicate numeric branch %s in union %s", typ.Name(), u.Name) } hasNumericBranch = true case *Union: r.errorf("union branch %s in union %s", typ.Name(), u.Name) continue case *Service: r.errorf("service branch %s in union %s", typ.Name(), u.Name) continue } } default: if _, has := branches[typeid]; has { r.errorf("duplicate branch %s in union %s (only one %s branch is allowed)", typ.Name(), u.Name, typeid) } } if _, has := ordinals[b.Ordinal]; has && b.Ordinal != 0 { r.errorf("duplicate ordinal %d for branch %s in union %s", b.Ordinal, b.Type.Name(), u.Name) } branches[typeid] = struct{}{} ordinals[b.Ordinal] = struct{}{} } } // Method holds the data for a service methods. type Method struct { Doc []string Name string Args []Type Return Type // nil for void Ordinal int64 Tags Tags } // Service holds the data of an mprot service. type Service struct { pos Pos Doc []string Name string Methods []Method } // Pos implements the Decl interface. func (s *Service) Pos() Pos { return s.pos } func (s *Service) validate(r errorReporter) { methods := make(map[string]struct{}, len(s.Methods)) for _, m := range s.Methods { if _, has := methods[m.Name]; has { r.errorf("duplicate method %s in service %s", m.Name, s.Name) } for _, arg := range m.Args { if isService(arg) { r.errorf("service argument in method %s of service %s", m.Name, s.Name) } } if isService(m.Return) { r.errorf("method %s of service %s returns service type", m.Name, s.Name) } methods[m.Name] = struct{}{} } } func isService(t Type) bool { if typ, ok := t.(*DefinedType); ok { _, isService := typ.Decl.(*Service) return isService } return false }
schema/decl.go
0.730194
0.425963
decl.go
starcoder
package geo import ( "fmt" "math" ) // Boundary represents a predefined geo-location polygon identified by two points. // As a rule, the boundary lower bound always has to be on bottom left, while the upper bound has to be on // the top right. // All the points with latlng values between these two points' latlng // are considered located inside this boundary polygon. type Boundary interface { // Lower returns the lower bound point. Lower() Point // Upper returns the upper bound point. Upper() Point } type boundary struct { lower Point upper Point } func (b *boundary) Lower() Point { if b == nil || b.lower == nil { return &point{0, 0} } return b.lower } func (b *boundary) Upper() Point { if b == nil || b.upper == nil { return &point{0, 0} } return b.upper } func (b *boundary) String() string { return fmt.Sprintf("[%v -> %v]", b.Lower(), b.Upper()) } // NewBoundary creates a new boundary instance with two specified geo-location points. // As a rule, the boundary lower bound always has to be on bottom left, while the upper bound has to be on // the top right. // If the values passed to the NewBoundary don't satisfy this rule, then the values are auto-normalized to keep // everything clean and in control. // This way we won't have an issue dealing with bounds above 180 or below -180 longitude. // Also we won't have an issue figuring out which direction (east or west) we're going to // calculate the boundary starting from the lower bound till we reach the upper bound. func NewBoundary(lower Point, upper Point) Boundary { // Normalizing the boundary. lowerLat := math.Min(lower.Latitude(), upper.Latitude()) upperLat := math.Max(lower.Latitude(), upper.Latitude()) var lowerLng float64 var upperLng float64 if math.Abs(lower.Latitude()) == NorthPoleLat || math.Abs(upper.Latitude()) == NorthPoleLat { lowerLng = 0 upperLng = 0 } else { lowerLng = lower.Longitude() upperLng = upper.Longitude() } chLower := make(chan Point, 1) chUpper := make(chan Point, 1) go func() { chLower <- NewPoint(lowerLat, lowerLng) }() go func() { chUpper <- NewPoint(upperLat, upperLng) }() return &boundary{lower: <-chLower, upper: <-chUpper} }
boundary.go
0.865892
0.50293
boundary.go
starcoder
package sqlparser // 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 Node) (w Visitor, err error) VisitEnd(node Node) error } // Walk traverses an AST 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 Node) error { return walk(v, node) } func walk(v Visitor, node Node) (err error) { // Visit the node itself if v, err = v.Visit(node); err != nil { return err } else if v == nil { return nil } // Visit node's children. switch n := node.(type) { case *Assignment: if err := walkIdentList(v, n.Columns); err != nil { return err } if err := walkExpr(v, n.Expr); err != nil { return err } case *SelectStatement: if err := walk(v, n.Columns); err != nil { return err } if n.FromItems != nil { if err := walk(v, n.FromItems); err != nil { return err } } if err := walkExpr(v, n.Condition); err != nil { return err } if err := walkExprs(v, n.GroupingElements); err != nil { return err } if err := walkExpr(v, n.HavingCondition); err != nil { return err } if n.Compound != nil { if err := walk(v, n.Compound); err != nil { return err } } for _, x := range n.OrderBy { if err := walk(v, x); err != nil { return err } } if err := walkExpr(v, n.Limit); err != nil { return err } if err := walkExpr(v, n.Offset); err != nil { return err } case *InsertStatement: if err := walk(v, n.TableName); err != nil { return err } if err := walkIdentList(v, n.ColumnNames); err != nil { return err } for _, x := range n.Expressions { if err := walk(v, x); err != nil { return err } } if n.Query != nil { if err := walk(v, n.Query); err != nil { return err } } if n.UpsertClause != nil { if err := walk(v, n.UpsertClause); err != nil { return err } } case *UpdateStatement: if n.TableName != nil { if err := walk(v, n.TableName); err != nil { return err } } for _, x := range n.Assignments { if err := walk(v, x); err != nil { return err } } if err := walkExpr(v, n.Condition); err != nil { return err } case *UpsertClause: if err := walkIndexedColumnList(v, n.Columns); err != nil { return err } if err := walkExpr(v, n.WhereExpr); err != nil { return err } for _, x := range n.Assignments { if err := walk(v, x); err != nil { return err } } if err := walkExpr(v, n.UpdateWhereExpr); err != nil { return err } case *DeleteStatement: if n.TableName != nil { if err := walk(v, n.TableName); err != nil { return err } } if err := walkExpr(v, n.Condition); err != nil { return err } case *ParenExpr: if err := walkExpr(v, n.X); err != nil { return err } case *UnaryExpr: if err := walkExpr(v, n.X); err != nil { return err } case *BinaryExpr: if err := walkExpr(v, n.X); err != nil { return err } if err := walkExpr(v, n.Y); err != nil { return err } case *CaseBlock: if err := walkExpr(v, n.Condition); err != nil { return err } if err := walkExpr(v, n.Body); err != nil { return err } case *CaseExpr: if err := walkExpr(v, n.Operand); err != nil { return err } for _, x := range n.Blocks { if err := walk(v, x); err != nil { return err } } if err := walkExpr(v, n.ElseExpr); err != nil { return err } case *Exprs: if err := walkExprs(v, n.Exprs); err != nil { return err } case *QualifiedRef: if err := walkIdent(v, n.Table); err != nil { return err } if err := walkIdent(v, n.Column); err != nil { return err } case *Call: if err := walkIdent(v, n.Name); err != nil { return err } if err := walkExprs(v, n.Args); err != nil { return err } if n.Filter != nil { if err := walk(v, n.Filter); err != nil { return err } } case *FilterClause: if err := walkExpr(v, n.X); err != nil { return err } case *OrderingTerm: if err := walkExpr(v, n.X); err != nil { return err } case *Range: if err := walkExpr(v, n.X); err != nil { return err } if err := walkExpr(v, n.Y); err != nil { return err } case *Exists: if n.Select != nil { if err := walk(v, n.Select); err != nil { return err } } case *ParenSource: if n.X != nil { if err := walk(v, n.X); err != nil { return err } } if err := walkIdent(v, n.Alias); err != nil { return err } case *TableName: if err := walkIdent(v, n.Name); err != nil { return err } if err := walkIdent(v, n.Alias); err != nil { return err } case *JoinClause: if n.X != nil { if err := walk(v, n.X); err != nil { return err } } if n.Operator != nil { if err := walk(v, n.Operator); err != nil { return err } } if n.Y != nil { if err := walk(v, n.Y); err != nil { return err } } if n.Constraint != nil { if err := walk(v, n.Constraint); err != nil { return err } } case *OnConstraint: if err := walkExpr(v, n.X); err != nil { return err } case *UsingConstraint: if err := walkIdentList(v, n.Columns); err != nil { return err } case *ResultColumn: if err := walkExpr(v, n.Expr); err != nil { return err } if err := walkIdent(v, n.Alias); err != nil { return err } case *IndexedColumn: if err := walkExpr(v, n.X); err != nil { return err } case *Type: if err := walkIdent(v, n.Name); err != nil { return err } if n.Precision != nil { if err := walk(v, n.Precision); err != nil { return err } } if n.Scale != nil { if err := walk(v, n.Scale); err != nil { return err } } } // Revisit original node after its children have been processed. return v.VisitEnd(node) } // VisitFunc represents a function type that implements Visitor. // Only executes on node entry. type VisitFunc func(Node) error // Visit executes fn. Walk visits node children if fn returns true. func (fn VisitFunc) Visit(node Node) (Visitor, error) { if err := fn(node); err != nil { return nil, err } return fn, nil } // VisitEnd is a no-op. func (fn VisitFunc) VisitEnd(node Node) error { return nil } // VisitEndFunc represents a function type that implements Visitor. // Only executes on node exit. type VisitEndFunc func(Node) error // Visit is a no-op. func (fn VisitEndFunc) Visit(node Node) (Visitor, error) { return fn, nil } // VisitEnd executes fn. func (fn VisitEndFunc) VisitEnd(node Node) error { return fn(node) } func walkIdent(v Visitor, x *Ident) error { if x != nil { if err := walk(v, x); err != nil { return err } } return nil } func walkIdentList(v Visitor, a []*Ident) error { for _, x := range a { if err := walk(v, x); err != nil { return err } } return nil } func walkExpr(v Visitor, x Expr) error { if x != nil { if err := walk(v, x); err != nil { return err } } return nil } func walkExprs(v Visitor, a []Expr) error { for _, x := range a { if err := walk(v, x); err != nil { return err } } return nil } func walkIndexedColumnList(v Visitor, a []*IndexedColumn) error { for _, x := range a { if err := walk(v, x); err != nil { return err } } return nil }
walk.go
0.699562
0.436142
walk.go
starcoder
package examples import ( "context" mock "github.com/stretchr/testify/mock" "testing" ) var _ ComplexTypes = (*MockComplexTypes)(nil) type MockComplexTypes struct { mock.Mock } func (x *MockComplexTypes) Normal(b_ bool) (int, error) { args := x.Called(b_) if len(args) > 0 { if t, ok := args.Get(0).(mockComplexTypes_Normal_ReturnFunc); ok { return t(b_) } } var r0 int if v := args.Get(0); v != nil { r0 = v.(int) } var r1 error if v := args.Get(1); v != nil { r1 = v.(error) } return r0, r1 } type mockComplexTypes_Normal struct { *mock.Call } type mockComplexTypes_Normal_ReturnFunc func(b bool) (int, error) func (c *mockComplexTypes_Normal) Return(arg0 int, arg1 error) *mock.Call { return c.Call.Return(arg0, arg1) } func (c *mockComplexTypes_Normal) ReturnFn(fn mockComplexTypes_Normal_ReturnFunc) *mock.Call { return c.Call.Return(fn) } func (x *MockComplexTypes) On_Normal(b_ bool) *mockComplexTypes_Normal { return &mockComplexTypes_Normal{Call: x.On("Normal", b_)} } func (x *MockComplexTypes) On_Normal_Any() *mockComplexTypes_Normal { return &mockComplexTypes_Normal{Call: x.On("Normal", mock.Anything)} } func (x *MockComplexTypes) On_Normal_Interface(b_ interface{}) *mockComplexTypes_Normal { return &mockComplexTypes_Normal{Call: x.On("Normal", b_)} } func (x *MockComplexTypes) Assert_Normal_Called(t *testing.T, b_ bool) bool { return x.AssertCalled(t, "Normal", b_) } func (x *MockComplexTypes) Assert_Normal_NumberOfCalls(t *testing.T, expectedCalls int) bool { return x.AssertNumberOfCalls(t, "Normal", expectedCalls) } func (x *MockComplexTypes) Assert_Normal_NotCalled(t *testing.T, b_ bool) bool { return x.AssertNotCalled(t, "Normal", b_) } func (x *MockComplexTypes) RemoveCtx(ctx_ context.Context) { args := x.Called() if len(args) > 0 { if t, ok := args.Get(0).(mockComplexTypes_RemoveCtx_ReturnFunc); ok { t(ctx_) } } } type mockComplexTypes_RemoveCtx struct { *mock.Call } type mockComplexTypes_RemoveCtx_ReturnFunc func(ctx context.Context) func (c *mockComplexTypes_RemoveCtx) Return() *mock.Call { return c.Call.Return() } func (c *mockComplexTypes_RemoveCtx) ReturnFn(fn mockComplexTypes_RemoveCtx_ReturnFunc) *mock.Call { return c.Call.Return(fn) } func (x *MockComplexTypes) On_RemoveCtx() *mockComplexTypes_RemoveCtx { return &mockComplexTypes_RemoveCtx{Call: x.On("RemoveCtx")} } func (x *MockComplexTypes) Assert_RemoveCtx_Called(t *testing.T) bool { return x.AssertCalled(t, "RemoveCtx") } func (x *MockComplexTypes) Assert_RemoveCtx_NumberOfCalls(t *testing.T, expectedCalls int) bool { return x.AssertNumberOfCalls(t, "RemoveCtx", expectedCalls) } func (x *MockComplexTypes) Assert_RemoveCtx_NotCalled(t *testing.T) bool { return x.AssertNotCalled(t, "RemoveCtx") } func (x *MockComplexTypes) AnonymousInterface(i_ interface { TestMethod() (bool, error) }) { args := x.Called(i_) if len(args) > 0 { if t, ok := args.Get(0).(mockComplexTypes_AnonymousInterface_ReturnFunc); ok { t(i_) } } } type mockComplexTypes_AnonymousInterface struct { *mock.Call } type mockComplexTypes_AnonymousInterface_ReturnFunc func(i interface { TestMethod() (bool, error) }) func (c *mockComplexTypes_AnonymousInterface) Return() *mock.Call { return c.Call.Return() } func (c *mockComplexTypes_AnonymousInterface) ReturnFn(fn mockComplexTypes_AnonymousInterface_ReturnFunc) *mock.Call { return c.Call.Return(fn) } func (x *MockComplexTypes) On_AnonymousInterface(i_ interface { TestMethod() (bool, error) }) *mockComplexTypes_AnonymousInterface { return &mockComplexTypes_AnonymousInterface{Call: x.On("AnonymousInterface", i_)} } func (x *MockComplexTypes) On_AnonymousInterface_Any() *mockComplexTypes_AnonymousInterface { return &mockComplexTypes_AnonymousInterface{Call: x.On("AnonymousInterface", mock.Anything)} } func (x *MockComplexTypes) On_AnonymousInterface_Interface(i_ interface{}) *mockComplexTypes_AnonymousInterface { return &mockComplexTypes_AnonymousInterface{Call: x.On("AnonymousInterface", i_)} } func (x *MockComplexTypes) Assert_AnonymousInterface_Called(t *testing.T, i_ interface { TestMethod() (bool, error) }) bool { return x.AssertCalled(t, "AnonymousInterface", i_) } func (x *MockComplexTypes) Assert_AnonymousInterface_NumberOfCalls(t *testing.T, expectedCalls int) bool { return x.AssertNumberOfCalls(t, "AnonymousInterface", expectedCalls) } func (x *MockComplexTypes) Assert_AnonymousInterface_NotCalled(t *testing.T, i_ interface { TestMethod() (bool, error) }) bool { return x.AssertNotCalled(t, "AnonymousInterface", i_) } func (x *MockComplexTypes) AnonymousStruct(s_ struct { testVar bool }) { args := x.Called(s_) if len(args) > 0 { if t, ok := args.Get(0).(mockComplexTypes_AnonymousStruct_ReturnFunc); ok { t(s_) } } } type mockComplexTypes_AnonymousStruct struct { *mock.Call } type mockComplexTypes_AnonymousStruct_ReturnFunc func(s struct { testVar bool }) func (c *mockComplexTypes_AnonymousStruct) Return() *mock.Call { return c.Call.Return() } func (c *mockComplexTypes_AnonymousStruct) ReturnFn(fn mockComplexTypes_AnonymousStruct_ReturnFunc) *mock.Call { return c.Call.Return(fn) } func (x *MockComplexTypes) On_AnonymousStruct(s_ struct { testVar bool }) *mockComplexTypes_AnonymousStruct { return &mockComplexTypes_AnonymousStruct{Call: x.On("AnonymousStruct", s_)} } func (x *MockComplexTypes) On_AnonymousStruct_Any() *mockComplexTypes_AnonymousStruct { return &mockComplexTypes_AnonymousStruct{Call: x.On("AnonymousStruct", mock.Anything)} } func (x *MockComplexTypes) On_AnonymousStruct_Interface(s_ interface{}) *mockComplexTypes_AnonymousStruct { return &mockComplexTypes_AnonymousStruct{Call: x.On("AnonymousStruct", s_)} } func (x *MockComplexTypes) Assert_AnonymousStruct_Called(t *testing.T, s_ struct { testVar bool }) bool { return x.AssertCalled(t, "AnonymousStruct", s_) } func (x *MockComplexTypes) Assert_AnonymousStruct_NumberOfCalls(t *testing.T, expectedCalls int) bool { return x.AssertNumberOfCalls(t, "AnonymousStruct", expectedCalls) } func (x *MockComplexTypes) Assert_AnonymousStruct_NotCalled(t *testing.T, s_ struct { testVar bool }) bool { return x.AssertNotCalled(t, "AnonymousStruct", s_) } func (x *MockComplexTypes) Channels(i_ chan<- int, o_ <-chan int) (chan bool, error) { args := x.Called(i_, o_) if len(args) > 0 { if t, ok := args.Get(0).(mockComplexTypes_Channels_ReturnFunc); ok { return t(i_, o_) } } var r0 chan bool if v := args.Get(0); v != nil { r0 = v.(chan bool) } var r1 error if v := args.Get(1); v != nil { r1 = v.(error) } return r0, r1 } type mockComplexTypes_Channels struct { *mock.Call } type mockComplexTypes_Channels_ReturnFunc func(i chan<- int, o <-chan int) (chan bool, error) func (c *mockComplexTypes_Channels) Return(arg0 chan bool, arg1 error) *mock.Call { return c.Call.Return(arg0, arg1) } func (c *mockComplexTypes_Channels) ReturnFn(fn mockComplexTypes_Channels_ReturnFunc) *mock.Call { return c.Call.Return(fn) } func (x *MockComplexTypes) On_Channels(i_ chan<- int, o_ <-chan int) *mockComplexTypes_Channels { return &mockComplexTypes_Channels{Call: x.On("Channels", i_, o_)} } func (x *MockComplexTypes) On_Channels_Any() *mockComplexTypes_Channels { return &mockComplexTypes_Channels{Call: x.On("Channels", mock.Anything, mock.Anything)} } func (x *MockComplexTypes) On_Channels_Interface(i_ interface{}, o_ interface{}) *mockComplexTypes_Channels { return &mockComplexTypes_Channels{Call: x.On("Channels", i_, o_)} } func (x *MockComplexTypes) Assert_Channels_Called(t *testing.T, i_ chan<- int, o_ <-chan int) bool { return x.AssertCalled(t, "Channels", i_, o_) } func (x *MockComplexTypes) Assert_Channels_NumberOfCalls(t *testing.T, expectedCalls int) bool { return x.AssertNumberOfCalls(t, "Channels", expectedCalls) } func (x *MockComplexTypes) Assert_Channels_NotCalled(t *testing.T, i_ chan<- int, o_ <-chan int) bool { return x.AssertNotCalled(t, "Channels", i_, o_) } func (x *MockComplexTypes) Variadic(i_ int, i2_ ...int) (bool, error) { args := x.Called(i_, i2_) if len(args) > 0 { if t, ok := args.Get(0).(mockComplexTypes_Variadic_ReturnFunc); ok { return t(i_, i2_...) } } var r0 bool if v := args.Get(0); v != nil { r0 = v.(bool) } var r1 error if v := args.Get(1); v != nil { r1 = v.(error) } return r0, r1 } type mockComplexTypes_Variadic struct { *mock.Call } type mockComplexTypes_Variadic_ReturnFunc func(i int, i2 ...int) (bool, error) func (c *mockComplexTypes_Variadic) Return(arg0 bool, arg1 error) *mock.Call { return c.Call.Return(arg0, arg1) } func (c *mockComplexTypes_Variadic) ReturnFn(fn mockComplexTypes_Variadic_ReturnFunc) *mock.Call { return c.Call.Return(fn) } func (x *MockComplexTypes) On_Variadic(i_ int, i2_ ...int) *mockComplexTypes_Variadic { return &mockComplexTypes_Variadic{Call: x.On("Variadic", i_, i2_)} } func (x *MockComplexTypes) On_Variadic_Any() *mockComplexTypes_Variadic { return &mockComplexTypes_Variadic{Call: x.On("Variadic", mock.Anything, mock.Anything)} } func (x *MockComplexTypes) On_Variadic_Interface(i_ interface{}, i2_ interface{}) *mockComplexTypes_Variadic { return &mockComplexTypes_Variadic{Call: x.On("Variadic", i_, i2_)} } func (x *MockComplexTypes) Assert_Variadic_Called(t *testing.T, i_ int, i2_ ...int) bool { return x.AssertCalled(t, "Variadic", i_, i2_) } func (x *MockComplexTypes) Assert_Variadic_NumberOfCalls(t *testing.T, expectedCalls int) bool { return x.AssertNumberOfCalls(t, "Variadic", expectedCalls) } func (x *MockComplexTypes) Assert_Variadic_NotCalled(t *testing.T, i_ int, i2_ ...int) bool { return x.AssertNotCalled(t, "Variadic", i_, i2_) }
examples/example_mock_complextypes.gen.go
0.785103
0.421611
example_mock_complextypes.gen.go
starcoder
package difficulty import "math" type Difficulty struct { hp, cs, od, ar float64 Preempt float64 CircleRadius float64 Mods Modifier Hit50 float64 Hit100 float64 Hit300 float64 HPMod float64 SpinnerRatio float64 Speed float64 ARReal float64 ODReal float64 CustomSpeed float64 } func NewDifficulty(hp, cs, od, ar float64) *Difficulty { diff := new(Difficulty) diff.hp = hp diff.cs = cs diff.od = od diff.ar = ar diff.CustomSpeed = 1 diff.calculate() return diff } func (diff *Difficulty) calculate() { hp, cs, od, ar := diff.hp, diff.cs, diff.od, diff.ar if diff.Mods&HardRock > 0 { ar = math.Min(ar*1.4, 10) cs = math.Min(cs*1.3, 10) od = math.Min(od*1.4, 10) hp = math.Min(hp*1.4, 10) } if diff.Mods&Easy > 0 { ar /= 2 cs /= 2 od /= 2 hp /= 2 } diff.HPMod = hp diff.CircleRadius = DifficultyRate(cs, 54.4, 32, 9.6) diff.Preempt = DifficultyRate(ar, 1800, 1200, 450) diff.Hit50 = DifficultyRate(od, 200, 150, 100) diff.Hit100 = DifficultyRate(od, 140, 100, 60) diff.Hit300 = DifficultyRate(od, 80, 50, 20) diff.SpinnerRatio = DifficultyRate(od, 3, 5, 7.5) diff.Speed = 1.0 / diff.GetModifiedTime(1) diff.ARReal = DiffFromRate(diff.GetModifiedTime(diff.Preempt), 1800, 1200, 450) diff.ODReal = DiffFromRate(diff.GetModifiedTime(diff.Hit300), 80, 50, 20) } func (diff *Difficulty) SetMods(mods Modifier) { diff.Mods = mods diff.calculate() } func (diff *Difficulty) CheckModActive(mods Modifier) bool { return diff.Mods&mods > 0 } func (diff *Difficulty) GetModifiedTime(time float64) float64 { if diff.Mods&DoubleTime > 0 { return time / (1.5 * diff.CustomSpeed) } else if diff.Mods&HalfTime > 0 { return time / (0.75 * diff.CustomSpeed) } else { return time / diff.CustomSpeed } } func (diff *Difficulty) GetHP() float64 { return diff.hp } func (diff *Difficulty) SetHP(hp float64) { diff.hp = hp diff.calculate() } func (diff *Difficulty) GetCS() float64 { return diff.cs } func (diff *Difficulty) SetCS(cs float64) { diff.cs = cs diff.calculate() } func (diff *Difficulty) GetOD() float64 { return diff.od } func (diff *Difficulty) SetOD(od float64) { diff.od = od diff.calculate() } func (diff *Difficulty) GetAR() float64 { return diff.ar } func (diff *Difficulty) SetAR(ar float64) { diff.ar = ar diff.calculate() } func (diff *Difficulty) SetCustomSpeed(speed float64) { diff.CustomSpeed = speed diff.calculate() } func DifficultyRate(diff, min, mid, max float64) float64 { if diff > 5 { return mid + (max-mid)*(diff-5)/5 } if diff < 5 { return mid - (mid-min)*(5-diff)/5 } return mid } func DiffFromRate(rate, min, mid, max float64) float64 { minStep := (min - mid) / 5 maxStep := (mid - max) / 5 if rate > mid { return -(rate - min) / minStep } return 5.0 - (rate-mid)/maxStep }
beatmap/difficulty/difficulty.go
0.744842
0.444203
difficulty.go
starcoder
package utils import ( "reflect" ) // IsNil checks whether `value` is nil. func IsNil(value interface{}) bool { return value == nil } // IsEmpty checks whether `value` is empty. func IsEmpty(value interface{}) bool { if value == nil { return true } switch value := value.(type) { case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64: return value == 0 case float32, float64: return value == 0 case bool: return value == false case string: return value == "" case []byte: return len(value) == 0 case []rune: return len(value) == 0 case []int: return len(value) == 0 case []string: return len(value) == 0 case []float32: return len(value) == 0 case []float64: return len(value) == 0 case map[string]interface{}: return len(value) == 0 default: var rv reflect.Value if v, ok := value.(reflect.Value); ok { rv = v } else { rv = reflect.ValueOf(value) } switch rv.Kind() { 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, reflect.Uintptr: return rv.Uint() == 0 case reflect.Float32, reflect.Float64: return rv.Float() == 0 case reflect.String: return rv.Len() == 0 case reflect.Struct: for i := 0; i < rv.NumField(); i++ { if !IsEmpty(rv) { return false } } return true case reflect.Chan, reflect.Map, reflect.Slice, reflect.Array: return rv.Len() == 0 case reflect.Func, reflect.Ptr, reflect.Interface, reflect.UnsafePointer: if rv.IsNil() { return true } } } return false } // IsInt checks whether `value` is type of int. func IsInt(value interface{}) bool { switch value.(type) { case int, *int, int8, *int8, int16, *int16, int32, *int32, int64, *int64: return true } return false } // IsUint checks whether `value` is type of uint. func IsUint(value interface{}) bool { switch value.(type) { case uint, *uint, uint8, *uint8, uint16, *uint16, uint32, *uint32, uint64, *uint64: return true } return false } // IsFloat checks whether `value` is type of float. func IsFloat(value interface{}) bool { switch value.(type) { case float32, *float32, float64, *float64: return true } return false } // IsSlice checks whether `value` is type of slice. func IsSlice(value interface{}) bool { var ( reflectValue = reflect.ValueOf(value) reflectKind = reflectValue.Kind() ) for reflectKind == reflect.Ptr { reflectValue = reflectValue.Elem() } switch reflectKind { case reflect.Slice, reflect.Array: return true } return false } // IsMap checks whether `value` is type of map. func IsMap(value interface{}) bool { var ( reflectValue = reflect.ValueOf(value) reflectKind = reflectValue.Kind() ) for reflectKind == reflect.Ptr { reflectValue = reflectValue.Elem() } switch reflectKind { case reflect.Map: return true } return false } // IsStruct checks whether `value` is type of struct. func IsStruct(value interface{}) bool { var ( reflectValue = reflect.ValueOf(value) reflectKind = reflectValue.Kind() ) for reflectKind == reflect.Ptr { reflectValue = reflectValue.Elem() reflectKind = reflectValue.Kind() } switch reflectKind { case reflect.Struct: return true } return false }
utils/is.go
0.631253
0.493164
is.go
starcoder
package reverset import "github.com/melvinodsa/goOdsa/utils" /*RTransform will do the reverse transformation of the data that was passed to it as the argument data. It returns a string as reversed transformed data */ func RTransform(data utils.Data) []byte { return data.GetData() } /*rTransformWrapper is a wrapper function for concuurent transformation of the input data to be processed in chunks */ func rTransformWrapper(channel chan utils.ChanByte, iString utils.ChanData) { result := utils.ChanByte{Output: RTransform(iString), Index: iString.Index} channel <- result } /*fTransformFactory creates the wrappers function necessary for the chunk processing of data once the maxChunk limit is crossed. endChannel is used to communicate the finished data array. */ func rTransformFactory(channel chan utils.ChanByte, endChannel chan [][]byte, data []utils.ChanData, maxChunk, startIndex, size int) { dataArray := make([][]byte, size) currentSize := 0 for { //Getting each data from the channel chanOut := <-channel dataArray[chanOut.Index] = chanOut.Output currentSize++ if startIndex < size { //Creating a wrapper function to process next chunk go rTransformWrapper(channel, data[startIndex]) startIndex++ } else if currentSize == size { endChannel <- dataArray <-channel return } } } /*RTransformChunk will reverse transform the chunk data with go routines handling the RTransform. maxChunks has the maximum chunks to be processed concurrently. endChannel will passed to the factory function to communicate the end result so that other can use the data. */ func RTransformChunk(maxChunks int, channel chan []utils.ChanData, dataChan chan utils.ChanByte, endChannel chan [][]byte) { for { data := <-channel size := len(data) startIndex := size if maxChunks < size { size = maxChunks startIndex = maxChunks } go rTransformFactory(dataChan, endChannel, data, maxChunks, startIndex, len(data)) //Cuncurrently processing the data to be transformed for i := 0; i < size; i++ { go rTransformWrapper(dataChan, data[i]) } return } }
modules/reverset/reverset.go
0.658637
0.525186
reverset.go
starcoder
package haversine import ( "fmt" "math" ) const ( // degrees that constitute π radians DegreesInPiRadian = 180 MetersPerKm = 1000 // radius of the earth in miles EarthRadiusMiles = 3958 // radius of the earth in kilometers EarthRadiusKm = 6371 // radius of the earth in meters EarthRadiusMeters = EarthRadiusKm * MetersPerKm // kilometers unit KM Unit = "kilometers" // meters unit M Unit = "meters" // miles unit MI Unit = "miles" ) type Unit string type Distance float64 type Kilometers Distance type Meters Distance type Miles Distance /* A coordinate represents a geographic coordinate. */ type Coordinate struct { Latitude float64 Longitude float64 } /* A Coordinate representing the change in two coordinates */ type Delta Coordinate /* Implementation of the Stringer interface for Coordinate type. */ func (coordinate Coordinate) String() string { return fmt.Sprintf("{latitude=%v, longitude=%v}", coordinate.Latitude, coordinate.Longitude) } /* Returns the radians equivalent of a Coordinate expressed in degrees. */ func (coordinate Coordinate) ToRadians() Coordinate { return Coordinate{ Latitude: degreesToRadians(coordinate.Latitude), Longitude: degreesToRadians(coordinate.Longitude), } } /* Method that returns the Haversine distance between it's receiver and a remote coordinate. */ func (coordinate Coordinate) DistanceTo(remote Coordinate, unit Unit) Distance { return toUnit(haversineDistance(coordinate, remote), unit) } /* Calculates and returns the Delta of a coordinate w.r.t another coordinate. */ func (coordinate Coordinate) Delta(origin Coordinate) Delta { return Delta{ Latitude: coordinate.Latitude - origin.Latitude, Longitude: coordinate.Longitude - origin.Longitude, } } /* degreesToRadians converts degrees to radians. */ func degreesToRadians(degrees float64) float64 { return degrees * math.Pi / DegreesInPiRadian } /* haversineDistance calculates the shortest path between two coordinates on the surface of the Earth. */ func haversineDistance(origin, remote Coordinate) Distance { origin, remote = origin.ToRadians(), remote.ToRadians() change := origin.Delta(remote) angle := math.Pow(math.Sin(change.Latitude/2), 2) + math.Cos(origin.Latitude)*math.Cos(remote.Latitude)* math.Pow(math.Sin(change.Longitude/2), 2) return Distance(2 * math.Atan2(math.Sqrt(angle), math.Sqrt(1-angle))) } /* */ func toUnit(distance Distance, unit Unit) Distance { var result Distance switch unit { case KM: result = Distance(Kilometers(distance * EarthRadiusKm)) case M: result = Distance(Meters(distance * EarthRadiusMeters)) case MI: result = Distance(Miles(distance * EarthRadiusMiles)) } return result }
pkg/haversine/haversine.go
0.866444
0.642026
haversine.go
starcoder
package schema import ( pschema "github.com/pulumi/pulumi/pkg/v3/codegen/schema" ) func configToProvider(config pschema.ComplexTypeSpec) pschema.ComplexTypeSpec { // The Provider schema is the Config schema with an additional Language block for each Property. for k, v := range config.Properties { v.Language = map[string]pschema.RawMessage{ "python": rawMessage(map[string]interface{}{ "mapCase": false, }), } config.Properties[k] = v } return config } var assumeRole = pschema.ComplexTypeSpec{ ObjectTypeSpec: pschema.ObjectTypeSpec{ Description: "The configuration for a Provider to assume a role.", Properties: map[string]pschema.PropertySpec{ "durationSeconds": { Description: "Number of seconds to restrict the assume role session duration.", TypeSpec: pschema.TypeSpec{Type: "integer"}, }, "externalId": { Description: "External identifier to use when assuming the role.", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "policy": { Description: "IAM Policy JSON describing further restricting permissions for the IAM Role being assumed.", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "policyArns": { Description: "Set of Amazon Resource Names (ARNs) of IAM Policies describing further restricting permissions for the role.", TypeSpec: pschema.TypeSpec{Type: "array", Items: &pschema.TypeSpec{Type: "string"}}, }, "roleArn": { Description: "Amazon Resource Name (ARN) of the IAM Role to assume.", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "sessionName": { Description: "Session name to use when assuming the role.", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "tags": { Description: "Map of assume role session tags.", TypeSpec: pschema.TypeSpec{ Type: "object", AdditionalProperties: &pschema.TypeSpec{Type: "string"}}, }, "transitiveTagKeys": { Description: "A list of keys for session tags that you want to set as transitive. If you set a tag key as transitive, the corresponding key and value passes to subsequent sessions in a role chain.", TypeSpec: pschema.TypeSpec{Type: "array", Items: &pschema.TypeSpec{Type: "string"}}, }, }, Type: "object", }, } var defaultTags = pschema.ComplexTypeSpec{ ObjectTypeSpec: pschema.ObjectTypeSpec{ Description: "The configuration with resource tag settings to apply across all resources handled by this provider. This is designed to replace redundant per-resource `tags` configurations. Provider tags can be overridden with new values, but not excluded from specific resources. To override provider tag values, use the `tags` argument within a resource to configure new tag values for matching keys.", Properties: map[string]pschema.PropertySpec{ "tags": { Description: "A group of tags to set across all resources.", TypeSpec: pschema.TypeSpec{ Type: "object", AdditionalProperties: &pschema.TypeSpec{Type: "string"}}, }, }, Type: "object", }, } var endpoints = pschema.ComplexTypeSpec{ ObjectTypeSpec: pschema.ObjectTypeSpec{ Description: "The configuration for for customizing service endpoints.", Properties: map[string]pschema.PropertySpec{ "accessanalyzer": { Description: "Override the default endpoint for AWS Access Analyzer", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "acm": { Description: "Override the default endpoint for AWS Certificate Manager", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "acmpca": { Description: "Override the default endpoint for AWS Certificate Manager Private Certificate Authority", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "amplify": { Description: "Override the default endpoint for AWS Amplify Console", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "appconfig": { Description: "Override the default endpoint for AWS AppConfig", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "applicationautoscaling": { Description: "Override the default endpoint for AWS Application Auto Scaling", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "applicationinsights": { Description: "Override the default endpoint for AWS CloudWatch Application Insights", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "appmesh": { Description: "Override the default endpoint for AWS App Mesh", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "apprunner": { Description: "Override the default endpoint for AWS App Runner", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "appstream": { Description: "Override the default endpoint for AWS AppStream 2.0", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "appsync": { Description: "Override the default endpoint for AWS AppSync", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "athena": { Description: "Override the default endpoint for AWS Athena", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "auditmanager": { Description: "Override the default endpoint for AWS Audit Manager", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "autoscaling": { Description: "Override the default endpoint for AWS Auto Scaling", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "backup": { Description: "Override the default endpoint for AWS Backup", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "batch": { Description: "Override the default endpoint for AWS Batch", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "budgets": { Description: "Override the default endpoint for AWS Budgets", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "chime": { Description: "Override the default endpoint for Amazon Chime", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "cloud9": { Description: "Override the default endpoint for AWS Cloud9", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "cloudformation": { Description: "Override the default endpoint for AWS CloudFormation", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "cloudfront": { Description: "Override the default endpoint for AWS CloudFront", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "cloudhsm": { Description: "Override the default endpoint for AWS CloudHSM", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "cloudsearch": { Description: "Override the default endpoint for AWS CloudSearch", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "cloudtrail": { Description: "Override the default endpoint for AWS CloudTrail", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "cloudwatch": { Description: "Override the default endpoint for AWS CloudWatch", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "cloudwatchevents": { Description: "Override the default endpoint for AWS CloudWatch Events", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "cloudwatchlogs": { Description: "Override the default endpoint for AWS CloudWatch Logs", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "codeartifact": { Description: "Override the default endpoint for AWS CodeArtifact", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "codebuild": { Description: "Override the default endpoint for AWS CodeBuild", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "codecommit": { Description: "Override the default endpoint for AWS CodeCommit", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "codedeploy": { Description: "Override the default endpoint for AWS CodeDeploy", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "codepipeline": { Description: "Override the default endpoint for AWS CodePipeline", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "codestarconnections": { Description: "Override the default endpoint for AWS CodeStart Connections", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "cognitoidentity": { Description: "Override the default endpoint for Amazon Cognito", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "configservice": { Description: "Override the default endpoint for AWS Config", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "connect": { Description: "Override the default endpoint for Amazon Connect", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "cur": { Description: "Override the default endpoint for AWS Cost and Usage Reports", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "dataexchange": { Description: "Override the default endpoint for AWS Data Exchange", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "datapipeline": { Description: "Override the default endpoint for AWS Data Pipeline", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "datasync": { Description: "Override the default endpoint for AWS DataSync", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "dax": { Description: "Override the default endpoint for AWS DynamoDB Accelerator", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "detective": { Description: "Override the default endpoint for AWS Detective", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "devicefarm": { Description: "Override the default endpoint for AWS Device Farm", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "directconnect": { Description: "Override the default endpoint for AWS Direct Connect", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "dlm": { Description: "Override the default endpoint for AWS Data Lifecycle Manager", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "dms": { Description: "Override the default endpoint for AWS Database Migration Service", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "docdb": { Description: "Override the default endpoint for AWS DocumentDB", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "ds": { Description: "Override the default endpoint for AWS Directory Service", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "dynamodb": { Description: "Override the default endpoint for AWS DynamoDB", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "ec2": { Description: "Override the default endpoint for AWS Elastic Compute Cloud (EC2)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "ecr": { Description: "Override the default endpoint for AWS Elastic Container Registry (ECR)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "ecrpublic": { Description: "Override the default endpoint for AWS Elastic Container Registry (ECR) Public", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "ecs": { Description: "Override the default endpoint for AWS Elastic Container Service (ECS)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "efs": { Description: "Override the default endpoint for AWS Elastic File System (EFS)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "eks": { Description: "Override the default endpoint for AWS Elastic Kubernetes Service (EKS)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "elasticache": { Description: "Override the default endpoint for AWS ElastiCache", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "elasticbeanstalk": { Description: "Override the default endpoint for AWS Elastic Beanstalk", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "elastictranscoder": { Description: "Override the default endpoint for AWS Elastic Transcoder", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "elb": { Description: "Override the default endpoint for AWS Elastic Load Balancing", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "elbv2": { Description: "Override the default endpoint for AWS Elastic Load Balancing V2", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "emr": { Description: "Override the default endpoint for AWS EMR", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "emrcontainers": { Description: "Override the default endpoint for AWS EMR on EKS", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "es": { Description: "Override the default endpoint for AWS OpenSearch Service (formerly Elasticsearch)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "firehose": { Description: "Override the default endpoint for AWS Kinesis Data Firehose", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "fms": { Description: "Override the default endpoint for AWS Firewall Manager", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "forecast": { Description: "Override the default endpoint for Amazon Forecast", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "fsx": { Description: "Override the default endpoint for AWS FSx", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "gamelift": { Description: "Override the default endpoint for AWS GameLift", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "glacier": { Description: "Override the default endpoint for Amazon S3 Glacier", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "globalaccelerator": { Description: "Override the default endpoint for AWS Global Accelerator", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "glue": { Description: "Override the default endpoint for AWS Glue", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "greengrass": { Description: "Override the default endpoint for AWS IoT Greengrass", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "guardduty": { Description: "Override the default endpoint for AWS GuardDuty", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "iam": { Description: "Override the default endpoint for AWS Identity and Access Management", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "identitystore": { Description: "Override the default endpoint for AWS Single Sign-On (SSO) Identity Store", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "imagebuilder": { Description: "Override the default endpoint for AWS Image Builder", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "inspector": { Description: "Override the default endpoint for Amazon Inspector", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "iot": { Description: "Override the default endpoint for AWS IoT", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "iotanalytics": { Description: "Override the default endpoint for AWS IoT Analytics", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "iotevents": { Description: "Override the default endpoint for AWS IoT Events", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "kafka": { Description: "Override the default endpoint for Amazon Managed Streaming for Apache Kafka (MSK)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "kinesis": { Description: "Override the default endpoint for Amazon Kinesis", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "kinesisanalytics": { Description: "Override the default endpoint for Amazon Kinesis Data Analytics", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "kinesisanalyticsv2": { Description: "Override the default endpoint for Amazon Kinesis Data Analytics V2", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "kinesisvideo": { Description: "Override the default endpoint for Amazon Kinesis Video Streams", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "kms": { Description: "Override the default endpoint for AWS Key Management Service", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "lakeformation": { Description: "Override the default endpoint for AWS Lake Formation", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "lambda": { Description: "Override the default endpoint for AWS Lambda", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "lexmodels": { Description: "Override the default endpoint for Amazon Lex", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "licensemanager": { Description: "Override the default endpoint for AWS License Manager", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "lightsail": { Description: "Override the default endpoint for Amazon Lightsail", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "location": { Description: "Override the default endpoint for Amazon Location", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "macie": { Description: "Override the default endpoint for Amazon Macie", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "macie2": { Description: "Override the default endpoint for Amazon Macie V2", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "managedblockchain": { Description: "Override the default endpoint for Amazon Managed Blockchain", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "marketplacecatalog": { Description: "Override the default endpoint for AWS Marketplace Catalog", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "mediaconnect": { Description: "Override the default endpoint for AWS MediaConnect", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "mediaconvert": { Description: "Override the default endpoint for AWS MediaConvert", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "medialive": { Description: "Override the default endpoint for AWS MediaLive", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "mediapackage": { Description: "Override the default endpoint for AWS MediaPackage", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "mediastore": { Description: "Override the default endpoint for AWS Elemental MediaStore container", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "mediastoredata": { Description: "Override the default endpoint for AWS Elemental MediaStore asset", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "memorydb": { Description: "Override the default endpoint for AWS MemoryDB for Redis", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "mq": { Description: "Override the default endpoint for Amazon MQ", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "mwaa": { Description: "Override the default endpoint for Amazon Managed Workflows for Apache Airflow", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "neptune": { Description: "Override the default endpoint for Amazon Neptune", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "networkfirewall": { Description: "Override the default endpoint for AWS Network Firewall", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "networkmanager": { Description: "Override the default endpoint for AWS Network Manager", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "opsworks": { Description: "Override the default endpoint for AWS OpsWorks", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "organizations": { Description: "Override the default endpoint for AWS Organizations", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "outposts": { Description: "Override the default endpoint for AWS Outposts", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "personalize": { Description: "Override the default endpoint for Amazon Personalize", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "pinpoint": { Description: "Override the default endpoint for Amazon Pinpoint", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "pricing": { Description: "Override the default endpoint for Amazon Web Services Price List Service", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "qldb": { Description: "Override the default endpoint for Amazon QLDB", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "quicksight": { Description: "Override the default endpoint for Amazon QuickSight", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "ram": { Description: "Override the default endpoint for AWS Resource Access Manager", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "rds": { Description: "Override the default endpoint for Amazon Relational Database Service", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "redshift": { Description: "Override the default endpoint for Amazon Redshift", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "resourcegroups": { Description: "Override the default endpoint for AWS Resource Groups", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "resourcegroupstaggingapi": { Description: "Override the default endpoint for AWS Resource Groups Tagging API", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "route53": { Description: "Override the default endpoint for Amazon Route 53", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "route53domains": { Description: "Override the default endpoint for Amazon Route 53 Domains", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "route53recoverycontrolconfig": { Description: "Override the default endpoint for Amazon Route 53 Recovery Control", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "route53recoveryreadiness": { Description: "Override the default endpoint for Amazon Route 53 Recovery Readiness", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "route53resolver": { Description: "Override the default endpoint for Amazon Route 53 Resolver", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "s3": { Description: "Override the default endpoint for Amazon Simple Storage Service (S3)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "s3control": { Description: "Override the default endpoint for Amazon Simple Storage Service (S3) Control", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "s3outposts": { Description: "Override the default endpoint for Amazon S3 on Outposts", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "sagemaker": { Description: "Override the default endpoint for AWS SageMaker", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "schemas": { Description: "Override the default endpoint for Amazon EventBridge Schema Registry", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "sdb": { Description: "Override the default endpoint for Amazon SimpleDB", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "secretsmanager": { Description: "Override the default endpoint for AWS Secrets Manager", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "securityhub": { Description: "Override the default endpoint for AWS Security Hub", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "serverlessrepo": { Description: "Override the default endpoint for AWS Serverless Application Repository", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "servicecatalog": { Description: "Override the default endpoint for AWS Service Catalog", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "servicediscovery": { Description: "Override the default endpoint for AWS Cloud Map", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "servicequotas": { Description: "Override the default endpoint for AWS Service Quotas", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "ses": { Description: "Override the default endpoint for Amazon Simple Email Service (SES)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "shield": { Description: "Override the default endpoint for AWS Shield Advanced API", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "signer": { Description: "Override the default endpoint for AWS Signer", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "sns": { Description: "Override the default endpoint for Amazon Simple Notification Service (SNS)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "sqs": { Description: "Override the default endpoint for Amazon Simple Queue Service (SQS)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "ssm": { Description: "Override the default endpoint for AWS Systems Manager", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "ssoadmin": { Description: "Override the default endpoint for AWS Single Sign On (SSO)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "stepfunctions": { Description: "Override the default endpoint for AWS Step Functions", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "storagegateway": { Description: "Override the default endpoint for AWS Storage Gateway", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "sts": { Description: "Override the default endpoint for AWS Security Token Service (STS)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "swf": { Description: "Override the default endpoint for Amazon Simple Workflow Service (SWF)", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "synthetics": { Description: "Override the default endpoint for Amazon CloudWatch Synthetics", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "timestreamwrite": { Description: "Override the default endpoint for Amazon Timestream", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "transfer": { Description: "Override the default endpoint for AWS Transfer Family", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "waf": { Description: "Override the default endpoint for AWS WAF Classic", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "wafregional": { Description: "Override the default endpoint for AWS WAF Regional Classic", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "wafv2": { Description: "Override the default endpoint for AWS WAF V2", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "worklink": { Description: "Override the default endpoint for Amazon WorkLink", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "workmail": { Description: "Override the default endpoint for Amazon WorkMail", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "workspaces": { Description: "Override the default endpoint for Amazon WorkSpaces", TypeSpec: pschema.TypeSpec{Type: "string"}, }, "xray": { Description: "Override the default endpoint for AWS X-Ray", TypeSpec: pschema.TypeSpec{Type: "string"}, }, }, Type: "object", }, } var ignoreTags = pschema.ComplexTypeSpec{ ObjectTypeSpec: pschema.ObjectTypeSpec{ Description: "The configuration with resource tag settings to ignore across all resources handled by this provider (except any individual service tag resources such as `ec2.Tag`) for situations where external systems are managing certain resource tags.", Properties: map[string]pschema.PropertySpec{ "keyPrefixes": { Description: "List of exact resource tag keys to ignore across all resources handled by this provider. This configuration prevents Pulumi from returning the tag in any `tags` attributes and displaying any configuration difference for the tag value. If any resource configuration still has this tag key configured in the `tags` argument, it will display a perpetual difference until the tag is removed from the argument or `ignoreChanges` is also used.", TypeSpec: pschema.TypeSpec{Type: "array", Items: &pschema.TypeSpec{Type: "string"}}, }, "keys": { Description: "List of resource tag key prefixes to ignore across all resources handled by this provider. This configuration prevents Pulumi from returning any tag key matching the prefixes in any `tags` attributes and displaying any configuration difference for those tag values. If any resource configuration still has a tag matching one of the prefixes configured in the `tags` argument, it will display a perpetual difference until the tag is removed from the argument or `ignoreChanges` is also used.", TypeSpec: pschema.TypeSpec{Type: "array", Items: &pschema.TypeSpec{Type: "string"}}, }, }, Type: "object", }, } var region = pschema.ComplexTypeSpec{ ObjectTypeSpec: pschema.ObjectTypeSpec{ Description: "A Region represents any valid Amazon region that may be targeted with deployments.", Type: "string", }, Enum: []pschema.EnumValueSpec{ {Name: "AFSouth1", Value: "af-south-1", Description: "Africa (Cape Town)"}, {Name: "APEast1", Value: "ap-east-1", Description: "Asia Pacific (Hong Kong)"}, {Name: "APNortheast1", Value: "ap-northeast-1", Description: "Asia Pacific (Tokyo)"}, {Name: "APNortheast2", Value: "ap-northeast-2", Description: "Asia Pacific (Seoul)"}, {Name: "APNortheast3", Value: "ap-northeast-3", Description: "Asia Pacific (Osaka)"}, {Name: "APSouth1", Value: "ap-south-1", Description: "Asia Pacific (Mumbai)"}, {Name: "APSoutheast1", Value: "ap-southeast-1", Description: "Asia Pacific (Singapore)"}, {Name: "APSoutheast2", Value: "ap-southeast-2", Description: "Asia Pacific (Sydney)"}, {Name: "CACentral", Value: "ca-central-1", Description: "Canada (Central)"}, {Name: "CNNorth1", Value: "cn-north-1", Description: "China (Beijing)"}, {Name: "CNNorthwest1", Value: "cn-northwest-1", Description: "China (Ningxia)"}, {Name: "EUCentral1", Value: "eu-central-1", Description: "Europe (Frankfurt)"}, {Name: "EUNorth1", Value: "eu-north-1", Description: "Europe (Stockholm)"}, {Name: "EUWest1", Value: "eu-west-1", Description: "Europe (Ireland)"}, {Name: "EUWest2", Value: "eu-west-2", Description: "Europe (London)"}, {Name: "EUWest3", Value: "eu-west-3", Description: "Europe (Paris)"}, {Name: "EUSouth1", Value: "eu-south-1", Description: "Europe (Milan)"}, {Name: "MESouth1", Value: "me-south-1", Description: "Middle East (Bahrain)"}, {Name: "SAEast1", Value: "sa-east-1", Description: "South America (São Paulo)"}, {Name: "USGovEast1", Value: "us-gov-east-1", Description: "AWS GovCloud (US-East)"}, {Name: "USGovWest1", Value: "us-gov-west-1", Description: "AWS GovCloud (US-West)"}, {Name: "USEast1", Value: "us-east-1", Description: "US East (N. Virginia)"}, {Name: "USEast2", Value: "us-east-2", Description: "US East (Ohio)"}, {Name: "USWest1", Value: "us-west-1", Description: "US West (N. California)"}, {Name: "USWest2", Value: "us-west-2", Description: "US West (Oregon)"}, }, } // typeOverlays augment the types defined by the schema. var typeOverlays = map[string]pschema.ComplexTypeSpec{ "aws-native:config:AssumeRole": assumeRole, "aws-native:index:ProviderAssumeRole": configToProvider(assumeRole), "aws-native:config:DefaultTags": defaultTags, "aws-native:index:ProviderDefaultTags": configToProvider(defaultTags), "aws-native:config:Endpoints": endpoints, "aws-native:index:ProviderEndpoint": configToProvider(endpoints), "aws-native:config:IgnoreTags": ignoreTags, "aws-native:index:ProviderIgnoreTags": configToProvider(ignoreTags), "aws-native:index/Region:Region": region, }
provider/pkg/schema/config.go
0.596551
0.504516
config.go
starcoder
package geoindex type ClusteringIndex struct { streetLevel *PointsIndex cityLevel *CountIndex worldLevel *CountIndex } var ( streetLevel = Km(45) cityLevel = Km(1000) ) // NewClusteringIndex creates index that clusters the points at three levels with cell size 0.5, 5 and 500km. // Useful for creating maps. func NewClusteringIndex() *ClusteringIndex { index := &ClusteringIndex{} index.streetLevel = NewPointsIndex(Km(0.5)) index.cityLevel = NewCountIndex(Km(10)) index.worldLevel = NewCountIndex(Km(500)) return index } // NewExpiringClusteringIndex creates index that clusters the points at three levels with cell size 0.5, 5 and 500km and // expires them after expiration minutes. func NewExpiringClusteringIndex(expiration Minutes) *ClusteringIndex { index := &ClusteringIndex{} index.streetLevel = NewExpiringPointsIndex(Km(0.5), expiration) index.cityLevel = NewExpiringCountIndex(Km(10), expiration) index.worldLevel = NewExpiringCountIndex(Km(500), expiration) return index } func (index *ClusteringIndex) Clone() *ClusteringIndex { clone := &ClusteringIndex{} clone.streetLevel = index.streetLevel.Clone() clone.cityLevel = index.cityLevel.Clone() clone.worldLevel = index.worldLevel.Clone() return clone } // Add adds a point. func (index *ClusteringIndex) Add(point Point) { index.streetLevel.Add(point) index.cityLevel.Add(point) index.worldLevel.Add(point) } // Remove removes a point. func (index *ClusteringIndex) Remove(id string) { index.streetLevel.Remove(id) index.cityLevel.Remove(id) index.worldLevel.Remove(id) } // Range returns points or count points depending on the size of the topLeft and bottomRight range. func (index *ClusteringIndex) Range(topLeft Point, bottomRight Point) []Point { dist := distance(topLeft, bottomRight) if dist < streetLevel { return index.streetLevel.Range(topLeft, bottomRight) } else if dist < cityLevel { return index.cityLevel.Range(topLeft, bottomRight) } else { return index.worldLevel.Range(topLeft, bottomRight) } } // KNearest returns the K-Nearest points near point within maxDistance, that match the accept function. func (index *ClusteringIndex) KNearest(point Point, k int, maxDistance Meters, accept func(p Point) bool) []Point { return index.streetLevel.KNearest(point, k, maxDistance, accept) }
hotelReservation/vendor/github.com/hailocab/go-geoindex/clustering-index.go
0.847274
0.510192
clustering-index.go
starcoder
// W niektórych językach idiomatyczne jest korzystanie z // [programowania generycznego](https://pl.wikipedia.org/wiki/Programowanie_uog%C3%B3lnione) i algorytmów. // Go, obecnie, nie wspiera tego paradygmatu. Go zazwyczaj udostępnia funkcje // gromadzenia danych, jeśli są one potrzebne specjalnie dla Twojego programu // i typów danych. // Oto kilka przykładów funkcji generycznych do pracy z wycinkami typu `strings`. // Możesz użyć tych przykładów do tworzenia własnych funkcji. Należy zauważyć, // że w niektórych przypadkach może być bardziej czytelnym osadzenie kodu, który // manipuluje kolekcjami, zamiast tworzyć funkcje pomocnicze. package main import ( "fmt" "strings" ) // Funkcja `Index` zwraca indeks elementu `t` z wycinka `vs`. Jeśli elementu nie // ma w wycinku, zwracana jest wartość `-1`. func Index(vs []string, t string) int { for i, v := range vs { if v == t { return i } } return -1 } // Funkcja `Include` zwraca `true`, jeśli element `t` jest w wycinku `vs`. func Include(vs []string, t string) bool { return Index(vs, t) >= 0 } // Funkcja `Any` zwraca `true`, jeśli którykolwiek z elementów w wycinku `vs` // spełnia warunek `f`. func Any(vs []string, f func(string) bool) bool { for _, v := range vs { if f(v) { return true } } return false } // Funkcja `All` zwraca `true`, jeśli wszystkie elementy wycinka `vs` spełniają // warunek `f`. func All(vs []string, f func(string) bool) bool { for _, v := range vs { if !f(v) { return false } } return true } // Funkcja `Filter` zwraca nowy wycinek zawierający elementy, które spełniają // warunek `f`. func Filter(vs []string, f func(string) bool) []string { vsf := make([]string, 0) for _, v := range vs { if f(v) { vsf = append(vsf, v) } } return vsf } // Funkcja `Map` zwraca nowy wycinek z wynikiem funkcji `f` wywołanej na // każdym elemencie oryginalnego wycinka. func Map(vs []string, f func(string) string) []string { vsm := make([]string, len(vs)) for i, v := range vs { vsm[i] = f(v) } return vsm } func main() { // Poniżej przykłady użycia powyższych funkcji. var strs = []string{"peach", "apple", "pear", "plum"} fmt.Println(Index(strs, "pear")) fmt.Println(Include(strs, "grape")) fmt.Println(Any(strs, func(v string) bool { return strings.HasPrefix(v, "p") })) fmt.Println(All(strs, func(v string) bool { return strings.HasPrefix(v, "p") })) fmt.Println(Filter(strs, func(v string) bool { return strings.Contains(v, "e") })) // We wszystkich powyższych przykładach używane były funkcje anonimowe, // ale można użyć nazwanych funkcji odpowiedniego typu. fmt.Println(Map(strs, strings.ToUpper)) }
examples/collection-functions/collection-functions.go
0.51879
0.420124
collection-functions.go
starcoder
package network // NATDeviceType indicates the type of the NAT device. type NATDeviceType int const ( // NATDeviceTypeUnknown indicates that the type of the NAT device is unknown. NATDeviceTypeUnknown NATDeviceType = iota // NATDeviceTypeCone indicates that the NAT device is a Cone NAT. // A Cone NAT is a NAT where all outgoing connections from the same source IP address and port are mapped by the NAT device // to the same IP address and port irrespective of the destination address. // With regards to RFC 3489, this could be either a Full Cone NAT, a Restricted Cone NAT or a // Port Restricted Cone NAT. However, we do NOT differentiate between them here and simply classify all such NATs as a Cone NAT. // NAT traversal with hole punching is possible with a Cone NAT ONLY if the remote peer is ALSO behind a Cone NAT. // If the remote peer is behind a Symmetric NAT, hole punching will fail. NATDeviceTypeCone // NATDeviceTypeSymmetric indicates that the NAT device is a Symmetric NAT. // A Symmetric NAT maps outgoing connections with different destination addresses to different IP addresses and ports, // even if they originate from the same source IP address and port. // NAT traversal with hole-punching is currently NOT possible in libp2p with Symmetric NATs irrespective of the remote peer's NAT type. NATDeviceTypeSymmetric ) func (r NATDeviceType) String() string { switch r { case 0: return "Unknown" case 1: return "Cone" case 2: return "Symmetric" default: return "unrecognized" } } // NATTransportProtocol is the transport protocol for which the NAT Device Type has been determined. type NATTransportProtocol int const ( // NATTransportUDP means that the NAT Device Type has been determined for the UDP Protocol. NATTransportUDP NATTransportProtocol = iota // NATTransportTCP means that the NAT Device Type has been determined for the TCP Protocol. NATTransportTCP ) func (n NATTransportProtocol) String() string { switch n { case 0: return "UDP" case 1: return "TCP" default: return "unrecognized" } }
vendor/github.com/libp2p/go-libp2p-core/network/nattype.go
0.710025
0.41253
nattype.go
starcoder
package binary_search_tree type Bst struct { root *node } type Data struct { Key int Value interface{} } type node struct { data Data left *node right *node } func NewBst() *Bst { return &Bst{nil} } func (t *Bst) Get(key int) (value interface{}, ok bool) { if n := find(t.root, key); n != nil { return n.data.Value, true } return 0, false } func (t *Bst) Set(key int, value interface{}) { t.root = insert(t.root, key, value) } func (t *Bst) Del(key int) { t.root = remove(t.root, key) } func (t *Bst) InOrder() []Data { return collect(inOrder, t.root) } func (t *Bst) PostOrderRecursive() []Data { return collect(postOrderRecursive, t.root) } func (t *Bst) PostOrderIterative() []Data { return collect(postOrderIterative, t.root) } func find(n *node, key int) *node { if n == nil || n.data.Key == key { return n } if key < n.data.Key { return find(n.left, key) } return find(n.right, key) } func insert(n *node, key int, value interface{}) *node { if n == nil { return &node{Data{key, value}, nil, nil} } if key == n.data.Key { n.data.Value = value return n } if key < n.data.Key { n.left = insert(n.left, key, value) } else { n.right = insert(n.right, key, value) } return n } func remove(n *node, key int) *node { if n == nil { return nil } if key == n.data.Key { if n.left == nil { return n.right } if n.right == nil { return n.left } return removeNodeWithTwoChildren(n) } if key < n.data.Key { n.left = remove(n.left, key) } else { n.right = remove(n.right, key) } return n } func removeNodeWithTwoChildren(n *node) *node { var predecessor *node n.left, predecessor = removeMax(n.left) n.data = predecessor.data return n } func removeMax(n *node) (root, max *node) { if n.right == nil { return n.left, n } n.right, max = removeMax(n.right) return n, max } func collect(fn func(*node, func(Data)), n *node) []Data { a := []Data{} fn(n, func(d Data) { a = append(a, d) }) return a } func inOrder(n *node, cb func(Data)) { if n == nil { return } inOrder(n.left, cb) cb(n.data) inOrder(n.right, cb) } func postOrderRecursive(n *node, cb func(Data)) { if n == nil { return } postOrderRecursive(n.left, cb) postOrderRecursive(n.right, cb) cb(n.data) } func postOrderIterative(n *node, cb func(Data)) { parents := []*node{} var child *node for { if child == nil && n.left != nil { parents = append(parents, n) n = n.left } else if (child == nil || child == n.left) && n.right != nil { parents = append(parents, n) n = n.right child = nil } else { cb(n.data) if len(parents) == 0 { return } child = n n = parents[len(parents)-1] parents = parents[:len(parents)-1] } } }
binary_search_tree/go/binary_search_tree.go
0.590661
0.403332
binary_search_tree.go
starcoder
package parser import ( "fmt" "strconv" "strings" ) type Atom interface { Parent() Atom Value() interface{} Kind() AtomKind } type Alpha struct { value string parent Atom } func (a Alpha) Parent() Atom { return a.parent } func (a Alpha) Value() interface{} { return a.value } func (a Alpha) Kind() AtomKind { return KindAlpha } type Bit struct { value string parent Atom } func (b Bit) Parent() Atom { return b.parent } func (b Bit) Value() interface{} { return b.value } func (b Bit) Kind() AtomKind { return KindBit } type Char struct { value string parent Atom } func (c Char) Parent() Atom { return c.parent } func (c Char) Value() interface{} { return c.value } func (c Char) Kind() AtomKind { return KindChar } type CRVal struct{ parent Atom } func (c CRVal) Parent() Atom { return c.parent } func (c CRVal) Value() interface{} { return "\r" } func (c CRVal) Kind() AtomKind { return KindCR } type LFVal struct{ parent Atom } func (l LFVal) Parent() Atom { return l.parent } func (l LFVal) Value() interface{} { return "\n" } func (l LFVal) Kind() AtomKind { return KindLF } type Ctl struct { parent Atom value string } func (c Ctl) Parent() Atom { return c.parent } func (c Ctl) Value() interface{} { return c.value } func (c Ctl) Kind() AtomKind { return KindCtl } type Digit struct { parent Atom value string } func (d Digit) Parent() Atom { return d.parent } func (d Digit) Value() interface{} { return d.value } func (d Digit) Kind() AtomKind { return KindDigit } type DQuote struct{ parent Atom } func (d DQuote) Parent() Atom { return d.parent } func (d DQuote) Value() interface{} { return "\"" } func (d DQuote) Kind() AtomKind { return KindDQuote } type HTab struct{ parent Atom } func (h HTab) Parent() Atom { return h.parent } func (h HTab) Value() interface{} { return "\t" } func (h HTab) Kind() AtomKind { return KindHTab } type Octet struct { parent Atom value rune } func (o Octet) Parent() Atom { return o.parent } func (o Octet) Value() interface{} { return o.value } func (o Octet) Kind() AtomKind { return KindOctet } type SPVal struct{ parent Atom } func (s SPVal) Parent() Atom { return s.parent } func (s SPVal) Value() interface{} { return " " } func (s SPVal) Kind() AtomKind { return KindSP } type VChar struct { parent Atom value string } func (v VChar) Parent() Atom { return v.parent } func (v VChar) Value() interface{} { return v.value } func (v VChar) Kind() AtomKind { return KindVChar } type OptionVal struct { parent Atom Valid bool value Atom } func (o OptionVal) Parent() Atom { return o.parent } func (o OptionVal) Value() interface{} { return o.value } func (o OptionVal) Kind() AtomKind { return KindOption } type AtomList struct { parent Atom value []Atom } func (a AtomList) Len() int { return len(a.value) } func (a AtomList) Parent() Atom { return a.parent } func (a AtomList) Value() interface{} { if a.value == nil { return nil } return a.value } func (a AtomList) Kind() AtomKind { return KindAtomList } func (a AtomList) AllTerminals() bool { for _, v := range a.value { switch i := v.(type) { case AtomList: if !i.AllTerminals() { return false } case RefResult: return false case OptionVal: return false } } return true } func (a AtomList) ReduceAsString() string { str := strings.Builder{} for _, v := range a.value { switch inst := v.(type) { case Alpha: str.WriteString(inst.value) case Char: str.WriteString(inst.value) case Digit: str.WriteString(inst.value) case DQuote: str.WriteString("\"") case SPVal: str.WriteString(" ") case LFVal: str.WriteString("\n") case VChar: str.WriteString(inst.value) case AtomList: str.WriteString(inst.ReduceAsString()) default: panic(fmt.Sprintf("Cannot reduce %T as string", v)) } } return str.String() } func (a AtomList) ReduceAsInt() (bool, int) { str := a.ReduceAsString() if str == "" { return false, 0 } i, err := strconv.Atoi(str) if err != nil { panic(fmt.Sprintf("ReduceAsInt failed: %s", err)) } return true, i } func (a AtomList) ReduceAsHex() (bool, int) { str := a.ReduceAsString() if str == "" { return false, 0 } i, err := strconv.ParseUint(str, 16, 8) if err != nil { panic(fmt.Sprintf("ReduceAsHex failed: %s", err)) } return true, int(i) } func (a AtomList) First() Atom { return a.Nth(0) } func (a AtomList) Nth(i int) Atom { return a.value[i] } type RefResult struct { Name string value Atom parent Atom } func (r RefResult) Parent() Atom { return r.parent } func (r RefResult) Value() interface{} { return r.value } func (r RefResult) Kind() AtomKind { return KindRefResult }
parser/types.go
0.584627
0.437944
types.go
starcoder
package util // Linear interpolation. // Lerp returns the value (1-t)*start + t*end. func Lerp(t, start, end float64) float64 { return (1-t)*start + t*end } // LerpClamp is a clamped [0,1] version of Lerp. func LerpClamp(t, start, end float64) float64 { if t < 0 { t = 0 } if t > 1 { t = 1 } return (1-t)*start + t*end } // InvLerp performs the inverse of Lerp and returns the value of t for a value v. func InvLerp(v, start, end float64) float64 { return (v - start) / (end - start) } // InvLerpClamp is a clamped [start, end] version of InvLerp. func InvLerpClamp(v, start, end float64) float64 { t := (v - start) / (end - start) if t < 0 { return 0 } if t > 1 { return 1 } return t } // Remap converts v from one space to another by applying InvLerp to find t in the initial range, and // then using t to find v' in the new range. func Remap(v, istart, iend, ostart, oend float64) float64 { return Lerp(InvLerp(v, istart, iend), ostart, oend) } // RemapClamp is a clamped version of Remap. func RemapClamp(v, istart, iend, ostart, oend float64) float64 { return LerpClamp(InvLerpClamp(v, istart, iend), ostart, oend) } // Float32 versions for Path and x/image/vector // Lerp32 is a float32 version of Lerp. func Lerp32(t, start, end float32) float32 { return (1-t)*start + t*end } // LerpClamp32 is a float32 version of LerpClamp. func LerpClamp32(t, start, end float32) float32 { if t < 0 { t = 0 } if t > 1 { t = 1 } return (1-t)*start + t*end } // InvLerp32 is a float32 version of InvLerp. func InvLerp32(v, start, end float32) float32 { return (v - start) / (end - start) } // InvLerpClamp32 is a float32 version of InvLerpClamp. func InvLerpClamp32(v, start, end float32) float32 { t := (v - start) / (end - start) if t < 0 { return 0 } if t > 1 { return 1 } return t } // Remap32 is a float32 version of Remap. func Remap32(v, istart, iend, ostart, oend float32) float32 { return Lerp32(InvLerp32(v, istart, iend), ostart, oend) } // RemapClamp32 is a float32 version of RemapClamp. func RemapClamp32(v, istart, iend, ostart, oend float32) float32 { return LerpClamp32(InvLerpClamp32(v, istart, iend), ostart, oend) }
util/lerp.go
0.843605
0.453141
lerp.go
starcoder
package filter import ( "fmt" "github.com/pkg/errors" "regexp" ) type Operator func(v string) bool const ( OperatorKey = "" OperatorEqual = "==" OperatorNotEqual = "!=" OperatorRegex = "?=" ) type OperatorFactory func(key, value string) (Operator, error) var Operators = map[string]OperatorFactory{ "==": func(key, value string) (Operator, error) { return func(v string) bool { return value == v }, nil }, "!=": func(key, value string) (Operator, error) { return func(v string) bool { return value != v }, nil }, "?=": func(key, value string) (operator Operator, e error) { re, err := regexp.Compile(value) if err != nil { return nil, errors.Errorf("bad regex in %s?=%s: %s", key, value, err) } return func(value string) bool { return re.MatchString(value) }, nil }, } type SimpleFilter struct { Raw string Key string Value string Operator Operator } func (s SimpleFilter) String() string { return s.Raw } func (s SimpleFilter) IsMatch(l Labels) bool { if label, ok := l[s.Key]; ok { labelValue := label.Value() return s.Operator(labelValue) } return false } // FilterFromOperator creates a new filter with the given operator. func FilterFromOperator(label, key string, operator Operator) Filter { return SimpleFilter{ Raw: label, Key: key, Operator: operator, } } // MustParse is like Parse but panics if parse fails. func MustParse(parts ...string) Filter { f, err := Parse(parts...) if err != nil { panic(err) } return f } // Parse returns a filter based on key, value, and operator // Argument patterns: // `"key"` - Will match if the key is found // `"keyOPvalue"` - Where OP is one or more none-word characters, will check the value of key against the provided value using the operator // `"key", "op", "value"` - Will check the value at key against the value using the operator func Parse(parts ...string) (Filter, error) { switch len(parts) { case 0: return nil, errors.New("at least one part required") case 1: matches := simpleFilterParseRE.FindStringSubmatch(parts[0]) if len(matches) == 4 { return newFilterFromOperator(matches[1], matches[2], matches[3]) } return SimpleFilter{ Raw: parts[0], Key: parts[0], Operator: func(value string) bool { return true }, }, nil case 3: return newFilterFromOperator(parts[0], parts[1], parts[2]) default: return nil, errors.Errorf("invalid parts %#v", parts) } } func newFilterFromOperator(k, op, v string) (Filter, error) { if factory, ok := Operators[op]; ok { fn, err := factory(k, v) if err != nil { return nil, err } return SimpleFilter{ Raw: fmt.Sprintf("%s%s%s", k, op, v), Key: k, Value: v, Operator: fn, }, nil } return nil, errors.Errorf("no operator factory registered for operator %q", op) } var simpleFilterParseRE = regexp.MustCompile(`(\w+)(\W{1,2})(.*)`)
pkg/filter/simple_filter.go
0.737442
0.414366
simple_filter.go
starcoder
package cppn import ( "errors" "fmt" "github.com/yaricom/goNEAT/neat/network" ) // Defines layout of neurons in the substrate type SubstrateLayout interface { // Returns coordinates of the neuron with specified index [0; count) and type NodePosition(index int, nType network.NodeNeuronType) (*PointF, error) // Returns number of BIAS neurons in the layout BiasCount() int // Returns number of INPUT neurons in the layout InputCount() int // Returns number of HIDDEN neurons in the layout HiddenCount() int // Returns number of OUTPUT neurons in the layout OutputCount() int } // Defines grid substrate layout type GridSubstrateLayout struct { // The number of bias nodes encoded in this substrate biasCount int // The number of input nodes encoded in this substrate inputCount int // The number of hidden nodes encoded in this substrate hiddenCount int // The number of output nodes encoded in this substrate outputCount int // The input coordinates increment inputDelta float64 // The hidden coordinates increment hiddenDelta float64 // The output coordinates increment outputDelta float64 } // Creates new instance with specified number of nodes to create layout for func NewGridSubstrateLayout(biasCount, inputCount, outputCount, hiddenCount int) *GridSubstrateLayout { s := GridSubstrateLayout{biasCount: biasCount, inputCount: inputCount, outputCount: outputCount, hiddenCount: hiddenCount} if s.inputCount != 0 { s.inputDelta = 2.0 / float64(inputCount) } if s.hiddenCount != 0 { s.hiddenDelta = 2.0 / float64(hiddenCount) } if s.outputCount != 0 { s.outputDelta = 2.0 / float64(outputCount) } return &s } func (g *GridSubstrateLayout) NodePosition(index int, nType network.NodeNeuronType) (*PointF, error) { if index < 0 { return nil, errors.New("neuron index can not be negative") } point := PointF{X: 0.0, Y: 0.0} delta := 0.0 count := 0 switch nType { case network.BiasNeuron: if index < g.biasCount { return &point, nil // BIAS always located at (0, 0) } else { return nil, errors.New("the BIAS index is out of range") } case network.HiddenNeuron: delta = g.hiddenDelta count = g.hiddenCount case network.InputNeuron: delta = g.inputDelta count = g.inputCount point.Y = -1.0 case network.OutputNeuron: delta = g.outputDelta count = g.outputCount point.Y = 1.0 } if index >= count { return nil, errors.New("neuron index is out of range") } else if nType == network.BiasNeuron { return &point, nil } // calculate X position point.X = -1.0 + delta/2.0 // the initial position with half delta shift point.X += float64(index) * delta return &point, nil } func (g *GridSubstrateLayout) BiasCount() int { return g.biasCount } func (g *GridSubstrateLayout) InputCount() int { return g.inputCount } func (g *GridSubstrateLayout) HiddenCount() int { return g.hiddenCount } func (g *GridSubstrateLayout) OutputCount() int { return g.outputCount } func (g *GridSubstrateLayout) String() string { str := fmt.Sprintf("GridSubstrateLayout:\n\tINPT: %d\n\tHIDN: %d\n\tOUTP: %d\n\tBIAS: %d", g.inputCount, g.hiddenCount, g.outputCount, g.biasCount) return str }
cppn/substrate_layout.go
0.803058
0.546799
substrate_layout.go
starcoder
package number import ( "crypto/rand" "errors" "fmt" "math/big" ) // Number of tries to generate coprime pair in generateCoprimes const tries = 5 // Generates a super increasing sequence of length n. // This function reports an error if n < 2. func GenerateSuperIncreasingSequence(n int) (r []*big.Int, err error) { if n < 2 { return nil, errors.New("Length of super increasing sequence should be greater than 1") } aux := big.NewInt(0) one := big.NewInt(1) two := big.NewInt(2) twoExpN := big.NewInt(0) r = make([]*big.Int, n) // Set first element of sequence to a value >= 2^n twoExpN.Exp(two, big.NewInt(int64(n)), nil) offset := generateRandomNumber(one, aux.Sqrt(twoExpN)) r[0] = offset.Add(offset, twoExpN) for i := 1; i < n; i++ { offset = generateRandomNumber(one, aux.Sqrt(r[i-1])) // Next element of the sequence must be at least 2 times larger than the previous one aux.Mul(two, r[i-1]) r[i] = offset.Add(offset, aux) } return r, nil } // Generates two coprime numbers A and B. Random number A will be such that // 1 <= A <= B - 1 . Prime B will have the same bit length as the bit length // of n + 1. func GenerateCoprimes(n *big.Int) (a *big.Int, b *big.Int, err error) { gcd := big.NewInt(0) one := big.NewInt(1) bitLen := n.BitLen() b, err = rand.Prime(rand.Reader, bitLen+1) if err != nil { return nil, nil, fmt.Errorf("Failed to generate prime number: %v", err) } // Try several times to find random number A that is coprime with B for i := tries; i > 0; i-- { a = generateRandomNumber(one, b) // Check to make sure A and B are coprime if gcd.GCD(nil, nil, a, b).Cmp(one) == 0 { return a, b, nil } } return nil, nil, fmt.Errorf("Failed to generate coprime number after %d attempts", tries) } // Generates a random number in the range [min, max). // This function panics if a random number cannot be generated. func generateRandomNumber(min *big.Int, max *big.Int) (num *big.Int) { diff := big.NewInt(0) if num, err := rand.Int(rand.Reader, diff.Sub(max, min)); err != nil { panic(err) } else { num.Add(num, min) return num } } // Generates a sequence m where each element m[i] is calculated as r[i]*a mod b. func MulMod(r []*big.Int, a *big.Int, b *big.Int) (m []*big.Int) { mul := big.NewInt(0) m = make([]*big.Int, len(r)) for i, ri := range r { mul.Mul(a, ri) m[i] = big.NewInt(0).Mod(mul, b) } return m }
internal/number/number.go
0.744471
0.425486
number.go
starcoder
package asm func (o Opcodes) Aad(ops ...Operand) { o.a.op("AAD", ops...) } func (o Opcodes) AAD(ops ...Operand) { o.a.op("AAD", ops...) } func (o Opcodes) Aam(ops ...Operand) { o.a.op("AAM", ops...) } func (o Opcodes) AAM(ops ...Operand) { o.a.op("AAM", ops...) } func (o Opcodes) Aas(ops ...Operand) { o.a.op("AAS", ops...) } func (o Opcodes) AAS(ops ...Operand) { o.a.op("AAS", ops...) } func (o Opcodes) Adcb(ops ...Operand) { o.a.op("ADCB", ops...) } func (o Opcodes) ADCB(ops ...Operand) { o.a.op("ADCB", ops...) } func (o Opcodes) Adcl(ops ...Operand) { o.a.op("ADCL", ops...) } func (o Opcodes) ADCL(ops ...Operand) { o.a.op("ADCL", ops...) } func (o Opcodes) Adcw(ops ...Operand) { o.a.op("ADCW", ops...) } func (o Opcodes) ADCW(ops ...Operand) { o.a.op("ADCW", ops...) } func (o Opcodes) Addb(ops ...Operand) { o.a.op("ADDB", ops...) } func (o Opcodes) ADDB(ops ...Operand) { o.a.op("ADDB", ops...) } func (o Opcodes) Addl(ops ...Operand) { o.a.op("ADDL", ops...) } func (o Opcodes) ADDL(ops ...Operand) { o.a.op("ADDL", ops...) } func (o Opcodes) Addw(ops ...Operand) { o.a.op("ADDW", ops...) } func (o Opcodes) ADDW(ops ...Operand) { o.a.op("ADDW", ops...) } func (o Opcodes) Adjsp(ops ...Operand) { o.a.op("ADJSP", ops...) } func (o Opcodes) ADJSP(ops ...Operand) { o.a.op("ADJSP", ops...) } func (o Opcodes) Andb(ops ...Operand) { o.a.op("ANDB", ops...) } func (o Opcodes) ANDB(ops ...Operand) { o.a.op("ANDB", ops...) } func (o Opcodes) Andl(ops ...Operand) { o.a.op("ANDL", ops...) } func (o Opcodes) ANDL(ops ...Operand) { o.a.op("ANDL", ops...) } func (o Opcodes) Andw(ops ...Operand) { o.a.op("ANDW", ops...) } func (o Opcodes) ANDW(ops ...Operand) { o.a.op("ANDW", ops...) } func (o Opcodes) Arpl(ops ...Operand) { o.a.op("ARPL", ops...) } func (o Opcodes) ARPL(ops ...Operand) { o.a.op("ARPL", ops...) } func (o Opcodes) Boundl(ops ...Operand) { o.a.op("BOUNDL", ops...) } func (o Opcodes) BOUNDL(ops ...Operand) { o.a.op("BOUNDL", ops...) } func (o Opcodes) Boundw(ops ...Operand) { o.a.op("BOUNDW", ops...) } func (o Opcodes) BOUNDW(ops ...Operand) { o.a.op("BOUNDW", ops...) } func (o Opcodes) Bsfl(ops ...Operand) { o.a.op("BSFL", ops...) } func (o Opcodes) BSFL(ops ...Operand) { o.a.op("BSFL", ops...) } func (o Opcodes) Bsfw(ops ...Operand) { o.a.op("BSFW", ops...) } func (o Opcodes) BSFW(ops ...Operand) { o.a.op("BSFW", ops...) } func (o Opcodes) Bsrl(ops ...Operand) { o.a.op("BSRL", ops...) } func (o Opcodes) BSRL(ops ...Operand) { o.a.op("BSRL", ops...) } func (o Opcodes) Bsrw(ops ...Operand) { o.a.op("BSRW", ops...) } func (o Opcodes) BSRW(ops ...Operand) { o.a.op("BSRW", ops...) } func (o Opcodes) Btl(ops ...Operand) { o.a.op("BTL", ops...) } func (o Opcodes) BTL(ops ...Operand) { o.a.op("BTL", ops...) } func (o Opcodes) Btw(ops ...Operand) { o.a.op("BTW", ops...) } func (o Opcodes) BTW(ops ...Operand) { o.a.op("BTW", ops...) } func (o Opcodes) Btcl(ops ...Operand) { o.a.op("BTCL", ops...) } func (o Opcodes) BTCL(ops ...Operand) { o.a.op("BTCL", ops...) } func (o Opcodes) Btcw(ops ...Operand) { o.a.op("BTCW", ops...) } func (o Opcodes) BTCW(ops ...Operand) { o.a.op("BTCW", ops...) } func (o Opcodes) Btrl(ops ...Operand) { o.a.op("BTRL", ops...) } func (o Opcodes) BTRL(ops ...Operand) { o.a.op("BTRL", ops...) } func (o Opcodes) Btrw(ops ...Operand) { o.a.op("BTRW", ops...) } func (o Opcodes) BTRW(ops ...Operand) { o.a.op("BTRW", ops...) } func (o Opcodes) Btsl(ops ...Operand) { o.a.op("BTSL", ops...) } func (o Opcodes) BTSL(ops ...Operand) { o.a.op("BTSL", ops...) } func (o Opcodes) Btsw(ops ...Operand) { o.a.op("BTSW", ops...) } func (o Opcodes) BTSW(ops ...Operand) { o.a.op("BTSW", ops...) } func (o Opcodes) Byte(ops ...Operand) { o.a.op("BYTE", ops...) } func (o Opcodes) BYTE(ops ...Operand) { o.a.op("BYTE", ops...) } func (o Opcodes) Clc(ops ...Operand) { o.a.op("CLC", ops...) } func (o Opcodes) CLC(ops ...Operand) { o.a.op("CLC", ops...) } func (o Opcodes) Cld(ops ...Operand) { o.a.op("CLD", ops...) } func (o Opcodes) CLD(ops ...Operand) { o.a.op("CLD", ops...) } func (o Opcodes) Cli(ops ...Operand) { o.a.op("CLI", ops...) } func (o Opcodes) CLI(ops ...Operand) { o.a.op("CLI", ops...) } func (o Opcodes) Clts(ops ...Operand) { o.a.op("CLTS", ops...) } func (o Opcodes) CLTS(ops ...Operand) { o.a.op("CLTS", ops...) } func (o Opcodes) Cmc(ops ...Operand) { o.a.op("CMC", ops...) } func (o Opcodes) CMC(ops ...Operand) { o.a.op("CMC", ops...) } func (o Opcodes) Cmpb(ops ...Operand) { o.a.op("CMPB", ops...) } func (o Opcodes) CMPB(ops ...Operand) { o.a.op("CMPB", ops...) } func (o Opcodes) Cmpl(ops ...Operand) { o.a.op("CMPL", ops...) } func (o Opcodes) CMPL(ops ...Operand) { o.a.op("CMPL", ops...) } func (o Opcodes) Cmpw(ops ...Operand) { o.a.op("CMPW", ops...) } func (o Opcodes) CMPW(ops ...Operand) { o.a.op("CMPW", ops...) } func (o Opcodes) Cmpsb(ops ...Operand) { o.a.op("CMPSB", ops...) } func (o Opcodes) CMPSB(ops ...Operand) { o.a.op("CMPSB", ops...) } func (o Opcodes) Cmpsl(ops ...Operand) { o.a.op("CMPSL", ops...) } func (o Opcodes) CMPSL(ops ...Operand) { o.a.op("CMPSL", ops...) } func (o Opcodes) Cmpsw(ops ...Operand) { o.a.op("CMPSW", ops...) } func (o Opcodes) CMPSW(ops ...Operand) { o.a.op("CMPSW", ops...) } func (o Opcodes) Daa(ops ...Operand) { o.a.op("DAA", ops...) } func (o Opcodes) DAA(ops ...Operand) { o.a.op("DAA", ops...) } func (o Opcodes) Das(ops ...Operand) { o.a.op("DAS", ops...) } func (o Opcodes) DAS(ops ...Operand) { o.a.op("DAS", ops...) } func (o Opcodes) Decb(ops ...Operand) { o.a.op("DECB", ops...) } func (o Opcodes) DECB(ops ...Operand) { o.a.op("DECB", ops...) } func (o Opcodes) Decl(ops ...Operand) { o.a.op("DECL", ops...) } func (o Opcodes) DECL(ops ...Operand) { o.a.op("DECL", ops...) } func (o Opcodes) Decq(ops ...Operand) { o.a.op("DECQ", ops...) } func (o Opcodes) DECQ(ops ...Operand) { o.a.op("DECQ", ops...) } func (o Opcodes) Decw(ops ...Operand) { o.a.op("DECW", ops...) } func (o Opcodes) DECW(ops ...Operand) { o.a.op("DECW", ops...) } func (o Opcodes) Divb(ops ...Operand) { o.a.op("DIVB", ops...) } func (o Opcodes) DIVB(ops ...Operand) { o.a.op("DIVB", ops...) } func (o Opcodes) Divl(ops ...Operand) { o.a.op("DIVL", ops...) } func (o Opcodes) DIVL(ops ...Operand) { o.a.op("DIVL", ops...) } func (o Opcodes) Divw(ops ...Operand) { o.a.op("DIVW", ops...) } func (o Opcodes) DIVW(ops ...Operand) { o.a.op("DIVW", ops...) } func (o Opcodes) Enter(ops ...Operand) { o.a.op("ENTER", ops...) } func (o Opcodes) ENTER(ops ...Operand) { o.a.op("ENTER", ops...) } func (o Opcodes) Haddpd(ops ...Operand) { o.a.op("HADDPD", ops...) } func (o Opcodes) HADDPD(ops ...Operand) { o.a.op("HADDPD", ops...) } func (o Opcodes) Haddps(ops ...Operand) { o.a.op("HADDPS", ops...) } func (o Opcodes) HADDPS(ops ...Operand) { o.a.op("HADDPS", ops...) } func (o Opcodes) Hlt(ops ...Operand) { o.a.op("HLT", ops...) } func (o Opcodes) HLT(ops ...Operand) { o.a.op("HLT", ops...) } func (o Opcodes) Hsubpd(ops ...Operand) { o.a.op("HSUBPD", ops...) } func (o Opcodes) HSUBPD(ops ...Operand) { o.a.op("HSUBPD", ops...) } func (o Opcodes) Hsubps(ops ...Operand) { o.a.op("HSUBPS", ops...) } func (o Opcodes) HSUBPS(ops ...Operand) { o.a.op("HSUBPS", ops...) } func (o Opcodes) Idivb(ops ...Operand) { o.a.op("IDIVB", ops...) } func (o Opcodes) IDIVB(ops ...Operand) { o.a.op("IDIVB", ops...) } func (o Opcodes) Idivl(ops ...Operand) { o.a.op("IDIVL", ops...) } func (o Opcodes) IDIVL(ops ...Operand) { o.a.op("IDIVL", ops...) } func (o Opcodes) Idivw(ops ...Operand) { o.a.op("IDIVW", ops...) } func (o Opcodes) IDIVW(ops ...Operand) { o.a.op("IDIVW", ops...) } func (o Opcodes) Imulb(ops ...Operand) { o.a.op("IMULB", ops...) } func (o Opcodes) IMULB(ops ...Operand) { o.a.op("IMULB", ops...) } func (o Opcodes) Imull(ops ...Operand) { o.a.op("IMULL", ops...) } func (o Opcodes) IMULL(ops ...Operand) { o.a.op("IMULL", ops...) } func (o Opcodes) Imulw(ops ...Operand) { o.a.op("IMULW", ops...) } func (o Opcodes) IMULW(ops ...Operand) { o.a.op("IMULW", ops...) } func (o Opcodes) Inb(ops ...Operand) { o.a.op("INB", ops...) } func (o Opcodes) INB(ops ...Operand) { o.a.op("INB", ops...) } func (o Opcodes) Inl(ops ...Operand) { o.a.op("INL", ops...) } func (o Opcodes) INL(ops ...Operand) { o.a.op("INL", ops...) } func (o Opcodes) Inw(ops ...Operand) { o.a.op("INW", ops...) } func (o Opcodes) INW(ops ...Operand) { o.a.op("INW", ops...) } func (o Opcodes) Incb(ops ...Operand) { o.a.op("INCB", ops...) } func (o Opcodes) INCB(ops ...Operand) { o.a.op("INCB", ops...) } func (o Opcodes) Incl(ops ...Operand) { o.a.op("INCL", ops...) } func (o Opcodes) INCL(ops ...Operand) { o.a.op("INCL", ops...) } func (o Opcodes) Incq(ops ...Operand) { o.a.op("INCQ", ops...) } func (o Opcodes) INCQ(ops ...Operand) { o.a.op("INCQ", ops...) } func (o Opcodes) Incw(ops ...Operand) { o.a.op("INCW", ops...) } func (o Opcodes) INCW(ops ...Operand) { o.a.op("INCW", ops...) } func (o Opcodes) Insb(ops ...Operand) { o.a.op("INSB", ops...) } func (o Opcodes) INSB(ops ...Operand) { o.a.op("INSB", ops...) } func (o Opcodes) Insl(ops ...Operand) { o.a.op("INSL", ops...) } func (o Opcodes) INSL(ops ...Operand) { o.a.op("INSL", ops...) } func (o Opcodes) Insw(ops ...Operand) { o.a.op("INSW", ops...) } func (o Opcodes) INSW(ops ...Operand) { o.a.op("INSW", ops...) } func (o Opcodes) Int(ops ...Operand) { o.a.op("INT", ops...) } func (o Opcodes) INT(ops ...Operand) { o.a.op("INT", ops...) } func (o Opcodes) Into(ops ...Operand) { o.a.op("INTO", ops...) } func (o Opcodes) INTO(ops ...Operand) { o.a.op("INTO", ops...) } func (o Opcodes) Iretl(ops ...Operand) { o.a.op("IRETL", ops...) } func (o Opcodes) IRETL(ops ...Operand) { o.a.op("IRETL", ops...) } func (o Opcodes) Iretw(ops ...Operand) { o.a.op("IRETW", ops...) } func (o Opcodes) IRETW(ops ...Operand) { o.a.op("IRETW", ops...) } func (o Opcodes) Jcc(ops ...Operand) { o.a.op("JCC", ops...) } func (o Opcodes) JCC(ops ...Operand) { o.a.op("JCC", ops...) } func (o Opcodes) Jcs(ops ...Operand) { o.a.op("JCS", ops...) } func (o Opcodes) JCS(ops ...Operand) { o.a.op("JCS", ops...) } func (o Opcodes) Jcxzl(ops ...Operand) { o.a.op("JCXZL", ops...) } func (o Opcodes) JCXZL(ops ...Operand) { o.a.op("JCXZL", ops...) } func (o Opcodes) Jeq(ops ...Operand) { o.a.op("JEQ", ops...) } func (o Opcodes) JEQ(ops ...Operand) { o.a.op("JEQ", ops...) } func (o Opcodes) Jge(ops ...Operand) { o.a.op("JGE", ops...) } func (o Opcodes) JGE(ops ...Operand) { o.a.op("JGE", ops...) } func (o Opcodes) Jgt(ops ...Operand) { o.a.op("JGT", ops...) } func (o Opcodes) JGT(ops ...Operand) { o.a.op("JGT", ops...) } func (o Opcodes) Jhi(ops ...Operand) { o.a.op("JHI", ops...) } func (o Opcodes) JHI(ops ...Operand) { o.a.op("JHI", ops...) } func (o Opcodes) Jle(ops ...Operand) { o.a.op("JLE", ops...) } func (o Opcodes) JLE(ops ...Operand) { o.a.op("JLE", ops...) } func (o Opcodes) Jls(ops ...Operand) { o.a.op("JLS", ops...) } func (o Opcodes) JLS(ops ...Operand) { o.a.op("JLS", ops...) } func (o Opcodes) Jlt(ops ...Operand) { o.a.op("JLT", ops...) } func (o Opcodes) JLT(ops ...Operand) { o.a.op("JLT", ops...) } func (o Opcodes) Jmi(ops ...Operand) { o.a.op("JMI", ops...) } func (o Opcodes) JMI(ops ...Operand) { o.a.op("JMI", ops...) } func (o Opcodes) Jne(ops ...Operand) { o.a.op("JNE", ops...) } func (o Opcodes) JNE(ops ...Operand) { o.a.op("JNE", ops...) } func (o Opcodes) Joc(ops ...Operand) { o.a.op("JOC", ops...) } func (o Opcodes) JOC(ops ...Operand) { o.a.op("JOC", ops...) } func (o Opcodes) Jos(ops ...Operand) { o.a.op("JOS", ops...) } func (o Opcodes) JOS(ops ...Operand) { o.a.op("JOS", ops...) } func (o Opcodes) Jpc(ops ...Operand) { o.a.op("JPC", ops...) } func (o Opcodes) JPC(ops ...Operand) { o.a.op("JPC", ops...) } func (o Opcodes) Jpl(ops ...Operand) { o.a.op("JPL", ops...) } func (o Opcodes) JPL(ops ...Operand) { o.a.op("JPL", ops...) } func (o Opcodes) Jps(ops ...Operand) { o.a.op("JPS", ops...) } func (o Opcodes) JPS(ops ...Operand) { o.a.op("JPS", ops...) } func (o Opcodes) Lahf(ops ...Operand) { o.a.op("LAHF", ops...) } func (o Opcodes) LAHF(ops ...Operand) { o.a.op("LAHF", ops...) } func (o Opcodes) Larl(ops ...Operand) { o.a.op("LARL", ops...) } func (o Opcodes) LARL(ops ...Operand) { o.a.op("LARL", ops...) } func (o Opcodes) Larw(ops ...Operand) { o.a.op("LARW", ops...) } func (o Opcodes) LARW(ops ...Operand) { o.a.op("LARW", ops...) } func (o Opcodes) Leal(ops ...Operand) { o.a.op("LEAL", ops...) } func (o Opcodes) LEAL(ops ...Operand) { o.a.op("LEAL", ops...) } func (o Opcodes) Leaw(ops ...Operand) { o.a.op("LEAW", ops...) } func (o Opcodes) LEAW(ops ...Operand) { o.a.op("LEAW", ops...) } func (o Opcodes) Leavel(ops ...Operand) { o.a.op("LEAVEL", ops...) } func (o Opcodes) LEAVEL(ops ...Operand) { o.a.op("LEAVEL", ops...) } func (o Opcodes) Leavew(ops ...Operand) { o.a.op("LEAVEW", ops...) } func (o Opcodes) LEAVEW(ops ...Operand) { o.a.op("LEAVEW", ops...) } func (o Opcodes) Lock(ops ...Operand) { o.a.op("LOCK", ops...) } func (o Opcodes) LOCK(ops ...Operand) { o.a.op("LOCK", ops...) } func (o Opcodes) Lodsb(ops ...Operand) { o.a.op("LODSB", ops...) } func (o Opcodes) LODSB(ops ...Operand) { o.a.op("LODSB", ops...) } func (o Opcodes) Lodsl(ops ...Operand) { o.a.op("LODSL", ops...) } func (o Opcodes) LODSL(ops ...Operand) { o.a.op("LODSL", ops...) } func (o Opcodes) Lodsw(ops ...Operand) { o.a.op("LODSW", ops...) } func (o Opcodes) LODSW(ops ...Operand) { o.a.op("LODSW", ops...) } func (o Opcodes) Long(ops ...Operand) { o.a.op("LONG", ops...) } func (o Opcodes) LONG(ops ...Operand) { o.a.op("LONG", ops...) } func (o Opcodes) Loop(ops ...Operand) { o.a.op("LOOP", ops...) } func (o Opcodes) LOOP(ops ...Operand) { o.a.op("LOOP", ops...) } func (o Opcodes) Loopeq(ops ...Operand) { o.a.op("LOOPEQ", ops...) } func (o Opcodes) LOOPEQ(ops ...Operand) { o.a.op("LOOPEQ", ops...) } func (o Opcodes) Loopne(ops ...Operand) { o.a.op("LOOPNE", ops...) } func (o Opcodes) LOOPNE(ops ...Operand) { o.a.op("LOOPNE", ops...) } func (o Opcodes) Lsll(ops ...Operand) { o.a.op("LSLL", ops...) } func (o Opcodes) LSLL(ops ...Operand) { o.a.op("LSLL", ops...) } func (o Opcodes) Lslw(ops ...Operand) { o.a.op("LSLW", ops...) } func (o Opcodes) LSLW(ops ...Operand) { o.a.op("LSLW", ops...) } func (o Opcodes) Movb(ops ...Operand) { o.a.op("MOVB", ops...) } func (o Opcodes) MOVB(ops ...Operand) { o.a.op("MOVB", ops...) } func (o Opcodes) Movl(ops ...Operand) { o.a.op("MOVL", ops...) } func (o Opcodes) MOVL(ops ...Operand) { o.a.op("MOVL", ops...) } func (o Opcodes) Movw(ops ...Operand) { o.a.op("MOVW", ops...) } func (o Opcodes) MOVW(ops ...Operand) { o.a.op("MOVW", ops...) } func (o Opcodes) Movblsx(ops ...Operand) { o.a.op("MOVBLSX", ops...) } func (o Opcodes) MOVBLSX(ops ...Operand) { o.a.op("MOVBLSX", ops...) } func (o Opcodes) Movblzx(ops ...Operand) { o.a.op("MOVBLZX", ops...) } func (o Opcodes) MOVBLZX(ops ...Operand) { o.a.op("MOVBLZX", ops...) } func (o Opcodes) Movbqsx(ops ...Operand) { o.a.op("MOVBQSX", ops...) } func (o Opcodes) MOVBQSX(ops ...Operand) { o.a.op("MOVBQSX", ops...) } func (o Opcodes) Movbqzx(ops ...Operand) { o.a.op("MOVBQZX", ops...) } func (o Opcodes) MOVBQZX(ops ...Operand) { o.a.op("MOVBQZX", ops...) } func (o Opcodes) Movbwsx(ops ...Operand) { o.a.op("MOVBWSX", ops...) } func (o Opcodes) MOVBWSX(ops ...Operand) { o.a.op("MOVBWSX", ops...) } func (o Opcodes) Movbwzx(ops ...Operand) { o.a.op("MOVBWZX", ops...) } func (o Opcodes) MOVBWZX(ops ...Operand) { o.a.op("MOVBWZX", ops...) } func (o Opcodes) Movwlsx(ops ...Operand) { o.a.op("MOVWLSX", ops...) } func (o Opcodes) MOVWLSX(ops ...Operand) { o.a.op("MOVWLSX", ops...) } func (o Opcodes) Movwlzx(ops ...Operand) { o.a.op("MOVWLZX", ops...) } func (o Opcodes) MOVWLZX(ops ...Operand) { o.a.op("MOVWLZX", ops...) } func (o Opcodes) Movwqsx(ops ...Operand) { o.a.op("MOVWQSX", ops...) } func (o Opcodes) MOVWQSX(ops ...Operand) { o.a.op("MOVWQSX", ops...) } func (o Opcodes) Movwqzx(ops ...Operand) { o.a.op("MOVWQZX", ops...) } func (o Opcodes) MOVWQZX(ops ...Operand) { o.a.op("MOVWQZX", ops...) } func (o Opcodes) Movsb(ops ...Operand) { o.a.op("MOVSB", ops...) } func (o Opcodes) MOVSB(ops ...Operand) { o.a.op("MOVSB", ops...) } func (o Opcodes) Movsl(ops ...Operand) { o.a.op("MOVSL", ops...) } func (o Opcodes) MOVSL(ops ...Operand) { o.a.op("MOVSL", ops...) } func (o Opcodes) Movsw(ops ...Operand) { o.a.op("MOVSW", ops...) } func (o Opcodes) MOVSW(ops ...Operand) { o.a.op("MOVSW", ops...) } func (o Opcodes) Mulb(ops ...Operand) { o.a.op("MULB", ops...) } func (o Opcodes) MULB(ops ...Operand) { o.a.op("MULB", ops...) } func (o Opcodes) Mull(ops ...Operand) { o.a.op("MULL", ops...) } func (o Opcodes) MULL(ops ...Operand) { o.a.op("MULL", ops...) } func (o Opcodes) Mulw(ops ...Operand) { o.a.op("MULW", ops...) } func (o Opcodes) MULW(ops ...Operand) { o.a.op("MULW", ops...) } func (o Opcodes) Negb(ops ...Operand) { o.a.op("NEGB", ops...) } func (o Opcodes) NEGB(ops ...Operand) { o.a.op("NEGB", ops...) } func (o Opcodes) Negl(ops ...Operand) { o.a.op("NEGL", ops...) } func (o Opcodes) NEGL(ops ...Operand) { o.a.op("NEGL", ops...) } func (o Opcodes) Negw(ops ...Operand) { o.a.op("NEGW", ops...) } func (o Opcodes) NEGW(ops ...Operand) { o.a.op("NEGW", ops...) } func (o Opcodes) Notb(ops ...Operand) { o.a.op("NOTB", ops...) } func (o Opcodes) NOTB(ops ...Operand) { o.a.op("NOTB", ops...) } func (o Opcodes) Notl(ops ...Operand) { o.a.op("NOTL", ops...) } func (o Opcodes) NOTL(ops ...Operand) { o.a.op("NOTL", ops...) } func (o Opcodes) Notw(ops ...Operand) { o.a.op("NOTW", ops...) } func (o Opcodes) NOTW(ops ...Operand) { o.a.op("NOTW", ops...) } func (o Opcodes) Orb(ops ...Operand) { o.a.op("ORB", ops...) } func (o Opcodes) ORB(ops ...Operand) { o.a.op("ORB", ops...) } func (o Opcodes) Orl(ops ...Operand) { o.a.op("ORL", ops...) } func (o Opcodes) ORL(ops ...Operand) { o.a.op("ORL", ops...) } func (o Opcodes) Orw(ops ...Operand) { o.a.op("ORW", ops...) } func (o Opcodes) ORW(ops ...Operand) { o.a.op("ORW", ops...) } func (o Opcodes) Outb(ops ...Operand) { o.a.op("OUTB", ops...) } func (o Opcodes) OUTB(ops ...Operand) { o.a.op("OUTB", ops...) } func (o Opcodes) Outl(ops ...Operand) { o.a.op("OUTL", ops...) } func (o Opcodes) OUTL(ops ...Operand) { o.a.op("OUTL", ops...) } func (o Opcodes) Outw(ops ...Operand) { o.a.op("OUTW", ops...) } func (o Opcodes) OUTW(ops ...Operand) { o.a.op("OUTW", ops...) } func (o Opcodes) Outsb(ops ...Operand) { o.a.op("OUTSB", ops...) } func (o Opcodes) OUTSB(ops ...Operand) { o.a.op("OUTSB", ops...) } func (o Opcodes) Outsl(ops ...Operand) { o.a.op("OUTSL", ops...) } func (o Opcodes) OUTSL(ops ...Operand) { o.a.op("OUTSL", ops...) } func (o Opcodes) Outsw(ops ...Operand) { o.a.op("OUTSW", ops...) } func (o Opcodes) OUTSW(ops ...Operand) { o.a.op("OUTSW", ops...) } func (o Opcodes) Pause(ops ...Operand) { o.a.op("PAUSE", ops...) } func (o Opcodes) PAUSE(ops ...Operand) { o.a.op("PAUSE", ops...) } func (o Opcodes) Popal(ops ...Operand) { o.a.op("POPAL", ops...) } func (o Opcodes) POPAL(ops ...Operand) { o.a.op("POPAL", ops...) } func (o Opcodes) Popaw(ops ...Operand) { o.a.op("POPAW", ops...) } func (o Opcodes) POPAW(ops ...Operand) { o.a.op("POPAW", ops...) } func (o Opcodes) Popcntw(ops ...Operand) { o.a.op("POPCNTW", ops...) } func (o Opcodes) POPCNTW(ops ...Operand) { o.a.op("POPCNTW", ops...) } func (o Opcodes) Popcntl(ops ...Operand) { o.a.op("POPCNTL", ops...) } func (o Opcodes) POPCNTL(ops ...Operand) { o.a.op("POPCNTL", ops...) } func (o Opcodes) Popcntq(ops ...Operand) { o.a.op("POPCNTQ", ops...) } func (o Opcodes) POPCNTQ(ops ...Operand) { o.a.op("POPCNTQ", ops...) } func (o Opcodes) Popfl(ops ...Operand) { o.a.op("POPFL", ops...) } func (o Opcodes) POPFL(ops ...Operand) { o.a.op("POPFL", ops...) } func (o Opcodes) Popfw(ops ...Operand) { o.a.op("POPFW", ops...) } func (o Opcodes) POPFW(ops ...Operand) { o.a.op("POPFW", ops...) } func (o Opcodes) Popl(ops ...Operand) { o.a.op("POPL", ops...) } func (o Opcodes) POPL(ops ...Operand) { o.a.op("POPL", ops...) } func (o Opcodes) Popw(ops ...Operand) { o.a.op("POPW", ops...) } func (o Opcodes) POPW(ops ...Operand) { o.a.op("POPW", ops...) } func (o Opcodes) Pushal(ops ...Operand) { o.a.op("PUSHAL", ops...) } func (o Opcodes) PUSHAL(ops ...Operand) { o.a.op("PUSHAL", ops...) } func (o Opcodes) Pushaw(ops ...Operand) { o.a.op("PUSHAW", ops...) } func (o Opcodes) PUSHAW(ops ...Operand) { o.a.op("PUSHAW", ops...) } func (o Opcodes) Pushfl(ops ...Operand) { o.a.op("PUSHFL", ops...) } func (o Opcodes) PUSHFL(ops ...Operand) { o.a.op("PUSHFL", ops...) } func (o Opcodes) Pushfw(ops ...Operand) { o.a.op("PUSHFW", ops...) } func (o Opcodes) PUSHFW(ops ...Operand) { o.a.op("PUSHFW", ops...) } func (o Opcodes) Pushl(ops ...Operand) { o.a.op("PUSHL", ops...) } func (o Opcodes) PUSHL(ops ...Operand) { o.a.op("PUSHL", ops...) } func (o Opcodes) Pushw(ops ...Operand) { o.a.op("PUSHW", ops...) } func (o Opcodes) PUSHW(ops ...Operand) { o.a.op("PUSHW", ops...) } func (o Opcodes) Rclb(ops ...Operand) { o.a.op("RCLB", ops...) } func (o Opcodes) RCLB(ops ...Operand) { o.a.op("RCLB", ops...) } func (o Opcodes) Rcll(ops ...Operand) { o.a.op("RCLL", ops...) } func (o Opcodes) RCLL(ops ...Operand) { o.a.op("RCLL", ops...) } func (o Opcodes) Rclw(ops ...Operand) { o.a.op("RCLW", ops...) } func (o Opcodes) RCLW(ops ...Operand) { o.a.op("RCLW", ops...) } func (o Opcodes) Rcrb(ops ...Operand) { o.a.op("RCRB", ops...) } func (o Opcodes) RCRB(ops ...Operand) { o.a.op("RCRB", ops...) } func (o Opcodes) Rcrl(ops ...Operand) { o.a.op("RCRL", ops...) } func (o Opcodes) RCRL(ops ...Operand) { o.a.op("RCRL", ops...) } func (o Opcodes) Rcrw(ops ...Operand) { o.a.op("RCRW", ops...) } func (o Opcodes) RCRW(ops ...Operand) { o.a.op("RCRW", ops...) } func (o Opcodes) Rep(ops ...Operand) { o.a.op("REP", ops...) } func (o Opcodes) REP(ops ...Operand) { o.a.op("REP", ops...) } func (o Opcodes) Repn(ops ...Operand) { o.a.op("REPN", ops...) } func (o Opcodes) REPN(ops ...Operand) { o.a.op("REPN", ops...) } func (o Opcodes) Rolb(ops ...Operand) { o.a.op("ROLB", ops...) } func (o Opcodes) ROLB(ops ...Operand) { o.a.op("ROLB", ops...) } func (o Opcodes) Roll(ops ...Operand) { o.a.op("ROLL", ops...) } func (o Opcodes) ROLL(ops ...Operand) { o.a.op("ROLL", ops...) } func (o Opcodes) Rolw(ops ...Operand) { o.a.op("ROLW", ops...) } func (o Opcodes) ROLW(ops ...Operand) { o.a.op("ROLW", ops...) } func (o Opcodes) Rorb(ops ...Operand) { o.a.op("RORB", ops...) } func (o Opcodes) RORB(ops ...Operand) { o.a.op("RORB", ops...) } func (o Opcodes) Rorl(ops ...Operand) { o.a.op("RORL", ops...) } func (o Opcodes) RORL(ops ...Operand) { o.a.op("RORL", ops...) } func (o Opcodes) Rorw(ops ...Operand) { o.a.op("RORW", ops...) } func (o Opcodes) RORW(ops ...Operand) { o.a.op("RORW", ops...) } func (o Opcodes) Sahf(ops ...Operand) { o.a.op("SAHF", ops...) } func (o Opcodes) SAHF(ops ...Operand) { o.a.op("SAHF", ops...) } func (o Opcodes) Salb(ops ...Operand) { o.a.op("SALB", ops...) } func (o Opcodes) SALB(ops ...Operand) { o.a.op("SALB", ops...) } func (o Opcodes) Sall(ops ...Operand) { o.a.op("SALL", ops...) } func (o Opcodes) SALL(ops ...Operand) { o.a.op("SALL", ops...) } func (o Opcodes) Salw(ops ...Operand) { o.a.op("SALW", ops...) } func (o Opcodes) SALW(ops ...Operand) { o.a.op("SALW", ops...) } func (o Opcodes) Sarb(ops ...Operand) { o.a.op("SARB", ops...) } func (o Opcodes) SARB(ops ...Operand) { o.a.op("SARB", ops...) } func (o Opcodes) Sarl(ops ...Operand) { o.a.op("SARL", ops...) } func (o Opcodes) SARL(ops ...Operand) { o.a.op("SARL", ops...) } func (o Opcodes) Sarw(ops ...Operand) { o.a.op("SARW", ops...) } func (o Opcodes) SARW(ops ...Operand) { o.a.op("SARW", ops...) } func (o Opcodes) Sbbb(ops ...Operand) { o.a.op("SBBB", ops...) } func (o Opcodes) SBBB(ops ...Operand) { o.a.op("SBBB", ops...) } func (o Opcodes) Sbbl(ops ...Operand) { o.a.op("SBBL", ops...) } func (o Opcodes) SBBL(ops ...Operand) { o.a.op("SBBL", ops...) } func (o Opcodes) Sbbw(ops ...Operand) { o.a.op("SBBW", ops...) } func (o Opcodes) SBBW(ops ...Operand) { o.a.op("SBBW", ops...) } func (o Opcodes) Scasb(ops ...Operand) { o.a.op("SCASB", ops...) } func (o Opcodes) SCASB(ops ...Operand) { o.a.op("SCASB", ops...) } func (o Opcodes) Scasl(ops ...Operand) { o.a.op("SCASL", ops...) } func (o Opcodes) SCASL(ops ...Operand) { o.a.op("SCASL", ops...) } func (o Opcodes) Scasw(ops ...Operand) { o.a.op("SCASW", ops...) } func (o Opcodes) SCASW(ops ...Operand) { o.a.op("SCASW", ops...) } func (o Opcodes) Setcc(ops ...Operand) { o.a.op("SETCC", ops...) } func (o Opcodes) SETCC(ops ...Operand) { o.a.op("SETCC", ops...) } func (o Opcodes) Setcs(ops ...Operand) { o.a.op("SETCS", ops...) } func (o Opcodes) SETCS(ops ...Operand) { o.a.op("SETCS", ops...) } func (o Opcodes) Seteq(ops ...Operand) { o.a.op("SETEQ", ops...) } func (o Opcodes) SETEQ(ops ...Operand) { o.a.op("SETEQ", ops...) } func (o Opcodes) Setge(ops ...Operand) { o.a.op("SETGE", ops...) } func (o Opcodes) SETGE(ops ...Operand) { o.a.op("SETGE", ops...) } func (o Opcodes) Setgt(ops ...Operand) { o.a.op("SETGT", ops...) } func (o Opcodes) SETGT(ops ...Operand) { o.a.op("SETGT", ops...) } func (o Opcodes) Sethi(ops ...Operand) { o.a.op("SETHI", ops...) } func (o Opcodes) SETHI(ops ...Operand) { o.a.op("SETHI", ops...) } func (o Opcodes) Setle(ops ...Operand) { o.a.op("SETLE", ops...) } func (o Opcodes) SETLE(ops ...Operand) { o.a.op("SETLE", ops...) } func (o Opcodes) Setls(ops ...Operand) { o.a.op("SETLS", ops...) } func (o Opcodes) SETLS(ops ...Operand) { o.a.op("SETLS", ops...) } func (o Opcodes) Setlt(ops ...Operand) { o.a.op("SETLT", ops...) } func (o Opcodes) SETLT(ops ...Operand) { o.a.op("SETLT", ops...) } func (o Opcodes) Setmi(ops ...Operand) { o.a.op("SETMI", ops...) } func (o Opcodes) SETMI(ops ...Operand) { o.a.op("SETMI", ops...) } func (o Opcodes) Setne(ops ...Operand) { o.a.op("SETNE", ops...) } func (o Opcodes) SETNE(ops ...Operand) { o.a.op("SETNE", ops...) } func (o Opcodes) Setoc(ops ...Operand) { o.a.op("SETOC", ops...) } func (o Opcodes) SETOC(ops ...Operand) { o.a.op("SETOC", ops...) } func (o Opcodes) Setos(ops ...Operand) { o.a.op("SETOS", ops...) } func (o Opcodes) SETOS(ops ...Operand) { o.a.op("SETOS", ops...) } func (o Opcodes) Setpc(ops ...Operand) { o.a.op("SETPC", ops...) } func (o Opcodes) SETPC(ops ...Operand) { o.a.op("SETPC", ops...) } func (o Opcodes) Setpl(ops ...Operand) { o.a.op("SETPL", ops...) } func (o Opcodes) SETPL(ops ...Operand) { o.a.op("SETPL", ops...) } func (o Opcodes) Setps(ops ...Operand) { o.a.op("SETPS", ops...) } func (o Opcodes) SETPS(ops ...Operand) { o.a.op("SETPS", ops...) } func (o Opcodes) Cdq(ops ...Operand) { o.a.op("CDQ", ops...) } func (o Opcodes) CDQ(ops ...Operand) { o.a.op("CDQ", ops...) } func (o Opcodes) Cwd(ops ...Operand) { o.a.op("CWD", ops...) } func (o Opcodes) CWD(ops ...Operand) { o.a.op("CWD", ops...) } func (o Opcodes) Shlb(ops ...Operand) { o.a.op("SHLB", ops...) } func (o Opcodes) SHLB(ops ...Operand) { o.a.op("SHLB", ops...) } func (o Opcodes) Shll(ops ...Operand) { o.a.op("SHLL", ops...) } func (o Opcodes) SHLL(ops ...Operand) { o.a.op("SHLL", ops...) } func (o Opcodes) Shlw(ops ...Operand) { o.a.op("SHLW", ops...) } func (o Opcodes) SHLW(ops ...Operand) { o.a.op("SHLW", ops...) } func (o Opcodes) Shrb(ops ...Operand) { o.a.op("SHRB", ops...) } func (o Opcodes) SHRB(ops ...Operand) { o.a.op("SHRB", ops...) } func (o Opcodes) Shrl(ops ...Operand) { o.a.op("SHRL", ops...) } func (o Opcodes) SHRL(ops ...Operand) { o.a.op("SHRL", ops...) } func (o Opcodes) Shrw(ops ...Operand) { o.a.op("SHRW", ops...) } func (o Opcodes) SHRW(ops ...Operand) { o.a.op("SHRW", ops...) } func (o Opcodes) Stc(ops ...Operand) { o.a.op("STC", ops...) } func (o Opcodes) STC(ops ...Operand) { o.a.op("STC", ops...) } func (o Opcodes) Std(ops ...Operand) { o.a.op("STD", ops...) } func (o Opcodes) STD(ops ...Operand) { o.a.op("STD", ops...) } func (o Opcodes) Sti(ops ...Operand) { o.a.op("STI", ops...) } func (o Opcodes) STI(ops ...Operand) { o.a.op("STI", ops...) } func (o Opcodes) Stosb(ops ...Operand) { o.a.op("STOSB", ops...) } func (o Opcodes) STOSB(ops ...Operand) { o.a.op("STOSB", ops...) } func (o Opcodes) Stosl(ops ...Operand) { o.a.op("STOSL", ops...) } func (o Opcodes) STOSL(ops ...Operand) { o.a.op("STOSL", ops...) } func (o Opcodes) Stosw(ops ...Operand) { o.a.op("STOSW", ops...) } func (o Opcodes) STOSW(ops ...Operand) { o.a.op("STOSW", ops...) } func (o Opcodes) Subb(ops ...Operand) { o.a.op("SUBB", ops...) } func (o Opcodes) SUBB(ops ...Operand) { o.a.op("SUBB", ops...) } func (o Opcodes) Subl(ops ...Operand) { o.a.op("SUBL", ops...) } func (o Opcodes) SUBL(ops ...Operand) { o.a.op("SUBL", ops...) } func (o Opcodes) Subw(ops ...Operand) { o.a.op("SUBW", ops...) } func (o Opcodes) SUBW(ops ...Operand) { o.a.op("SUBW", ops...) } func (o Opcodes) Syscall(ops ...Operand) { o.a.op("SYSCALL", ops...) } func (o Opcodes) SYSCALL(ops ...Operand) { o.a.op("SYSCALL", ops...) } func (o Opcodes) Testb(ops ...Operand) { o.a.op("TESTB", ops...) } func (o Opcodes) TESTB(ops ...Operand) { o.a.op("TESTB", ops...) } func (o Opcodes) Testl(ops ...Operand) { o.a.op("TESTL", ops...) } func (o Opcodes) TESTL(ops ...Operand) { o.a.op("TESTL", ops...) } func (o Opcodes) Testw(ops ...Operand) { o.a.op("TESTW", ops...) } func (o Opcodes) TESTW(ops ...Operand) { o.a.op("TESTW", ops...) } func (o Opcodes) Verr(ops ...Operand) { o.a.op("VERR", ops...) } func (o Opcodes) VERR(ops ...Operand) { o.a.op("VERR", ops...) } func (o Opcodes) Verw(ops ...Operand) { o.a.op("VERW", ops...) } func (o Opcodes) VERW(ops ...Operand) { o.a.op("VERW", ops...) } func (o Opcodes) Wait(ops ...Operand) { o.a.op("WAIT", ops...) } func (o Opcodes) WAIT(ops ...Operand) { o.a.op("WAIT", ops...) } func (o Opcodes) Word(ops ...Operand) { o.a.op("WORD", ops...) } func (o Opcodes) WORD(ops ...Operand) { o.a.op("WORD", ops...) } func (o Opcodes) Xchgb(ops ...Operand) { o.a.op("XCHGB", ops...) } func (o Opcodes) XCHGB(ops ...Operand) { o.a.op("XCHGB", ops...) } func (o Opcodes) Xchgl(ops ...Operand) { o.a.op("XCHGL", ops...) } func (o Opcodes) XCHGL(ops ...Operand) { o.a.op("XCHGL", ops...) } func (o Opcodes) Xchgw(ops ...Operand) { o.a.op("XCHGW", ops...) } func (o Opcodes) XCHGW(ops ...Operand) { o.a.op("XCHGW", ops...) } func (o Opcodes) Xlat(ops ...Operand) { o.a.op("XLAT", ops...) } func (o Opcodes) XLAT(ops ...Operand) { o.a.op("XLAT", ops...) } func (o Opcodes) Xorb(ops ...Operand) { o.a.op("XORB", ops...) } func (o Opcodes) XORB(ops ...Operand) { o.a.op("XORB", ops...) } func (o Opcodes) Xorl(ops ...Operand) { o.a.op("XORL", ops...) } func (o Opcodes) XORL(ops ...Operand) { o.a.op("XORL", ops...) } func (o Opcodes) Xorw(ops ...Operand) { o.a.op("XORW", ops...) } func (o Opcodes) XORW(ops ...Operand) { o.a.op("XORW", ops...) } func (o Opcodes) Fmovb(ops ...Operand) { o.a.op("FMOVB", ops...) } func (o Opcodes) FMOVB(ops ...Operand) { o.a.op("FMOVB", ops...) } func (o Opcodes) Fmovbp(ops ...Operand) { o.a.op("FMOVBP", ops...) } func (o Opcodes) FMOVBP(ops ...Operand) { o.a.op("FMOVBP", ops...) } func (o Opcodes) Fmovd(ops ...Operand) { o.a.op("FMOVD", ops...) } func (o Opcodes) FMOVD(ops ...Operand) { o.a.op("FMOVD", ops...) } func (o Opcodes) Fmovdp(ops ...Operand) { o.a.op("FMOVDP", ops...) } func (o Opcodes) FMOVDP(ops ...Operand) { o.a.op("FMOVDP", ops...) } func (o Opcodes) Fmovf(ops ...Operand) { o.a.op("FMOVF", ops...) } func (o Opcodes) FMOVF(ops ...Operand) { o.a.op("FMOVF", ops...) } func (o Opcodes) Fmovfp(ops ...Operand) { o.a.op("FMOVFP", ops...) } func (o Opcodes) FMOVFP(ops ...Operand) { o.a.op("FMOVFP", ops...) } func (o Opcodes) Fmovl(ops ...Operand) { o.a.op("FMOVL", ops...) } func (o Opcodes) FMOVL(ops ...Operand) { o.a.op("FMOVL", ops...) } func (o Opcodes) Fmovlp(ops ...Operand) { o.a.op("FMOVLP", ops...) } func (o Opcodes) FMOVLP(ops ...Operand) { o.a.op("FMOVLP", ops...) } func (o Opcodes) Fmovv(ops ...Operand) { o.a.op("FMOVV", ops...) } func (o Opcodes) FMOVV(ops ...Operand) { o.a.op("FMOVV", ops...) } func (o Opcodes) Fmovvp(ops ...Operand) { o.a.op("FMOVVP", ops...) } func (o Opcodes) FMOVVP(ops ...Operand) { o.a.op("FMOVVP", ops...) } func (o Opcodes) Fmovw(ops ...Operand) { o.a.op("FMOVW", ops...) } func (o Opcodes) FMOVW(ops ...Operand) { o.a.op("FMOVW", ops...) } func (o Opcodes) Fmovwp(ops ...Operand) { o.a.op("FMOVWP", ops...) } func (o Opcodes) FMOVWP(ops ...Operand) { o.a.op("FMOVWP", ops...) } func (o Opcodes) Fmovx(ops ...Operand) { o.a.op("FMOVX", ops...) } func (o Opcodes) FMOVX(ops ...Operand) { o.a.op("FMOVX", ops...) } func (o Opcodes) Fmovxp(ops ...Operand) { o.a.op("FMOVXP", ops...) } func (o Opcodes) FMOVXP(ops ...Operand) { o.a.op("FMOVXP", ops...) } func (o Opcodes) Fcomd(ops ...Operand) { o.a.op("FCOMD", ops...) } func (o Opcodes) FCOMD(ops ...Operand) { o.a.op("FCOMD", ops...) } func (o Opcodes) Fcomdp(ops ...Operand) { o.a.op("FCOMDP", ops...) } func (o Opcodes) FCOMDP(ops ...Operand) { o.a.op("FCOMDP", ops...) } func (o Opcodes) Fcomdpp(ops ...Operand) { o.a.op("FCOMDPP", ops...) } func (o Opcodes) FCOMDPP(ops ...Operand) { o.a.op("FCOMDPP", ops...) } func (o Opcodes) Fcomf(ops ...Operand) { o.a.op("FCOMF", ops...) } func (o Opcodes) FCOMF(ops ...Operand) { o.a.op("FCOMF", ops...) } func (o Opcodes) Fcomfp(ops ...Operand) { o.a.op("FCOMFP", ops...) } func (o Opcodes) FCOMFP(ops ...Operand) { o.a.op("FCOMFP", ops...) } func (o Opcodes) Fcoml(ops ...Operand) { o.a.op("FCOML", ops...) } func (o Opcodes) FCOML(ops ...Operand) { o.a.op("FCOML", ops...) } func (o Opcodes) Fcomlp(ops ...Operand) { o.a.op("FCOMLP", ops...) } func (o Opcodes) FCOMLP(ops ...Operand) { o.a.op("FCOMLP", ops...) } func (o Opcodes) Fcomw(ops ...Operand) { o.a.op("FCOMW", ops...) } func (o Opcodes) FCOMW(ops ...Operand) { o.a.op("FCOMW", ops...) } func (o Opcodes) Fcomwp(ops ...Operand) { o.a.op("FCOMWP", ops...) } func (o Opcodes) FCOMWP(ops ...Operand) { o.a.op("FCOMWP", ops...) } func (o Opcodes) Fucom(ops ...Operand) { o.a.op("FUCOM", ops...) } func (o Opcodes) FUCOM(ops ...Operand) { o.a.op("FUCOM", ops...) } func (o Opcodes) Fucomp(ops ...Operand) { o.a.op("FUCOMP", ops...) } func (o Opcodes) FUCOMP(ops ...Operand) { o.a.op("FUCOMP", ops...) } func (o Opcodes) Fucompp(ops ...Operand) { o.a.op("FUCOMPP", ops...) } func (o Opcodes) FUCOMPP(ops ...Operand) { o.a.op("FUCOMPP", ops...) } func (o Opcodes) Fadddp(ops ...Operand) { o.a.op("FADDDP", ops...) } func (o Opcodes) FADDDP(ops ...Operand) { o.a.op("FADDDP", ops...) } func (o Opcodes) Faddw(ops ...Operand) { o.a.op("FADDW", ops...) } func (o Opcodes) FADDW(ops ...Operand) { o.a.op("FADDW", ops...) } func (o Opcodes) Faddl(ops ...Operand) { o.a.op("FADDL", ops...) } func (o Opcodes) FADDL(ops ...Operand) { o.a.op("FADDL", ops...) } func (o Opcodes) Faddf(ops ...Operand) { o.a.op("FADDF", ops...) } func (o Opcodes) FADDF(ops ...Operand) { o.a.op("FADDF", ops...) } func (o Opcodes) Faddd(ops ...Operand) { o.a.op("FADDD", ops...) } func (o Opcodes) FADDD(ops ...Operand) { o.a.op("FADDD", ops...) } func (o Opcodes) Fmuldp(ops ...Operand) { o.a.op("FMULDP", ops...) } func (o Opcodes) FMULDP(ops ...Operand) { o.a.op("FMULDP", ops...) } func (o Opcodes) Fmulw(ops ...Operand) { o.a.op("FMULW", ops...) } func (o Opcodes) FMULW(ops ...Operand) { o.a.op("FMULW", ops...) } func (o Opcodes) Fmull(ops ...Operand) { o.a.op("FMULL", ops...) } func (o Opcodes) FMULL(ops ...Operand) { o.a.op("FMULL", ops...) } func (o Opcodes) Fmulf(ops ...Operand) { o.a.op("FMULF", ops...) } func (o Opcodes) FMULF(ops ...Operand) { o.a.op("FMULF", ops...) } func (o Opcodes) Fmuld(ops ...Operand) { o.a.op("FMULD", ops...) } func (o Opcodes) FMULD(ops ...Operand) { o.a.op("FMULD", ops...) } func (o Opcodes) Fsubdp(ops ...Operand) { o.a.op("FSUBDP", ops...) } func (o Opcodes) FSUBDP(ops ...Operand) { o.a.op("FSUBDP", ops...) } func (o Opcodes) Fsubw(ops ...Operand) { o.a.op("FSUBW", ops...) } func (o Opcodes) FSUBW(ops ...Operand) { o.a.op("FSUBW", ops...) } func (o Opcodes) Fsubl(ops ...Operand) { o.a.op("FSUBL", ops...) } func (o Opcodes) FSUBL(ops ...Operand) { o.a.op("FSUBL", ops...) } func (o Opcodes) Fsubf(ops ...Operand) { o.a.op("FSUBF", ops...) } func (o Opcodes) FSUBF(ops ...Operand) { o.a.op("FSUBF", ops...) } func (o Opcodes) Fsubd(ops ...Operand) { o.a.op("FSUBD", ops...) } func (o Opcodes) FSUBD(ops ...Operand) { o.a.op("FSUBD", ops...) } func (o Opcodes) Fsubrdp(ops ...Operand) { o.a.op("FSUBRDP", ops...) } func (o Opcodes) FSUBRDP(ops ...Operand) { o.a.op("FSUBRDP", ops...) } func (o Opcodes) Fsubrw(ops ...Operand) { o.a.op("FSUBRW", ops...) } func (o Opcodes) FSUBRW(ops ...Operand) { o.a.op("FSUBRW", ops...) } func (o Opcodes) Fsubrl(ops ...Operand) { o.a.op("FSUBRL", ops...) } func (o Opcodes) FSUBRL(ops ...Operand) { o.a.op("FSUBRL", ops...) } func (o Opcodes) Fsubrf(ops ...Operand) { o.a.op("FSUBRF", ops...) } func (o Opcodes) FSUBRF(ops ...Operand) { o.a.op("FSUBRF", ops...) } func (o Opcodes) Fsubrd(ops ...Operand) { o.a.op("FSUBRD", ops...) } func (o Opcodes) FSUBRD(ops ...Operand) { o.a.op("FSUBRD", ops...) } func (o Opcodes) Fdivdp(ops ...Operand) { o.a.op("FDIVDP", ops...) } func (o Opcodes) FDIVDP(ops ...Operand) { o.a.op("FDIVDP", ops...) } func (o Opcodes) Fdivw(ops ...Operand) { o.a.op("FDIVW", ops...) } func (o Opcodes) FDIVW(ops ...Operand) { o.a.op("FDIVW", ops...) } func (o Opcodes) Fdivl(ops ...Operand) { o.a.op("FDIVL", ops...) } func (o Opcodes) FDIVL(ops ...Operand) { o.a.op("FDIVL", ops...) } func (o Opcodes) Fdivf(ops ...Operand) { o.a.op("FDIVF", ops...) } func (o Opcodes) FDIVF(ops ...Operand) { o.a.op("FDIVF", ops...) } func (o Opcodes) Fdivd(ops ...Operand) { o.a.op("FDIVD", ops...) } func (o Opcodes) FDIVD(ops ...Operand) { o.a.op("FDIVD", ops...) } func (o Opcodes) Fdivrdp(ops ...Operand) { o.a.op("FDIVRDP", ops...) } func (o Opcodes) FDIVRDP(ops ...Operand) { o.a.op("FDIVRDP", ops...) } func (o Opcodes) Fdivrw(ops ...Operand) { o.a.op("FDIVRW", ops...) } func (o Opcodes) FDIVRW(ops ...Operand) { o.a.op("FDIVRW", ops...) } func (o Opcodes) Fdivrl(ops ...Operand) { o.a.op("FDIVRL", ops...) } func (o Opcodes) FDIVRL(ops ...Operand) { o.a.op("FDIVRL", ops...) } func (o Opcodes) Fdivrf(ops ...Operand) { o.a.op("FDIVRF", ops...) } func (o Opcodes) FDIVRF(ops ...Operand) { o.a.op("FDIVRF", ops...) } func (o Opcodes) Fdivrd(ops ...Operand) { o.a.op("FDIVRD", ops...) } func (o Opcodes) FDIVRD(ops ...Operand) { o.a.op("FDIVRD", ops...) } func (o Opcodes) Fxchd(ops ...Operand) { o.a.op("FXCHD", ops...) } func (o Opcodes) FXCHD(ops ...Operand) { o.a.op("FXCHD", ops...) } func (o Opcodes) Ffree(ops ...Operand) { o.a.op("FFREE", ops...) } func (o Opcodes) FFREE(ops ...Operand) { o.a.op("FFREE", ops...) } func (o Opcodes) Fldcw(ops ...Operand) { o.a.op("FLDCW", ops...) } func (o Opcodes) FLDCW(ops ...Operand) { o.a.op("FLDCW", ops...) } func (o Opcodes) Fldenv(ops ...Operand) { o.a.op("FLDENV", ops...) } func (o Opcodes) FLDENV(ops ...Operand) { o.a.op("FLDENV", ops...) } func (o Opcodes) Frstor(ops ...Operand) { o.a.op("FRSTOR", ops...) } func (o Opcodes) FRSTOR(ops ...Operand) { o.a.op("FRSTOR", ops...) } func (o Opcodes) Fsave(ops ...Operand) { o.a.op("FSAVE", ops...) } func (o Opcodes) FSAVE(ops ...Operand) { o.a.op("FSAVE", ops...) } func (o Opcodes) Fstcw(ops ...Operand) { o.a.op("FSTCW", ops...) } func (o Opcodes) FSTCW(ops ...Operand) { o.a.op("FSTCW", ops...) } func (o Opcodes) Fstenv(ops ...Operand) { o.a.op("FSTENV", ops...) } func (o Opcodes) FSTENV(ops ...Operand) { o.a.op("FSTENV", ops...) } func (o Opcodes) Fstsw(ops ...Operand) { o.a.op("FSTSW", ops...) } func (o Opcodes) FSTSW(ops ...Operand) { o.a.op("FSTSW", ops...) } func (o Opcodes) F2xm1(ops ...Operand) { o.a.op("F2XM1", ops...) } func (o Opcodes) F2XM1(ops ...Operand) { o.a.op("F2XM1", ops...) } func (o Opcodes) Fabs(ops ...Operand) { o.a.op("FABS", ops...) } func (o Opcodes) FABS(ops ...Operand) { o.a.op("FABS", ops...) } func (o Opcodes) Fchs(ops ...Operand) { o.a.op("FCHS", ops...) } func (o Opcodes) FCHS(ops ...Operand) { o.a.op("FCHS", ops...) } func (o Opcodes) Fclex(ops ...Operand) { o.a.op("FCLEX", ops...) } func (o Opcodes) FCLEX(ops ...Operand) { o.a.op("FCLEX", ops...) } func (o Opcodes) Fcos(ops ...Operand) { o.a.op("FCOS", ops...) } func (o Opcodes) FCOS(ops ...Operand) { o.a.op("FCOS", ops...) } func (o Opcodes) Fdecstp(ops ...Operand) { o.a.op("FDECSTP", ops...) } func (o Opcodes) FDECSTP(ops ...Operand) { o.a.op("FDECSTP", ops...) } func (o Opcodes) Fincstp(ops ...Operand) { o.a.op("FINCSTP", ops...) } func (o Opcodes) FINCSTP(ops ...Operand) { o.a.op("FINCSTP", ops...) } func (o Opcodes) Finit(ops ...Operand) { o.a.op("FINIT", ops...) } func (o Opcodes) FINIT(ops ...Operand) { o.a.op("FINIT", ops...) } func (o Opcodes) Fld1(ops ...Operand) { o.a.op("FLD1", ops...) } func (o Opcodes) FLD1(ops ...Operand) { o.a.op("FLD1", ops...) } func (o Opcodes) Fldl2e(ops ...Operand) { o.a.op("FLDL2E", ops...) } func (o Opcodes) FLDL2E(ops ...Operand) { o.a.op("FLDL2E", ops...) } func (o Opcodes) Fldl2t(ops ...Operand) { o.a.op("FLDL2T", ops...) } func (o Opcodes) FLDL2T(ops ...Operand) { o.a.op("FLDL2T", ops...) } func (o Opcodes) Fldlg2(ops ...Operand) { o.a.op("FLDLG2", ops...) } func (o Opcodes) FLDLG2(ops ...Operand) { o.a.op("FLDLG2", ops...) } func (o Opcodes) Fldln2(ops ...Operand) { o.a.op("FLDLN2", ops...) } func (o Opcodes) FLDLN2(ops ...Operand) { o.a.op("FLDLN2", ops...) } func (o Opcodes) Fldpi(ops ...Operand) { o.a.op("FLDPI", ops...) } func (o Opcodes) FLDPI(ops ...Operand) { o.a.op("FLDPI", ops...) } func (o Opcodes) Fldz(ops ...Operand) { o.a.op("FLDZ", ops...) } func (o Opcodes) FLDZ(ops ...Operand) { o.a.op("FLDZ", ops...) } func (o Opcodes) Fnop(ops ...Operand) { o.a.op("FNOP", ops...) } func (o Opcodes) FNOP(ops ...Operand) { o.a.op("FNOP", ops...) } func (o Opcodes) Fpatan(ops ...Operand) { o.a.op("FPATAN", ops...) } func (o Opcodes) FPATAN(ops ...Operand) { o.a.op("FPATAN", ops...) } func (o Opcodes) Fprem(ops ...Operand) { o.a.op("FPREM", ops...) } func (o Opcodes) FPREM(ops ...Operand) { o.a.op("FPREM", ops...) } func (o Opcodes) Fprem1(ops ...Operand) { o.a.op("FPREM1", ops...) } func (o Opcodes) FPREM1(ops ...Operand) { o.a.op("FPREM1", ops...) } func (o Opcodes) Fptan(ops ...Operand) { o.a.op("FPTAN", ops...) } func (o Opcodes) FPTAN(ops ...Operand) { o.a.op("FPTAN", ops...) } func (o Opcodes) Frndint(ops ...Operand) { o.a.op("FRNDINT", ops...) } func (o Opcodes) FRNDINT(ops ...Operand) { o.a.op("FRNDINT", ops...) } func (o Opcodes) Fscale(ops ...Operand) { o.a.op("FSCALE", ops...) } func (o Opcodes) FSCALE(ops ...Operand) { o.a.op("FSCALE", ops...) } func (o Opcodes) Fsin(ops ...Operand) { o.a.op("FSIN", ops...) } func (o Opcodes) FSIN(ops ...Operand) { o.a.op("FSIN", ops...) } func (o Opcodes) Fsincos(ops ...Operand) { o.a.op("FSINCOS", ops...) } func (o Opcodes) FSINCOS(ops ...Operand) { o.a.op("FSINCOS", ops...) } func (o Opcodes) Fsqrt(ops ...Operand) { o.a.op("FSQRT", ops...) } func (o Opcodes) FSQRT(ops ...Operand) { o.a.op("FSQRT", ops...) } func (o Opcodes) Ftst(ops ...Operand) { o.a.op("FTST", ops...) } func (o Opcodes) FTST(ops ...Operand) { o.a.op("FTST", ops...) } func (o Opcodes) Fxam(ops ...Operand) { o.a.op("FXAM", ops...) } func (o Opcodes) FXAM(ops ...Operand) { o.a.op("FXAM", ops...) } func (o Opcodes) Fxtract(ops ...Operand) { o.a.op("FXTRACT", ops...) } func (o Opcodes) FXTRACT(ops ...Operand) { o.a.op("FXTRACT", ops...) } func (o Opcodes) Fyl2x(ops ...Operand) { o.a.op("FYL2X", ops...) } func (o Opcodes) FYL2X(ops ...Operand) { o.a.op("FYL2X", ops...) } func (o Opcodes) Fyl2xp1(ops ...Operand) { o.a.op("FYL2XP1", ops...) } func (o Opcodes) FYL2XP1(ops ...Operand) { o.a.op("FYL2XP1", ops...) } func (o Opcodes) Cmpxchgb(ops ...Operand) { o.a.op("CMPXCHGB", ops...) } func (o Opcodes) CMPXCHGB(ops ...Operand) { o.a.op("CMPXCHGB", ops...) } func (o Opcodes) Cmpxchgl(ops ...Operand) { o.a.op("CMPXCHGL", ops...) } func (o Opcodes) CMPXCHGL(ops ...Operand) { o.a.op("CMPXCHGL", ops...) } func (o Opcodes) Cmpxchgw(ops ...Operand) { o.a.op("CMPXCHGW", ops...) } func (o Opcodes) CMPXCHGW(ops ...Operand) { o.a.op("CMPXCHGW", ops...) } func (o Opcodes) Cmpxchg8b(ops ...Operand) { o.a.op("CMPXCHG8B", ops...) } func (o Opcodes) CMPXCHG8B(ops ...Operand) { o.a.op("CMPXCHG8B", ops...) } func (o Opcodes) Cpuid(ops ...Operand) { o.a.op("CPUID", ops...) } func (o Opcodes) CPUID(ops ...Operand) { o.a.op("CPUID", ops...) } func (o Opcodes) Invd(ops ...Operand) { o.a.op("INVD", ops...) } func (o Opcodes) INVD(ops ...Operand) { o.a.op("INVD", ops...) } func (o Opcodes) Invlpg(ops ...Operand) { o.a.op("INVLPG", ops...) } func (o Opcodes) INVLPG(ops ...Operand) { o.a.op("INVLPG", ops...) } func (o Opcodes) Lfence(ops ...Operand) { o.a.op("LFENCE", ops...) } func (o Opcodes) LFENCE(ops ...Operand) { o.a.op("LFENCE", ops...) } func (o Opcodes) Mfence(ops ...Operand) { o.a.op("MFENCE", ops...) } func (o Opcodes) MFENCE(ops ...Operand) { o.a.op("MFENCE", ops...) } func (o Opcodes) Movntil(ops ...Operand) { o.a.op("MOVNTIL", ops...) } func (o Opcodes) MOVNTIL(ops ...Operand) { o.a.op("MOVNTIL", ops...) } func (o Opcodes) Rdmsr(ops ...Operand) { o.a.op("RDMSR", ops...) } func (o Opcodes) RDMSR(ops ...Operand) { o.a.op("RDMSR", ops...) } func (o Opcodes) Rdpmc(ops ...Operand) { o.a.op("RDPMC", ops...) } func (o Opcodes) RDPMC(ops ...Operand) { o.a.op("RDPMC", ops...) } func (o Opcodes) Rdtsc(ops ...Operand) { o.a.op("RDTSC", ops...) } func (o Opcodes) RDTSC(ops ...Operand) { o.a.op("RDTSC", ops...) } func (o Opcodes) Rsm(ops ...Operand) { o.a.op("RSM", ops...) } func (o Opcodes) RSM(ops ...Operand) { o.a.op("RSM", ops...) } func (o Opcodes) Sfence(ops ...Operand) { o.a.op("SFENCE", ops...) } func (o Opcodes) SFENCE(ops ...Operand) { o.a.op("SFENCE", ops...) } func (o Opcodes) Sysret(ops ...Operand) { o.a.op("SYSRET", ops...) } func (o Opcodes) SYSRET(ops ...Operand) { o.a.op("SYSRET", ops...) } func (o Opcodes) Wbinvd(ops ...Operand) { o.a.op("WBINVD", ops...) } func (o Opcodes) WBINVD(ops ...Operand) { o.a.op("WBINVD", ops...) } func (o Opcodes) Wrmsr(ops ...Operand) { o.a.op("WRMSR", ops...) } func (o Opcodes) WRMSR(ops ...Operand) { o.a.op("WRMSR", ops...) } func (o Opcodes) Xaddb(ops ...Operand) { o.a.op("XADDB", ops...) } func (o Opcodes) XADDB(ops ...Operand) { o.a.op("XADDB", ops...) } func (o Opcodes) Xaddl(ops ...Operand) { o.a.op("XADDL", ops...) } func (o Opcodes) XADDL(ops ...Operand) { o.a.op("XADDL", ops...) } func (o Opcodes) Xaddw(ops ...Operand) { o.a.op("XADDW", ops...) } func (o Opcodes) XADDW(ops ...Operand) { o.a.op("XADDW", ops...) } func (o Opcodes) Cmovlcc(ops ...Operand) { o.a.op("CMOVLCC", ops...) } func (o Opcodes) CMOVLCC(ops ...Operand) { o.a.op("CMOVLCC", ops...) } func (o Opcodes) Cmovlcs(ops ...Operand) { o.a.op("CMOVLCS", ops...) } func (o Opcodes) CMOVLCS(ops ...Operand) { o.a.op("CMOVLCS", ops...) } func (o Opcodes) Cmovleq(ops ...Operand) { o.a.op("CMOVLEQ", ops...) } func (o Opcodes) CMOVLEQ(ops ...Operand) { o.a.op("CMOVLEQ", ops...) } func (o Opcodes) Cmovlge(ops ...Operand) { o.a.op("CMOVLGE", ops...) } func (o Opcodes) CMOVLGE(ops ...Operand) { o.a.op("CMOVLGE", ops...) } func (o Opcodes) Cmovlgt(ops ...Operand) { o.a.op("CMOVLGT", ops...) } func (o Opcodes) CMOVLGT(ops ...Operand) { o.a.op("CMOVLGT", ops...) } func (o Opcodes) Cmovlhi(ops ...Operand) { o.a.op("CMOVLHI", ops...) } func (o Opcodes) CMOVLHI(ops ...Operand) { o.a.op("CMOVLHI", ops...) } func (o Opcodes) Cmovlle(ops ...Operand) { o.a.op("CMOVLLE", ops...) } func (o Opcodes) CMOVLLE(ops ...Operand) { o.a.op("CMOVLLE", ops...) } func (o Opcodes) Cmovlls(ops ...Operand) { o.a.op("CMOVLLS", ops...) } func (o Opcodes) CMOVLLS(ops ...Operand) { o.a.op("CMOVLLS", ops...) } func (o Opcodes) Cmovllt(ops ...Operand) { o.a.op("CMOVLLT", ops...) } func (o Opcodes) CMOVLLT(ops ...Operand) { o.a.op("CMOVLLT", ops...) } func (o Opcodes) Cmovlmi(ops ...Operand) { o.a.op("CMOVLMI", ops...) } func (o Opcodes) CMOVLMI(ops ...Operand) { o.a.op("CMOVLMI", ops...) } func (o Opcodes) Cmovlne(ops ...Operand) { o.a.op("CMOVLNE", ops...) } func (o Opcodes) CMOVLNE(ops ...Operand) { o.a.op("CMOVLNE", ops...) } func (o Opcodes) Cmovloc(ops ...Operand) { o.a.op("CMOVLOC", ops...) } func (o Opcodes) CMOVLOC(ops ...Operand) { o.a.op("CMOVLOC", ops...) } func (o Opcodes) Cmovlos(ops ...Operand) { o.a.op("CMOVLOS", ops...) } func (o Opcodes) CMOVLOS(ops ...Operand) { o.a.op("CMOVLOS", ops...) } func (o Opcodes) Cmovlpc(ops ...Operand) { o.a.op("CMOVLPC", ops...) } func (o Opcodes) CMOVLPC(ops ...Operand) { o.a.op("CMOVLPC", ops...) } func (o Opcodes) Cmovlpl(ops ...Operand) { o.a.op("CMOVLPL", ops...) } func (o Opcodes) CMOVLPL(ops ...Operand) { o.a.op("CMOVLPL", ops...) } func (o Opcodes) Cmovlps(ops ...Operand) { o.a.op("CMOVLPS", ops...) } func (o Opcodes) CMOVLPS(ops ...Operand) { o.a.op("CMOVLPS", ops...) } func (o Opcodes) Cmovqcc(ops ...Operand) { o.a.op("CMOVQCC", ops...) } func (o Opcodes) CMOVQCC(ops ...Operand) { o.a.op("CMOVQCC", ops...) } func (o Opcodes) Cmovqcs(ops ...Operand) { o.a.op("CMOVQCS", ops...) } func (o Opcodes) CMOVQCS(ops ...Operand) { o.a.op("CMOVQCS", ops...) } func (o Opcodes) Cmovqeq(ops ...Operand) { o.a.op("CMOVQEQ", ops...) } func (o Opcodes) CMOVQEQ(ops ...Operand) { o.a.op("CMOVQEQ", ops...) } func (o Opcodes) Cmovqge(ops ...Operand) { o.a.op("CMOVQGE", ops...) } func (o Opcodes) CMOVQGE(ops ...Operand) { o.a.op("CMOVQGE", ops...) } func (o Opcodes) Cmovqgt(ops ...Operand) { o.a.op("CMOVQGT", ops...) } func (o Opcodes) CMOVQGT(ops ...Operand) { o.a.op("CMOVQGT", ops...) } func (o Opcodes) Cmovqhi(ops ...Operand) { o.a.op("CMOVQHI", ops...) } func (o Opcodes) CMOVQHI(ops ...Operand) { o.a.op("CMOVQHI", ops...) } func (o Opcodes) Cmovqle(ops ...Operand) { o.a.op("CMOVQLE", ops...) } func (o Opcodes) CMOVQLE(ops ...Operand) { o.a.op("CMOVQLE", ops...) } func (o Opcodes) Cmovqls(ops ...Operand) { o.a.op("CMOVQLS", ops...) } func (o Opcodes) CMOVQLS(ops ...Operand) { o.a.op("CMOVQLS", ops...) } func (o Opcodes) Cmovqlt(ops ...Operand) { o.a.op("CMOVQLT", ops...) } func (o Opcodes) CMOVQLT(ops ...Operand) { o.a.op("CMOVQLT", ops...) } func (o Opcodes) Cmovqmi(ops ...Operand) { o.a.op("CMOVQMI", ops...) } func (o Opcodes) CMOVQMI(ops ...Operand) { o.a.op("CMOVQMI", ops...) } func (o Opcodes) Cmovqne(ops ...Operand) { o.a.op("CMOVQNE", ops...) } func (o Opcodes) CMOVQNE(ops ...Operand) { o.a.op("CMOVQNE", ops...) } func (o Opcodes) Cmovqoc(ops ...Operand) { o.a.op("CMOVQOC", ops...) } func (o Opcodes) CMOVQOC(ops ...Operand) { o.a.op("CMOVQOC", ops...) } func (o Opcodes) Cmovqos(ops ...Operand) { o.a.op("CMOVQOS", ops...) } func (o Opcodes) CMOVQOS(ops ...Operand) { o.a.op("CMOVQOS", ops...) } func (o Opcodes) Cmovqpc(ops ...Operand) { o.a.op("CMOVQPC", ops...) } func (o Opcodes) CMOVQPC(ops ...Operand) { o.a.op("CMOVQPC", ops...) } func (o Opcodes) Cmovqpl(ops ...Operand) { o.a.op("CMOVQPL", ops...) } func (o Opcodes) CMOVQPL(ops ...Operand) { o.a.op("CMOVQPL", ops...) } func (o Opcodes) Cmovqps(ops ...Operand) { o.a.op("CMOVQPS", ops...) } func (o Opcodes) CMOVQPS(ops ...Operand) { o.a.op("CMOVQPS", ops...) } func (o Opcodes) Cmovwcc(ops ...Operand) { o.a.op("CMOVWCC", ops...) } func (o Opcodes) CMOVWCC(ops ...Operand) { o.a.op("CMOVWCC", ops...) } func (o Opcodes) Cmovwcs(ops ...Operand) { o.a.op("CMOVWCS", ops...) } func (o Opcodes) CMOVWCS(ops ...Operand) { o.a.op("CMOVWCS", ops...) } func (o Opcodes) Cmovweq(ops ...Operand) { o.a.op("CMOVWEQ", ops...) } func (o Opcodes) CMOVWEQ(ops ...Operand) { o.a.op("CMOVWEQ", ops...) } func (o Opcodes) Cmovwge(ops ...Operand) { o.a.op("CMOVWGE", ops...) } func (o Opcodes) CMOVWGE(ops ...Operand) { o.a.op("CMOVWGE", ops...) } func (o Opcodes) Cmovwgt(ops ...Operand) { o.a.op("CMOVWGT", ops...) } func (o Opcodes) CMOVWGT(ops ...Operand) { o.a.op("CMOVWGT", ops...) } func (o Opcodes) Cmovwhi(ops ...Operand) { o.a.op("CMOVWHI", ops...) } func (o Opcodes) CMOVWHI(ops ...Operand) { o.a.op("CMOVWHI", ops...) } func (o Opcodes) Cmovwle(ops ...Operand) { o.a.op("CMOVWLE", ops...) } func (o Opcodes) CMOVWLE(ops ...Operand) { o.a.op("CMOVWLE", ops...) } func (o Opcodes) Cmovwls(ops ...Operand) { o.a.op("CMOVWLS", ops...) } func (o Opcodes) CMOVWLS(ops ...Operand) { o.a.op("CMOVWLS", ops...) } func (o Opcodes) Cmovwlt(ops ...Operand) { o.a.op("CMOVWLT", ops...) } func (o Opcodes) CMOVWLT(ops ...Operand) { o.a.op("CMOVWLT", ops...) } func (o Opcodes) Cmovwmi(ops ...Operand) { o.a.op("CMOVWMI", ops...) } func (o Opcodes) CMOVWMI(ops ...Operand) { o.a.op("CMOVWMI", ops...) } func (o Opcodes) Cmovwne(ops ...Operand) { o.a.op("CMOVWNE", ops...) } func (o Opcodes) CMOVWNE(ops ...Operand) { o.a.op("CMOVWNE", ops...) } func (o Opcodes) Cmovwoc(ops ...Operand) { o.a.op("CMOVWOC", ops...) } func (o Opcodes) CMOVWOC(ops ...Operand) { o.a.op("CMOVWOC", ops...) } func (o Opcodes) Cmovwos(ops ...Operand) { o.a.op("CMOVWOS", ops...) } func (o Opcodes) CMOVWOS(ops ...Operand) { o.a.op("CMOVWOS", ops...) } func (o Opcodes) Cmovwpc(ops ...Operand) { o.a.op("CMOVWPC", ops...) } func (o Opcodes) CMOVWPC(ops ...Operand) { o.a.op("CMOVWPC", ops...) } func (o Opcodes) Cmovwpl(ops ...Operand) { o.a.op("CMOVWPL", ops...) } func (o Opcodes) CMOVWPL(ops ...Operand) { o.a.op("CMOVWPL", ops...) } func (o Opcodes) Cmovwps(ops ...Operand) { o.a.op("CMOVWPS", ops...) } func (o Opcodes) CMOVWPS(ops ...Operand) { o.a.op("CMOVWPS", ops...) } func (o Opcodes) Adcq(ops ...Operand) { o.a.op("ADCQ", ops...) } func (o Opcodes) ADCQ(ops ...Operand) { o.a.op("ADCQ", ops...) } func (o Opcodes) Addq(ops ...Operand) { o.a.op("ADDQ", ops...) } func (o Opcodes) ADDQ(ops ...Operand) { o.a.op("ADDQ", ops...) } func (o Opcodes) Andq(ops ...Operand) { o.a.op("ANDQ", ops...) } func (o Opcodes) ANDQ(ops ...Operand) { o.a.op("ANDQ", ops...) } func (o Opcodes) Bsfq(ops ...Operand) { o.a.op("BSFQ", ops...) } func (o Opcodes) BSFQ(ops ...Operand) { o.a.op("BSFQ", ops...) } func (o Opcodes) Bsrq(ops ...Operand) { o.a.op("BSRQ", ops...) } func (o Opcodes) BSRQ(ops ...Operand) { o.a.op("BSRQ", ops...) } func (o Opcodes) Btcq(ops ...Operand) { o.a.op("BTCQ", ops...) } func (o Opcodes) BTCQ(ops ...Operand) { o.a.op("BTCQ", ops...) } func (o Opcodes) Btq(ops ...Operand) { o.a.op("BTQ", ops...) } func (o Opcodes) BTQ(ops ...Operand) { o.a.op("BTQ", ops...) } func (o Opcodes) Btrq(ops ...Operand) { o.a.op("BTRQ", ops...) } func (o Opcodes) BTRQ(ops ...Operand) { o.a.op("BTRQ", ops...) } func (o Opcodes) Btsq(ops ...Operand) { o.a.op("BTSQ", ops...) } func (o Opcodes) BTSQ(ops ...Operand) { o.a.op("BTSQ", ops...) } func (o Opcodes) Cmpq(ops ...Operand) { o.a.op("CMPQ", ops...) } func (o Opcodes) CMPQ(ops ...Operand) { o.a.op("CMPQ", ops...) } func (o Opcodes) Cmpsq(ops ...Operand) { o.a.op("CMPSQ", ops...) } func (o Opcodes) CMPSQ(ops ...Operand) { o.a.op("CMPSQ", ops...) } func (o Opcodes) Cmpxchgq(ops ...Operand) { o.a.op("CMPXCHGQ", ops...) } func (o Opcodes) CMPXCHGQ(ops ...Operand) { o.a.op("CMPXCHGQ", ops...) } func (o Opcodes) Cqo(ops ...Operand) { o.a.op("CQO", ops...) } func (o Opcodes) CQO(ops ...Operand) { o.a.op("CQO", ops...) } func (o Opcodes) Divq(ops ...Operand) { o.a.op("DIVQ", ops...) } func (o Opcodes) DIVQ(ops ...Operand) { o.a.op("DIVQ", ops...) } func (o Opcodes) Idivq(ops ...Operand) { o.a.op("IDIVQ", ops...) } func (o Opcodes) IDIVQ(ops ...Operand) { o.a.op("IDIVQ", ops...) } func (o Opcodes) Imulq(ops ...Operand) { o.a.op("IMULQ", ops...) } func (o Opcodes) IMULQ(ops ...Operand) { o.a.op("IMULQ", ops...) } func (o Opcodes) Iretq(ops ...Operand) { o.a.op("IRETQ", ops...) } func (o Opcodes) IRETQ(ops ...Operand) { o.a.op("IRETQ", ops...) } func (o Opcodes) Jcxzq(ops ...Operand) { o.a.op("JCXZQ", ops...) } func (o Opcodes) JCXZQ(ops ...Operand) { o.a.op("JCXZQ", ops...) } func (o Opcodes) Leaq(ops ...Operand) { o.a.op("LEAQ", ops...) } func (o Opcodes) LEAQ(ops ...Operand) { o.a.op("LEAQ", ops...) } func (o Opcodes) Leaveq(ops ...Operand) { o.a.op("LEAVEQ", ops...) } func (o Opcodes) LEAVEQ(ops ...Operand) { o.a.op("LEAVEQ", ops...) } func (o Opcodes) Lodsq(ops ...Operand) { o.a.op("LODSQ", ops...) } func (o Opcodes) LODSQ(ops ...Operand) { o.a.op("LODSQ", ops...) } func (o Opcodes) Movq(ops ...Operand) { o.a.op("MOVQ", ops...) } func (o Opcodes) MOVQ(ops ...Operand) { o.a.op("MOVQ", ops...) } func (o Opcodes) Movlqsx(ops ...Operand) { o.a.op("MOVLQSX", ops...) } func (o Opcodes) MOVLQSX(ops ...Operand) { o.a.op("MOVLQSX", ops...) } func (o Opcodes) Movlqzx(ops ...Operand) { o.a.op("MOVLQZX", ops...) } func (o Opcodes) MOVLQZX(ops ...Operand) { o.a.op("MOVLQZX", ops...) } func (o Opcodes) Movntiq(ops ...Operand) { o.a.op("MOVNTIQ", ops...) } func (o Opcodes) MOVNTIQ(ops ...Operand) { o.a.op("MOVNTIQ", ops...) } func (o Opcodes) Movsq(ops ...Operand) { o.a.op("MOVSQ", ops...) } func (o Opcodes) MOVSQ(ops ...Operand) { o.a.op("MOVSQ", ops...) } func (o Opcodes) Mulq(ops ...Operand) { o.a.op("MULQ", ops...) } func (o Opcodes) MULQ(ops ...Operand) { o.a.op("MULQ", ops...) } func (o Opcodes) Negq(ops ...Operand) { o.a.op("NEGQ", ops...) } func (o Opcodes) NEGQ(ops ...Operand) { o.a.op("NEGQ", ops...) } func (o Opcodes) Notq(ops ...Operand) { o.a.op("NOTQ", ops...) } func (o Opcodes) NOTQ(ops ...Operand) { o.a.op("NOTQ", ops...) } func (o Opcodes) Orq(ops ...Operand) { o.a.op("ORQ", ops...) } func (o Opcodes) ORQ(ops ...Operand) { o.a.op("ORQ", ops...) } func (o Opcodes) Popfq(ops ...Operand) { o.a.op("POPFQ", ops...) } func (o Opcodes) POPFQ(ops ...Operand) { o.a.op("POPFQ", ops...) } func (o Opcodes) Popq(ops ...Operand) { o.a.op("POPQ", ops...) } func (o Opcodes) POPQ(ops ...Operand) { o.a.op("POPQ", ops...) } func (o Opcodes) Pushfq(ops ...Operand) { o.a.op("PUSHFQ", ops...) } func (o Opcodes) PUSHFQ(ops ...Operand) { o.a.op("PUSHFQ", ops...) } func (o Opcodes) Pushq(ops ...Operand) { o.a.op("PUSHQ", ops...) } func (o Opcodes) PUSHQ(ops ...Operand) { o.a.op("PUSHQ", ops...) } func (o Opcodes) Rclq(ops ...Operand) { o.a.op("RCLQ", ops...) } func (o Opcodes) RCLQ(ops ...Operand) { o.a.op("RCLQ", ops...) } func (o Opcodes) Rcrq(ops ...Operand) { o.a.op("RCRQ", ops...) } func (o Opcodes) RCRQ(ops ...Operand) { o.a.op("RCRQ", ops...) } func (o Opcodes) Rolq(ops ...Operand) { o.a.op("ROLQ", ops...) } func (o Opcodes) ROLQ(ops ...Operand) { o.a.op("ROLQ", ops...) } func (o Opcodes) Rorq(ops ...Operand) { o.a.op("RORQ", ops...) } func (o Opcodes) RORQ(ops ...Operand) { o.a.op("RORQ", ops...) } func (o Opcodes) Quad(ops ...Operand) { o.a.op("QUAD", ops...) } func (o Opcodes) QUAD(ops ...Operand) { o.a.op("QUAD", ops...) } func (o Opcodes) Salq(ops ...Operand) { o.a.op("SALQ", ops...) } func (o Opcodes) SALQ(ops ...Operand) { o.a.op("SALQ", ops...) } func (o Opcodes) Sarq(ops ...Operand) { o.a.op("SARQ", ops...) } func (o Opcodes) SARQ(ops ...Operand) { o.a.op("SARQ", ops...) } func (o Opcodes) Sbbq(ops ...Operand) { o.a.op("SBBQ", ops...) } func (o Opcodes) SBBQ(ops ...Operand) { o.a.op("SBBQ", ops...) } func (o Opcodes) Scasq(ops ...Operand) { o.a.op("SCASQ", ops...) } func (o Opcodes) SCASQ(ops ...Operand) { o.a.op("SCASQ", ops...) } func (o Opcodes) Shlq(ops ...Operand) { o.a.op("SHLQ", ops...) } func (o Opcodes) SHLQ(ops ...Operand) { o.a.op("SHLQ", ops...) } func (o Opcodes) Shrq(ops ...Operand) { o.a.op("SHRQ", ops...) } func (o Opcodes) SHRQ(ops ...Operand) { o.a.op("SHRQ", ops...) } func (o Opcodes) Stosq(ops ...Operand) { o.a.op("STOSQ", ops...) } func (o Opcodes) STOSQ(ops ...Operand) { o.a.op("STOSQ", ops...) } func (o Opcodes) Subq(ops ...Operand) { o.a.op("SUBQ", ops...) } func (o Opcodes) SUBQ(ops ...Operand) { o.a.op("SUBQ", ops...) } func (o Opcodes) Testq(ops ...Operand) { o.a.op("TESTQ", ops...) } func (o Opcodes) TESTQ(ops ...Operand) { o.a.op("TESTQ", ops...) } func (o Opcodes) Xaddq(ops ...Operand) { o.a.op("XADDQ", ops...) } func (o Opcodes) XADDQ(ops ...Operand) { o.a.op("XADDQ", ops...) } func (o Opcodes) Xchgq(ops ...Operand) { o.a.op("XCHGQ", ops...) } func (o Opcodes) XCHGQ(ops ...Operand) { o.a.op("XCHGQ", ops...) } func (o Opcodes) Xorq(ops ...Operand) { o.a.op("XORQ", ops...) } func (o Opcodes) XORQ(ops ...Operand) { o.a.op("XORQ", ops...) } func (o Opcodes) Xgetbv(ops ...Operand) { o.a.op("XGETBV", ops...) } func (o Opcodes) XGETBV(ops ...Operand) { o.a.op("XGETBV", ops...) } func (o Opcodes) Addpd(ops ...Operand) { o.a.op("ADDPD", ops...) } func (o Opcodes) ADDPD(ops ...Operand) { o.a.op("ADDPD", ops...) } func (o Opcodes) Addps(ops ...Operand) { o.a.op("ADDPS", ops...) } func (o Opcodes) ADDPS(ops ...Operand) { o.a.op("ADDPS", ops...) } func (o Opcodes) Addsd(ops ...Operand) { o.a.op("ADDSD", ops...) } func (o Opcodes) ADDSD(ops ...Operand) { o.a.op("ADDSD", ops...) } func (o Opcodes) Addss(ops ...Operand) { o.a.op("ADDSS", ops...) } func (o Opcodes) ADDSS(ops ...Operand) { o.a.op("ADDSS", ops...) } func (o Opcodes) Andnl(ops ...Operand) { o.a.op("ANDNL", ops...) } func (o Opcodes) ANDNL(ops ...Operand) { o.a.op("ANDNL", ops...) } func (o Opcodes) Andnq(ops ...Operand) { o.a.op("ANDNQ", ops...) } func (o Opcodes) ANDNQ(ops ...Operand) { o.a.op("ANDNQ", ops...) } func (o Opcodes) Andnpd(ops ...Operand) { o.a.op("ANDNPD", ops...) } func (o Opcodes) ANDNPD(ops ...Operand) { o.a.op("ANDNPD", ops...) } func (o Opcodes) Andnps(ops ...Operand) { o.a.op("ANDNPS", ops...) } func (o Opcodes) ANDNPS(ops ...Operand) { o.a.op("ANDNPS", ops...) } func (o Opcodes) Andpd(ops ...Operand) { o.a.op("ANDPD", ops...) } func (o Opcodes) ANDPD(ops ...Operand) { o.a.op("ANDPD", ops...) } func (o Opcodes) Andps(ops ...Operand) { o.a.op("ANDPS", ops...) } func (o Opcodes) ANDPS(ops ...Operand) { o.a.op("ANDPS", ops...) } func (o Opcodes) Bextrl(ops ...Operand) { o.a.op("BEXTRL", ops...) } func (o Opcodes) BEXTRL(ops ...Operand) { o.a.op("BEXTRL", ops...) } func (o Opcodes) Bextrq(ops ...Operand) { o.a.op("BEXTRQ", ops...) } func (o Opcodes) BEXTRQ(ops ...Operand) { o.a.op("BEXTRQ", ops...) } func (o Opcodes) Blsil(ops ...Operand) { o.a.op("BLSIL", ops...) } func (o Opcodes) BLSIL(ops ...Operand) { o.a.op("BLSIL", ops...) } func (o Opcodes) Blsiq(ops ...Operand) { o.a.op("BLSIQ", ops...) } func (o Opcodes) BLSIQ(ops ...Operand) { o.a.op("BLSIQ", ops...) } func (o Opcodes) Blsmskl(ops ...Operand) { o.a.op("BLSMSKL", ops...) } func (o Opcodes) BLSMSKL(ops ...Operand) { o.a.op("BLSMSKL", ops...) } func (o Opcodes) Blsmskq(ops ...Operand) { o.a.op("BLSMSKQ", ops...) } func (o Opcodes) BLSMSKQ(ops ...Operand) { o.a.op("BLSMSKQ", ops...) } func (o Opcodes) Blsrl(ops ...Operand) { o.a.op("BLSRL", ops...) } func (o Opcodes) BLSRL(ops ...Operand) { o.a.op("BLSRL", ops...) } func (o Opcodes) Blsrq(ops ...Operand) { o.a.op("BLSRQ", ops...) } func (o Opcodes) BLSRQ(ops ...Operand) { o.a.op("BLSRQ", ops...) } func (o Opcodes) Bzhil(ops ...Operand) { o.a.op("BZHIL", ops...) } func (o Opcodes) BZHIL(ops ...Operand) { o.a.op("BZHIL", ops...) } func (o Opcodes) Bzhiq(ops ...Operand) { o.a.op("BZHIQ", ops...) } func (o Opcodes) BZHIQ(ops ...Operand) { o.a.op("BZHIQ", ops...) } func (o Opcodes) Cmppd(ops ...Operand) { o.a.op("CMPPD", ops...) } func (o Opcodes) CMPPD(ops ...Operand) { o.a.op("CMPPD", ops...) } func (o Opcodes) Cmpps(ops ...Operand) { o.a.op("CMPPS", ops...) } func (o Opcodes) CMPPS(ops ...Operand) { o.a.op("CMPPS", ops...) } func (o Opcodes) Cmpsd(ops ...Operand) { o.a.op("CMPSD", ops...) } func (o Opcodes) CMPSD(ops ...Operand) { o.a.op("CMPSD", ops...) } func (o Opcodes) Cmpss(ops ...Operand) { o.a.op("CMPSS", ops...) } func (o Opcodes) CMPSS(ops ...Operand) { o.a.op("CMPSS", ops...) } func (o Opcodes) Comisd(ops ...Operand) { o.a.op("COMISD", ops...) } func (o Opcodes) COMISD(ops ...Operand) { o.a.op("COMISD", ops...) } func (o Opcodes) Comiss(ops ...Operand) { o.a.op("COMISS", ops...) } func (o Opcodes) COMISS(ops ...Operand) { o.a.op("COMISS", ops...) } func (o Opcodes) Cvtpd2pl(ops ...Operand) { o.a.op("CVTPD2PL", ops...) } func (o Opcodes) CVTPD2PL(ops ...Operand) { o.a.op("CVTPD2PL", ops...) } func (o Opcodes) Cvtpd2ps(ops ...Operand) { o.a.op("CVTPD2PS", ops...) } func (o Opcodes) CVTPD2PS(ops ...Operand) { o.a.op("CVTPD2PS", ops...) } func (o Opcodes) Cvtpl2pd(ops ...Operand) { o.a.op("CVTPL2PD", ops...) } func (o Opcodes) CVTPL2PD(ops ...Operand) { o.a.op("CVTPL2PD", ops...) } func (o Opcodes) Cvtpl2ps(ops ...Operand) { o.a.op("CVTPL2PS", ops...) } func (o Opcodes) CVTPL2PS(ops ...Operand) { o.a.op("CVTPL2PS", ops...) } func (o Opcodes) Cvtps2pd(ops ...Operand) { o.a.op("CVTPS2PD", ops...) } func (o Opcodes) CVTPS2PD(ops ...Operand) { o.a.op("CVTPS2PD", ops...) } func (o Opcodes) Cvtps2pl(ops ...Operand) { o.a.op("CVTPS2PL", ops...) } func (o Opcodes) CVTPS2PL(ops ...Operand) { o.a.op("CVTPS2PL", ops...) } func (o Opcodes) Cvtsd2sl(ops ...Operand) { o.a.op("CVTSD2SL", ops...) } func (o Opcodes) CVTSD2SL(ops ...Operand) { o.a.op("CVTSD2SL", ops...) } func (o Opcodes) Cvtsd2sq(ops ...Operand) { o.a.op("CVTSD2SQ", ops...) } func (o Opcodes) CVTSD2SQ(ops ...Operand) { o.a.op("CVTSD2SQ", ops...) } func (o Opcodes) Cvtsd2ss(ops ...Operand) { o.a.op("CVTSD2SS", ops...) } func (o Opcodes) CVTSD2SS(ops ...Operand) { o.a.op("CVTSD2SS", ops...) } func (o Opcodes) Cvtsl2sd(ops ...Operand) { o.a.op("CVTSL2SD", ops...) } func (o Opcodes) CVTSL2SD(ops ...Operand) { o.a.op("CVTSL2SD", ops...) } func (o Opcodes) Cvtsl2ss(ops ...Operand) { o.a.op("CVTSL2SS", ops...) } func (o Opcodes) CVTSL2SS(ops ...Operand) { o.a.op("CVTSL2SS", ops...) } func (o Opcodes) Cvtsq2sd(ops ...Operand) { o.a.op("CVTSQ2SD", ops...) } func (o Opcodes) CVTSQ2SD(ops ...Operand) { o.a.op("CVTSQ2SD", ops...) } func (o Opcodes) Cvtsq2ss(ops ...Operand) { o.a.op("CVTSQ2SS", ops...) } func (o Opcodes) CVTSQ2SS(ops ...Operand) { o.a.op("CVTSQ2SS", ops...) } func (o Opcodes) Cvtss2sd(ops ...Operand) { o.a.op("CVTSS2SD", ops...) } func (o Opcodes) CVTSS2SD(ops ...Operand) { o.a.op("CVTSS2SD", ops...) } func (o Opcodes) Cvtss2sl(ops ...Operand) { o.a.op("CVTSS2SL", ops...) } func (o Opcodes) CVTSS2SL(ops ...Operand) { o.a.op("CVTSS2SL", ops...) } func (o Opcodes) Cvtss2sq(ops ...Operand) { o.a.op("CVTSS2SQ", ops...) } func (o Opcodes) CVTSS2SQ(ops ...Operand) { o.a.op("CVTSS2SQ", ops...) } func (o Opcodes) Cvttpd2pl(ops ...Operand) { o.a.op("CVTTPD2PL", ops...) } func (o Opcodes) CVTTPD2PL(ops ...Operand) { o.a.op("CVTTPD2PL", ops...) } func (o Opcodes) Cvttps2pl(ops ...Operand) { o.a.op("CVTTPS2PL", ops...) } func (o Opcodes) CVTTPS2PL(ops ...Operand) { o.a.op("CVTTPS2PL", ops...) } func (o Opcodes) Cvttsd2sl(ops ...Operand) { o.a.op("CVTTSD2SL", ops...) } func (o Opcodes) CVTTSD2SL(ops ...Operand) { o.a.op("CVTTSD2SL", ops...) } func (o Opcodes) Cvttsd2sq(ops ...Operand) { o.a.op("CVTTSD2SQ", ops...) } func (o Opcodes) CVTTSD2SQ(ops ...Operand) { o.a.op("CVTTSD2SQ", ops...) } func (o Opcodes) Cvttss2sl(ops ...Operand) { o.a.op("CVTTSS2SL", ops...) } func (o Opcodes) CVTTSS2SL(ops ...Operand) { o.a.op("CVTTSS2SL", ops...) } func (o Opcodes) Cvttss2sq(ops ...Operand) { o.a.op("CVTTSS2SQ", ops...) } func (o Opcodes) CVTTSS2SQ(ops ...Operand) { o.a.op("CVTTSS2SQ", ops...) } func (o Opcodes) Divpd(ops ...Operand) { o.a.op("DIVPD", ops...) } func (o Opcodes) DIVPD(ops ...Operand) { o.a.op("DIVPD", ops...) } func (o Opcodes) Divps(ops ...Operand) { o.a.op("DIVPS", ops...) } func (o Opcodes) DIVPS(ops ...Operand) { o.a.op("DIVPS", ops...) } func (o Opcodes) Divsd(ops ...Operand) { o.a.op("DIVSD", ops...) } func (o Opcodes) DIVSD(ops ...Operand) { o.a.op("DIVSD", ops...) } func (o Opcodes) Divss(ops ...Operand) { o.a.op("DIVSS", ops...) } func (o Opcodes) DIVSS(ops ...Operand) { o.a.op("DIVSS", ops...) } func (o Opcodes) Emms(ops ...Operand) { o.a.op("EMMS", ops...) } func (o Opcodes) EMMS(ops ...Operand) { o.a.op("EMMS", ops...) } func (o Opcodes) Fxrstor(ops ...Operand) { o.a.op("FXRSTOR", ops...) } func (o Opcodes) FXRSTOR(ops ...Operand) { o.a.op("FXRSTOR", ops...) } func (o Opcodes) Fxrstor64(ops ...Operand) { o.a.op("FXRSTOR64", ops...) } func (o Opcodes) FXRSTOR64(ops ...Operand) { o.a.op("FXRSTOR64", ops...) } func (o Opcodes) Fxsave(ops ...Operand) { o.a.op("FXSAVE", ops...) } func (o Opcodes) FXSAVE(ops ...Operand) { o.a.op("FXSAVE", ops...) } func (o Opcodes) Fxsave64(ops ...Operand) { o.a.op("FXSAVE64", ops...) } func (o Opcodes) FXSAVE64(ops ...Operand) { o.a.op("FXSAVE64", ops...) } func (o Opcodes) Lddqu(ops ...Operand) { o.a.op("LDDQU", ops...) } func (o Opcodes) LDDQU(ops ...Operand) { o.a.op("LDDQU", ops...) } func (o Opcodes) Ldmxcsr(ops ...Operand) { o.a.op("LDMXCSR", ops...) } func (o Opcodes) LDMXCSR(ops ...Operand) { o.a.op("LDMXCSR", ops...) } func (o Opcodes) Maskmovou(ops ...Operand) { o.a.op("MASKMOVOU", ops...) } func (o Opcodes) MASKMOVOU(ops ...Operand) { o.a.op("MASKMOVOU", ops...) } func (o Opcodes) Maskmovq(ops ...Operand) { o.a.op("MASKMOVQ", ops...) } func (o Opcodes) MASKMOVQ(ops ...Operand) { o.a.op("MASKMOVQ", ops...) } func (o Opcodes) Maxpd(ops ...Operand) { o.a.op("MAXPD", ops...) } func (o Opcodes) MAXPD(ops ...Operand) { o.a.op("MAXPD", ops...) } func (o Opcodes) Maxps(ops ...Operand) { o.a.op("MAXPS", ops...) } func (o Opcodes) MAXPS(ops ...Operand) { o.a.op("MAXPS", ops...) } func (o Opcodes) Maxsd(ops ...Operand) { o.a.op("MAXSD", ops...) } func (o Opcodes) MAXSD(ops ...Operand) { o.a.op("MAXSD", ops...) } func (o Opcodes) Maxss(ops ...Operand) { o.a.op("MAXSS", ops...) } func (o Opcodes) MAXSS(ops ...Operand) { o.a.op("MAXSS", ops...) } func (o Opcodes) Minpd(ops ...Operand) { o.a.op("MINPD", ops...) } func (o Opcodes) MINPD(ops ...Operand) { o.a.op("MINPD", ops...) } func (o Opcodes) Minps(ops ...Operand) { o.a.op("MINPS", ops...) } func (o Opcodes) MINPS(ops ...Operand) { o.a.op("MINPS", ops...) } func (o Opcodes) Minsd(ops ...Operand) { o.a.op("MINSD", ops...) } func (o Opcodes) MINSD(ops ...Operand) { o.a.op("MINSD", ops...) } func (o Opcodes) Minss(ops ...Operand) { o.a.op("MINSS", ops...) } func (o Opcodes) MINSS(ops ...Operand) { o.a.op("MINSS", ops...) } func (o Opcodes) Movapd(ops ...Operand) { o.a.op("MOVAPD", ops...) } func (o Opcodes) MOVAPD(ops ...Operand) { o.a.op("MOVAPD", ops...) } func (o Opcodes) Movaps(ops ...Operand) { o.a.op("MOVAPS", ops...) } func (o Opcodes) MOVAPS(ops ...Operand) { o.a.op("MOVAPS", ops...) } func (o Opcodes) Movou(ops ...Operand) { o.a.op("MOVOU", ops...) } func (o Opcodes) MOVOU(ops ...Operand) { o.a.op("MOVOU", ops...) } func (o Opcodes) Movhlps(ops ...Operand) { o.a.op("MOVHLPS", ops...) } func (o Opcodes) MOVHLPS(ops ...Operand) { o.a.op("MOVHLPS", ops...) } func (o Opcodes) Movhpd(ops ...Operand) { o.a.op("MOVHPD", ops...) } func (o Opcodes) MOVHPD(ops ...Operand) { o.a.op("MOVHPD", ops...) } func (o Opcodes) Movhps(ops ...Operand) { o.a.op("MOVHPS", ops...) } func (o Opcodes) MOVHPS(ops ...Operand) { o.a.op("MOVHPS", ops...) } func (o Opcodes) Movlhps(ops ...Operand) { o.a.op("MOVLHPS", ops...) } func (o Opcodes) MOVLHPS(ops ...Operand) { o.a.op("MOVLHPS", ops...) } func (o Opcodes) Movlpd(ops ...Operand) { o.a.op("MOVLPD", ops...) } func (o Opcodes) MOVLPD(ops ...Operand) { o.a.op("MOVLPD", ops...) } func (o Opcodes) Movlps(ops ...Operand) { o.a.op("MOVLPS", ops...) } func (o Opcodes) MOVLPS(ops ...Operand) { o.a.op("MOVLPS", ops...) } func (o Opcodes) Movmskpd(ops ...Operand) { o.a.op("MOVMSKPD", ops...) } func (o Opcodes) MOVMSKPD(ops ...Operand) { o.a.op("MOVMSKPD", ops...) } func (o Opcodes) Movmskps(ops ...Operand) { o.a.op("MOVMSKPS", ops...) } func (o Opcodes) MOVMSKPS(ops ...Operand) { o.a.op("MOVMSKPS", ops...) } func (o Opcodes) Movnto(ops ...Operand) { o.a.op("MOVNTO", ops...) } func (o Opcodes) MOVNTO(ops ...Operand) { o.a.op("MOVNTO", ops...) } func (o Opcodes) Movntpd(ops ...Operand) { o.a.op("MOVNTPD", ops...) } func (o Opcodes) MOVNTPD(ops ...Operand) { o.a.op("MOVNTPD", ops...) } func (o Opcodes) Movntps(ops ...Operand) { o.a.op("MOVNTPS", ops...) } func (o Opcodes) MOVNTPS(ops ...Operand) { o.a.op("MOVNTPS", ops...) } func (o Opcodes) Movntq(ops ...Operand) { o.a.op("MOVNTQ", ops...) } func (o Opcodes) MOVNTQ(ops ...Operand) { o.a.op("MOVNTQ", ops...) } func (o Opcodes) Movo(ops ...Operand) { o.a.op("MOVO", ops...) } func (o Opcodes) MOVO(ops ...Operand) { o.a.op("MOVO", ops...) } func (o Opcodes) Movqozx(ops ...Operand) { o.a.op("MOVQOZX", ops...) } func (o Opcodes) MOVQOZX(ops ...Operand) { o.a.op("MOVQOZX", ops...) } func (o Opcodes) Movsd(ops ...Operand) { o.a.op("MOVSD", ops...) } func (o Opcodes) MOVSD(ops ...Operand) { o.a.op("MOVSD", ops...) } func (o Opcodes) Movss(ops ...Operand) { o.a.op("MOVSS", ops...) } func (o Opcodes) MOVSS(ops ...Operand) { o.a.op("MOVSS", ops...) } func (o Opcodes) Movupd(ops ...Operand) { o.a.op("MOVUPD", ops...) } func (o Opcodes) MOVUPD(ops ...Operand) { o.a.op("MOVUPD", ops...) } func (o Opcodes) Movups(ops ...Operand) { o.a.op("MOVUPS", ops...) } func (o Opcodes) MOVUPS(ops ...Operand) { o.a.op("MOVUPS", ops...) } func (o Opcodes) Mulpd(ops ...Operand) { o.a.op("MULPD", ops...) } func (o Opcodes) MULPD(ops ...Operand) { o.a.op("MULPD", ops...) } func (o Opcodes) Mulps(ops ...Operand) { o.a.op("MULPS", ops...) } func (o Opcodes) MULPS(ops ...Operand) { o.a.op("MULPS", ops...) } func (o Opcodes) Mulsd(ops ...Operand) { o.a.op("MULSD", ops...) } func (o Opcodes) MULSD(ops ...Operand) { o.a.op("MULSD", ops...) } func (o Opcodes) Mulss(ops ...Operand) { o.a.op("MULSS", ops...) } func (o Opcodes) MULSS(ops ...Operand) { o.a.op("MULSS", ops...) } func (o Opcodes) Mulxl(ops ...Operand) { o.a.op("MULXL", ops...) } func (o Opcodes) MULXL(ops ...Operand) { o.a.op("MULXL", ops...) } func (o Opcodes) Mulxq(ops ...Operand) { o.a.op("MULXQ", ops...) } func (o Opcodes) MULXQ(ops ...Operand) { o.a.op("MULXQ", ops...) } func (o Opcodes) Orpd(ops ...Operand) { o.a.op("ORPD", ops...) } func (o Opcodes) ORPD(ops ...Operand) { o.a.op("ORPD", ops...) } func (o Opcodes) Orps(ops ...Operand) { o.a.op("ORPS", ops...) } func (o Opcodes) ORPS(ops ...Operand) { o.a.op("ORPS", ops...) } func (o Opcodes) Packsslw(ops ...Operand) { o.a.op("PACKSSLW", ops...) } func (o Opcodes) PACKSSLW(ops ...Operand) { o.a.op("PACKSSLW", ops...) } func (o Opcodes) Packsswb(ops ...Operand) { o.a.op("PACKSSWB", ops...) } func (o Opcodes) PACKSSWB(ops ...Operand) { o.a.op("PACKSSWB", ops...) } func (o Opcodes) Packuswb(ops ...Operand) { o.a.op("PACKUSWB", ops...) } func (o Opcodes) PACKUSWB(ops ...Operand) { o.a.op("PACKUSWB", ops...) } func (o Opcodes) Paddb(ops ...Operand) { o.a.op("PADDB", ops...) } func (o Opcodes) PADDB(ops ...Operand) { o.a.op("PADDB", ops...) } func (o Opcodes) Paddl(ops ...Operand) { o.a.op("PADDL", ops...) } func (o Opcodes) PADDL(ops ...Operand) { o.a.op("PADDL", ops...) } func (o Opcodes) Paddq(ops ...Operand) { o.a.op("PADDQ", ops...) } func (o Opcodes) PADDQ(ops ...Operand) { o.a.op("PADDQ", ops...) } func (o Opcodes) Paddsb(ops ...Operand) { o.a.op("PADDSB", ops...) } func (o Opcodes) PADDSB(ops ...Operand) { o.a.op("PADDSB", ops...) } func (o Opcodes) Paddsw(ops ...Operand) { o.a.op("PADDSW", ops...) } func (o Opcodes) PADDSW(ops ...Operand) { o.a.op("PADDSW", ops...) } func (o Opcodes) Paddusb(ops ...Operand) { o.a.op("PADDUSB", ops...) } func (o Opcodes) PADDUSB(ops ...Operand) { o.a.op("PADDUSB", ops...) } func (o Opcodes) Paddusw(ops ...Operand) { o.a.op("PADDUSW", ops...) } func (o Opcodes) PADDUSW(ops ...Operand) { o.a.op("PADDUSW", ops...) } func (o Opcodes) Paddw(ops ...Operand) { o.a.op("PADDW", ops...) } func (o Opcodes) PADDW(ops ...Operand) { o.a.op("PADDW", ops...) } func (o Opcodes) Pand(ops ...Operand) { o.a.op("PAND", ops...) } func (o Opcodes) PAND(ops ...Operand) { o.a.op("PAND", ops...) } func (o Opcodes) Pandn(ops ...Operand) { o.a.op("PANDN", ops...) } func (o Opcodes) PANDN(ops ...Operand) { o.a.op("PANDN", ops...) } func (o Opcodes) Pavgb(ops ...Operand) { o.a.op("PAVGB", ops...) } func (o Opcodes) PAVGB(ops ...Operand) { o.a.op("PAVGB", ops...) } func (o Opcodes) Pavgw(ops ...Operand) { o.a.op("PAVGW", ops...) } func (o Opcodes) PAVGW(ops ...Operand) { o.a.op("PAVGW", ops...) } func (o Opcodes) Pcmpeqb(ops ...Operand) { o.a.op("PCMPEQB", ops...) } func (o Opcodes) PCMPEQB(ops ...Operand) { o.a.op("PCMPEQB", ops...) } func (o Opcodes) Pcmpeql(ops ...Operand) { o.a.op("PCMPEQL", ops...) } func (o Opcodes) PCMPEQL(ops ...Operand) { o.a.op("PCMPEQL", ops...) } func (o Opcodes) Pcmpeqw(ops ...Operand) { o.a.op("PCMPEQW", ops...) } func (o Opcodes) PCMPEQW(ops ...Operand) { o.a.op("PCMPEQW", ops...) } func (o Opcodes) Pcmpgtb(ops ...Operand) { o.a.op("PCMPGTB", ops...) } func (o Opcodes) PCMPGTB(ops ...Operand) { o.a.op("PCMPGTB", ops...) } func (o Opcodes) Pcmpgtl(ops ...Operand) { o.a.op("PCMPGTL", ops...) } func (o Opcodes) PCMPGTL(ops ...Operand) { o.a.op("PCMPGTL", ops...) } func (o Opcodes) Pcmpgtw(ops ...Operand) { o.a.op("PCMPGTW", ops...) } func (o Opcodes) PCMPGTW(ops ...Operand) { o.a.op("PCMPGTW", ops...) } func (o Opcodes) Pdepl(ops ...Operand) { o.a.op("PDEPL", ops...) } func (o Opcodes) PDEPL(ops ...Operand) { o.a.op("PDEPL", ops...) } func (o Opcodes) Pdepq(ops ...Operand) { o.a.op("PDEPQ", ops...) } func (o Opcodes) PDEPQ(ops ...Operand) { o.a.op("PDEPQ", ops...) } func (o Opcodes) Pextl(ops ...Operand) { o.a.op("PEXTL", ops...) } func (o Opcodes) PEXTL(ops ...Operand) { o.a.op("PEXTL", ops...) } func (o Opcodes) Pextq(ops ...Operand) { o.a.op("PEXTQ", ops...) } func (o Opcodes) PEXTQ(ops ...Operand) { o.a.op("PEXTQ", ops...) } func (o Opcodes) Pextrb(ops ...Operand) { o.a.op("PEXTRB", ops...) } func (o Opcodes) PEXTRB(ops ...Operand) { o.a.op("PEXTRB", ops...) } func (o Opcodes) Pextrd(ops ...Operand) { o.a.op("PEXTRD", ops...) } func (o Opcodes) PEXTRD(ops ...Operand) { o.a.op("PEXTRD", ops...) } func (o Opcodes) Pextrq(ops ...Operand) { o.a.op("PEXTRQ", ops...) } func (o Opcodes) PEXTRQ(ops ...Operand) { o.a.op("PEXTRQ", ops...) } func (o Opcodes) Phaddd(ops ...Operand) { o.a.op("PHADDD", ops...) } func (o Opcodes) PHADDD(ops ...Operand) { o.a.op("PHADDD", ops...) } func (o Opcodes) Phaddsw(ops ...Operand) { o.a.op("PHADDSW", ops...) } func (o Opcodes) PHADDSW(ops ...Operand) { o.a.op("PHADDSW", ops...) } func (o Opcodes) Phaddw(ops ...Operand) { o.a.op("PHADDW", ops...) } func (o Opcodes) PHADDW(ops ...Operand) { o.a.op("PHADDW", ops...) } func (o Opcodes) Phminposuw(ops ...Operand) { o.a.op("PHMINPOSUW", ops...) } func (o Opcodes) PHMINPOSUW(ops ...Operand) { o.a.op("PHMINPOSUW", ops...) } func (o Opcodes) Phsubd(ops ...Operand) { o.a.op("PHSUBD", ops...) } func (o Opcodes) PHSUBD(ops ...Operand) { o.a.op("PHSUBD", ops...) } func (o Opcodes) Phsubsw(ops ...Operand) { o.a.op("PHSUBSW", ops...) } func (o Opcodes) PHSUBSW(ops ...Operand) { o.a.op("PHSUBSW", ops...) } func (o Opcodes) Phsubw(ops ...Operand) { o.a.op("PHSUBW", ops...) } func (o Opcodes) PHSUBW(ops ...Operand) { o.a.op("PHSUBW", ops...) } func (o Opcodes) Pinsrb(ops ...Operand) { o.a.op("PINSRB", ops...) } func (o Opcodes) PINSRB(ops ...Operand) { o.a.op("PINSRB", ops...) } func (o Opcodes) Pinsrd(ops ...Operand) { o.a.op("PINSRD", ops...) } func (o Opcodes) PINSRD(ops ...Operand) { o.a.op("PINSRD", ops...) } func (o Opcodes) Pinsrq(ops ...Operand) { o.a.op("PINSRQ", ops...) } func (o Opcodes) PINSRQ(ops ...Operand) { o.a.op("PINSRQ", ops...) } func (o Opcodes) Pinsrw(ops ...Operand) { o.a.op("PINSRW", ops...) } func (o Opcodes) PINSRW(ops ...Operand) { o.a.op("PINSRW", ops...) } func (o Opcodes) Pmaddwl(ops ...Operand) { o.a.op("PMADDWL", ops...) } func (o Opcodes) PMADDWL(ops ...Operand) { o.a.op("PMADDWL", ops...) } func (o Opcodes) Pmaxsw(ops ...Operand) { o.a.op("PMAXSW", ops...) } func (o Opcodes) PMAXSW(ops ...Operand) { o.a.op("PMAXSW", ops...) } func (o Opcodes) Pmaxub(ops ...Operand) { o.a.op("PMAXUB", ops...) } func (o Opcodes) PMAXUB(ops ...Operand) { o.a.op("PMAXUB", ops...) } func (o Opcodes) Pminsw(ops ...Operand) { o.a.op("PMINSW", ops...) } func (o Opcodes) PMINSW(ops ...Operand) { o.a.op("PMINSW", ops...) } func (o Opcodes) Pminub(ops ...Operand) { o.a.op("PMINUB", ops...) } func (o Opcodes) PMINUB(ops ...Operand) { o.a.op("PMINUB", ops...) } func (o Opcodes) Pmovmskb(ops ...Operand) { o.a.op("PMOVMSKB", ops...) } func (o Opcodes) PMOVMSKB(ops ...Operand) { o.a.op("PMOVMSKB", ops...) } func (o Opcodes) Pmovsxbd(ops ...Operand) { o.a.op("PMOVSXBD", ops...) } func (o Opcodes) PMOVSXBD(ops ...Operand) { o.a.op("PMOVSXBD", ops...) } func (o Opcodes) Pmovsxbq(ops ...Operand) { o.a.op("PMOVSXBQ", ops...) } func (o Opcodes) PMOVSXBQ(ops ...Operand) { o.a.op("PMOVSXBQ", ops...) } func (o Opcodes) Pmovsxbw(ops ...Operand) { o.a.op("PMOVSXBW", ops...) } func (o Opcodes) PMOVSXBW(ops ...Operand) { o.a.op("PMOVSXBW", ops...) } func (o Opcodes) Pmovsxdq(ops ...Operand) { o.a.op("PMOVSXDQ", ops...) } func (o Opcodes) PMOVSXDQ(ops ...Operand) { o.a.op("PMOVSXDQ", ops...) } func (o Opcodes) Pmovsxwd(ops ...Operand) { o.a.op("PMOVSXWD", ops...) } func (o Opcodes) PMOVSXWD(ops ...Operand) { o.a.op("PMOVSXWD", ops...) } func (o Opcodes) Pmovsxwq(ops ...Operand) { o.a.op("PMOVSXWQ", ops...) } func (o Opcodes) PMOVSXWQ(ops ...Operand) { o.a.op("PMOVSXWQ", ops...) } func (o Opcodes) Pmovzxbd(ops ...Operand) { o.a.op("PMOVZXBD", ops...) } func (o Opcodes) PMOVZXBD(ops ...Operand) { o.a.op("PMOVZXBD", ops...) } func (o Opcodes) Pmovzxbq(ops ...Operand) { o.a.op("PMOVZXBQ", ops...) } func (o Opcodes) PMOVZXBQ(ops ...Operand) { o.a.op("PMOVZXBQ", ops...) } func (o Opcodes) Pmovzxbw(ops ...Operand) { o.a.op("PMOVZXBW", ops...) } func (o Opcodes) PMOVZXBW(ops ...Operand) { o.a.op("PMOVZXBW", ops...) } func (o Opcodes) Pmovzxdq(ops ...Operand) { o.a.op("PMOVZXDQ", ops...) } func (o Opcodes) PMOVZXDQ(ops ...Operand) { o.a.op("PMOVZXDQ", ops...) } func (o Opcodes) Pmovzxwd(ops ...Operand) { o.a.op("PMOVZXWD", ops...) } func (o Opcodes) PMOVZXWD(ops ...Operand) { o.a.op("PMOVZXWD", ops...) } func (o Opcodes) Pmovzxwq(ops ...Operand) { o.a.op("PMOVZXWQ", ops...) } func (o Opcodes) PMOVZXWQ(ops ...Operand) { o.a.op("PMOVZXWQ", ops...) } func (o Opcodes) Pmuldq(ops ...Operand) { o.a.op("PMULDQ", ops...) } func (o Opcodes) PMULDQ(ops ...Operand) { o.a.op("PMULDQ", ops...) } func (o Opcodes) Pmulhuw(ops ...Operand) { o.a.op("PMULHUW", ops...) } func (o Opcodes) PMULHUW(ops ...Operand) { o.a.op("PMULHUW", ops...) } func (o Opcodes) Pmulhw(ops ...Operand) { o.a.op("PMULHW", ops...) } func (o Opcodes) PMULHW(ops ...Operand) { o.a.op("PMULHW", ops...) } func (o Opcodes) Pmulld(ops ...Operand) { o.a.op("PMULLD", ops...) } func (o Opcodes) PMULLD(ops ...Operand) { o.a.op("PMULLD", ops...) } func (o Opcodes) Pmullw(ops ...Operand) { o.a.op("PMULLW", ops...) } func (o Opcodes) PMULLW(ops ...Operand) { o.a.op("PMULLW", ops...) } func (o Opcodes) Pmululq(ops ...Operand) { o.a.op("PMULULQ", ops...) } func (o Opcodes) PMULULQ(ops ...Operand) { o.a.op("PMULULQ", ops...) } func (o Opcodes) Por(ops ...Operand) { o.a.op("POR", ops...) } func (o Opcodes) POR(ops ...Operand) { o.a.op("POR", ops...) } func (o Opcodes) Psadbw(ops ...Operand) { o.a.op("PSADBW", ops...) } func (o Opcodes) PSADBW(ops ...Operand) { o.a.op("PSADBW", ops...) } func (o Opcodes) Pshufb(ops ...Operand) { o.a.op("PSHUFB", ops...) } func (o Opcodes) PSHUFB(ops ...Operand) { o.a.op("PSHUFB", ops...) } func (o Opcodes) Pshufhw(ops ...Operand) { o.a.op("PSHUFHW", ops...) } func (o Opcodes) PSHUFHW(ops ...Operand) { o.a.op("PSHUFHW", ops...) } func (o Opcodes) Pshufl(ops ...Operand) { o.a.op("PSHUFL", ops...) } func (o Opcodes) PSHUFL(ops ...Operand) { o.a.op("PSHUFL", ops...) } func (o Opcodes) Pshuflw(ops ...Operand) { o.a.op("PSHUFLW", ops...) } func (o Opcodes) PSHUFLW(ops ...Operand) { o.a.op("PSHUFLW", ops...) } func (o Opcodes) Pshufw(ops ...Operand) { o.a.op("PSHUFW", ops...) } func (o Opcodes) PSHUFW(ops ...Operand) { o.a.op("PSHUFW", ops...) } func (o Opcodes) Pslll(ops ...Operand) { o.a.op("PSLLL", ops...) } func (o Opcodes) PSLLL(ops ...Operand) { o.a.op("PSLLL", ops...) } func (o Opcodes) Psllo(ops ...Operand) { o.a.op("PSLLO", ops...) } func (o Opcodes) PSLLO(ops ...Operand) { o.a.op("PSLLO", ops...) } func (o Opcodes) Psllq(ops ...Operand) { o.a.op("PSLLQ", ops...) } func (o Opcodes) PSLLQ(ops ...Operand) { o.a.op("PSLLQ", ops...) } func (o Opcodes) Psllw(ops ...Operand) { o.a.op("PSLLW", ops...) } func (o Opcodes) PSLLW(ops ...Operand) { o.a.op("PSLLW", ops...) } func (o Opcodes) Psral(ops ...Operand) { o.a.op("PSRAL", ops...) } func (o Opcodes) PSRAL(ops ...Operand) { o.a.op("PSRAL", ops...) } func (o Opcodes) Psraw(ops ...Operand) { o.a.op("PSRAW", ops...) } func (o Opcodes) PSRAW(ops ...Operand) { o.a.op("PSRAW", ops...) } func (o Opcodes) Psrll(ops ...Operand) { o.a.op("PSRLL", ops...) } func (o Opcodes) PSRLL(ops ...Operand) { o.a.op("PSRLL", ops...) } func (o Opcodes) Psrlo(ops ...Operand) { o.a.op("PSRLO", ops...) } func (o Opcodes) PSRLO(ops ...Operand) { o.a.op("PSRLO", ops...) } func (o Opcodes) Psrlq(ops ...Operand) { o.a.op("PSRLQ", ops...) } func (o Opcodes) PSRLQ(ops ...Operand) { o.a.op("PSRLQ", ops...) } func (o Opcodes) Psrlw(ops ...Operand) { o.a.op("PSRLW", ops...) } func (o Opcodes) PSRLW(ops ...Operand) { o.a.op("PSRLW", ops...) } func (o Opcodes) Psubb(ops ...Operand) { o.a.op("PSUBB", ops...) } func (o Opcodes) PSUBB(ops ...Operand) { o.a.op("PSUBB", ops...) } func (o Opcodes) Psubl(ops ...Operand) { o.a.op("PSUBL", ops...) } func (o Opcodes) PSUBL(ops ...Operand) { o.a.op("PSUBL", ops...) } func (o Opcodes) Psubq(ops ...Operand) { o.a.op("PSUBQ", ops...) } func (o Opcodes) PSUBQ(ops ...Operand) { o.a.op("PSUBQ", ops...) } func (o Opcodes) Psubsb(ops ...Operand) { o.a.op("PSUBSB", ops...) } func (o Opcodes) PSUBSB(ops ...Operand) { o.a.op("PSUBSB", ops...) } func (o Opcodes) Psubsw(ops ...Operand) { o.a.op("PSUBSW", ops...) } func (o Opcodes) PSUBSW(ops ...Operand) { o.a.op("PSUBSW", ops...) } func (o Opcodes) Psubusb(ops ...Operand) { o.a.op("PSUBUSB", ops...) } func (o Opcodes) PSUBUSB(ops ...Operand) { o.a.op("PSUBUSB", ops...) } func (o Opcodes) Psubusw(ops ...Operand) { o.a.op("PSUBUSW", ops...) } func (o Opcodes) PSUBUSW(ops ...Operand) { o.a.op("PSUBUSW", ops...) } func (o Opcodes) Psubw(ops ...Operand) { o.a.op("PSUBW", ops...) } func (o Opcodes) PSUBW(ops ...Operand) { o.a.op("PSUBW", ops...) } func (o Opcodes) Punpckhbw(ops ...Operand) { o.a.op("PUNPCKHBW", ops...) } func (o Opcodes) PUNPCKHBW(ops ...Operand) { o.a.op("PUNPCKHBW", ops...) } func (o Opcodes) Punpckhlq(ops ...Operand) { o.a.op("PUNPCKHLQ", ops...) } func (o Opcodes) PUNPCKHLQ(ops ...Operand) { o.a.op("PUNPCKHLQ", ops...) } func (o Opcodes) Punpckhqdq(ops ...Operand) { o.a.op("PUNPCKHQDQ", ops...) } func (o Opcodes) PUNPCKHQDQ(ops ...Operand) { o.a.op("PUNPCKHQDQ", ops...) } func (o Opcodes) Punpckhwl(ops ...Operand) { o.a.op("PUNPCKHWL", ops...) } func (o Opcodes) PUNPCKHWL(ops ...Operand) { o.a.op("PUNPCKHWL", ops...) } func (o Opcodes) Punpcklbw(ops ...Operand) { o.a.op("PUNPCKLBW", ops...) } func (o Opcodes) PUNPCKLBW(ops ...Operand) { o.a.op("PUNPCKLBW", ops...) } func (o Opcodes) Punpckllq(ops ...Operand) { o.a.op("PUNPCKLLQ", ops...) } func (o Opcodes) PUNPCKLLQ(ops ...Operand) { o.a.op("PUNPCKLLQ", ops...) } func (o Opcodes) Punpcklqdq(ops ...Operand) { o.a.op("PUNPCKLQDQ", ops...) } func (o Opcodes) PUNPCKLQDQ(ops ...Operand) { o.a.op("PUNPCKLQDQ", ops...) } func (o Opcodes) Punpcklwl(ops ...Operand) { o.a.op("PUNPCKLWL", ops...) } func (o Opcodes) PUNPCKLWL(ops ...Operand) { o.a.op("PUNPCKLWL", ops...) } func (o Opcodes) Pxor(ops ...Operand) { o.a.op("PXOR", ops...) } func (o Opcodes) PXOR(ops ...Operand) { o.a.op("PXOR", ops...) } func (o Opcodes) Rcpps(ops ...Operand) { o.a.op("RCPPS", ops...) } func (o Opcodes) RCPPS(ops ...Operand) { o.a.op("RCPPS", ops...) } func (o Opcodes) Rcpss(ops ...Operand) { o.a.op("RCPSS", ops...) } func (o Opcodes) RCPSS(ops ...Operand) { o.a.op("RCPSS", ops...) } func (o Opcodes) Rsqrtps(ops ...Operand) { o.a.op("RSQRTPS", ops...) } func (o Opcodes) RSQRTPS(ops ...Operand) { o.a.op("RSQRTPS", ops...) } func (o Opcodes) Rsqrtss(ops ...Operand) { o.a.op("RSQRTSS", ops...) } func (o Opcodes) RSQRTSS(ops ...Operand) { o.a.op("RSQRTSS", ops...) } func (o Opcodes) Sarxl(ops ...Operand) { o.a.op("SARXL", ops...) } func (o Opcodes) SARXL(ops ...Operand) { o.a.op("SARXL", ops...) } func (o Opcodes) Sarxq(ops ...Operand) { o.a.op("SARXQ", ops...) } func (o Opcodes) SARXQ(ops ...Operand) { o.a.op("SARXQ", ops...) } func (o Opcodes) Shlxl(ops ...Operand) { o.a.op("SHLXL", ops...) } func (o Opcodes) SHLXL(ops ...Operand) { o.a.op("SHLXL", ops...) } func (o Opcodes) Shlxq(ops ...Operand) { o.a.op("SHLXQ", ops...) } func (o Opcodes) SHLXQ(ops ...Operand) { o.a.op("SHLXQ", ops...) } func (o Opcodes) Shrxl(ops ...Operand) { o.a.op("SHRXL", ops...) } func (o Opcodes) SHRXL(ops ...Operand) { o.a.op("SHRXL", ops...) } func (o Opcodes) Shrxq(ops ...Operand) { o.a.op("SHRXQ", ops...) } func (o Opcodes) SHRXQ(ops ...Operand) { o.a.op("SHRXQ", ops...) } func (o Opcodes) Shufpd(ops ...Operand) { o.a.op("SHUFPD", ops...) } func (o Opcodes) SHUFPD(ops ...Operand) { o.a.op("SHUFPD", ops...) } func (o Opcodes) Shufps(ops ...Operand) { o.a.op("SHUFPS", ops...) } func (o Opcodes) SHUFPS(ops ...Operand) { o.a.op("SHUFPS", ops...) } func (o Opcodes) Sqrtpd(ops ...Operand) { o.a.op("SQRTPD", ops...) } func (o Opcodes) SQRTPD(ops ...Operand) { o.a.op("SQRTPD", ops...) } func (o Opcodes) Sqrtps(ops ...Operand) { o.a.op("SQRTPS", ops...) } func (o Opcodes) SQRTPS(ops ...Operand) { o.a.op("SQRTPS", ops...) } func (o Opcodes) Sqrtsd(ops ...Operand) { o.a.op("SQRTSD", ops...) } func (o Opcodes) SQRTSD(ops ...Operand) { o.a.op("SQRTSD", ops...) } func (o Opcodes) Sqrtss(ops ...Operand) { o.a.op("SQRTSS", ops...) } func (o Opcodes) SQRTSS(ops ...Operand) { o.a.op("SQRTSS", ops...) } func (o Opcodes) Stmxcsr(ops ...Operand) { o.a.op("STMXCSR", ops...) } func (o Opcodes) STMXCSR(ops ...Operand) { o.a.op("STMXCSR", ops...) } func (o Opcodes) Subpd(ops ...Operand) { o.a.op("SUBPD", ops...) } func (o Opcodes) SUBPD(ops ...Operand) { o.a.op("SUBPD", ops...) } func (o Opcodes) Subps(ops ...Operand) { o.a.op("SUBPS", ops...) } func (o Opcodes) SUBPS(ops ...Operand) { o.a.op("SUBPS", ops...) } func (o Opcodes) Subsd(ops ...Operand) { o.a.op("SUBSD", ops...) } func (o Opcodes) SUBSD(ops ...Operand) { o.a.op("SUBSD", ops...) } func (o Opcodes) Subss(ops ...Operand) { o.a.op("SUBSS", ops...) } func (o Opcodes) SUBSS(ops ...Operand) { o.a.op("SUBSS", ops...) } func (o Opcodes) Ucomisd(ops ...Operand) { o.a.op("UCOMISD", ops...) } func (o Opcodes) UCOMISD(ops ...Operand) { o.a.op("UCOMISD", ops...) } func (o Opcodes) Ucomiss(ops ...Operand) { o.a.op("UCOMISS", ops...) } func (o Opcodes) UCOMISS(ops ...Operand) { o.a.op("UCOMISS", ops...) } func (o Opcodes) Unpckhpd(ops ...Operand) { o.a.op("UNPCKHPD", ops...) } func (o Opcodes) UNPCKHPD(ops ...Operand) { o.a.op("UNPCKHPD", ops...) } func (o Opcodes) Unpckhps(ops ...Operand) { o.a.op("UNPCKHPS", ops...) } func (o Opcodes) UNPCKHPS(ops ...Operand) { o.a.op("UNPCKHPS", ops...) } func (o Opcodes) Unpcklpd(ops ...Operand) { o.a.op("UNPCKLPD", ops...) } func (o Opcodes) UNPCKLPD(ops ...Operand) { o.a.op("UNPCKLPD", ops...) } func (o Opcodes) Unpcklps(ops ...Operand) { o.a.op("UNPCKLPS", ops...) } func (o Opcodes) UNPCKLPS(ops ...Operand) { o.a.op("UNPCKLPS", ops...) } func (o Opcodes) Xorpd(ops ...Operand) { o.a.op("XORPD", ops...) } func (o Opcodes) XORPD(ops ...Operand) { o.a.op("XORPD", ops...) } func (o Opcodes) Xorps(ops ...Operand) { o.a.op("XORPS", ops...) } func (o Opcodes) XORPS(ops ...Operand) { o.a.op("XORPS", ops...) } func (o Opcodes) Pcmpestri(ops ...Operand) { o.a.op("PCMPESTRI", ops...) } func (o Opcodes) PCMPESTRI(ops ...Operand) { o.a.op("PCMPESTRI", ops...) } func (o Opcodes) Retfw(ops ...Operand) { o.a.op("RETFW", ops...) } func (o Opcodes) RETFW(ops ...Operand) { o.a.op("RETFW", ops...) } func (o Opcodes) Retfl(ops ...Operand) { o.a.op("RETFL", ops...) } func (o Opcodes) RETFL(ops ...Operand) { o.a.op("RETFL", ops...) } func (o Opcodes) Retfq(ops ...Operand) { o.a.op("RETFQ", ops...) } func (o Opcodes) RETFQ(ops ...Operand) { o.a.op("RETFQ", ops...) } func (o Opcodes) Swapgs(ops ...Operand) { o.a.op("SWAPGS", ops...) } func (o Opcodes) SWAPGS(ops ...Operand) { o.a.op("SWAPGS", ops...) } func (o Opcodes) Crc32b(ops ...Operand) { o.a.op("CRC32B", ops...) } func (o Opcodes) CRC32B(ops ...Operand) { o.a.op("CRC32B", ops...) } func (o Opcodes) Crc32q(ops ...Operand) { o.a.op("CRC32Q", ops...) } func (o Opcodes) CRC32Q(ops ...Operand) { o.a.op("CRC32Q", ops...) } func (o Opcodes) Imul3q(ops ...Operand) { o.a.op("IMUL3Q", ops...) } func (o Opcodes) IMUL3Q(ops ...Operand) { o.a.op("IMUL3Q", ops...) } func (o Opcodes) Prefetcht0(ops ...Operand) { o.a.op("PREFETCHT0", ops...) } func (o Opcodes) PREFETCHT0(ops ...Operand) { o.a.op("PREFETCHT0", ops...) } func (o Opcodes) Prefetcht1(ops ...Operand) { o.a.op("PREFETCHT1", ops...) } func (o Opcodes) PREFETCHT1(ops ...Operand) { o.a.op("PREFETCHT1", ops...) } func (o Opcodes) Prefetcht2(ops ...Operand) { o.a.op("PREFETCHT2", ops...) } func (o Opcodes) PREFETCHT2(ops ...Operand) { o.a.op("PREFETCHT2", ops...) } func (o Opcodes) Prefetchnta(ops ...Operand) { o.a.op("PREFETCHNTA", ops...) } func (o Opcodes) PREFETCHNTA(ops ...Operand) { o.a.op("PREFETCHNTA", ops...) } func (o Opcodes) Movql(ops ...Operand) { o.a.op("MOVQL", ops...) } func (o Opcodes) MOVQL(ops ...Operand) { o.a.op("MOVQL", ops...) } func (o Opcodes) Bswapl(ops ...Operand) { o.a.op("BSWAPL", ops...) } func (o Opcodes) BSWAPL(ops ...Operand) { o.a.op("BSWAPL", ops...) } func (o Opcodes) Bswapq(ops ...Operand) { o.a.op("BSWAPQ", ops...) } func (o Opcodes) BSWAPQ(ops ...Operand) { o.a.op("BSWAPQ", ops...) } func (o Opcodes) Aesenc(ops ...Operand) { o.a.op("AESENC", ops...) } func (o Opcodes) AESENC(ops ...Operand) { o.a.op("AESENC", ops...) } func (o Opcodes) Aesenclast(ops ...Operand) { o.a.op("AESENCLAST", ops...) } func (o Opcodes) AESENCLAST(ops ...Operand) { o.a.op("AESENCLAST", ops...) } func (o Opcodes) Aesdec(ops ...Operand) { o.a.op("AESDEC", ops...) } func (o Opcodes) AESDEC(ops ...Operand) { o.a.op("AESDEC", ops...) } func (o Opcodes) Aesdeclast(ops ...Operand) { o.a.op("AESDECLAST", ops...) } func (o Opcodes) AESDECLAST(ops ...Operand) { o.a.op("AESDECLAST", ops...) } func (o Opcodes) Aesimc(ops ...Operand) { o.a.op("AESIMC", ops...) } func (o Opcodes) AESIMC(ops ...Operand) { o.a.op("AESIMC", ops...) } func (o Opcodes) Aeskeygenassist(ops ...Operand) { o.a.op("AESKEYGENASSIST", ops...) } func (o Opcodes) AESKEYGENASSIST(ops ...Operand) { o.a.op("AESKEYGENASSIST", ops...) } func (o Opcodes) Roundps(ops ...Operand) { o.a.op("ROUNDPS", ops...) } func (o Opcodes) ROUNDPS(ops ...Operand) { o.a.op("ROUNDPS", ops...) } func (o Opcodes) Roundss(ops ...Operand) { o.a.op("ROUNDSS", ops...) } func (o Opcodes) ROUNDSS(ops ...Operand) { o.a.op("ROUNDSS", ops...) } func (o Opcodes) Roundpd(ops ...Operand) { o.a.op("ROUNDPD", ops...) } func (o Opcodes) ROUNDPD(ops ...Operand) { o.a.op("ROUNDPD", ops...) } func (o Opcodes) Roundsd(ops ...Operand) { o.a.op("ROUNDSD", ops...) } func (o Opcodes) ROUNDSD(ops ...Operand) { o.a.op("ROUNDSD", ops...) } func (o Opcodes) Movddup(ops ...Operand) { o.a.op("MOVDDUP", ops...) } func (o Opcodes) MOVDDUP(ops ...Operand) { o.a.op("MOVDDUP", ops...) } func (o Opcodes) Movshdup(ops ...Operand) { o.a.op("MOVSHDUP", ops...) } func (o Opcodes) MOVSHDUP(ops ...Operand) { o.a.op("MOVSHDUP", ops...) } func (o Opcodes) Movsldup(ops ...Operand) { o.a.op("MOVSLDUP", ops...) } func (o Opcodes) MOVSLDUP(ops ...Operand) { o.a.op("MOVSLDUP", ops...) } func (o Opcodes) Pshufd(ops ...Operand) { o.a.op("PSHUFD", ops...) } func (o Opcodes) PSHUFD(ops ...Operand) { o.a.op("PSHUFD", ops...) } func (o Opcodes) Pclmulqdq(ops ...Operand) { o.a.op("PCLMULQDQ", ops...) } func (o Opcodes) PCLMULQDQ(ops ...Operand) { o.a.op("PCLMULQDQ", ops...) } func (o Opcodes) Vzeroupper(ops ...Operand) { o.a.op("VZEROUPPER", ops...) } func (o Opcodes) VZEROUPPER(ops ...Operand) { o.a.op("VZEROUPPER", ops...) } func (o Opcodes) Vmovdqu(ops ...Operand) { o.a.op("VMOVDQU", ops...) } func (o Opcodes) VMOVDQU(ops ...Operand) { o.a.op("VMOVDQU", ops...) } func (o Opcodes) Vmovntdq(ops ...Operand) { o.a.op("VMOVNTDQ", ops...) } func (o Opcodes) VMOVNTDQ(ops ...Operand) { o.a.op("VMOVNTDQ", ops...) } func (o Opcodes) Vmovdqa(ops ...Operand) { o.a.op("VMOVDQA", ops...) } func (o Opcodes) VMOVDQA(ops ...Operand) { o.a.op("VMOVDQA", ops...) } func (o Opcodes) Vpcmpeqb(ops ...Operand) { o.a.op("VPCMPEQB", ops...) } func (o Opcodes) VPCMPEQB(ops ...Operand) { o.a.op("VPCMPEQB", ops...) } func (o Opcodes) Vpxor(ops ...Operand) { o.a.op("VPXOR", ops...) } func (o Opcodes) VPXOR(ops ...Operand) { o.a.op("VPXOR", ops...) } func (o Opcodes) Vpmovmskb(ops ...Operand) { o.a.op("VPMOVMSKB", ops...) } func (o Opcodes) VPMOVMSKB(ops ...Operand) { o.a.op("VPMOVMSKB", ops...) } func (o Opcodes) Vpand(ops ...Operand) { o.a.op("VPAND", ops...) } func (o Opcodes) VPAND(ops ...Operand) { o.a.op("VPAND", ops...) } func (o Opcodes) Vptest(ops ...Operand) { o.a.op("VPTEST", ops...) } func (o Opcodes) VPTEST(ops ...Operand) { o.a.op("VPTEST", ops...) } func (o Opcodes) Vpbroadcastb(ops ...Operand) { o.a.op("VPBROADCASTB", ops...) } func (o Opcodes) VPBROADCASTB(ops ...Operand) { o.a.op("VPBROADCASTB", ops...) } func (o Opcodes) Vpshufb(ops ...Operand) { o.a.op("VPSHUFB", ops...) } func (o Opcodes) VPSHUFB(ops ...Operand) { o.a.op("VPSHUFB", ops...) } func (o Opcodes) Vpshufd(ops ...Operand) { o.a.op("VPSHUFD", ops...) } func (o Opcodes) VPSHUFD(ops ...Operand) { o.a.op("VPSHUFD", ops...) } func (o Opcodes) Vperm2f128(ops ...Operand) { o.a.op("VPERM2F128", ops...) } func (o Opcodes) VPERM2F128(ops ...Operand) { o.a.op("VPERM2F128", ops...) } func (o Opcodes) Vpalignr(ops ...Operand) { o.a.op("VPALIGNR", ops...) } func (o Opcodes) VPALIGNR(ops ...Operand) { o.a.op("VPALIGNR", ops...) } func (o Opcodes) Vpaddq(ops ...Operand) { o.a.op("VPADDQ", ops...) } func (o Opcodes) VPADDQ(ops ...Operand) { o.a.op("VPADDQ", ops...) } func (o Opcodes) Vpaddd(ops ...Operand) { o.a.op("VPADDD", ops...) } func (o Opcodes) VPADDD(ops ...Operand) { o.a.op("VPADDD", ops...) } func (o Opcodes) Vpsrldq(ops ...Operand) { o.a.op("VPSRLDQ", ops...) } func (o Opcodes) VPSRLDQ(ops ...Operand) { o.a.op("VPSRLDQ", ops...) } func (o Opcodes) Vpslldq(ops ...Operand) { o.a.op("VPSLLDQ", ops...) } func (o Opcodes) VPSLLDQ(ops ...Operand) { o.a.op("VPSLLDQ", ops...) } func (o Opcodes) Vpsrlq(ops ...Operand) { o.a.op("VPSRLQ", ops...) } func (o Opcodes) VPSRLQ(ops ...Operand) { o.a.op("VPSRLQ", ops...) } func (o Opcodes) Vpsllq(ops ...Operand) { o.a.op("VPSLLQ", ops...) } func (o Opcodes) VPSLLQ(ops ...Operand) { o.a.op("VPSLLQ", ops...) } func (o Opcodes) Vpsrld(ops ...Operand) { o.a.op("VPSRLD", ops...) } func (o Opcodes) VPSRLD(ops ...Operand) { o.a.op("VPSRLD", ops...) } func (o Opcodes) Vpslld(ops ...Operand) { o.a.op("VPSLLD", ops...) } func (o Opcodes) VPSLLD(ops ...Operand) { o.a.op("VPSLLD", ops...) } func (o Opcodes) Vpor(ops ...Operand) { o.a.op("VPOR", ops...) } func (o Opcodes) VPOR(ops ...Operand) { o.a.op("VPOR", ops...) } func (o Opcodes) Vpblendd(ops ...Operand) { o.a.op("VPBLENDD", ops...) } func (o Opcodes) VPBLENDD(ops ...Operand) { o.a.op("VPBLENDD", ops...) } func (o Opcodes) Vinserti128(ops ...Operand) { o.a.op("VINSERTI128", ops...) } func (o Opcodes) VINSERTI128(ops ...Operand) { o.a.op("VINSERTI128", ops...) } func (o Opcodes) Vperm2i128(ops ...Operand) { o.a.op("VPERM2I128", ops...) } func (o Opcodes) VPERM2I128(ops ...Operand) { o.a.op("VPERM2I128", ops...) } func (o Opcodes) Rorxl(ops ...Operand) { o.a.op("RORXL", ops...) } func (o Opcodes) RORXL(ops ...Operand) { o.a.op("RORXL", ops...) } func (o Opcodes) Rorxq(ops ...Operand) { o.a.op("RORXQ", ops...) } func (o Opcodes) RORXQ(ops ...Operand) { o.a.op("RORXQ", ops...) } func (o Opcodes) Vbroadcastss(ops ...Operand) { o.a.op("VBROADCASTSS", ops...) } func (o Opcodes) VBROADCASTSS(ops ...Operand) { o.a.op("VBROADCASTSS", ops...) } func (o Opcodes) Vbroadcastsd(ops ...Operand) { o.a.op("VBROADCASTSD", ops...) } func (o Opcodes) VBROADCASTSD(ops ...Operand) { o.a.op("VBROADCASTSD", ops...) } func (o Opcodes) Vmovddup(ops ...Operand) { o.a.op("VMOVDDUP", ops...) } func (o Opcodes) VMOVDDUP(ops ...Operand) { o.a.op("VMOVDDUP", ops...) } func (o Opcodes) Vmovshdup(ops ...Operand) { o.a.op("VMOVSHDUP", ops...) } func (o Opcodes) VMOVSHDUP(ops ...Operand) { o.a.op("VMOVSHDUP", ops...) } func (o Opcodes) Vmovsldup(ops ...Operand) { o.a.op("VMOVSLDUP", ops...) } func (o Opcodes) VMOVSLDUP(ops ...Operand) { o.a.op("VMOVSLDUP", ops...) } func (o Opcodes) Jcxzw(ops ...Operand) { o.a.op("JCXZW", ops...) } func (o Opcodes) JCXZW(ops ...Operand) { o.a.op("JCXZW", ops...) } func (o Opcodes) Fcmovcc(ops ...Operand) { o.a.op("FCMOVCC", ops...) } func (o Opcodes) FCMOVCC(ops ...Operand) { o.a.op("FCMOVCC", ops...) } func (o Opcodes) Fcmovcs(ops ...Operand) { o.a.op("FCMOVCS", ops...) } func (o Opcodes) FCMOVCS(ops ...Operand) { o.a.op("FCMOVCS", ops...) } func (o Opcodes) Fcmoveq(ops ...Operand) { o.a.op("FCMOVEQ", ops...) } func (o Opcodes) FCMOVEQ(ops ...Operand) { o.a.op("FCMOVEQ", ops...) } func (o Opcodes) Fcmovhi(ops ...Operand) { o.a.op("FCMOVHI", ops...) } func (o Opcodes) FCMOVHI(ops ...Operand) { o.a.op("FCMOVHI", ops...) } func (o Opcodes) Fcmovls(ops ...Operand) { o.a.op("FCMOVLS", ops...) } func (o Opcodes) FCMOVLS(ops ...Operand) { o.a.op("FCMOVLS", ops...) } func (o Opcodes) Fcmovne(ops ...Operand) { o.a.op("FCMOVNE", ops...) } func (o Opcodes) FCMOVNE(ops ...Operand) { o.a.op("FCMOVNE", ops...) } func (o Opcodes) Fcmovnu(ops ...Operand) { o.a.op("FCMOVNU", ops...) } func (o Opcodes) FCMOVNU(ops ...Operand) { o.a.op("FCMOVNU", ops...) } func (o Opcodes) Fcmovun(ops ...Operand) { o.a.op("FCMOVUN", ops...) } func (o Opcodes) FCMOVUN(ops ...Operand) { o.a.op("FCMOVUN", ops...) } func (o Opcodes) Fcomi(ops ...Operand) { o.a.op("FCOMI", ops...) } func (o Opcodes) FCOMI(ops ...Operand) { o.a.op("FCOMI", ops...) } func (o Opcodes) Fcomip(ops ...Operand) { o.a.op("FCOMIP", ops...) } func (o Opcodes) FCOMIP(ops ...Operand) { o.a.op("FCOMIP", ops...) } func (o Opcodes) Fucomi(ops ...Operand) { o.a.op("FUCOMI", ops...) } func (o Opcodes) FUCOMI(ops ...Operand) { o.a.op("FUCOMI", ops...) } func (o Opcodes) Fucomip(ops ...Operand) { o.a.op("FUCOMIP", ops...) } func (o Opcodes) FUCOMIP(ops ...Operand) { o.a.op("FUCOMIP", ops...) } func (o Opcodes) Xacquire(ops ...Operand) { o.a.op("XACQUIRE", ops...) } func (o Opcodes) XACQUIRE(ops ...Operand) { o.a.op("XACQUIRE", ops...) } func (o Opcodes) Xrelease(ops ...Operand) { o.a.op("XRELEASE", ops...) } func (o Opcodes) XRELEASE(ops ...Operand) { o.a.op("XRELEASE", ops...) } func (o Opcodes) Xbegin(ops ...Operand) { o.a.op("XBEGIN", ops...) } func (o Opcodes) XBEGIN(ops ...Operand) { o.a.op("XBEGIN", ops...) } func (o Opcodes) Xend(ops ...Operand) { o.a.op("XEND", ops...) } func (o Opcodes) XEND(ops ...Operand) { o.a.op("XEND", ops...) } func (o Opcodes) Xabort(ops ...Operand) { o.a.op("XABORT", ops...) } func (o Opcodes) XABORT(ops ...Operand) { o.a.op("XABORT", ops...) } func (o Opcodes) Xtest(ops ...Operand) { o.a.op("XTEST", ops...) } func (o Opcodes) XTEST(ops ...Operand) { o.a.op("XTEST", ops...) } func (o Opcodes) Last(ops ...Operand) { o.a.op("LAST", ops...) } func (o Opcodes) LAST(ops ...Operand) { o.a.op("LAST", ops...) }
vendor/github.com/tmthrgd/asm/opcode.go
0.544801
0.540863
opcode.go
starcoder
package glong import ( "github.com/goki/mat32" ) // GABABParams control the GABAB dynamics in PFC Maint neurons, based on Brunel & Wang (2001) // parameters. We have to do some things to make it work for rate code neurons.. type GABABParams struct { RiseTau float32 `def:"45" desc:"rise time for bi-exponential time dynamics of GABA-B"` DecayTau float32 `def:"50" desc:"decay time for bi-exponential time dynamics of GABA-B"` Gbar float32 `def:"0.2" desc:"overall strength multiplier of GABA-B current"` Gbase float32 `def:"0.2" desc:"baseline level of GABA-B channels open independent of inhibitory input (is added to spiking-produced conductance)"` Smult float32 `def:"15" desc:"multiplier for converting Gi from FFFB to GABA spikes"` MaxTime float32 `inactive:"+" desc:"time offset when peak conductance occurs, in msec, computed from RiseTau and DecayTau"` TauFact float32 `view:"-" desc:"time constant factor used in integration: (Decay / Rise) ^ (Rise / (Decay - Rise))"` } func (gp *GABABParams) Defaults() { gp.RiseTau = 45 gp.DecayTau = 50 gp.Gbar = 0.2 gp.Gbase = 0.2 gp.Smult = 15 gp.Update() } func (gp *GABABParams) Update() { gp.TauFact = mat32.Pow(gp.DecayTau/gp.RiseTau, gp.RiseTau/(gp.DecayTau-gp.RiseTau)) gp.MaxTime = ((gp.RiseTau * gp.DecayTau) / (gp.DecayTau - gp.RiseTau)) * mat32.Log(gp.DecayTau/gp.RiseTau) } // GFmV returns the GABA-B conductance as a function of normalized membrane potential func (gp *GABABParams) GFmV(v float32) float32 { vbio := mat32.Max(v*100-100, -90) // critical to not go past -90 return 1 / (1 + mat32.FastExp(0.1*((vbio+90)+10))) } // GFmS returns the GABA-B conductance as a function of GABA spiking rate, // based on normalized spiking factor (i.e., Gi from FFFB etc) func (gp *GABABParams) GFmS(s float32) float32 { ss := s * gp.Smult // convert to spikes return 1 / (1 + mat32.FastExp(-(ss-7.1)/1.4)) } // BiExp computes bi-exponential update, returns dG and dX deltas to add to g and x func (gp *GABABParams) BiExp(g, x float32) (dG, dX float32) { dG = (gp.TauFact*x - g) / gp.RiseTau dX = -x / gp.DecayTau return } // GABAB returns the updated GABA-B / GIRK activation and underlying x value // based on current values and gi inhibitory conductance (proxy for GABA spikes) func (gp *GABABParams) GABAB(gabaB, gabaBx, gi float32) (g, x float32) { dG, dX := gp.BiExp(gabaB, gabaBx) x = gabaBx + gp.GFmS(gi) + dX // gets new input g = gabaB + dG return } // GgabaB returns the overall net GABAB / GIRK conductance including // Gbar, Gbase, and voltage-gating func (gp *GABABParams) GgabaB(gabaB, vm float32) float32 { return gp.Gbar * gp.GFmV(vm) * (gabaB + gp.Gbase) }
glong/gabab.go
0.811825
0.510863
gabab.go
starcoder
package engine import ( "fmt" "github.com/proullon/ramsql/engine/log" "github.com/proullon/ramsql/engine/parser" "strconv" "time" ) // Operator compares 2 values and return a boolean type Operator func(leftValue Value, rightValue Value) bool // NewOperator initializes the operator matching the Token number func NewOperator(token int, lexeme string) (Operator, error) { switch token { case parser.EqualityToken: return equalityOperator, nil case parser.DistinctnessToken: return distinctnessOperator, nil case parser.LeftDipleToken: return lessThanOperator, nil case parser.RightDipleToken: return greaterThanOperator, nil case parser.LessOrEqualToken: return lessOrEqualOperator, nil case parser.GreaterOrEqualToken: return greaterOrEqualOperator, nil } return nil, fmt.Errorf("Operator '%s' does not exist", lexeme) } func convToDate(t interface{}) (time.Time, error) { switch t := t.(type) { default: log.Debug("convToDate> unexpected type %T\n", t) return time.Time{}, fmt.Errorf("unexpected internal type %T", t) case string: d, err := parser.ParseDate(string(t)) if err != nil { return time.Time{}, fmt.Errorf("cannot parse date %v", t) } return *d, nil } } func convToFloat(t interface{}) (float64, error) { switch t := t.(type) { default: log.Debug("convToFloat> unexpected type %T\n", t) return 0, fmt.Errorf("unexpected internal type %T", t) case float64: return float64(t), nil case int64: return float64(int64(t)), nil case int: return float64(int(t)), nil case string: return strconv.ParseFloat(string(t), 64) } } func greaterThanOperator(leftValue Value, rightValue Value) bool { log.Debug("GreaterThanOperator") var left, right float64 var err error var rvalue interface{} if rightValue.v != nil { rvalue = rightValue.v } else { rvalue = rightValue.lexeme } var leftDate time.Time var isDate bool left, err = convToFloat(leftValue.v) if err != nil { leftDate, err = convToDate(leftValue.v) if err != nil { log.Debug("GreaterThanOperator> %s\n", err) return false } isDate = true } if !isDate { right, err = convToFloat(rvalue) if err != nil { log.Debug("GreaterThanOperator> %s\n", err) return false } return left > right } rightDate, err := convToDate(rvalue) if err != nil { log.Debug("GreaterThanOperator> %s\n", err) return false } return leftDate.After(rightDate) } func lessOrEqualOperator(leftValue Value, rightValue Value) bool { return lessThanOperator(leftValue, rightValue) || equalityOperator(leftValue, rightValue) } func greaterOrEqualOperator(leftValue Value, rightValue Value) bool { return greaterThanOperator(leftValue, rightValue) || equalityOperator(leftValue, rightValue) } func lessThanOperator(leftValue Value, rightValue Value) bool { log.Debug("LessThanOperator") var left, right float64 var err error var rvalue interface{} if rightValue.v != nil { rvalue = rightValue.v } else { rvalue = rightValue.lexeme } var leftDate time.Time var isDate bool left, err = convToFloat(leftValue.v) if err != nil { leftDate, err = convToDate(leftValue.v) if err != nil { log.Debug("LessThanOperator> %s\n", err) return false } isDate = true } if !isDate { right, err = convToFloat(rvalue) if err != nil { log.Debug("LessThanOperator> %s\n", err) return false } return left < right } rightDate, err := convToDate(rvalue) if err != nil { log.Debug("LessThanOperator> %s\n", err) return false } return leftDate.Before(rightDate) } // EqualityOperator checks if given value are equal func equalityOperator(leftValue Value, rightValue Value) bool { if fmt.Sprintf("%v", leftValue.v) == rightValue.lexeme { return true } return false } // DistinctnessOperator checks if given value are distinct func distinctnessOperator(leftValue Value, rightValue Value) bool { if fmt.Sprintf("%v", leftValue.v) != rightValue.lexeme { return true } return false } // TrueOperator always returns true func TrueOperator(leftValue Value, rightValue Value) bool { return true } func inOperator(leftValue Value, rightValue Value) bool { // Right value should be a slice of string values, ok := rightValue.v.([]string) if !ok { log.Debug("InOperator: rightValue.v is not a []string !") return false } for i := range values { log.Debug("InOperator: Testing %v against %s", leftValue.v, values[i]) if fmt.Sprintf("%v", leftValue.v) == values[i] { return true } } return false } func notInOperator(leftValue Value, rightValue Value) bool { return !inOperator(leftValue, rightValue) } func isNullOperator(leftValue Value, rightValue Value) bool { return leftValue.v == nil } func isNotNullOperator(leftValue Value, rightValue Value) bool { return leftValue.v != nil }
engine/operator.go
0.815416
0.533337
operator.go
starcoder
package main import ( "github.com/gen2brain/raylib-go/raylib" ) func main() { screenWidth := int32(800) screenHeight := int32(450) raylib.InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib logo animation") logoPositionX := screenWidth/2 - 128 logoPositionY := screenHeight/2 - 128 framesCounter := 0 lettersCount := int32(0) topSideRecWidth := int32(16) leftSideRecHeight := int32(16) bottomSideRecWidth := int32(16) rightSideRecHeight := int32(16) state := 0 // Tracking animation states (State Machine) alpha := float32(1.0) // Useful for fading raylib.SetTargetFPS(60) for !raylib.WindowShouldClose() { if state == 0 { // State 0: Small box blinking framesCounter++ if framesCounter == 120 { state = 1 framesCounter = 0 // Reset counter... will be used later... } } else if state == 1 { // State 1: Top and left bars growing topSideRecWidth += 4 leftSideRecHeight += 4 if topSideRecWidth == 256 { state = 2 } } else if state == 2 { // State 2: Bottom and right bars growing bottomSideRecWidth += 4 rightSideRecHeight += 4 if bottomSideRecWidth == 256 { state = 3 } } else if state == 3 { // State 3: Letters appearing (one by one) framesCounter++ if framesCounter%12 == 0 { // Every 12 frames, one more letter! lettersCount++ framesCounter = 0 } if lettersCount >= 6 { // When all letters have appeared, just fade out everything alpha -= 0.02 if alpha <= 0.0 { alpha = 0.0 state = 4 } } } else if state == 4 { // State 4: Reset and Replay if raylib.IsKeyPressed(raylib.KeyR) { framesCounter = 0 lettersCount = 0 topSideRecWidth = 16 leftSideRecHeight = 16 bottomSideRecWidth = 16 rightSideRecHeight = 16 alpha = 1.0 state = 0 // Return to State 0 } } raylib.BeginDrawing() raylib.ClearBackground(raylib.RayWhite) if state == 0 { if (framesCounter/15)%2 == 0 { raylib.DrawRectangle(logoPositionX, logoPositionY, 16, 16, raylib.Black) } } else if state == 1 { raylib.DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, raylib.Black) raylib.DrawRectangle(logoPositionX, logoPositionY, 16, leftSideRecHeight, raylib.Black) } else if state == 2 { raylib.DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, raylib.Black) raylib.DrawRectangle(logoPositionX, logoPositionY, 16, leftSideRecHeight, raylib.Black) raylib.DrawRectangle(logoPositionX+240, logoPositionY, 16, rightSideRecHeight, raylib.Black) raylib.DrawRectangle(logoPositionX, logoPositionY+240, bottomSideRecWidth, 16, raylib.Black) } else if state == 3 { raylib.DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, raylib.Fade(raylib.Black, alpha)) raylib.DrawRectangle(logoPositionX, logoPositionY+16, 16, leftSideRecHeight-32, raylib.Fade(raylib.Black, alpha)) raylib.DrawRectangle(logoPositionX+240, logoPositionY+16, 16, rightSideRecHeight-32, raylib.Fade(raylib.Black, alpha)) raylib.DrawRectangle(logoPositionX, logoPositionY+240, bottomSideRecWidth, 16, raylib.Fade(raylib.Black, alpha)) raylib.DrawRectangle(screenWidth/2-112, screenHeight/2-112, 224, 224, raylib.Fade(raylib.RayWhite, alpha)) text := "raylib" length := int32(len(text)) if lettersCount > length { lettersCount = length } raylib.DrawText(text[0:lettersCount], screenWidth/2-44, screenHeight/2+48, 50, raylib.Fade(raylib.Black, alpha)) } else if state == 4 { raylib.DrawText("[R] REPLAY", 340, 200, 20, raylib.Gray) } raylib.EndDrawing() } raylib.CloseWindow() }
examples/shapes/logo_raylib_anim/main.go
0.569972
0.480783
main.go
starcoder
package goja import ( "math" "time" ) const ( maxTime = 8.64e15 ) func timeFromMsec(msec int64) time.Time { sec := msec / 1000 nsec := (msec % 1000) * 1e6 return time.Unix(sec, nsec) } func makeDate(args []Value, loc *time.Location) (t time.Time, valid bool) { pick := func(index int, default_ int64) (int64, bool) { if index >= len(args) { return default_, true } value := args[index] if valueInt, ok := value.assertInt(); ok { return valueInt, true } valueFloat := value.ToFloat() if math.IsNaN(valueFloat) || math.IsInf(valueFloat, 0) { return 0, false } return int64(valueFloat), true } switch { case len(args) >= 2: var year, month, day, hour, minute, second, millisecond int64 if year, valid = pick(0, 1900); !valid { return } if month, valid = pick(1, 0); !valid { return } if day, valid = pick(2, 1); !valid { return } if hour, valid = pick(3, 0); !valid { return } if minute, valid = pick(4, 0); !valid { return } if second, valid = pick(5, 0); !valid { return } if millisecond, valid = pick(6, 0); !valid { return } if year >= 0 && year <= 99 { year += 1900 } t = time.Date(int(year), time.Month(int(month)+1), int(day), int(hour), int(minute), int(second), int(millisecond)*1e6, loc) case len(args) == 0: t = time.Now() valid = true default: // one argument pv := toPrimitiveNumber(args[0]) if val, ok := pv.assertString(); ok { return dateParse(val.String()) } var n int64 if i, ok := pv.assertInt(); ok { n = i } else if f, ok := pv.assertFloat(); ok { if math.IsNaN(f) || math.IsInf(f, 0) { return } if math.Abs(f) > maxTime { return } n = int64(f) } else { n = pv.ToInteger() } t = timeFromMsec(n) valid = true } msec := t.Unix()*1000 + int64(t.Nanosecond()/1e6) if msec < 0 { msec = -msec } if msec > maxTime { valid = false } return } func (r *Runtime) newDateTime(args []Value, loc *time.Location) *Object { t, isSet := makeDate(args, loc) return r.newDateObject(t, isSet) } func (r *Runtime) builtin_newDate(args []Value) *Object { return r.newDateTime(args, time.Local) } func (r *Runtime) builtin_date(call FunctionCall) Value { return asciiString(dateFormat(time.Now())) } func (r *Runtime) date_parse(call FunctionCall) Value { return r.newDateObject(dateParse(call.Argument(0).String())) } func (r *Runtime) date_UTC(call FunctionCall) Value { t, valid := makeDate(call.Arguments, time.UTC) if !valid { return _NaN } return intToValue(int64(t.UnixNano() / 1e6)) } func (r *Runtime) date_now(call FunctionCall) Value { return intToValue(time.Now().UnixNano() / 1e6) } func (r *Runtime) dateproto_toString(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return asciiString(d.time.Format(dateTimeLayout)) } else { return stringInvalidDate } } r.typeErrorResult(true, "Method Date.prototype.toString is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_toUTCString(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return asciiString(d.time.In(time.UTC).Format(dateTimeLayout)) } else { return stringInvalidDate } } r.typeErrorResult(true, "Method Date.prototype.toUTCString is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_toISOString(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return asciiString(d.time.In(time.UTC).Format(isoDateTimeLayout)) } else { panic(r.newError(r.global.RangeError, "Invalid time value")) } } r.typeErrorResult(true, "Method Date.prototype.toISOString is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_toJSON(call FunctionCall) Value { obj := r.toObject(call.This) tv := obj.self.toPrimitiveNumber() if f, ok := tv.assertFloat(); ok { if math.IsNaN(f) || math.IsInf(f, 0) { return _null } } else if _, ok := tv.assertInt(); !ok { return _null } if toISO, ok := obj.self.getStr("toISOString").(*Object); ok { if toISO, ok := toISO.self.assertCallable(); ok { return toISO(FunctionCall{ This: obj, }) } } r.typeErrorResult(true, "toISOString is not a function") panic("Unreachable") } func (r *Runtime) dateproto_toDateString(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return asciiString(d.time.Format(dateLayout)) } else { return stringInvalidDate } } r.typeErrorResult(true, "Method Date.prototype.toDateString is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_toTimeString(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return asciiString(d.time.Format(timeLayout)) } else { return stringInvalidDate } } r.typeErrorResult(true, "Method Date.prototype.toTimeString is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_toLocaleString(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return asciiString(d.time.Format(datetimeLayout_en_GB)) } else { return stringInvalidDate } } r.typeErrorResult(true, "Method Date.prototype.toLocaleString is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_toLocaleDateString(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return asciiString(d.time.Format(dateLayout_en_GB)) } else { return stringInvalidDate } } r.typeErrorResult(true, "Method Date.prototype.toLocaleDateString is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_toLocaleTimeString(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return asciiString(d.time.Format(timeLayout_en_GB)) } else { return stringInvalidDate } } r.typeErrorResult(true, "Method Date.prototype.toLocaleTimeString is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_valueOf(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(d.time.Unix()*1000 + int64(d.time.Nanosecond()/1e6)) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.valueOf is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getTime(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getTime is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getFullYear(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.Year())) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getFullYear is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getUTCFullYear(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.In(time.UTC).Year())) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getUTCFullYear is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getMonth(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.Month()) - 1) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getMonth is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getUTCMonth(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.In(time.UTC).Month()) - 1) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getUTCMonth is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getHours(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.Hour())) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getHours is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getUTCHours(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.In(time.UTC).Hour())) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getUTCHours is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getDate(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.Day())) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getDate is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getUTCDate(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.In(time.UTC).Day())) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getUTCDate is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getDay(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.Weekday())) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getDay is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getUTCDay(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.In(time.UTC).Weekday())) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getUTCDay is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getMinutes(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.Minute())) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getMinutes is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getUTCMinutes(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.In(time.UTC).Minute())) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getUTCMinutes is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getSeconds(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.Second())) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getSeconds is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getUTCSeconds(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.In(time.UTC).Second())) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getUTCSeconds is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getMilliseconds(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.Nanosecond() / 1e6)) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getMilliseconds is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getUTCMilliseconds(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { return intToValue(int64(d.time.In(time.UTC).Nanosecond() / 1e6)) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getUTCMilliseconds is called on incompatible receiver") return nil } func (r *Runtime) dateproto_getTimezoneOffset(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { _, offset := d.time.Zone() return intToValue(int64(-offset / 60)) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.getTimezoneOffset is called on incompatible receiver") return nil } func (r *Runtime) dateproto_setTime(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { msec := call.Argument(0).ToInteger() d.time = timeFromMsec(msec) return intToValue(msec) } r.typeErrorResult(true, "Method Date.prototype.setTime is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setMilliseconds(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { msec := int(call.Argument(0).ToInteger()) d.time = time.Date(d.time.Year(), d.time.Month(), d.time.Day(), d.time.Hour(), d.time.Minute(), d.time.Second(), msec*1e6, time.Local) return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.setMilliseconds is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setUTCMilliseconds(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { msec := int(call.Argument(0).ToInteger()) t := d.time.In(time.UTC) d.time = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), msec*1e6, time.UTC).In(time.Local) return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.setUTCMilliseconds is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setSeconds(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { sec := int(call.Argument(0).ToInteger()) var nsec int if len(call.Arguments) > 1 { nsec = int(call.Arguments[1].ToInteger() * 1e6) } else { nsec = d.time.Nanosecond() } d.time = time.Date(d.time.Year(), d.time.Month(), d.time.Day(), d.time.Hour(), d.time.Minute(), sec, nsec, time.Local) return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.setSeconds is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setUTCSeconds(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { sec := int(call.Argument(0).ToInteger()) var nsec int t := d.time.In(time.UTC) if len(call.Arguments) > 1 { nsec = int(call.Arguments[1].ToInteger() * 1e6) } else { nsec = t.Nanosecond() } d.time = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), sec, nsec, time.UTC).In(time.Local) return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.setUTCSeconds is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setMinutes(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { min := int(call.Argument(0).ToInteger()) var sec, nsec int if len(call.Arguments) > 1 { sec = int(call.Arguments[1].ToInteger()) } else { sec = d.time.Second() } if len(call.Arguments) > 2 { nsec = int(call.Arguments[2].ToInteger() * 1e6) } else { nsec = d.time.Nanosecond() } d.time = time.Date(d.time.Year(), d.time.Month(), d.time.Day(), d.time.Hour(), min, sec, nsec, time.Local) return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.setMinutes is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setUTCMinutes(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { min := int(call.Argument(0).ToInteger()) var sec, nsec int t := d.time.In(time.UTC) if len(call.Arguments) > 1 { sec = int(call.Arguments[1].ToInteger()) } else { sec = t.Second() } if len(call.Arguments) > 2 { nsec = int(call.Arguments[2].ToInteger() * 1e6) } else { nsec = t.Nanosecond() } d.time = time.Date(t.Year(), t.Month(), t.Day(), t.Hour(), min, sec, nsec, time.UTC).In(time.Local) return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.setUTCMinutes is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setHours(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { hour := int(call.Argument(0).ToInteger()) var min, sec, nsec int if len(call.Arguments) > 1 { min = int(call.Arguments[1].ToInteger()) } else { min = d.time.Minute() } if len(call.Arguments) > 2 { sec = int(call.Arguments[2].ToInteger()) } else { sec = d.time.Second() } if len(call.Arguments) > 3 { nsec = int(call.Arguments[3].ToInteger() * 1e6) } else { nsec = d.time.Nanosecond() } d.time = time.Date(d.time.Year(), d.time.Month(), d.time.Day(), hour, min, sec, nsec, time.Local) return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.setHours is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setUTCHours(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { hour := int(call.Argument(0).ToInteger()) var min, sec, nsec int t := d.time.In(time.UTC) if len(call.Arguments) > 1 { min = int(call.Arguments[1].ToInteger()) } else { min = t.Minute() } if len(call.Arguments) > 2 { sec = int(call.Arguments[2].ToInteger()) } else { sec = t.Second() } if len(call.Arguments) > 3 { nsec = int(call.Arguments[3].ToInteger() * 1e6) } else { nsec = t.Nanosecond() } d.time = time.Date(d.time.Year(), d.time.Month(), d.time.Day(), hour, min, sec, nsec, time.UTC).In(time.Local) return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.setUTCHours is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setDate(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { d.time = time.Date(d.time.Year(), d.time.Month(), int(call.Argument(0).ToInteger()), d.time.Hour(), d.time.Minute(), d.time.Second(), d.time.Nanosecond(), time.Local) return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.setDate is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setUTCDate(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { t := d.time.In(time.UTC) d.time = time.Date(t.Year(), t.Month(), int(call.Argument(0).ToInteger()), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC).In(time.Local) return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.setUTCDate is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setMonth(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { month := time.Month(int(call.Argument(0).ToInteger()) + 1) var day int if len(call.Arguments) > 1 { day = int(call.Arguments[1].ToInteger()) } else { day = d.time.Day() } d.time = time.Date(d.time.Year(), month, day, d.time.Hour(), d.time.Minute(), d.time.Second(), d.time.Nanosecond(), time.Local) return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.setMonth is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setUTCMonth(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if d.isSet { month := time.Month(int(call.Argument(0).ToInteger()) + 1) var day int t := d.time.In(time.UTC) if len(call.Arguments) > 1 { day = int(call.Arguments[1].ToInteger()) } else { day = t.Day() } d.time = time.Date(t.Year(), month, day, t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC).In(time.Local) return intToValue(d.time.UnixNano() / 1e6) } else { return _NaN } } r.typeErrorResult(true, "Method Date.prototype.setUTCMonth is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setFullYear(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if !d.isSet { d.time = time.Unix(0, 0) } year := int(call.Argument(0).ToInteger()) var month time.Month var day int if len(call.Arguments) > 1 { month = time.Month(call.Arguments[1].ToInteger() + 1) } else { month = d.time.Month() } if len(call.Arguments) > 2 { day = int(call.Arguments[2].ToInteger()) } else { day = d.time.Day() } d.time = time.Date(year, month, day, d.time.Hour(), d.time.Minute(), d.time.Second(), d.time.Nanosecond(), time.Local) return intToValue(d.time.UnixNano() / 1e6) } r.typeErrorResult(true, "Method Date.prototype.setFullYear is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) dateproto_setUTCFullYear(call FunctionCall) Value { obj := r.toObject(call.This) if d, ok := obj.self.(*dateObject); ok { if !d.isSet { d.time = time.Unix(0, 0) } year := int(call.Argument(0).ToInteger()) var month time.Month var day int t := d.time.In(time.UTC) if len(call.Arguments) > 1 { month = time.Month(call.Arguments[1].ToInteger() + 1) } else { month = t.Month() } if len(call.Arguments) > 2 { day = int(call.Arguments[2].ToInteger()) } else { day = t.Day() } d.time = time.Date(year, month, day, t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), time.UTC).In(time.Local) return intToValue(d.time.UnixNano() / 1e6) } r.typeErrorResult(true, "Method Date.prototype.setUTCFullYear is called on incompatible receiver") panic("Unreachable") } func (r *Runtime) createDateProto(val *Object) objectImpl { o := &baseObject{ class: classObject, val: val, extensible: true, prototype: r.global.ObjectPrototype, } o.init() o._putProp("constructor", r.global.Date, true, false, true) o._putProp("toString", r.newNativeFunc(r.dateproto_toString, nil, "toString", nil, 0), true, false, true) o._putProp("toDateString", r.newNativeFunc(r.dateproto_toDateString, nil, "toDateString", nil, 0), true, false, true) o._putProp("toTimeString", r.newNativeFunc(r.dateproto_toTimeString, nil, "toTimeString", nil, 0), true, false, true) o._putProp("toLocaleString", r.newNativeFunc(r.dateproto_toLocaleString, nil, "toLocaleString", nil, 0), true, false, true) o._putProp("toLocaleDateString", r.newNativeFunc(r.dateproto_toLocaleDateString, nil, "toLocaleDateString", nil, 0), true, false, true) o._putProp("toLocaleTimeString", r.newNativeFunc(r.dateproto_toLocaleTimeString, nil, "toLocaleTimeString", nil, 0), true, false, true) o._putProp("valueOf", r.newNativeFunc(r.dateproto_valueOf, nil, "valueOf", nil, 0), true, false, true) o._putProp("getTime", r.newNativeFunc(r.dateproto_getTime, nil, "getTime", nil, 0), true, false, true) o._putProp("getFullYear", r.newNativeFunc(r.dateproto_getFullYear, nil, "getFullYear", nil, 0), true, false, true) o._putProp("getUTCFullYear", r.newNativeFunc(r.dateproto_getUTCFullYear, nil, "getUTCFullYear", nil, 0), true, false, true) o._putProp("getMonth", r.newNativeFunc(r.dateproto_getMonth, nil, "getMonth", nil, 0), true, false, true) o._putProp("getUTCMonth", r.newNativeFunc(r.dateproto_getUTCMonth, nil, "getUTCMonth", nil, 0), true, false, true) o._putProp("getDate", r.newNativeFunc(r.dateproto_getDate, nil, "getDate", nil, 0), true, false, true) o._putProp("getUTCDate", r.newNativeFunc(r.dateproto_getUTCDate, nil, "getUTCDate", nil, 0), true, false, true) o._putProp("getDay", r.newNativeFunc(r.dateproto_getDay, nil, "getDay", nil, 0), true, false, true) o._putProp("getUTCDay", r.newNativeFunc(r.dateproto_getUTCDay, nil, "getUTCDay", nil, 0), true, false, true) o._putProp("getHours", r.newNativeFunc(r.dateproto_getHours, nil, "getHours", nil, 0), true, false, true) o._putProp("getUTCHours", r.newNativeFunc(r.dateproto_getUTCHours, nil, "getUTCHours", nil, 0), true, false, true) o._putProp("getMinutes", r.newNativeFunc(r.dateproto_getMinutes, nil, "getMinutes", nil, 0), true, false, true) o._putProp("getUTCMinutes", r.newNativeFunc(r.dateproto_getUTCMinutes, nil, "getUTCMinutes", nil, 0), true, false, true) o._putProp("getSeconds", r.newNativeFunc(r.dateproto_getSeconds, nil, "getSeconds", nil, 0), true, false, true) o._putProp("getUTCSeconds", r.newNativeFunc(r.dateproto_getUTCSeconds, nil, "getUTCSeconds", nil, 0), true, false, true) o._putProp("getMilliseconds", r.newNativeFunc(r.dateproto_getMilliseconds, nil, "getMilliseconds", nil, 0), true, false, true) o._putProp("getUTCMilliseconds", r.newNativeFunc(r.dateproto_getUTCMilliseconds, nil, "getUTCMilliseconds", nil, 0), true, false, true) o._putProp("getTimezoneOffset", r.newNativeFunc(r.dateproto_getTimezoneOffset, nil, "getTimezoneOffset", nil, 0), true, false, true) o._putProp("setTime", r.newNativeFunc(r.dateproto_setTime, nil, "setTime", nil, 1), true, false, true) o._putProp("setMilliseconds", r.newNativeFunc(r.dateproto_setMilliseconds, nil, "setMilliseconds", nil, 1), true, false, true) o._putProp("setUTCMilliseconds", r.newNativeFunc(r.dateproto_setUTCMilliseconds, nil, "setUTCMilliseconds", nil, 1), true, false, true) o._putProp("setSeconds", r.newNativeFunc(r.dateproto_setSeconds, nil, "setSeconds", nil, 2), true, false, true) o._putProp("setUTCSeconds", r.newNativeFunc(r.dateproto_setUTCSeconds, nil, "setUTCSeconds", nil, 2), true, false, true) o._putProp("setMinutes", r.newNativeFunc(r.dateproto_setMinutes, nil, "setMinutes", nil, 3), true, false, true) o._putProp("setUTCMinutes", r.newNativeFunc(r.dateproto_setUTCMinutes, nil, "setUTCMinutes", nil, 3), true, false, true) o._putProp("setHours", r.newNativeFunc(r.dateproto_setHours, nil, "setHours", nil, 4), true, false, true) o._putProp("setUTCHours", r.newNativeFunc(r.dateproto_setUTCHours, nil, "setUTCHours", nil, 4), true, false, true) o._putProp("setDate", r.newNativeFunc(r.dateproto_setDate, nil, "setDate", nil, 1), true, false, true) o._putProp("setUTCDate", r.newNativeFunc(r.dateproto_setUTCDate, nil, "setUTCDate", nil, 1), true, false, true) o._putProp("setMonth", r.newNativeFunc(r.dateproto_setMonth, nil, "setMonth", nil, 2), true, false, true) o._putProp("setUTCMonth", r.newNativeFunc(r.dateproto_setUTCMonth, nil, "setUTCMonth", nil, 2), true, false, true) o._putProp("setFullYear", r.newNativeFunc(r.dateproto_setFullYear, nil, "setFullYear", nil, 3), true, false, true) o._putProp("setUTCFullYear", r.newNativeFunc(r.dateproto_setUTCFullYear, nil, "setUTCFullYear", nil, 3), true, false, true) o._putProp("toUTCString", r.newNativeFunc(r.dateproto_toUTCString, nil, "toUTCString", nil, 0), true, false, true) o._putProp("toISOString", r.newNativeFunc(r.dateproto_toISOString, nil, "toISOString", nil, 0), true, false, true) o._putProp("toJSON", r.newNativeFunc(r.dateproto_toJSON, nil, "toJSON", nil, 1), true, false, true) return o } func (r *Runtime) createDate(val *Object) objectImpl { o := r.newNativeFuncObj(val, r.builtin_date, r.builtin_newDate, "Date", r.global.DatePrototype, 7) o._putProp("parse", r.newNativeFunc(r.date_parse, nil, "parse", nil, 1), true, false, true) o._putProp("UTC", r.newNativeFunc(r.date_UTC, nil, "UTC", nil, 7), true, false, true) o._putProp("now", r.newNativeFunc(r.date_now, nil, "now", nil, 0), true, false, true) return o } func (r *Runtime) newLazyObject(create func(*Object) objectImpl) *Object { val := &Object{runtime: r} o := &lazyObject{ val: val, create: create, } val.self = o return val } func (r *Runtime) initDate() { //r.global.DatePrototype = r.newObject() //o := r.global.DatePrototype.self r.global.DatePrototype = r.newLazyObject(r.createDateProto) //r.global.Date = r.newNativeFunc(r.builtin_date, r.builtin_newDate, "Date", r.global.DatePrototype, 7) //o := r.global.Date.self r.global.Date = r.newLazyObject(r.createDate) r.addToGlobal("Date", r.global.Date) }
vendor/github.com/dop251/goja/builtin_date.go
0.616705
0.44746
builtin_date.go
starcoder
package qparams import ( "bytes" "errors" "fmt" "net/url" "reflect" "strconv" "strings" ) // Encode encodes a query using the given struct. // It can only encode bool, int, float32, float64 and string values or // slices of one of these types. // All other typed fields in the struct are ignored. func Encode(in interface{}) (string, error) { v := reflect.ValueOf(in) t := reflect.TypeOf(in) if v.Kind() == reflect.Ptr { v = v.Elem() t = t.Elem() } if v.Kind() != reflect.Struct { return "", errors.New("cannot encode: not a struct") } b := new(bytes.Buffer) for i := 0; i < v.NumField(); i++ { name := strings.ToLower(t.Field(i).Name) switch v.Field(i).Kind() { case reflect.Bool, reflect.Float64, reflect.Float32, reflect.Int, reflect.String: if err := encode(b, name, v.Field(i)); err != nil { return "", err } case reflect.Slice: for j := 0; j < v.Field(i).Len(); j++ { if err := encode(b, name, v.Field(i).Index(j)); err != nil { return "", err } } } } return b.String(), nil } func encode(b *bytes.Buffer, name string, v reflect.Value) error { switch v.Kind() { case reflect.Bool: return appendQuery(b, name, fmt.Sprintf("%t", v.Bool())) case reflect.Float64, reflect.Float32: return appendQuery(b, name, fmt.Sprintf("%f", v.Float())) case reflect.Int: return appendQuery(b, name, fmt.Sprintf("%d", v.Int())) case reflect.String: return appendQuery(b, name, v.String()) } return nil } func appendQuery(b *bytes.Buffer, name, value string) error { if b.Len() == 0 { if err := b.WriteByte('?'); err != nil { return err } } else { if err := b.WriteByte('&'); err != nil { return err } } str := name + "=" + url.QueryEscape(value) _, err := b.WriteString(str) return err } // Decode decodes a query into the given struct. // It can only be used to decode bool, int, float32, float64 and string values or // slices of one of these types. // All other typed fields of the given struct are ignored. func Decode(vals url.Values, out interface{}) error { t := reflect.TypeOf(out) if t.Kind() != reflect.Ptr { return errors.New("cannot decode: not a pointer") } if t.Elem().Kind() != reflect.Struct { return errors.New("cannot decode: not a struct") } for i := 0; i < t.Elem().NumField(); i++ { v := vals.Get(strings.ToLower(t.Elem().Field(i).Name)) if v == "" { continue } switch t.Elem().Field(i).Type.Kind() { case reflect.Bool: x, err := decodeBool(v) if err != nil { return err } reflect.ValueOf(out).Elem().Field(i).SetBool(x) case reflect.Float64: x, err := decodeFloat64(v) if err != nil { return err } reflect.ValueOf(out).Elem().Field(i).SetFloat(x) case reflect.Float32: x, err := decodeFloat32(v) if err != nil { return err } reflect.ValueOf(out).Elem().Field(i).SetFloat(float64(x)) case reflect.Int: x, err := decodeInt(v) if err != nil { return err } reflect.ValueOf(out).Elem().Field(i).SetInt(int64(x)) case reflect.String: reflect.ValueOf(out).Elem().Field(i).SetString(v) case reflect.Slice: for _, v := range vals[strings.ToLower(t.Elem().Field(i).Name)] { switch t.Elem().Field(i).Type.Elem().Kind() { case reflect.Bool: x, err := decodeBool(v) if err != nil { return err } reflect.ValueOf(out).Elem().Field(i).Set( reflect.Append(reflect.ValueOf(out).Elem().Field(i), reflect.ValueOf(x)), ) case reflect.Float64: x, err := decodeFloat64(v) if err != nil { return err } reflect.ValueOf(out).Elem().Field(i).Set( reflect.Append(reflect.ValueOf(out).Elem().Field(i), reflect.ValueOf(x)), ) case reflect.Float32: x, err := decodeFloat32(v) if err != nil { return err } reflect.ValueOf(out).Elem().Field(i).Set( reflect.Append(reflect.ValueOf(out).Elem().Field(i), reflect.ValueOf(x)), ) case reflect.Int: x, err := decodeInt(v) if err != nil { return err } reflect.ValueOf(out).Elem().Field(i).Set( reflect.Append(reflect.ValueOf(out).Elem().Field(i), reflect.ValueOf(x)), ) case reflect.String: reflect.ValueOf(out).Elem().Field(i).Set( reflect.Append(reflect.ValueOf(out).Elem().Field(i), reflect.ValueOf(v)), ) } } } } return nil } func decodeInt(val string) (int, error) { return strconv.Atoi(val) } func decodeFloat64(val string) (float64, error) { x, err := strconv.ParseFloat(val, 64) return float64(x), err } func decodeFloat32(val string) (float32, error) { x, err := strconv.ParseFloat(val, 32) return float32(x), err } func decodeBool(val string) (bool, error) { return strconv.ParseBool(val) }
query.go
0.663996
0.468487
query.go
starcoder
package mysqlproto // https://dev.mysql.com/doc/internals/en/com-query-response.html#column-type type Type byte const ( TypeDecimal Type = 0x00 TypeTiny Type = 0x01 TypeShort Type = 0x02 TypeLong Type = 0x03 TypeFloat Type = 0x04 TypeDouble Type = 0x05 TypeNULL Type = 0x06 TypeTimestamp Type = 0x07 TypeLongLong Type = 0x08 TypeInt24 Type = 0x09 TypeDate Type = 0x0a TypeTime Type = 0x0b TypeDateTime Type = 0x0c TypeYear Type = 0x0d TypeNewDate Type = 0x0e TypeVarchar Type = 0x0f TypeBit Type = 0x10 TypeTimestamp2 Type = 0x11 TypeDateTime2 Type = 0x12 TypeTime2 Type = 0x13 TypeNewDecimal Type = 0xf6 TypeEnum Type = 0xf7 TypeSet Type = 0xf8 TypeTinyBLOB Type = 0xf9 TypeMediumBLOB Type = 0xfa TypeLongBLOB Type = 0xfb TypeBLOB Type = 0xfc TypeVarString Type = 0xfd TypeString Type = 0xfe TypeGEOMETRY Type = 0xff ) func (t Type) String() string { switch t { case TypeDecimal: return "DECIMAL" case TypeTiny: return "TINY" case TypeShort: return "SHORT" case TypeLong: return "LONG" case TypeFloat: return "FLOAT" case TypeDouble: return "DOUBLE" case TypeNULL: return "NULL" case TypeTimestamp: return "TIMESTAMP" case TypeLongLong: return "LONGLONG" case TypeInt24: return "INT24" case TypeDate: return "DATE" case TypeTime: return "TIME" case TypeDateTime: return "DATETIME" case TypeYear: return "YEAR" case TypeNewDate: return "NEWDATE" case TypeVarchar: return "VARCHAR" case TypeBit: return "BIT" case TypeTimestamp2: return "TIMESTAMP2" case TypeDateTime2: return "DATETIME2" case TypeTime2: return "TIME2" case TypeNewDecimal: return "NEWDECIMAL" case TypeEnum: return "ENUM" case TypeSet: return "SET" case TypeTinyBLOB: return "TINY_BLOB" case TypeMediumBLOB: return "MEDIUM_BLOB" case TypeLongBLOB: return "LONG_BLOB" case TypeBLOB: return "BLOB" case TypeVarString: return "VAR_STRING" case TypeString: return "STRING" case TypeGEOMETRY: return "GEOMETRY" default: return "UNKNOWN" } }
types.go
0.52975
0.435541
types.go
starcoder
package metrics import ( "context" "github.com/prometheus/procfs" "go.opencensus.io/stats" "go.opencensus.io/stats/view" ) // A ProcessCollector collects stats about a process. type ProcessCollector struct { cpuTotal *stats.Float64Measure openFDs *stats.Int64Measure maxFDs *stats.Int64Measure vsize *stats.Int64Measure maxVsize *stats.Int64Measure rss *stats.Int64Measure startTime *stats.Float64Measure views []*view.View } // NewProcessCollector creates a new ProcessCollector. func NewProcessCollector(name string) *ProcessCollector { pc := &ProcessCollector{ cpuTotal: stats.Float64( name+"_process_cpu_seconds_total", "Total user and system CPU time spent in seconds.", stats.UnitSeconds, ), openFDs: stats.Int64( name+"_process_open_fds", "Number of open file descriptors.", "{file_descriptor}", ), maxFDs: stats.Int64( name+"_process_max_fds", "Maximum number of open file descriptors.", "{file_descriptor}", ), vsize: stats.Int64( name+"_process_virtual_memory_bytes", "Virtual memory size in bytes.", stats.UnitBytes, ), maxVsize: stats.Int64( name+"_process_virtual_memory_max_bytes", "Maximum amount of virtual memory available in bytes.", stats.UnitBytes, ), rss: stats.Int64( name+"_process_resident_memory_bytes", "Resident memory size in bytes.", stats.UnitBytes, ), startTime: stats.Float64( name+"_process_start_time_seconds", "Start time of the process since unix epoch in seconds.", stats.UnitSeconds, ), } pc.views = []*view.View{ { Name: pc.cpuTotal.Name(), Description: pc.cpuTotal.Description(), Measure: pc.cpuTotal, Aggregation: view.LastValue(), }, { Name: pc.openFDs.Name(), Description: pc.openFDs.Description(), Measure: pc.openFDs, Aggregation: view.LastValue(), }, { Name: pc.maxFDs.Name(), Description: pc.maxFDs.Description(), Measure: pc.maxFDs, Aggregation: view.LastValue(), }, { Name: pc.vsize.Name(), Description: pc.vsize.Description(), Measure: pc.vsize, Aggregation: view.LastValue(), }, { Name: pc.maxVsize.Name(), Description: pc.maxVsize.Description(), Measure: pc.maxVsize, Aggregation: view.LastValue(), }, { Name: pc.rss.Name(), Description: pc.rss.Description(), Measure: pc.rss, Aggregation: view.LastValue(), }, { Name: pc.startTime.Name(), Description: pc.startTime.Description(), Measure: pc.startTime, Aggregation: view.LastValue(), }, } return pc } // Views returns the views for the process collector. func (pc *ProcessCollector) Views() []*view.View { return pc.views } // Measure measures the stats for a process. func (pc *ProcessCollector) Measure(ctx context.Context, pid int) error { proc, err := procfs.NewProc(pid) if err != nil { return err } procStat, err := proc.Stat() if err != nil { return err } procStartTime, err := procStat.StartTime() if err != nil { return err } procFDLen, err := proc.FileDescriptorsLen() if err != nil { return err } procLimits, err := proc.Limits() if err != nil { return err } stats.Record(ctx, pc.cpuTotal.M(procStat.CPUTime()), pc.openFDs.M(int64(procFDLen)), pc.maxFDs.M(procLimits.OpenFiles), pc.vsize.M(int64(procStat.VSize)), pc.maxVsize.M(procLimits.AddressSpace), pc.rss.M(int64(procStat.RSS)), pc.startTime.M(procStartTime), ) return nil }
internal/telemetry/metrics/processes.go
0.526099
0.444143
processes.go
starcoder
package gfx import ( "errors" "github.com/rainu/launchpad-super-trigger/pad" ) // Fill fills the given rectangle with the given color func (e Renderer) Fill(x0, y0, x1, y1 int, color pad.Color) error { frame := buildFill(x0, y0, x1, y1, color) for _, pixel := range frame { if err := pixel.Light(e); err != nil { return err } } return nil } func buildFill(x0, y0, x1, y1 int, color pad.Color) Frame { frame := make(Frame, 0, 64) appendPixel := func(x, y int) { if x < minX || y < minY || x > maxX || y > maxY { return } frame = append(frame, FramePixel{ X: x, Y: y, Color: color, }) } if x1 >= x0 && y1 >= y0 { // +--> // | // v for x := x0; x <= x1; x++ { for y := y0; y <= y1; y++ { appendPixel(x, y) } } } else if x1 <= x0 && y1 >= y0 { // <--+ // | // v for x := x0; x >= x1; x-- { for y := y0; y <= y1; y++ { appendPixel(x, y) } } } else if x1 >= x0 && y1 <= y0 { // ^ // | // +--> for x := x0; x <= x1; x++ { for y := y0; y >= y1; y-- { appendPixel(x, y) } } } else { // ^ // | // <--+ for x := x1; x >= x0; x-- { for y := y0; y >= y1; y-- { appendPixel(x, y) } } } return frame } // FillQuadrant fills the given quadrant with the given color // 2.| 1. // ---+--- // 3.| 4. func (e Renderer) FillQuadrant(q Quadrant, color pad.Color) error { switch q { case FirstQuadrant: return e.Fill(4, minY, maxY, 3, color) case SecondQuadrant: return e.Fill(minX, minY, 3, 3, color) case ThirdQuadrant: return e.Fill(minX, 4, 3, maxY, color) case ForthQuadrant: return e.Fill(4, 4, maxX, maxY, color) default: return errors.New("invalid quadrant") } } // FillHorizontalLine fills the at the given position a line of the given color with the given length func (e Renderer) FillHorizontalLine(x, y, length int, color pad.Color) error { return e.Fill(x, y, x+length-1, y, color) } // FillVerticalLine fills the at the given position a line of the given color with the given length func (e Renderer) FillVerticalLine(x, y, length int, color pad.Color) error { return e.Fill(x, y, x, y+length-1, color) }
gfx/filler.go
0.773559
0.570092
filler.go
starcoder
package ast // nodeType is used to declare the different possible types of AST nodes type nodeType string const ( TypeResource nodeType = "Resource" TypeIdentifier nodeType = "Identifier" TypeComment nodeType = "Comment" TypeGroupComment nodeType = "GroupComment" TypeResourceComment nodeType = "ResourceComment" TypeMessage nodeType = "Message" TypeTerm nodeType = "Term" TypeAttribute nodeType = "Attribute" TypePattern nodeType = "Pattern" TypeText nodeType = "TextElement" TypePlaceable nodeType = "Placeable" TypeStringLiteral nodeType = "StringLiteral" TypeNumberLiteral nodeType = "NumberLiteral" TypeMessageReference nodeType = "MessageReference" TypeTermReference nodeType = "TermReference" TypeVariableReference nodeType = "VariableReference" TypeFunctionReference nodeType = "FunctionReference" TypeCallArguments nodeType = "CallArguments" TypeNamedArgument nodeType = "NamedArgument" TypeSelectExpression nodeType = "SelectExpression" TypeVariant nodeType = "Variant" TypeJunk nodeType = "Junk" ) // IsEntry checks if a type represents an entry of a resource func IsEntry(typ nodeType) bool { return IsComment(typ) || anyOf(typ, TypeMessage, TypeTerm) } // IsComment checks if a type represents any of the three comment types func IsComment(typ nodeType) bool { return anyOf(typ, TypeComment, TypeGroupComment, TypeResourceComment) } // IsPatternElement checks if a type represents an element of a pattern func IsPatternElement(typ nodeType) bool { return anyOf(typ, TypeText, TypePlaceable) } // IsExpression checks if a type represents an expression used in placeables func IsExpression(typ nodeType) bool { return IsLiteral(typ) || anyOf(TypeMessageReference, TypeTermReference, TypeVariableReference, TypeFunctionReference, TypeSelectExpression) } // IsLiteral checks if a type represents a literal (text or number) func IsLiteral(typ nodeType) bool { return anyOf(typ, TypeStringLiteral, TypeNumberLiteral) } // anyOf checks if the given type matches any of the specified other types func anyOf(typ nodeType, types ...nodeType) bool { for _, toCompare := range types { if typ == toCompare { return true } } return false }
fluent/parser/ast/types.go
0.613352
0.455501
types.go
starcoder
package golist import ( "fmt" "math/rand" "time" ) // SliceBool is a slice of type bool. type SliceBool struct { data []bool } // NewSliceBool returns a pointer to a new SliceBool initialized with the specified elements. func NewSliceBool(elems ...bool) *SliceBool { s := new(SliceBool) s.data = make([]bool, len(elems)) for i := 0; i < len(elems); i++ { s.data[i] = elems[i] } return s } // Append adds the elements to the end of SliceBool. func (s *SliceBool) Append(elems ...bool) *SliceBool { if s == nil { return nil } s.data = append(s.data, elems...) return s } // Prepend adds the elements to the beginning of SliceBool. func (s *SliceBool) Prepend(elems ...bool) *SliceBool { if s == nil { return nil } s.data = append(elems, s.data...) return s } // At returns the element in SliceBool at the specified index. func (s *SliceBool) At(index int) bool { if s.data == nil || len(s.data) == 0 { panic("SliceBool does not contain any elements") } if index >= len(s.data) || index < 0 { panic(fmt.Sprintf("index %d outside the range of SliceBool", index)) } return s.data[index] } // Set sets the element of SliceBool at the specified index. func (s *SliceBool) Set(index int, elem bool) *SliceBool { if s == nil { return nil } s.data[index] = elem return s } // Insert inserts the elements into SliceBool at the specified index. func (s *SliceBool) Insert(index int, elems ...bool) *SliceBool { if s == nil { return nil } // Grow the slice by the number of elements (using the zero value) var zero bool for i := 0; i < len(elems); i++ { s.data = append(s.data, zero) } // Use copy to move the upper part of the slice out of the way and open a hole. copy(s.data[index+len(elems):], s.data[index:]) // Store the new values for i := 0; i < len(elems); i++ { s.data[index+i] = elems[i] } // Return the result. return s } // Remove removes the element from SliceBool at the specified index. func (s *SliceBool) Remove(index int) *SliceBool { if s == nil { return nil } s.data = append(s.data[:index], s.data[index+1:]...) return s } // Filter removes elements from SliceBool that do not satisfy the filter function. func (s *SliceBool) Filter(fn func(elem bool) bool) *SliceBool { if s == nil { return nil } data := s.data[:0] for _, elem := range s.data { if fn(elem) { data = append(data, elem) } } s.data = data return s } // Transform modifies each element of SliceBool according to the specified function. func (s *SliceBool) Transform(fn func(elem bool) bool) *SliceBool { if s == nil { return nil } for i, elem := range s.data { s.data[i] = fn(elem) } return s } // Unique modifies SliceBool to keep only the first occurrence of each element (removing any duplicates). func (s *SliceBool) Unique() *SliceBool { if s == nil { return nil } seen := make(map[bool]struct{}) data := s.data[:0] for _, elem := range s.data { if _, ok := seen[elem]; !ok { data = append(data, elem) seen[elem] = struct{}{} } } s.data = data return s } // Reverse reverses the order of the elements of SliceBool. func (s *SliceBool) Reverse() *SliceBool { if s == nil { return nil } for i := len(s.data)/2 - 1; i >= 0; i-- { opp := len(s.data) - 1 - i s.Swap(i, opp) } return s } // Shuffle randomly shuffles the order of the elements in SliceBool. func (s *SliceBool) Shuffle(seed int64) *SliceBool { if s == nil { return nil } if seed == 0 { seed = time.Now().UnixNano() } r := rand.New(rand.NewSource(seed)) r.Shuffle(s.Count(), s.Swap) return s } // Data returns the raw elements of SliceBool. func (s *SliceBool) Data() []bool { if s == nil { return nil } return s.data } // Count returns the number of elements in SliceBool. func (s *SliceBool) Count() int { return len(s.data) } // Len returns the number of elements in SliceBool (alias for Count). func (s *SliceBool) Len() int { return s.Count() } // Swap swaps the elements in SliceBool specified by the indices i and j. func (s *SliceBool) Swap(i, j int) { s.data[i], s.data[j] = s.data[j], s.data[i] } // Clone performs a deep copy of SliceBool and returns it func (s *SliceBool) Clone() *SliceBool { if s == nil { return nil } s2 := new(SliceBool) s2.data = make([]bool, len(s.data)) copy(s2.data, s.data) return s2 } // Equal returns true if the SliceBool is logically equivalent to the specified SliceBool. func (s *SliceBool) Equal(s2 *SliceBool) bool { if s == s2 { return true } if s == nil || s2 == nil { return false // has to be false because s == s2 tested earlier } if len(s.data) != len(s2.data) { return false } for i, elem := range s.data { if elem != s2.data[i] { return false } } return true }
slice_bool.go
0.747984
0.532364
slice_bool.go
starcoder
package cnns import ( "fmt" "math" "strings" "github.com/LdDl/cnns/tensor" "github.com/pkg/errors" "gonum.org/v1/gonum/mat" ) type poolingType int const ( poolMAX = iota + 1 poolMIN poolAVG ) func (pt poolingType) String() string { switch pt { case poolMAX: return "max" case poolMIN: return "min" case poolAVG: return "avg" default: return fmt.Sprintf("Pooling type #%d is not defined", pt) } } type zeroPaddingType int const ( poolVALID = iota + 1 poolSAME ) func (zpt zeroPaddingType) String() string { switch zpt { case poolVALID: return "valid" case poolSAME: return "same" default: return fmt.Sprintf("Zero padding type #%d is not defined", zpt) } } // PoolingLayer Pooling layer structure /* Oj - Input data Ok - Output data LocalDelta - Gradients */ type PoolingLayer struct { Oj *mat.Dense Ok *mat.Dense Masks *mat.Dense Stride int ExtendFilter int masksIndices [][][2]int OutputSize *tensor.TDsize inputSize *tensor.TDsize PoolingType poolingType ZeroPadding zeroPaddingType trainMode bool } // NewPoolingLayer Constructor for pooling layer. func NewPoolingLayer(inSize *tensor.TDsize, stride, extendFilter int, poolingType string, zeroPad string) Layer { newLayer := &PoolingLayer{ inputSize: inSize, Oj: mat.NewDense(inSize.X, inSize.Y, nil), Ok: &mat.Dense{}, Masks: mat.NewDense(inSize.X, inSize.Y, nil), Stride: stride, ExtendFilter: extendFilter, trainMode: false, } switch strings.ToLower(zeroPad) { case "same": newLayer.ZeroPadding = poolSAME // If zero padding truly needed? if (inSize.X-extendFilter)%stride != 0 { newLayer.OutputSize = &tensor.TDsize{ X: int(math.Ceil(float64(inSize.X-extendFilter)/float64(stride) + 1)), Y: int(math.Ceil(float64(inSize.Y-extendFilter)/float64(stride) + 1)), Z: inSize.Z, } } else { // Ignore predefined zeroPad value. newLayer.ZeroPadding = poolVALID newLayer.OutputSize = &tensor.TDsize{ X: (inSize.X-extendFilter)/stride + 1, Y: (inSize.Y-extendFilter)/stride + 1, Z: inSize.Z, } } break default: // Default is 'VALID' newLayer.ZeroPadding = poolVALID newLayer.OutputSize = &tensor.TDsize{ X: (inSize.X-extendFilter)/stride + 1, Y: (inSize.Y-extendFilter)/stride + 1, Z: inSize.Z, } break } switch strings.ToLower(poolingType) { case "max": newLayer.PoolingType = poolMAX break case "min": newLayer.PoolingType = poolMIN break case "avg": newLayer.PoolingType = poolAVG break default: fmt.Printf("Warning: type '%s' for pooling layer is not supported. Use 'max', 'min' or 'avg'\n", poolingType) newLayer.PoolingType = poolMAX break } return newLayer } // SetCustomWeights Set user's weights (make it carefully) for pooling layer func (pool *PoolingLayer) SetCustomWeights(t []*mat.Dense) { fmt.Println("There are no weights for pooling layer") } // GetInputSize Returns dimensions of incoming data for pooling layer func (pool *PoolingLayer) GetInputSize() *tensor.TDsize { return pool.inputSize } // GetOutputSize Returns output size (dimensions) of pooling layer func (pool *PoolingLayer) GetOutputSize() *tensor.TDsize { return pool.OutputSize } // GetActivatedOutput Returns pooling layer's output func (pool *PoolingLayer) GetActivatedOutput() *mat.Dense { return pool.Ok } // GetWeights Returns pooling layer's weights func (pool *PoolingLayer) GetWeights() []*mat.Dense { fmt.Println("There are no weights for pooling layer") return nil } // GetGradients Returns pooling layer's gradients func (pool *PoolingLayer) GetGradients() *mat.Dense { return pool.Masks } // FeedForward Feed data to pooling layer func (pool *PoolingLayer) FeedForward(input *mat.Dense) error { pool.Oj = input if pool.ZeroPadding == poolSAME { matrixR, matrixC := pool.Oj.Dims() stacked := &mat.Dense{} for c := 0; c < pool.OutputSize.Z; c++ { // Add padding for each channel partialMatrix := ExtractChannel(pool.Oj, matrixR, matrixC, pool.OutputSize.Z, c) //pool.Oj.Slice(c*matrixC, matrixR/pool.OutputSize.Z+c*matrixC, 0, matrixC).(*mat.Dense) padded := ZeroPadding(partialMatrix, 1) if stacked.IsEmpty() { stacked = padded } else { t := &mat.Dense{} t.Stack(stacked, padded) stacked = t } } pool.Oj = stacked } pool.doActivation() return nil } // DoActivation Pooling layer's output activation func (pool *PoolingLayer) doActivation() { pool.Ok, pool.Masks, pool.masksIndices = Pool2D(pool.Oj, pool.OutputSize.X, pool.OutputSize.Y, pool.OutputSize.Z, pool.ExtendFilter, pool.Stride, pool.PoolingType, true) } // CalculateGradients Evaluate pooling layer's gradients func (pool *PoolingLayer) CalculateGradients(errorsDense *mat.Dense) error { errorsReshaped := errorsDense var err error okR, okC := pool.Ok.Dims() errR, errC := errorsDense.Dims() if okR != errR || okC != errC { errorsReshaped, err = Reshape(errorsDense, okR, okC) if err != nil { return errors.Wrap(err, "Can't call CalculateGradients() on pooling layer while reshaping incoming gradients") } } stride := pool.Stride windowSize := pool.ExtendFilter channels := pool.OutputSize.Z errorsRows, errorsCols := errorsReshaped.Dims() maskR, maskC := pool.Masks.Dims() maskIndicesSplit := len(pool.masksIndices) / channels for c := 0; c < channels; c++ { partialErrors := ExtractChannel(errorsReshaped, errorsRows, errorsCols, channels, c) partialErrRows, partialErrCols := partialErrors.Dims() partialMask := ExtractChannel(pool.Masks, maskR, maskC, channels, c) partialMaskIndices := pool.masksIndices[c*maskIndicesSplit : maskIndicesSplit+c*maskIndicesSplit] for y := 0; y < partialErrRows; y++ { startYi := y * stride startYj := startYi + windowSize for x := 0; x < partialErrCols; x++ { startX := x * stride part := partialMask.Slice(startYi, startYj, startX, startX+windowSize).(*mat.Dense) part.Set(partialMaskIndices[y][x][0], partialMaskIndices[y][x][1], partialErrors.At(y, x)) } } } return nil } // UpdateWeights Just to point, that pooling layer does NOT updating weights func (pool *PoolingLayer) UpdateWeights(lp *LearningParams) { // "There are no weights to update for pooling layer" } // PrintOutput Pretty print pooling layer's output func (pool *PoolingLayer) PrintOutput() { fmt.Println("Printing Pooling Layer output...") } // PrintWeights Just to point, that pooling layer has not gradients func (pool *PoolingLayer) PrintWeights() { fmt.Println("There are no weights for pooling layer") } // SetActivationFunc Set activation function for layer func (pool *PoolingLayer) SetActivationFunc(f func(v float64) float64) { // Nothing here. Just for interface. fmt.Println("You can not set activation function for pooling layer") } // SetActivationDerivativeFunc Set derivative of activation function func (pool *PoolingLayer) SetActivationDerivativeFunc(f func(v float64) float64) { // Nothing here. Just for interface. fmt.Println("You can not set derivative of activation function for pooling layer") } // GetStride Returns stride of layer func (pool *PoolingLayer) GetStride() int { return pool.Stride } // GetType Returns "pool" as layer's type func (pool *PoolingLayer) GetType() string { return "pool" }
pooling_layer.go
0.765506
0.405625
pooling_layer.go
starcoder
package dstask import ( "fmt" "os" ) func Help(cmd string) { var helpStr string showKey := false switch cmd { case CMD_NEXT: helpStr = `Usage: dstask next [filter] [--] Usage: dstask [filter] [--] Example: dstask +work +bug -- Display list of non-resolved tasks in the current context, most recent last, optional filter. It is the default command, so "next" is unnecessary. Bypass the current context with --. Colour key: ` showKey = true case CMD_ADD: helpStr = `Usage: dstask add [template:<id>] [task summary] [--] Example: dstask add Fix main web page 500 error +bug P1 project:website Add a task, returning the git commit output which contains the task ID, used later to reference the task. Tags, project and priority can be added anywhere within the task summary. Add -- to ignore the current context. / can be used when adding tasks to note any words after. A copy of an existing task can be made by including "template:<id>". See "dstask help template" for more information on templates. ` case CMD_TEMPLATE: helpStr = `Usage dstask template <id> [task summary] [--] Example: dstask template Fix main web page 500 error +bug P1 project:website Example: dstask template 34 project: If valid task ID is supplied, a copy of the task is created as a template. If no ID is given, a new task template is created. Tags, project and priority can be added anywhere within the task summary. Add -- to ignore the current context. / can be used when adding tasks to note any words after Template tasks are not displayed with "show-open" or "show-next" commands. Their intent is to act as a readily available task template for commonly used or repeated tasks. To create a new task from a template use the command: "dstask add template:<id> [task summary] [--]" The template task <id> remains unchanged, but a new task is created as a copy with any modifications made in the task summary. Github-style task lists (checklists) are recommended for templates, useful for performing procedures. Example: - [ ] buy bananas - [ ] eat bananas - [ ] make coffee ` case CMD_RM, CMD_REMOVE: helpStr = `Usage: dstask remove <id...> Example: dstask 15 remove Remove a task. The task is deleted from the filesystem, and the change is committed. ` case CMD_LOG: helpStr = `Usage: dstask log [task summary] [--] Example: dstask log Fix main web page 500 error +bug P1 project:website Add an immediately resolved task. Syntax identical to add command. Tags, project and priority can be added anywhere within the task summary. Add -- to ignore the current context. ` case CMD_START: helpStr = `Usage: dstask <id...> start Usage: dstask start [task summary] [--] Example: dstask 15 start Example: dstask start Fix main web page 500 error +bug P1 project:website Mark a task as active, meaning you're currently at work on the task. Alternatively, "start" can add a task and start it immediately with the same syntax is the "add" command. Tags, project and priority can be added anywhere within the task summary. Add -- to ignore the current context. ` case CMD_NOTE: fallthrough case CMD_NOTES: helpStr = `Usage: dstask note <id> Usage: dstask note <id> <text> Example task 13 note problem is faulty hardware Edit or append text to the markdown notes attached to a particular task. ` case CMD_STOP: helpStr = `Usage: dstask <id...> stop [text] Example: dstask 15 stop Example: dstask 15 stop replaced some hardware Set a task as inactive, meaning you've stopped work on the task. Optional text may be added, which will be appended to the note. ` case CMD_RESOLVE: fallthrough case CMD_DONE: helpStr = `Usage: dstask <id...> done [closing note] Example: dstask 15 done Example: dstask 15 done replaced some hardware Resolve a task. Optional text may be added, which will be appended to the note. ` case CMD_CONTEXT: helpStr = `Usage: dstask context <filter> Example: dstask context +work -bug Example: dstask context none Set a global filter consisting of a project, tags or antitags. Subsequent new tasks and most commands will then have this filter applied automatically. For example, if you were to run "task add fix the webserver," the given task would then have the tag "work" applied automatically. To reset to no context, run: dstask context none Context can also be set with the environment variable DSTASK_CONTEXT. If set, this context string will override the context stored on disk. ` case CMD_MODIFY: helpStr = `Usage: dstask <id...> modify <filter> Usage: dstask modify <filter> Example: dstask 34 modify -work +home project:workbench -project:website Modify the attributes of the given tasks, specified by ID. If no ID is given, the operation will be performed to all tasks in the current context subject to confirmation. Modifiable attributes: tags, project and priority. ` case CMD_EDIT: helpStr = `Usage: dstask <id...> edit Edit a task in your text editor. ` case CMD_UNDO: helpStr = `Usage: dstask undo Usage: dstask undo <n> Undo the last <n> commits on the repository. Default is 1. Use dstask git log To see commit history. For more complicated history manipulation it may be best to revert/rebase/merge on the dstask repository itself. The dstask repository is at ~/.dstask by default. ` case CMD_SYNC: helpStr = `Usage: dstask sync Synchronise with the remote git server. Runs git pull then git push. If there are conflicts that cannot be automatically resolved, it is necessary to manually resolve them in ~/.dstask or with the "task git" command. ` case CMD_GIT: helpStr = `Usage: dstask git <args...> Example: dstask git status Run the given git command inside ~/.dstask ` case CMD_SHOW_RESOLVED: helpStr = `Usage: dstask resolved Show a report of last 1000 resolved tasks. ` case CMD_SHOW_TEMPLATES: helpStr = `Usage: dtask show-templates [filter] [--] Show a report of stored template tasks with an optional filter. Bypass the current context with --` case CMD_OPEN: helpStr = `Usage: dstask <id...> open Open all URLs found within the task summary and notes. If you commonly have dozens of tabs open to later action, convert them into tasks to open later with this command. ` case CMD_SHOW_PROJECTS: helpStr = `Usage: dstask show-projects Show a breakdown of projects with progress information ` default: helpStr = `Usage: dstask [id...] <cmd> [task summary/filter] Where [task summary] is text with tags/project/priority specified. Tags are specified with + (or - for filtering) eg: +work. The project is specified with a project:g prefix eg: project:dstask -- no quotes. Priorities run from P3 (low), P2 (default) to P1 (high) and P0 (critical). Text can also be specified for a substring search of description and notes. Cmd and IDs can be swapped, multiple IDs can be specified for batch operations. run "dstask help <cmd>" for command specific help. Add -- to ignore the current context. / can be used when adding tasks to note any words after. Available commands: next : Show most important tasks (priority, creation date -- truncated and default) add : Add a task template : Add a task template log : Log a task (already resolved) start : Change task status to active note : Append to or edit note for a task stop : Change task status to pending done : Resolve a task context : Set global context for task list and new tasks (use "none" to set no context) modify : Change task attributes specified on command line edit : Edit task with text editor undo : Undo last n commits sync : Pull then push to git repository, automatic merge commit. open : Open all URLs found in summary/annotations git : Pass a command to git in the repository. Used for push/pull. remove : Remove a task (use to remove tasks added by mistake) show-projects : List projects with completion status show-tags : List tags in use show-active : Show tasks that have been started show-paused : Show tasks that have been started then stopped show-open : Show all non-resolved tasks (without truncation) show-resolved : Show resolved tasks show-templates : Show task templates show-unorganised : Show untagged tasks with no projects (global context) import-tw : Import tasks from taskwarrior via stdin help : Get help on any command or show this message version : Show dstask version information Colour Key: ` showKey = true } fmt.Fprint(os.Stderr, helpStr) if showKey { colourPrintln(0, FG_PRIORITY_CRITICAL, BG_DEFAULT_2, "Critical priority") colourPrintln(0, FG_PRIORITY_HIGH, BG_DEFAULT_2, "High priority") colourPrintln(0, FG_DEFAULT, BG_DEFAULT_1, "Normal priority") colourPrintln(0, FG_PRIORITY_LOW, BG_DEFAULT_2, "Low priority") colourPrintln(0, FG_ACTIVE, BG_ACTIVE, "Active") colourPrintln(0, FG_DEFAULT, BG_PAUSED, "Paused") } os.Exit(0) } func colourPrintln(mode, fg, bg int, line string) { line = FixStr(line, 25) fmt.Fprintf(os.Stderr, "\033[%d;38;5;%d;48;5;%dm%s\033[0m\n", mode, fg, bg, line) }
help.go
0.556641
0.407039
help.go
starcoder
package benchmarked // Equal checks if two slices of bytes are equal var Equal = equal14 func equal1(a, b []byte) bool { return string(a) == string(b) } func equal2(a, b []byte) bool { la := len(a) lb := len(b) if la == 0 && lb == 0 { return true } else if la != lb { return false } // len(a) == len(b) from this point on for i := 0; i < la; i++ { if a[i] != b[i] { return false } } return true } func equal3(a, b []byte) bool { la := len(a) lb := len(b) if la == 0 && lb == 0 { return true } else if la == 1 && lb == 1 && a[0] == b[0] { return true } else if la != lb { return false } // len(a) == len(b) from this point on for i := 0; i < la; i++ { if a[i] != b[i] { return false } } return true } func equal4(a, b []byte) bool { la := len(a) lb := len(b) for i := 0; i < la; i++ { if i >= lb { return false } else if a[i] != b[i] { return false } } return true } func equal5(a, b []byte) bool { la := len(a) lb := len(b) switch la { case 0: return lb == 0 case 1: return lb == 1 && a[0] == b[0] case 2: return lb == 2 && a[0] == b[0] && a[1] == b[1] case 3: return lb == 3 && a[0] == b[0] && a[1] == b[1] && a[2] == b[2] case 4: return lb == 4 && a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3] case lb: break default: // la != lb return false } // The length is 5 or above, start at index 4 for i := 4; i < la; i++ { if i >= lb { return false } else if a[i] != b[i] { return false } } return true } func equal6(a, b []byte) bool { la := 0 for range a { la++ } for i, v := range b { if i >= la { return false } else if a[i] != v { return false } } return true } func equal7(a, b []byte) bool { la := len(a) for i, v := range b { if i >= la || a[i] != v { return false } } return true } func equal8(a, b []byte) bool { la := len(a) lb := len(b) if la == 0 && lb == 0 { return true } else if la != lb { return false } for i := 0; i < lb; i++ { if i >= la || a[i] != b[i] { return false } } return true } // Best performance so far func equal9(a, b []byte) bool { la := len(a) lb := len(b) if la != lb { return false } for i := 0; i < lb; i++ { if i >= la || a[i] != b[i] { return false } } return true } func equal10(a, b []byte) bool { la := len(a) lb := len(b) if la == 0 && lb == 0 { return true } else if la != lb { return false } // From this point on, la == lb for i := 0; i < la; i++ { if a[i] != b[i] { return false } } return true } func equal11(a, b []byte) bool { la := len(a) lb := len(b) if la == 0 && lb == 0 { return true } else if la != lb { return false } else if la == 1 && lb == 1 && a[0] == b[0] { return true } // From this point on, la == lb for i := 0; i < la; i++ { if a[i] != b[i] { return false } } return true } func equal12(a, b []byte) bool { la := len(a) lb := len(b) switch la { case 0: if lb == 0 { return true } case 1: if lb == 1 && a[0] == b[0] { return true } case lb: break default: // la != lb return false } // From this point on, la == lb // And la == 1 is already covered, so we can loop from index 1 for i := 1; i < la; i++ { if a[i] != b[i] { return false } } return true } func equal13(a, b []byte) bool { la := len(a) lb := len(b) if la != lb { return false } else if la == 1 && a[0] == b[0] { return true } for i := 0; i < lb; i++ { if i >= la || a[i] != b[i] { return false } } return true } func equal14(a, b []byte) bool { if len(a) != len(b) { return false } for i := 0; i < len(b); i++ { if i >= len(a) || a[i] != b[i] { return false } } return true }
vendor/github.com/xyproto/benchmarked/equal.go
0.587825
0.471162
equal.go
starcoder
package unifier import ( "fmt" "github.com/twtiger/gosecco/constants" "github.com/twtiger/gosecco/tree" ) type replacer struct { expression tree.Expression macros map[string]tree.Macro err error } func (r *replacer) AcceptAnd(b tree.And) { var left tree.Boolean var right tree.Boolean left, r.err = replace(b.Left, r.macros) if r.err == nil { right, r.err = replace(b.Right, r.macros) r.expression = tree.And{Left: left, Right: right} } } func (r *replacer) AcceptArgument(tree.Argument) {} func (r *replacer) AcceptArithmetic(b tree.Arithmetic) { var left tree.Numeric var right tree.Numeric left, r.err = replace(b.Left, r.macros) if r.err == nil { right, r.err = replace(b.Right, r.macros) r.expression = tree.Arithmetic{Left: left, Op: b.Op, Right: right} } } func (r *replacer) AcceptBinaryNegation(b tree.BinaryNegation) { var op tree.Numeric op, r.err = replace(b.Operand, r.macros) r.expression = tree.BinaryNegation{op} } func (r *replacer) AcceptBooleanLiteral(tree.BooleanLiteral) {} func (r *replacer) AcceptCall(b tree.Call) { v, ok := r.macros[b.Name] // we get the name of the macro if !ok { r.err = fmt.Errorf("Macro '%s' is not defined", b.Name) return } nm := make(map[string]tree.Macro) for i, k := range b.Args { var e tree.Expression e, r.err = replace(k, r.macros) if r.err == nil { m := tree.Macro{Name: v.ArgumentNames[i], Body: e} nm[v.ArgumentNames[i]] = m } else { return } } for k, v := range r.macros { nm[k] = v } if r.err == nil { r.expression, r.err = replace(v.Body, nm) } } func (r *replacer) AcceptComparison(b tree.Comparison) { var left tree.Numeric var right tree.Numeric left, r.err = replace(b.Left, r.macros) if r.err == nil { right, r.err = replace(b.Right, r.macros) r.expression = tree.Comparison{ Left: left, Op: b.Op, Right: right, } } } func (r *replacer) AcceptInclusion(b tree.Inclusion) { var rights []tree.Numeric for _, e := range b.Rights { right, err := replace(e, r.macros) if err != nil { r.err = err } rights = append(rights, right) } left, err := replace(b.Left, r.macros) if err != nil { r.err = err } r.expression = tree.Inclusion{Positive: b.Positive, Left: left, Rights: rights} } func (r *replacer) AcceptNegation(b tree.Negation) { var op tree.Numeric op, r.err = replace(b.Operand, r.macros) r.expression = tree.Negation{Operand: op} } func (r *replacer) AcceptNumericLiteral(tree.NumericLiteral) {} func (r *replacer) AcceptOr(b tree.Or) { var left tree.Boolean var right tree.Boolean left, r.err = replace(b.Left, r.macros) if r.err == nil { right, r.err = replace(b.Right, r.macros) r.expression = tree.And{Left: left, Right: right} r.expression = tree.Or{Left: left, Right: right} } } func (r *replacer) AcceptVariable(b tree.Variable) { expr, ok := r.macros[b.Name] if ok { x, ee := replace(expr.Body, r.macros) if ee != nil { r.err = ee } r.expression = x } else { value, ok2 := constants.GetConstant(b.Name) if ok2 { r.expression = tree.NumericLiteral{Value: uint64(value)} } else { r.err = fmt.Errorf("Variable '%s' is not defined", b.Name) } } }
vendor/github.com/twtiger/gosecco/unifier/unifier_visitor.go
0.523664
0.48499
unifier_visitor.go
starcoder
package protocol import ( "github.com/google/uuid" ) // PlayerListEntry is an entry found in the PlayerList packet. It represents a single player using the UUID // found in the entry, and contains several properties such as the skin. type PlayerListEntry struct { // UUID is the UUID of the player as sent in the Login packet when the client joined the server. It must // match this UUID exactly for the correct XBOX Live icon to show up in the list. UUID uuid.UUID // EntityUniqueID is the unique entity ID of the player. This ID typically stays consistent during the // lifetime of a world, but servers often send the runtime ID for this. EntityUniqueID int64 // Username is the username that is shown in the player list of the player that obtains a PlayerList // packet with this entry. It does not have to be the same as the actual username of the player. Username string // XUID is the XBOX Live user ID of the player, which will remain consistent as long as the player is // logged in with the XBOX Live account. XUID string // PlatformChatID is an identifier only set for particular platforms when chatting (presumably only for // Nintendo Switch). It is otherwise an empty string, and is used to decide which players are able to // chat with each other. PlatformChatID string // BuildPlatform is the platform of the player as sent by that player in the Login packet. BuildPlatform int32 // Skin is the skin of the player that should be added to the player list. Once sent here, it will not // have to be sent again. Skin Skin // Teacher is a Minecraft: Education Edition field. It specifies if the player to be added to the player // list is a teacher. Teacher bool // Host specifies if the player that is added to the player list is the host of the game. Host bool } // WritePlayerAddEntry writes a PlayerListEntry x to Writer w in a way that adds the player to the list. func WritePlayerAddEntry(w *Writer, x *PlayerListEntry) { w.UUID(&x.UUID) w.Varint64(&x.EntityUniqueID) w.String(&x.Username) w.String(&x.XUID) w.String(&x.PlatformChatID) w.Int32(&x.BuildPlatform) WriteSerialisedSkin(w, &x.Skin) w.Bool(&x.Teacher) w.Bool(&x.Host) } // PlayerAddEntry reads a PlayerListEntry x from Reader r in a way that adds a player to the list. func PlayerAddEntry(r *Reader, x *PlayerListEntry) { r.UUID(&x.UUID) r.Varint64(&x.EntityUniqueID) r.String(&x.Username) r.String(&x.XUID) r.String(&x.PlatformChatID) r.Int32(&x.BuildPlatform) SerialisedSkin(r, &x.Skin) r.Bool(&x.Teacher) r.Bool(&x.Host) }
minecraft/protocol/player.go
0.566019
0.413359
player.go
starcoder
package function import ( "fmt" "math" "reflect" "github.com/src-d/go-mysql-server/sql" "github.com/src-d/go-mysql-server/sql/expression" ) // Ceil returns the smallest integer value not less than X. type Ceil struct { expression.UnaryExpression } // NewCeil creates a new Ceil expression. func NewCeil(num sql.Expression) sql.Expression { return &Ceil{expression.UnaryExpression{Child: num}} } // Type implements the Expression interface. func (c *Ceil) Type() sql.Type { childType := c.Child.Type() if sql.IsNumber(childType) { return childType } return sql.Int32 } func (c *Ceil) String() string { return fmt.Sprintf("CEIL(%s)", c.Child) } // WithChildren implements the Expression interface. func (c *Ceil) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(c, len(children), 1) } return NewCeil(children[0]), nil } // Eval implements the Expression interface. func (c *Ceil) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { child, err := c.Child.Eval(ctx, row) if err != nil { return nil, err } if child == nil { return nil, nil } if !sql.IsNumber(c.Child.Type()) { child, err = sql.Float64.Convert(child) if err != nil { return int32(0), nil } return int32(math.Ceil(child.(float64))), nil } if !sql.IsDecimal(c.Child.Type()) { return child, err } switch num := child.(type) { case float64: return math.Ceil(num), nil case float32: return float32(math.Ceil(float64(num))), nil default: return nil, sql.ErrInvalidType.New(reflect.TypeOf(num)) } } // Floor returns the biggest integer value not less than X. type Floor struct { expression.UnaryExpression } // NewFloor returns a new Floor expression. func NewFloor(num sql.Expression) sql.Expression { return &Floor{expression.UnaryExpression{Child: num}} } // Type implements the Expression interface. func (f *Floor) Type() sql.Type { childType := f.Child.Type() if sql.IsNumber(childType) { return childType } return sql.Int32 } func (f *Floor) String() string { return fmt.Sprintf("FLOOR(%s)", f.Child) } // WithChildren implements the Expression interface. func (f *Floor) WithChildren(children ...sql.Expression) (sql.Expression, error) { if len(children) != 1 { return nil, sql.ErrInvalidChildrenNumber.New(f, len(children), 1) } return NewFloor(children[0]), nil } // Eval implements the Expression interface. func (f *Floor) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { child, err := f.Child.Eval(ctx, row) if err != nil { return nil, err } if child == nil { return nil, nil } if !sql.IsNumber(f.Child.Type()) { child, err = sql.Float64.Convert(child) if err != nil { return int32(0), nil } return int32(math.Floor(child.(float64))), nil } if !sql.IsDecimal(f.Child.Type()) { return child, err } switch num := child.(type) { case float64: return math.Floor(num), nil case float32: return float32(math.Floor(float64(num))), nil default: return nil, sql.ErrInvalidType.New(reflect.TypeOf(num)) } } // Round returns the number (x) with (d) requested decimal places. // If d is negative, the number is returned with the (abs(d)) least significant // digits of it's integer part set to 0. If d is not specified or nil/null // it defaults to 0. type Round struct { expression.BinaryExpression } // NewRound returns a new Round expression. func NewRound(args ...sql.Expression) (sql.Expression, error) { argLen := len(args) if argLen == 0 || argLen > 2 { return nil, sql.ErrInvalidArgumentNumber.New("ROUND", "1 or 2", argLen) } var right sql.Expression if len(args) == 2 { right = args[1] } return &Round{expression.BinaryExpression{Left: args[0], Right: right}}, nil } // Children implements the Expression interface. func (r *Round) Children() []sql.Expression { if r.Right == nil { return []sql.Expression{r.Left} } return r.BinaryExpression.Children() } // Eval implements the Expression interface. func (r *Round) Eval(ctx *sql.Context, row sql.Row) (interface{}, error) { xVal, err := r.Left.Eval(ctx, row) if err != nil { return nil, err } if xVal == nil { return nil, nil } dVal := float64(0) if r.Right != nil { var dTemp interface{} dTemp, err = r.Right.Eval(ctx, row) if err != nil { return nil, err } if dTemp != nil { switch dNum := dTemp.(type) { case float64: dVal = float64(int64(dNum)) case float32: dVal = float64(int64(dNum)) case int64: dVal = float64(dNum) case int32: dVal = float64(dNum) case int16: dVal = float64(dNum) case int8: dVal = float64(dNum) case uint64: dVal = float64(dNum) case uint32: dVal = float64(dNum) case uint16: dVal = float64(dNum) case uint8: dVal = float64(dNum) case int: dVal = float64(dNum) default: dTemp, err = sql.Float64.Convert(dTemp) if err == nil { dVal = dTemp.(float64) } } } } if !sql.IsNumber(r.Left.Type()) { xVal, err = sql.Float64.Convert(xVal) if err != nil { return int32(0), nil } xNum := xVal.(float64) return int32(math.Round(xNum*math.Pow(10.0, dVal)) / math.Pow(10.0, dVal)), nil } switch xNum := xVal.(type) { case float64: return math.Round(xNum*math.Pow(10.0, dVal)) / math.Pow(10.0, dVal), nil case float32: return float32(math.Round(float64(xNum)*math.Pow(10.0, dVal)) / math.Pow(10.0, dVal)), nil case int64: return int64(math.Round(float64(xNum)*math.Pow(10.0, dVal)) / math.Pow(10.0, dVal)), nil case int32: return int32(math.Round(float64(xNum)*math.Pow(10.0, dVal)) / math.Pow(10.0, dVal)), nil case int16: return int16(math.Round(float64(xNum)*math.Pow(10.0, dVal)) / math.Pow(10.0, dVal)), nil case int8: return int8(math.Round(float64(xNum)*math.Pow(10.0, dVal)) / math.Pow(10.0, dVal)), nil case uint64: return uint64(math.Round(float64(xNum)*math.Pow(10.0, dVal)) / math.Pow(10.0, dVal)), nil case uint32: return uint32(math.Round(float64(xNum)*math.Pow(10.0, dVal)) / math.Pow(10.0, dVal)), nil case uint16: return uint16(math.Round(float64(xNum)*math.Pow(10.0, dVal)) / math.Pow(10.0, dVal)), nil case uint8: return uint8(math.Round(float64(xNum)*math.Pow(10.0, dVal)) / math.Pow(10.0, dVal)), nil case int: return int(math.Round(float64(xNum)*math.Pow(10.0, dVal)) / math.Pow(10.0, dVal)), nil default: return nil, sql.ErrInvalidType.New(r.Left.Type().Type().String()) } } // IsNullable implements the Expression interface. func (r *Round) IsNullable() bool { return r.Left.IsNullable() } func (r *Round) String() string { if r.Right == nil { return fmt.Sprintf("ROUND(%s, 0)", r.Left.String()) } return fmt.Sprintf("ROUND(%s, %s)", r.Left.String(), r.Right.String()) } // Resolved implements the Expression interface. func (r *Round) Resolved() bool { return r.Left.Resolved() && (r.Right == nil || r.Right.Resolved()) } // Type implements the Expression interface. func (r *Round) Type() sql.Type { leftChildType := r.Left.Type() if sql.IsNumber(leftChildType) { return leftChildType } return sql.Int32 } // WithChildren implements the Expression interface. func (r *Round) WithChildren(children ...sql.Expression) (sql.Expression, error) { return NewRound(children...) }
sql/expression/function/ceil_round_floor.go
0.738669
0.475423
ceil_round_floor.go
starcoder
package colonist import ( "fmt" "math" "math/rand" "github.com/rs/xid" "github.com/thebrubaker/colony/storage" ) type DesireType string const ( Fulfillment DesireType = "Fulfillment" Belonging DesireType = "Belonging" Esteem DesireType = "Esteem" ) type Desires map[DesireType]float64 func (d Desires) Increase(t DesireType, amount float64) { d[t] = math.Min(100, d[t]+amount) } func (d Desires) Decrease(t DesireType, amount float64) { d[t] = math.Max(0, d[t]-amount) } type NeedType string const ( Hunger NeedType = "Hunger" Thirst NeedType = "Thirst" Stress NeedType = "Stress" Exhaustion NeedType = "Exhaustion" Fear NeedType = "Fear" Pain NeedType = "Pain" ) type Needs map[NeedType]float64 func (n Needs) Increase(t NeedType, amount float64) { n[t] = math.Min(100, n[t]+amount) } func (n Needs) Decrease(t NeedType, amount float64) { n[t] = math.Max(0, n[t]-amount) } type SkillType string const ( Hunting SkillType = "Hunting" Crafting SkillType = "Crafting" Cooking SkillType = "Cooking" Building SkillType = "Building" Gathering SkillType = "Gathering" Mining SkillType = "Mining" Woodcutting SkillType = "Woodcutting" Science SkillType = "Science" Combat SkillType = "Combat" Charisma SkillType = "Charisma" Medicine SkillType = "Medicine" Tinkering SkillType = "Tinkering" ) type Skills map[SkillType]float64 func (n Skills) Increase(t SkillType, amount float64) { n[t] += amount } func (n Skills) Decrease(t SkillType, amount float64) { n[t] = math.Max(0, n[t]-amount) } // Colonist struct type Colonist struct { Key string `json:"key"` Name string `json:"name"` Status string `json:"status"` Age uint `json:"age"` Bag *storage.Storage `json:"bag"` Equipment *Equipment `json:"equipment"` Desires Desires `json:"desires"` Needs Needs `json:"needs"` Skills Skills `json:"skills"` } // GenerateColonist returns a new colonist with the given name // and a random set of skills and stats. func NewColonist() *Colonist { return &Colonist{ Key: xid.New().String(), Name: generateName(), Age: generateAge(), Bag: &storage.Storage{ Size: 30, Items: []interface{}{}, }, Equipment: &Equipment{}, Desires: createDesires(), Needs: createNeeds(), Skills: generateSkills(), } } func generateName() string { firstNames := []string{ "Merek", "Carac", "Ulric", "Tybalt", "Borin", "Sadon", "Terrowin", "Rowan", "Forthwind", "Althalos", "Fendrel", "Brom", "Hadrian", "Benedict", "Gregory", "Peter", "Henry", "Frederick", "Walter", "Thomas", "Arthur", "Bryce", "Donald", "Leofrick", "Letholdus", "Lief", "Barda", "Rulf", "Robin", "Gavin", "Terrin", "Terryn", "Ronald", "Jarin", "Cassius", "Leo", "Cedric", "Gavin", "Peyton", "Josef", "Janshai", "Doran", "Asher", "Quinn", "Zane ", "Xalvador", "Favian", "Destrian", "Dain", "Berinon", "Tristan", "Gorvenal", "Alfie", "Andy", "Basil", "Buddy", "Carter", "Charlie", "Danny", "Eddie", "Finn", "Freddie", "George", "Harrison", "Hank", "Jack", "Jonny", "Karl", "Leo", "Leonard", "Manny", "Mason", "Noah", "Oscar", "Pete", "Robin", "Sammy", "Tim", "Toby", "Tyler", "Victor", "Will", "Zack", } lastNames := []string{ "Ashdown", "Baker", "Bennett", "Bigge", "Brickenden", "Brooker", "Browne", "Carpenter", "Cheeseman", "Clarke", "Cooper", "Fletcher", "Foreman", "Godfrey", "Hughes", "Mannering", "Payne", "Rolfe", "Taylor", "Walter", "Ward", "Webb", "Wood", "Abbey", "Arkwright", "Bauer", "Bell", "Brewster", "Chamberlain", "Chandler", "Chapman", "Clarke", "Collier", "Cooper", "Dempster", "Harper", "Inman", "Jenner", "Kemp", "Kitchener", "Knight", "Lister", "Miller", "Packard", "Page", "Payne", "Palmer", "Parker", "Porter", "Rolfe", "Ryder", "Saylor", "Scrivens", "Sommer", "Smith", "Spinner", } nickNames := []string{ "Stormbringer", "Swiftflight", "Sorrowsweet", "Shadowmere", "Shadowfax", "Keirstrider", "Bruno", "Fireflanel", "Curonious", "Suntaria", "Gypsy", "Titanium", "Curse", "Lightning", "Thunder", "Storm", "<NAME>", "Goldentrot", "Stareyes", "Rock", "Morningstar", "Firefreeze", "Veillantif", "Winddodger", "Hafaleil", "Starflare", "Elton", "Cobalt", "Darktonian", "<NAME>", "Death Storm", "Grand Prancer", "Big Heart", "Canterwell", "Fury", "Wildfire", "Tempest", "Silvermane", "Bowrider", "Bucephalus", "Rocinante", "Ares", "Blade", "Maverick", "Tank", "<NAME>", "Fish", "Fox", "Grant", "Hardy", "Hawk", "Hendman", "Keen", "Lightfoot", "Mannering", "Moody", "Mundy", "Peacock", "Power", "Pratt", "Proude", "Pruitt", "Puttock", "Quick", "Rey", "Rose", "Russ", "Selly", "Sharp", "Short", "Sommer", "Sparks", "Spear", "Stern", "Sweet", "Tait", "Terrell", "Truman", } firstName := firstNames[rand.Intn(len(firstNames))] lastName := lastNames[rand.Intn(len(lastNames))] nickName := nickNames[rand.Intn(len(nickNames))] return fmt.Sprintf("%s \"%s\" %s", firstName, nickName, lastName) } func generateAge() uint { return 20 + uint(rand.Intn(400)) } func (c *Colonist) SetStatus(s string) { c.Status = s } func createDesires() map[DesireType]float64 { return map[DesireType]float64{ Fulfillment: float64(rand.Intn(60)), Belonging: float64(rand.Intn(60)), Esteem: float64(rand.Intn(60)), } } func createNeeds() map[NeedType]float64 { return map[NeedType]float64{ Hunger: float64(rand.Intn(80)), Thirst: float64(rand.Intn(80)), Stress: float64(rand.Intn(80)), Exhaustion: float64(rand.Intn(80)), Fear: float64(rand.Intn(80)), Pain: float64(rand.Intn(80)), } } func generateSkills() map[SkillType]float64 { var values [11]float64 for i := 0; i < 2; i++ { values[i] = 4 + (rand.Float64() * 10) } for i := 2; i < 8; i++ { values[i] = 3 + (rand.Float64() * 5) } for i := 8; i < 11; i++ { values[i] = rand.Float64() * 2 } rand.Shuffle(len(values), func(i, j int) { values[i], values[j] = values[j], values[i] }) return map[SkillType]float64{ Hunting: values[0], Crafting: values[1], Cooking: values[2], Building: values[3], Gathering: values[4], Mining: values[5], Woodcutting: values[6], Science: values[7], Combat: values[8], Charisma: values[9], Medicine: values[10], Tinkering: values[10], } }
colonist/colonist.go
0.524151
0.454896
colonist.go
starcoder
package schema const RUMV3Schema = `{ "$id": "docs/spec/transactions/rum_v3_transaction.json", "type": "object", "description": "An event corresponding to an incoming request or similar task occurring in a monitored service", "allOf": [ { "properties": { "id": { "type": "string", "description": "Hex encoded 64 random bits ID of the transaction.", "maxLength": 1024 }, "tid": { "description": "Hex encoded 128 random bits ID of the correlated trace.", "type": "string", "maxLength": 1024 }, "pid": { "description": "Hex encoded 64 random bits ID of the parent transaction or span. Only root transactions of a trace do not have a parent_id, otherwise it needs to be set.", "type": [ "string", "null" ], "maxLength": 1024 }, "t": { "type": "string", "description": "Keyword of specific relevance in the service's domain (eg: 'request', 'backgroundjob', etc)", "maxLength": 1024 }, "n": { "type": [ "string", "null" ], "description": "Generic designation of a transaction in the scope of a single service (eg: 'GET /users/:id')", "maxLength": 1024 }, "y": { "type": ["array", "null"], "$id": "docs/spec/spans/rum_v3_span.json", "description": "An event captured by an agent occurring in a monitored service", "allOf": [ { "properties": { "id": { "description": "Hex encoded 64 random bits ID of the span.", "type": "string", "maxLength": 1024 }, "pi": { "description": "Index of the parent span in the list. Absent when the parent is a transaction.", "type": ["integer", "null"], "maxLength": 1024 }, "s": { "type": [ "number", "null" ], "description": "Offset relative to the transaction's timestamp identifying the start of the span, in milliseconds" }, "t": { "type": "string", "description": "Keyword of specific relevance in the service's domain (eg: 'db.postgresql.query', 'template.erb', etc)", "maxLength": 1024 }, "su": { "type": [ "string", "null" ], "description": "A further sub-division of the type (e.g. postgresql, elasticsearch)", "maxLength": 1024 }, "ac": { "type": [ "string", "null" ], "description": "The specific kind of event within the sub-type represented by the span (e.g. query, connect)", "maxLength": 1024 }, "c": { "type": [ "object", "null" ], "description": "Any other arbitrary data captured by the agent, optionally provided by the user", "properties": { "dt": { "type": [ "object", "null" ], "description": "An object containing contextual data about the destination for spans", "properties": { "ad": { "type": [ "string", "null" ], "description": "Destination network address: hostname (e.g. 'localhost'), FQDN (e.g. 'elastic.co'), IPv4 (e.g. '127.0.0.1') or IPv6 (e.g. '::1')", "maxLength": 1024 }, "po": { "type": [ "integer", "null" ], "description": "Destination network port (e.g. 443)" }, "se": { "description": "Destination service context", "type": [ "object", "null" ], "properties": { "t": { "description": "Type of the destination service (e.g. 'db', 'elasticsearch'). Should typically be the same as span.type.", "type": [ "string", "null" ], "maxLength": 1024 }, "n": { "description": "Identifier for the destination service (e.g. 'http://elastic.co', 'elasticsearch', 'rabbitmq')", "type": [ "string", "null" ], "maxLength": 1024 }, "rc": { "description": "Identifier for the destination service resource being operated on (e.g. 'http://elastic.co:80', 'elasticsearch', 'rabbitmq/queue_name')", "type": [ "string", "null" ], "maxLength": 1024 } }, "required": [ "t", "n", "rc" ] } } }, "h": { "type": [ "object", "null" ], "description": "An object containing contextual data of the related http request.", "properties": { "url": { "type": [ "string", "null" ], "description": "The raw url of the correlating http request." }, "sc": { "type": [ "integer", "null" ], "description": "The status code of the http request." }, "mt": { "type": [ "string", "null" ], "maxLength": 1024, "description": "The method of the http request." } } }, "g": { "$id": "docs/spec/tags.json", "title": "Tags", "type": ["object", "null"], "description": "A flat mapping of user-defined tags with string, boolean or number values.", "patternProperties": { "^[^.*\"]*$": { "type": ["string", "boolean", "number", "null"], "maxLength": 1024 } }, "additionalProperties": false }, "se": { "description": "Service related information can be sent per event. Provided information will override the more generic information from metadata, non provided fields will be set according to the metadata information.", "properties": { "a": { "description": "Name and version of the Elastic APM agent", "type": [ "object", "null" ], "properties": { "n": { "description": "Name of the Elastic APM agent, e.g. \"Python\"", "type": [ "string", "null" ], "maxLength": 1024 }, "ve": { "description": "Version of the Elastic APM agent, e.g.\"1.0.0\"", "type": [ "string", "null" ], "maxLength": 1024 } } }, "n": { "description": "Immutable name of the service emitting this event", "type": [ "string", "null" ], "pattern": "^[a-zA-Z0-9 _-]+$", "maxLength": 1024 } } } } }, "d": { "type": "number", "description": "Duration of the span in milliseconds", "minimum": 0 }, "n": { "type": "string", "description": "Generic designation of a span in the scope of a transaction", "maxLength": 1024 }, "st": { "type": [ "array", "null" ], "description": "List of stack frames with variable attributes (eg: lineno, filename, etc)", "items": { "$id": "docs/spec/rum_v3_stacktrace_frame.json", "title": "Stacktrace", "type": "object", "description": "A stacktrace frame, contains various bits (most optional) describing the context of the frame", "properties": { "ap": { "description": "The absolute path of the file involved in the stack frame", "type": [ "string", "null" ] }, "co": { "description": "Column number", "type": [ "integer", "null" ] }, "cli": { "description": "The line of code part of the stack frame", "type": [ "string", "null" ] }, "f": { "description": "The relative filename of the code involved in the stack frame, used e.g. to do error checksumming", "type": [ "string", "null" ] }, "cn": { "description": "The classname of the code involved in the stack frame", "type": [ "string", "null" ] }, "fn": { "description": "The function involved in the stack frame", "type": [ "string", "null" ] }, "li": { "description": "The line number of code part of the stack frame, used e.g. to do error checksumming", "type": [ "integer", "null" ] }, "mo": { "description": "The module to which frame belongs to", "type": [ "string", "null" ] }, "poc": { "description": "The lines of code after the stack frame", "type": [ "array", "null" ], "minItems": 0, "items": { "type": "string" } }, "prc": { "description": "The lines of code before the stack frame", "type": [ "array", "null" ], "minItems": 0, "items": { "type": "string" } } }, "required": [ "f" ] }, "minItems": 0 }, "sy": { "type": [ "boolean", "null" ], "description": "Indicates whether the span was executed synchronously or asynchronously." } }, "required": [ "d", "n", "t", "id" ] }, { "required": [ "s" ], "properties": { "s": { "type": "number" } } } ] }, "me": { "type": ["array", "null"], "$id": "docs/spec/metricsets/rum_v3_metricset.json", "description": "Data captured by an agent representing an event occurring in a monitored service", "properties": { "y": { "type": ["object", "null"], "description": "span", "properties": { "t": { "type": "string", "description": "type", "maxLength": 1024 }, "su": { "type": ["string", "null"], "description": "subtype", "maxLength": 1024 } } }, "sa": { "type": "object", "description": "Sampled application metrics collected from the agent.", "properties": { "xdc": { "description": "transaction.duration.count", "$schema": "http://json-schema.org/draft-04/schema#", "$id": "docs/spec/metricsets/rum_v3_sample.json", "type": ["object", "null"], "description": "A single metric sample.", "properties": { "v": {"type": "number"} }, "required": ["v"] }, "xds": { "description": "transaction.duration.sum.us", "$schema": "http://json-schema.org/draft-04/schema#", "$id": "docs/spec/metricsets/rum_v3_sample.json", "type": ["object", "null"], "description": "A single metric sample.", "properties": { "v": {"type": "number"} }, "required": ["v"] }, "xbc": { "description": "transaction.breakdown.count", "$schema": "http://json-schema.org/draft-04/schema#", "$id": "docs/spec/metricsets/rum_v3_sample.json", "type": ["object", "null"], "description": "A single metric sample.", "properties": { "v": {"type": "number"} }, "required": ["v"] }, "ysc": { "description": "span.self_time.count", "$schema": "http://json-schema.org/draft-04/schema#", "$id": "docs/spec/metricsets/rum_v3_sample.json", "type": ["object", "null"], "description": "A single metric sample.", "properties": { "v": {"type": "number"} }, "required": ["v"] }, "yss": { "description": "span.self_time.sum.us", "$schema": "http://json-schema.org/draft-04/schema#", "$id": "docs/spec/metricsets/rum_v3_sample.json", "type": ["object", "null"], "description": "A single metric sample.", "properties": { "v": {"type": "number"} }, "required": ["v"] } } }, "tags": { "$id": "docs/spec/tags.json", "title": "Tags", "type": ["object", "null"], "description": "A flat mapping of user-defined tags with string, boolean or number values.", "patternProperties": { "^[^.*\"]*$": { "type": ["string", "boolean", "number", "null"], "maxLength": 1024 } }, "additionalProperties": false } }, "required": ["sa"] }, "yc": { "type": "object", "properties": { "sd": { "type": "integer", "description": "Number of correlated spans that are recorded." }, "dd": { "type": [ "integer", "null" ], "description": "Number of spans that have been dd by the a recording the x." } }, "required": [ "sd" ] }, "c": { "$id": "docs/spec/rum_v3_context.json", "title": "Context", "description": "Any arbitrary contextual information regarding the event, captured by the agent, optionally provided by the user", "type": [ "object", "null" ], "properties": { "cu": { "description": "An arbitrary mapping of additional metadata to store with the event.", "type": [ "object", "null" ], "patternProperties": { "^[^.*\"]*$": {} }, "additionalProperties": false }, "r": { "type": [ "object", "null" ], "allOf": [ { "properties": { "sc": { "type": [ "integer", "null" ], "description": "The status code of the http request." }, "ts": { "type": [ "number", "null" ], "description": "Total size of the payload." }, "ebs": { "type": [ "number", "null" ], "description": "The encoded size of the payload." }, "dbs": { "type": [ "number", "null" ], "description": "The decoded size of the payload." }, "he": { "type": [ "object", "null" ], "patternProperties": { "[.*]*$": { "type": [ "string", "array", "null" ], "items": { "type": [ "string" ] } } } } } } ] }, "q": { "properties": { "en": { "description": "The env variable is a compounded of environment information passed from the webserver.", "type": [ "object", "null" ], "properties": {} }, "he": { "description": "Should include any headers sent by the requester. Cookies will be taken by headers if supplied.", "type": [ "object", "null" ], "patternProperties": { "[.*]*$": { "type": [ "string", "array", "null" ], "items": { "type": [ "string" ] } } } }, "hve": { "description": "HTTP version.", "type": [ "string", "null" ], "maxLength": 1024 }, "mt": { "description": "HTTP method.", "type": "string", "maxLength": 1024 } }, "required": [ "mt" ] }, "g": { "$id": "docs/spec/tags.json", "title": "Tags", "type": ["object", "null"], "description": "A flat mapping of user-defined tags with string, boolean or number values.", "patternProperties": { "^[^.*\"]*$": { "type": ["string", "boolean", "number", "null"], "maxLength": 1024 } }, "additionalProperties": false }, "u": { "$id": "docs/spec/rum_v3_user.json", "title": "User", "type": [ "object", "null" ], "properties": { "id": { "description": "Identifier of the logged in user, e.g. the primary key of the user", "type": [ "string", "integer", "null" ], "maxLength": 1024 }, "em": { "description": "Email of the logged in user", "type": [ "string", "null" ], "maxLength": 1024 }, "un": { "description": "The username of the logged in user", "type": [ "string", "null" ], "maxLength": 1024 } } }, "p": { "description": "", "type": [ "object", "null" ], "properties": { "rf": { "description": "RUM specific field that stores the URL of the page that 'linked' to the current page.", "type": [ "string", "null" ] }, "url": { "description": "RUM specific field that stores the URL of the current page", "type": [ "string", "null" ] } } }, "se": { "description": "Service related information can be sent per event. Provided information will override the more generic information from metadata, non provided fields will be set according to the metadata information.", "$id": "docs/spec/rum_v3_service.json", "title": "Service", "type": [ "object", "null" ], "properties": { "a": { "description": "Name and version of the Elastic APM agent", "type": [ "object", "null" ], "properties": { "n": { "description": "Name of the Elastic APM agent, e.g. \"Python\"", "type": [ "string", "null" ], "maxLength": 1024 }, "ve": { "description": "Version of the Elastic APM agent, e.g.\"1.0.0\"", "type": [ "string", "null" ], "maxLength": 1024 } } }, "fw": { "description": "Name and version of the web framework used", "type": [ "object", "null" ], "properties": { "n": { "type": [ "string", "null" ], "maxLength": 1024 }, "ve": { "type": [ "string", "null" ], "maxLength": 1024 } } }, "la": { "description": "Name and version of the programming language used", "type": [ "object", "null" ], "properties": { "n": { "type": [ "string", "null" ], "maxLength": 1024 }, "ve": { "type": [ "string", "null" ], "maxLength": 1024 } } }, "n": { "description": "Immutable name of the service emitting this event", "type": [ "string", "null" ], "pattern": "^[a-zA-Z0-9 _-]+$", "maxLength": 1024 }, "en": { "description": "Environment name of the service, e.g. \"production\" or \"staging\"", "type": [ "string", "null" ], "maxLength": 1024 }, "ru": { "description": "Name and version of the language runtime running this service", "type": [ "object", "null" ], "properties": { "n": { "type": [ "string", "null" ], "maxLength": 1024 }, "ve": { "type": [ "string", "null" ], "maxLength": 1024 } } }, "ve": { "description": "Version of the service emitting this event", "type": [ "string", "null" ], "maxLength": 1024 } } } } }, "d": { "type": "number", "description": "How long the transaction took to complete, in ms with 3 decimal points", "minimum": 0 }, "rt": { "type": [ "string", "null" ], "description": "The result of the transaction. For HTTP-related transactions, this should be the status code formatted like 'HTTP 2xx'.", "maxLength": 1024 }, "k": { "type": [ "object", "null" ], "description": "A mark captures the timing of a significant event during the lifetime of a transaction. Marks are organized into groups and can be set by the user or the agent.", "$id": "docs/spec/transactions/rum_v3_mark.json", "type": ["object", "null"], "description": "A mark captures the timing in milliseconds of a significant event during the lifetime of a transaction. Every mark is a simple key value pair, where the value has to be a number, and can be set by the user or the agent.", "properties": { "a": { "type": ["object", "null"], "description": "agent", "properties": { "dc": { "type": ["number", "null"], "description": "domComplete" }, "di": { "type": ["number", "null"], "description": "domInteractive" }, "ds": { "type": ["number", "null"], "description": "domContentLoadedEventStart" }, "de": { "type": ["number", "null"], "description": "domContentLoadedEventEnd" }, "fb": { "type": ["number", "null"], "description": "timeToFirstByte" }, "fp": { "type": ["number", "null"], "description": "firstContentfulPaint" }, "lp": { "type": ["number", "null"], "description": "largestContentfulPaint" } } }, "nt": { "type": ["object", "null"], "description": "navigation-timing", "properties": { "fs": { "type": ["number", "null"], "description": "fetchStart" }, "ls": { "type": ["number", "null"], "description": "domainLookupStart" }, "le": { "type": ["number", "null"], "description": "domainLookupEnd" }, "cs": { "type": ["number", "null"], "description": "connectStart" }, "ce": { "type": ["number", "null"], "description": "connectEnd" }, "qs": { "type": ["number", "null"], "description": "requestStart" }, "rs": { "type": ["number", "null"], "description": "responseStart" }, "re": { "type": ["number", "null"], "description": "responseEnd" }, "dl": { "type": ["number", "null"], "description": "domLoading" }, "di": { "type": ["number", "null"], "description": "domInteractive" }, "ds": { "type": ["number", "null"], "description": "domContentLoadedEventStart" }, "de": { "type": ["number", "null"], "description": "domContentLoadedEventEnd" }, "dc": { "type": ["number", "null"], "description": "domComplete" }, "es": { "type": ["number", "null"], "description": "loadEventStart" }, "ee": { "type": ["number", "null"], "description": "loadEventEnd" } } } } }, "sm": { "type": [ "boolean", "null" ], "description": "Transactions that are 'sampled' will include all available information. Transactions that are not sampled will not have 'spans' or 'context'. Defaults to true." } }, "required": [ "id", "tid", "yc", "d", "t" ] } ] } `
model/transaction/generated/schema/rum_v3_transaction.go
0.782455
0.540681
rum_v3_transaction.go
starcoder
package isa497 import ( "fmt" ) // Tree represents a Tree data structure. type Tree struct { key int root *Tree parent *Tree left *Tree right *Tree } // Key returns the key-value of a tree func (t *Tree) Key() int { return t.key } // NewTree returns a new Tree struct. func NewTree(k int) (t *Tree) { t = &Tree{ key: k, parent: nil, left: nil, right: nil, } t.root = t return } func inorderTreeWalk(t *Tree) { if t != nil { inorderTreeWalk(t.left) fmt.Println(t.key) inorderTreeWalk(t.right) } } func recTreeSearch(x *Tree, key int) *Tree { if x == nil || x.key == key { return x } if key < x.key { return recTreeSearch(x.left, key) } return recTreeSearch(x.right, key) } func iterTreeSearch(x *Tree, key int) *Tree { for x != nil && key != x.key { if key < x.key { x = x.left } else { x = x.right } } return x } func treeMin(x *Tree) *Tree { for x.left != nil { x = x.left } return x } func treeMax(x *Tree) *Tree { for x.right != nil { x = x.right } return x } func treeSuccessor(x *Tree) *Tree { if x.right != nil { return treeMin(x.right) } y := x.root for y != nil && x == y.right { x = y y = y.root } return y } func treeInsert(t, z *Tree) { var x, y *Tree for x = t.root; x != nil; { y = x if z.key < x.key { x = x.left } else { x = x.right } } z.parent = y z.root = y.root switch { case y == nil: t.root = z case z.key < y.key: y.left = z default: y.right = z } } func transplant(t, u, v *Tree) { switch { case u.parent == nil: t.root = v case u == u.parent.left: u.parent.left = v default: u.parent.right = v } if v != nil { v.parent = u.parent } } func treeDelete(t, z *Tree) { var y *Tree switch { case z.left == nil: transplant(t, z, z.right) case z.right == nil: transplant(t, z, z.left) default: if y = treeMin(z.right); y.parent != z { transplant(t, y, y.right) y.right = z.right y.right.parent = y } transplant(t, z, y) y.left = z.left y.left.parent = y } }
trees.go
0.803482
0.467149
trees.go
starcoder
package ontap // FcPort A Fibre Channel (FC) port is the physical port of an FC adapter on an ONTAP cluster node that can be connected to an FC network to provide FC network connectivity. An FC port defines the location of an FC interface within the ONTAP cluster. type FcPort struct { Links InlineResponse201Links `json:"_links,omitempty"` // A description of the FC port. Description string `json:"description,omitempty"` // The administrative state of the FC port. If this property is set to _false_, all FC connectivity to FC interfaces are blocked. Optional in PATCH. Enabled bool `json:"enabled,omitempty"` Fabric FcPortFabric `json:"fabric,omitempty"` // The FC port name. Name string `json:"name,omitempty"` Node InlineResponse201Node `json:"node,omitempty"` // The physical network protocol of the FC port. PhysicalProtocol string `json:"physical_protocol,omitempty"` Speed FcPortSpeed `json:"speed,omitempty"` // The operational state of the FC port. - startup - The port is booting up. - link_not_connected - The port has finished initialization, but a link with the fabric is not established. - online - The port is initialized and a link with the fabric has been established. - link_disconnected - The link was present at one point on this port but is currently not established. - offlined_by_user - The port is administratively disabled. - offlined_by_system - The port is set to offline by the system. This happens when the port encounters too many errors. - node_offline - The state information for the port cannot be retrieved. The node is offline or inaccessible. State string `json:"state,omitempty"` // The network protocols supported by the FC port. SupportedProtocols []string `json:"supported_protocols,omitempty"` Transceiver FcPortTransceiver `json:"transceiver,omitempty"` // The unique identifier of the FC port. Uuid string `json:"uuid,omitempty"` // The base world wide node name (WWNN) for the FC port. Wwnn string `json:"wwnn,omitempty"` // The base world wide port name (WWPN) for the FC port. Wwpn string `json:"wwpn,omitempty"` }
ontap/model_fc_port.go
0.696681
0.406155
model_fc_port.go
starcoder
package schoolsout import ( "errors" "sync" "time" ) // Calendar is used to determine and calculate applicable holidays. type Calendar struct { sync.RWMutex DisableShiftSaturday bool DisableShiftSunday bool holidays []HolidayDefinition } // HolidayDefinition is the definition of a single Holiday. type HolidayDefinition struct { Name string calculation DateCalculation checkForYearShift bool // Special case for New Year's Day } // Holiday is an instance of a holiday that occurs in a single year. type Holiday struct { Name string Date time.Time } // ClearHolidays removes all previously loaded holidays. func (so *Calendar) ClearHolidays() { so.Lock() defer so.Unlock() so.holidays = nil } // AddHoliday adds a new holiday definition to the Calendar instance. func (so *Calendar) AddHoliday(name string, def DateCalculation, mayShiftYear bool) { so.Lock() defer so.Unlock() so.holidays = append(so.holidays, HolidayDefinition{ Name: name, calculation: so.shiftForWeekend(def), checkForYearShift: mayShiftYear, }) } // Unique list of the currently loaded holiday names (order is not guaranteed). func (so *Calendar) ListHolidays() []string { names := make([]string, len(so.holidays)) for i, h := range so.holidays { names[i] = h.Name } return names } // AllHolidaysForYear generates a list of all holidays for the specified year (order is not guaranteed). func (so *Calendar) AllHolidaysForYear(year int) []Holiday { so.Lock() defer so.Unlock() c := []Holiday{} for _, def := range so.holidays { f := func(processYear int) { date := def.calculation(processYear) // Only push to slice if resulting year matches if date.Year() == year { c = append(c, Holiday{Name: def.Name, Date: date}) } } //Execute for specified year f(year) //If this holiday might shift years, check previous & next year if def.checkForYearShift { f(year - 1) f(year + 1) } } return c } // HolidayDateForYears returns the date(s) applicable for the holiday over the specified years func (so *Calendar) HolidayDateForYears(name string, years []int) ([]time.Time, error) { so.Lock() defer so.Unlock() for _, def := range so.holidays { if def.Name == name { d := []time.Time{} for _, year := range years { d = append(d, def.calculation(year)) } return d, nil } } return nil, errors.New("holiday not found") } // IsHoliday returns true if the passed time.Time occurs on a holiday for the specified year. func (so *Calendar) IsHoliday(date time.Time) bool { for _, h := range so.AllHolidaysForYear(date.Year()) { if h.Date.Month() == date.Month() && h.Date.Day() == date.Day() { return true } } return false } // shiftForWeekend will adjust a holiday to Friday or Sunday based to meet federal guidelines. func (so *Calendar) shiftForWeekend(calc DateCalculation) DateCalculation { return func(year int) time.Time { date := calc(year) if !so.DisableShiftSaturday && date.Weekday() == time.Saturday { date = date.AddDate(0, 0, -1) } if !so.DisableShiftSunday && date.Weekday() == time.Sunday { date = date.AddDate(0, 0, 1) } return date } } type DateCalculation func(year int) time.Time // FixedDay returns a function for calculating a fixed date in a particular year. func FixedDay(day int, month time.Month) DateCalculation { return func(year int) time.Time { return time.Date(year, month, day, 0, 0, 0, 0, time.UTC) } } // NthWeekdayOf returns a function for determining the Nth (idx) weekday of the specified month in a particular year. func NthWeekdayOf(idx int, dow time.Weekday, month time.Month) DateCalculation { return func(year int) time.Time { firstOfMonth := time.Date(year, month, 1, 0, 0, 0, 0, time.UTC) offset := int(firstOfMonth.Weekday()) - int(dow) if offset > 0 { offset = 7 - offset } else { offset = -offset } initialWeekdayOf := firstOfMonth.AddDate(0, 0, offset) return initialWeekdayOf.AddDate(0, 0, 7*(idx-1)) } } // LastWeekdayOf returns a function for determining the last weekday of the specified month in a particular year. func LastWeekdayOf(dow time.Weekday, month time.Month) DateCalculation { initFunc := NthWeekdayOf(1, dow, month) return func(year int) time.Time { lwdo := initFunc(year) adjLastDayOfMonth := time.Date(year, month+1, 1, 0, 0, 0, 0, time.UTC).AddDate(0, 0, -7) for lwdo.Before(adjLastDayOfMonth) { lwdo = lwdo.AddDate(0, 0, 7) } return lwdo } }
schoolsout.go
0.675444
0.533397
schoolsout.go
starcoder
package kdtree import ( "container/heap" "math" "github.com/go-spatial/geom" ) /* heapEntry is an entry in the heap for storing nodes so we can get back the nearest neighbors in order. */ type heapEntry struct { node *KdNode d float64 } /* kdNodeHeap is an array of heap entries. We are not using a pointer in this array for simplicity and to avoid the dereference. This is likely ok due to the small size of heapEntry. If for some reason heapEntry gets larger then this should be changed to a pointer. Also, benchmarks may reveal that a pointer is faster. Dunno. https://stackoverflow.com/questions/27622083/performance-slices-of-structs-vs-slices-of-pointers-to-structs */ type kdNodeHeap []heapEntry // Implements the container/heap interface. func (knh kdNodeHeap) Len() int { return len(knh) } func (knh kdNodeHeap) Less(i, j int) bool { return knh[i].d < knh[j].d } func (knh kdNodeHeap) Swap(i, j int) { knh[i], knh[j] = knh[j], knh[i] } func (knh *kdNodeHeap) Push(x interface{}) { // this will simply panic if the wrong type is passed. he, ok := x.(*heapEntry) if !ok { panic("the wrong interface type was passed to kdNodeHeap.") } *knh = append(*knh, *he) } func (knh *kdNodeHeap) Pop() interface{} { old := *knh n := len(old) x := old[n-1] *knh = old[0 : n-1] return x } /* DistanceFunc specifies how to calculate the distance from a point to the extent. In most cases the default EuclideanDistance function will do just fine. */ type DistanceFunc func(p geom.Pointer, e *geom.Extent) float64 func distance(c1 [2]float64, c2 [2]float64) float64 { v1 := c2[0] - c1[0] v2 := c2[1] - c1[1] return math.Sqrt(v1*v1 + v2*v2) } func EuclideanDistance(p geom.Pointer, e *geom.Extent) float64 { if e.ContainsPoint(p.XY()) { return 0 } x := p.XY()[0] y := p.XY()[1] if x < e.MinX() { if y < e.MinY() { return distance(p.XY(), e.Min()) } if y > e.MaxY() { return distance(p.XY(), [2]float64{e.MinX(), e.MaxY()}) } return e.MinX() - x } if x > e.MaxX() { if y < e.MinY() { return distance(p.XY(), [2]float64{e.MaxX(), e.MinY()}) } if y > e.MaxY() { return distance(p.XY(), e.Max()) } return x - e.MaxX() } if y < e.MinY() { return e.MinY() - y } return y - e.MaxY() } type NearestNeighborIterator struct { p geom.Pointer kdTree *KdTree df DistanceFunc currentIt *heapEntry nodeHeap kdNodeHeap bboxHeap kdNodeHeap } /* NewNearestNeighborIterator creates an iterator that returns the neighboring points in descending order. Retrieving all the results will occur in O(n log(n)) time. Results are calculated in a lazy fashion so retrieving the nearest point or the nearest handful should still be quite efficient. Algorithm: * Initialize by calculating the distance from the source point to the root node and the root node's bounding box. Push both these values onto their respective heaps (nodeHeap & bboxHeap) * While there is still data to return: * If the distance on the top of the nodeHeap is < the distance on the top of bboxHeap we know that node is closer than all the remaining nodes and can be returned to the user. * Otherwise, the node might not be closest, so pop of the next bounding box and push its children onto the nodeHeap. The iterator design here was taken from: https://ewencp.org/blog/golang-iterators/index.html To use this iterator: nnit := NewNearestNeighborIterator(geom.Point{0,0}, myKdTree, EuclideanDistance) for nnit.Next() { n, d := nnit.Value() // do stuff } */ func NewNearestNeighborIterator(p geom.Pointer, kdTree *KdTree, df DistanceFunc) *NearestNeighborIterator { result := NearestNeighborIterator{ p: p, kdTree: kdTree, df: df, } result.pushNode(kdTree.root) return &result } /* Next iterates to the next nearest neighbor. True is returned if there is another nearest neighbor, otherwise false is returned. */ func (nni *NearestNeighborIterator) Next() bool { for { if nni.nodeHeap.Len() == 0 && nni.bboxHeap.Len() == 0 { nni.currentIt = nil break } if nni.nodeHeap.Len() > 0 && ((nni.bboxHeap.Len() > 0 && nni.nodeHeap[0].d <= nni.bboxHeap[0].d) || nni.bboxHeap.Len() == 0) { he := (heap.Pop(&nni.nodeHeap).(heapEntry)) nni.currentIt = &he break } parent := heap.Pop(&nni.bboxHeap).(heapEntry).node nni.pushNode(parent.Left()) nni.pushNode(parent.Right()) } return nni.currentIt != nil } // pushNode pushes the specified node onto both the bboxHeap and nodeHeap. func (nni *NearestNeighborIterator) pushNode(n *KdNode) { if n == nil { return } // push the bounding box distance onto the bbox heap d := nni.df(nni.p, &n.bbox) heap.Push(&nni.bboxHeap, &heapEntry{n, d}) // push the point distance onto the node heap d = nni.df(nni.p, geom.NewExtent(n.p.XY())) heap.Push(&nni.nodeHeap, &heapEntry{n, d}) } // Value returns the geometry pointer and distance for the current neighbor. func (nni *NearestNeighborIterator) Value() (geom.Pointer, float64) { return nni.currentIt.node.P(), nni.currentIt.d }
planar/index/kdtree/nearest_neighbor_iterator.go
0.798619
0.465691
nearest_neighbor_iterator.go
starcoder
The mapping system is based on a set of rules described inside a JSON mapping file, here's an example: { "raws": { "ui": "user_id" }, "mapped": { "oi": { "name": "is_opted_in", "values": { "0": "false", "1": "true" } } }, "reversed": [ { "name": "order_status", "values": { "1": "pending_payment", "2": "failed", "3": "processing", "4": "completed", "5": "on_hold", "6": "canceled", "7": "refunded" } } ] } The mapping has 3 sections: - raws: only the column qualifier is translated from its short version to a meaningful name. - mapped: the column qualifier is translated from its short version to a meaningful name, and the value is translated from its short-value to the full value. - reversed: the column qualifier contains the real data which is mapped to a value as described in the "values" property and the column name is taken from the "name" attribute. Considering the mapping above, let's say we have a row with the following data coming from Big Table: { "ui": "12345", "oi": "1", "3": "1" } The mapping system will map it to a new data.Event containing the following data: { "user_id": "12345", "is_opted_in": "true", "order_status": "processing" } */ package mapping import ( "encoding/json" "os" "path/filepath" ) // Mapping describes the mapping between data stored in Big Table and its human-readable representation. type Mapping struct { // columns that are taken as there are in Big Table Raws map[string]string `json:"raws"` // columns that needs to be mapped to a string value Mapped map[string]Map `json:"mapped"` // columns featuring a reversed mapping, meaning that the column qualifier is the data Reversed []Map `json:"reversed"` } // Map is used to map a column to a set of string values. type Map struct { Name string `json:"name"` Values map[string]string `json:"values"` } // LoadMapping loads a mapping from a slice of bytes. // You can use this function if you prefer to open the mapping file yourself. func LoadMapping(c []byte) (*Mapping, error) { m := &Mapping{} err := json.Unmarshal(c, &m) if err != nil { return nil, err } return m, nil } // LoadMappingFromFile loads a mapping from a file. func LoadMappingFromFile(path string) (*Mapping, error) { c, err := os.ReadFile(filepath.Clean(path)) if err != nil { return nil, err } return LoadMapping(c) }
mapping/mapping.go
0.777722
0.663349
mapping.go
starcoder
package geometry import ( "math" "sort" ) type collisionCheckForCardinalDirection struct { border *Line firstVector *Line secondVector *Line } type collisionCheckForDiagonalDirection struct { firstBorder *Line secondBorder *Line firstVector *Line secondVector *Line thirdVector *Line } type diagonalCollisionSet struct { distance *Point length float32 } type byLength []diagonalCollisionSet func (a byLength) Len() int { return len(a) } func (a byLength) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byLength) Less(i, j int) bool { return a[i].length < a[j].length } // StopMovementOnCollision checks for a possible collision of rectangles movingRect and stillRect when movingRect gets // moved into direction by the specified distance. Returns in case of a collision this method will return the movingRect // moved for the max distance that will not cause a collision. It will return null of there is no collision of the two // given Rectangles. // movingRect: the rectangle that gets moved // stillRect: another rectangle that doesn't move // direction: direction of movement of movingRect // distance: distance of movement of movingRect func StopMovementOnCollision(movingRect *Rectangle, stillRect *Rectangle, direction Direction, distance *Point) *Rectangle { switch direction { case Up: return stopUpMovement(movingRect, stillRect, distance) case UpRight: return stopUpRightMovement(movingRect, stillRect, distance) case Right: return stopRightMovement(movingRect, stillRect, distance) case DownRight: return stopDownRightMovement(movingRect, stillRect, distance) case Down: return stopDownMovement(movingRect, stillRect, distance) case DownLeft: return stopDownLeftMovement(movingRect, stillRect, distance) case Left: return stopLeftMovement(movingRect, stillRect, distance) case UpLeft: return stopUpLeftMovement(movingRect, stillRect, distance) default: return nil } } func stopUpMovement(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Rectangle { var collision = getCollisionForMovementUp(movingRect, stillRect, distance) if nil != collision { return &Rectangle{X: movingRect.X, Y: collision.Y, Width: movingRect.Width, Height: movingRect.Height} } if stillRect.Width < movingRect.Width && nil != getCollisionForMovementDown(stillRect, movingRect, &Point{X: 0, Y: -1 * distance.Y}) { return &Rectangle{X: movingRect.X, Y: stillRect.Y + stillRect.Height, Width: movingRect.Width, Height: movingRect.Height} } return nil } func stopDownMovement(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Rectangle { var collision = getCollisionForMovementDown(movingRect, stillRect, distance) if nil != collision { return &Rectangle{X: movingRect.X, Y: collision.Y - movingRect.Height, Width: movingRect.Width, Height: movingRect.Height} } if stillRect.Width < movingRect.Width && nil != getCollisionForMovementUp(stillRect, movingRect, &Point{X: 0, Y: -1 * distance.Y}) { return &Rectangle{X: movingRect.X, Y: stillRect.Y - movingRect.Height, Width: movingRect.Width, Height: movingRect.Height} } return nil } func stopLeftMovement(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Rectangle { var collision = getCollisionForMovementLeft(movingRect, stillRect, distance) if nil != collision { return &Rectangle{X: collision.X, Y: movingRect.Y, Width: movingRect.Width, Height: movingRect.Height} } if stillRect.Height < movingRect.Height && nil != getCollisionForMovementRight(stillRect, movingRect, &Point{X: -1 * distance.X, Y: 0}) { return &Rectangle{X: stillRect.X + stillRect.Width, Y: movingRect.Y, Width: movingRect.Width, Height: movingRect.Height} } return nil } func stopRightMovement(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Rectangle { var collision = getCollisionForMovementRight(movingRect, stillRect, distance) if nil != collision { return &Rectangle{X: collision.X - movingRect.Width, Y: movingRect.Y, Width: movingRect.Width, Height: movingRect.Height} } if stillRect.Height < movingRect.Height && nil != getCollisionForMovementLeft(stillRect, movingRect, &Point{X: -1 * distance.X, Y: 0}) { return &Rectangle{X: stillRect.X - movingRect.Width, Y: movingRect.Y, Width: movingRect.Width, Height: movingRect.Height} } return nil } func stopUpRightMovement(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Rectangle { var maxUpRightMovement = getMaxUpRightMovement(movingRect, stillRect, distance) if nil != maxUpRightMovement { return movingRect.Add(maxUpRightMovement) } if stillRect.Width < movingRect.Width || stillRect.Height < movingRect.Height { var maxDownLeftMovement = getMaxDownLeftMovement(stillRect, movingRect, &Point{X: -1 * distance.X, Y: -1 * distance.Y}) if nil != maxDownLeftMovement { return &Rectangle{X: movingRect.X + -1*maxDownLeftMovement.X, Y: movingRect.Y + -1*maxDownLeftMovement.Y, Width: movingRect.Width, Height: movingRect.Height} } } return nil } func stopDownRightMovement(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Rectangle { var maxDownRightMovement = getMaxDownRightMovement(movingRect, stillRect, distance) if nil != maxDownRightMovement { return movingRect.Add(maxDownRightMovement) } if stillRect.Width < movingRect.Width || stillRect.Height < movingRect.Height { var maxUpLeftMovement = getMaxUpLeftMovement(stillRect, movingRect, &Point{X: -1 * distance.X, Y: -1 * distance.Y}) if nil != maxUpLeftMovement { return &Rectangle{X: movingRect.X + -1*maxUpLeftMovement.X, Y: movingRect.Y + -1*maxUpLeftMovement.Y, Width: movingRect.Width, Height: movingRect.Height} } } return nil } func stopUpLeftMovement(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Rectangle { var maxUpLeftMovement = getMaxUpLeftMovement(movingRect, stillRect, distance) if nil != maxUpLeftMovement { return movingRect.Add(maxUpLeftMovement) } if stillRect.Width < movingRect.Width || stillRect.Height < movingRect.Height { var maxDownRightMovement = getMaxDownRightMovement(stillRect, movingRect, &Point{X: -1 * distance.X, Y: -1 * distance.Y}) if nil != maxDownRightMovement { return &Rectangle{X: movingRect.X + -1*maxDownRightMovement.X, Y: movingRect.Y + -1*maxDownRightMovement.Y, Width: movingRect.Width, Height: movingRect.Height} } } return nil } func stopDownLeftMovement(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Rectangle { var maxDownLeftMovement = getMaxDownLeftMovement(movingRect, stillRect, distance) if nil != maxDownLeftMovement { return movingRect.Add(maxDownLeftMovement) } if stillRect.Width < movingRect.Width || stillRect.Height < movingRect.Height { var maxUpRightMovement = getMaxUpRightMovement(stillRect, movingRect, &Point{X: -1 * distance.X, Y: -1 * distance.Y}) if nil != maxUpRightMovement { return &Rectangle{X: movingRect.X + -1*maxUpRightMovement.X, Y: movingRect.Y + -1*maxUpRightMovement.Y, Width: movingRect.Width, Height: movingRect.Height} } } return nil } func checkCollisionOnCardinalDirection(provider *collisionCheckForCardinalDirection) *Point { var line = provider.border var collision = line.GetIntersection(provider.firstVector) if nil == collision { collision = line.GetIntersection(provider.secondVector) } return collision } func checkCollisionOnDiagonalDirection(provider *collisionCheckForDiagonalDirection) *Point { var collisions = make([]diagonalCollisionSet, 0) var borders = []*Line{provider.firstBorder, provider.secondBorder} var vectors = []*Line{provider.firstVector, provider.secondVector, provider.thirdVector} for _, v := range vectors { var collision *Point = nil for _, b := range borders { if nil == collision { collision = b.GetIntersection(v) } } if nil != collision { var a = math.Abs(float64(v.Start.X - collision.X)) var b = math.Abs(float64(v.Start.Y - collision.Y)) var length = math.Sqrt(a*a + b*b) var setItem = diagonalCollisionSet{distance: &Point{X: collision.X - v.Start.X, Y: collision.Y - v.Start.Y}, length: float32(length)} collisions = append(collisions, setItem) } } if len(collisions) > 0 { sort.Sort(byLength(collisions)) return collisions[0].distance } return nil } func getCollisionForMovementUp(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Point { var collisionCheck collisionCheckForCardinalDirection collisionCheck.border = stillRect.BottomBorder() collisionCheck.firstVector = &Line{Start: &Point{X: movingRect.X, Y: movingRect.Y}, End: &Point{X: movingRect.X, Y: movingRect.Y + distance.Y}} collisionCheck.secondVector = &Line{Start: &Point{X: movingRect.X + movingRect.Width, Y: movingRect.Y}, End: &Point{X: movingRect.X + movingRect.Width + distance.X, Y: movingRect.Y + distance.Y}} return checkCollisionOnCardinalDirection(&collisionCheck) } func getCollisionForMovementDown(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Point { var collisionCheck collisionCheckForCardinalDirection collisionCheck.border = stillRect.TopBorder() collisionCheck.firstVector = &Line{Start: &Point{X: movingRect.X, Y: movingRect.Y + movingRect.Height}, End: &Point{X: movingRect.X + distance.X, Y: movingRect.Y + movingRect.Height + distance.Y}} collisionCheck.secondVector = &Line{Start: &Point{X: movingRect.X + movingRect.Width, Y: movingRect.Y + movingRect.Height}, End: &Point{X: movingRect.X + movingRect.Width + distance.X, Y: movingRect.Y + movingRect.Height + distance.Y}} return checkCollisionOnCardinalDirection(&collisionCheck) } func getCollisionForMovementLeft(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Point { var collisionCheck collisionCheckForCardinalDirection collisionCheck.border = stillRect.RightBorder() collisionCheck.firstVector = &Line{Start: &Point{X: movingRect.X, Y: movingRect.Y}, End: &Point{X: movingRect.X + distance.X, Y: movingRect.Y}} collisionCheck.secondVector = &Line{Start: &Point{X: movingRect.X, Y: movingRect.Y + movingRect.Height}, End: &Point{X: movingRect.X + distance.X, Y: movingRect.Y + movingRect.Height}} return checkCollisionOnCardinalDirection(&collisionCheck) } func getCollisionForMovementRight(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Point { var collisionCheck collisionCheckForCardinalDirection collisionCheck.border = stillRect.LeftBorder() collisionCheck.firstVector = &Line{Start: &Point{X: movingRect.X + movingRect.Width, Y: movingRect.Y}, End: &Point{X: movingRect.X + movingRect.Width + distance.X, Y: movingRect.Y}} collisionCheck.secondVector = &Line{Start: &Point{X: movingRect.X + movingRect.Width, Y: movingRect.Y + movingRect.Height}, End: &Point{X: movingRect.X + movingRect.Width + distance.X, Y: movingRect.Y + movingRect.Height}} return checkCollisionOnCardinalDirection(&collisionCheck) } func getMaxUpRightMovement(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Point { var collisionCheck collisionCheckForDiagonalDirection collisionCheck.firstBorder = stillRect.LeftBorder() collisionCheck.secondBorder = stillRect.BottomBorder() collisionCheck.firstVector = &Line{Start: &Point{X: movingRect.X, Y: movingRect.Y}, End: &Point{X: movingRect.X + distance.X, Y: movingRect.Y + distance.Y}} collisionCheck.secondVector = &Line{Start: &Point{X: movingRect.X + movingRect.Width, Y: movingRect.Y}, End: &Point{X: movingRect.X + movingRect.Width + distance.X, Y: movingRect.Y + distance.Y}} collisionCheck.thirdVector = &Line{Start: &Point{X: movingRect.X + movingRect.Width, Y: movingRect.Y + movingRect.Height}, End: &Point{X: movingRect.X + movingRect.Width + distance.X, Y: movingRect.Y + movingRect.Height + distance.Y}} return checkCollisionOnDiagonalDirection(&collisionCheck) } func getMaxDownRightMovement(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Point { var collisionCheck collisionCheckForDiagonalDirection collisionCheck.firstBorder = stillRect.LeftBorder() collisionCheck.secondBorder = stillRect.TopBorder() collisionCheck.firstVector = &Line{Start: &Point{X: movingRect.X, Y: movingRect.Y + movingRect.Height}, End: &Point{X: movingRect.X + distance.X, Y: movingRect.Y + movingRect.Height + distance.Y}} collisionCheck.secondVector = &Line{Start: &Point{X: movingRect.X + movingRect.Width, Y: movingRect.Y + movingRect.Height}, End: &Point{X: movingRect.X + movingRect.Width + distance.X, Y: movingRect.Y + movingRect.Height + distance.Y}} collisionCheck.thirdVector = &Line{Start: &Point{X: movingRect.X + movingRect.Width, Y: movingRect.Y}, End: &Point{X: movingRect.X + movingRect.Width + distance.X, Y: movingRect.Y + distance.Y}} return checkCollisionOnDiagonalDirection(&collisionCheck) } func getMaxUpLeftMovement(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Point { var collisionCheck collisionCheckForDiagonalDirection collisionCheck.firstBorder = stillRect.RightBorder() collisionCheck.secondBorder = stillRect.BottomBorder() collisionCheck.firstVector = &Line{Start: &Point{X: movingRect.X, Y: movingRect.Y}, End: &Point{X: movingRect.X + distance.X, Y: movingRect.Y + distance.Y}} collisionCheck.secondVector = &Line{Start: &Point{X: movingRect.X, Y: movingRect.Y + movingRect.Height}, End: &Point{X: movingRect.X + distance.X, Y: movingRect.Y + movingRect.Height + distance.Y}} collisionCheck.thirdVector = &Line{Start: &Point{X: movingRect.X + movingRect.Width, Y: movingRect.Y}, End: &Point{X: movingRect.X + movingRect.Width + distance.X, Y: movingRect.Y + distance.Y}} return checkCollisionOnDiagonalDirection(&collisionCheck) } func getMaxDownLeftMovement(movingRect *Rectangle, stillRect *Rectangle, distance *Point) *Point { var collisionCheck collisionCheckForDiagonalDirection collisionCheck.firstBorder = stillRect.RightBorder() collisionCheck.secondBorder = stillRect.TopBorder() collisionCheck.firstVector = &Line{Start: &Point{X: movingRect.X, Y: movingRect.Y}, End: &Point{X: movingRect.X + distance.X, Y: movingRect.Y + distance.Y}} collisionCheck.secondVector = &Line{Start: &Point{X: movingRect.X, Y: movingRect.Y + movingRect.Height}, End: &Point{X: movingRect.X + distance.X, Y: movingRect.Y + movingRect.Height + distance.Y}} collisionCheck.thirdVector = &Line{Start: &Point{X: movingRect.X + movingRect.Width, Y: movingRect.Y + movingRect.Height}, End: &Point{X: movingRect.X + movingRect.Width + distance.X, Y: movingRect.Y + movingRect.Height + distance.Y}} return checkCollisionOnDiagonalDirection(&collisionCheck) }
src/engine/geometry/collision-detection.go
0.836154
0.710515
collision-detection.go
starcoder
package unencrypted_communication import ( "github.com/damianmcgrath/threagile/model" ) func Category() model.RiskCategory { return model.RiskCategory{ Id: "unencrypted-communication", Title: "Unencrypted Communication", Description: "Due to the confidentiality and/or integrity rating of the data assets transferred over the " + "communication link this connection must be encrypted.", Impact: "If this risk is unmitigated, network attackers might be able to to eavesdrop on unencrypted sensitive data sent between components.", ASVS: "V9 - Communication Verification Requirements", CheatSheet: "https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html", Action: "Encryption of Communication Links", Mitigation: "Apply transport layer encryption to the communication link.", Check: "Are recommendations from the linked cheat sheet and referenced ASVS chapter applied?", Function: model.Operations, STRIDE: model.InformationDisclosure, DetectionLogic: "Unencrypted technical communication links of in-scope technical assets (excluding " + model.Monitoring.String() + " traffic as well as " + model.LocalFileAccess.String() + " and " + model.InProcessLibraryCall.String() + ") " + "transferring sensitive data.", // TODO more detailed text required here RiskAssessment: "Depending on the confidentiality rating of the transferred data-assets either medium or high risk.", FalsePositives: "When all sensitive data sent over the communication link is already fully encrypted on document or data level. " + "Also intra-container/pod communication can be considered false positive when container orchestration platform handles encryption.", ModelFailurePossibleReason: false, CWE: 319, } } func SupportedTags() []string { return []string{} } // check for communication links that should be encrypted due to their confidentiality and/or integrity func GenerateRisks() []model.Risk { risks := make([]model.Risk, 0) for _, technicalAsset := range model.ParsedModelRoot.TechnicalAssets { for _, dataFlow := range technicalAsset.CommunicationLinks { transferringAuthData := dataFlow.Authentication != model.NoneAuthentication sourceAsset := model.ParsedModelRoot.TechnicalAssets[dataFlow.SourceId] targetAsset := model.ParsedModelRoot.TechnicalAssets[dataFlow.TargetId] if !technicalAsset.OutOfScope || !sourceAsset.OutOfScope { if !dataFlow.Protocol.IsEncrypted() && !dataFlow.Protocol.IsProcessLocal() && !sourceAsset.Technology.IsUnprotectedCommsTolerated() && !targetAsset.Technology.IsUnprotectedCommsTolerated() { addedOne := false for _, sentDataAsset := range dataFlow.DataAssetsSent { dataAsset := model.ParsedModelRoot.DataAssets[sentDataAsset] if isHighSensitivity(dataAsset) || transferringAuthData { risks = append(risks, createRisk(technicalAsset, dataFlow, true, transferringAuthData)) addedOne = true break } else if !dataFlow.VPN && isMediumSensitivity(dataAsset) { risks = append(risks, createRisk(technicalAsset, dataFlow, false, transferringAuthData)) addedOne = true break } } if !addedOne { for _, receivedDataAsset := range dataFlow.DataAssetsReceived { dataAsset := model.ParsedModelRoot.DataAssets[receivedDataAsset] if isHighSensitivity(dataAsset) || transferringAuthData { risks = append(risks, createRisk(technicalAsset, dataFlow, true, transferringAuthData)) break } else if !dataFlow.VPN && isMediumSensitivity(dataAsset) { risks = append(risks, createRisk(technicalAsset, dataFlow, false, transferringAuthData)) break } } } } } } } return risks } func createRisk(technicalAsset model.TechnicalAsset, dataFlow model.CommunicationLink, highRisk bool, transferringAuthData bool) model.Risk { impact := model.MediumImpact if highRisk { impact = model.HighImpact } target := model.ParsedModelRoot.TechnicalAssets[dataFlow.TargetId] title := "<b>Unencrypted Communication</b> named <b>" + dataFlow.Title + "</b> between <b>" + technicalAsset.Title + "</b> and <b>" + target.Title + "</b>" if transferringAuthData { title += " transferring authentication data (like credentials, token, session-id, etc.)" } if dataFlow.VPN { title += " (even VPN-protected connections need to encrypt their data in-transit when confidentiality is " + "rated " + model.StrictlyConfidential.String() + " or integrity is rated " + model.MissionCritical.String() + ")" } likelihood := model.Unlikely if dataFlow.IsAcrossTrustBoundaryNetworkOnly() { likelihood = model.Likely } risk := model.Risk{ Category: Category(), Severity: model.CalculateSeverity(likelihood, impact), ExploitationLikelihood: likelihood, ExploitationImpact: impact, Title: title, MostRelevantTechnicalAssetId: technicalAsset.Id, MostRelevantCommunicationLinkId: dataFlow.Id, DataBreachProbability: model.Possible, DataBreachTechnicalAssetIDs: []string{target.Id}, } risk.SyntheticId = risk.Category.Id + "@" + dataFlow.Id + "@" + technicalAsset.Id + "@" + target.Id return risk } func isHighSensitivity(dataAsset model.DataAsset) bool { return dataAsset.Confidentiality == model.StrictlyConfidential || dataAsset.Integrity == model.MissionCritical } func isMediumSensitivity(dataAsset model.DataAsset) bool { return dataAsset.Confidentiality == model.Confidential || dataAsset.Integrity == model.Critical }
risks/built-in/unencrypted-communication/unencrypted-communication-rule.go
0.5
0.443781
unencrypted-communication-rule.go
starcoder
package dfl import ( "reflect" "strings" "github.com/pkg/errors" "github.com/spatialcurrent/go-adaptive-functions/pkg/af" ) // AssignAdd is a BinaryOperator which sets the added value of the left side and right side to the attribute or variable defined by the left side. type AssignAdd struct { *BinaryOperator } func (a AssignAdd) Dfl(quotes []string, pretty bool, tabs int) string { b := a.Builder("+=", quotes, tabs) if pretty { b = b.Indent(tabs).Pretty(pretty).Tabs(tabs + 1).TrimRight(pretty) switch a.Left.(type) { case *Attribute: switch a.Right.(type) { case *Function, *Pipe: return b.Dfl() } case *Variable: switch a.Right.(type) { case *Function, *Pipe: return b.Dfl() } } return a.BinaryOperator.Dfl("+=", quotes, pretty, tabs) } return b.Dfl() } func (a AssignAdd) Sql(pretty bool, tabs int) string { if pretty { switch left := a.Left.(type) { case *Variable: str := strings.Repeat(" ", tabs) + "WHERE " + a.Right.Sql(pretty, tabs) + "\n" str += strings.Repeat(" ", tabs) + "INTO TEMP TABLE " + left.Sql(pretty, tabs) + ";" return str } return "" } switch left := a.Left.(type) { case *Variable: return "WHERE " + a.Right.Sql(pretty, tabs) + " INTO TEMP TABLE " + left.Sql(pretty, tabs) + ";" // #nosec } return "" } func (a AssignAdd) Map() map[string]interface{} { return a.BinaryOperator.Map("assignadd", a.Left, a.Right) } // Compile returns a compiled version of this node. func (a AssignAdd) Compile() Node { left := a.Left.Compile() right := a.Right.Compile() return &AssignAdd{&BinaryOperator{Left: left, Right: right}} } func (a AssignAdd) Evaluate(vars map[string]interface{}, ctx interface{}, funcs FunctionMap, quotes []string) (map[string]interface{}, interface{}, error) { switch left := a.Left.(type) { case Attribute: vars, lv, rv, err := a.EvaluateLeftAndRight(vars, ctx, funcs, quotes) if err != nil { return vars, 0, err } value, err := af.Add.ValidateRun(lv, rv) if err != nil { return vars, 0, errors.Wrap(err, ErrorEvaluate{Node: a, Quotes: quotes}.Error()) } if len(left.Name) == 0 { return vars, value, nil } if t := reflect.TypeOf(ctx); t.Kind() != reflect.Map { ctx = map[string]interface{}{} } path := left.Name obj := ctx for len(path) > 0 { if !strings.Contains(path, ".") { reflect.ValueOf(obj).SetMapIndex(reflect.ValueOf(path), reflect.ValueOf(value)) break } pair := strings.SplitN(path, ".", 2) objectValue := reflect.ValueOf(obj) next := objectValue.MapIndex(reflect.ValueOf(pair[0])) if (reflect.TypeOf(next.Interface()).Kind() != reflect.Map) || (!objectValue.IsValid()) || objectValue.IsNil() { m := map[string]interface{}{} objectValue.SetMapIndex(reflect.ValueOf(pair[0]), reflect.ValueOf(m)) obj = m } else { obj = next.Interface() } path = pair[1] } return vars, ctx, nil case Variable: vars, lv, rv, err := a.EvaluateLeftAndRight(vars, ctx, funcs, quotes) if err != nil { return vars, 0, err } value, err := af.Add.ValidateRun(lv, rv) if err != nil { return vars, 0, errors.Wrap(err, ErrorEvaluate{Node: a, Quotes: quotes}.Error()) } path := left.Name var obj interface{} obj = vars for len(path) > 0 { if !strings.Contains(path, ".") { reflect.ValueOf(obj).SetMapIndex(reflect.ValueOf(path), reflect.ValueOf(value)) break } pair := strings.SplitN(path, ".", 2) objectValue := reflect.ValueOf(obj) next := objectValue.MapIndex(reflect.ValueOf(pair[0])) if (reflect.TypeOf(next.Interface()).Kind() != reflect.Map) || (!objectValue.IsValid()) || objectValue.IsNil() { m := map[string]interface{}{} objectValue.SetMapIndex(reflect.ValueOf(pair[0]), reflect.ValueOf(m)) obj = m } else { obj = next.Interface() } path = pair[1] } return vars, ctx, nil } return vars, ctx, &ErrorEvaluate{Node: a, Quotes: quotes} }
pkg/dfl/AssignAdd.go
0.705075
0.445107
AssignAdd.go
starcoder
package slice import "reflect" // IntersectGeneric returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectGeneric(left, right interface{}) interface{} { if left == nil || right == nil { return nil } return IntersectValue(reflect.ValueOf(left), reflect.ValueOf(right)).Interface() } // IntersectValue returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectValue(left, right reflect.Value) reflect.Value { var result = reflect.Zero(left.Type()) length := left.Len() if length == 0 || !right.IsValid() || right.Len() == 0 { return result } for i := 0; i < length; i++ { v := left.Index(i) if ContainsValue(right, v.Interface()) { result = reflect.Append(result, v) } } return result } // IntersectInterface returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectInterface(left, right []interface{}) []interface{} { var result []interface{} if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsInterface(right, v) { result = append(result, v) } } return result } // IntersectString returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectString(left, right []string) []string { var result []string if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsString(right, v) { result = append(result, v) } } return result } // IntersectBool returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectBool(left, right []bool) []bool { var result []bool if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsBool(right, v) { result = append(result, v) } } return result } // IntersectInt returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectInt(left, right []int) []int { var result []int if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsInt(right, v) { result = append(result, v) } } return result } // IntersectInt8 returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectInt8(left, right []int8) []int8 { var result []int8 if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsInt8(right, v) { result = append(result, v) } } return result } // IntersectInt16 returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectInt16(left, right []int16) []int16 { var result []int16 if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsInt16(right, v) { result = append(result, v) } } return result } // IntersectInt32 returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectInt32(left, right []int32) []int32 { var result []int32 if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsInt32(right, v) { result = append(result, v) } } return result } // IntersectInt64 returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectInt64(left, right []int64) []int64 { var result []int64 if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsInt64(right, v) { result = append(result, v) } } return result } // IntersectUint returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectUint(left, right []uint) []uint { var result []uint if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsUint(right, v) { result = append(result, v) } } return result } // IntersectUint8 returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectUint8(left, right []uint8) []uint8 { var result []uint8 if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsUint8(right, v) { result = append(result, v) } } return result } // IntersectUint16 returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectUint16(left, right []uint16) []uint16 { var result []uint16 if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsUint16(right, v) { result = append(result, v) } } return result } // IntersectUint32 returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectUint32(left, right []uint32) []uint32 { var result []uint32 if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsUint32(right, v) { result = append(result, v) } } return result } // IntersectUint64 returns intersection of left and right, in the left order. // The duplicate members in left are kept. func IntersectUint64(left, right []uint64) []uint64 { var result []uint64 if len(left) == 0 || len(right) == 0 { return result } for _, v := range left { if ContainsUint64(right, v) { result = append(result, v) } } return result }
intersect.go
0.846387
0.611411
intersect.go
starcoder
package scolumn import ( "bytes" "fmt" "math/rand" "reflect" "github.com/tobgu/qframe/config/rolling" "github.com/tobgu/qframe/internal/column" "github.com/tobgu/qframe/internal/hash" "github.com/tobgu/qframe/internal/index" qfstrings "github.com/tobgu/qframe/internal/strings" "github.com/tobgu/qframe/qerrors" "github.com/tobgu/qframe/types" ) var stringApplyFuncs = map[string]func(index.Int, Column) interface{}{ "ToUpper": toUpper, } // This is an example of how a more efficient built in function // could be implemented that makes use of the underlying representation // to make the operation faster than what could be done using the // generic function based API. // This function is roughly 3 - 4 times faster than applying the corresponding // general function (depending on the input size, etc. of course). func toUpper(ix index.Int, source Column) interface{} { if len(source.pointers) == 0 { return source } pointers := make([]qfstrings.Pointer, len(source.pointers)) sizeEstimate := int(float64(len(source.data)) * (float64(len(ix)) / float64(len(source.pointers)))) data := make([]byte, 0, sizeEstimate) strBuf := make([]byte, 1024) for _, i := range ix { str, isNull := source.stringAt(i) pointers[i] = qfstrings.NewPointer(len(data), len(str), isNull) data = append(data, qfstrings.ToUpper(&strBuf, str)...) } return NewBytes(pointers, data) } func (c Column) StringAt(i uint32, naRep string) string { if s, isNull := c.stringAt(i); !isNull { return s } return naRep } func (c Column) Get(i uint32) interface{} { s, _ := c.stringAt(i) return s } func (c Column) Set(i uint32, val interface{}) { fmt.Println(val) p := c.pointers[i] inval := []byte(val.(string)) if p.Len() >= len(inval) { c.pointers[i] = qfstrings.NewPointer(p.Offset(), len(inval), false) for j := p.Offset(); j < p.Offset()+len(inval); j++ { c.data[j] = inval[j-p.Offset()] } } else { d := make([]byte, 0, len(c.data)+len(inval)) dif := len(inval) - p.Len() d = append(d, c.data[:p.Offset()]...) d = append(d, inval...) c.pointers[i] = qfstrings.NewPointer(p.Offset(), len(inval), false) d = append(d, c.data[p.Offset()+p.Len():]...) c.data = d for j := int(i + 1); j < len(c.pointers); j++ { p = c.pointers[j] c.pointers[j] = qfstrings.NewPointer(p.Offset()+dif, p.Len(), false) } } // c.data[i] = val.(byte) } func (c Column) stringSlice(index index.Int) []*string { result := make([]*string, len(index)) for i, ix := range index { s, isNull := c.stringAt(ix) if isNull { result[i] = nil } else { result[i] = &s } } return result } func (c Column) AppendByteStringAt(buf []byte, i uint32) []byte { p := c.pointers[i] if p.IsNull() { return append(buf, "null"...) } str := qfstrings.UnsafeBytesToString(c.data[p.Offset() : p.Offset()+p.Len()]) return qfstrings.AppendQuotedString(buf, str) } func (c Column) ByteSize() int { return 8*cap(c.pointers) + cap(c.data) } func (c Column) Len() int { return len(c.pointers) } func (c Column) Equals(index index.Int, other column.Column, otherIndex index.Int) bool { otherC, ok := other.(Column) if !ok { return false } for ix, x := range index { s, sNull := c.stringAt(x) os, osNull := otherC.stringAt(otherIndex[ix]) if sNull || osNull { if sNull && osNull { continue } return false } if s != os { return false } } return true } func (c Comparable) Compare(i, j uint32) column.CompareResult { x, xNull := c.column.bytesAt(i) y, yNull := c.column.bytesAt(j) if xNull || yNull { if !xNull { return c.nullGtValue } if !yNull { return c.nullLtValue } return c.equalNullValue } r := bytes.Compare(x, y) switch r { case -1: return c.ltValue case 1: return c.gtValue default: return column.Equal } } func (c Comparable) Hash(i uint32, seed uint64) uint64 { x, isNull := c.column.bytesAt(i) if isNull { if c.equalNullValue == column.NotEqual { // Use a random value here to avoid hash collisions when // we don't consider null to equal null. // Use a random value here to avoid hash collisions when // we don't consider null to equal null. return rand.Uint64() } b := [1]byte{0} return hash.HashBytes(b[:], seed) } return hash.HashBytes(x, seed) } func (c Column) filterBuiltIn(index index.Int, comparator string, comparatee interface{}, bIndex index.Bool) error { comparatee = qfstrings.InterfaceSliceToStringSlice(comparatee) switch t := comparatee.(type) { case string: filterFn, ok := filterFuncs1[comparator] if !ok { return qerrors.New("filter string", "unknown filter operator %v for single value argument", comparator) } return filterFn(index, c, t, bIndex) case []string: filterFn, ok := multiInputFilterFuncs[comparator] if !ok { return qerrors.New("filter string", "unknown filter operator %v for multi value argument", comparator) } return filterFn(index, c, qfstrings.NewStringSet(t), bIndex) case Column: filterFn, ok := filterFuncs2[comparator] if !ok { return qerrors.New("filter string", "unknown filter operator %v for column - column comparison", comparator) } return filterFn(index, c, t, bIndex) case nil: filterFn, ok := filterFuncs0[comparator] if !ok { return qerrors.New("filter string", "unknown filter operator %v for zero argument", comparator) } return filterFn(index, c, bIndex) default: return qerrors.New("filter string", "invalid comparison value type %v", reflect.TypeOf(comparatee)) } } func (c Column) filterCustom1(index index.Int, fn func(*string) bool, bIndex index.Bool) { for i, x := range bIndex { if !x { bIndex[i] = fn(stringToPtr(c.stringAt(index[i]))) } } } func (c Column) filterCustom2(index index.Int, fn func(*string, *string) bool, comparatee interface{}, bIndex index.Bool) error { otherC, ok := comparatee.(Column) if !ok { return qerrors.New("filter string", "expected comparatee to be string column, was %v", reflect.TypeOf(comparatee)) } for i, x := range bIndex { if !x { bIndex[i] = fn(stringToPtr(c.stringAt(index[i])), stringToPtr(otherC.stringAt(index[i]))) } } return nil } func (c Column) Filter(index index.Int, comparator interface{}, comparatee interface{}, bIndex index.Bool) error { var err error switch t := comparator.(type) { case string: err = c.filterBuiltIn(index, t, comparatee, bIndex) case func(*string) bool: c.filterCustom1(index, t, bIndex) case func(*string, *string) bool: err = c.filterCustom2(index, t, comparatee, bIndex) default: err = qerrors.New("filter string", "invalid filter type %v", reflect.TypeOf(comparator)) } return err } type Column struct { pointers []qfstrings.Pointer data []byte } func NewBytes(pointers []qfstrings.Pointer, bytes []byte) Column { return Column{pointers: pointers, data: bytes} } func NewStrings(strings []string) Column { data := make([]byte, 0, len(strings)) pointers := make([]qfstrings.Pointer, len(strings)) offset := 0 for i, s := range strings { pointers[i] = qfstrings.NewPointer(offset, len(s), false) offset += len(s) data = append(data, s...) } return NewBytes(pointers, data) } func New(strings []*string) Column { data := make([]byte, 0, len(strings)) pointers := make([]qfstrings.Pointer, len(strings)) offset := 0 for i, s := range strings { if s == nil { pointers[i] = qfstrings.NewPointer(offset, 0, true) } else { sLen := len(*s) pointers[i] = qfstrings.NewPointer(offset, sLen, false) offset += sLen data = append(data, *s...) } } return NewBytes(pointers, data) } func NewConst(val *string, count int) Column { var data []byte pointers := make([]qfstrings.Pointer, count) if val == nil { data = make([]byte, 0) for i := range pointers { pointers[i] = qfstrings.NewPointer(0, 0, true) } } else { sLen := len(*val) data = make([]byte, 0, sLen) data = append(data, *val...) for i := range pointers { pointers[i] = qfstrings.NewPointer(0, sLen, false) } } return NewBytes(pointers, data) } func (c Column) stringAt(i uint32) (string, bool) { p := c.pointers[i] if p.IsNull() { return "", true } return qfstrings.UnsafeBytesToString(c.data[p.Offset() : p.Offset()+p.Len()]), false } func (c Column) bytesAt(i uint32) ([]byte, bool) { p := c.pointers[i] if p.IsNull() { return nil, true } return c.data[p.Offset() : p.Offset()+p.Len()], false } func (c Column) stringCopyAt(i uint32) (string, bool) { // Similar to stringAt but will allocate a new string and copy the content into it. p := c.pointers[i] if p.IsNull() { return "", true } return string(c.data[p.Offset() : p.Offset()+p.Len()]), false } func (c Column) subset(index index.Int) Column { data := make([]byte, 0, len(index)) pointers := make([]qfstrings.Pointer, len(index)) offset := 0 for i, ix := range index { p := c.pointers[ix] pointers[i] = qfstrings.NewPointer(offset, p.Len(), p.IsNull()) if !p.IsNull() { data = append(data, c.data[p.Offset():p.Offset()+p.Len()]...) offset += p.Len() } } return Column{data: data, pointers: pointers} } func (c Column) Subset(index index.Int) column.Column { return c.subset(index) } func (c Column) Comparable(reverse, equalNull, nullLast bool) column.Comparable { result := Comparable{column: c, ltValue: column.LessThan, gtValue: column.GreaterThan, nullLtValue: column.LessThan, nullGtValue: column.GreaterThan, equalNullValue: column.NotEqual} if reverse { result.ltValue, result.nullLtValue, result.gtValue, result.nullGtValue = result.gtValue, result.nullGtValue, result.ltValue, result.nullLtValue } if nullLast { result.nullLtValue, result.nullGtValue = result.nullGtValue, result.nullLtValue } if equalNull { result.equalNullValue = column.Equal } return result } func (c Column) String() string { return fmt.Sprintf("%v", c.data) } func (c Column) Aggregate(indices []index.Int, fn interface{}) (column.Column, error) { switch t := fn.(type) { case string: // There are currently no built in aggregations for strings return nil, qerrors.New("string aggregate", "aggregation function %c is not defined for string column", fn) case func([]*string) *string: data := make([]*string, 0, len(indices)) for _, ix := range indices { data = append(data, t(c.stringSlice(ix))) } return New(data), nil default: return nil, qerrors.New("string aggregate", "invalid aggregation function type: %v", t) } } func stringToPtr(s string, isNull bool) *string { if isNull { return nil } return &s } func (c Column) Apply1(fn interface{}, ix index.Int) (interface{}, error) { switch t := fn.(type) { case func(*string) int: result := make([]int, len(c.pointers)) for _, i := range ix { result[i] = t(stringToPtr(c.stringAt(i))) } return result, nil case func(*string) float64: result := make([]float64, len(c.pointers)) for _, i := range ix { result[i] = t(stringToPtr(c.stringAt(i))) } return result, nil case func(*string) bool: result := make([]bool, len(c.pointers)) for _, i := range ix { result[i] = t(stringToPtr(c.stringAt(i))) } return result, nil case func(*string) *string: result := make([]*string, len(c.pointers)) for _, i := range ix { result[i] = t(stringToPtr(c.stringAt(i))) } return result, nil case string: if f, ok := stringApplyFuncs[t]; ok { return f(ix, c), nil } return nil, qerrors.New("string.apply1", "unknown built in function %v", t) default: return nil, qerrors.New("string.apply1", "cannot apply type %#v to column", fn) } } func (c Column) Apply2(fn interface{}, s2 column.Column, ix index.Int) (column.Column, error) { s2S, ok := s2.(Column) if !ok { return nil, qerrors.New("string.apply2", "invalid column type %v", reflect.TypeOf(s2)) } switch t := fn.(type) { case func(*string, *string) *string: result := make([]*string, len(c.pointers)) for _, i := range ix { result[i] = t(stringToPtr(c.stringAt(i)), stringToPtr(s2S.stringAt(i))) } return New(result), nil case string: // No built in functions for strings at this stage return nil, qerrors.New("string.apply2", "unknown built in function %s", t) default: return nil, qerrors.New("string.apply2", "cannot apply type %#v to column", fn) } } func (c Column) View(ix index.Int) View { return View{column: c, index: ix} } func (c Column) Rolling(fn interface{}, ix index.Int, config rolling.Config) (column.Column, error) { return c, nil } func (c Column) FunctionType() types.FunctionType { return types.FunctionTypeString } func (c Column) DataType() types.DataType { return types.String } type Comparable struct { column Column ltValue column.CompareResult gtValue column.CompareResult nullLtValue column.CompareResult nullGtValue column.CompareResult equalNullValue column.CompareResult }
internal/scolumn/column.go
0.658637
0.449091
column.go
starcoder
package rdf import ( "encoding/json" "fmt" ) // LiteralType is the TermType literals const LiteralType = "Literal" var literalTermType = termType{LiteralType} // A Literal is literal term type Literal struct { value string language string datatype *NamedNode } // NewLiteral creates a new literal func NewLiteral(value string, language string, datatype *NamedNode) *Literal { return &Literal{value, language, datatype} } func (node *Literal) String() string { if node.datatype == nil || node.datatype.value == XSDString.value { return fmt.Sprintf("\"%s\"", escape(node.value)) } else if node.language != "" && node.datatype.value == RDFLangString.value { return fmt.Sprintf("\"%s\"@%s", escape(node.value), node.language) } return fmt.Sprintf("\"%s\"^^<%s>", escape(node.value), node.datatype.value) } // TermType of a literal is "Literal" func (node *Literal) TermType() string { return LiteralType } // Value of a literal is its string value, without the datatype and langauge func (node *Literal) Value() string { return node.value } // Language of a literal is the literal's language tag func (node *Literal) Language() string { return node.language } // Datatype of a literal returns the literal's datatype func (node *Literal) Datatype() Term { if node.datatype != nil { return node.datatype } return XSDString } // Equal checks for functional equivalence of terms func (node *Literal) Equal(term Term) bool { if term.TermType() != LiteralType || term.Value() != node.value { return false } switch term := term.(type) { case *Literal: return term.language == node.language && ((term.datatype == nil && node.datatype == nil) || term.datatype.value == node.datatype.value) case TermLiteral: return term.Language() == node.language && term.Datatype().Equal(node.Datatype()) default: return false } } // MarshalJSON marshals the literal into a byte slice func (node *Literal) MarshalJSON() ([]byte, error) { result := &term{value{literalTermType, node.value}, node.language, nil} if node.datatype != nil { result.Datatype = &value{namedNodeTermType, node.datatype.value} } return json.Marshal(result) } // UnmarshalJSON umarshals a byte slice into the literal func (node *Literal) UnmarshalJSON(data []byte) error { t := &term{} err := json.Unmarshal(data, t) if err != nil { return err } else if t.TermType != LiteralType { return ErrTermType } node.value = t.Value if t.Datatype != nil { if t.Datatype.TermType != NamedNodeType { return ErrTermType } node.datatype = &NamedNode{t.Datatype.Value} if t.Datatype.Value == RDFLangString.value { node.language = t.Language } } return nil }
literal.go
0.658088
0.404949
literal.go
starcoder
package rbtree // This file contains all RB tree iteration methods implementations type enumerable struct{ it Iterator } type iterator struct { enumerable tree RbTree curr *Node } type walk struct { iterator stack []*Node } type walkPreorder struct{ walk } type walkInorder struct { walk p *Node } type walkPostorder struct { walk p *Node } type ascend struct{ ordered } type descend struct{ ordered } type ordered struct { iterator next *Node to Comparable } // NewWalkInorder creates Enumerable that walks tree inorder (left, node, right) func NewWalkInorder(t RbTree) Enumerable { e := &walkInorder{ walk: newWalk(t), } if len(e.stack) > 0 { e.p = e.stack[0] } e.it = e return e } // NewWalkPreorder creates Enumerable that walks tree preorder (node, left, right) func NewWalkPreorder(t RbTree) Enumerable { e := &walkPreorder{ walk: newWalk(t), } e.it = e return e } // NewWalkPostorder creates Enumerable that walks tree postorder (left, right, node) func NewWalkPostorder(t RbTree) Enumerable { e := &walkPostorder{ walk: newWalk(t), } if len(e.stack) > 0 { e.p = e.stack[0] } e.it = e return e } // NewAscend creates Enumerable that walks tree in ascending order func NewAscend(t RbTree) Enumerable { return NewWalkInorder(t) } // NewAscendRange creates Enumerable that walks tree in ascending order within the range [from, to] func NewAscendRange(t RbTree, from, to Comparable) Enumerable { ordered := newOrdered(t) e := &ascend{ordered: ordered} e.it = e n, ok := e.tree.SearchNode(from) if ok && to != nil { e.next = n e.to = to } return e } // NewOpenAscendRange creates Enumerable that walks tree in ascending order within the range (from, to]) // open means that both ends not necessary present in the tree. If not // the nearest tree nodes will be found and iteration starts and stops using them func NewOpenAscendRange(t RbTree, from, to Comparable) Enumerable { ordered := newOrdered(t) e := &ascend{ordered: ordered} e.it = e n, ok := e.tree.SearchNode(from) if ok && to != nil { e.next = n e.to = to } else if from != nil && to != nil { fn, ok := e.tree.Ceiling(from) if ok { e.next, _ = e.tree.SearchNode(fn) e.to = to } } return e } // NewDescend creates Enumerable that walks tree in descending order func NewDescend(t RbTree) Enumerable { e := newDescend(t) max := e.tree.Maximum() if max != nil { e.next = max e.to = t.Minimum().key } return e } // NewDescendRange that walks tree in descending order within the range [from, to] func NewDescendRange(t RbTree, from, to Comparable) Enumerable { e := newDescend(t) n, ok := e.tree.SearchNode(from) if ok && to != nil { e.next = n e.to = to } return e } // NewOpenDescendRange that walks tree in descending order within the range (from, to) // open means that both ends not necessary present in the tree. If not // the nearest tree nodes will be found and iteration starts and stops using them func NewOpenDescendRange(t RbTree, from, to Comparable) Enumerable { e := newDescend(t) n, ok := e.tree.SearchNode(from) if ok && to != nil { e.next = n e.to = to } else if from != nil && to != nil { fn, ok := e.tree.Floor(from) if ok { e.next, _ = e.tree.SearchNode(fn) e.to = to } } return e } func (i *walkInorder) Next() bool { for len(i.stack) > 0 { if i.p.isNotNil() { i.p = i.p.left if i.p.isNotNil() { i.stack = append(i.stack, i.p) } } else { top := len(i.stack) - 1 i.p = i.stack[top] i.curr = i.p i.stack = i.stack[:top] i.p = i.p.right if i.p.isNotNil() { i.stack = append(i.stack, i.p) } return true } } return false } func (i *walkPreorder) Next() bool { if len(i.stack) > 0 { top := len(i.stack) - 1 p := i.stack[top] i.curr = p i.stack = i.stack[:top] if p.right.isNotNil() { i.stack = append(i.stack, p.right) } if p.left.isNotNil() { i.stack = append(i.stack, p.left) } return true } return false } func (i *walkPostorder) Next() bool { for len(i.stack) > 0 { top := len(i.stack) - 1 next := i.stack[top] if next.right == i.p || next.left == i.p || (next.right.isNil() && next.left.isNil()) { i.stack = i.stack[:top] i.curr = next i.p = next return true } if next.right.isNotNil() { i.stack = append(i.stack, next.right) } if next.left.isNotNil() { i.stack = append(i.stack, next.left) } } return false } func (i *ascend) Next() bool { result := i.next.isNotNil() && (i.next.key.Less(i.to) || i.next.key.Equal(i.to)) if result { i.curr = i.next i.next = i.curr.Successor() } return result } func (i *descend) Next() bool { result := i.next.isNotNil() && !i.next.key.Less(i.to) if result { i.curr = i.next i.next = i.curr.Predecessor() } return result } // Foreach does tree iteration and calls the callback for // every value in the tree until callback returns false. func (e *enumerable) Foreach(callback NodeAction) { for e.it.Next() { callback(e.it.Current()) } } func (e *enumerable) Iterator() Iterator { return e.it } func (i *iterator) Current() Comparable { return i.curr.key } func (i *iterator) current() *Node { return i.curr } func newWalk(t RbTree) walk { it := iterator{tree: t} w := walk{ iterator: it, stack: make([]*Node, 0), } if t.Len() > 0 { w.stack = append(w.stack, t.Root()) } return w } func newDescend(t RbTree) *descend { ordered := newOrdered(t) e := &descend{ordered: ordered} e.it = e return e } func newOrdered(t RbTree) ordered { it := iterator{tree: t} return ordered{iterator: it} }
rbtree/iterate.go
0.80479
0.526343
iterate.go
starcoder
package schema // GitLabSchemaJSON is the content of the file "gitlab.schema.json". const GitLabSchemaJSON = `{ "$schema": "http://json-schema.org/draft-07/schema#", "$id": "gitlab.schema.json#", "title": "GitLabConnection", "description": "Configuration for a connection to GitLab (GitLab.com or GitLab self-managed).", "allowComments": true, "type": "object", "additionalProperties": false, "required": ["url", "token", "projectQuery"], "properties": { "url": { "description": "URL of a GitLab instance, such as https://gitlab.example.com or (for GitLab.com) https://gitlab.com.", "type": "string", "pattern": "^https?://", "not": { "type": "string", "pattern": "example\\.com" }, "format": "uri", "examples": ["https://gitlab.com", "https://gitlab.example.com"] }, "token": { "description": "A GitLab access token with \"api\" scope. If you are enabling permissions with identity provider type \"external\", this token should also have \"sudo\" scope.", "type": "string", "minLength": 1 }, "gitURLType": { "description": "The type of Git URLs to use for cloning and fetching Git repositories on this GitLab instance.\n\nIf \"http\", Sourcegraph will access GitLab repositories using Git URLs of the form http(s)://gitlab.example.com/myteam/myproject.git (using https: if the GitLab instance uses HTTPS).\n\nIf \"ssh\", Sourcegraph will access GitLab repositories using Git URLs of the form git@example.gitlab.com:myteam/myproject.git. See the documentation for how to provide SSH private keys and known_hosts: https://docs.sourcegraph.com/admin/repo/auth#repositories-that-need-http-s-or-ssh-authentication.", "type": "string", "enum": ["http", "ssh"], "default": "http" }, "certificate": { "description": "TLS certificate of the GitLab instance. This is only necessary if the certificate is self-signed or signed by an internal CA. To get the certificate run ` + "`" + `openssl s_client -connect HOST:443 -showcerts < /dev/null 2> /dev/null | openssl x509 -outform PEM` + "`" + `. To escape the value into a JSON string, you may want to use a tool like https://json-escape-text.now.sh.", "type": "string", "pattern": "^-----BEGIN CERTIFICATE-----\n", "examples": ["-----BEGIN CERTIFICATE-----\n..."] }, "projects": { "description": "A list of projects to mirror from this GitLab instance. Supports including by name ({\"name\": \"group/name\"}) or by ID ({\"id\": 42}).", "type": "array", "minItems": 1, "items": { "type": "object", "title": "GitLabProject", "additionalProperties": false, "anyOf": [{ "required": ["name"] }, { "required": ["id"] }], "properties": { "name": { "description": "The name of a GitLab project (\"group/name\") to mirror.", "type": "string", "pattern": "^[\\w-]+(/[\\w.-]+)+$" }, "id": { "description": "The ID of a GitLab project (as returned by the GitLab instance's API) to mirror.", "type": "integer" } } }, "examples": [ [{ "name": "group/name" }, { "id": 42 }], [{ "name": "gnachman/iterm2" }, { "name": "gitlab-org/gitlab-ce" }] ] }, "exclude": { "description": "A list of projects to never mirror from this GitLab instance. Takes precedence over \"projects\" and \"projectQuery\" configuration. Supports excluding by name ({\"name\": \"group/name\"}) or by ID ({\"id\": 42}).", "type": "array", "items": { "type": "object", "title": "ExcludedGitLabProject", "additionalProperties": false, "anyOf": [{ "required": ["name"] }, { "required": ["id"] }], "properties": { "name": { "description": "The name of a GitLab project (\"group/name\") to exclude from mirroring.", "type": "string", "pattern": "^[\\w-]+/[\\w.-]+$" }, "id": { "description": "The ID of a GitLab project (as returned by the GitLab instance's API) to exclude from mirroring.", "type": "integer" } } }, "examples": [ [{ "name": "group/name" }, { "id": 42 }], [{ "name": "gitlab-org/gitlab-ee" }, { "name": "gitlab-com/www-gitlab-com" }] ] }, "projectQuery": { "description": "An array of strings specifying which GitLab projects to mirror on Sourcegraph. Each string is a URL path and query that targets a GitLab API endpoint returning a list of projects. If the string only contains a query, then \"projects\" is used as the path. Examples: \"?membership=true&search=foo\", \"groups/mygroup/projects\".\n\nThe special string \"none\" can be used as the only element to disable this feature. Projects matched by multiple query strings are only imported once. Here are a few endpoints that return a list of projects: https://docs.gitlab.com/ee/api/projects.html#list-all-projects, https://docs.gitlab.com/ee/api/groups.html#list-a-groups-projects, https://docs.gitlab.com/ee/api/search.html#scope-projects.", "type": "array", "default": ["none"], "items": { "type": "string", "minLength": 1 }, "minItems": 1, "examples": [["?membership=true&search=foo", "groups/mygroup/projects"]] }, "repositoryPathPattern": { "description": "The pattern used to generate a the corresponding Sourcegraph repository name for a GitLab project. In the pattern, the variable \"{host}\" is replaced with the GitLab URL's host (such as gitlab.example.com), and \"{pathWithNamespace}\" is replaced with the GitLab project's \"namespace/path\" (such as \"myteam/myproject\").\n\nFor example, if your GitLab is https://gitlab.example.com and your Sourcegraph is https://src.example.com, then a repositoryPathPattern of \"{host}/{pathWithNamespace}\" would mean that a GitLab project at https://gitlab.example.com/myteam/myproject is available on Sourcegraph at https://src.example.com/gitlab.example.com/myteam/myproject.\n\nIt is important that the Sourcegraph repository name generated with this pattern be unique to this code host. If different code hosts generate repository names that collide, Sourcegraph's behavior is undefined.", "type": "string", "default": "{host}/{pathWithNamespace}" }, "nameTransformations": { "description": "An array of transformations will apply to the repository name. Currently, only regex replacement is supported. All transformations happen after \"repositoryPathPattern\" is processed.", "type": "array", "items": { "$ref": "#/definitions/NameTransformation" }, "examples": [ [ { "regex": "\\.d/", "replacement": "/" }, { "regex": "-git$", "replacement": "" } ] ] }, "initialRepositoryEnablement": { "description": "Defines whether repositories from this GitLab instance should be enabled and cloned when they are first seen by Sourcegraph. If false, the site admin must explicitly enable GitLab repositories (in the site admin area) to clone them and make them searchable on Sourcegraph. If true, they will be enabled and cloned immediately (subject to rate limiting by GitLab); site admins can still disable them explicitly, and they'll remain disabled.", "type": "boolean" }, "authorization": { "title": "GitLabAuthorization", "description": "If non-null, enforces GitLab repository permissions. This requires that there be an item in the ` + "`" + `auth.providers` + "`" + ` field of type \"gitlab\" with the same ` + "`" + `url` + "`" + ` field as specified in this ` + "`" + `GitLabConnection` + "`" + `.", "type": "object", "additionalProperties": false, "required": ["identityProvider"], "properties": { "identityProvider": { "description": "The source of identity to use when computing permissions. This defines how to compute the GitLab identity to use for a given Sourcegraph user.", "type": "object", "required": ["type"], "properties": { "type": { "type": "string", "enum": ["oauth", "username", "external"] } }, "oneOf": [ { "$ref": "#/definitions/OAuthIdentity" }, { "$ref": "#/definitions/UsernameIdentity" }, { "$ref": "#/definitions/ExternalIdentity" } ], "!go": { "taggedUnionType": true } }, "ttl": { "description": "The TTL of how long to cache permissions data. This is 3 hours by default.\n\nDecreasing the TTL will increase the load on the code host API. If you have X private repositories on your instance, it will take ~X/100 API requests to fetch the complete list for 1 user. If you have Y users, you will incur up to X*Y/100 API requests per cache refresh period (depending on user activity).\n\nIf set to zero, Sourcegraph will sync a user's entire accessible repository list on every request (NOT recommended).\n\nPublic and internal repositories are cached once for all users per cache TTL period.", "type": "string", "default": "3h" } } } }, "definitions": { "OAuthIdentity": { "type": "object", "additionalProperties": false, "required": ["type"], "properties": { "type": { "type": "string", "const": "oauth" }, "minBatchingThreshold": { "description": "The minimum number of GitLab projects to fetch at which to start batching requests to fetch project visibility. Please consult with the Sourcegraph support team before modifying this.", "type": "integer", "default": 200 }, "maxBatchRequests": { "description": "The maximum number of batch API requests to make for GitLab Project visibility. Please consult with the Sourcegraph support team before modifying this.", "type": "integer", "default": 300 } } }, "UsernameIdentity": { "type": "object", "additionalProperties": false, "required": ["type"], "properties": { "type": { "type": "string", "const": "username" } } }, "ExternalIdentity": { "type": "object", "additionalProperties": false, "required": ["type", "authProviderID", "authProviderType", "gitlabProvider"], "properties": { "type": { "type": "string", "const": "external" }, "authProviderID": { "type": "string", "description": "The value of the ` + "`" + `configID` + "`" + ` field of the targeted authentication provider." }, "authProviderType": { "type": "string", "description": "The ` + "`" + `type` + "`" + ` field of the targeted authentication provider." }, "gitlabProvider": { "type": "string", "description": "The name that identifies the authentication provider to GitLab. This is passed to the ` + "`" + `?provider=` + "`" + ` query parameter in calls to the GitLab Users API. If you're not sure what this value is, you can look at the ` + "`" + `identities` + "`" + ` field of the GitLab Users API result (` + "`" + `curl -H 'PRIVATE-TOKEN: $YOUR_TOKEN' $GITLAB_URL/api/v4/users` + "`" + `)." } } }, "NameTransformation": { "title": "GitLabNameTransformation", "type": "object", "additionalProperties": false, "anyOf": [{ "required": ["regex", "replacement"] }], "properties": { "regex": { "type": "string", "format": "regex", "description": "The regex to match for the occurrences of its replacement." }, "replacement": { "type": "string", "description": "The replacement used to replace all matched occurrences by the regex." } } } } } `
schema/gitlab_stringdata.go
0.816406
0.443841
gitlab_stringdata.go
starcoder
package main import ( "math/rand" "sort" ) // MAXSECS is the maximum number of seconds in a year. const MAXSECS = 365 * 24 * 3600 // Interval represents an availability interval. type Interval struct { beg, end uint32 cnt uint32 ratio float32 } // Overlap checks the overlap between two intervals. func (i Interval) Overlap(o Interval) bool { return i.end > o.beg && i.beg < o.end } // Contiguous checks the intervals are Contiguous. func (i Interval) Contiguous(o Interval) bool { return i.end == o.beg || i.beg == o.end } // Include returns true if the interval include t. func (i Interval) Include(t uint32) bool { return t >= i.beg && t <= i.end } // Normalize ensures the interval is within the range. func (i *Interval) Normalize() { if i.end > MAXSECS { i.end = MAXSECS } } // Intervals is a slice of intervals. type Intervals []Interval // Reset cleans so the object can be reused. func (s *Intervals) Reset() { *s = (*s)[:0] } // AddFailure adds a failure event avoiding collisions. // Return false if an overlap check fails. func (s *Intervals) AddFailure(t uint32, mttr uint32, check bool) bool { x := Interval{t, t + mttr, 0, 0.0} x.Normalize() if check && s.CheckCollision(x) { return false } *s = append(*s, x) return true } // CheckCollision returns true if an existing interval overlaps. func (s Intervals) CheckCollision(x Interval) bool { for i := range s { if s[i].Overlap(x) { return true } } return false } // CheckCollisionTime returns true if t matches an existing interval. func (s Intervals) CheckCollisionTime(t uint32) bool { for i := range s { if s[i].Include(t) { return true } } return false } // AddFailures adds multiple failures avoiding collisions. func (s *Intervals) AddFailures(n int, r *rand.Rand, mttr uint32) { for n > 0 { t := uint32(r.Int31n(MAXSECS)) if !s.AddFailure(t, mttr, true) { continue } n-- } } // FindNonFailureTime returns a timestamp which does not match an existing interval. func (s Intervals) FindNonFailureTime(r *rand.Rand) uint32 { for { t := uint32(r.Int31n(MAXSECS)) if !s.CheckCollisionTime(t) { return t } } } // Normalize puts the list of intervals in canonical form func (sp *Intervals) Normalize(sorted bool) { // Sort intervals s := *sp if len(s) == 0 { return } if !sorted { sort.Sort(s) } // Merge contiguous or overlapping intervals for i := 1; i < len(s); { if s[i].Overlap(s[i-1]) { if s[i-1].end < s[i].end { s[i-1].end = s[i].end } s = append(s[:i], s[i+1:]...) continue } if s[i].Contiguous(s[i-1]) { s[i-1].end = s[i].end s = append(s[:i], s[i+1:]...) continue } i++ } *sp = s } // Equal returns true if the two objects are identical func (s Intervals) Equal(other Intervals) bool { if len(s) != len(other) { return false } for i := 0; i < len(s); i++ { if s[i] != other[i] { return false } } return true } // MergeNodes merges two interval slices associated to two nodes of the same zone func (s *Intervals) MergeNodes(a, b Intervals) { s.merge(a, b, func(x, y Interval) Interval { return Interval{x.beg, x.end, x.cnt, x.ratio + y.ratio} }) } // MergeNodes merges two interval slices associated to two zones of the same cluster func (s *Intervals) MergeZones(a, b Intervals) { s.merge(a, b, func(x, y Interval) Interval { return Interval{x.beg, x.end, x.cnt + y.cnt, x.ratio * y.ratio} }) } // merge applies the generic merge algorithm of two interval slices. // The two slices must be sorted. func (s *Intervals) merge(a, b Intervals, gen func(x, y Interval) Interval) { s.Reset() i, j := 0, 0 var x Interval for i < len(a) && j < len(b) { ab, ae, bb, be := a[i].beg, a[i].end, b[j].beg, b[j].end switch { case ae <= bb: *s = append(*s, a[i]) i++ case be <= ab: *s = append(*s, b[j]) j++ case ab == bb: switch { case ae == be: *s = append(*s, gen(a[i], b[j])) i++ j++ case ae < be: *s = append(*s, gen(a[i], b[j])) b[j].beg = ae i++ default: *s = append(*s, gen(b[j], a[i])) a[i].beg = be j++ } case ab < bb: x = a[i] x.end, a[i].beg = bb, bb *s = append(*s, x) default: x = b[j] x.end, b[j].beg = ab, ab *s = append(*s, x) } } switch { case i < len(a): *s = append(*s, a[i:]...) case j < len(b): *s = append(*s, b[j:]...) } } // Implements sort interface. func (s Intervals) Len() int { return len(s) } func (s Intervals) Less(i, j int) bool { return s[i].beg < s[j].beg } func (s Intervals) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
simufail/interval.go
0.730482
0.5144
interval.go
starcoder
package semantic import "github.com/google/gapid/gapil/ast" // Function represents function like objects in the semantic graph. type Function struct { owned AST *ast.Function // the underlying syntax node this was built from Annotations // the annotations applied to the function Named // the name of the function Docs Documentation // the documentation for the function Return *Parameter // the return parameter This *Parameter // the this parameter, missing for non method functions FullParameters []*Parameter // all the parameters, including This at the start if valid, and Return at the end if not void Block *Block // the body of the function, missing for externs Signature *Signature // the type signature of the function Extern bool // true if this was declared as an extern Subroutine bool // true if this was declared as a subroutine Order LogicalOrder // the logical order of the statements relative to the fence } func (*Function) isNode() {} // CallParameters returns the full set of parameters with the return value // filtered out. func (f *Function) CallParameters() []*Parameter { if f.Return.Type == VoidType { return f.FullParameters } return f.FullParameters[0 : len(f.FullParameters)-1] } // Parameter represents a single parameter declaration for a function. type Parameter struct { AST *ast.Parameter // the underlying syntax node this was built from Annotations // the annotations applied to the parameter Function *Function // the function this parameter belongs to Named // the name of the parameter Docs Documentation // the documentation for the parameter Type Type // the type of the parameter } func (*Parameter) isNode() {} func (*Parameter) isExpression() {} // ExpressionType implements Expression for parameter lookup. func (p *Parameter) ExpressionType() Type { return p.Type } // IsThis returns true if this parameter is the This parameter of it's function. func (p *Parameter) IsThis() bool { return p == p.Function.This } // IsReturn returns true if this parameter is the Return parameter of it's function. func (p *Parameter) IsReturn() bool { return p == p.Function.Return } // Observed represents the final observed value of an output parameter. // It is never produced directly from the ast, but is inserted when inferring // the value of an unknown from observed outputs. type Observed struct { Parameter *Parameter // the output parameter to infer from } func (*Observed) isNode() {} func (*Observed) isExpression() {} // ExpressionType implements Expression for observed parameter lookup. func (e *Observed) ExpressionType() Type { return e.Parameter.Type } // Callable wraps a Function declaration into a first class function value expression, // optionally binding to an object if its a method. type Callable struct { Object Expression // the object to use as the this parameter for a method Function *Function // the function this expression represents } func (*Callable) isNode() {} func (*Callable) isExpression() {} // TODO: Do we really want this as an expression? // ExpressionType implements Expression returning the function type signature. func (c *Callable) ExpressionType() Type { if c.Function.Signature != nil { return c.Function.Signature } return VoidType } // Call represents a function call. It binds an Callable to the arguments it // will be passed. type Call struct { AST *ast.Call // the underlying syntax node this was built from Target *Callable // the function expression this invokes Arguments []Expression // the arguments to pass to the function Type Type // the return type of the call } func (*Call) isNode() {} func (*Call) isExpression() {} func (*Call) isStatement() {} // ExpressionType implements Expression returning the underlying function return type. func (c *Call) ExpressionType() Type { return c.Type } // Signature represents a callable type signature type Signature struct { owned noMembers Named // the full type name Return Type // the return type of the callable Arguments []Type // the required callable arguments } func (*Signature) isNode() {} func (*Signature) isType() {}
gapil/semantic/function.go
0.681621
0.639145
function.go
starcoder
package keys import ( "golang.org/x/exp/event" ) // Value represents a key for untyped values. type Value string // From can be used to get a value from a Label. func (k Value) From(l event.Label) interface{} { return l.Value.Interface() } // Of creates a new Label with this key and the supplied value. func (k Value) Of(v interface{}) event.Label { return event.Label{Name: string(k), Value: event.ValueOf(v)} } // Tag represents a key for tagging labels that have no value. // These are used when the existence of the label is the entire information it // carries, such as marking events to be of a specific kind, or from a specific // package. type Tag string // New creates a new Label with this key. func (k Tag) New() event.Label { return event.Label{Name: string(k)} } // Int represents a key type Int string // Of creates a new Label with this key and the supplied value. func (k Int) Of(v int) event.Label { return event.Label{Name: string(k), Value: event.Int64Of(int64(v))} } // From can be used to get a value from a Label. func (k Int) From(l event.Label) int { return int(l.Value.Int64()) } // Int8 represents a key type Int8 string // Of creates a new Label with this key and the supplied value. func (k Int8) Of(v int8) event.Label { return event.Label{Name: string(k), Value: event.Int64Of(int64(v))} } // From can be used to get a value from a Label. func (k Int8) From(l event.Label) int8 { return int8(l.Value.Int64()) } // Int16 represents a key type Int16 string // Of creates a new Label with this key and the supplied value. func (k Int16) Of(v int16) event.Label { return event.Label{Name: string(k), Value: event.Int64Of(int64(v))} } // From can be used to get a value from a Label. func (k Int16) From(l event.Label) int16 { return int16(l.Value.Int64()) } // Int32 represents a key type Int32 string // Of creates a new Label with this key and the supplied value. func (k Int32) Of(v int32) event.Label { return event.Label{Name: string(k), Value: event.Int64Of(int64(v))} } // From can be used to get a value from a Label. func (k Int32) From(l event.Label) int32 { return int32(l.Value.Int64()) } // Int64 represents a key type Int64 string // Of creates a new Label with this key and the supplied value. func (k Int64) Of(v int64) event.Label { return event.Label{Name: string(k), Value: event.Int64Of(v)} } // From can be used to get a value from a Label. func (k Int64) From(l event.Label) int64 { return l.Value.Int64() } // UInt represents a key type UInt string // Of creates a new Label with this key and the supplied value. func (k UInt) Of(v uint) event.Label { return event.Label{Name: string(k), Value: event.Uint64Of(uint64(v))} } // From can be used to get a value from a Label. func (k UInt) From(l event.Label) uint { return uint(l.Value.Uint64()) } // UInt8 represents a key type UInt8 string // Of creates a new Label with this key and the supplied value. func (k UInt8) Of(v uint8) event.Label { return event.Label{Name: string(k), Value: event.Uint64Of(uint64(v))} } // From can be used to get a value from a Label. func (k UInt8) From(l event.Label) uint8 { return uint8(l.Value.Uint64()) } // UInt16 represents a key type UInt16 string // Of creates a new Label with this key and the supplied value. func (k UInt16) Of(v uint16) event.Label { return event.Label{Name: string(k), Value: event.Uint64Of(uint64(v))} } // From can be used to get a value from a Label. func (k UInt16) From(l event.Label) uint16 { return uint16(l.Value.Uint64()) } // UInt32 represents a key type UInt32 string // Of creates a new Label with this key and the supplied value. func (k UInt32) Of(v uint32) event.Label { return event.Label{Name: string(k), Value: event.Uint64Of(uint64(v))} } // From can be used to get a value from a Label. func (k UInt32) From(l event.Label) uint32 { return uint32(l.Value.Uint64()) } // UInt64 represents a key type UInt64 string // Of creates a new Label with this key and the supplied value. func (k UInt64) Of(v uint64) event.Label { return event.Label{Name: string(k), Value: event.Uint64Of(v)} } // From can be used to get a value from a Label. func (k UInt64) From(l event.Label) uint64 { return l.Value.Uint64() } // Float32 represents a key type Float32 string // Of creates a new Label with this key and the supplied value. func (k Float32) Of(v float32) event.Label { return event.Label{Name: string(k), Value: event.Float64Of(float64(v))} } // From can be used to get a value from a Label. func (k Float32) From(l event.Label) float32 { return float32(l.Value.Float64()) } // Float64 represents a key type Float64 string // Of creates a new Label with this key and the supplied value. func (k Float64) Of(v float64) event.Label { return event.Label{Name: string(k), Value: event.Float64Of(v)} } // From can be used to get a value from a Label. func (k Float64) From(l event.Label) float64 { return l.Value.Float64() } // String represents a key type String string // Of creates a new Label with this key and the supplied value. func (k String) Of(v string) event.Label { return event.Label{Name: string(k), Value: event.StringOf(v)} } // From can be used to get a value from a Label. func (k String) From(l event.Label) string { return l.Value.String() } // Bool represents a key type Bool string // Of creates a new Label with this key and the supplied value. func (k Bool) Of(v bool) event.Label { return event.Label{Name: string(k), Value: event.BoolOf(v)} } // From can be used to get a value from a Label. func (k Bool) From(l event.Label) bool { return l.Value.Bool() }
event/keys/keys.go
0.876357
0.730554
keys.go
starcoder
package information import ( "cloud.google.com/go/spanner" "cloud.google.com/go/spanner/spansql" ) type ( // Columns is a collection of Collumns Columns []*Column // Column is a row from information_schema.columns (see: https://cloud.google.com/spanner/docs/information-schema#information_schemacolumns) Column struct { // The name of the catalog. Always an empty string. TableCatalog *string `spanner:"TABLE_CATALOG"` // The name of the schema. An empty string if unnamed. TableSchema *string `spanner:"TABLE_SCHEMA"` // The name of the table. TableName *string `spanner:"TABLE_NAME"` // The name of the column. ColumnName *string `spanner:"COLUMN_NAME"` // The ordinal position of the column in the table, starting with a value of 1. OrdinalPosition int64 `spanner:"ORDINAL_POSITION"` // Included to satisfy the SQL standard. Always NULL. ColumnDefault []byte `spanner:"COLUMN_DEFAULT"` // Included to satisfy the SQL standard. Always NULL. DataType *string `spanner:"DATA_TYPE"` // A string that indicates whether the column is nullable. In accordance with the SQL standard, the string is either YES or NO, rather than a Boolean value. IsNullable *string `spanner:"IS_NULLABLE"` // The data type of the column. SpannerType *string `spanner:"SPANNER_TYPE"` // A string that indicates whether the column is generated. The string is either ALWAYS for a generated column or NEVER for a non-generated column. IsGenerated bool `spanner:"IS_GENERATED"` // A string representing the SQL expression of a generated column. NULL if the column is not a generated column. GenerationExpression *string `spanner:"GENERATION_EXPRESSION"` // A string that indicates whether the generated column is stored. The string is always YES for generated columns, and NULL for non-generated columns. IsStored *string `spanner:"IS_STORED"` // The current state of the column. A new stored generated column added to an existing table may go through multiple user-observable states before it is fully usable. Possible values are: // WRITE_ONLY: The column is being backfilled. No read is allowed. // COMMITTED: The column is fully usable. SpannerState *string `spanner:"SPANNER_STATE"` IsPrimaryKey bool `spanner:"IS_PRIMARY_KEY"` } ) const getColSqlStr = `SELECT ` + `c.COLUMN_NAME, c.ORDINAL_POSITION, c.IS_NULLABLE, c.SPANNER_TYPE, c.SPANNER_STATE, ` + `EXISTS (` + ` SELECT 1 FROM INFORMATION_SCHEMA.INDEX_COLUMNS ic ` + ` WHERE ic.TABLE_SCHEMA = "" and ic.TABLE_NAME = c.TABLE_NAME ` + ` AND ic.COLUMN_NAME = c.COLUMN_NAME` + ` AND ic.INDEX_NAME = "PRIMARY_KEY" ` + `) IS_PRIMARY_KEY, ` + `IS_GENERATED = "ALWAYS" AS IS_GENERATED ` + `FROM INFORMATION_SCHEMA.COLUMNS c ` + `WHERE c.TABLE_SCHEMA = "" AND c.TABLE_NAME = @table_name ` + `ORDER BY c.ORDINAL_POSITION` var ( // getColumnsForTableQuery renders a query for fetching all columns for a table from information_schema.columns getColumnsForTableQuery = spansql.Query{ Select: spansql.Select{ List: []spansql.Expr{ spansql.ID("TABLE_CATALOG"), spansql.ID("TABLE_SCHEMA"), spansql.ID("TABLE_NAME"), spansql.ID("COLUMN_NAME"), spansql.ID("ORDINAL_POSITION"), spansql.ID("COLUMN_DEFAULT"), spansql.ID("DATA_TYPE"), spansql.ID("IS_NULLABLE"), spansql.ID("SPANNER_TYPE"), spansql.ID("IS_GENERATED"), spansql.ID("GENERATION_EXPRESSION"), spansql.ID("IS_STORED"), spansql.ID("SPANNER_STATE"), }, From: []spansql.SelectFrom{ spansql.SelectFromTable{ Table: "information_schema.columns", }, }, Where: spansql.LogicalOp{ Op: spansql.And, LHS: spansql.ComparisonOp{ Op: spansql.Eq, LHS: spansql.ID("table_schema"), RHS: spansql.StringLiteral(""), }, RHS: spansql.ComparisonOp{ Op: spansql.Eq, LHS: spansql.ID("table_name"), RHS: spansql.Param("table_name"), }, }, }, Order: []spansql.Order{ {Expr: spansql.ID("ORDINAL_POSITION")}, {Expr: spansql.ID("COLUMN_NAME")}, }, } ) // GetColumnsQuery returns a spanner statement for fetching column information for a table func GetColumnsQuery(table string) spanner.Statement { // st := spanner.NewStatement(getColumnsForTableQuery.SQL()) st := spanner.NewStatement(getColSqlStr) st.Params["table_name"] = table return st }
pkg/schema/information/column.go
0.613468
0.430387
column.go
starcoder
package easing import ( "math" ) var easings = []func(float64) float64{ Linear, OutQuad, InQuad, InQuad, OutQuad, InOutQuad, InCubic, OutCubic, InOutCubic, InQuart, OutQuart, InOutQuart, InQuint, OutQuint, InOutQuint, InSine, OutSine, InOutSine, InExpo, OutExpo, InOutExpo, InCirc, OutCirc, InOutCirc, InElastic, OutElastic, OutHalfElastic, OutQuartElastic, InOutElastic, InBack, OutBack, InOutBack, InBounce, OutBounce, InOutBounce, } func GetEasing(easingID int64) func(float64) float64 { if easingID < 0 || easingID >= int64(len(easings)) { easingID = 0 } return easings[easingID] } /* ======================== Using equations from: https://github.com/fogleman/ease/blob/master/ease.go ========================*/ func Linear(t float64) float64 { return t } func InQuad(t float64) float64 { return t * t } func OutQuad(t float64) float64 { return -t * (t - 2) } func InOutQuad(t float64) float64 { if t < 0.5 { return 2 * t * t } else { t = 2*t - 1 return -0.5 * (t*(t-2) - 1) } } func InCubic(t float64) float64 { return t * t * t } func OutCubic(t float64) float64 { t -= 1 return t*t*t + 1 } func InOutCubic(t float64) float64 { t *= 2 if t < 1 { return 0.5 * t * t * t } else { t -= 2 return 0.5 * (t*t*t + 2) } } func InQuart(t float64) float64 { return t * t * t * t } func OutQuart(t float64) float64 { t -= 1 return -(t*t*t*t - 1) } func InOutQuart(t float64) float64 { t *= 2 if t < 1 { return 0.5 * t * t * t * t } else { t -= 2 return -0.5 * (t*t*t*t - 2) } } func InQuint(t float64) float64 { return t * t * t * t * t } func OutQuint(t float64) float64 { t -= 1 return t*t*t*t*t + 1 } func InOutQuint(t float64) float64 { t *= 2 if t < 1 { return 0.5 * t * t * t * t * t } else { t -= 2 return 0.5 * (t*t*t*t*t + 2) } } func InSine(t float64) float64 { return -1*math.Cos(t*math.Pi/2) + 1 } func OutSine(t float64) float64 { return math.Sin(t * math.Pi / 2) } func InOutSine(t float64) float64 { return -0.5 * (math.Cos(math.Pi*t) - 1) } func InExpo(t float64) float64 { if t == 0 { return 0 } else { return math.Pow(2, 10*(t-1)) } } func OutExpo(t float64) float64 { if t == 1 { return 1 } else { return 1 - math.Pow(2, -10*t) } } func InOutExpo(t float64) float64 { if t == 0 { return 0 } else if t == 1 { return 1 } else { if t < 0.5 { return 0.5 * math.Pow(2, (20*t)-10) } else { return 1 - 0.5*math.Pow(2, (-20*t)+10) } } } func InCirc(t float64) float64 { return -1 * (math.Sqrt(1-t*t) - 1) } func OutCirc(t float64) float64 { t -= 1 return math.Sqrt(1 - (t * t)) } func InOutCirc(t float64) float64 { t *= 2 if t < 1 { return -0.5 * (math.Sqrt(1-t*t) - 1) } else { t = t - 2 return 0.5 * (math.Sqrt(1-t*t) + 1) } } func InElastic(t float64) float64 { return InElasticFunction(0.5)(t) } func OutElastic(t float64) float64 { return OutElasticFunction(0.5, 1)(t) } func OutHalfElastic(t float64) float64 { return OutElasticFunction(0.5, 0.5)(t) } func OutQuartElastic(t float64) float64 { return OutElasticFunction(0.5, 0.25)(t) } func InOutElastic(t float64) float64 { return InOutElasticFunction(0.5)(t) } func InElasticFunction(period float64) func(float64) float64 { p := period return func(t float64) float64 { t -= 1 return -1 * (math.Pow(2, 10*t) * math.Sin((t-p/4)*(2*math.Pi)/p)) } } func OutElasticFunction(period, mod float64) func(float64) float64 { p := period return func(t float64) float64 { return math.Pow(2, -10*t)*math.Sin((mod*t-p/4)*(2*math.Pi/p)) + 1 } } func InOutElasticFunction(period float64) func(float64) float64 { p := period return func(t float64) float64 { t *= 2 if t < 1 { t -= 1 return -0.5 * (math.Pow(2, 10*t) * math.Sin((t-p/4)*2*math.Pi/p)) } else { t -= 1 return math.Pow(2, -10*t)*math.Sin((t-p/4)*2*math.Pi/p)*0.5 + 1 } } } func InBack(t float64) float64 { s := 1.70158 return t * t * ((s+1)*t - s) } func OutBack(t float64) float64 { s := 1.70158 t -= 1 return t*t*((s+1)*t+s) + 1 } func InOutBack(t float64) float64 { s := 1.70158 t *= 2 if t < 1 { s *= 1.525 return 0.5 * (t * t * ((s+1)*t - s)) } else { t -= 2 s *= 1.525 return 0.5 * (t*t*((s+1)*t+s) + 2) } } func InBounce(t float64) float64 { return 1 - OutBounce(1-t) } func OutBounce(t float64) float64 { if t < 4/11.0 { return (121 * t * t) / 16.0 } else if t < 8/11.0 { return (363 / 40.0 * t * t) - (99 / 10.0 * t) + 17/5.0 } else if t < 9/10.0 { return (4356 / 361.0 * t * t) - (35442 / 1805.0 * t) + 16061/1805.0 } else { return (54 / 5.0 * t * t) - (513 / 25.0 * t) + 268/25.0 } } func InOutBounce(t float64) float64 { if t < 0.5 { return InBounce(2*t) * 0.5 } else { return OutBounce(2*t-1)*0.5 + 0.5 } } func InSquare(t float64) float64 { if t < 1 { return 0 } else { return 1 } } func OutSquare(t float64) float64 { if t > 0 { return 1 } else { return 0 } } func InOutSquare(t float64) float64 { if t < 0.5 { return 0 } else { return 1 } }
animation/easing/equations.go
0.721154
0.570511
equations.go
starcoder
// Package mlearning provides a few abstracted machine learning algorithms. package mlearning import ( "math/rand" "sort" ) type Feature string type Class string type Weight float64 type Iterator interface { Next() bool Features() []Feature Class() Class Predicted(c Class) } type FeatureCollection interface { Features() []Feature } type SimpleIterator struct { Index int FeatureSlice []FeatureCollection ClassSlice []Class PredictedSlice []Class } func (i *SimpleIterator) Next() bool { i.Index++ return i.Index <= len(i.FeatureSlice) } func (i *SimpleIterator) Features() []Feature { return i.FeatureSlice[i.Index-1].Features() } func (i *SimpleIterator) Class() Class { return i.ClassSlice[i.Index-1] } func (i *SimpleIterator) Predicted(c Class) { if len(i.PredictedSlice) >= i.Index { i.PredictedSlice[i.Index-1] = c } } func (i *SimpleIterator) Reset(shuffle bool) { i.Index = 0 if shuffle { for j := range i.FeatureSlice { k := rand.Intn(j + 1) i.FeatureSlice[j], i.FeatureSlice[k] = i.FeatureSlice[k], i.FeatureSlice[j] i.ClassSlice[j], i.ClassSlice[k] = i.ClassSlice[k], i.ClassSlice[j] } } } type Model struct { Weights map[Feature]map[Class]Weight Classes []Class I int Totals map[Feature]map[Class]Weight Timestamps map[Feature]map[Class]int } func NewModel() *Model { return &Model{ Weights: make(map[Feature]map[Class]Weight), Classes: make([]Class, 0), I: 0, Totals: make(map[Feature]map[Class]Weight), Timestamps: make(map[Feature]map[Class]int), } } type Perceptron struct { *Model } func NewPerceptron() *Perceptron { return &Perceptron{ Model: NewModel(), } } func (p *Perceptron) Predict(features []Feature) (Class, Weight) { scores := map[Class]Weight{} for _, feat := range features { if weights, ok := p.Weights[feat]; ok { for class, weight := range weights { scores[class] += weight } } } mclass := Class("") mweight := Weight(0) for class, weight := range scores { if weight > mweight { mclass, mweight = class, weight } } return mclass, mweight } type Prediction struct { Class Class Weight Weight } type byWeight []Prediction func (a byWeight) Len() int { return len(a) } func (a byWeight) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a byWeight) Less(i, j int) bool { return a[i].Weight > a[j].Weight } func (p *Perceptron) PredictAll(features []Feature) []Prediction { scores := map[Class]Weight{} for _, feat := range features { if weights, ok := p.Weights[feat]; ok { for class, weight := range weights { scores[class] += weight } } } predictions := make([]Prediction, 0, len(scores)) for c, w := range scores { predictions = append(predictions, Prediction{c, w}) } sort.Sort(byWeight(predictions)) return predictions } func (p *Perceptron) Train(fs Iterator) (int, int) { c, n := 0, 0 for fs.Next() { feats := fs.Features() guess, _ := p.Predict(feats) truth := fs.Class() fs.Predicted(guess) p.Update(truth, guess, feats) if guess == truth { c++ } n++ } return c, n } func (p *Perceptron) Test(fs Iterator) (int, int) { c, n := 0, 0 for fs.Next() { feats := fs.Features() guess, _ := p.Predict(feats) fs.Predicted(guess) truth := fs.Class() if guess == truth { c++ } n++ } return c, n } func (p *Perceptron) Update(truth Class, guess Class, features []Feature) { p.I++ for _, f := range features { p.UpdateFeature(truth, f, 1) p.UpdateFeature(guess, f, -1) } } func (p *Perceptron) UpdateFeature(c Class, f Feature, w Weight) { nrItersAtThisWeight := p.I if ci, ok := p.Timestamps[f]; ok { nrItersAtThisWeight -= ci[c] } if _, ok := p.Totals[f]; !ok { p.Totals[f] = map[Class]Weight{} } if _, ok := p.Weights[f]; !ok { p.Weights[f] = map[Class]Weight{} } if _, ok := p.Timestamps[f]; !ok { p.Timestamps[f] = map[Class]int{} } p.Totals[f][c] += Weight(nrItersAtThisWeight) * p.Weights[f][c] p.Weights[f][c] += w p.Timestamps[f][c] = p.I }
pkg/mlearning/perceptron.go
0.725746
0.437884
perceptron.go
starcoder
package promql import ( "fmt" "time" "github.com/wolffcm/flux" "github.com/wolffcm/flux/execute" "github.com/wolffcm/flux/plan" "github.com/wolffcm/flux/semantic" "github.com/wolffcm/flux/values" ) const LinearRegressionKind = "linearRegression" type LinearRegressionOpSpec struct { Predict bool `json:"predict"` // Stored as seconds in float64 to avoid back-and-forth duration conversions from PromQL. FromNow float64 `json:"fromNow"` } func init() { linearRegressionSignature := flux.FunctionSignature(map[string]semantic.PolyType{ "predict": semantic.Bool, "fromNow": semantic.Float, }, nil) flux.RegisterPackageValue("internal/promql", LinearRegressionKind, flux.FunctionValue(LinearRegressionKind, createLinearRegressionOpSpec, linearRegressionSignature)) flux.RegisterOpSpec(LinearRegressionKind, newLinearRegressionOp) plan.RegisterProcedureSpec(LinearRegressionKind, newLinearRegressionProcedure, LinearRegressionKind) execute.RegisterTransformation(LinearRegressionKind, createLinearRegressionTransformation) } func createLinearRegressionOpSpec(args flux.Arguments, a *flux.Administration) (flux.OperationSpec, error) { if err := a.AddParentFromArgs(args); err != nil { return nil, err } spec := new(LinearRegressionOpSpec) if p, ok, err := args.GetBool("predict"); err != nil { return nil, err } else if ok { spec.Predict = p } if d, ok, err := args.GetFloat("fromNow"); err != nil { return nil, err } else if ok { spec.FromNow = d } return spec, nil } func newLinearRegressionOp() flux.OperationSpec { return new(LinearRegressionOpSpec) } func (s *LinearRegressionOpSpec) Kind() flux.OperationKind { return LinearRegressionKind } type LinearRegressionProcedureSpec struct { plan.DefaultCost Predict bool FromNow float64 } func newLinearRegressionProcedure(qs flux.OperationSpec, pa plan.Administration) (plan.ProcedureSpec, error) { spec, ok := qs.(*LinearRegressionOpSpec) if !ok { return nil, fmt.Errorf("invalid spec type %T", qs) } return &LinearRegressionProcedureSpec{ Predict: spec.Predict, FromNow: spec.FromNow, }, nil } func (s *LinearRegressionProcedureSpec) Kind() plan.ProcedureKind { return LinearRegressionKind } func (s *LinearRegressionProcedureSpec) Copy() plan.ProcedureSpec { ns := new(LinearRegressionProcedureSpec) *ns = *s return ns } // TriggerSpec implements plan.TriggerAwareProcedureSpec func (s *LinearRegressionProcedureSpec) TriggerSpec() plan.TriggerSpec { return plan.NarrowTransformationTriggerSpec{} } func createLinearRegressionTransformation(id execute.DatasetID, mode execute.AccumulationMode, spec plan.ProcedureSpec, a execute.Administration) (execute.Transformation, execute.Dataset, error) { s, ok := spec.(*LinearRegressionProcedureSpec) if !ok { return nil, nil, fmt.Errorf("invalid spec type %T", spec) } cache := execute.NewTableBuilderCache(a.Allocator()) d := execute.NewDataset(id, mode, cache) t := NewLinearRegressionTransformation(d, cache, s) return t, d, nil } type linearRegressionTransformation struct { d execute.Dataset cache execute.TableBuilderCache predict bool fromNow float64 } func NewLinearRegressionTransformation(d execute.Dataset, cache execute.TableBuilderCache, spec *LinearRegressionProcedureSpec) *linearRegressionTransformation { return &linearRegressionTransformation{ d: d, cache: cache, predict: spec.Predict, fromNow: spec.FromNow, } } func (t *linearRegressionTransformation) RetractTable(id execute.DatasetID, key flux.GroupKey) error { return t.d.RetractTable(key) } func (t *linearRegressionTransformation) Process(id execute.DatasetID, tbl flux.Table) error { // TODO: Check that all columns are part of the key, except _value and _time. key := tbl.Key() builder, created := t.cache.TableBuilder(key) if !created { return fmt.Errorf("linearRegression found duplicate table with key: %v", tbl.Key()) } if err := execute.AddTableKeyCols(key, builder); err != nil { return err } cols := tbl.Cols() timeIdx := execute.ColIdx(execute.DefaultTimeColLabel, cols) if timeIdx < 0 { return fmt.Errorf("time column not found (cols: %v): %s", cols, execute.DefaultTimeColLabel) } stopIdx := execute.ColIdx(execute.DefaultStopColLabel, cols) if stopIdx < 0 { return fmt.Errorf("stop column not found (cols: %v): %s", cols, execute.DefaultStopColLabel) } valIdx := execute.ColIdx(execute.DefaultValueColLabel, cols) if valIdx < 0 { return fmt.Errorf("value column not found (cols: %v): %s", cols, execute.DefaultValueColLabel) } if key.Value(stopIdx).Type() != semantic.Time { return fmt.Errorf("stop column is not of time type") } var ( numVals int sumX, sumY float64 sumXY, sumX2 float64 firstTime time.Time ) err := tbl.Do(func(cr flux.ColReader) error { vs := cr.Floats(valIdx) times := cr.Times(timeIdx) for i := 0; i < cr.Len(); i++ { if !vs.IsValid(i) || !times.IsValid(i) { continue } v := vs.Value(i) ts := values.Time(times.Value(i)).Time() if numVals == 0 { // Subtle difference between deriv() and predict_linear() intercept time. if t.predict { firstTime = key.ValueTime(stopIdx).Time() } else { firstTime = ts } } x := float64(ts.Sub(firstTime).Seconds()) numVals++ sumY += v sumX += x sumXY += x * v sumX2 += x * x } return nil }) if err != nil { return err } // Omit output table if there are not at least two samples to compute a rate from. if numVals < 2 { return nil } n := float64(numVals) covXY := sumXY - sumX*sumY/n varX := sumX2 - sumX*sumX/n slope := covXY / varX resultValue := slope if t.predict { intercept := sumY/n - slope*sumX/n resultValue = slope*t.fromNow + intercept } outValIdx, err := builder.AddCol(flux.ColMeta{Label: execute.DefaultValueColLabel, Type: flux.TFloat}) if err != nil { return fmt.Errorf("error appending value column: %s", err) } if err := builder.AppendFloat(outValIdx, resultValue); err != nil { return err } return execute.AppendKeyValues(key, builder) } func (t *linearRegressionTransformation) UpdateWatermark(id execute.DatasetID, mark execute.Time) error { return t.d.UpdateWatermark(mark) } func (t *linearRegressionTransformation) UpdateProcessingTime(id execute.DatasetID, pt execute.Time) error { return t.d.UpdateProcessingTime(pt) } func (t *linearRegressionTransformation) Finish(id execute.DatasetID, err error) { t.d.Finish(err) }
stdlib/internal/promql/linear_regression.go
0.740737
0.501526
linear_regression.go
starcoder
path.go Description: Objects which are finite path fragments. */ package sequences import ( "fmt" mc "github.com/kwesiRutledge/ModelChecking" ) /* Type Declarations */ type FinitePathFragment struct { s []mc.TransitionSystemState } type InfinitePathFragment struct { UniquePrefix FinitePathFragment RepeatingSuffix FinitePathFragment } type PathFragment interface { Check() error IsMaximal() bool IsInitial() bool } // Functions func (fragmentIn FinitePathFragment) Check() error { // Verify that the transitions in the path fragment are okay for sIndex := 0; sIndex < len(fragmentIn.s)-1; sIndex++ { si := fragmentIn.s[sIndex] sip1 := fragmentIn.s[sIndex+1] siAncestors, err := mc.Post(si) if err != nil { return fmt.Errorf("There was an issue computing the %vth post (Post(%v)): %v", sIndex, si, err) } if !sip1.In(siAncestors) { return fmt.Errorf( "The %vth state (%v) is not in the post of the %vth state (%v).", sIndex+1, sip1, sIndex, si, ) } } // Return nothing if all transitions are correct return nil } /* Check Description: For the InfinitePathFragment object, this checks that: - The sequences within UniquePrefix and RepeatingSuffix are independently valid - The transition from UniquePrefix to RepeatingSuffix is valid - The transition from the end of RepeatingSuffix to the beginning of RepeatingSuffix is valid */ func (fragmentIn InfinitePathFragment) Check() error { // Make sure that the suffix contains at least one element if len(fragmentIn.RepeatingSuffix.s) == 0 { return fmt.Errorf("The RepeatingSuffix value has length 0. If this is a FinitePathFragment, then use that object instead!") } //Verify that Both the prefix and suffix are valid by themselves err := fragmentIn.UniquePrefix.Check() if err != nil { return fmt.Errorf("There was an issue while checking the prefix of the path fragment: %v", err) } err = fragmentIn.RepeatingSuffix.Check() if err != nil { return fmt.Errorf("There was an issue while checking the suffix of the path fragment: %v", err) } //Check that the first state in the suffix is in the Post of the last state from the prefix lastStateInPrefix := fragmentIn.UniquePrefix.s[len(fragmentIn.UniquePrefix.s)-1] firstStateInSuffix := fragmentIn.RepeatingSuffix.s[0] ancestorsOfLastState, err := mc.Post(lastStateInPrefix) if err != nil { return fmt.Errorf("There was an error computing the Post of the last state in the prefix: %v", err) } if !firstStateInSuffix.In(ancestorsOfLastState) { return fmt.Errorf("The first state in the suffix \"%v\" was not an ancestor of the last state in the prefix \"%v\".", firstStateInSuffix, lastStateInPrefix) } //Check that the first state in the suffix is in the Post of the last state in the suffix lastStateInSuffix := fragmentIn.RepeatingSuffix.s[len(fragmentIn.RepeatingSuffix.s)-1] ancestorsOfLastState, err = mc.Post(lastStateInSuffix) if err != nil { return fmt.Errorf("There was an error computing the Post of the last state in the suffix: %v", err) } if !firstStateInSuffix.In(ancestorsOfLastState) { return fmt.Errorf("The first state in the suffix \"%v\" was not an ancestor of the last state in the suffix \"%v\".", firstStateInSuffix, lastStateInSuffix) } // If you made it this far, then everything is fine. return nil } /* IsMaximal Description: For the FinitePathFragment, this is true if the last state is terminal. Assumption: Assumes that you've already checked the FinitePathFragment. */ func (fragmentIn FinitePathFragment) IsMaximal() bool { //Grabs last state in path. finalState := fragmentIn.s[len(fragmentIn.s)-1] return finalState.IsTerminal() } /* IsMaximal Description: For the InfinitePathFragment, this is always true. Assumption: This assumes that the InfinitePathFragment was already checked. */ func (fragmentIn InfinitePathFragment) IsMaximal() bool { return true } /* IsInitial Description For any type of execution, this is true if the first state of the execution is in the transition system's initial state set. */ func (fragmentIn FinitePathFragment) IsInitial() bool { initialState := fragmentIn.s[0] System := *&initialState.System return initialState.In(System.I) } func (fragmentIn InfinitePathFragment) IsInitial() bool { var initialState mc.TransitionSystemState if len(fragmentIn.UniquePrefix.s) > 0 { initialState = fragmentIn.UniquePrefix.s[0] } else { initialState = fragmentIn.RepeatingSuffix.s[0] } System := *&initialState.System return initialState.In(System.I) } /* IsPath() Description: This function should work for either FinitePathFragment or InitialPathFragment objects and will check to see if the given fragment is initial and maximal before returning true or false. Assumption: This function assumes that fragmentIn has previously been checked. */ func IsPath(fragmentIn PathFragment) bool { return fragmentIn.IsInitial() && fragmentIn.IsMaximal() } /* ToTrace Description: Uses the labels of this transition system to compute the trace of a finite or infinite path. Assumptions: This function assumes that you've run fragmentIn.Check() beforehand. */ func (fragmentIn FinitePathFragment) ToTrace() FiniteTrace { // Get System firstState := fragmentIn.s[0] ts := *&firstState.System var SequenceOfAPSubsets [][]mc.AtomicProposition for _, tempState := range fragmentIn.s { SequenceOfAPSubsets = append(SequenceOfAPSubsets, ts.L[tempState]) } // Return final answer. return FiniteTrace{L: SequenceOfAPSubsets} } func (fragmentIn InfinitePathFragment) ToTrace() InfiniteTrace { return InfiniteTrace{ UniquePrefix: fragmentIn.UniquePrefix.ToTrace(), RepeatingSuffix: fragmentIn.RepeatingSuffix.ToTrace(), } }
sequences/path.go
0.743075
0.415136
path.go
starcoder
This provides support for local-data persistent volumes, by two means: * Removes volumes using "local-data" from the internal pods copy, for the duration of the current autoscaler RunOnce loop. local-data volumes (as any volume using a no-provisioner storage class) breaks the VolumeBinding predicate used during Scheduler Framework's evaluations. * Injects a custom resource request to pods having "local-data" volumes. Our autoscaler fork is placing the same resource on NodeInfo templates built from ASG/MIG/VMSS when they offer nodes with local-data storage. Those virtual NodeInfos are used when the autoscaler evaluates upscale candidates. Injecting those requests on pods allows us to upscale only nodes having local data, and to know those nodes can host a single pod requesting a local-data volume (because allocatable qty = request = 1). Caveats: * That's obviously not upstreamable * With that resource req, none of the existing real nodes can be considered by autoscaler as schedulable for pods requesting local-data volumes: the "storageclass/local-data" resource is only available on virtual nodes built from asg templates (so, during upscale simulations and for upcoming nodes), but not at "filter out pods schedulables on existing real nodes" phase. Hence the need for an other patch: once those nodes just became ready but the pod is not scheduled on them yet (eg. when their local data volume isn't built or bound yet): the autoscaler wouldn't consider those fresh nodes (now evaluated by using nodeInfos built from real/live nodes) suitable for their pendind pods anymore, since now the nodes don't have the requested custom resource. Which would lead to spurious re-upscales during the "node became Ready -> pod now scheduled to that node" phase. * Using that hack forces the use nodeinfos built from asg templates, rather than from real world nodes (as op. to upstream behaviour). Which we do also for other reasons anyway (scale from zero + balance similar). */ package pods import ( "time" "k8s.io/autoscaler/cluster-autoscaler/context" "k8s.io/autoscaler/cluster-autoscaler/processors/datadog/common" apiv1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/fields" client "k8s.io/client-go/kubernetes" v1lister "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/tools/cache" klog "k8s.io/klog/v2" ) type transformLocalData struct { pvcLister v1lister.PersistentVolumeClaimLister stopChannel chan struct{} } // NewTransformLocalData instantiate a transformLocalData processor func NewTransformLocalData() *transformLocalData { return &transformLocalData{ stopChannel: make(chan struct{}), } } // CleanUp shuts down the pv lister func (p *transformLocalData) CleanUp() { close(p.stopChannel) } // Process replace volumes to local-data pv by our custom resource func (p *transformLocalData) Process(ctx *context.AutoscalingContext, pods []*apiv1.Pod) ([]*apiv1.Pod, error) { if p.pvcLister == nil { p.pvcLister = NewPersistentVolumeClaimLister(ctx.ClientSet, p.stopChannel) } for _, po := range pods { var volumes []apiv1.Volume for _, vol := range po.Spec.Volumes { if vol.PersistentVolumeClaim == nil { volumes = append(volumes, vol) continue } pvc, err := p.pvcLister.PersistentVolumeClaims(po.Namespace).Get(vol.PersistentVolumeClaim.ClaimName) if err != nil { if !apierrors.IsNotFound(err) { klog.Warningf("failed to fetch pvc for %s/%s: %v", po.GetNamespace(), po.GetName(), err) } volumes = append(volumes, vol) continue } if *pvc.Spec.StorageClassName != "local-data" { volumes = append(volumes, vol) continue } if len(po.Spec.Containers[0].Resources.Requests) == 0 { po.Spec.Containers[0].Resources.Requests = apiv1.ResourceList{} } if len(po.Spec.Containers[0].Resources.Limits) == 0 { po.Spec.Containers[0].Resources.Limits = apiv1.ResourceList{} } po.Spec.Containers[0].Resources.Requests[common.DatadogLocalDataResource] = common.DatadogLocalDataQuantity.DeepCopy() po.Spec.Containers[0].Resources.Limits[common.DatadogLocalDataResource] = common.DatadogLocalDataQuantity.DeepCopy() } po.Spec.Volumes = volumes } return pods, nil } // NewPersistentVolumeClaimLister builds a persistentvolumeclaim lister. func NewPersistentVolumeClaimLister(kubeClient client.Interface, stopchannel <-chan struct{}) v1lister.PersistentVolumeClaimLister { listWatcher := cache.NewListWatchFromClient(kubeClient.CoreV1().RESTClient(), "persistentvolumeclaims", apiv1.NamespaceAll, fields.Everything()) store, reflector := cache.NewNamespaceKeyedIndexerAndReflector(listWatcher, &apiv1.PersistentVolumeClaim{}, time.Hour) lister := v1lister.NewPersistentVolumeClaimLister(store) go reflector.Run(stopchannel) return lister }
cluster-autoscaler/processors/datadog/pods/transform_local_data.go
0.677154
0.478773
transform_local_data.go
starcoder
// A Paillier implementation in Go with some optimizations. // This includes choosing g = n + 1. More documentation required. package paillier import ( "crypto/rand" "math/big" ) var bigZero = big.NewInt(0) var bigOne = big.NewInt(1) // Encrypter is an interface for additively homomorphic encryption schemes. type Encrypter interface { // Randomize (re-)randomizes an encrypted value Randomize(ciphertext *big.Int) *big.Int // Encrypt encrypts a message (big.Int) Encrypt(plaintext *big.Int) *big.Int // PartiallyEncrypt does the first part of the encryption, so that the // (computationally expensive) randomization can be done at a later time. PartiallyEncrypt(plaintext *big.Int) *big.Int // Add adds two encrypted values and returns the encrypted sum. Add(ciphertextA, ciphertextB *big.Int) *big.Int // AddTo adds b to the Encrypted value a (and also returns it). AddTo(ciphertextA, ciphertextB *big.Int) *big.Int // Mul multiplies the plaintext value b with the encrypted value a and returns the result. Mul(ciphertextA, plaintextB *big.Int) *big.Int } // PublicKey is a Paillier public key and implements the Encrypter interface type PublicKey struct { N *big.Int N2 *big.Int // cached value of N^2 Nplus1 *big.Int // cached value of N + 1 bits int // Number of bits of N } // PrivateKey is a Paillier private key type PrivateKey struct { PublicKey Lambda *big.Int X *big.Int // Cached value for faster decryption } //lcm computes the least common multiple func lcm(a, b *big.Int) *big.Int { t := new(big.Int) t.Div(t.Mul(a, b), new(big.Int).GCD(nil, nil, a, b)) return t } // Just use the default randomness provider of crypto/rand. var random = rand.Reader // GenerateKey generates a random Paillier private key func GenerateKey(bits int) (priv *PrivateKey, err error) { var p, q *big.Int n := new(big.Int) for { p, _ = rand.Prime(random, bits>>1) q, _ = rand.Prime(random, bits>>1) n.Mul(p, q) if n.Bit(bits-1) == 1 && p.Cmp(q) != 0 { break } } lambda := lcm(p.Sub(p, bigOne), q.Sub(q, bigOne)) np1 := new(big.Int).Add(n, bigOne) n2 := new(big.Int).Mul(n, n) x := new(big.Int) x.ModInverse(x.Div(x.Sub(x.Exp(np1, lambda, n2), bigOne), n), n) priv = &PrivateKey{PublicKey{n, n2, np1, bits}, lambda, x} return } // getRN computes r^N mod N^2 func (k *PublicKey) getRN() *big.Int { r, _ := rand.Int(random, k.N) return r.Exp(r, k.N, k.N2) } // Randomize randomizes an encrypted value. func (k *PublicKey) Randomize(a *big.Int) *big.Int { rn := k.getRN() return rn.Mul(rn, a) } // Encrypt encrypts a message (big.Int). func (k *PublicKey) Encrypt(m *big.Int) *big.Int { return k.Randomize(k.PartiallyEncrypt(m)) } // PartiallyEncrypt does the first part of the encryption, so that the // (computationally expensive) randomization can be done at a later time. func (k *PublicKey) PartiallyEncrypt(m *big.Int) *big.Int { t := new(big.Int).Mul(k.N, m) t.Add(t, bigOne) return t.Mod(t, k.N2) } // Add adds two encrypted values and returns the encrypted sum. func (k *PublicKey) Add(a, b *big.Int) *big.Int { t := new(big.Int).Mul(a, b) return t.Mod(t, k.N2) } // AddTo adds b to the Encrypted value a (and also returns it). func (k *PublicKey) AddTo(a, b *big.Int) *big.Int { return a.Mod(a.Mul(a, b), k.N2) } // Mul multiplies the plaintext value b with the encrypted value a and returns the result. func (k *PublicKey) Mul(a, b *big.Int) *big.Int { return new(big.Int).Exp(a, b, k.N2) } // Decrypt attempts to decrypt the provided cyphertext and returns the result. func (k *PrivateKey) Decrypt(c *big.Int) *big.Int { t := new(big.Int) return t.Mod(t.Mul(t.Div(t.Sub(t.Exp(c, k.Lambda, k.N2), bigOne), k.N), k.X), k.N) }
paillier.go
0.763748
0.484624
paillier.go
starcoder
package consumer // Bool represents a function that accepts a bool. type Bool func(bool) // Int represents a function that accepts a int. type Int func(int) // Int8 represents a function that accepts a int8. type Int8 func(int8) // Int16 represents a function that accepts a int16. type Int16 func(int16) // Int32 represents a function that accepts a int32. type Int32 func(int32) // Int64 represents a function that accepts a int64. type Int64 func(int64) // Uint represents a function that accepts a uint. type Uint func(uint) // Uint8 represents a function that accepts a uint8. type Uint8 func(uint8) // Uint16 represents a function that accepts a uint16. type Uint16 func(uint16) // Uint32 represents a function that accepts a uint32. type Uint32 func(uint32) // Uint64 represents a function that accepts a uint64. type Uint64 func(uint64) // Uintptr represents a function that accepts a uintptr. type Uintptr func(uintptr) // Float32 represents a function that accepts a float32. type Float32 func(float32) // Float64 represents a function that accepts a float64. type Float64 func(float64) // Complex64 represents a function that accepts a complex64. type Complex64 func(complex64) // Complex128 represents a function that accepts a complex128. type Complex128 func(complex128) // Byte represents a function that accepts a byte. type Byte func(byte) // Rune represents a function that accepts a rune. type Rune func(rune) // String represents a function that accepts a string. type String func(string) // Error represents a function that accepts a error. type Error func(error) // Interface represents a function that accepts a interface{}. type Interface func(interface{}) // Bools represents a function that accepts a []bool. type Bools func([]bool) // Ints represents a function that accepts a []int. type Ints func([]int) // Int8s represents a function that accepts a []int8. type Int8s func([]int8) // Int16s represents a function that accepts a []int16. type Int16s func([]int16) // Int32s represents a function that accepts a []int32. type Int32s func([]int32) // Int64s represents a function that accepts a []int64. type Int64s func([]int64) // Uints represents a function that accepts a []uint. type Uints func([]uint) // Uint8s represents a function that accepts a []uint8. type Uint8s func([]uint8) // Uint16s represents a function that accepts a []uint16. type Uint16s func([]uint16) // Uint32s represents a function that accepts a []uint32. type Uint32s func([]uint32) // Uint64s represents a function that accepts a []uint64. type Uint64s func([]uint64) // Uintptrs represents a function that accepts a []uintptr. type Uintptrs func([]uintptr) // Float32s represents a function that accepts a []float32. type Float32s func([]float32) // Float64s represents a function that accepts a []float64. type Float64s func([]float64) // Complex64s represents a function that accepts a []complex64. type Complex64s func([]complex64) // Complex128s represents a function that accepts a []complex128. type Complex128s func([]complex128) // Bytes represents a function that accepts a []byte. type Bytes func([]byte) // Runes represents a function that accepts a []rune. type Runes func([]rune) // Strings represents a function that accepts a []string. type Strings func([]string) // Errors represents a function that accepts a []error. type Errors func([]error) // Interfaces represents a function that accepts a []interface{}. type Interfaces func([]interface{})
functional/consumer/consumer.go
0.631822
0.612397
consumer.go
starcoder
package axes // label.go contains code that calculates the positions of labels on the axes. import ( "fmt" "image" "github.com/mum4k/termdash/align" "github.com/mum4k/termdash/internal/alignfor" ) // LabelOrientation represents the orientation of text labels. type LabelOrientation int // String implements fmt.Stringer() func (lo LabelOrientation) String() string { if n, ok := labelOrientationNames[lo]; ok { return n } return "LabelOrientationUnknown" } // labelOrientationNames maps LabelOrientation values to human readable names. var labelOrientationNames = map[LabelOrientation]string{ LabelOrientationHorizontal: "LabelOrientationHorizontal", LabelOrientationVertical: "LabelOrientationVertical", } const ( // LabelOrientationHorizontal is the default label orientation where text // flows horizontally. LabelOrientationHorizontal LabelOrientation = iota // LabelOrientationVertical is an orientation where text flows vertically. LabelOrientationVertical ) // Label is one value label on an axis. type Label struct { // Value if the value to be displayed. Value *Value // Position of the label within the canvas. Pos image.Point } // yLabels returns labels that should be placed next to the Y axis. // The labelWidth is the width of the area from the left-most side of the // canvas until the Y axis (not including the Y axis). This is the area where // the labels will be placed and aligned. // Labels are returned in an increasing value order. // Label value is not trimmed to the provided labelWidth, the label width is // only used to align the labels. Alignment is done with the assumption that // longer labels will be trimmed. func yLabels(scale *YScale, labelWidth int) ([]*Label, error) { if min := 2; scale.GraphHeight < min { return nil, fmt.Errorf("cannot place labels on a canvas with height %d, minimum is %d", scale.GraphHeight, min) } if min := 0; labelWidth < min { return nil, fmt.Errorf("cannot place labels in label area width %d, minimum is %d", labelWidth, min) } var labels []*Label const labelSpacing = 4 seen := map[string]bool{} for y := scale.GraphHeight - 1; y >= 0; y -= labelSpacing { label, err := rowLabel(scale, y, labelWidth) if err != nil { return nil, err } if !seen[label.Value.Text()] { labels = append(labels, label) seen[label.Value.Text()] = true } } // If we have data, place at least two labels, first and last. haveData := scale.Min.Rounded != 0 || scale.Max.Rounded != 0 if len(labels) < 2 && haveData { const maxRow = 0 label, err := rowLabel(scale, maxRow, labelWidth) if err != nil { return nil, err } labels = append(labels, label) } return labels, nil } // rowLabelArea determines the area available for labels on the specified row. // The row is the Y coordinate of the row, Y coordinates grow down. func rowLabelArea(row int, labelWidth int) image.Rectangle { return image.Rect(0, row, labelWidth, row+1) } // rowLabel returns label for the specified row. func rowLabel(scale *YScale, y int, labelWidth int) (*Label, error) { v, err := scale.CellLabel(y) if err != nil { return nil, fmt.Errorf("unable to determine label value for row %d: %v", y, err) } ar := rowLabelArea(y, labelWidth) pos, err := alignfor.Text(ar, v.Text(), align.HorizontalRight, align.VerticalMiddle) if err != nil { return nil, fmt.Errorf("unable to align the label value: %v", err) } return &Label{ Value: v, Pos: pos, }, nil } // xSpace represents an available space among the X axis. type xSpace struct { // min is the current relative coordinate. // These are zero based, i.e. not adjusted to axisStart. cur int // max is the maximum relative coordinate. // These are zero based, i.e. not adjusted to axisStart. // The xSpace instance contains points 0 <= x < max max int // graphZero is the (0, 0) point on the graph. graphZero image.Point } // newXSpace returns a new xSpace instance initialized for the provided width. func newXSpace(graphZero image.Point, graphWidth int) *xSpace { return &xSpace{ cur: 0, max: graphWidth, graphZero: graphZero, } } // Implements fmt.Stringer. func (xs *xSpace) String() string { return fmt.Sprintf("xSpace(size:%d)-cur:%v-max:%v", xs.Remaining(), image.Point{xs.cur, xs.graphZero.Y}, image.Point{xs.max, xs.graphZero.Y}) } // Remaining returns the remaining size on the X axis. func (xs *xSpace) Remaining() int { return xs.max - xs.cur } // Relative returns the relative coordinate within the space, these are zero // based. func (xs *xSpace) Relative() image.Point { return image.Point{xs.cur, xs.graphZero.Y + 1} } // LabelPos returns the absolute coordinate on the canvas where a label should // be placed. The is the coordinate that represents the current relative // coordinate of the space. func (xs *xSpace) LabelPos() image.Point { return image.Point{xs.cur + xs.graphZero.X, xs.graphZero.Y + 2} // First down is the axis, second the label. } // Sub subtracts the specified size from the beginning of the available // space. func (xs *xSpace) Sub(size int) error { if xs.Remaining() < size { return fmt.Errorf("unable to subtract %d from the start, not enough size in %v", size, xs) } xs.cur += size return nil } // xLabels returns labels that should be placed under the X axis. // The graphZero is the (0, 0) point of the graph area on the canvas. // Labels are returned in an increasing value order. // Returned labels shouldn't be trimmed, their count is adjusted so that they // fit under the width of the axis. // The customLabels map value positions in the series to the desired custom // label. These are preferred if present. func xLabels(scale *XScale, graphZero image.Point, customLabels map[int]string, lo LabelOrientation) ([]*Label, error) { space := newXSpace(graphZero, scale.GraphWidth) const minSpacing = 3 var res []*Label next := int(scale.Min.Value) for haveLabels := 0; haveLabels <= int(scale.Max.Value); haveLabels = len(res) { label, err := colLabel(scale, space, customLabels, lo) if err != nil { return nil, err } if label == nil { break } res = append(res, label) next++ if next > int(scale.Max.Value) { break } nextCell, err := scale.ValueToCell(next) if err != nil { return nil, err } skip := nextCell - space.Relative().X if skip < minSpacing { skip = minSpacing } if space.Remaining() <= skip { break } if err := space.Sub(skip); err != nil { return nil, err } } return res, nil } // colLabel returns a label placed at the beginning of the space. // The space is adjusted according to how much space was taken by the label. // Returns nil, nil if the label doesn't fit in the space. func colLabel(scale *XScale, space *xSpace, customLabels map[int]string, lo LabelOrientation) (*Label, error) { pos := space.Relative() label, err := scale.CellLabel(pos.X) if err != nil { return nil, fmt.Errorf("unable to determine label value for column %d: %v", pos.X, err) } if custom, ok := customLabels[int(label.Value)]; ok { label = NewTextValue(custom) } var labelLen int switch lo { case LabelOrientationHorizontal: labelLen = len(label.Text()) case LabelOrientationVertical: labelLen = 1 } if labelLen > space.Remaining() { return nil, nil } abs := space.LabelPos() if err := space.Sub(labelLen); err != nil { return nil, err } return &Label{ Value: label, Pos: abs, }, nil }
widgets/linechart/internal/axes/label.go
0.934001
0.697892
label.go
starcoder
package iso20022 // Details of the securities trade. type SecuritiesTradeDetails55 struct { // Market in which a trade transaction has been executed. PlaceOfTrade *PlaceOfTradeIdentification1 `xml:"PlcOfTrad,omitempty"` // Infrastructure which may be a component of a clearing house and wich facilitates clearing and settlement for its members by standing between the buyer and the seller. It may net transactions and it substitutes itself as settlement counterparty for each position. PlaceOfClearing *PlaceOfClearingIdentification1 `xml:"PlcOfClr,omitempty"` // Specifies the date/time on which the trade was executed. TradeDate *TradeDate5Choice `xml:"TradDt,omitempty"` // Date and time at which the securities are to be delivered or received. SettlementDate *SettlementDate9Choice `xml:"SttlmDt,omitempty"` // Date and time at which a transaction is completed and cleared, ie, payment is effected and securities are delivered. EffectiveSettlementDate *SettlementDate11Choice `xml:"FctvSttlmDt"` // Specifies the price of the traded financial instrument. // This is the deal price of the individual trade transaction. // If there is only one trade transaction for the execution of the trade, then the deal price could equal the executed trade price (unless, for example, the price includes commissions or rounding, or some other factor has been applied to the deal price or the executed trade price, or both). DealPrice *Price2 `xml:"DealPric,omitempty"` // Specifies that a trade is to be reported to a third party. Reporting []*Reporting6Choice `xml:"Rptg,omitempty"` // Number of days on which the interest rate accrues (daily accrual note). NumberOfDaysAccrued *Max3Number `xml:"NbOfDaysAcrd,omitempty"` // Indicates the conditions under which the order/trade is to be/was executed. TradeTransactionCondition []*TradeTransactionCondition5Choice `xml:"TradTxCond,omitempty"` // Specifies the role of the investor in the transaction. InvestorCapacity *InvestorCapacity4Choice `xml:"InvstrCpcty,omitempty"` // Specifies the role of the trading party in the transaction. TradeOriginatorRole *TradeOriginator3Choice `xml:"TradOrgtrRole,omitempty"` // Provides additional settlement processing information which can not be included within the structured fields of the message. SettlementInstructionProcessingAdditionalDetails *Max350Text `xml:"SttlmInstrPrcgAddtlDtls,omitempty"` // Provides additional details pertaining to foreign exchange instructions. FXAdditionalDetails *Max350Text `xml:"FxAddtlDtls,omitempty"` } func (s *SecuritiesTradeDetails55) AddPlaceOfTrade() *PlaceOfTradeIdentification1 { s.PlaceOfTrade = new(PlaceOfTradeIdentification1) return s.PlaceOfTrade } func (s *SecuritiesTradeDetails55) AddPlaceOfClearing() *PlaceOfClearingIdentification1 { s.PlaceOfClearing = new(PlaceOfClearingIdentification1) return s.PlaceOfClearing } func (s *SecuritiesTradeDetails55) AddTradeDate() *TradeDate5Choice { s.TradeDate = new(TradeDate5Choice) return s.TradeDate } func (s *SecuritiesTradeDetails55) AddSettlementDate() *SettlementDate9Choice { s.SettlementDate = new(SettlementDate9Choice) return s.SettlementDate } func (s *SecuritiesTradeDetails55) AddEffectiveSettlementDate() *SettlementDate11Choice { s.EffectiveSettlementDate = new(SettlementDate11Choice) return s.EffectiveSettlementDate } func (s *SecuritiesTradeDetails55) AddDealPrice() *Price2 { s.DealPrice = new(Price2) return s.DealPrice } func (s *SecuritiesTradeDetails55) AddReporting() *Reporting6Choice { newValue := new(Reporting6Choice) s.Reporting = append(s.Reporting, newValue) return newValue } func (s *SecuritiesTradeDetails55) SetNumberOfDaysAccrued(value string) { s.NumberOfDaysAccrued = (*Max3Number)(&value) } func (s *SecuritiesTradeDetails55) AddTradeTransactionCondition() *TradeTransactionCondition5Choice { newValue := new(TradeTransactionCondition5Choice) s.TradeTransactionCondition = append(s.TradeTransactionCondition, newValue) return newValue } func (s *SecuritiesTradeDetails55) AddInvestorCapacity() *InvestorCapacity4Choice { s.InvestorCapacity = new(InvestorCapacity4Choice) return s.InvestorCapacity } func (s *SecuritiesTradeDetails55) AddTradeOriginatorRole() *TradeOriginator3Choice { s.TradeOriginatorRole = new(TradeOriginator3Choice) return s.TradeOriginatorRole } func (s *SecuritiesTradeDetails55) SetSettlementInstructionProcessingAdditionalDetails(value string) { s.SettlementInstructionProcessingAdditionalDetails = (*Max350Text)(&value) } func (s *SecuritiesTradeDetails55) SetFXAdditionalDetails(value string) { s.FXAdditionalDetails = (*Max350Text)(&value) }
SecuritiesTradeDetails55.go
0.830044
0.431405
SecuritiesTradeDetails55.go
starcoder
package fields import ( "time" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) // Object is a wrappers of zap.Object. func Object(key string, val zapcore.ObjectMarshaler) zap.Field { return zap.Object(key, val) } // Bool is a wrappers of zap.Bool. func Bool(key string, val bool) zap.Field { return zap.Bool(key, val) } // Bools is a wrappers of zap.Bools. func Bools(key string, val []bool) zap.Field { return zap.Bools(key, val) } // String is a wrappers of zap.String. func String(key string, val string) zap.Field { return zap.String(key, val) } // Strings is a wrappers of zap.Strings. func Strings(key string, val []string) zap.Field { return zap.Strings(key, val) } // ByteString is a wrappers of zap.ByteString. func ByteString(key string, val []byte) zap.Field { return zap.ByteString(key, val) } // ByteStrings is a wrappers of zap.ByteStrings. func ByteStrings(key string, val [][]byte) zap.Field { return zap.ByteStrings(key, val) } // Binary is a wrappers of zap.Binary. func Binary(key string, val []byte) zap.Field { return zap.Binary(key, val) } // Int is a wrappers of zap.Int. func Int(key string, val int) zap.Field { return zap.Int(key, val) } // Int64 is a wrappers of zap.Int64. func Int64(key string, val int64) zap.Field { return zap.Int64(key, val) } // Float32 is a wrappers of zap.Float32. func Float32(key string, val float32) zap.Field { return zap.Float32(key, val) } // Float32s is a wrappers of zap.Float32s. func Float32s(key string, val []float32) zap.Field { return zap.Float32s(key, val) } // Float64 is a wrappers of zap.Float64. func Float64(key string, val float64) zap.Field { return zap.Float64(key, val) } // Float64s is a wrappers of zap.Float64s. func Float64s(key string, val []float64) zap.Field { return zap.Float64s(key, val) } // Time is a wrappers of zap.Time. func Time(key string, val time.Time) zap.Field { return zap.Time(key, val) } // Times is a wrappers of zap.Times. func Times(key string, val []time.Time) zap.Field { return zap.Times(key, val) } // Duration is a wrappers of zap.Duration. func Duration(key string, val time.Duration) zap.Field { return zap.Duration(key, val) } // Durations is a wrappers of zap.Durations. func Durations(key string, val []time.Duration) zap.Field { return zap.Durations(key, val) } // Any is a wrappers of zap.Any. func Any(key string, val interface{}) zap.Field { return zap.Any(key, val) } // Error is a wrappers of zap.Error. func Error(err error) zap.Field { return zap.Error(err) } // NamedError is a wrappers of zap.NamedError. func NamedError(key string, err error) zap.Field { return zap.NamedError(key, err) }
fields/wrappers.go
0.813609
0.461017
wrappers.go
starcoder
package extractor import ( "errors" "fmt" "sync" ) // Collector acts as an N fanout pipe from an extractor to receivers. It also simplifies collection by abstracting channel complexity type Collector struct { // Extractor is expected to pass candlesticks and errors over their respective channels Extractor Collectable // Receivers is the list of receivers that receive candlesticks over the `.Collect()` function Receivers []Receiver // Error handler syncronously passes errors from the extrator to the function. Default function prints to stdout ErrorHandler func(error) // running tracks whether or not the collecter is active running bool } // CollectorConfig encapsulates the collection configuration and process type CollectorConfig struct { // Extractor is expected to pass candlesticks and errors over their respective channels Extractor Collectable // Receivers is the list of receivers that receive candlesticks over the `.Collect()` function Receivers []Receiver // Override the default error handler, which prints to stdout ErrorHandler func(error) } // Collectable provides an abstraction to allow any etractor impementation to be used type Collectable interface { Candlesticks() chan *Candlestick Errors() chan error Stop() } // NewCollector builds a collector with the provided chan, and using any receivers provided func NewCollector(config *CollectorConfig) *Collector { c := &Collector{ Extractor: config.Extractor, Receivers: config.Receivers, } if config.ErrorHandler != nil { c.ErrorHandler = config.ErrorHandler } else { c.ErrorHandler = func(e error) { fmt.Printf("Extraction Error: %s\n", e.Error()) } } return c } // Add adds the receiver to the list of reveivers to be used when the collection fires func (c *Collector) Add(r Receiver) { c.Receivers = append(c.Receivers, r) } // Collect collects from either the collectors chan, or the chan param, if provided func (c *Collector) Collect() error { if c.running { return errors.New("Collection already started") } defer c.Close() if len(c.Receivers) == 0 { return errors.New("No receivers set for the collector when Collect was called") } c.running = true var wg sync.WaitGroup wg.Add(1) go func() { defer wg.Done() for cdl := range c.Extractor.Candlesticks() { c.fanOut(cdl) } }() wg.Add(1) go func() { defer wg.Done() for err := range c.Extractor.Errors() { c.ErrorHandler(err) } }() wg.Wait() c.Close() return nil } func (c *Collector) fanOut(cdl *Candlestick) (err error) { for _, rcv := range c.Receivers { cErr := rcv.Collect(cdl) if cErr != nil { c.ErrorHandler(cErr) } } return nil } // Close stops the extractor and closes all receivers func (c *Collector) Close() { c.running = false // Close all receivers for i := range c.Receivers { c.Receivers[i].Close() } }
extractor/collector.go
0.795181
0.4165
collector.go
starcoder
--------------------------------------------------------------------------- Copyright (c) 2013-2015 AT&T Intellectual Property Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------------------------------------------------------------------- */ /* Mnemonic: tomap.go Absrtract: Various functions which transform something into a map. Date: 25 November 2015 Author: <NAME> Mods: 24 Oct 2016 - Fix bug when inserting an interface. */ package transform import ( "fmt" "os" "reflect" ) var ( depth int = 0 ) /* Accept a structure and build a map from its values. The map is [string]string, and the keys are taken from fields tagged with tags that match the tag_id string passed in. If the tag id is map, then a tag might be `map:"xyz"` where xyz is used as the name in the map, or `map:"_"` where the structure field name is used in the map. If the tag id "_" is passed in, then all fields in the structure are captured. This function will capture all simple fields (int, bool, float, etc.) and structures, anonynmous structures and pointers to structures. It will _NOT_ capture arrays or maps. */ func Struct_to_map( ustruct interface{}, tag_id string ) ( m map[string]string ) { var imeta reflect.Type var thing reflect.Value thing = reflect.ValueOf( ustruct ) // thing is the actual usr struct (in reflect container) if thing.Kind() == reflect.Ptr { thing = thing.Elem() // deref the pointer to get the real container imeta = thing.Type() // snag the type allowing for extraction of meta data } else { imeta = reflect.TypeOf( thing ) // convert input to a Type allowing for extraction of meta data } m = make( map[string]string ) return struct_to_map( thing, imeta, tag_id, m, "" ) } func dec_depth() { if depth > 0 { depth-- } } /* Insert a value into the map using its 'tag'. If the value is a struct, map or array (slice) then we recurse to insert each component (array/map) and invoke the struct function to dive into the struct extracting tagged fields. */ func insert_value( thing reflect.Value, tkind reflect.Kind, anon bool, tag string, tag_id string, m map[string]string, pfx string ) { depth++ if depth > 50 { fmt.Fprintf( os.Stderr, "recursion to deep in transform insert value: %s\n%s\n", pfx, tkind ) os.Exit( 1 ) } defer dec_depth() tag = pfx + tag switch tkind { case reflect.String: m[tag] = fmt.Sprintf( "%s", thing ) case reflect.Ptr: p := thing.Elem() switch p.Kind() { case reflect.String: m[tag] = fmt.Sprintf( "%s", p ) case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8: m[tag] = fmt.Sprintf( "%d", p.Int() ) case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8: m[tag] = fmt.Sprintf( "%d", p.Uint() ) case reflect.Float64, reflect.Float32: m[tag] = fmt.Sprintf( "%f", p.Float() ) case reflect.Bool: m[tag] = fmt.Sprintf( "%v", p.Bool() ) case reflect.Struct: struct_to_map( p, p.Type(), tag_id, m, pfx + tag + "/" ) // recurse to process with a prefix which matches the field default: fmt.Fprintf( os.Stderr, "transform: ptr of this kind is not handled: %s\n", p.Kind() ) } case reflect.Uintptr: p := thing.Elem() m[tag] = fmt.Sprintf( "%d", p.Uint() ) case reflect.Int, reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8: m[tag] = fmt.Sprintf( "%d", thing.Int() ) case reflect.Uint, reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8: m[tag] = fmt.Sprintf( "%d", thing.Uint() ) case reflect.Float64, reflect.Float32: m[tag] = fmt.Sprintf( "%f", thing.Float() ) case reflect.Bool: m[tag] = fmt.Sprintf( "%v", thing.Bool() ) case reflect.Struct: if anon { struct_to_map( thing, thing.Type(), tag_id, m, pfx ) // recurse to process; anonymous fields share this level namespace } else { struct_to_map( thing, thing.Type(), tag_id, m, tag + "/" ) // recurse to process; tag becomes the prefix } case reflect.Slice: length := thing.Len() capacity := thing.Cap() mtag := fmt.Sprintf( "%s.cap", tag ) // set capacity and length of the slice m[mtag] = fmt.Sprintf( "%d", capacity ) mtag = fmt.Sprintf( "%s.len", tag ) m[mtag] = fmt.Sprintf( "%d", length ) for j := 0; j < length; j++ { v := thing.Slice( j, j+1 ) // value struct for the jth element (which will be a slice too :( vk := v.Type().Elem().Kind() // must drill down for the kind new_tag := fmt.Sprintf( "%s/%d", tag, j ) insert_value( thing.Index( j ), vk, false, new_tag, tag_id, m, "" ) // prefix already on the tag, the 'index' changes as we go through the slice } case reflect.Map: keys := thing.MapKeys() // list of all of the keys (values) for _, key := range keys { vk := thing.Type().Elem().Kind() // must drill down for the kind new_tag := fmt.Sprintf( "%s/%s", tag, key ) insert_value( thing.MapIndex( key ), vk, false, new_tag, tag_id, m, pfx ) // prefix stays the same, just gets a new tag } case reflect.Interface: p := thing.Elem() insert_value( p, p.Kind(), anon, tag, tag_id, m, "" ) // tag stays the same, so pfx is empty default: //fmt.Fprintf( os.Stderr, "transform: stm: field cannot be captured in a map: tag=%s type=%s val=%s\n", tag, thing.Kind(), reflect.ValueOf( thing ) ) } } /* We require the initial 'thing' passed to be a struct, this then is the real entry point, but is broken so that it can be recursively called as we encounter structs in the insert code. */ func struct_to_map( thing reflect.Value, imeta reflect.Type, tag_id string, m map[string]string, pfx string ) ( map[string]string ) { if thing.Kind() != reflect.Struct { return m } if m == nil { m = make( map[string]string ) } for i := 0; i < thing.NumField(); i++ { f := thing.Field( i ) // get the _value_ of the ith field fmeta := imeta.Field( i ) // get the ith field's metadata from Type (a struct_type) ftag := fmeta.Tag.Get( tag_id ) // get the field's datacache tag if ftag == "_" || tag_id == "_" { ftag = fmeta.Name } if ftag != "" || fmeta.Anonymous { // process all structs regardless of tag insert_value( f, f.Kind(), fmeta.Anonymous, ftag, tag_id, m, pfx ) } } return m }
transform/tomap.go
0.592549
0.46132
tomap.go
starcoder
package statistics import ( "encoding/binary" types "github.com/zhukovaskychina/xmysql-server/server/innodb/basic" "github.com/zhukovaskychina/xmysql-server/server/mysql" "math" ) // calcFraction is used to calculate the fraction of the interval [lower, upper] that lies within the [lower, value] // using the continuous-value assumption. func calcFraction(lower, upper, value float64) float64 { if upper <= lower { return 0.5 } if value <= lower { return 0 } if value >= upper { return 1 } frac := (value - lower) / (upper - lower) if math.IsNaN(frac) || math.IsInf(frac, 0) || frac < 0 || frac > 1 { return 0.5 } return frac } // preCalculateDatumScalar converts the lower and upper to scalar. When the datum type is KindString or KindBytes, we also // calculate their common prefix length, because when a value falls between lower and upper, the common prefix // of lower and upper equals to the common prefix of the lower, upper and the value. func preCalculateDatumScalar(lower, upper *types.Datum) (float64, float64, int) { common := 0 if lower.Kind() == types.KindString || lower.Kind() == types.KindBytes { common = commonPrefixLength(lower.GetBytes(), upper.GetBytes()) } return convertDatumToScalar(lower, common), convertDatumToScalar(upper, common), common } func convertDatumToScalar(value *types.Datum, commonPfxLen int) float64 { switch value.Kind() { case types.KindFloat32: return float64(value.GetFloat32()) case types.KindFloat64: return value.GetFloat64() case types.KindInt64: return float64(value.GetInt64()) case types.KindUint64: return float64(value.GetUint64()) case types.KindMysqlDecimal: scalar, err := value.GetMysqlDecimal().ToFloat64() if err != nil { return 0 } return scalar case types.KindMysqlDuration: return float64(value.GetMysqlDuration().Duration) case types.KindMysqlTime: valueTime := value.GetMysqlTime() var minTime types.Time switch valueTime.Type { case mysql.TypeDate: minTime = types.Time{ Time: types.MinDatetime, Type: mysql.TypeDate, Fsp: types.DefaultFsp, } case mysql.TypeDatetime: minTime = types.Time{ Time: types.MinDatetime, Type: mysql.TypeDatetime, Fsp: types.DefaultFsp, } case mysql.TypeTimestamp: minTime = types.Time{ Time: types.MinTimestamp, Type: mysql.TypeTimestamp, Fsp: types.DefaultFsp, } } return float64(valueTime.Sub(&minTime).Duration) case types.KindString, types.KindBytes: bytes := value.GetBytes() if len(bytes) <= commonPfxLen { return 0 } return convertBytesToScalar(bytes[commonPfxLen:]) default: // do not know how to convert return 0 } } func commonPrefixLength(lower, upper []byte) int { minLen := len(lower) if minLen > len(upper) { minLen = len(upper) } for i := 0; i < minLen; i++ { if lower[i] != upper[i] { return i } } return minLen } func convertBytesToScalar(value []byte) float64 { // Bytes type is viewed as a base-256 value, so we only consider at most 8 bytes. var buf [8]byte copy(buf[:], value) return float64(binary.BigEndian.Uint64(buf[:])) }
server/innodb/statistics/scalar.go
0.802594
0.499329
scalar.go
starcoder
package hash import ( "fmt" "math/big" "math/rand" "reflect" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common/hexutil" ) const ( // HashLength is the expected length of the hash HashLength = 32 ) var ( // Zero is an empty hash. Zero = Hash{} hashT = reflect.TypeOf(Hash{}) ) // Hash represents the 32 byte hash of arbitrary data. type Hash [HashLength]byte // BytesToHash sets b to hash. // If b is larger than len(h), b will be cropped from the left. func BytesToHash(b []byte) Hash { var h Hash h.SetBytes(b) return h } // BigToHash sets byte representation of b to hash. // If b is larger than len(h), b will be cropped from the left. func BigToHash(b *big.Int) Hash { return BytesToHash(b.Bytes()) } // HexToHash sets byte representation of s to hash. // If b is larger than len(h), b will be cropped from the left. func HexToHash(s string) Hash { return BytesToHash(hexutil.MustDecode(s)) } // Bytes gets the byte representation of the underlying hash. func (h Hash) Bytes() []byte { return h[:] } // Big converts a hash to a big integer. func (h Hash) Big() *big.Int { return new(big.Int).SetBytes(h[:]) } // Hex converts a hash to a hex string. func (h Hash) Hex() string { return hexutil.Encode(h[:]) } // TerminalString implements log.TerminalStringer, formatting a string for console // output during logging. func (h Hash) TerminalString() string { return fmt.Sprintf("%x…%x", h[:3], h[29:]) } // String implements the stringer interface and is used also by the logger when // doing full logging into a file. func (h Hash) String() string { return h.Hex() } // Format implements fmt.Formatter, forcing the byte slice to be formatted as is, // without going through the stringer interface used for logging. func (h Hash) Format(s fmt.State, c rune) { fmt.Fprintf(s, "%"+string(c), h[:]) } // UnmarshalText parses a hash in hex syntax. func (h *Hash) UnmarshalText(input []byte) error { return hexutil.UnmarshalFixedText("Hash", input, h[:]) } // UnmarshalJSON parses a hash in hex syntax. func (h *Hash) UnmarshalJSON(input []byte) error { return hexutil.UnmarshalFixedJSON(hashT, input, h[:]) } // MarshalText returns the hex representation of h. func (h Hash) MarshalText() ([]byte, error) { return hexutil.Bytes(h[:]).MarshalText() } // SetBytes sets the hash to the value of b. // If b is larger than len(h), b will be cropped from the left. func (h *Hash) SetBytes(b []byte) { if len(b) > len(h) { b = b[len(b)-HashLength:] } copy(h[HashLength-len(b):], b) } // FakeHash generates random fake hash for testing purpose. func FakeHash(seed ...int64) (h common.Hash) { randRead := rand.Read if len(seed) > 0 { src := rand.NewSource(seed[0]) rnd := rand.New(src) randRead = rnd.Read } _, err := randRead(h[:]) if err != nil { panic(err) } return }
hash/hash.go
0.778649
0.459379
hash.go
starcoder
package modulation import ( "fmt" "math" "math/rand" "github.com/Hunter-Dolan/midrange/options" ) type Modulator struct { Options *options.Options carrierCount int carrierSpacing float64 data *[]bool dataLength int frameCount int frameIndex int CachedWave *[]float64 } func (m *Modulator) SetData(data *[]bool) { m.data = data m.setup() } func (m *Modulator) NextWave() *[]float64 { frame := m.buildFrame(m.frameIndex) m.frameIndex++ return frame.wave() } func (m *Modulator) FullWave() []float64 { if m.CachedWave == nil { numberOfFrames := int64(m.FrameCount()) sampleRate := int64(m.Options.Kilobitrate * 1000) numberOfSamplesPerFrame := int64(float64(sampleRate) * (float64(m.Options.FrameDuration) / float64(1000.0))) offsetSamples := numberOfSamplesPerFrame numberOfSamples := (numberOfSamplesPerFrame * numberOfFrames) if options.OffsetGroups != 1 { numberOfSamples = (numberOfSamplesPerFrame * numberOfFrames) + offsetSamples } fullWave := make([]float64, numberOfSamples) carrierData := make([][]float64, m.carrierCount) ts := 1 / float64(sampleRate) for i := int(0); i < int(numberOfFrames); i++ { frame := m.buildFrame(i) for carrierIndex, freq := range frame.allCarriers() { carrierData[carrierIndex] = append(carrierData[carrierIndex], freq) } } scaler := float64(math.Pow(2, float64(options.BitDepth-2))) signalScaler := scaler guard := int64(numberOfSamplesPerFrame - (numberOfSamplesPerFrame / options.GuardDivisor)) fmt.Println("Generating Phases") for phase := int64(0); phase < numberOfSamples; phase++ { amplitude := float64(0.0) carrierCount := 0 if phase%10000 == 0 { fmt.Println("Phase:", phase, int((float64(phase)/float64(numberOfSamples))*100.0), "%") } for carrierIndex, frequencies := range carrierData { offsetIndex := int64(carrierIndex % options.OffsetGroups) carrierOffset := int64(0) if offsetIndex != 0 { carrierOffset = int64(int64(offsetSamples/(options.OffsetGroups)) * int64(offsetIndex)) } frequencyIndex := phase - carrierOffset if frequencyIndex >= 0 && frequencyIndex < (numberOfSamplesPerFrame*numberOfFrames) { frameIndex := frequencyIndex / numberOfSamplesPerFrame frequency := frequencies[frameIndex] if frequency != -1.0 && frequencyIndex < ((frameIndex+1)*numberOfSamplesPerFrame)-guard { amplitude += (math.Sin(float64(phase) * ts * frequency * 2 * (math.Pi))) carrierCount++ } } } if carrierCount != 0 { amplitude = amplitude / float64(carrierCount) } noise := float64(0) scaler := float64(signalScaler) if m.Options.NoiseLevel != 0 { noiseAmplitude := (scaler / float64(100.0)) * float64(m.Options.NoiseLevel) scaler = scaler - noiseAmplitude noise = noiseAmplitude * rand.Float64() } fullWave[phase] = (amplitude * scaler) + noise } fmt.Println("wave generated") m.CachedWave = &fullWave } return *m.CachedWave } func (m *Modulator) Reset() { m.frameIndex = 0 } func (m *Modulator) FrameCount() int { return m.frameCount } func (m *Modulator) setup() { m.carrierSpacing = float64(m.Options.OMFSKConstant) / (float64(m.Options.FrameDuration) / 1000.0) m.carrierCount = int(math.Floor(float64(m.Options.Bandwidth) / m.carrierSpacing)) m.dataLength = len(*m.data) m.frameCount = int(math.Ceil(float64(m.dataLength)/float64(m.carrierCount)) + 2) m.frameIndex = 0 fmt.Println((m.carrierCount * (1000 / m.Options.FrameDuration)), "baud") } func (m *Modulator) buildHeaderFrame(frameIndex int) frame { data := make([]bool, m.carrierCount) for i := 0; i < m.carrierCount; i++ { data[i] = i%2 == frameIndex } f := frame{} f.data = data f.carrierSpacing = m.carrierSpacing f.frameIndex = frameIndex f.options = m.Options f.header = true return f } func (m Modulator) buildFrame(frameIndex int) frame { if frameIndex <= 1 { return m.buildHeaderFrame(frameIndex) } leftEnd := m.carrierCount * (frameIndex - 2) rightEnd := int(leftEnd + m.carrierCount) if rightEnd > m.dataLength { rightEnd = m.dataLength - 1 } data := (*m.data)[leftEnd:rightEnd] f := frame{} f.data = data //fmt.Println(data) f.carrierSpacing = m.carrierSpacing f.frameIndex = frameIndex f.options = m.Options return f }
modulation/modulator.go
0.677901
0.421909
modulator.go
starcoder
package rgba4444 import ( "image" "image/color" ) // Image is an in-memory image whose At method returns rgba4444.Color values. type Image struct { // (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*2]. Pix []uint8 // Stride is the Pix stride (in bytes) between vertically adjacent pixels. Stride int // Rect is the image's bounds. Rect image.Rectangle } func New(r image.Rectangle) *Image { w, h := r.Dx(), r.Dy() pix := make([]uint8, 2*w*h) return &Image{pix, 2 * w, r} } func (p *Image) ColorModel() color.Model { return Model } func (p *Image) Bounds() image.Rectangle { return p.Rect } func (p *Image) At(x, y int) color.Color { return p.RGBA4444At(x, y) } func (p *Image) RGBA4444At(x, y int) Color { if !(image.Point{x, y}.In(p.Rect)) { return Color{} } i := p.PixOffset(x, y) return Color{ uint8(p.Pix[i+0] >> 4), uint8(p.Pix[i+0] & 0x0F), uint8(p.Pix[i+1] >> 4), uint8(p.Pix[i+1] & 0x0F), } } // PixOffset returns the index of the first element of Pix that corresponds to // the pixel at (x, y). func (p *Image) PixOffset(x, y int) int { return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*2 } func (p *Image) Set(x, y int, c color.Color) { if !(image.Point{x, y}.In(p.Rect)) { return } i := p.PixOffset(x, y) c1 := Model.Convert(c).(Color) p.Pix[i+0] = (c1.R << 4) | (c1.G & 0x0F) p.Pix[i+1] = (c1.B << 4) | (c1.A & 0x0F) } func (p *Image) SetRGBA4444(x, y int, c Color) { if !(image.Point{x, y}.In(p.Rect)) { return } i := p.PixOffset(x, y) p.Pix[i+0] = (c.R << 4) | (c.G & 0x0F) p.Pix[i+1] = (c.B << 4) | (c.A & 0x0F) } // SubImage returns an image representing the portion of the image p visible // through r. The returned value shares pixels with the original image. func (p *Image) SubImage(r image.Rectangle) image.Image { r = r.Intersect(p.Rect) if r.Empty() { return &Image{} } i := p.PixOffset(r.Min.X, r.Min.Y) return &Image{ Pix: p.Pix[i:], Stride: p.Stride, Rect: r, } } // Opaque scans the entire image and reports whether it is fully opaque. func (p *Image) Opaque() bool { if p.Rect.Empty() { return true } i0, i1 := 1, p.Rect.Dx()*2 for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ { for i := i0; i < i1; i += 2 { if (p.Pix[i] & 0x0F) != 0x0F { return false } } i0 += p.Stride i1 += p.Stride } return true }
image.go
0.811078
0.517937
image.go
starcoder
// Package pktline reads and writes the pkt-line format described in // https://git-scm.com/docs/protocol-common#_pkt_line_format. package pktline import ( "encoding/hex" "fmt" "io" ) // MaxSize is the maximum number of bytes permitted in a single pkt-line. const MaxSize = 65516 // Type indicates the type of a packet. type Type int8 // Packet types. const ( // Flush indicates the end of a message. Flush Type = 0 // Delim indicates the end of a section in the Version 2 protocol. // https://git-scm.com/docs/protocol-v2#_packet_line_framing Delim Type = 1 // Data indicates a packet with data. Data Type = 4 ) // Reader reads pkt-lines from an io.Reader object. It does not perform any // internal buffering and does not read any more bytes than requested. type Reader struct { r io.Reader typ Type buf []byte err error } // NewReader returns a new Reader that reads from r. func NewReader(r io.Reader) *Reader { return &Reader{ r: r, buf: make([]byte, 0, 1024), } } // Next advances the Reader to the next pkt-line, which will then be available // through the Bytes or Text methods. It returns false when the Reader // encounters an error. After Next returns false, the Err method will return any // error that occurred while reading. func (pr *Reader) Next() bool { if pr.err != nil { return false } pr.typ, pr.buf, pr.err = read(pr.r, pr.buf) return pr.err == nil } func read(r io.Reader, buf []byte) (_ Type, _ []byte, err error) { var lengthHex [4]byte if _, err := io.ReadFull(r, lengthHex[:]); err != nil { if err == io.EOF { err = io.ErrUnexpectedEOF } return Flush, buf[:0], fmt.Errorf("read packet line: %w", err) } var length [2]byte if _, err := hex.Decode(length[:], lengthHex[:]); err != nil { return Flush, buf[:0], fmt.Errorf("read packet line: invalid length: %w", err) } switch { case length[0] == 0 && length[1] == 0: return Flush, buf[:0], nil case length[0] == 0 && length[1] == 1: return Delim, buf[:0], nil case length[0] == 0 && length[1] < byte(len(lengthHex)): return Flush, buf[:0], fmt.Errorf("read packet line: invalid length %q", lengthHex) } n := int(length[0])<<8 | int(length[1]) - len(lengthHex) if n == 0 { // "Implementations SHOULD NOT send an empty pkt-line ("0004")." // ... but we're here for it. return Data, buf[:0], nil } if n > MaxSize { return Flush, buf[:0], fmt.Errorf("read packet line: invalid length %q", lengthHex) } if n > cap(buf) { buf = make([]byte, n) } else { buf = buf[:n] } if _, err := io.ReadFull(r, buf); err != nil { if err == io.EOF { err = io.ErrUnexpectedEOF } return Flush, buf[:0], fmt.Errorf("read packet line: %w", err) } return Data, buf, nil } // Type returns the type of the most recent packet read by a call to Next. func (pr *Reader) Type() Type { return pr.typ } // Err returns the first error encountered by the Reader. func (pr *Reader) Err() error { return pr.err } // Bytes returns the data of the most recent packet read by a call to Next. // It returns an error if Next returned false or the most recent packet is not // a Data packet. The underlying array may point to data that will be // overwritten by a subsequent call to Next. func (pr *Reader) Bytes() ([]byte, error) { if pr.err != nil { return nil, pr.err } if pr.typ != Data { return nil, fmt.Errorf("unexpected packet (want %d, got %d)", Data, pr.typ) } return pr.buf, nil } // Text returns the data of the most recent packet read by a call to Next, // stripping the trailing line-feed ('\n') if present. It returns an error if // Next returned false or the most recent packet is not a Data packet. // The underlying array may point to data that will be overwritten by a // subsequent call to Next. func (pr *Reader) Text() ([]byte, error) { data, err := pr.Bytes() return trimLF(data), err } func trimLF(line []byte) []byte { if len(line) == 0 || line[len(line)-1] != '\n' { return line } return line[:len(line)-1] } // Append appends a data-pkt to dst with the given data. It panics if // len(line) == 0 or len(line) > MaxSize. func Append(dst []byte, line []byte) []byte { if len(line) == 0 { panic("empty pkt-line") } if len(line) > MaxSize { panic("pkt-line too large") } n := len(line) + 4 dst = append(dst, hexDigits[n>>12], hexDigits[n>>8&0xf], hexDigits[n>>4&0xf], hexDigits[n&0xf], ) dst = append(dst, line...) return dst } // AppendString appends a data-pkt to dst with the given data. It panics if // len(line) == 0 or len(line) > MaxSize. func AppendString(dst []byte, line string) []byte { if len(line) == 0 { panic("empty pkt-line") } if len(line) > MaxSize { panic("pkt-line too large") } n := len(line) + 4 dst = append(dst, hexDigits[n>>12], hexDigits[n>>8&0xf], hexDigits[n>>4&0xf], hexDigits[n&0xf], ) dst = append(dst, line...) return dst } // AppendFlush appends a flush-pkt to dst. func AppendFlush(dst []byte) []byte { return append(dst, "0000"...) } // AppendDelim appends a delim-pkt to dst. func AppendDelim(dst []byte) []byte { return append(dst, "0001"...) } const hexDigits = "0123456789abcdef"
internal/pktline/pktline.go
0.696681
0.467332
pktline.go
starcoder
package oak import ( "image" "image/draw" ) // A Background can be used as a background draw layer. Backgrounds will be drawn as the first // element in each frame, and are expected to cover up data drawn on the previous frame. type Background interface { GetRGBA() *image.RGBA } // DrawLoop // Unless told to stop, the draw channel will repeatedly // 1. draw the background color to a temporary buffer // 2. draw all visible rendered elements onto the temporary buffer. // 3. draw the buffer's data at the viewport's position to the screen. // 4. publish the screen to display in window. func (w *Window) drawLoop() { <-w.drawCh draw.Draw(w.winBuffers[w.bufferIdx].RGBA(), w.winBuffers[w.bufferIdx].Bounds(), w.bkgFn(), zeroPoint, draw.Src) w.publish() drawFrame := func() { buff := w.winBuffers[w.bufferIdx] if buff.RGBA() != nil { // Publish what was drawn last frame to screen, then work on preparing the next frame. w.publish() draw.Draw(buff.RGBA(), buff.Bounds(), w.bkgFn(), zeroPoint, draw.Src) w.DrawStack.PreDraw() p := w.viewPos w.DrawStack.DrawToScreen(buff.RGBA(), &p, w.ScreenWidth, w.ScreenHeight) } } drawLoadingFrame := func() { buff := w.winBuffers[w.bufferIdx] w.publish() draw.Draw(buff.RGBA(), w.winBuffers[w.bufferIdx].Bounds(), w.bkgFn(), zeroPoint, draw.Src) if w.LoadingR != nil { w.LoadingR.Draw(w.winBuffers[w.bufferIdx].RGBA(), 0, 0) } } if w.config.UnlimitedDrawFrameRate { // this code is duplicated as an optimization: it's much faster // to have a 'default' case than to flood a channel, and we can't conditionally // add a default case to a select. for { select { case <-w.quitCh: return case <-w.drawCh: <-w.drawCh loadingSelectUnlimited: for { select { case <-w.quitCh: return case <-w.drawCh: break loadingSelectUnlimited case <-w.animationFrame: drawLoadingFrame() case <-w.DrawTicker.C: drawLoadingFrame() default: drawLoadingFrame() } } case f := <-w.betweenDrawCh: f() case <-w.animationFrame: drawFrame() case <-w.DrawTicker.C: drawFrame() default: drawFrame() } } } for { select { case <-w.quitCh: return case <-w.drawCh: <-w.drawCh loadingSelect: for { select { case <-w.quitCh: return case <-w.drawCh: break loadingSelect case <-w.animationFrame: drawLoadingFrame() case <-w.DrawTicker.C: drawLoadingFrame() } } case f := <-w.betweenDrawCh: f() case <-w.animationFrame: drawFrame() case <-w.DrawTicker.C: drawFrame() } } } func (w *Window) publish() { w.prePublish(w.winBuffers[w.bufferIdx].RGBA()) w.windowTextures[w.bufferIdx].Upload(zeroPoint, w.winBuffers[w.bufferIdx], w.winBuffers[w.bufferIdx].Bounds()) w.Window.Scale(w.windowRect, w.windowTextures[w.bufferIdx], w.windowTextures[w.bufferIdx].Bounds(), draw.Src) w.Window.Publish() // every frame, swap buffers. This enables drivers which might hold on to the rgba buffers we publish as if they // were immutable. w.bufferIdx = (w.bufferIdx + 1) % bufferCount } // DoBetweenDraws will execute the given function in-between draw frames. It will prevent draws from happening until // the provided function has terminated. DoBetweenDraws will block until the provided function is called within the // draw loop's schedule, but will not wait for that function itself to terminate. func (w *Window) DoBetweenDraws(f func()) { w.betweenDrawCh <- f }
drawLoop.go
0.631367
0.482185
drawLoop.go
starcoder
package chapter3 import ( "fmt" ) /* Three in One: Describe how you could use a single array to implement three stacks. Hint #2: A stack is simply a data structure in which the most recently added elements are removed first. Can you simulate a single stack using an array? Remember that there are many possible solutions, and there are tradeoffs of each. Hint #12: We could simulate three stacks in an array by just allocating the first third of the array to the first stack, the second third to the second stack, and the final third to the third stack. One might actually be much bigger than the others, though. Can we be more flexible with the divisions? Hint #38: If you want to allow for flexible divisions, you can shift stacks around. Can you ensure that all available capacity is used? Hint #58: Try thinking about the array as circular, such that the end of the array "wraps around" to the start of the array. */ //NewThreeStackArray Initialises a three array stack with the individual stack capacity provided. func NewThreeStackArray() *ThreeStackArray { return &ThreeStackArray{ stackCapacity: 33, array: [99]int{}, sizes: [3]int{}, } } //ThreeStackArray implements three separate stacks using a single underlying array. type ThreeStackArray struct { stackCapacity int array [99]int sizes [3]int } func (t *ThreeStackArray) pop(stack int) (int, error) { if !t.isValidStack(stack) { return 0, fmt.Errorf("stack %d is not a valid stack", stack) } if t.isEmpty(stack) { return 0, fmt.Errorf("stack %d is empty", stack) } target := t.array[t.stackIndex(stack)] t.array[t.stackIndex(stack)] = 0 t.sizes[stack]-- return target, nil } func (t *ThreeStackArray) push(stack, target int) error { if !t.isValidStack(stack) { return fmt.Errorf("stack %d is not a valid stack", stack) } if t.isFull(stack) { return fmt.Errorf("stack %d is full", stack) } t.sizes[stack]++ t.array[t.stackIndex(stack)] = target return nil } func (t *ThreeStackArray) peek(stack int) (int, error) { if t.isEmpty(stack) { return 0, fmt.Errorf("stack %d is empty", stack) } return t.array[t.stackIndex(stack)], nil } //Aux/helper functions func (t *ThreeStackArray) stackIndex(stackNum int) int { offset := t.stackCapacity * stackNum size := t.sizes[stackNum] return offset + size - 1 } func (t *ThreeStackArray) isFull(stack int) bool { return t.sizes[stack] == t.stackCapacity } func (t *ThreeStackArray) isEmpty(stack int) bool { return t.sizes[stack] == 0 } func (t *ThreeStackArray) isValidStack(stack int) bool { return stack >= 0 && stack < 3 }
chapter3/q3.1.go
0.788339
0.804291
q3.1.go
starcoder
package merkle import ( "bytes" "crypto/sha256" "github.com/33cn/chain33/types" ) /* WARNING! If you're reading this because you're learning about crypto and/or designing a new system that will use merkle trees, keep in mind that the following merkle tree algorithm has a serious flaw related to duplicate txids, resulting in a vulnerability (CVE-2012-2459). The reason is that if the number of hashes in the list at a given time is odd, the last one is duplicated before computing the next level (which is unusual in Merkle trees). This results in certain sequences of transactions leading to the same merkle root. For example, these two trees: A A / \ / \ B C B C / \ | / \ / \ D E F D E F F / \ / \ / \ / \ / \ / \ / \ 1 2 3 4 5 6 1 2 3 4 5 6 5 6 for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and 6 are repeated) result in the same root hash A (because the hash of both of (F) and (F,F) is C). The vulnerability results from being able to send a block with such a transaction list, with the same merkle root, and the same block hash as the original without duplication, resulting in failed validation. If the receiving node proceeds to mark that block as permanently invalid however, it will fail to accept further unmodified (and thus potentially valid) versions of the same block. We defend against this by detecting the case where we would hash two identical hashes at the end of the list together, and treating that identically to the block having an invalid merkle root. Assuming no double-SHA256 collisions, this will detect all known ways of changing the transactions without affecting the merkle root. */ /*Computation This implements a constant-space merkle root/path calculator, limited to 2^32 leaves. */ //flage =1 只计算roothash flage =2 只计算branch flage =3 计算roothash 和 branch func Computation(leaves [][]byte, flage int, branchpos uint32) (roothash []byte, mutated bool, pbranch [][]byte) { if len(leaves) == 0 { return nil, false, nil } if flage < 1 || flage > 3 { return nil, false, nil } var count int var branch [][]byte var level uint32 var h []byte inner := make([][]byte, 32) var matchlevel uint32 = 0xff mutated = false var matchh bool for count, h = range leaves { if (uint32(count) == branchpos) && (flage&2) != 0 { matchh = true } else { matchh = false } count++ // 1左移level位 for level = 0; 0 == ((count) & (1 << level)); level++ { //需要计算branch if (flage & 2) != 0 { if matchh { branch = append(branch, inner[level]) } else if matchlevel == level { branch = append(branch, h) matchh = true } } if bytes.Equal(inner[level], h) { mutated = true } //计算inner[level] + h 的hash值 h = GetHashFromTwoHash(inner[level], h) } inner[level] = h if matchh { matchlevel = level } } for level = 0; 0 == (count & (1 << level)); level++ { } h = inner[level] matchh = matchlevel == level for count != (1 << level) { if (flage&2) != 0 && matchh { branch = append(branch, h) } h = GetHashFromTwoHash(h, h) count += (1 << level) level++ // And propagate the result upwards accordingly. for 0 == (count & (1 << level)) { if (flage & 2) != 0 { if matchh { branch = append(branch, inner[level]) } else if matchlevel == level { branch = append(branch, h) matchh = true } } h = GetHashFromTwoHash(inner[level], h) level++ } } return h, mutated, branch } //GetHashFromTwoHash 计算左右节点hash的父hash func GetHashFromTwoHash(left []byte, right []byte) []byte { if left == nil || right == nil { return nil } leftlen := len(left) rightlen := len(right) parent := make([]byte, leftlen+rightlen) copy(parent, left) copy(parent[leftlen:], right) hash := sha256.Sum256(parent) parenthash := sha256.Sum256(hash[:]) return parenthash[:] } //GetMerkleRoot 获取merkle roothash func GetMerkleRoot(leaves [][]byte) (roothash []byte) { if leaves == nil { return nil } proothash, _, _ := Computation(leaves, 1, 0) return proothash } //GetMerkleBranch 获取指定txindex的branch position 从0开始 func GetMerkleBranch(leaves [][]byte, position uint32) [][]byte { _, _, branchs := Computation(leaves, 2, position) return branchs } //GetMerkleRootFromBranch 通过branch 获取对应的roothash 用于指定txhash的proof证明 func GetMerkleRootFromBranch(merkleBranch [][]byte, leaf []byte, Index uint32) []byte { hash := leaf for _, branch := range merkleBranch { if (Index & 1) != 0 { hash = GetHashFromTwoHash(branch, hash) } else { hash = GetHashFromTwoHash(hash, branch) } Index >>= 1 } return hash } //GetMerkleRootAndBranch 获取merkle roothash 以及指定tx index的branch,注释:position从0开始 func GetMerkleRootAndBranch(leaves [][]byte, position uint32) (roothash []byte, branchs [][]byte) { roothash, _, branchs = Computation(leaves, 3, position) return } var zeroHash [32]byte //CalcMerkleRoot 计算merkle树根 func CalcMerkleRoot(txs []*types.Transaction) []byte { var hashes [][]byte for _, tx := range txs { hashes = append(hashes, tx.Hash()) } if hashes == nil { return zeroHash[:] } merkleroot := GetMerkleRoot(hashes) if merkleroot == nil { panic("calc merkle root error") } return merkleroot } //CalcMerkleRootCache 计算merkle树根缓存 func CalcMerkleRootCache(txs []*types.TransactionCache) []byte { var hashes [][]byte for _, tx := range txs { hashes = append(hashes, tx.Hash()) } if hashes == nil { return zeroHash[:] } merkleroot := GetMerkleRoot(hashes) if merkleroot == nil { panic("calc merkle root error") } return merkleroot }
vendor/github.com/33cn/chain33/common/merkle/merkle.go
0.510496
0.507202
merkle.go
starcoder
package gglm import ( "fmt" ) var _ Mat = &Mat2{} var _ fmt.Stringer = &Mat2{} type Mat2 struct { Data [2][2]float32 } func (m *Mat2) Get(row, col int) float32 { return m.Data[col][row] } func (m *Mat2) Set(row, col int, val float32) { m.Data[col][row] = val } func (m *Mat2) Size() MatSize { return MatSize2x2 } func (m *Mat2) String() string { //+ always shows +/- sign; - means pad to the right; 9 means total of 9 digits (or padding if less); .3 means 3 decimals return fmt.Sprintf("\n| %+-9.3f %+-9.3f |\n| %+-9.3f %+-9.3f |\n", m.Data[0][0], m.Data[0][1], m.Data[1][0], m.Data[1][1]) } func (m *Mat2) Col(c int) *Vec2 { return &Vec2{Data: m.Data[c]} } //Add m += m2 func (m *Mat2) Add(m2 *Mat2) *Mat2 { m.Data[0][0] += m2.Data[0][0] m.Data[0][1] += m2.Data[0][1] m.Data[1][0] += m2.Data[1][0] m.Data[1][1] += m2.Data[1][1] return m } //Add m -= m2 func (m *Mat2) Sub(m2 *Mat2) *Mat2 { m.Data[0][0] -= m2.Data[0][0] m.Data[0][1] -= m2.Data[0][1] m.Data[1][0] -= m2.Data[1][0] m.Data[1][1] -= m2.Data[1][1] return m } //Mul m *= m2 func (m1 *Mat2) Mul(m2 *Mat2) *Mat2 { m1.Data = [2][2]float32{ { m1.Data[0][0]*m2.Data[0][0] + m1.Data[1][0]*m2.Data[0][1], m1.Data[0][1]*m2.Data[0][0] + m1.Data[1][1]*m2.Data[0][1], }, { m1.Data[0][0]*m2.Data[1][0] + m1.Data[1][0]*m2.Data[1][1], m1.Data[0][1]*m2.Data[1][0] + m1.Data[1][1]*m2.Data[1][1], }, } return m1 } //Scale m *= x (element wise multiplication) func (m *Mat2) Scale(x float32) *Mat2 { m.Data[0][0] *= x m.Data[0][1] *= x m.Data[1][0] *= x m.Data[1][1] *= x return m } func (v *Mat2) Clone() *Mat2 { return &Mat2{Data: v.Data} } func (m *Mat2) Eq(m2 *Mat2) bool { return m.Data == m2.Data } //AddMat2 m3 = m1 + m2 func AddMat2(m1, m2 *Mat2) *Mat2 { return &Mat2{ Data: [2][2]float32{ { m1.Data[0][0] + m2.Data[0][0], m1.Data[0][1] + m2.Data[0][1], }, { m1.Data[1][0] + m2.Data[1][0], m1.Data[1][1] + m2.Data[1][1], }, }, } } //SubMat2 m3 = m1 - m2 func SubMat2(m1, m2 *Mat2) *Mat2 { return &Mat2{ Data: [2][2]float32{ { m1.Data[0][0] - m2.Data[0][0], m1.Data[0][1] - m2.Data[0][1], }, { m1.Data[1][0] - m2.Data[1][0], m1.Data[1][1] - m2.Data[1][1], }, }, } } //MulMat2 m3 = m1 * m2 func MulMat2(m1, m2 *Mat2) *Mat2 { return &Mat2{ Data: [2][2]float32{ { m1.Data[0][0]*m2.Data[0][0] + m1.Data[1][0]*m2.Data[0][1], m1.Data[0][1]*m2.Data[0][0] + m1.Data[1][1]*m2.Data[0][1], }, { m1.Data[0][0]*m2.Data[1][0] + m1.Data[1][0]*m2.Data[1][1], m1.Data[0][1]*m2.Data[1][0] + m1.Data[1][1]*m2.Data[1][1], }, }, } } //MulMat2Vec2 v2 = m1 * v1 func MulMat2Vec2(m1 *Mat2, v1 *Vec2) *Vec2 { return &Vec2{ Data: [2]float32{ m1.Data[0][0]*v1.Data[0] + m1.Data[1][0]*v1.Data[1], m1.Data[0][1]*v1.Data[0] + m1.Data[1][1]*v1.Data[1], }, } } //NewMat2Id returns the 2x2 identity matrix func NewMat2Id() *Mat2 { return &Mat2{ Data: [2][2]float32{ {1, 0}, {0, 1}, }, } }
gglm/mat2.go
0.629547
0.486941
mat2.go
starcoder
package errorx // Trait is a static characteristic of an error type. // All errors of a specific type possess exactly the same traits. // Traits are both defined along with an error and inherited from a supertype and a namespace. type Trait struct { id uint64 label string } // RegisterTrait declares a new distinct traits. // Traits are matched exactly, distinct traits are considered separate event if they have the same label. func RegisterTrait(label string) Trait { return newTrait(label) } // HasTrait checks if an error possesses the expected trait. // Traits are always properties of a type rather than of an instance, so trait check is an alternative to a type check. // This alternative is preferable, though, as it is less brittle and generally creates less of a dependency. func HasTrait(err error, key Trait) bool { typedErr := Cast(err) if typedErr == nil { return false } return typedErr.HasTrait(key) } // Temporary is a trait that signifies that an error is temporary in nature. func Temporary() Trait { return traitTemporary } // Timeout is a trait that signifies that an error is some sort iof timeout. func Timeout() Trait { return traitTimeout } // NotFound is a trait that marks such an error where the requested object is not found. func NotFound() Trait { return traitNotFound } // Duplicate is a trait that marks such an error where an update is failed as a duplicate. func Duplicate() Trait { return traitDuplicate } // IsTemporary checks for Temporary trait. func IsTemporary(err error) bool { return HasTrait(err, Temporary()) } // IsTimeout checks for Timeout trait. func IsTimeout(err error) bool { return HasTrait(err, Timeout()) } // IsNotFound checks for NotFound trait. func IsNotFound(err error) bool { return HasTrait(err, NotFound()) } // IsDuplicate checks for Duplicate trait. func IsDuplicate(err error) bool { return HasTrait(err, Duplicate()) } var ( traitTemporary = RegisterTrait("temporary") traitTimeout = RegisterTrait("timeout") traitNotFound = RegisterTrait("not_found") traitDuplicate = RegisterTrait("duplicate") ) func newTrait(label string) Trait { return Trait{ id: nextInternalID(), label: label, } }
vendor/github.com/joomcode/errorx/trait.go
0.856347
0.586286
trait.go
starcoder