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 utils import ( "math" "math/rand" "sort" "time" ) func init() { rand.Seed(time.Now().UnixNano()) } //Gaussian returns the gaussien at zero func Gaussian(mean float64, std float64) float64 { return mean + std*gauassian() } func gauassian() float64 { //Polar method var x, y, z float64 for z >= 1 || z == 0 { x = (2 * rand.Float64()) - float64(1) y = (2 * rand.Float64()) - float64(1) z = x*x + y*y } return float64(x * math.Sqrt(-2*math.Log(z)/z)) } //RandWeightSet sets a randomweight based on min max values func RandWeightSet(mean, std, ninputelements float64) float64 { return Gaussian(mean, std) * (math.Sqrt((2.0) / (ninputelements))) } //RandomFloat32 returns a random float32 func RandomFloat32(floor, ceiling float32) float32 { return (rand.Float32() * (ceiling - floor)) + (floor) } //RandomFloat64 returns a random float64 func RandomFloat64(floor, ceiling float64) float64 { return (rand.Float64() * (ceiling - floor)) + (floor) } //NormalSortedGaussianVector sorts randomlygenerated vector of gaussian values that are then normalized func NormalSortedGaussianVector(length int) []float32 { slice := make([]float32, length) adder := float32(0.0) for i := 0; i < length; i++ { slice[i] = float32(gauassian()) adder += slice[i] } sort.Sort(f32slice(slice)) for i := range slice { slice[i] /= adder } return slice } //NormalGaussianVector randomlygenerated vector of gaussian values that are then normalized func NormalGaussianVector(length int) []float32 { slice := make([]float32, length) adder := float32(0.0) for i := 0; i < length; i++ { slice[i] = float32(gauassian()) adder += slice[i] } for i := range slice { slice[i] /= adder } return slice } //RandomSigmaGaussian2dKernel returns a randomly generated Gaussian 2d Kernal func RandomSigmaGaussian2dKernel(h, w int) []float32 { sigma := (rand.Float32() + 1) * float32(h+w) / 2 return Gaussian2dKernel(sigma, h, w) } //Gaussian2dKernel will return a func Gaussian2dKernel(sigma float32, h, w int) []float32 { mean := float64(h+w) / 4.0 //crewed radius sigma1 := float64(sigma) kernel := make([]float32, h*w) adder := float32(0.0) for i := 0; i < h; i++ { for j := 0; j < w; j++ { x := float64(i) y := float64(j) point := gaussiankern(x, mean, sigma1) * gaussiankern(y, mean, sigma1) kernel[i*w+j] = float32(point) adder += kernel[i*w+j] } } //now Normalize it for i := range kernel { kernel[i] /= adder } return kernel } func gaussiankern(x, mu, sig float64) float64 { a := (x - mu) / sig return math.Exp(-(a * a) / 2) } //RandomGaussianKernelsInChannels makes 2d GaussianKernels that are in the channels func RandomGaussianKernelsInChannels(h, w, c int, hwc bool) []float32 { kernels := make([]float32, 0, h*w*c) for i := 0; i < c; i++ { kernels = append(kernels, RandomSigmaGaussian2dKernel(h, w)...) } if hwc == false { return kernels } tensor := make([]float32, h*w*c) for i := 0; i < h; i++ { for j := 0; j < w; j++ { for k := 0; k < c; k++ { tensor[(i*w*c)+(j*c)+k] = kernels[(k*h*w)+(i*w)+j] } } } return tensor } type f32slice []float32 func (f f32slice) Len() int { return len(f) } func (f f32slice) Swap(i, j int) { f[i], f[j] = f[j], f[i] } func (f f32slice) Less(i, j int) bool { /*if f[i]<f[j]==true{ return true }*/ return f[i] < f[j] } func outerproductvol(v1, v2, v3 []float32) []float32 { output := make([]float32, len(v1)*len(v2)*len(v3)) a := len(v2) b := len(v3) for i := 0; i < len(v1); i++ { for j := 0; j < len(v2); j++ { for k := 0; k < len(v3); k++ { output[(i*a*b)+(j*b)+k] = v1[i] * v2[j] * v3[k] } } } return output } //Gaussian returns the gaussien at zero func gaussianstd3333() float32 { return float32(Gaussian(0, .3333)) }
utils/gaussian.go
0.787441
0.569254
gaussian.go
starcoder
package GoNeuralNetwork import "math" func sigmoid(input float64) float64 { inp := float64(int(input*10000)) / 10000 return 1.0 / (1.0 + math.Exp(-inp)) } func elU(input float64) float64 { inp := float64(int(input*10000)) / 10000 if inp > 0 { return inp } return 1.0 * (math.Exp(inp) - 1) } func relU(input float64) float64 { inp := float64(int(input*10000)) / 10000 if inp > 0 { return inp } return 0 } func leakyRelU(input float64) float64 { inp := float64(int(input*10000)) / 10000 if input > 0.1*inp { return inp } return 0.1 * inp } func tanh(input float64) float64 { inp := float64(int(input*10000)) / 10000 return math.Tanh(inp) } func linear(input float64) float64 { inp := float64(int(input*10000)) / 10000 return inp } func derivativeSigmoid(input float64) float64 { //σ(x)⋅(1−σ(x)) inp := float64(int(input*10000)) / 10000 return sigmoid(inp) * (1 - sigmoid(inp)) } func derivativeElu(input float64) float64 { inp := float64(int(input*10000)) / 10000 if input > 0 { return 1 } return 1.0 * (math.Exp(inp)) } func derivativeRelU(input float64) float64 { inp := float64(int(input*10000)) / 10000 if inp < 0 { return 0 } return 1 } func derivativeLeakyRelU(input float64) float64 { inp := float64(int(input*10000)) / 10000 if inp < 0 { return 0.01 } return 1 } func derivativeTanh(input float64) float64 { inp := float64(int(input*10000)) / 10000 //1 - tanh^2(x) return 1 - (math.Tanh(inp) * math.Tanh(inp)) } func derivativeLinear(input float64) float64 { return 1.0 } //============USABLE============= func Sigmoid() (func(input float64) float64, func(input float64) float64) { return sigmoid, derivativeSigmoid } func ElU() (func(input float64) float64, func(input float64) float64) { return elU, derivativeElu } func RelU() (func(input float64) float64, func(input float64) float64) { return relU, derivativeRelU } func LeakyRelU() (func(input float64) float64, func(input float64) float64) { return leakyRelU, derivativeLeakyRelU } func Tanh() (func(input float64) float64, func(input float64) float64) { return tanh, derivativeTanh } func Linear() (func(input float64) float64, func(input float64) float64) { return linear, derivativeLinear }
activations.go
0.82755
0.507202
activations.go
starcoder
package gomodel import "database/sql" type ( // Store defines the interface to store data from databqase rows Store interface { // Init will be called twice, first to allocate initial data space, second to specified // the final row count // Init initial the data store with size rows, if size is not enough, // Realloc will be called Init(size int) // Final indicate the last found rows Final(size int) // Ptrs should store pointers of data store at given index to the ptr parameter Ptrs(index int, ptrs []interface{}) // Realloc will occurred if the initial size is not enough, only occured // when call the All method of Scanner. // The return value shold be the new size of Store. // If don't want to continue, just return a non-positive number. Realloc(currSize int) (latest int) } // Scanner scan database rows to data Store when Error is nil, if the Rows is // empty, sql.ErrNoRows was returned, the Rows will always be be Closed Scanner struct { Error error Rows *sql.Rows Stmt Stmt } ) func (sc Scanner) Close() { stmt := sc.Stmt sc.Stmt = nil if stmt != nil { stmt.Close() } } func _rowCount(c int) int { const DEFAULT_ROW_COUNT = 10 if c >= 0 { return c } return DEFAULT_ROW_COUNT } const ( _SCAN_ALL = true _SCAN_LIMIT = !_SCAN_ALL ) func (sc Scanner) multiple(s Store, count int, scanType bool) error { if sc.Error != nil { return sc.Error } defer sc.Close() var ( index int ptrs []interface{} err error ) rows := sc.Rows defer rows.Close() for rows.Next() && (index < count || scanType == _SCAN_ALL) { if index == 0 { cols, _ := rows.Columns() s.Init(count) ptrs = make([]interface{}, len(cols)) } if index == count { if count = s.Realloc(count); count <= 0 { break // don't continue } } s.Ptrs(index, ptrs) if err = rows.Scan(ptrs...); err != nil { return err } index++ } if index == 0 { err = sql.ErrNoRows } else { s.Final(index) } return err } func (sc Scanner) All(s Store, initsize int) error { return sc.multiple(s, _rowCount(initsize), _SCAN_ALL) } func (sc Scanner) Limit(s Store, rowCount int) error { return sc.multiple(s, _rowCount(rowCount), _SCAN_LIMIT) } func (sc Scanner) One(ptrs ...interface{}) error { if sc.Error != nil { return sc.Error } defer sc.Close() rows := sc.Rows defer rows.Close() var err error if rows.Next() { err = rows.Scan(ptrs...) } else { err = sql.ErrNoRows } return err }
scan.go
0.508056
0.40116
scan.go
starcoder
package adventlang import ( "github.com/alecthomas/participle/v2" "github.com/alecthomas/participle/v2/lexer" ) type Program struct { Pos lexer.Position Statements []*Statement `@@*` } type Statement struct { Pos lexer.Position If *IfStatement `@@` For *ForStatement `| @@` While *WhileStatement `| @@` // These optional semi-colons could cause problems Return *ReturnStatement `| @@ ";"?` Break *string `| @"break" ";"?` Continue *string `| @"continue" ";"?` // -- Expr *Expr `| @@ ";"` } type IfStatement struct { Pos lexer.Position Condition *Expr `"if" "(" @@ ")"` If []*Statement `"{" @@* "}"` Else []*Statement `("else" "{" @@* "}")?` } type ForStatement struct { Pos lexer.Position Init *Expr `"for" "(" @@? ";"` Condition *Expr `@@? ";"` Post *Expr `@@? ")"` Block []*Statement `"{" @@* "}"` } type WhileStatement struct { Pos lexer.Position Condition *Expr `"while" "(" @@? ")"` Block []*Statement `"{" @@* "}"` } type ReturnStatement struct { Pos lexer.Position Expr *Expr `"return" @@?` } type Expr struct { Pos lexer.Position Assignment *Assignment `@@` } type Assignment struct { Pos lexer.Position Let *string `@"let"?` LogicOr *LogicOr `@@` Op *string `( @"="` Next *Assignment ` @@ )?` } type LogicOr struct { Pos lexer.Position LogicAnd *LogicAnd `@@` Op *string `( @"or"` Next *LogicOr ` @@ )?` } type LogicAnd struct { Pos lexer.Position Equality *Equality `@@` Op *string `( @"and"` Next *LogicAnd ` @@ )?` } type Equality struct { Pos lexer.Position Comparison *Comparison `@@` Op *string `[ @( "!" "=" | "=" "=" )` Next *Equality ` @@ ]` } type Comparison struct { Pos lexer.Position Addition *Addition `@@` Op *string `[ @( ">" "=" | ">" | "<" "=" | "<" )` Next *Comparison ` @@ ]` } type Addition struct { Pos lexer.Position Multiplication *Multiplication `@@` Op *string `[ @( "-" | "+" )` Next *Addition ` @@ ]` } type Multiplication struct { Pos lexer.Position Unary *Unary `@@` Op *string `[ @( "/" | "*" | "%" )` Next *Multiplication ` @@ ]` } type Unary struct { Pos lexer.Position Op *string `( @( "!" | "-" )` Unary *Unary ` @@ )` Primary *Primary `| @@` } type Primary struct { Pos lexer.Position FuncLiteral *FuncLiteral `@@` ListLiteral *ListLiteral `| @@` DictLiteral *DictLiteral `| @@` Call *Call `| @@` SubExpression *SubExpression `| @@` Number *float64 `| ( @Float | @Int )` Str *string `| @String` True *bool `| @"true"` False *bool `| @"false"` Undefined *string `| @"undefined"` Ident *string `| @Ident` } type FuncLiteral struct { Pos lexer.Position Params []string `"func" "(" ( @Ident ( "," @Ident )* )? ")"` Block []*Statement `"{" @@* "}"` } type ListLiteral struct { Pos lexer.Position Items []*Expr `"[" ( @@ ( "," @@ )* )? "]"` } type DictLiteral struct { Pos lexer.Position Items []*DictKV `"{" ( @@ ( "," @@ )* )? "}"` } type DictKV struct { Pos lexer.Position KeyExpr *Expr `( @@ |` KeyStr *string `"'" @Ident "'")` ValueExpr *Expr `":" @@` } type Call struct { Pos lexer.Position Ident *string `@Ident` CallChain *CallChain `@@` } type SubExpression struct { Pos lexer.Position Expr *Expr `"(" @@ ")" ` CallChain *CallChain `@@?` } type CallChain struct { Pos lexer.Position Args *CallArgs `( @@` Index *CallIndex ` | @@` Property *CallProperty ` | @@ )` Next *CallChain `@@?` } type CallArgs struct { Exprs []*Expr `"(" (@@ ("," @@)*)? ")"` } type CallIndex struct { Expr *Expr `"[" @@ "]"` } type CallProperty struct { Ident *string `"." @Ident` } var ( lex = lexer.MustSimple([]lexer.Rule{ {"comment", `//.*|/\*.*?\*/`, nil}, {"whitespace", `\s+`, nil}, {"Float", `([0-9]*[.])?[0-9]+`, nil}, {"Int", `[\d]+`, nil}, {"String", `"([^"]*)"`, nil}, {"Ident", `[\w]+`, nil}, {"Punct", `[-[!*%()+_={}\|:;"<,>./]|]`, nil}, }) parser = participle.MustBuild(&Program{}, participle.Lexer(lex), participle.UseLookahead(2)) ) func GetGrammer() string { return parser.String() } func GenerateAST(source string) (*Program, error) { ast := &Program{} err := parser.ParseString("", source, ast) if err != nil { return nil, err } return ast, nil }
pkg/adventlang/parse.go
0.682891
0.420302
parse.go
starcoder
package binson import ( "bytes" "encoding/binary" "fmt" "math" ) const( binsonBegin byte = 0x40 binsonEnd = 0x41 binsonBeginArray = 0x42 binsonEndArray = 0x43 binsonTrue = 0x44 binsonFalse = 0x45 binsonInteger1 = 0x10 binsonInteger2 = 0x11 binsonInteger4 = 0x12 binsonInteger8 = 0x13 binsonDouble = 0x46 binsonString1 = 0x14 binsonString2 = 0x15 binsonString4 = 0x16 binsonBytes1 = 0x18 binsonBytes2 = 0x19 binsonBytes4 = 0x1a ) type field interface { toBytes() []byte } type Binson map[binsonString]field type BinsonArray []field type binsonInt int64 type binsonString string type binsonBytes []byte type binsonBool bool type binsonFloat float64 func packInteger(value int64) []byte { buf := new(bytes.Buffer) if math.MinInt8 <= value && value <= math.MaxInt8 { binary.Write(buf, binary.LittleEndian, int8(value)) } else if math.MinInt16 <= value && value <= math.MaxInt16 { binary.Write(buf, binary.LittleEndian, int16(value)) } else if math.MinInt32 <= value && value <= math.MaxInt32 { binary.Write(buf, binary.LittleEndian, int32(value)) } else { binary.Write(buf, binary.LittleEndian, value) } return buf.Bytes() } func (b Binson) toBytes() []byte { var buf bytes.Buffer buf.WriteByte(binsonBegin) for _, key := range b.FieldNames(){ buf.Write(binsonString(key).toBytes()) buf.Write(b[binsonString(key)].toBytes()) } buf.WriteByte(binsonEnd) return buf.Bytes() } func (b *BinsonArray) ToBytes() []byte { return b.toBytes() } func (b *BinsonArray) toBytes() []byte { var buf bytes.Buffer buf.WriteByte(binsonBeginArray) for _, field := range *b { buf.Write(field.toBytes()) } buf.WriteByte(binsonEndArray) return buf.Bytes() } func (a binsonInt) toBytes() []byte { buf := new(bytes.Buffer) packedInt := packInteger(int64(a)) switch len(packedInt) { case 1: buf.WriteByte(binsonInteger1) case 2: buf.WriteByte(binsonInteger2) case 4: buf.WriteByte(binsonInteger4) case 8: buf.WriteByte(binsonInteger8) default: panic(fmt.Sprintf("Can not handle byte array of size %d", len(packedInt))) } buf.Write(packedInt) return buf.Bytes() } func (a binsonString) toBytes() []byte { buf := new(bytes.Buffer) lengtBytes := packInteger(int64(len(a))) switch len(lengtBytes) { case 1: buf.WriteByte(binsonString1) case 2: buf.WriteByte(binsonString2) case 4: buf.WriteByte(binsonString4) default: panic(fmt.Sprintf("Can not handle byte array of size %d", len(lengtBytes))) } buf.Write(lengtBytes) buf.WriteString(string(a)) return buf.Bytes() } func (a binsonBytes) toBytes() []byte { buf := new(bytes.Buffer) lengtBytes := packInteger(int64(len(a))) switch len(lengtBytes) { case 1: buf.WriteByte(binsonBytes1) case 2: buf.WriteByte(binsonBytes2) case 4: buf.WriteByte(binsonBytes4) default: panic(fmt.Sprintf("Can not handle byte array of size %d", len(lengtBytes))) } buf.Write(lengtBytes) buf.Write(a) return buf.Bytes() } func (a binsonBool) toBytes() []byte { if a { return []byte{binsonTrue} } else { return []byte{binsonFalse} } } func (a binsonFloat) toBytes() []byte { buf := new(bytes.Buffer) buf.WriteByte(binsonDouble) binary.Write(buf, binary.LittleEndian, float64(a)) return buf.Bytes() } func readInteger(prefix byte, buf *bytes.Buffer) (int64, error) { switch prefix { case binsonString1, binsonBytes1, binsonInteger1: var value int8 err := binary.Read(buf, binary.LittleEndian, &value) return int64(value), err case binsonString2, binsonBytes2, binsonInteger2: var value int16 err := binary.Read(buf, binary.LittleEndian, &value) return int64(value), err case binsonString4, binsonBytes4, binsonInteger4: var value int32 err := binary.Read(buf, binary.LittleEndian, &value) return int64(value), err case binsonInteger8: var value int64 err := binary.Read(buf, binary.LittleEndian, &value) return value, err default: panic(fmt.Sprintf("Unknown prefix: %X", prefix)) } } func parseBinson(buf *bytes.Buffer) (Binson, error) { b := NewBinson() for { next, err := buf.ReadByte() if err != nil { return nil, err } else if next == binsonEnd { return b, nil } name, err := parseString(next, buf) if err != nil { return nil, err } next, err = buf.ReadByte() if err != nil { return nil, err } field, err1 := parseField(next, buf) if err1 != nil { return nil, err1 } b.Put(name, field) } } func parseArray(buf *bytes.Buffer) (*BinsonArray, error) { a := NewBinsonArray() for { next, errRead := buf.ReadByte() if errRead != nil { return nil, errRead } else if next == binsonEndArray { return a, nil } field, errParse := parseField(next, buf) if errParse != nil { return nil, errParse } a.Put(field) } } func parseString(start byte, buf *bytes.Buffer) (string, error) { length, err := readInteger(start, buf) data := buf.Next(int(length)) text := string(data) return text, err } func parseBytes(start byte, buf *bytes.Buffer) ([]byte, error) { length, err := readInteger(start, buf) data := buf.Next(int(length)) return data, err } func parseInteger(start byte, buf *bytes.Buffer) (int64, error) { value, err := readInteger(start, buf) return value, err } func parseFloat(buf *bytes.Buffer) (float64, error) { var value float64 err := binary.Read(buf, binary.LittleEndian, &value) return value, err } func parseField(start byte, buf *bytes.Buffer) (interface{}, error) { switch start { case binsonBegin: return parseBinson(buf) case binsonBeginArray: return parseArray(buf) case binsonString1, binsonString2, binsonString4: return parseString(start, buf) case binsonBytes1, binsonBytes2, binsonBytes4: return parseBytes(start, buf) case binsonInteger1, binsonInteger2, binsonInteger4, binsonInteger8: return parseInteger(start, buf) case binsonTrue: return true, nil case binsonFalse: return false, nil case binsonDouble: return parseFloat(buf) default: return nil, fmt.Errorf("Unknown byte: %X", start) } } // Parses bytes to a Binson object. func Parse(data []byte) (Binson, error) { buf := bytes.NewBuffer(data) start, err := buf.ReadByte() if err != nil { return nil, err } field, err := parseField(start, buf) binson, ok := field.(Binson) if !ok { return nil, fmt.Errorf("Got none Binson type: %T", field) } return binson, err } // Writes this Binson object to bytes func (b Binson) ToBytes() []byte { return b.toBytes() }
pack_unpack.go
0.648578
0.444143
pack_unpack.go
starcoder
package animation import ( "github.com/juan-medina/goecs" ) // Sequence represent a set of frames that will be render with a delay type Sequence struct { Sheet string // Sheet is the sprite sheet where the animation sprites are Base string // Base is the base name for each frame. ex : Idle_%d.png Rotation float32 // Rotation for this AnimationSequence Scale float32 // Scale for this AnimationSequence Frames int32 // Frames are the number of frame in this animation Delay float32 // Delay number of seconds to wait in each frame } // Type return this goecs.ComponentType func (s Sequence) Type() goecs.ComponentType { return TYPE.Sequence } // State allow to easily switch animations type State struct { Current string // Current is the animation that is running Speed float32 // Speed is the current animation speed Time float32 // Time is the time in this frame Frame int32 // Frame is the current frame number } // Type return this goecs.ComponentType func (s State) Type() goecs.ComponentType { return TYPE.State } // Animation allow to easily switch animations type Animation struct { Sequences map[string]Sequence // Sequences is the different AnimationSequence for this Animation Current string // Current is the animation that be like to run Speed float32 // Speed is a multiplier of th speed of the current animation FlipX bool // FlipX indicates if the Animation is flipped in the X-Assis FlipY bool // FlipY indicates if the Animation is flipped in the Y-Assis } // Type return this goecs.ComponentType func (a Animation) Type() goecs.ComponentType { return TYPE.Animation } type types struct { // Animation is the goecs.ComponentType for animation.Animation Animation goecs.ComponentType // State is the goecs.ComponentType for animation.State State goecs.ComponentType // Sequence is the goecs.ComponentType for animation.Sequence Sequence goecs.ComponentType } // TYPE hold the goecs.ComponentType for our animation components var TYPE = types{ Animation: goecs.NewComponentType(), State: goecs.NewComponentType(), Sequence: goecs.NewComponentType(), } type gets struct { // AlternateColor gets a AlternateColor from a goecs.Entity Animation func(e *goecs.Entity) Animation // Layer gets a Layer from a goecs.Entity State func(e *goecs.Entity) State // Layer gets a Layer from a goecs.Entity Sequence func(e *goecs.Entity) Sequence } // Get animation component var Get = gets{ // Animation gets a animation.Animation from a goecs.Entity Animation: func(e *goecs.Entity) Animation { return e.Get(TYPE.Animation).(Animation) }, // State gets a animation.State from a goecs.Entity State: func(e *goecs.Entity) State { return e.Get(TYPE.State).(State) }, // Sequence gets a animation.Sequence from a goecs.Entity Sequence: func(e *goecs.Entity) Sequence { return e.Get(TYPE.Sequence).(Sequence) }, }
components/animation/animation.go
0.805364
0.409221
animation.go
starcoder
package warmup2 import "math" /* Given a string and a non-negative int n, return a larger string that is n copies of the original string. */ func string_times(str string, n int) string { var temp string = "" for i := 0; i < n; i++ { temp += str } return temp } /* Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front; */ func front_times(str string, n int) string { var temp string = "" for i := 0; i < n; i++ { if len(str) < 3 { temp += str } else { temp += str[0:3] } } return temp } /* Given a string, return a new string made of every other char starting with the first, so "Hello" yields "Hlo". */ func string_bits(str string) string { var temp string = "" for i := 0; i < len(str); i++ { if i%2 == 0 { temp += str[i : i+1] } } return temp } /* Given a non-empty string like "Code" return a string like "CCoCodCode". */ func string_splosion(str string) string { var temp string = "" for i := 0; i < len(str); i++ { temp += str[0 : i+1] } return temp } /* Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring). */ func last2(str string) int { var count int = 0 suffix := str[len(str)-2:] for i := 0; i < len(str)-2; i++ { if str[i:i+2] == suffix { count++ } } return count } /* Given an array of ints, return the number of 9's in the array. */ func array_count9(nums []int) int { var count int = 0 for _, val := range nums { if val == 9 { count++ } } return count } /* Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4. */ func array_front9(nums []int) bool { var size int = int(math.Min(float64(len(nums)), 4)) for i := 0; i < size; i++ { if nums[i] == 9 { return true } } return false } /* Given an array of ints, return True if .. 1, 2, 3, .. appears in the array somewhere. */ func array123(nums []int) bool { if len(nums) < 3 { return false } for i := 0; i < len(nums)-2; i++ { if nums[i] == 1 && nums[i+1] == 2 && nums[i+2] == 3 { return true } } return false } /* Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings. */ func string_match(a, b string) int { var count int = 0 for i := 0; i < int(math.Min(float64(len(a)), float64(len(b))))-1; i++ { if a[i] == b[i] && a[i+1] == b[i+1] { count++ } } return count }
Go/CodingBat/warmup-2.go
0.547948
0.443058
warmup-2.go
starcoder
package stackable import ( "errors" ) // Stackable is an interface for an element that can be placed into // a slice but should be incremented as a stack instead of appended // to the slice. type Stackable interface { GetItem() interface{} GetCount() uint SetCount(uint) } // Stack is a struct that represents the count of a given element. type Stack struct { Item interface{} Count uint } // GetItem returns the Item of the Stack func (s Stack) GetItem() interface{} { return s.Item } // GetCount returns the count of the Item in the Stack func (s Stack) GetCount() uint { return s.Count } // SetCount sets the count of the Item in the Stack func (s Stack) SetCount(count uint) { s.Count = count } // Put is a utility method for putting an element which may or may not implement // the Stackable interface into a slice of other elements or stackable interfaces. // If the element is stackable, the stack will be incremented by the argument's stack // count. If the element is not stackable, it will simply be appended to the slice. func Put(slice []interface{}, elem interface{}) ([]interface{}, error) { if stack, ok := elem.(Stackable); ok { return putStack(slice, stack) } return putElem(slice, elem) } func GetCount(elem interface{}) uint { if stack, ok := elem.(Stackable); ok { return stack.GetCount() } return 1 } // Has is a utility method for determining if an element, or the count // of a Stackable element exists within the given slice. It is useful to run a check // on Has before executing Take to remove an element or Stackable from the slice. func Has(slice []interface{}, elem interface{}) bool { if stack, ok := elem.(Stackable); ok { return hasStack(slice, stack) } return hasElem(slice, elem) } // Take is a utility method for removing an element for a Stackable from a // given slice. If the element is Stackable, and the matching Stackable // within the slice has the same count, the Stackable will be removed from the // slice. If the existing Stackable has a higher count, then that Stackable count // will be deducted by the given element Stackable. Otherwise an error is returned. func Take(slice []interface{}, elem interface{}) ([]interface{}, error) { if stack, ok := elem.(Stackable); ok { return takeStack(slice, stack) } return takeElem(slice, elem) } func takeStack(slice []interface{}, stack Stackable) ([]interface{}, error) { for i, elem := range slice { if s, ok := elem.(Stackable); ok && s.GetItem() == stack.GetItem() { if s.GetCount() == stack.GetCount() { return removeIndex(slice, i), nil } if stack.GetCount() < s.GetCount() { slice[i] = &Stack{ s.GetItem(), s.GetCount() - stack.GetCount(), } return slice, nil } return nil, errors.New("stack count is too large to take from slice") } } return nil, errors.New("stack not found within slice") } func takeElem(slice []interface{}, elem interface{}) ([]interface{}, error) { for i, e := range slice { if e == elem { return removeIndex(slice, i), nil } } return nil, errors.New("element does not exist within slice") } func removeIndex(slice []interface{}, i int) []interface{} { slice[i] = slice[len(slice)-1] // Copy last element to index i. slice[len(slice)-1] = "" // Erase last element (write zero value). return slice[:len(slice)-1] // Truncate slice. } func hasStack(slice []interface{}, stack Stackable) bool { for _, elem := range slice { if s, ok := elem.(Stackable); ok && s.GetItem() == stack.GetItem() { return s.GetCount() >= stack.GetCount() } } return false } func hasElem(slice []interface{}, elem interface{}) bool { for _, e := range slice { if e == elem { return true } } return false } func putStack(slice []interface{}, stack Stackable) ([]interface{}, error) { for i, elem := range slice { if s, ok := elem.(Stackable); ok && s.GetItem() == stack.GetItem() { combined, err := CombineStacks(s, stack) slice[i] = combined return slice, err } } slice = append(slice, &Stack{ stack.GetItem(), stack.GetCount(), }) return slice, nil } func putElem(slice []interface{}, elem interface{}) ([]interface{}, error) { return append(slice, elem), nil } // CombineStacks returns a new Stack that combines the counts of two Stacks // as long as the elements in the stacks match. func CombineStacks(a Stackable, b Stackable) (*Stack, error) { if a.GetItem() != b.GetItem() { return nil, errors.New("cannot combine stacks where items do not match") } return &Stack{ a.GetItem(), a.GetCount() + b.GetCount(), }, nil }
stackable/stack.go
0.793026
0.54153
stack.go
starcoder
package iso20022 // Set of elements used to provide information on the settlement of the instruction. type SettlementInformation15 struct { // Agent through which the instructing agent will reimburse the instructed agent. // Usage: If InstructingAgent and InstructedAgent have the same reimbursement agent, then only InstructingReimbursementAgent must be used. InstructingReimbursementAgent *BranchAndFinancialInstitutionIdentification4 `xml:"InstgRmbrsmntAgt,omitempty"` // Unambiguous identification of the account of the instructing reimbursement agent account at its servicing agent in the payment chain. InstructingReimbursementAgentAccount *CashAccount16 `xml:"InstgRmbrsmntAgtAcct,omitempty"` // Agent at which the instructed agent will be reimbursed. // Usage: If InstructedReimbursementAgent contains a branch of the InstructedAgent, then the party in InstructedAgent will claim reimbursement from that branch/will be paid by that branch. // Usage: If InstructingAgent and InstructedAgent have the same reimbursement agent, then only InstructingReimbursementAgent must be used. InstructedReimbursementAgent *BranchAndFinancialInstitutionIdentification4 `xml:"InstdRmbrsmntAgt,omitempty"` // Unambiguous identification of the account of the instructed reimbursement agent account at its servicing agent in the payment chain. InstructedReimbursementAgentAccount *CashAccount16 `xml:"InstdRmbrsmntAgtAcct,omitempty"` } func (s *SettlementInformation15) AddInstructingReimbursementAgent() *BranchAndFinancialInstitutionIdentification4 { s.InstructingReimbursementAgent = new(BranchAndFinancialInstitutionIdentification4) return s.InstructingReimbursementAgent } func (s *SettlementInformation15) AddInstructingReimbursementAgentAccount() *CashAccount16 { s.InstructingReimbursementAgentAccount = new(CashAccount16) return s.InstructingReimbursementAgentAccount } func (s *SettlementInformation15) AddInstructedReimbursementAgent() *BranchAndFinancialInstitutionIdentification4 { s.InstructedReimbursementAgent = new(BranchAndFinancialInstitutionIdentification4) return s.InstructedReimbursementAgent } func (s *SettlementInformation15) AddInstructedReimbursementAgentAccount() *CashAccount16 { s.InstructedReimbursementAgentAccount = new(CashAccount16) return s.InstructedReimbursementAgentAccount }
SettlementInformation15.go
0.667581
0.542742
SettlementInformation15.go
starcoder
package boruta import ( "math" "strings" ) // ListFilter is used to filter elements in a collection. type ListFilter interface { // Match tells if element matches the filter. Match(elem interface{}) bool } // SortOrder denotes in which order (ascending or descending) collection should be sorted. type SortOrder bool // ListDirection denotes in which direction collection should be traversed. type ListDirection bool const ( // SortOrderAsc means ascending order. This is the default. SortOrderAsc SortOrder = false // SortOrderDesc means descending order. SortOrderDesc SortOrder = true // DirectionForward means that list is traversed in forward direction. This is the default. DirectionForward ListDirection = false // DirectionBackward means that list is traversed in backward direction. DirectionBackward ListDirection = true // MaxPageLimit denotes maximum value that pageInfo.Limit can be. MaxPageLimit = uint16(math.MaxUint16) ) // SortInfo contains information needed to sort collections in Boruta (requests, workers). type SortInfo struct { // Item by which collection should be sorted. Item string // Order in which collection should be sorted. Order SortOrder } // ListInfo contains information about filtered list - how many items are there and how many items // are left till the end. type ListInfo struct { // TotalItems contains information how many items in total is in filtered collection. TotalItems uint64 // RemainingItems contains information how many items are left till the end of colleciton // (when paginating). RemainingItems uint64 } // RequestsPaginator contains information to get specific page of listed requests. type RequestsPaginator struct { // ID sets page border. When direction is set to forward the page will start with first // request after the ID and contain up to Limit items. If direction is set backward then // page contains up to Limit items before ID. ID ReqID // Direction in which list should be traversed. Direction ListDirection // Limit up to how many elements can be stored on one page. Limit uint16 } // WorkersPaginator contains information to get specific page of listed workers. type WorkersPaginator struct { // ID sets page border. When direction is set to forward the page will start with first // workes after the ID and contain up to Limit items. If direction is set backward then // page contains up to Limit items before ID. ID WorkerUUID // Direction in which list should be traversed. Direction ListDirection // Limit up to how many elements can be stored on one page. Limit uint16 } // String returns textual representation of SortOrder ("ascending" or "descending"). func (order SortOrder) String() string { if order == SortOrderDesc { return "descending" } return "ascending" } // MarshalText is implementation of encoding.TextMarshaler interface. It is used to properly // marshal from structures that contain SortOrder members. func (order *SortOrder) MarshalText() ([]byte, error) { return []byte(order.String()), nil } // UnmarshalText is implementation of encoding.TextUnmarshaler interface. It is used to properly // unmarshal structures that contain SortOrder members. func (order *SortOrder) UnmarshalText(text []byte) error { switch strings.ToLower(string(text)) { case "": fallthrough // ascending is the default order case SortOrderAsc.String(): *order = SortOrderAsc return nil case SortOrderDesc.String(): *order = SortOrderDesc return nil default: return ErrWrongSortOrder } } // String returns textual representation of ListDirection ("forward" or "backward"). func (direction ListDirection) String() string { if direction == DirectionBackward { return "backward" } return "forward" } // MarshalText is implementation of encoding.TextMarshaler interface. It is used to properly // marshal from structures that contain ListDirection members. func (direction *ListDirection) MarshalText() ([]byte, error) { return []byte(direction.String()), nil } // UnmarshalText is implementation of encoding.TextUnmarshaler interface. It is used to properly // unmarshal structures that contain ListDirection members. func (direction *ListDirection) UnmarshalText(text []byte) error { switch strings.ToLower(string(text)) { case "": fallthrough // forward is the default direction case DirectionForward.String(): *direction = DirectionForward case DirectionBackward.String(): *direction = DirectionBackward default: return ErrWrongListDirection } return nil }
lists.go
0.765769
0.410934
lists.go
starcoder
package main import ( "math" ray "github.com/gen2brain/raylib-go/raylib" ) func main() { screenWidth := int32(1000) screenHeight := int32(1000) ray.SetConfigFlags(ray.FlagMsaa4xHint) ray.InitWindow(screenWidth, screenHeight, "xtra") camera := ray.Camera{} camera.Position = ray.NewVector3(0.0, 10.0, 10.0) camera.Target = ray.NewVector3(0.0, 5.0, 0.0) camera.Up = ray.NewVector3(0.0, 1.0, 0.0) camera.Fovy = 45.0 ray.SetTargetFPS(60) const OrbitRadius = 20.0 propeller := ray.LoadModelFromMesh(ray.GenMeshCube(1, 1, 1)) propellerBase := ray.LoadModelFromMesh(ray.GenMeshCylinder(0.8, 1.5, 30)) for !ray.WindowShouldClose() { sn, cs := math.Sincos((float64)(ray.GetTime())) camera.Position = ray.NewVector3(OrbitRadius*(float32)(sn), 20.0, OrbitRadius*(float32)(cs)) ray.BeginDrawing() ray.ClearBackground(ray.RayWhite) ray.BeginMode3D(camera) { ray.DrawGrid(20, 1.0) ray.DrawCube(ray.NewVector3(0, 5, 0), 2.0, 2.5, 16.0, ray.Blue) ray.DrawCube(ray.NewVector3(0, 5.2, 3), 16.0, 0.5, 4.0, ray.SkyBlue) ray.DrawCube(ray.NewVector3(0, 5.2, -6), 8.0, 0.2, 3.0, ray.SkyBlue) ray.DrawCube(ray.NewVector3(0, 7, -6), 0.2, 3, 3.0, ray.SkyBlue) ray.DrawSphere(ray.NewVector3(0, 6, 3.5), 1, ray.LightGray) ray.DrawCube(ray.NewVector3(0, 7, -6), 0.2, 3, 3.0, ray.LightGray) ray.DrawModelEx(propeller, ray.NewVector3(0, 5, 8.5), ray.NewVector3(0, 0, 1), ray.GetTime()*1000, ray.NewVector3(1, 7, 0.1), ray.Orange, ) ray.DrawModelEx(propellerBase, ray.NewVector3(0, 5, 7.5), ray.NewVector3(1, 0, 0), 90, ray.NewVector3(1, 1, 1), ray.Orange, ) /* ray.DrawSphere(ray.NewVector3(-1.0, 0.0, -2.0), 1.0, ray.Green) ray.DrawSphereWires(ray.NewVector3(1.0, 0.0, 2.0), 2.0, 16, 16, ray.Lime) ray.DrawCylinder(ray.NewVector3(4.0, 0.0, -2.0), 1.0, 2.0, 3.0, 4, ray.SkyBlue) ray.DrawCylinderWires(ray.NewVector3(4.0, 0.0, -2.0), 1.0, 2.0, 3.0, 4, ray.DarkBlue) ray.DrawCylinderWires(ray.NewVector3(4.5, -1.0, 2.0), 1.0, 1.0, 2.0, 6, ray.Brown) ray.DrawCylinder(ray.NewVector3(1.0, 0.0, -4.0), 0.0, 1.5, 3.0, 8, ray.Gold) ray.DrawCylinderWires(ray.NewVector3(1.0, 0.0, -4.0), 0.0, 1.5, 3.0, 8, ray.Pink) // Draw a grid */ } ray.EndMode3D() ray.EndDrawing() } ray.CloseWindow() }
plane/main.go
0.653127
0.534127
main.go
starcoder
package entries import ( "sort" "unicode" ) // List is a list of entries. type List struct { list []*Entry } func copyEntrySlice(slice []*Entry) []*Entry { return append([]*Entry{}, slice...) } // FromOffset returns n entries from a given offset. // If there aren't enough entries from offset, it will return as many as it can. // If offset is out of bounds, it will return an ErrListOutOfbounds func (es List) FromOffset(offset, n int) (List, error) { if offset >= len(es.list) { return List{}, ErrListOutOfBounds{offset, len(es.list)} } if offset+n > len(es.list) { return List{es.list[offset:]}, nil } return List{es.list[offset : offset+n]}, nil } // First returns the first N entries in the list. // If there's not N entries, it will return as many as possible. func (es List) First(n int) List { if n > len(es.list) { return List{copyEntrySlice(es.list)} } newList, _ := es.FromOffset(0, n) return newList } // Last returns the last N entries in the list. // If there's not N entries, it will return as many as possible. func (es List) Last(n int) List { if n > len(es.list) { return List{copyEntrySlice(es.list)} } newList, _ := es.FromOffset(len(es.list)-n, n) return newList } // Slice returns the entries as a slice of *Entry. func (es List) Slice() []*Entry { return copyEntrySlice(es.list) } // Reverse reverses an entry list. func (es List) Reverse() List { newList := []*Entry{} for i := range es.list { newList = append(newList, es.list[len(es.list)-i-1]) } return List{newList} } // Sort sorts an List. func (es List) Sort(sortType SortType) List { var sortable sort.Interface var entries = copyEntrySlice(es.list) switch sortType { case SortAlpha: sortable = SortableByAlpha(entries) case SortDate: sortable = SortableByDate(entries) case SortPath: sortable = SortableByPathAlpha(entries) } sort.Sort(sortable) return List{list: entries} } // SortType is the method used to sort an List. type SortType int const ( // SortAlpha uses alphabetical sorting for entries. SortAlpha SortType = iota // SortDate uses date sorting for entries. SortDate // SortPath uses alphabetical sorting for paths. SortPath ) // SortableByAlpha implements sort.Interface for []*Entry based on the alphabetical ordering of titles. // Courtesy of this StackOverflow answer: https://stackoverflow.com/questions/35076109/in-golang-how-can-i-sort-a-list-of-strings-alphabetically-without-completely-ig type SortableByAlpha []*Entry func (es SortableByAlpha) Len() int { return len(es) } func (es SortableByAlpha) Swap(i, j int) { es[i], es[j] = es[j], es[i] } func (es SortableByAlpha) Less(i, j int) bool { iRunes := []rune(es[i].Title) jRunes := []rune(es[j].Title) max := len(iRunes) if max > len(jRunes) { max = len(jRunes) } for idx := 0; idx < max; idx++ { ir := iRunes[idx] jr := jRunes[idx] lir := unicode.ToLower(ir) ljr := unicode.ToLower(jr) if lir != ljr { return lir < ljr } // the lowercase runes are the same, so compare the original if ir != jr { return ir < jr } } return false } // SortableByPathAlpha implements sort.Interface for []*Entry based on the alphabetical ordering of titles. // Courtesy of this StackOverflow answer: https://stackoverflow.com/questions/35076109/in-golang-how-can-i-sort-a-list-of-strings-alphabetically-without-completely-ig type SortableByPathAlpha []*Entry func (es SortableByPathAlpha) Len() int { return len(es) } func (es SortableByPathAlpha) Swap(i, j int) { es[i], es[j] = es[j], es[i] } func (es SortableByPathAlpha) Less(i, j int) bool { iRunes := []rune(es[i].Path) jRunes := []rune(es[j].Path) max := len(iRunes) if max > len(jRunes) { max = len(jRunes) } for idx := 0; idx < max; idx++ { ir := iRunes[idx] jr := jRunes[idx] lir := unicode.ToLower(ir) ljr := unicode.ToLower(jr) if lir != ljr { return lir < ljr } // the lowercase runes are the same, so compare the original if ir != jr { return ir < jr } } return false } // SortableByDate implements the sort.Interface for []*Entry based on entry dates. type SortableByDate []*Entry func (es SortableByDate) Len() int { return len(es) } func (es SortableByDate) Swap(i, j int) { es[i], es[j] = es[j], es[i] } func (es SortableByDate) Less(i, j int) bool { return es[i].Date.Before(es[j].Date) }
entries/list.go
0.771456
0.466785
list.go
starcoder
package levenshtein func CalculateDistance(firstWord string, secondWord string) int { numOfColumns := len(firstWord) + 1 numOfRows := len(secondWord) + 1 distanceMatrix := createZeroedMatrix(numOfColumns, numOfRows) distanceMatrix = prepareMatrix(distanceMatrix) distanceMatrix = runLevenshteinAlgorithmOnMatrix(distanceMatrix, firstWord, secondWord) // result distance is in the bottom right cell levenshteinDistance := distanceMatrix[numOfColumns-1][numOfRows-1] return levenshteinDistance } func createZeroedMatrix(numOfColumns int, numOfRows int) [][]int { matrix := make([][]int, numOfColumns) // Fill every column with empty arrays for columnIndex := 0; columnIndex < numOfColumns; columnIndex++ { matrix[columnIndex] = make([]int, numOfRows) } return matrix } func prepareMatrix(distanceMatrix [][]int) [][]int { numOfColumns := getNumberOfMatrixColumns(distanceMatrix) numOfRows := getNumberOfMatrixRows(distanceMatrix) // Fill first row with 0,1,2,... for columnIndex := 0; columnIndex < numOfColumns; columnIndex++ { distanceMatrix[columnIndex][0] = columnIndex } // Fill first column with 0,1,2,... for rowIndex := 0; rowIndex < numOfRows; rowIndex++ { distanceMatrix[0][rowIndex] = rowIndex } return distanceMatrix } func runLevenshteinAlgorithmOnMatrix(distanceMatrix [][]int, firstWord string, secondWord string) [][] int { numOfColumns := getNumberOfMatrixColumns(distanceMatrix) numOfRows := getNumberOfMatrixRows(distanceMatrix) for rowIndex := 1; rowIndex < numOfRows; rowIndex++ { for columnIndex := 1; columnIndex < numOfColumns; columnIndex++ { if firstWord[columnIndex-1] == secondWord[rowIndex-1] { distanceMatrix[columnIndex][rowIndex] = distanceMatrix[columnIndex-1][rowIndex-1] } else { costOfSubstitution := distanceMatrix[columnIndex-1][rowIndex-1] + 1 costOfInsertion := distanceMatrix[columnIndex][rowIndex-1] + 1 costOfDeletion := distanceMatrix[columnIndex-1][rowIndex] + 1 costOfCheapest := getMinimumOfNumbers(costOfSubstitution, costOfInsertion, costOfDeletion) distanceMatrix[columnIndex][rowIndex] = costOfCheapest } } } return distanceMatrix }
levenshtein.go
0.751375
0.785267
levenshtein.go
starcoder
package object import ( "fmt" "github.com/simp7/times" "time" ) type accurate struct { times.Object ms int } //Accurate is function that returns the struct that implements times.Object. //Minimum unit of Accurate is second. //As Accurate returns the most-accurate times.Object object, It is encouraged to compare other object that implements times.Object with this. func Accurate(millisecond, second, minute, hour, day int) times.Object { a := new(accurate) a.Object = Standard(second, minute, hour, day) a.SetMilliSecond(millisecond) return a } // AccurateFor is function that gets built-in time.Time object and convert it to the struct that implements times.Object. object. // The other feature of AccurateFor is same as Accurate. func AccurateFor(t time.Time) times.Object { return Accurate(t.Nanosecond()/1000000, t.Second(), t.Minute(), t.Hour(), t.Day()) } //AccurateZero is zero value of Object by using Accurate. func AccurateZero() times.Object { return Accurate(0, 0, 0, 0, 0) } func (t *accurate) Tick() { t.ms++ t.trim() } func (t *accurate) Rewind() { t.ms-- t.trim() } //Should be called after calculation func (t *accurate) trim() { if t.MilliSecond() >= 1000 { for i := 0; i < t.MilliSecond()/1000; i++ { t.Object.Tick() } t.ms %= 1000 } if t.MilliSecond() < 0 { t.Object.Rewind() t.ms += 1000 } } func (t *accurate) MilliSecond() int { return t.ms } func (t *accurate) Equal(another times.Object) bool { return t.Day() == another.Day() && t.Hour() == another.Hour() && t.Minute() == another.Minute() && t.Second() == another.Second() && t.MilliSecond() == another.MilliSecond() } func (t *accurate) SetMilliSecond(ms int) times.Object { if t.ms >= 1000 || t.ms < 0 { t.ms = 0 } t.ms = ms return t } func (t *accurate) SetSecond(second int) times.Object { t.Object.SetSecond(second) return t } func (t *accurate) SetMinute(minute int) times.Object { t.Object.SetMinute(minute) return t } func (t *accurate) SetHour(hour int) times.Object { t.Object.SetHour(hour) return t } func (t *accurate) SetDay(day int) times.Object { t.Object.SetDay(day) return t } func (t *accurate) Serialize() string { return fmt.Sprintf("%d/%d/%d/%d/%d", t.Day(), t.Hour(), t.Minute(), t.Second(), t.MilliSecond()) }
object/accurate.go
0.84556
0.567517
accurate.go
starcoder
package service // Stability is a type that represents the relative stability of a service // module type Stability int const ( // StabilityExperimental represents relative stability of the most immature // service modules. At this level of stability, we're not even certain we've // built the right thing! StabilityExperimental Stability = iota // StabilityPreview represents relative stability of modules we believe are // approaching a stable state. StabilityPreview // StabilityStable represents relative stability of the mature, production- // ready service modules. StabilityStable ) // ProvisioningParameters wraps a map containing provisioning parameters. type ProvisioningParameters struct { Parameters } // InstanceDetails is an alias for maps intended to contain non-sensitive // details of a service instance. It exists only to improve the clarity of // function signatures and documentation. type InstanceDetails map[string]interface{} // SecureInstanceDetails is an alias for maps intended to contain sensitive // details of a service instance. It exists only to improve the clarity of // function signatures and documentation. type SecureInstanceDetails map[string]interface{} // BindingParameters wraps a map containing binding parameters. type BindingParameters struct { Parameters } // BindingDetails is an alias for maps intended to contain non-sensitive // details of a service binding. It exists only to improve the clarity of // function signatures and documentation. type BindingDetails map[string]interface{} // SecureBindingDetails is an alias for maps intended to contain sensitive // details of a service binding. It exists only to improve the clarity of // function signatures and documentation. type SecureBindingDetails map[string]interface{} // Credentials is an interface to be implemented by service-specific types // that represent service credentials. This interface doesn't require any // functions to be implemented. It exists to improve the clarity of function // signatures and documentation. type Credentials interface{}
pkg/service/types.go
0.75183
0.603873
types.go
starcoder
package renderer import ( "github.com/g3n/engine/math32" "log" ) // getCenter gets the centerpoint of a 3D box func getCenter(box math32.Box3) *math32.Vector3 { return box.Center(nil) } // focusOnSelection sets the camera focus on the current selection func (app *RenderingApp) focusOnSelection() { var bbox *math32.Box3 first := true for inode := range app.selectionBuffer { tmp := inode.BoundingBox() if first { bbox = math32.NewBox3(&tmp.Min, &tmp.Max) log.Println(bbox) first = false } else { bbox.ExpandByPoint(&tmp.Min) bbox.ExpandByPoint(&tmp.Max) } } if first { return } position := app.Camera().GetCamera().Position() C := bbox.Center(nil) r := C.DistanceTo(&bbox.Max) a := app.CameraPersp().Fov() d := r / math32.Sin(a/2) P := math32.Vector3{X: C.X, Y: C.Y, Z: C.Z} dir := math32.Vector3{X: C.X, Y: C.Y, Z: C.Z} P.Add(((position.Sub(C)).Normalize().MultiplyScalar(d))) dir.Sub(&P) app.Camera().GetCamera().SetPositionVec(&P) app.Camera().GetCamera().LookAt(C) } // getViewVectorByName gets a view direction vector by name func getViewVectorByName(view string) math32.Vector3 { modifier := math32.Vector3{X: 0, Y: 0, Z: 0} switch view { case "top": modifier.Y = 10 case "bottom": modifier.Y = -10 case "front": modifier.Z = 10 case "rear": modifier.Z = -10 case "left": modifier.X = 10 case "right": modifier.X = -10 } return modifier } // setCamera set camera sets a camera standard view by name func (app *RenderingApp) setCamera(view string) { modifier := getViewVectorByName(view) bbox := app.Scene().ChildAt(0).BoundingBox() C := bbox.Center(nil) pos := modifier.Add(C) app.focusCameraToCenter(*pos) } // focusCameraToCenter sets the camera focus to the center of the entire model func (app *RenderingApp) focusCameraToCenter(position math32.Vector3) { bbox := app.Scene().ChildAt(0).BoundingBox() C := bbox.Center(nil) r := C.DistanceTo(&bbox.Max) a := app.CameraPersp().Fov() d := r / math32.Sin(a/2) P := math32.Vector3{X: C.X, Y: C.Y, Z: C.Z} dir := math32.Vector3{X: C.X, Y: C.Y, Z: C.Z} P.Add(((position.Sub(C)).Normalize().MultiplyScalar(d))) dir.Sub(&P) app.Camera().GetCamera().SetPositionVec(&P) app.Camera().GetCamera().LookAt(C) } // zoomToExtent zooms the view to extent func (app *RenderingApp) zoomToExtent() { pos := app.Camera().GetCamera().Position() app.focusCameraToCenter(pos) }
renderer/camera.go
0.628749
0.445469
camera.go
starcoder
package float32z import ( "sort" "strconv" ) const ( // BitSize is the size in bits of this type. BitSize = 32 ) var ( _ sort.Interface = Slice{} ) // Ptr returns a pointer to the value. func Ptr(v float32) *float32 { return &v } // PtrZeroToNil returns a pointer to the value, or nil if 0. func PtrZeroToNil(v float32) *float32 { if v == 0 { return nil } return &v } // PtrDefToNil returns a pointer to the value, or nil if "def". func PtrDefToNil(v float32, def float32) *float32 { if v == def { return nil } return &v } // Val returns the pointer value, defaulting to zero if nil. func Val(v *float32) float32 { if v == nil { return 0 } return *v } // ValDef returns the pointer value, defaulting to "def" if nil. func ValDef(v *float32, def float32) float32 { if v == nil { return def } return *v } // Parse parses a string as base 10 float32. func Parse(v string) (float32, error) { p, err := strconv.ParseFloat(v, BitSize) if err != nil { return 0, err } return (float32)(p), nil } // MustParse is like Parse but panics on error. func MustParse(v string) float32 { p, err := Parse(v) if err != nil { panic(err) } return p } // Slice is a slice of values. type Slice []float32 // Len implements the sort.Interface interface. func (s Slice) Len() int { return len(s) } // Less implements the sort.Interface interface. func (s Slice) Less(i, j int) bool { return s[i] < s[j] } // Swap implements the sort.Interface interface. func (s Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // SliceToMap converts a slice to map. func SliceToMap(s []float32) map[float32]struct{} { m := make(map[float32]struct{}, len(s)) for _, v := range s { m[v] = struct{}{} } return m } // MapToSlice converts a map to slice. func MapToSlice(m map[float32]struct{}) []float32 { s := make([]float32, 0, len(m)) for v := range m { s = append(s, v) } return s } // SafeIndex returns "s[i]" if possible, and 0 otherwise. func SafeIndex(s []float32, i int) float32 { if s == nil || i < 0 || i >= len(s) { return 0 } return s[i] } // SafeIndexDef returns "s[i]" if possible, and "def" otherwise. func SafeIndexDef(s []float32, i int, def float32) float32 { if s == nil || i < 0 || i >= len(s) { return def } return s[i] } // SafeIndexPtr returns "s[i]" if possible, and nil otherwise. func SafeIndexPtr(s []float32, i int) *float32 { if s == nil || i < 0 || i >= len(s) { return nil } return Ptr(s[i]) }
numeric/float32z/float32z.go
0.763484
0.403391
float32z.go
starcoder
package propertycost import ( "errors" "math" ) //DownPayment describes a down payment and //its assocciated costs. //AmountInHand - how much money you have to pay down on the price of the house //RequiredPercentage - The percentage of property cost that needs to be a down payment //Rent(decimal form) - The rent on the down payment if you have to take a loan to reach the required down payment. //Amortization(decimal form) - The required Amortization percentage on the down payment you hade to take a loan for. type DownPayment struct { AmountInHand float64 RequiredPercentage float64 Rent float64 Amortization float64 } //RentRebate describes the rent rebate you get //on loans. It's modelled after how the Swedish //rent rebate system works. //BeforeLimit(decimal form) - Rent rebate percentage before you reach the rent cost limit (over a year) //AfterLimit(decimal form) - Rent rebate percentage after you reach the rent cost limit //Limit - Limit where you payed enough rentcosts to go to the AfterLimit rent rebate percentage type RentRebate struct { Limit float64 BeforeLimit float64 AfterLimit float64 } //TaxProperty modelled after the Swedish system //TaxationValuePercentageOfValue(decimal form) - Is the stupid percentage of the market value of your house which counts to the taxation value. Its complicated in how the market price is set, here we approximate it to be the price of the house. //Percent(decimal form) - is the tax you need to pay on the taxation value of the house //Roof - the maximum value the property tax can reach. type TaxProperty struct { TaxationValuePercentageOfValue float64 Percent float64 Roof float64 } //Rent(decimal form) //Amortization(decimal form) //DownPayment - self explanatory type Mortgage struct { Rent float64 Amortization float64 DownPayment DownPayment } func HouseMonthly(price, operatingCost float64, mortgage Mortgage, rentRebate RentRebate, taxProperty TaxProperty, propertyInsuranceMonthly float64) (RealCostMonthly, AmortizationMonthly float64, err error) { condoCostMonthly, amortization, err := CondoMonthly(price, operatingCost, mortgage, rentRebate, propertyInsuranceMonthly) if err != nil { return 0, 0, err } return condoCostMonthly + HouseTax(price, taxProperty)/12.0, amortization, nil } func HouseTax(price float64, taxProperty TaxProperty) float64 { return math.Min(price*taxProperty.TaxationValuePercentageOfValue*taxProperty.Percent, taxProperty.Roof) } func CondoMonthly(price, operatingCost float64, mortgage Mortgage, rentRebate RentRebate, propertyInsuranceMonthly float64) (RealCostMonthly, AmortizationMonthly float64, err error) { mainRent, downPaymentRent, err := Rent(price, mortgage) if err != nil { return 0, 0, err } rent := mainRent + downPaymentRent rentCost := rent - Rebate(rent, rentRebate) mainAmortization, dpAmortization, err := Amortization(price, mortgage) if err != nil { return 0, 0, err } return rentCost/12 + operatingCost/float64(12) + propertyInsuranceMonthly, mainAmortization/12 + dpAmortization/12, nil } func RequiredDownPayment(price float64, downPayment DownPayment) float64 { return price * downPayment.RequiredPercentage } //Yearly func Rebate(rentTotal float64, rentRebate RentRebate) float64 { return math.Min(rentTotal, rentRebate.Limit)*rentRebate.BeforeLimit + math.Max(0, rentTotal-rentRebate.Limit)*rentRebate.AfterLimit } //Yearly func Amortization(price float64, mortgage Mortgage) (mainAmortization float64, downPaymentAmortization float64, err error) { mortgageTot, err := mortgageTotal(price, mortgage) if err != nil { return 0, 0, err } mainAmortization = (mortgageTot) * mortgage.Amortization downPaymentAmortization = downPaymentBorrowed(price, mortgage.DownPayment) * mortgage.DownPayment.Amortization return mainAmortization, downPaymentAmortization, nil } func Rent(price float64, mortgage Mortgage) (mainRent float64, downPaymentRent float64, err error) { downPayment := mortgage.DownPayment mortgageTot, err := mortgageTotal(price, mortgage) if err != nil { return 0, 0, err } mainRent = mortgageTot * mortgage.Rent downPaymentRent = downPaymentBorrowed(price, mortgage.DownPayment) * downPayment.Rent return mainRent, downPaymentRent, nil } //taxes are given i a decimal percentage i.e 50% = 0.5 func HousePurchaseFees(price, mortgageDeedCurrent, mortgageDeedTax, titleDeedTax float64) float64 { return MortgageDeed(price, mortgageDeedCurrent, mortgageDeedTax) + TitleDeed(price, titleDeedTax) } //taxes are given i a decimal percentage i.e 50% = 0.5 func MortgageDeed(price, mortgageDeedCurrent, mortgageDeedTax float64) float64 { return (price - mortgageDeedCurrent) * mortgageDeedTax } //taxes are given i a decimal percentage i.e 50% = 0.5 func TitleDeed(price, titleDeedTax float64) float64 { return price * titleDeedTax } func downPaymentBorrowed(price float64, downPayment DownPayment) float64 { return math.Max(0, RequiredDownPayment(price, downPayment)-downPayment.AmountInHand) } func mortgageTotal(price float64, mortgage Mortgage) (float64, error) { mortgageAmount := price - (mortgage.DownPayment.AmountInHand + downPaymentBorrowed(price, mortgage.DownPayment)) if mortgageAmount < 0 { return 0, errors.New("Can not down pay more then the price of the property") } return mortgageAmount, nil }
pkg/propertycost/propertycost.go
0.713032
0.637214
propertycost.go
starcoder
package neural import "math" // ActivationFunc is the structure that represents a forward function and its derivative function type ActivationFunc struct { f func(float64) float64 fprime func(float64) float64 } // NewActivationFunc creates a new ActivationFunc structure func NewActivationFunc(f, fprime func(float64) float64) (*ActivationFunc, error) { if f == nil || fprime == nil { return nil, ErrInvalidFunction } return &ActivationFunc{f: f, fprime: fprime}, nil } // ActivationFuncSigmoid is the logistic sigmoid activation function and its derivative var ActivationFuncSigmoid = &ActivationFunc{ f: func(z float64) float64 { return 1.0 / (1.0 + math.Exp(-z)) }, fprime: func(z float64) float64 { s := 1.0 / (1.0 + math.Exp(-z)) return s * (1.0 - s) }, } // ActivationFuncTanH is the hyperbolic tangent function and its derivative var ActivationFuncTanH = &ActivationFunc{ f: func(z float64) float64 { return math.Tanh(z) }, fprime: func(z float64) float64 { return 1.0 - math.Pow(math.Tanh(z), 2.0) }, } // ActivationFuncSwish is the self gated activation function and its derivative. // Swish : z * sigmoid(z) // Swish Derivative calculated by product rule (f(z) * g(z))' = f'(z) * g(z) + f(z) * g'(z) : // = z' * sigmoid(z) + z * sigmoid'(z) // = sigmoid(z) + z * sigmoid(z) * (1 - sigmoid(z)) var ActivationFuncSwish = &ActivationFunc{ f: func(z float64) float64 { return z / (1.0 + math.Exp(-z)) }, fprime: func(z float64) float64 { s := 1.0 / (1.0 + math.Exp(-z)) sP := s * (1.0 - s) return s + z*sP }, } // ActivationFuncLinear is the linear is the function with slope 1 that passes through 0, 0 and its derivative var ActivationFuncLinear = ActivationFuncLinearGenerator(1.0, 0.0) // ActivationFuncLinearGenerator generates a linear funtion where forward function returns the value a*z + b and its derivative returns a func ActivationFuncLinearGenerator(a, b float64) *ActivationFunc { return &ActivationFunc{ f: func(z float64) float64 { return a*z + b }, fprime: func(z float64) float64 { return a }, } } // ActivationFuncReLu is the rectified linear unit function and its derivative var ActivationFuncReLu = ActivationFuncReLuGenerator(0.0) // ActivationFuncLeakyRelu is the leaky rectified linear unit funciton with its scalar for non-positive values set to 0.01 by default. var ActivationFuncLeakyRelu = ActivationFuncReLuGenerator(0.01) // ActivationFuncReLuGenerator is a ReLu / leaky ReLu / randomized ReLu generator function. func ActivationFuncReLuGenerator(scalar float64) *ActivationFunc { return &ActivationFunc{ f: func(z float64) float64 { if z > 0 { return z } return z * scalar }, fprime: func(z float64) float64 { if z > 0 { return 1.0 } return scalar }, } }
activation.go
0.847258
0.591694
activation.go
starcoder
// Exercise 3.11: Enhance comma so that it deals correctly with floating-point numbers and an optional sign. // Exercise 3.12: Write a function that reports whether two strings are anagrams of each other, that is, they contain the same letters in a different order. package main import ( "bytes" "fmt" "reflect" "strings" ) // Note: recursive comma() included for reference // comma inserts commas in a non-negative decimal integer string. func comma(s string) string { runes := []rune(s) n := len(runes) if n <= 3 { return s } return comma(string(runes[:n-3])) + "," + string(runes[n-3:]) } func trimLeftChar(s string) string { for i := range s { // i is the index of the first byte of the string's code points if i > 0 { return s[i:] } } return s[:0] } func enhancedComma(s string) string { if strings.HasPrefix(s, "+") { return "+" + enhancedComma(trimLeftChar(s)) } else if strings.HasPrefix(s, "-") { return "-" + enhancedComma(trimLeftChar(s)) } if strings.Contains(s, ".") { splitString := strings.Split(s, ".") return enhancedComma(splitString[0]) + "." + splitString[1] } n := len(s) if n <= 3 { return s } return enhancedComma(s[:n-3]) + "," + s[n-3:] } func nonRecursiveComma(s string) string { var buf bytes.Buffer reversed := reverse(s) for i, v := range reversed { if i > 0 && i%3 == 0 { buf.WriteRune(',') } buf.WriteRune(v) } return reverse(buf.String()) } func reverse(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) } func mapString(s string) map[rune]int { rmap := make(map[rune]int) runes := []rune(s) for _, r := range runes { rmap[r]++ } return rmap } func isAnagram(s string, t string) bool { if len(s) != len(t) { return false } sMap := mapString(s) tMap := mapString(t) return reflect.DeepEqual(sMap, tMap) } func main() { fmt.Println(nonRecursiveComma("12345")) fmt.Println(nonRecursiveComma("123456")) fmt.Println(nonRecursiveComma("123")) fmt.Println(nonRecursiveComma("1")) fmt.Println(enhancedComma("1234")) fmt.Println(enhancedComma("+1234")) fmt.Println(enhancedComma("-12345.4556")) fmt.Println(enhancedComma("-12345678345634556.99999999")) fmt.Println(enhancedComma("12")) fmt.Println(comma("プローグラム")) fmt.Println(isAnagram("Hello", "olleH")) fmt.Println(isAnagram("Hello", "Hello!")) fmt.Println(isAnagram("H", "H")) }
ch3/strings/strings.go
0.671794
0.445469
strings.go
starcoder
package pointers import ( "time" ) // ---- Public Functions ---- // Bool receives an input of bool and returns a pointer to that type. func Bool(b bool) *bool { return &b } // Byte receives an input of byte and returns a pointer to that type. func Byte(b byte) *byte { return &b } // Complex64 receives an input of complex64 and returns a pointer to that type. func Complex64(c complex64) *complex64 { return &c } // Complex128 receives an input of complex128 and returns a pointer to that type. func Complex128(c complex128) *complex128 { return &c } // Error receives an input of error and returns a pointer to that type. func Error(e error) *error { return &e } // Float32 receives an input of float32 and returns a pointer to that type. func Float32(f float32) *float32 { return &f } // Float64 receives an input of float64 and returns a pointer to that type. func Float64(f float64) *float64 { return &f } // Int receives an input of int and returns a pointer to that type. func Int(i int) *int { return &i } // Int8 receives an input of int8 and returns a pointer to that type. func Int8(i int8) *int8 { return &i } // Int16 receives an input of int16 and returns a pointer to that type. func Int16(i int16) *int16 { return &i } // Int32 receives an input of int32 and returns a pointer to that type. func Int32(i int32) *int32 { return &i } // Int64 receives an input of int64 and returns a pointer to that type. func Int64(i int64) *int64 { return &i } // Rune receives an input of rune and returns a pointer to that type. func Rune(r rune) *rune { return &r } // String receives an input of string and returns a pointer to that type. func String(s string) *string { return &s } // Uint receives an input of uint and returns a pointer to that type. func Uint(u uint) *uint { return &u } // Uint8 receives an input of uint8 and returns a pointer to that type. func Uint8(u uint8) *uint8 { return &u } // Uint16 receives an input of uint16 and returns a pointer to that type. func Uint16(u uint16) *uint16 { return &u } // Uint32 receives an input of uint32 and returns a pointer to that type. func Uint32(u uint32) *uint32 { return &u } // Uint64 receives an input of uint64 and returns a pointer to that type. func Uint64(u uint64) *uint64 { return &u } // Uintptr receives an input of uintptr and returns a pointer to that type. func Uintptr(u uintptr) *uintptr { return &u } // Duration receives an input of time.Duration and returns a pointer to that type. func Duration(d time.Duration) *time.Duration { return &d } // Time receives an input of time.Time and returns a pointer to that type. func Time(t time.Time) *time.Time { return &t }
pointers.go
0.846546
0.498657
pointers.go
starcoder
package mlpack /* #cgo CFLAGS: -I./capi -Wall #cgo LDFLAGS: -L. -lmlpack_go_local_coordinate_coding #include <capi/local_coordinate_coding.h> #include <stdlib.h> */ import "C" import "gonum.org/v1/gonum/mat" type LocalCoordinateCodingOptionalParam struct { Atoms int InitialDictionary *mat.Dense InputModel *localCoordinateCoding Lambda float64 MaxIterations int Normalize bool Seed int Test *mat.Dense Tolerance float64 Training *mat.Dense Verbose bool } func LocalCoordinateCodingOptions() *LocalCoordinateCodingOptionalParam { return &LocalCoordinateCodingOptionalParam{ Atoms: 0, InitialDictionary: nil, InputModel: nil, Lambda: 0, MaxIterations: 0, Normalize: false, Seed: 0, Test: nil, Tolerance: 0.01, Training: nil, Verbose: false, } } /* An implementation of Local Coordinate Coding (LCC), which codes data that approximately lives on a manifold using a variation of l1-norm regularized sparse coding. Given a dense data matrix X with n points and d dimensions, LCC seeks to find a dense dictionary matrix D with k atoms in d dimensions, and a coding matrix Z with n points in k dimensions. Because of the regularization method used, the atoms in D should lie close to the manifold on which the data points lie. The original data matrix X can then be reconstructed as D * Z. Therefore, this program finds a representation of each point in X as a sparse linear combination of atoms in the dictionary D. The coding is found with an algorithm which alternates between a dictionary step, which updates the dictionary D, and a coding step, which updates the coding matrix Z. To run this program, the input matrix X must be specified (with -i), along with the number of atoms in the dictionary (-k). An initial dictionary may also be specified with the "InitialDictionary" parameter. The l1-norm regularization parameter is specified with the "Lambda" parameter. For example, to run LCC on the dataset data using 200 atoms and an l1-regularization parameter of 0.1, saving the dictionary "Dictionary" and the codes into "Codes", use // Initialize optional parameters for LocalCoordinateCoding(). param := mlpack.LocalCoordinateCodingOptions() param.Training = data param.Atoms = 200 param.Lambda = 0.1 codes, dict, _ := mlpack.LocalCoordinateCoding(param) The maximum number of iterations may be specified with the "MaxIterations" parameter. Optionally, the input data matrix X can be normalized before coding with the "Normalize" parameter. An LCC model may be saved using the "OutputModel" output parameter. Then, to encode new points from the dataset points with the previously saved model lcc_model, saving the new codes to new_codes, the following command can be used: // Initialize optional parameters for LocalCoordinateCoding(). param := mlpack.LocalCoordinateCodingOptions() param.InputModel = &lcc_model param.Test = points new_codes, _, _ := mlpack.LocalCoordinateCoding(param) Input parameters: - Atoms (int): Number of atoms in the dictionary. Default value 0. - InitialDictionary (mat.Dense): Optional initial dictionary. - InputModel (localCoordinateCoding): Input LCC model. - Lambda (float64): Weighted l1-norm regularization parameter. Default value 0. - MaxIterations (int): Maximum number of iterations for LCC (0 indicates no limit). Default value 0. - Normalize (bool): If set, the input data matrix will be normalized before coding. - Seed (int): Random seed. If 0, 'std::time(NULL)' is used. Default value 0. - Test (mat.Dense): Test points to encode. - Tolerance (float64): Tolerance for objective function. Default value 0.01. - Training (mat.Dense): Matrix of training data (X). - Verbose (bool): Display informational messages and the full list of parameters and timers at the end of execution. Output parameters: - codes (mat.Dense): Output codes matrix. - dictionary (mat.Dense): Output dictionary matrix. - outputModel (localCoordinateCoding): Output for trained LCC model. */ func LocalCoordinateCoding(param *LocalCoordinateCodingOptionalParam) (*mat.Dense, *mat.Dense, localCoordinateCoding) { resetTimers() enableTimers() disableBacktrace() disableVerbose() restoreSettings("Local Coordinate Coding") // Detect if the parameter was passed; set if so. if param.Atoms != 0 { setParamInt("atoms", param.Atoms) setPassed("atoms") } // Detect if the parameter was passed; set if so. if param.InitialDictionary != nil { gonumToArmaMat("initial_dictionary", param.InitialDictionary) setPassed("initial_dictionary") } // Detect if the parameter was passed; set if so. if param.InputModel != nil { setLocalCoordinateCoding("input_model", param.InputModel) setPassed("input_model") } // Detect if the parameter was passed; set if so. if param.Lambda != 0 { setParamDouble("lambda", param.Lambda) setPassed("lambda") } // Detect if the parameter was passed; set if so. if param.MaxIterations != 0 { setParamInt("max_iterations", param.MaxIterations) setPassed("max_iterations") } // Detect if the parameter was passed; set if so. if param.Normalize != false { setParamBool("normalize", param.Normalize) setPassed("normalize") } // Detect if the parameter was passed; set if so. if param.Seed != 0 { setParamInt("seed", param.Seed) setPassed("seed") } // Detect if the parameter was passed; set if so. if param.Test != nil { gonumToArmaMat("test", param.Test) setPassed("test") } // Detect if the parameter was passed; set if so. if param.Tolerance != 0.01 { setParamDouble("tolerance", param.Tolerance) setPassed("tolerance") } // Detect if the parameter was passed; set if so. if param.Training != nil { gonumToArmaMat("training", param.Training) setPassed("training") } // Detect if the parameter was passed; set if so. if param.Verbose != false { setParamBool("verbose", param.Verbose) setPassed("verbose") enableVerbose() } // Mark all output options as passed. setPassed("codes") setPassed("dictionary") setPassed("output_model") // Call the mlpack program. C.mlpackLocalCoordinateCoding() // Initialize result variable and get output. var codesPtr mlpackArma codes := codesPtr.armaToGonumMat("codes") var dictionaryPtr mlpackArma dictionary := dictionaryPtr.armaToGonumMat("dictionary") var outputModel localCoordinateCoding outputModel.getLocalCoordinateCoding("output_model") // Clear settings. clearSettings() // Return output(s). return codes, dictionary, outputModel }
local_coordinate_coding.go
0.716913
0.425546
local_coordinate_coding.go
starcoder
package list import ( "github.com/peterzeller/go-fun/equality" "github.com/peterzeller/go-fun/iterable" "github.com/peterzeller/go-fun/slice" "github.com/peterzeller/go-fun/zero" ) // List is an immutable data type which is backed by a slice. type List[T any] struct { slice []T } // At returns the element at the given position func (l List[T]) At(i int) T { return l.slice[i] } // Iterator for the list. func (l List[T]) Iterator() iterable.Iterator[T] { state := 0 return iterable.Fun[T](func() (T, bool) { if state >= len(l.slice) { return zero.Value[T](), false } res := l.slice[state] state++ return res, true }) } // Length of the list. func (l List[T]) Length() int { return len(l.slice) } // Create a new list func New[T any](elems ...T) List[T] { s := make([]T, len(elems)) copy(s, elems) return List[T]{slice: s} } // Append another list to this list. func (l List[T]) Append(r List[T]) List[T] { if l.Length() == 0 { return r } if r.Length() == 0 { return l } s := make([]T, 0, len(l.slice)+len(r.slice)) return List[T]{slice: append(append(s, l.slice...), r.slice...)} } // Contains checks whether the list contains the given element. func (l List[T]) Contains(elem T, eq equality.Equality[T]) bool { return slice.ContainsEq(l.slice, elem, eq) } // Equal checks whether this list is equal to another list func (l List[T]) Equal(other *List[T], eq equality.Equality[T]) bool { return slice.Equal(l.slice, other.slice, eq) } // PrefixOf checks whether this list is a prefix of another list func (l List[T]) PrefixOf(other *List[T], eq equality.Equality[T]) bool { return slice.PrefixOf(l.slice, other.slice, eq) } // Forall checks whether all elements in the lists satisfy the given condition. func (l List[T]) Forall(cond func(T) bool) bool { return slice.Exists(l.slice, cond) } // Exists checks whether some element in the list satisfies the given condition. func (l List[T]) Exists(cond func(T) bool) bool { return slice.Exists(l.slice, cond) } // Skip the first n element of the list func (l List[T]) Skip(n int) List[T] { if n == 0 { return l } if n >= l.Length() { return New[T]() } return New(l.slice[n:]...) } // Limit the length of the list and take only the first n elements. func (l List[T]) Limit(n int) List[T] { if n == 0 { return New[T]() } if n >= l.Length() { return l } return New(l.slice[:n]...) }
list/list.go
0.745398
0.579192
list.go
starcoder
package arraylist import ( "errors" "github.com/WUMUXIAN/go-common-utils/datastructure/shared" ) type ArrayList struct { elements []interface{} size int capacity int Comparator shared.Comparator } // New creates a new array list with given comparator func New(comparator shared.Comparator) *ArrayList { // We give a capacity of 10 initially. return &ArrayList{ make([]interface{}, 10), 0, 10, comparator, } } func (a *ArrayList) ensureCapacity(newCapcity int) { if a.capacity > newCapcity { return } elements := make([]interface{}, newCapcity) copy(elements, a.elements) a.elements = elements a.capacity = newCapcity } // Append appends an element to the end of the array list func (a *ArrayList) Append(element interface{}) { a.Add(a.size, element) } // Add adds an element in front of the given index in the array list func (a *ArrayList) Add(index int, element interface{}) error { if index < 0 || index > a.size { return errors.New("index out of range") } if a.size == len(a.elements) { a.ensureCapacity(a.size*2 + 1) } for i := a.size - 1; i >= index; i-- { a.elements[i+1] = a.elements[i] } a.elements[index] = element a.size++ return nil } // Remove removes an element from the array list func (a *ArrayList) Remove(element interface{}) error { index, err := a.GetIndexOf(element) if err != nil { return errors.New("element not found") } return a.RemoveAt(index) } // RemoveAt removes an element at given index func (a *ArrayList) RemoveAt(index int) error { if index < 0 || index >= a.size { return errors.New("index out of range") } for i := index; i < a.size-1; i++ { a.elements[i] = a.elements[i+1] } a.size-- return nil } // GetIndexOf gets index of an element func (a *ArrayList) GetIndexOf(element interface{}) (int, error) { for i := 0; i < a.size; i++ { if a.Comparator(a.elements[i], element) == 0 { return i, nil } } return -1, errors.New("element not found") } // Get gets element at given index func (a *ArrayList) Get(index int) (interface{}, error) { if index < 0 || index >= a.size { return nil, errors.New("index out of range") } return a.elements[index], nil } // Set sets element at given index func (a *ArrayList) Set(index int, element interface{}) error { if index < 0 || index >= a.size { return errors.New("index out of range") } a.elements[index] = element return nil } // Contains checks whether the array list contains an element func (a *ArrayList) Contains(element interface{}) bool { _, err := a.GetIndexOf(element) return err == nil } // GetSize gets the size of the array list func (a *ArrayList) GetSize() int { return a.size } // Clear clears the array list func (a *ArrayList) Clear() { a.elements = make([]interface{}, 10) a.size = 0 a.capacity = 10 } // ToSlice returns the array list as a slice func (a *ArrayList) ToSlice() []interface{} { return a.elements[:a.size] } // Iterator gets the iterator func (a *ArrayList) Iterator() *Iterator { return &Iterator{a, -1} }
datastructure/arraylist/arraylist.go
0.742515
0.419886
arraylist.go
starcoder
package cogol import ( "fmt" "reflect" ) const ( failureMsg = "Expected %v, got %v" ) // assertion represents a typical assertion // Includes expected and actual values, as well as the context (ctx) of the the test type assertion struct { expected interface{} actual interface{} ctx *Context kill func(f *failure) } // failure represents a failed assertion, with the test's context (ctx) // and error message (msg) type failure struct { ctx *Context msg string } // fail is a more beautiful way to create a failure instance func (a *assertion) fail(msg string) *failure { return &failure{ctx: a.ctx, msg: msg} } // UseKiller allows users to use custom assertion killers func (ctx *Context) UseKiller(killer func(f *failure)) { ctx.assertionKiller = killer } // Expect creates a new assertion with actual value and nil as an expected one func (ctx *Context) Expect(actual interface{}) *assertion { return &assertion{nil, actual, ctx, ctx.assertionKiller} } // defaultKiller just calls ctx.Kill method instead of doing some fancy stuff func defaultKiller(f *failure) { f.ctx.Kill(f.msg) } // ToBe receives an expected assertion value and then compares it to the actual one, if they do not match, killer-method id called func (a *assertion) ToBe(expected interface{}) { a.expected = expected if a.actual == nil { a.kill(a.fail( fmt.Sprintf(failureMsg, a.expected, "nil", )), ) return } if reflect.TypeOf(a.expected) != reflect.TypeOf(a.actual) { a.kill(a.fail( fmt.Sprintf(failureMsg, "type to be "+reflect.TypeOf(a.expected).String(), reflect.TypeOf(a.actual).String()), )) return } if !reflect.DeepEqual(a.expected, a.actual) { a.kill(a.fail( fmt.Sprintf(failureMsg, a.expected, a.actual), )) return } a.ctx.test.success = true } func (a *assertion) ToBeNot(unexpected interface{}) { if reflect.DeepEqual(a.actual, unexpected) { a.kill(a.fail( fmt.Sprintf("Expected %v to be not %v", a.actual, unexpected), )) return } a.ctx.test.success = true } func (a *assertion) ToBeNil() { if a.actual != nil { a.kill(a.fail( fmt.Sprintf(failureMsg, "nil", a.actual), )) return } a.ctx.test.success = true } func (a *assertion) ToBeNotNil() { if a.actual == nil { a.kill(a.fail( fmt.Sprintf(failureMsg, "not nil", "nil"), )) return } a.ctx.test.success = true } func (a *assertion) ToBeZero() { if !reflect.ValueOf(a.actual).IsZero() { a.kill(a.fail( fmt.Sprintf(failureMsg, "zero value for "+reflect.TypeOf(a.actual).String()+" type", a.actual), )) return } a.ctx.test.success = true } func (a *assertion) ToBeNotZero() { if reflect.ValueOf(a.actual).IsZero() { a.kill(a.fail( fmt.Sprintf(failureMsg, "not zero value for "+reflect.TypeOf(a.actual).String()+" type", "zero value"), )) return } a.ctx.test.success = true } func (a *assertion) ToBeTrue() { if !reflect.DeepEqual(a.actual, true) { a.kill(a.fail( fmt.Sprintf(failureMsg, "true", a.actual), )) return } a.ctx.test.success = true } func (a *assertion) ToBeFalse() { if !reflect.DeepEqual(a.actual, false) { a.kill(a.fail( fmt.Sprintf(failureMsg, "false", a.actual), )) return } a.ctx.test.success = true }
assertions.go
0.606615
0.524029
assertions.go
starcoder
package poc import ( "math/big" "github.com/shopspring/decimal" ) const ( iterativeMPrecision = 256 iterativeDecimalPrecision = 256 ) var ( //bigDecimalZero = decimal.NewFromInt(0) bigDecimalOne = decimal.NewFromInt(1) bigDecimalTwo = decimal.NewFromInt(2) power2Table [257]*big.Int negPower2Table [257]decimal.Decimal ) func init() { // fill negPower2Table negPower2Table[0] = decimal.NewFromInt(1) for i := 1; i <= 256; i++ { negPower2Table[i] = negPower2Table[i-1].DivRound(bigDecimalTwo, iterativeDecimalPrecision) } // fill power2Table var bigTwo = big.NewInt(2) power2Table[0] = big.NewInt(1) for i := 1; i <= 256; i++ { power2Table[i] = new(big.Int).Mul(power2Table[i-1], bigTwo) } } func log2ByIterative(hi *big.Int) decimal.Decimal { p, r := extractH(hi) // hi = 2^p + r y := decimal.NewFromBigInt(r, 0) y = y.DivRound(decimal.NewFromBigInt(power2Table[p], 0), iterativeDecimalPrecision) y = y.Add(bigDecimalOne) // y = 1 + r / (2^p), 1 <= y < 2 log2Y := iterativeLog2(y) pd := decimal.NewFromInt(int64(p)) return pd.Add(log2Y) } func iterativeLog2(y decimal.Decimal) decimal.Decimal { if y.Equal(bigDecimalOne) { return decimal.NewFromInt(0) } if y.Equal(bigDecimalTwo) { return decimal.NewFromInt(1) } var result = decimal.NewFromInt(0) var m, accumulatedM int var z = y.Mul(bigDecimalTwo) var ok bool for { m, z, ok = iterativeLog2GetM(z.DivRound(bigDecimalTwo, iterativeDecimalPrecision), accumulatedM) if !ok { break } accumulatedM += m result = result.Add(negPower2Table[accumulatedM]) } return result } func iterativeLog2GetM(y decimal.Decimal, accumulatedM int) (m int, z decimal.Decimal, ok bool) { z = decimal.NewFromInt(0).Add(y) for m+accumulatedM < iterativeMPrecision { m++ z = z.Mul(z) z = z.Round(iterativeDecimalPrecision) if z.GreaterThanOrEqual(bigDecimalTwo) { return m, z, true } } return iterativeMPrecision + 1, z, false } func calcQualityByDecimal(bl int, h *big.Int, log2Func func(*big.Int) decimal.Decimal) *big.Int { // Note: Q1 = SIZE * BL Q1 := decimal.NewFromInt(int64(1 << uint(bl) * bl)) // Note: log2FH = log2(H) log2FH := log2Func(h) // Note: Q2 = 256 - log2(H) Q2 := decimal.NewFromInt(256) Q2 = Q2.Sub(log2FH) if Q2.Cmp(decimal.NewFromInt(0)) <= 0 { panic("Zero") } Quality := Q1.DivRound(Q2, iterativeDecimalPrecision).BigInt() return Quality } // extractH takes hi ranges in (0, 2^257) func extractH(hi *big.Int) (exp int, r *big.Int) { for i := 256; i >= 0; i-- { t := power2Table[i] c := hi.Cmp(t) if c < 0 { continue } return i, new(big.Int).Sub(hi, t) } panic(hi.String()) } func (proof *DefaultProof) GetQualityByIterative(slot, height uint64) *big.Int { hashVal := proof.GetHashVal(slot, height) // Note: Q1 = SIZE * BL Q1 := decimal.NewFromInt(int64(1 << uint(proof.BL) * proof.BL)) // Note: BH = H in BigInt BH := new(big.Int).SetBytes(hashVal[:]) // Note: log2FH = log2(H) log2FH := log2ByIterative(BH) // Note: Q2 = 256 - log2(H) Q2 := decimal.NewFromInt(256) Q2 = Q2.Sub(log2FH) if Q2.Cmp(decimal.NewFromInt(0)) <= 0 { panic("Zero") } Quality := Q1.DivRound(Q2, iterativeDecimalPrecision).BigInt() return Quality }
poc/log2.go
0.61057
0.421373
log2.go
starcoder
package cp import "math" type DampedSpringForceFunc func(spring *DampedSpring, dist float64) float64 type DampedSpring struct { *Constraint AnchorA, AnchorB Vector RestLength, Stiffness, Damping float64 SpringForceFunc DampedSpringForceFunc targetVrn, vCoef float64 r1, r2 Vector nMass float64 n Vector jAcc float64 } func NewDampedSpring(a, b *Body, anchorA, anchorB Vector, restLength, stiffness, damping float64) *Constraint { spring := &DampedSpring{ AnchorA: anchorA, AnchorB: anchorB, RestLength: restLength, Stiffness: stiffness, Damping: damping, SpringForceFunc: DefaultSpringForce, jAcc: 0, } spring.Constraint = NewConstraint(spring, a, b) return spring.Constraint } func (spring *DampedSpring) PreStep(dt float64) { a := spring.a b := spring.b spring.r1 = a.transform.Vect(spring.AnchorA.Sub(a.cog)) spring.r2 = b.transform.Vect(spring.AnchorB.Sub(b.cog)) delta := b.p.Add(spring.r2).Sub(a.p.Add(spring.r1)) dist := delta.Length() if dist != 0 { spring.n = delta.Mult(1.0 / dist) } else { spring.n = delta.Mult(1.0 / INFINITY) } k := k_scalar(a, b, spring.r1, spring.r2, spring.n) assert(k != 0, "Unsolvable spring") spring.nMass = 1.0 / k spring.targetVrn = 0 spring.vCoef = 1.0 - math.Exp(-spring.Damping*dt*k) fSpring := spring.SpringForceFunc(spring, dist) spring.jAcc = fSpring * dt apply_impulses(a, b, spring.r1, spring.r2, spring.n.Mult(spring.jAcc)) } func (spring *DampedSpring) ApplyCachedImpulse(dt_coef float64) { // nothing to do here } func (spring *DampedSpring) ApplyImpulse(dt float64) { a := spring.a b := spring.b n := spring.n r1 := spring.r1 r2 := spring.r2 vrn := normal_relative_velocity(a, b, r1, r2, n) vDamp := (spring.targetVrn - vrn) * spring.vCoef spring.targetVrn = vrn + vDamp jDamp := vDamp * spring.nMass spring.jAcc += jDamp apply_impulses(a, b, spring.r1, spring.r2, spring.n.Mult(jDamp)) } func (spring *DampedSpring) GetImpulse() float64 { return spring.jAcc } func DefaultSpringForce(spring *DampedSpring, dist float64) float64 { return (spring.RestLength - dist) * spring.Stiffness }
dampedspring.go
0.83772
0.451266
dampedspring.go
starcoder
package nitro import ( "image" "image/color" ) // Tiled is an image.Image whose pixels are stored as a sequence of 8x8 tiles. // Since it is conceptually one-dimensional, its bounds may be undefined. type Tiled struct { Pix []uint8 Stride int // number of tiles per row Rect image.Rectangle Palette color.Palette } func (t *Tiled) ColorModel() color.Model { return t.Palette } func (t *Tiled) Bounds() image.Rectangle { return t.Rect } // Tile returns an image representing a portion of t. // The upper left tile of the returned image will be the nth tile in t, // and the tiles following the nth tile will fill the remaining width and // height of the returned image from left to right, top to bottom. // The returned value shares pixels with the original image. func (t *Tiled) Tile(n, width, height int) *Tiled { if n*64 >= len(t.Pix) { return &Tiled{ Palette: t.Palette, } } r := image.Rect(0, 0, width, height) stride := (width + 7) / 8 return &Tiled{ Pix: t.Pix[n*64:], Rect: r, Stride: stride, Palette: t.Palette, } } // PixOffset returns the index Pix that corresponds to the pixel at (x, y). func (t *Tiled) PixOffset(x, y int) int { // TODO: try to get this under the inlining limit x, y = x-t.Rect.Min.X, y-t.Rect.Min.Y return (y/8*t.Stride+x/8)*64 + y%8*8 + x%8 } func (t *Tiled) ColorIndexAt(x, y int) uint8 { if !image.Pt(x, y).In(t.Rect) { return 0 } i := t.PixOffset(x, y) if i >= len(t.Pix) { return 0 } return t.Pix[i] } func (t *Tiled) SetColorIndex(x, y int, index uint8) { if !image.Pt(x, y).In(t.Rect) { return } i := t.PixOffset(x, y) if i >= len(t.Pix) { return } t.Pix[i] = index } func (t *Tiled) At(x, y int) color.Color { if len(t.Palette) == 0 { return nil } if !image.Pt(x, y).In(t.Rect) { return t.Palette[0] } i := t.PixOffset(x, y) if i >= len(t.Pix) { return t.Palette[0] } return t.Palette[t.Pix[i]] } func (t *Tiled) Set(x, y int, c color.Color) { if !image.Pt(x, y).In(t.Rect) { return } i := t.PixOffset(x, y) if i >= len(t.Pix) { return } t.Pix[i] = uint8(t.Palette.Index(c)) } func NewTiled(r image.Rectangle, pal color.Palette) *Tiled { return &Tiled{ Pix: make([]uint8, r.Dx()*r.Dy()), Rect: r, Stride: r.Dx() / 8, Palette: pal, } }
nitro/tiled.go
0.770637
0.613208
tiled.go
starcoder
package ns_x import ( "github.com/bytedance/ns-x/v2/base" "reflect" "strconv" "strings" ) // Builder is a convenience tool to describe the whole network and build // when a node is described for the first time, a unique id is assigned to it, which will be the index of node in the built network type Builder interface { // Chain save the current chain and begin to describe a new chain Chain() Builder // Node connect the given node to the end of current chain Node(node base.Node) Builder // Group insert a group to current chain, which means end of current chain will be connected to in node, and the end of current chain will be set to out node Group(inName, outName string) Builder // NodeWithName same to Node, but name it with the given name NodeWithName(name string, node base.Node) Builder // GroupWithName same to Group, but name the whole group with the given name GroupWithName(name string, inName, outName string) Builder // NodeOfName find the node with the given name, and then connect it to the end of the chain NodeOfName(name string) Builder // GroupOfName find the group with the given name, and then perform the Group operation on it GroupOfName(name string) Builder // Summary print the structure of the network to standard output Summary() Builder // Build actually connect the nodes with relation described before, any connection outside the builder will be overwritten // parameters are used to configure the network, return the built network, and a map from name to named nodes Build() (*Network, map[string]base.Node) } type group struct { inName, outName string } type builder struct { nodeToID map[base.Node]int nameToNode map[string]base.Node nodeToName map[base.Node]string nameToGroup map[string]*group current base.Node connections map[base.Node]map[base.Node]interface{} } func NewBuilder() Builder { return &builder{ nodeToID: map[base.Node]int{}, nameToNode: map[string]base.Node{}, nodeToName: map[base.Node]string{}, nameToGroup: map[string]*group{}, connections: map[base.Node]map[base.Node]interface{}{}, } } func (b *builder) Chain() Builder { b.current = nil return b } func (b *builder) Node(node base.Node) Builder { return b.NodeWithName("", node) } func (b *builder) NodeWithName(name string, node base.Node) Builder { if b.current != nil { connection, ok := b.connections[b.current] if !ok { connection = map[base.Node]interface{}{} b.connections[b.current] = connection } connection[node] = nil } if _, ok := b.nodeToID[node]; !ok { b.nodeToID[node] = len(b.nodeToID) } if name != "" { b.nameToNode[name] = node b.nodeToName[node] = name } b.current = node return b } func (b *builder) Group(inName, outName string) Builder { return b.GroupWithName("", inName, outName) } func (b *builder) GroupWithName(name string, inName, outName string) Builder { if name != "" { b.nameToGroup[name] = &group{inName: inName, outName: outName} } in := b.requireNodeByName(inName) out := b.requireNodeByName(outName) b.Node(in) b.current = out return b } func (b *builder) NodeOfName(name string) Builder { return b.Node(b.requireNodeByName(name)) } func (b *builder) GroupOfName(name string) Builder { group, ok := b.nameToGroup[name] if !ok { panic("no group with name: " + name) } return b.Group(group.inName, group.outName) } func (b *builder) Summary() Builder { nodes := make([]base.Node, len(b.nodeToID)) println("network summary: ") for node, index := range b.nodeToID { nodes[index] = node } for index, node := range nodes { println(b.toString(node, index)) } println() return b } func (b *builder) Build() (*Network, map[string]base.Node) { nodes := make([]base.Node, len(b.nodeToID)) for node, index := range b.nodeToID { nodes[index] = node } for node, connection := range b.connections { node.SetNext(normalize(connection)...) } return NewNetwork(nodes), b.nameToNode } func (b *builder) toString(node base.Node, index int) string { sb := strings.Builder{} sb.WriteString("node ") sb.WriteString(strconv.Itoa(index)) sb.WriteString(": {name: \"") sb.WriteString(b.nodeToName[node]) sb.WriteString("\", type: ") t := reflect.TypeOf(node) if t.Kind() == reflect.Ptr { sb.WriteString(t.Elem().Name()) } else { sb.WriteString(t.Name()) } sb.WriteString(", next: [") connection := b.connections[node] next := make([]string, 0, len(connection)) for n := range connection { next = append(next, strconv.Itoa(b.nodeToID[n])) } sb.WriteString(strings.Join(next, ",")) sb.WriteString("]}") return sb.String() } func normalize(nodes map[base.Node]interface{}) []base.Node { result := make([]base.Node, 0, len(nodes)) for node := range nodes { result = append(result, node) } return result } func (b *builder) requireNodeByName(name string) base.Node { if name == "" { panic("name cannot be empty string") } node, ok := b.nameToNode[name] if !ok { panic("no node with name " + name) } return node }
builder.go
0.533397
0.532486
builder.go
starcoder
package kameria import ( mathOld "math" "reflect" "time" kmath "github.com/M-Quadra/kameria/k-math" ) type math struct{} // Math for call kmath func simply without type var Math = math{} // only support for ...{int|int64|string|float32|float64|time.Time} // default nil func (m math) Max(x ...interface{}) interface{} { if len(x) <= 0 { return nil } switch x[0].(type) { case int: return kmath.Max.Any(x, func(a, b interface{}) bool { return a.(int) < b.(int) }) case int64: return kmath.Max.Any(x, func(a, b interface{}) bool { return a.(int64) < b.(int64) }) case string: return kmath.Max.Any(x, func(a, b interface{}) bool { return a.(string) < b.(string) }) case float32: return kmath.Max.Any(x, func(a, b interface{}) bool { return a.(float32) < b.(float32) }) case float64: return kmath.Max.Any(x, func(a, b interface{}) bool { return a.(float64) < b.(float64) }) case time.Time: return kmath.Max.Any(x, func(a, b interface{}) bool { return a.(time.Time).Before(b.(time.Time)) }) } return nil } // only support for ...{int|int64|string|float32|float64|time.Time} // default nil func (m math) Min(x ...interface{}) interface{} { if len(x) <= 0 { return nil } switch x[0].(type) { case int: return kmath.Min.Any(x, func(a, b interface{}) bool { return a.(int) > b.(int) }) case int64: return kmath.Min.Any(x, func(a, b interface{}) bool { return a.(int64) > b.(int64) }) case string: return kmath.Min.Any(x, func(a, b interface{}) bool { return a.(string) > b.(string) }) case float32: return kmath.Min.Any(x, func(a, b interface{}) bool { return a.(float32) > b.(float32) }) case float64: return kmath.Min.Any(x, func(a, b interface{}) bool { return a.(float64) > b.(float64) }) case time.Time: return kmath.Min.Any(x, func(a, b interface{}) bool { return a.(time.Time).After(b.(time.Time)) }) } return nil } // only support for []{int|int64|float32|float64} // default nil func (m math) Sum(x interface{}) interface{} { rv := reflect.ValueOf(x) if rv.Len() <= 0 { return nil } switch rv.Index(0).Interface().(type) { case int: return kmath.Reduce(x, int(0), func(result, elem interface{}) interface{} { return result.(int) + elem.(int) }).(int) case int64: return kmath.Reduce(x, int64(0), func(result, elem interface{}) interface{} { return result.(int64) + elem.(int64) }) case float32: return kmath.Reduce(x, float32(0), func(result, elem interface{}) interface{} { return result.(float32) + elem.(float32) }) case float64: return kmath.Reduce(x, float64(0), func(result, elem interface{}) interface{} { return result.(float64) + elem.(float64) }) } return nil } // only support for []{int|int64|float32|float64} // default 0 func (m math) Mean(x interface{}) float64 { rv := reflect.ValueOf(x) l := rv.Len() if l <= 0 { return 0 } switch rv.Index(0).Interface().(type) { case int: return kmath.Reduce(x, float64(0), func(result, elem interface{}) interface{} { return result.(float64) + float64(elem.(int))/float64(l) }).(float64) case int64: return kmath.Reduce(x, float64(0), func(result, elem interface{}) interface{} { return result.(float64) + float64(elem.(int64))/float64(l) }).(float64) case float32: return kmath.Reduce(x, float64(0), func(result, elem interface{}) interface{} { return result.(float64) + float64(elem.(float32))/float64(l) }).(float64) case float64: return kmath.Reduce(x, float64(0), func(result, elem interface{}) interface{} { return result.(float64) + elem.(float64)/float64(l) }).(float64) } return 0 } //Limit4Int return mid ∈ [min, max] func Limit4Int(min, mid, max int) int { if min > max { min, max = max, min } mid = kmath.Max.Ints(min, mid) mid = kmath.Min.Ints(mid, max) return mid } //Limit4Int64 return mid ∈ [min, max] func Limit4Int64(min, mid, max int64) int64 { if min > max { min, max = max, min } mid = kmath.Max.Int64s(min, mid) mid = kmath.Min.Int64s(mid, max) return mid } //Limit4Float32 return mid ∈ [min, max] func Limit4Float32(min, mid, max float32) float32 { return float32(Limit4Float64(float64(min), float64(mid), float64(max))) } //Limit4Float64 return mid ∈ [min, max] func Limit4Float64(min, mid, max float64) float64 { nMin := mathOld.Min(min, max) nMax := mathOld.Max(min, max) mid = mathOld.Max(nMin, mid) mid = mathOld.Min(mid, nMax) return mid } // SoftmaxFloat64 softmax func SoftmaxFloat64(ary []float64) []float64 { if ary == nil { return nil } if len(ary) <= 0 { return []float64{} } optAry := []float64{} sum := 0.0 for i, v := range ary { optAry = append(optAry, mathOld.Exp(v)) sum += optAry[i] } for i := range optAry { optAry[i] /= sum } return optAry }
math.go
0.595022
0.414129
math.go
starcoder
// Sample program to show how to grow a slice using the built-in function append // and how append grows the capacity of the underlying array. package main import "fmt" func main() { // Declare a nil slice of strings. var data []string // Capture the capacity of the slice. lastCap := cap(data) // Append ~100k strings to the slice. for record := 1; record <= 1e5; record++ { // Use the built-in function append to add to the slice. value := fmt.Sprintf("Rec: %d", record) data = append(data, value) // When the capacity of the slice changes, display the changes. if lastCap != cap(data) { // Calculate the percent of change. capChg := float64(cap(data)-lastCap) / float64(lastCap) * 100 // Save the new values for capacity. lastCap = cap(data) // Display the results. fmt.Printf("Addr[%p]\tIndex[%d]\t\tCap[%d - %2.f%%]\n", &data[0], record, cap(data), capChg) } } } // Outputs: // Addr[0xc000010200] Index[1] Cap[1 - +Inf%] // Addr[0xc00000c080] Index[2] Cap[2 - 100%] // Addr[0xc000064080] Index[3] Cap[4 - 100%] // Addr[0xc00007e000] Index[5] Cap[8 - 100%] // Addr[0xc000080000] Index[9] Cap[16 - 100%] // Addr[0xc00007c200] Index[17] Cap[32 - 100%] // Addr[0xc000082000] Index[33] Cap[64 - 100%] // Addr[0xc000084000] Index[65] Cap[128 - 100%] // Addr[0xc000079000] Index[129] Cap[256 - 100%] // Addr[0xc000086000] Index[257] Cap[512 - 100%] // Addr[0xc00008a000] Index[513] Cap[1024 - 100%] // Addr[0xc000090000] Index[1025] Cap[1280 - 25%] // Addr[0xc00009a000] Index[1281] Cap[1704 - 33%] // Addr[0xc0000b2000] Index[1705] Cap[2560 - 50%] // Addr[0xc0000c0000] Index[2561] Cap[3584 - 40%] // Addr[0xc0000d4000] Index[3585] Cap[4608 - 29%] // Addr[0xc0000ec000] Index[4609] Cap[6144 - 33%] // Addr[0xc00010e000] Index[6145] Cap[7680 - 25%] // Addr[0xc000134000] Index[7681] Cap[9728 - 27%] // Addr[0xc000166000] Index[9729] Cap[12288 - 26%] // Addr[0xc0001a6000] Index[12289] Cap[15360 - 25%] // Addr[0xc0001f4000] Index[15361] Cap[19456 - 27%] // Addr[0xc000258000] Index[19457] Cap[24576 - 26%] // Addr[0xc0002d6000] Index[24577] Cap[30720 - 25%] // Addr[0xc000372000] Index[30721] Cap[38400 - 25%] // Addr[0xc000434000] Index[38401] Cap[48128 - 25%] // Addr[0xc00053c000] Index[48129] Cap[60416 - 26%] // Addr[0xc000628000] Index[60417] Cap[75776 - 25%] // Addr[0xc000750000] Index[75777] Cap[94720 - 25%] // Addr[0xc0008c2000] Index[94721] Cap[118784 - 25%]
content/docs/language/slices/example4/example4.go
0.672977
0.682838
example4.go
starcoder
package cmd // FunctionCall represents the details of the function call type FunctionCall struct { // ContractAddress Is a field element of 251 bits. Represented as up to 64 hex digits ContractAddress string `json:"contract_address"` // EntryPointSelector Is a field element of 251 bits. Represented as up to 64 hex digits EntryPointSelector string `json:"entry_point_selector"` // CallData are the parameters passed to the function CallData []string } // BlockHash Is a field element of 251 bits. Represented as up to 64 hex digits type BlockHash string // BlockTag Is a tag specifying a dynamic reference to a block type BlockTag string // Felt represent aN field element. Represented as up to 63 hex digits and leading 4 bits zeroed. type Felt string // BlockNumber The block's number (its height) type BlockNumber uint64 // ChainID StarkNet chain id, given in hex representation. type ChainID string // ProtocolVersion StarkNet protocol version, given in hex representation. type ProtocolVersion string type BlockNumberOrTag struct { BlockNumber BlockTag } // BlockHashOrTag The hash (id) of the requested block or a block tag, for the block referencing the state or call the transaction on. type BlockHashOrTag struct { BlockHash BlockTag } // RequestRPC Represent the calls a function in a contract and returns the return value. Using this call will not create a transaction; hence, will not change the state type RequestRPC struct { Request FunctionCall `json:"request"` BlockHash BlockHash `json:"block_hash"` } // ResultCall Is a field element of 251 bits. Represented as up to 64 hex digits type ResultCall []string // BlockTransactionCount represent the number of transactions in the designated block type BlockTransactionCount struct { TransactionCount int } // StateDiffItem represent a change in a single storage item type StateDiffItem struct { // The contract address for which the state changed Address Felt `json:"address"` // The key of the changed value Key Felt `json:"key"` // THe new value applied to the given address Value Felt `json:"value"` } // ContractItem represent a new contract added as part of the new state type ContractItem struct { // The address of the contract code Address Felt `json:"address"` // The hash of the contract code ContractHash Felt `json:"contractHash"` } // StateDiff represent the change in state applied in this block, given as a mapping of addresses to the new values and/or new contracts type StateDiff struct { StorageDiffs []StateDiffItem `json:"storage_diffs"` Contracts []ContractItem `json:"contracts"` } type StateUpdate struct { BlockHash BlockHash `json:"block_hash"` NewRoot Felt `json:"new_root"` OldRoot Felt `json:"old_root"` AcceptedTime uint64 `json:"accepted_time"` StateDiff StateDiff `json:"state_diff"` } type Address Felt // TxnHash The transaction hash, as assigned in StarkNet type TxnHash Felt // Txn Transaction type Txn struct { // The function the transaction invokes FunctionCall // The hash identifying the transaction TxnHash TxnHash `json:"txn_hash"` } type TxnStatus string const ( TxnStatusUnknown TxnStatus = "UNKNOWN" TxnStatusReceived = "RECEIVED" TxnStatusPending = "PENDING" TxnStatusAcceptedOnL2 = "ACCEPTED_ON_L2" TxnStatusAcceptedOnL1 = "ACCEPTED_ON_L1" TxnStatusRejected = "REJECTED" ) // EthAddress represent an ethereum address type EthAddress string type MsgToL1 struct { // The target L1 address the message is sent to ToAddress Felt `json:"to_address"` // The Payload of the message Payload Felt `json:"payload"` } type MsgToL2 struct { // The originating L1 contract that sent the message FromAddress EthAddress `json:"from_address"` // The Payload of the message. The call data to the L1 handler Payload []Felt `json:"payload"` } // EventFilter represent an event filter/query type EventFilter struct { FromBlock BlockNumber `json:"fromBlock"` ToBlock BlockNumber `json:"toBlock"` Address Address `json:"address"` Keys []Felt `json:"keys"` } // EventContent represent the content of an Event type EventContent struct { Keys []Felt `json:"keys"` Data []Felt `json:"data"` } // Event represent a StarkNet Event type Event struct { EventContent FromAddress Address `json:"from_address"` } // EmittedEvent Represent Event information decorated with metadata on where it was emitted type EmittedEvent struct { Event BlockHash BlockHash `json:"block_hash"` TransactionHash TxnHash `json:"transaction_hash"` } // TxnReceipt Receipt of the transaction type TxnReceipt struct { TxnHash TxnHash `json:"txn_hash"` Status TxnStatus `json:"status"` StatusData string `json:"status_data"` MessagesSent []MsgToL1 `json:"messages_sent"` L1OriginMessage MsgToL2 `json:"l1_origin_message"` Events Event `json:"events"` } // CodeResult The code and ABI for the requested contract type CodeResult struct { Bytecode []Felt `json:"bytecode"` // The ABI of the contract in JSON format. Uses the same structure as EVM ABI Abi string `json:"abi"` } // SyncStatus Returns an object about the sync status, or false if the node is not syncing type SyncStatus struct { // The hash of the block from which the sync started StartingBlock BlockHash `json:"starting_block"` // The hash of the current block being synchronized CurrentBlock BlockHash `json:"current_block"` // The hash of the estimated the highest block to be synchronized HighestBlock BlockHash `json:"highest_block"` } // ResultPageRequest A request for a specific page of results type ResultPageRequest struct { PageSize uint64 `json:"page_size"` PageNumber uint64 `json:"page_number"` }
cmd/cli/types.go
0.776581
0.531757
types.go
starcoder
package utils import "math" // May be three dimensional, like in vase mode type Segment struct { SegmentLength float64 FeedRate float64 FilamentFeedLength float64 LayerHeight float64 } type HotEnd struct { filamentDiameter float64 nozzleDiameter float64 feedRatio float64 filamentCrossSection float64 nozzleCrossSection float64 } func NewHotEnd(filamentDiameter float64, nozzleDiameter float64) HotEnd { return HotEnd{ filamentDiameter: filamentDiameter, nozzleDiameter: nozzleDiameter, filamentCrossSection: math.Pow(filamentDiameter/2, 2) * math.Pi, nozzleCrossSection: math.Pow(nozzleDiameter/2, 2) * math.Pi, feedRatio: math.Pow(filamentDiameter/2, 2) / math.Pow(nozzleDiameter/2, 2), } } func NewExtruder(hotEnd HotEnd) Extruder { return Extruder{ hotEnd: hotEnd, } } func (h HotEnd) FeedRatio() float64 { return h.feedRatio } type Extruder struct { hotEnd HotEnd } func (e Extruder) FullPrecisionSegmentVolume(segment Segment) (segmentVolume float64) { return e.hotEnd.filamentCrossSection * segment.FilamentFeedLength } func (e Extruder) FullPrecisionCrossSection(segment Segment) (crossSection float64) { return e.FullPrecisionSegmentVolume(segment) / segment.SegmentLength } func (e Extruder) FullPrecisionSegmentWidth(segment Segment) (extrusionWidth float64) { return (e.FullPrecisionCrossSection(segment)-math.Pi*math.Pow(segment.LayerHeight/2, 2))/segment.LayerHeight + segment.LayerHeight } func (e Extruder) SegmentVolume(segment Segment, decimals float64) (segmentVolume float64) { return round(e.FullPrecisionSegmentVolume(segment), decimals) } func (e Extruder) CrossSection(segment Segment, decimals float64) (crossSection float64) { return round(e.FullPrecisionCrossSection(segment), decimals) } func (e Extruder) SegmentWidth(segment Segment, decimals float64) (extrusionWidth float64) { return round(e.FullPrecisionSegmentWidth(segment), decimals) } func round(float float64, decimals float64) float64 { return math.Round(float*math.Pow(10, decimals)) / math.Pow(10, decimals) }
utils/calculation.go
0.836588
0.563678
calculation.go
starcoder
package geogoth // LineStringLength counts length of LineString func LineStringLength(linestr *LineString) float64 { var length float64 coords := linestr.Coords lineCoords := make([][]float64, 0) // Creates slice for coords of one line for i := range coords { y, x := linestr.Coords[i][0], linestr.Coords[i][1] lineCoords = append(lineCoords, []float64{y, x}) } for i := 0; i < len(lineCoords)-1; i++ { lengthTmp := DistancePointPointDeg(lineCoords[i][0], lineCoords[i][1], lineCoords[i+1][0], lineCoords[i+1][1]) length = length + lengthTmp } return length } // MultiLineStringLength counts length of MultiLineString func MultiLineStringLength(mlineStr MultiLineString) float64 { var length float64 lineCoords := make([][]float64, 0) // Creates slice for coords of one line mlineCoords := make([][][]float64, 0) // Creates slice for coords of the MultiLineString multlinestr := (mlineStr.Coords) // Convert interface to [][][]float64 for i := range multlinestr { // Finds coords of the MultiLineString for j := range multlinestr[i] { y, x := multlinestr[i][j][0], multlinestr[i][j][1] lineCoords = append(lineCoords, []float64{y, x}) } mlineCoords = append(mlineCoords, lineCoords) lineCoords = nil // empty slice } for i := range mlineCoords { for j := 0; j < len(mlineCoords[i])-1; j++ { lengthTmp := DistancePointPointDeg(mlineCoords[i][j][0], mlineCoords[i][j][1], mlineCoords[i][j+1][0], mlineCoords[i][j+1][1]) length = length + lengthTmp } } return length } // PolygonLength counts length of Polygon func PolygonLength(polygon Polygon) float64 { var length float64 lineCoords := make([][]float64, 0) // Creates slice for coords of one line polCoords := make([][][]float64, 0) // Creates slice for coords of the MultiLineString polygonCoords := polygon.Coords // Convert interface to [][][]float64 for i := range polygonCoords { // Finds coords of the MultiLineString for j := range polygonCoords[i] { y, x := polygon.Coords[i][j][0], polygon.Coords[i][j][1] lineCoords = append(lineCoords, []float64{y, x}) } polCoords = append(polCoords, lineCoords) lineCoords = nil // empty slice } for i := range polCoords { for j := 0; j < len(polCoords[i])-1; j++ { lengthTmp := DistancePointPointDeg(polCoords[i][j][0], polCoords[i][j][1], polCoords[i][j+1][0], polCoords[i][j+1][1]) length = length + lengthTmp } } return length } // MultipolygonLength counts length of MultipolygonLength func MultipolygonLength(mpolygon MultiPolygon) float64 { var length float64 mpolyg := mpolygon.Coords mpolygCoords := make([][][]float64, 0) // Creates slice for coords of the MultiPolygon mlineCoords := make([][]float64, 0) // Creates slice for coords of one line for m := range mpolyg { // Finds coords of MultiPolygon for p := range mpolyg[m] { for i := range mpolyg[m][p] { y, x := mpolygon.Coords[m][p][i][0], mpolygon.Coords[m][p][i][1] mlineCoords = append(mlineCoords, []float64{y, x}) } mpolygCoords = append(mpolygCoords, mlineCoords) mlineCoords = nil // empty slice } } for i := range mpolygCoords { for j := 0; j < len(mpolygCoords[i])-1; j++ { lengthTmp := DistancePointPointDeg(mpolygCoords[i][j][0], mpolygCoords[i][j][1], mpolygCoords[i][j+1][0], mpolygCoords[i][j+1][1]) length = length + lengthTmp } } return length }
lengths.go
0.816333
0.469095
lengths.go
starcoder
package main import ( "fmt" "log" "strings" "strconv" ) var input = "R3, R1, R4, L4, R3, R1, R1, L3, L5, L5, L3, R1, R4, L2, L1, R3, L3, R2, R1, R1, L5, L2, L1, R2, L4, R1, L2, L4, R2, R2, L2, L4, L3, R1, R4, R3, L1, R1, L5, R4, L2, R185, L2, R4, R49, L3, L4, R5, R1, R1, L1, L1, R2, L1, L4, R4, R5, R4, L3, L5, R1, R71, L1, R1, R186, L5, L2, R5, R4, R1, L5, L2, R3, R2, R5, R5, R4, R1, R4, R2, L1, R4, L1, L4, L5, L4, R4, R5, R1, L2, L4, L1, L5, L3, L5, R2, L5, R4, L4, R3, R3, R1, R4, L1, L2, R2, L1, R4, R2, R2, R5, R2, R5, L1, R1, L4, R5, R4, R2, R4, L5, R3, R2, R5, R3, L3, L5, L4, L3, L2, L2, R3, R2, L1, L1, L5, R1, L3, R3, R4, R5, L3, L5, R1, L3, L5, L5, L2, R1, L3, L1, L3, R4, L1, R3, L2, L2, R3, R3, R4, R4, R1, L4, R1, L5" type CompassDirection int const ( N CompassDirection = iota E S W ) type Point struct { North int East int } type Path struct { Location Point Bearing CompassDirection History map[Point]int } func main() { // start with no distances from starting point, facing north var path Path path.Init(0,0,N) // Remove white space, and create slice splitting on , from original input inp := strings.Split(strings.Join(strings.Fields(input),""),",") for _,step := range inp { if len(step) >= 2 { dir := string(step[0]) if mag,err := strconv.Atoi(string(step[1:])); err == nil { path.turn(dir) if done := path.move(mag); done { break; } } else { log.Fatal("Bad input") } } else { log.Fatal("Bad input") } } fmt.Println(path.Location) fmt.Println("Total distance: ", abs(path.Location.North) + abs(path.Location.East)) } func (p *Path) Init (north int, east int, bearing CompassDirection) { p.Location = Point{north, east} p.Bearing = bearing p.History = make(map[Point]int) } func (p *Path) turn (direction string) { switch direction { case "R": p.Bearing = (p.Bearing + 1) % 4 case "L": p.Bearing = (p.Bearing + 3) % 4 default: log.Fatal("Invalid turn") } } func (p *Path) move (magnitude int) bool { for i := 0; i < abs(magnitude); i++ { switch p.Bearing { case N: p.Location.North += 1 case E: p.Location.East += 1 case S: p.Location.North -= 1 case W: p.Location.East -= 1 default: log.Fatal("Invalid direction") } p.History[p.Location] += 1 if p.History[p.Location] == 2 { fmt.Println(p.Location) return true } } return false } func abs(x int) int { if x < 0 { return -x } else { return x } }
days/1/main.go
0.518546
0.559771
main.go
starcoder
package ahrs import ( "github.com/chewxy/math32" "github.com/foxis/EasyRobot/pkg/core/math/vec" ) type MahonyAHRS struct { Options accel, gyro, mag vec.Vector3D q vec.Quaternion eInt vec.Vector3D SamplePeriod float32 } func NewMahony(opts ...Option) AHRS { m := MahonyAHRS{ Options: defaultOptions(), q: vec.Quaternion{1, 0, 0, 0}, } applyOptions(&m.Options, opts...) return &m } func (m *MahonyAHRS) Acceleration() vec.Vector { return m.accel[:] } func (m *MahonyAHRS) Gyroscope() vec.Vector { return m.gyro[:] } func (m *MahonyAHRS) Magnetometer() vec.Vector { return m.mag[:] } func (m *MahonyAHRS) Orientation() vec.Vector { return m.q[:] } func (m *MahonyAHRS) Reset() AHRS { m.q.Vector().FillC(0) m.eInt.Vector().FillC(0) m.q[0] = 1 return m } func (m *MahonyAHRS) Update(samplePeriod float32) AHRS { m.SamplePeriod = samplePeriod return m } func (m *MahonyAHRS) Calculate() AHRS { if !(m.Options.HasAccelerator && m.Options.HasGyroscope) { panic(-1) } if !m.Options.HasMagnetometer { return m.calculateWOMag() } q1, q2, q3, q4 := m.q[0], m.q[1], m.q[2], m.q[3] // short name local variable for readability // Auxiliary variables to avoid repeated arithmetic q1q1 := q1 * q1 q1q2 := q1 * q2 q1q3 := q1 * q3 q1q4 := q1 * q4 q2q2 := q2 * q2 q2q3 := q2 * q3 q2q4 := q2 * q4 q3q3 := q3 * q3 q3q4 := q3 * q4 q4q4 := q4 * q4 // Normalise accelerometer measurement a := m.accel.Clone().NormalFast() // Normalise magnetometer measurement mag := m.mag.Clone().NormalFast() // Reference direction of Earth's magnetic field hx := 2*mag[0]*(0.5-q3q3-q4q4) + 2*mag[1]*(q2q3-q1q4) + 2*mag[2]*(q2q4+q1q3) hy := 2*mag[0]*(q2q3+q1q4) + 2*mag[1]*(0.5-q2q2-q4q4) + 2*mag[2]*(q3q4-q1q2) bx := math32.Sqrt((hx * hx) + (hy * hy)) bz := 2*mag[0]*(q2q4-q1q3) + 2*mag[1]*(q3q4+q1q2) + 2*mag[2]*(0.5-q2q2-q3q3) // Estimated direction of gravity and magnetic field v := vec.Vector3D{ 2 * (q2q4 - q1q3), 2 * (q1q2 + q3q4), q1q1 - q2q2 - q3q3 + q4q4, } w := vec.Vector3D{ 2*bx*(0.5-q3q3-q4q4) + 2*bz*(q2q4-q1q3), 2*bx*(q2q3-q1q4) + 2*bz*(q1q2+q3q4), 2*bx*(q1q3+q2q4) + 2*bz*(0.5-q2q2-q3q3), } // Error is cross product between estimated direction and measured direction of gravity e := vec.Vector3D{ (a[1]*v[2] - a[2]*v[1]) + (mag[1]*w[2] - mag[2]*w[1]), (a[2]*v[0] - a[0]*v[2]) + (mag[2]*w[0] - mag[0]*w[2]), (a[0]*v[1] - a[1]*v[0]) + (mag[0]*w[1] - mag[1]*w[0]), } if m.GainI > 0 { m.eInt.Add(e) // accumulate integral error } else { m.eInt = vec.Vector3D{} // prevent integral wind up } // Apply feedback terms g := m.gyro.Clone().MulCAdd(m.GainP, e).MulCAdd(m.GainI, m.eInt) // Integrate rate of change of quaternion m.q[0] = q1 + (-q2*g[0]-q3*g[1]-q4*g[2])*(0.5*m.SamplePeriod) m.q[1] = q2 + (q1*g[0]+q3*g[2]-q4*g[1])*(0.5*m.SamplePeriod) m.q[2] = q3 + (q1*g[1]-q2*g[2]+q4*g[0])*(0.5*m.SamplePeriod) m.q[3] = q4 + (q1*g[2]+q2*g[1]-q3*g[0])*(0.5*m.SamplePeriod) m.q.NormalFast() return m } func (m *MahonyAHRS) calculateWOMag() AHRS { q1, q2, q3, q4 := m.q[0], m.q[1], m.q[2], m.q[3] // short name local variable for readability // Normalise accelerometer measurement a := m.accel.Clone().NormalFast() // Estimated direction of gravity v := vec.Vector3D{ 2.0 * (q2*q4 - q1*q3), 2.0 * (q1*q2 + q3*q4), q1*q1 - q2*q2 - q3*q3 + q4*q4, } // Error is cross product between estimated direction and measured direction of gravity e := v.Cross(*a) if m.GainI > 0 { m.eInt.Add(*e) // accumulate integral error } else { m.eInt = vec.Vector3D{} // prevent integral wind up } // Apply feedback terms g := m.gyro.Clone().MulCAdd(m.GainP, *e).MulCAdd(m.GainI, m.eInt) // Integrate rate of change of quaternion m.q[0] = q1 + (-q2*g[0]-q3*g[1]-q4*g[2])*(0.5*m.SamplePeriod) m.q[1] = q2 + (q1*g[0]+q3*g[2]-q4*g[1])*(0.5*m.SamplePeriod) m.q[2] = q3 + (q1*g[1]-q2*g[2]+q4*g[0])*(0.5*m.SamplePeriod) m.q[3] = q4 + (q1*g[2]+q2*g[1]-q3*g[0])*(0.5*m.SamplePeriod) m.q.NormalFast() return m }
pkg/core/math/filter/ahrs/mahony.go
0.754192
0.596022
mahony.go
starcoder
package main import "fmt" // 1st attempt at populating the integer array func populateIntegerArray(input [5]int) { input[0] = 3 input[1] = 6 input[2] = 9 input[3] = 12 input[4] = 15 } // 2nd attempt at populating the integer array func populateIntegerArrayWithReturnValue(input [5]int) [5]int { input[0] = 3 input[1] = 6 input[2] = 9 input[3] = 12 input[4] = 15 return input } func beatlesArrayExample() { // Declare and initialize values in an array var beatles [4]string beatles[0] = "John" beatles[1] = "Paul" beatles[2] = "Ringo" beatles[3] = "George" fmt.Printf("Beatles consists of: %v\n", beatles) fmt.Println("The name of third band member in the beatles array is", beatles[2]) fmt.Println("Length of beatles: ", len(beatles)) // In Go, arrays are values. When we assign one array to another, all the elements from // the array on the right hand side are copied over to the array on the left hand side. var greatRockBandFromThe60s [4]string greatRockBandFromThe60s = beatles fmt.Printf("Members from a great rock band from the 1960s: %v\n", greatRockBandFromThe60s) // Since arrays are values, equality comparisons of two arrays are done value for value. // Note that the beatles array and the greatRockBandFromThe60s array have two different // addresses in memory. The value comparison only checks the values of the arrays, and // the memory address of the two arrays is not a criteria for the comparison. fmt.Printf("beatles mem address: %p\n", &beatles) fmt.Printf("greatRockBandFromThe60s mem address: %p\n", &greatRockBandFromThe60s) if beatles == greatRockBandFromThe60s { fmt.Println("The beatles array equals the greatRockBandFromThe60s array") } } func u2ArrayExample() { // Declare and initialize using the := operator. Instead of writing 4 lines of code // to initialize the array, we get the job done in 1 line of code using an array // literal value u2 := [4]string{"Bono", "Edge", "Adam", "Larry"} fmt.Printf("U2 consists of: %v\n", u2) fmt.Println("The name of second band member in the u2 array is", u2[1]) fmt.Println("Length of u2: ", len(u2)) } func main() { // Declare an array of 5 integers // Note: If we do not initialize a value for the array, they will default to the // zero value of the type. In the case of integers, we expect the zero value to be 0. var myArray [5]int fmt.Printf("Contents of myArray: %v\n\n", myArray) // Arrays are passed by value to functions, meaning a copy of the array is passed // and not a reference (pointer) to the array. populateIntegerArray(myArray) fmt.Printf("Contents of myArray: %v\n\n", myArray) myArray = populateIntegerArrayWithReturnValue(myArray) fmt.Printf("Contents of myArray: %v\n\n", myArray) // Use the built in len function to get the length of an array fmt.Println("Length of myArray: ", len(myArray)) beatlesArrayExample() u2ArrayExample() }
Section 3/declarearrays.go
0.665737
0.550003
declarearrays.go
starcoder
package execute import ( "github.com/EMCECS/influx/query" uuid "github.com/satori/go.uuid" ) // Dataset represents the set of data produced by a transformation. type Dataset interface { Node RetractTable(key query.GroupKey) error UpdateProcessingTime(t Time) error UpdateWatermark(mark Time) error Finish(error) SetTriggerSpec(t query.TriggerSpec) } // DataCache holds all working data for a transformation. type DataCache interface { Table(query.GroupKey) (query.Table, error) ForEach(func(query.GroupKey)) ForEachWithContext(func(query.GroupKey, Trigger, TableContext)) DiscardTable(query.GroupKey) ExpireTable(query.GroupKey) SetTriggerSpec(t query.TriggerSpec) } type AccumulationMode int const ( DiscardingMode AccumulationMode = iota AccumulatingMode AccumulatingRetractingMode ) type DatasetID uuid.UUID func (id DatasetID) String() string { return uuid.UUID(id).String() } var ZeroDatasetID DatasetID func (id DatasetID) IsZero() bool { return id == ZeroDatasetID } type dataset struct { id DatasetID ts []Transformation accMode AccumulationMode watermark Time processingTime Time cache DataCache } func NewDataset(id DatasetID, accMode AccumulationMode, cache DataCache) *dataset { return &dataset{ id: id, accMode: accMode, cache: cache, } } func (d *dataset) AddTransformation(t Transformation) { d.ts = append(d.ts, t) } func (d *dataset) SetTriggerSpec(spec query.TriggerSpec) { d.cache.SetTriggerSpec(spec) } func (d *dataset) UpdateWatermark(mark Time) error { d.watermark = mark if err := d.evalTriggers(); err != nil { return err } for _, t := range d.ts { if err := t.UpdateWatermark(d.id, mark); err != nil { return err } } return nil } func (d *dataset) UpdateProcessingTime(time Time) error { d.processingTime = time if err := d.evalTriggers(); err != nil { return err } for _, t := range d.ts { if err := t.UpdateProcessingTime(d.id, time); err != nil { return err } } return nil } func (d *dataset) evalTriggers() (err error) { d.cache.ForEachWithContext(func(key query.GroupKey, trigger Trigger, bc TableContext) { if err != nil { // Skip the rest once we have encountered an error return } c := TriggerContext{ Table: bc, Watermark: d.watermark, CurrentProcessingTime: d.processingTime, } if trigger.Triggered(c) { err = d.triggerTable(key) } if trigger.Finished() { d.expireTable(key) } }) return err } func (d *dataset) triggerTable(key query.GroupKey) error { b, err := d.cache.Table(key) if err != nil { return err } b.RefCount(len(d.ts)) switch d.accMode { case DiscardingMode: for _, t := range d.ts { if err := t.Process(d.id, b); err != nil { return err } } d.cache.DiscardTable(key) case AccumulatingRetractingMode: for _, t := range d.ts { if err := t.RetractTable(d.id, b.Key()); err != nil { return err } } fallthrough case AccumulatingMode: for _, t := range d.ts { if err := t.Process(d.id, b); err != nil { return err } } } return nil } func (d *dataset) expireTable(key query.GroupKey) { d.cache.ExpireTable(key) } func (d *dataset) RetractTable(key query.GroupKey) error { d.cache.DiscardTable(key) for _, t := range d.ts { if err := t.RetractTable(d.id, key); err != nil { return err } } return nil } func (d *dataset) Finish(err error) { if err == nil { // Only trigger tables we if we not finishing because of an error. d.cache.ForEach(func(bk query.GroupKey) { if err != nil { return } err = d.triggerTable(bk) d.cache.ExpireTable(bk) }) } for _, t := range d.ts { t.Finish(d.id, err) } }
query/execute/dataset.go
0.562898
0.428054
dataset.go
starcoder
package gcp import ( "context" "fmt" "path" "sync" "time" "cloud.google.com/go/storage" "github.com/Jeffail/benthos/v3/internal/bloblang/field" "github.com/Jeffail/benthos/v3/internal/bundle" ioutput "github.com/Jeffail/benthos/v3/internal/component/output" "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/lib/input" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/message/batch" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/output" "github.com/Jeffail/benthos/v3/lib/output/writer" "github.com/Jeffail/benthos/v3/lib/types" "github.com/gofrs/uuid" ) func init() { bundle.AllOutputs.Add(bundle.OutputConstructorFromSimple(func(c output.Config, nm bundle.NewManagement) (output.Type, error) { g, err := newGCPCloudStorageOutput(nm, c.GCPCloudStorage, nm.Logger(), nm.Metrics()) if err != nil { return nil, err } w, err := output.NewAsyncWriter(output.TypeGCPCloudStorage, c.GCPCloudStorage.MaxInFlight, g, nm.Logger(), nm.Metrics()) if err != nil { return nil, err } w = output.OnlySinglePayloads(w) return output.NewBatcherFromConfig(c.GCPCloudStorage.Batching, w, nm, nm.Logger(), nm.Metrics()) }), docs.ComponentSpec{ Name: output.TypeGCPCloudStorage, Type: docs.TypeOutput, Status: docs.StatusBeta, Version: "3.43.0", Categories: []string{ string(input.CategoryServices), string(input.CategoryGCP), }, Summary: ` Sends message parts as objects to a Google Cloud Storage bucket. Each object is uploaded with the path specified with the ` + "`path`" + ` field.`, Description: ioutput.Description(true, true, ` In order to have a different path for each object you should use function interpolations described [here](/docs/configuration/interpolation#bloblang-queries), which are calculated per message of a batch. ### Metadata Metadata fields on messages will be sent as headers, in order to mutate these values (or remove them) check out the [metadata docs](/docs/configuration/metadata). ### Credentials By default Benthos will use a shared credentials file when connecting to GCP services. You can find out more [in this document](/docs/guides/cloud/gcp). ### Batching It's common to want to upload messages to Google Cloud Storage as batched archives, the easiest way to do this is to batch your messages at the output level and join the batch of messages with an `+"[`archive`](/docs/components/processors/archive)"+` and/or `+"[`compress`](/docs/components/processors/compress)"+` processor. For example, if we wished to upload messages as a .tar.gz archive of documents we could achieve that with the following config: `+"```yaml"+` output: gcp_cloud_storage: bucket: TODO path: ${!count("files")}-${!timestamp_unix_nano()}.tar.gz batching: count: 100 period: 10s processors: - archive: format: tar - compress: algorithm: gzip `+"```"+` Alternatively, if we wished to upload JSON documents as a single large document containing an array of objects we can do that with: `+"```yaml"+` output: gcp_cloud_storage: bucket: TODO path: ${!count("files")}-${!timestamp_unix_nano()}.json batching: count: 100 processors: - archive: format: json_array `+"```"+``), Config: docs.FieldComponent().WithChildren( docs.FieldCommon("bucket", "The bucket to upload messages to."), docs.FieldCommon( "path", "The path of each message to upload.", `${!count("files")}-${!timestamp_unix_nano()}.txt`, `${!meta("kafka_key")}.json`, `${!json("doc.namespace")}/${!json("doc.id")}.json`, ).IsInterpolated(), docs.FieldCommon("content_type", "The content type to set for each object.").IsInterpolated(), docs.FieldCommon("collision_mode", `Determines how file path collisions should be dealt with.`). HasDefault(`overwrite`). HasAnnotatedOptions( "overwrite", "Replace the existing file with the new one.", "append", "Append the message bytes to the original file.", "error-if-exists", "Return an error, this is the equivalent of a nack.", "ignore", "Do not modify the original file, the new data will be dropped.", ).AtVersion("3.53.0"), docs.FieldAdvanced("content_encoding", "An optional content encoding to set for each object.").IsInterpolated(), docs.FieldAdvanced("chunk_size", "An optional chunk size which controls the maximum number of bytes of the object that the Writer will attempt to send to the server in a single request. If ChunkSize is set to zero, chunking will be disabled."), docs.FieldCommon("max_in_flight", "The maximum number of messages to have in flight at a given time. Increase this to improve throughput."), batch.FieldSpec(), ).ChildDefaultAndTypesFromStruct(output.NewGCPCloudStorageConfig()), }) } // gcpCloudStorageOutput is a benthos writer.Type implementation that writes // messages to a GCP Cloud Storage bucket. type gcpCloudStorageOutput struct { conf output.GCPCloudStorageConfig path *field.Expression contentType *field.Expression contentEncoding *field.Expression client *storage.Client connMut sync.RWMutex log log.Modular stats metrics.Type } // newGCPCloudStorageOutput creates a new GCP Cloud Storage bucket writer.Type. func newGCPCloudStorageOutput( mgr bundle.NewManagement, conf output.GCPCloudStorageConfig, log log.Modular, stats metrics.Type, ) (*gcpCloudStorageOutput, error) { g := &gcpCloudStorageOutput{ conf: conf, log: log, stats: stats, } bEnv := mgr.BloblEnvironment() var err error if g.path, err = bEnv.NewField(conf.Path); err != nil { return nil, fmt.Errorf("failed to parse path expression: %v", err) } if g.contentType, err = bEnv.NewField(conf.ContentType); err != nil { return nil, fmt.Errorf("failed to parse content type expression: %v", err) } if g.contentEncoding, err = bEnv.NewField(conf.ContentEncoding); err != nil { return nil, fmt.Errorf("failed to parse content encoding expression: %v", err) } return g, nil } // ConnectWithContext attempts to establish a connection to the target Google // Cloud Storage bucket. func (g *gcpCloudStorageOutput) ConnectWithContext(ctx context.Context) error { g.connMut.Lock() defer g.connMut.Unlock() var err error g.client, err = storage.NewClient(ctx) if err != nil { return err } g.log.Infof("Uploading message parts as objects to GCP Cloud Storage bucket: %v\n", g.conf.Bucket) return nil } // WriteWithContext attempts to write message contents to a target GCP Cloud // Storage bucket as files. func (g *gcpCloudStorageOutput) WriteWithContext(ctx context.Context, msg types.Message) error { g.connMut.RLock() client := g.client g.connMut.RUnlock() if client == nil { return types.ErrNotConnected } return writer.IterateBatchedSend(msg, func(i int, p types.Part) error { metadata := map[string]string{} p.Metadata().Iter(func(k, v string) error { metadata[k] = v return nil }) outputPath := g.path.String(i, msg) var err error if g.conf.CollisionMode != output.GCPCloudStorageOverwriteCollisionMode { _, err = client.Bucket(g.conf.Bucket).Object(outputPath).Attrs(ctx) } isMerge := false var tempPath string if err == storage.ErrObjectNotExist || g.conf.CollisionMode == output.GCPCloudStorageOverwriteCollisionMode { tempPath = outputPath } else { isMerge = true if g.conf.CollisionMode == output.GCPCloudStorageErrorIfExistsCollisionMode { return fmt.Errorf("file at path already exists: %s", outputPath) } else if g.conf.CollisionMode == output.GCPCloudStorageIgnoreCollisionMode { return nil } tempUUID, err := uuid.NewV4() if err != nil { return err } dir := path.Dir(outputPath) tempFileName := fmt.Sprintf("%s.tmp", tempUUID.String()) tempPath = path.Join(dir, tempFileName) } w := client.Bucket(g.conf.Bucket).Object(tempPath).NewWriter(ctx) w.ChunkSize = g.conf.ChunkSize w.ContentType = g.contentType.String(i, msg) w.ContentEncoding = g.contentEncoding.String(i, msg) w.Metadata = metadata if _, err = w.Write(p.Get()); err != nil { return err } if err := w.Close(); err != nil { return err } if isMerge { if err := g.appendToFile(ctx, tempPath, outputPath); err != nil { return err } } return err }) } // CloseAsync begins cleaning up resources used by this reader asynchronously. func (g *gcpCloudStorageOutput) CloseAsync() { go func() { g.connMut.Lock() if g.client != nil { g.client.Close() g.client = nil } g.connMut.Unlock() }() } // WaitForClose will block until either the reader is closed or a specified // timeout occurs. func (g *gcpCloudStorageOutput) WaitForClose(time.Duration) error { return nil } func (g *gcpCloudStorageOutput) appendToFile(ctx context.Context, source, dest string) error { client := g.client bucket := client.Bucket(g.conf.Bucket) src := bucket.Object(source) dst := bucket.Object(dest) if _, err := dst.ComposerFrom(dst, src).Run(ctx); err != nil { return err } // Remove the temporary file used for the merge if err := src.Delete(ctx); err != nil { g.log.Errorf("Failed to delete temporary file used for merging: %v", err) } return nil }
internal/impl/gcp/cloud_storage_output.go
0.608361
0.631594
cloud_storage_output.go
starcoder
package benchkit import ( "math" "sort" "time" ) // TimeResult contains the memory measurements of a memory benchmark // at each point of the benchmark. type TimeResult struct { N int Setup time.Time Start time.Time Teardown time.Time Each []TimeStep } // TimeStep contains statistics about a step of the benchmark. type TimeStep struct { all []time.Duration Significant []time.Duration Min time.Duration Max time.Duration Avg time.Duration SD time.Duration } // µ is the expected value. Greek letters because we can. func (t *TimeStep) µ() time.Duration { // since all values are equaly probable, µ is sum/length var sum time.Duration for _, dur := range t.Significant { sum += dur } return sum / time.Duration(len(t.Significant)) } // σ is the standard deviation. Greek letters because we can. func (t *TimeStep) σ() time.Duration { var sum time.Duration for _, dur := range t.Significant { sum += ((dur - t.µ()) * (dur - t.µ())) } scaled := sum / time.Duration(len(t.Significant)) σ := math.Sqrt(float64(scaled)) return time.Duration(σ) } // P returns the percentile duration of the step, such as p50, p90, p99... func (t *TimeStep) P(factor float64) time.Duration { if len(t.all) == 0 { return time.Duration(0) } pIdx := pIndex(len(t.all), factor) return t.all[pIdx-1] } // PRange returns the percentile duration of the step, such as p50, p90, p99... func (t *TimeStep) PRange(from, to float64) []time.Duration { if len(t.all) == 0 { return t.all } fromIdx := pIndex(len(t.all), from) toIdx := pIndex(len(t.all), to) return t.all[fromIdx-1 : toIdx] } func pIndex(base int, factor float64) int { power := math.Log10(factor) closest := 10 * math.Pow10(int(power)) idx := int(math.Ceil((factor * float64(base)) / closest)) return idx } type timeBenchKit struct { n int setup time.Time start time.Time teardown time.Time each *timeEach results *TimeResult } func (t *timeBenchKit) Setup() { t.setup = time.Now() } func (t *timeBenchKit) Starting() { t.start = time.Now() } func (t *timeBenchKit) Each() BenchEach { return t.each } func (t *timeBenchKit) Teardown() { t.teardown = time.Now() t.results.N = t.n t.results.Setup = t.setup t.results.Start = t.start t.results.Teardown = t.teardown t.results.Each = make([]TimeStep, len(t.each.after)) for i, after := range t.each.after { d := durationSlice(after) sort.Sort(&d) step := TimeStep{all: d} step.Significant = step.PRange(0.5, 0.95) step.Min = step.Significant[0] step.Max = step.Significant[len(step.Significant)-1] step.Avg = step.µ() step.SD = step.σ() t.results.Each[i] = step } } type timeEach struct { before [][]time.Time after [][]time.Duration } func (t *timeEach) Before(id int) { t.before[id] = append(t.before[id], time.Now()) } func (t *timeEach) After(id int) { beforeIdx := max(len(t.before[id])-1, 0) before := t.before[id][beforeIdx] t.after[id] = append(t.after[id], time.Since(before)) } // Time will track timings over exactly n steps, m times for each step. // Memory is allocated in advance for m times per step, but you can record // less than m times without effect, or more than m times with a loss of // precision (due to extra allocation). func Time(n, m int) (BenchKit, *TimeResult) { bench := &timeBenchKit{ n: n, each: &timeEach{ before: make([][]time.Time, n), after: make([][]time.Duration, n), }, results: &TimeResult{}, } for i := 0; i < n; i++ { bench.each.before[i] = make([]time.Time, 0, m) bench.each.after[i] = make([]time.Duration, 0, m) } return bench, bench.results } func max(a, b int) int { if a > b { return a } return b } type durationSlice []time.Duration func (d *durationSlice) Len() int { return len(*d) } func (d *durationSlice) Less(i, j int) bool { return (*d)[i] < (*d)[j] } func (d *durationSlice) Swap(i, j int) { (*d)[i], (*d)[j] = (*d)[j], (*d)[i] }
vendor/github.com/aybabtme/benchkit/time_kit.go
0.819569
0.539469
time_kit.go
starcoder
package commonxl import ( "fmt" "log" "time" "github.com/Bridgement/grate" ) // Sheet holds raw and rendered values for a spreadsheet. type Sheet struct { Formatter *Formatter NumRows int NumCols int Rows [][]Cell CurRow int } // Resize the sheet for the number of rows and cols given. // Newly added cells default to blank. func (s *Sheet) Resize(rows, cols int) { for i := range s.Rows { if i > rows { break } n := cols - len(s.Rows[i]) if n <= 0 { continue } s.Rows[i] = append(s.Rows[i], make([]Cell, n)...) } if rows <= 0 { rows = 1 } if cols <= 0 { cols = 1 } s.CurRow = 0 s.NumRows = rows s.NumCols = cols for rows >= len(s.Rows) { s.Rows = append(s.Rows, make([]Cell, cols)) } } // Put the value at the cell location given. func (s *Sheet) Put(row, col int, value interface{}, fmtNum uint16) { //log.Println(row, col, value, fmtNum) if row >= s.NumRows || col >= s.NumCols { if grate.Debug { log.Printf("grate: cell out of bounds row %d>=%d, col %d>=%d", row, s.NumRows, col, s.NumCols) } // per the spec, this is an invalid Excel file // but we'll resize in place instead of crashing out if row >= s.NumRows { s.NumRows = row + 1 } if col >= s.NumCols { s.NumCols = col + 1 } s.Resize(s.NumRows, s.NumCols) } if spec, ok := value.(string); ok { if spec == grate.EndRowMerged || spec == grate.EndColumnMerged || spec == grate.ContinueRowMerged || spec == grate.ContinueColumnMerged { s.Rows[row][col] = NewCell(value) s.Rows[row][col][1] = StaticCell return } } ct, ok := s.Formatter.getCellType(fmtNum) if !ok || fmtNum == 0 { s.Rows[row][col] = NewCell(value) } else { s.Rows[row][col] = NewCellWithType(value, ct, s.Formatter) } s.Rows[row][col].SetFormatNumber(fmtNum) } // Set changes the value in an existing cell location. // NB Currently only used for populating string results for formulas. func (s *Sheet) Set(row, col int, value interface{}) { if row > s.NumRows || col > s.NumCols { log.Println("grate: cell out of bounds") return } s.Rows[row][col][0] = value s.Rows[row][col][1] = StringCell } // SetURL adds a hyperlink to an existing cell location. func (s *Sheet) SetURL(row, col int, link string) { if row > s.NumRows || col > s.NumCols { log.Println("grate: cell out of bounds") return } s.Rows[row][col].SetURL(link) } // Next advances to the next record of content. // It MUST be called prior to any Scan(). func (s *Sheet) Next() bool { if (s.CurRow + 1) > len(s.Rows) { return false } s.CurRow++ return true } // Raw extracts the raw Cell interfaces underlying the current row. func (s *Sheet) Raw() []Cell { rr := make([]Cell, s.NumCols) for i, cell := range s.Rows[s.CurRow-1] { rr[i] = cell.Clone() } return rr } // Strings extracts values from the current record into a list of strings. func (s *Sheet) Strings() []string { res := make([]string, s.NumCols) for i, cell := range s.Rows[s.CurRow-1] { if cell.Type() == BlankCell { res[i] = "" continue } if cell.Type() == StaticCell { res[i] = cell.Value().(string) continue } val := cell.Value() fs, ok := s.Formatter.Apply(cell.FormatNo(), val) if !ok { fs = fmt.Sprint(val) } res[i] = fs } return res } // Types extracts the data types from the current record into a list. // options: "boolean", "integer", "float", "string", "date", // and special cases: "blank", "hyperlink" which are string types func (s *Sheet) Types() []string { res := make([]string, s.NumCols) for i, cell := range s.Rows[s.CurRow-1] { res[i] = cell.Type().String() } return res } // Formats extracts the format code for the current record into a list. func (s *Sheet) Formats() []string { ok := true res := make([]string, s.NumCols) for i, cell := range s.Rows[s.CurRow-1] { res[i], ok = builtInFormats[cell.FormatNo()] if !ok { res[i] = fmt.Sprint(cell.FormatNo()) } } return res } // Scan extracts values from the current record into the provided arguments // Arguments must be pointers to one of 5 supported types: // bool, int64, float64, string, or time.Time // If invalid, returns ErrInvalidScanType func (s *Sheet) Scan(args ...interface{}) error { row := s.Rows[s.CurRow-1] for i, a := range args { val := row[i].Value() switch v := a.(type) { case bool, int64, float64, string, time.Time: return fmt.Errorf("scan destinations must be pointer (arg %d is not)", i) case *bool: if x, ok := val.(bool); ok { *v = x } else { return fmt.Errorf("scan destination %d expected *%T, not *bool", i, val) } case *int64: if x, ok := val.(int64); ok { *v = x } else { return fmt.Errorf("scan destination %d expected *%T, not *int64", i, val) } case *float64: if x, ok := val.(float64); ok { *v = x } else { return fmt.Errorf("scan destination %d expected *%T, not *float64", i, val) } case *string: if x, ok := val.(string); ok { *v = x } else { return fmt.Errorf("scan destination %d expected *%T, not *string", i, val) } case *time.Time: if x, ok := val.(time.Time); ok { *v = x } else { return fmt.Errorf("scan destination %d expected *%T, not *time.Time", i, val) } default: return fmt.Errorf("scan destination for arg %d is not supported (%T)", i, a) } } return nil } // IsEmpty returns true if there are no data values. func (s *Sheet) IsEmpty() bool { return (s.NumCols <= 1 && s.NumRows <= 1) } // Err returns the last error that occured. func (s *Sheet) Err() error { return nil }
commonxl/sheet.go
0.567457
0.436382
sheet.go
starcoder
package iso20022 // Provides the details of each individual secured market transaction. type MoneyMarketTransactionStatus2 struct { // Unique transaction identifier will be created at the time a transaction is first executed, shared with all registered entities and counterparties involved in the transaction, and used to track that particular transaction during its lifetime. UniqueTransactionIdentifier *Max105Text `xml:"UnqTxIdr,omitempty"` // Internal unique transaction identifier used by the reporting agent for each transaction. ProprietaryTransactionIdentification *Max105Text `xml:"PrtryTxId"` // Unique and unambiguous legal entity identification of the branch of the reporting agent in which the transaction has been booked. // // Usage: This field must only be provided if the transaction has been conducted and booked by a branch of the reporting agent and only if this branch has its own LEI that the reporting agent can clearly identify. // Where the transaction has been booked by the head office or the reporting agent cannot be identified by a unique branch-specific LEI, the reporting agent must provide the LEI of the head office. BranchIdentification *LEIIdentifier `xml:"BrnchId,omitempty"` // Defines status of the reported transaction. Status *StatisticalReportingStatus2Code `xml:"Sts"` // Provides the details of the rule which could not be validated. ValidationRule []*GenericValidationRuleIdentification1 `xml:"VldtnRule,omitempty"` // Additional information that can not be captured in the structured fields and/or any other specific block. SupplementaryData []*SupplementaryData1 `xml:"SplmtryData,omitempty"` } func (m *MoneyMarketTransactionStatus2) SetUniqueTransactionIdentifier(value string) { m.UniqueTransactionIdentifier = (*Max105Text)(&value) } func (m *MoneyMarketTransactionStatus2) SetProprietaryTransactionIdentification(value string) { m.ProprietaryTransactionIdentification = (*Max105Text)(&value) } func (m *MoneyMarketTransactionStatus2) SetBranchIdentification(value string) { m.BranchIdentification = (*LEIIdentifier)(&value) } func (m *MoneyMarketTransactionStatus2) SetStatus(value string) { m.Status = (*StatisticalReportingStatus2Code)(&value) } func (m *MoneyMarketTransactionStatus2) AddValidationRule() *GenericValidationRuleIdentification1 { newValue := new (GenericValidationRuleIdentification1) m.ValidationRule = append(m.ValidationRule, newValue) return newValue } func (m *MoneyMarketTransactionStatus2) AddSupplementaryData() *SupplementaryData1 { newValue := new (SupplementaryData1) m.SupplementaryData = append(m.SupplementaryData, newValue) return newValue }
MoneyMarketTransactionStatus2.go
0.796134
0.446796
MoneyMarketTransactionStatus2.go
starcoder
package values import ( "fmt" "regexp" "github.com/freetsdb/freetsdb/services/flux/semantic" ) type Typer interface { Type() semantic.Type PolyType() semantic.PolyType } type Value interface { Typer Str() string Int() int64 UInt() uint64 Float() float64 Bool() bool Time() Time Duration() Duration Regexp() *regexp.Regexp Array() Array Object() Object Function() Function Equal(Value) bool } type value struct { t semantic.Type v interface{} } func (v value) Type() semantic.Type { return v.t } func (v value) PolyType() semantic.PolyType { return v.t.PolyType() } func (v value) Str() string { CheckKind(v.t.Nature(), semantic.String) return v.v.(string) } func (v value) Int() int64 { CheckKind(v.t.Nature(), semantic.Int) return v.v.(int64) } func (v value) UInt() uint64 { CheckKind(v.t.Nature(), semantic.UInt) return v.v.(uint64) } func (v value) Float() float64 { CheckKind(v.t.Nature(), semantic.Float) return v.v.(float64) } func (v value) Bool() bool { CheckKind(v.t.Nature(), semantic.Bool) return v.v.(bool) } func (v value) Time() Time { CheckKind(v.t.Nature(), semantic.Time) return v.v.(Time) } func (v value) Duration() Duration { CheckKind(v.t.Nature(), semantic.Duration) return v.v.(Duration) } func (v value) Regexp() *regexp.Regexp { CheckKind(v.t.Nature(), semantic.Regexp) return v.v.(*regexp.Regexp) } func (v value) Array() Array { CheckKind(v.t.Nature(), semantic.Array) return v.v.(Array) } func (v value) Object() Object { CheckKind(v.t.Nature(), semantic.Object) return v.v.(Object) } func (v value) Function() Function { CheckKind(v.t.Nature(), semantic.Function) return v.v.(Function) } func (v value) Equal(r Value) bool { if v.Type() != r.Type() { return false } switch k := v.Type().Nature(); k { case semantic.Bool: return v.Bool() == r.Bool() case semantic.UInt: return v.UInt() == r.UInt() case semantic.Int: return v.Int() == r.Int() case semantic.Float: return v.Float() == r.Float() case semantic.String: return v.Str() == r.Str() case semantic.Time: return v.Time() == r.Time() case semantic.Duration: return v.Duration() == r.Duration() case semantic.Regexp: return v.Regexp().String() == r.Regexp().String() case semantic.Object: return v.Object().Equal(r.Object()) case semantic.Array: return v.Array().Equal(r.Array()) case semantic.Function: return v.Function().Equal(r.Function()) default: return false } } func (v value) String() string { return fmt.Sprintf("%v", v.v) } // InvalidValue is a non nil value who's type is semantic.Invalid var InvalidValue = value{t: semantic.Invalid} // New constructs a new Value by inferring the type from the interface. If the interface // does not translate to a valid Value type, then InvalidValue is returned. func New(v interface{}) Value { switch v := v.(type) { case string: return NewString(v) case int64: return NewInt(v) case uint64: return NewUInt(v) case float64: return NewFloat(v) case bool: return NewBool(v) case Time: return NewTime(v) case Duration: return NewDuration(v) case *regexp.Regexp: return NewRegexp(v) default: return InvalidValue } } func NewString(v string) Value { return value{ t: semantic.String, v: v, } } func NewInt(v int64) Value { return value{ t: semantic.Int, v: v, } } func NewUInt(v uint64) Value { return value{ t: semantic.UInt, v: v, } } func NewFloat(v float64) Value { return value{ t: semantic.Float, v: v, } } func NewBool(v bool) Value { return value{ t: semantic.Bool, v: v, } } func NewTime(v Time) Value { return value{ t: semantic.Time, v: v, } } func NewDuration(v Duration) Value { return value{ t: semantic.Duration, v: v, } } func NewRegexp(v *regexp.Regexp) Value { return value{ t: semantic.Regexp, v: v, } } func UnexpectedKind(got, exp semantic.Nature) error { return fmt.Errorf("unexpected kind: got %q expected %q", got, exp) } // CheckKind panics if got != exp. func CheckKind(got, exp semantic.Nature) { if got != exp { panic(UnexpectedKind(got, exp)) } }
services/flux/values/values.go
0.757166
0.564399
values.go
starcoder
package grid func NewGrid(values [][]int, allowDiagonalNeighbours bool) *Grid { g := &Grid{ colLength: len(values[0]), rowLength: len(values), cells: make([][]*Cell, len(values)), allowDiagonalNeighbours: allowDiagonalNeighbours, } for x, rows := range values { g.cells[x] = make([]*Cell, len(rows)) for y, v := range rows { g.cells[x][y] = &Cell{ x: x, y: y, grid: g, Value: v, } } } return g } type Grid struct { colLength int rowLength int cells [][]*Cell allowDiagonalNeighbours bool } func (g Grid) CellAt(x int, y int) *Cell { if x < 0 || x >= len(g.cells) { return nil } if y < 0 || y >= len(g.cells[x]) { return nil } return g.cells[x][y] } func (g Grid) CellAtTopLeft() *Cell { return g.cells[0][0] } func (g Grid) CellAtBottomRight() *Cell { return g.cells[g.rowLength-1][g.colLength-1] } func (g Grid) Each(callback func(c *Cell) bool) { for _, cells := range g.cells { for _, c := range cells { shouldContinue := callback(c) if !shouldContinue { return } } } } func (g Grid) Size() int { return len(g.cells) * len(g.cells[0]) } type Cell struct { x int y int grid *Grid neighbours []*Cell Value int } func (c Cell) Neighbours() []*Cell { if c.neighbours == nil { neighbours := make([]*Cell, 0, 8) coordsList := make([][2]int, 0, 8) coordsList = append(coordsList, [][2]int{ {c.x, c.y - 1}, // N {c.x + 1, c.y}, // E {c.x, c.y + 1}, // S {c.x - 1, c.y}, // W }...) if c.grid.allowDiagonalNeighbours { coordsList = append(coordsList, [][2]int{ {c.x + 1, c.y - 1}, // NE {c.x + 1, c.y + 1}, // SE {c.x - 1, c.y + 1}, // SW {c.x - 1, c.y - 1}, // NW }...) } for _, coords := range coordsList { n := c.grid.CellAt(coords[0], coords[1]) if n == nil { continue } neighbours = append(neighbours, n) } c.neighbours = neighbours } return c.neighbours } func (c Cell) ID() int { return c.x + (c.y * c.grid.colLength) } func (c Cell) X() int { return c.x } func (c Cell) Y() int { return c.y }
internal/grid/grid.go
0.810816
0.742445
grid.go
starcoder
package circuit import ( "sync" "github.com/consensys/gkr-mimc/common" "github.com/consensys/gkr-mimc/polynomial" "github.com/consensys/gnark-crypto/ecc/bn254/fr" ) // Circuit contains all the statical informations necessary to // describe a GKR circuit. type Circuit struct { Layers []Layer } // Assignment gathers all the values representing the steps of // computations being proved by GKR type Assignment struct { Values [][][]fr.Element } // NewCircuit construct a new circuit object func NewCircuit( wiring [][]Wire, ) Circuit { layers := make([]Layer, len(wiring)) for i := range layers { layers[i] = NewLayer(wiring[i]) } return Circuit{ Layers: layers, } } // Assign returns a complete assignment from a vector of inputs func (c *Circuit) Assign(inputs [][]fr.Element, nCore int) Assignment { assignment := make([][][]fr.Element, len(c.Layers)+1) // The first layer of assignment is equal to the inputs assignment[0] = inputs // We use the transition funcs to create the next layers // one after the other for i, layer := range c.Layers { assignment[i+1] = layer.Evaluate(assignment[i], nCore) } return Assignment{Values: assignment} } // LayerAsBKTWithCopy creates a deep-copy of a given layer of the assignment func (a *Assignment) LayerAsBKTWithCopy(layer, nCore int) []polynomial.BookKeepingTable { res := make([]polynomial.BookKeepingTable, len(a.Values[layer])) var wg sync.WaitGroup wg.Add(len(res)) semaphore := common.NewSemaphore(nCore) defer semaphore.Close() // Deep-copies the values of the assignment for i, tab := range a.Values[layer] { go func(i int, tab []fr.Element) { semaphore.Acquire() res[i].Table = make([]fr.Element, len(tab)) copy(res[i].Table, tab) semaphore.Release() wg.Done() }(i, tab) } wg.Wait() return res } // LayerAsBKTNoCopy creates a deep-copy of a given layer of the assignment func (a *Assignment) LayerAsBKTNoCopy(layer int) []polynomial.BookKeepingTable { res := make([]polynomial.BookKeepingTable, len(a.Values[layer])) // Copies the headers of the slices for i, tab := range a.Values[layer] { res[i] = polynomial.NewBookKeepingTable(tab) } return res }
circuit/circuit.go
0.677047
0.408926
circuit.go
starcoder
package filter import ( "bytes" "encoding/json" "fmt" "github.com/AdRoll/baker" "github.com/jmespath/go-jmespath" ) const expandJSONhelp = ` ExpandJSON extracts values from a JSON formatted record field and writes them into other fields of the same record. It supports [JMESPath](https://jmespath.org/tutorial.html) to select the values to copy inside the JSON. ### Example A possible filter configuration is: [[filter]] name="ExpandJSON" [filter.config] Source = "json_data" [filter.config.Fields] jfield1 = "field1" jfield2 = "field2" In this example, the filter extracts values of the ` + "`jfield1`" + ` and ` + "`jfield2`" + ` keys of the JSON object present in field ` + "`json_data`" + `of the record. Then, the values of that keys will be written into the field ` + "`field1`" + ` and ` + "`field2`" + ` of the same record. ` var ExpandJSONDesc = baker.FilterDesc{ Name: "ExpandJSON", New: NewExpandJSON, Config: &ExpandJSONConfig{}, Help: expandJSONhelp, } type ExpandJSONConfig struct { Source string `help:"record field that contains the json" required:"true"` Fields map[string]string `help:"<JMESPath -> record field> map, the rest will be ignored" required:"true"` TrueFalseValues []string `help:"bind the json boolean values to correstponding strings" default:"[\"true\", \"false\"]"` } func (cfg *ExpandJSONConfig) fillDefaults() { if len(cfg.TrueFalseValues) == 0 { cfg.TrueFalseValues = []string{"true", "false"} } } const trueIdx, falseIdx = 0, 1 type ExpandJSON struct { cfg *ExpandJSONConfig fields []baker.FieldIndex jexp []*jmespath.JMESPath source baker.FieldIndex trueFalseValues [2][]byte } func NewExpandJSON(cfg baker.FilterParams) (baker.Filter, error) { dcfg := cfg.DecodedConfig.(*ExpandJSONConfig) dcfg.fillDefaults() ut := &ExpandJSON{cfg: dcfg} val, ok := cfg.FieldByName(dcfg.Source) if !ok { return nil, fmt.Errorf("field %q unknown, can't expand it", dcfg.Source) } ut.source = val for j, f := range dcfg.Fields { i, ok := cfg.FieldByName(f) if !ok { return nil, fmt.Errorf("field %q unknown, can't expand %q into it", f, j) } c, err := jmespath.Compile(j) if err != nil { return nil, fmt.Errorf("malformed JMESPath expression %q for field %q", j, f) } ut.fields = append(ut.fields, i) ut.jexp = append(ut.jexp, c) } if l := len(dcfg.TrueFalseValues); l != 2 { return nil, fmt.Errorf("only two 'true' 'false' values allowed, %v given", l) } ut.trueFalseValues = [2][]byte{ []byte(dcfg.TrueFalseValues[trueIdx]), []byte(dcfg.TrueFalseValues[falseIdx]), } return ut, nil } func (f *ExpandJSON) Stats() baker.FilterStats { return baker.FilterStats{} } func (f *ExpandJSON) Process(l baker.Record, next func(baker.Record)) { data := f.processJSON(l.Get(f.source)) for i, c := range f.jexp { r, err := c.Search(data) if err != nil || r == nil { continue } l.Set(f.fields[i], f.postProcessJSON(r)) } next(l) } func (f *ExpandJSON) processJSON(data []byte) interface{} { if len(data) == 0 { return nil } d := json.NewDecoder(bytes.NewReader(data)) d.UseNumber() // leave numbers as strings var x interface{} if err := d.Decode(&x); err != nil { return nil } return x } func (f *ExpandJSON) postProcessJSON(r interface{}) []byte { switch typedValue := r.(type) { case json.Number: return []byte(typedValue) case string: return []byte(typedValue) case bool: if typedValue { return f.trueFalseValues[trueIdx] } else { return f.trueFalseValues[falseIdx] } default: val, _ := json.Marshal(typedValue) return val } }
filter/expand_json.go
0.6973
0.450782
expand_json.go
starcoder
package main import ( "fmt" "io/ioutil" "log" "path/filepath" "reflect" "strings" yaml "gopkg.in/yaml.v2" rivescript "github.com/aichaos/rivescript-go" ) // TestCase wraps each RiveScript test. type TestCase struct { file string name string username string rs *rivescript.RiveScript steps []TestStep } // RootSchema is the root of the YAML structure. type RootSchema map[string]TestSchema // TestSchema describes the YAML test files. type TestSchema struct { Username string `yaml:"username"` UTF8 bool `yaml:"utf8"` Debug bool `yaml:"debug"` Tests []TestStep } // TestStep describes the YAML structure for the actual tests. type TestStep struct { Source string `yaml:"source"` Input string `yaml:"input"` Reply interface{} `yaml:"reply"` Assert map[string]string `yaml:"assert"` Set map[string]string `yaml:"set"` } // NewTestCase initializes a new test. func NewTestCase(file, name string, opts TestSchema) *TestCase { username := opts.Username if username == "" { username = "localuser" } return &TestCase{ file: file, name: name, username: username, rs: rivescript.New(&rivescript.Config{ Debug: opts.Debug, UTF8: opts.UTF8, }), steps: opts.Tests, } } // Run steps through the test cases and runs them. func (t *TestCase) Run() { var hasErrors bool for _, step := range t.steps { var err error if step.Source != "" { t.source(step) } else if step.Input != "" { err = t.input(step) } else if len(step.Set) > 0 { t.set(step) } else if len(step.Assert) > 0 { err = t.get(step) } else { log.Printf("Unsupported test step") } if err != nil { t.fail(err) hasErrors = true break } } var sym string if hasErrors { sym = `❌` } else { sym = `✓` } fmt.Printf("%s %s#%s\n", sym, t.file, t.name) } // source handles a `source` step, which parses RiveScript code. func (t *TestCase) source(step TestStep) { t.rs.Stream(step.Source) t.rs.SortReplies() } // input handles an `input` step, which tests the brain for a reply. func (t *TestCase) input(step TestStep) error { reply, err := t.rs.Reply(t.username, step.Input) if err != nil { return t.expectedError(step, reply, err) } // Random replies? if expect, ok := step.Reply.([]interface{}); ok { pass := false for _, candidate := range expect { cmp, ok := candidate.(string) if !ok { return fmt.Errorf( "Error", ) } if cmp == reply { pass = true break } } if !pass { return fmt.Errorf( "Did not get expected reply for input: %s\n"+ "Expected one of: %v\n"+ " Got: %s", step.Input, expect, reply, ) } } else if expect, ok := step.Reply.(string); ok { if reply != strings.TrimSpace(expect) { return fmt.Errorf( "Did not get expected reply for input: %s\n"+ "Expected: %s\n"+ " Got: %s", step.Input, expect, reply, ) } } else { return fmt.Errorf( "YAML error: `reply` was neither a `string` nor a `[]string` "+ "at %s test %s (input %s); reply was: '%v' (type %s)", t.file, t.name, step.Input, step.Reply, reflect.TypeOf(step.Reply), ) } return nil } // expectedError inspects a Reply() error to see if it was expected by the test. func (t *TestCase) expectedError(step TestStep, reply string, err error) error { // Map of expected errors to their string counterpart from the test file. goodErrors := map[string]error{ "ERR: No Reply Matched": rivescript.ErrNoTriggerMatched, } if expect, ok := goodErrors[step.Reply.(string)]; ok { if err == expect { return nil } } return fmt.Errorf( "Got unexpected error from Reply (input step: %s; expected: %v): %s", step.Input, step.Reply, err, ) } // set handles a `set` step, which sets user variables. func (t *TestCase) set(step TestStep) { for key, value := range step.Set { t.rs.SetUservar(t.username, key, value) } } // get handles an `assert` step, which tests user variables. func (t *TestCase) get(step TestStep) error { for key, expect := range step.Assert { value, err := t.rs.GetUservar(t.username, key) if err != nil { return err } if value != expect { return fmt.Errorf( "Did not get expected user variable: %s\n"+ "Expected: %s\n"+ " Got: %s", key, expect, value, ) } } return nil } // fail handles a failed test. func (t *TestCase) fail(err error) { banner := fmt.Sprintf("Failed: %s#%s", t.file, t.name) fmt.Printf("%s\n%s\n%s\n\n", banner, strings.Repeat("=", len(banner)), err, ) } func main() { tests, err := filepath.Glob("../tests/*.yml") if err != nil { panic(err) } for _, filename := range tests { yamlSource, err := ioutil.ReadFile(filename) if err != nil { panic(err) } data := RootSchema{} yaml.Unmarshal(yamlSource, &data) for name, opts := range data { test := NewTestCase(filename, name, opts) test.Run() } } }
go/main.go
0.595375
0.409575
main.go
starcoder
package flow import ( "github.com/skydive-project/skydive/common" "github.com/skydive-project/skydive/filters" ) // MergeContext describes a mechanism to merge flow sets type MergeContext struct { Sort bool SortBy string SortOrder common.SortOrder Dedup bool DedupBy string } // NewFlowSet creates a new empty FlowSet func NewFlowSet() *FlowSet { return &FlowSet{ Flows: make([]*Flow, 0), } } func getDedupField(flow *Flow, field string) (interface{}, error) { if field == "" { return flow.TrackingID, nil } if v, err := flow.GetFieldString(field); err != nil { return flow.GetFieldInt64(field) } else { return v, nil } } func compareByField(lf, rf *Flow, field string) (bool, error) { if field == "" { return lf.Last <= rf.Last, nil } // compare first int64 has it is more often used with sort if v1, err := lf.GetFieldInt64(field); err == nil { v2, _ := rf.GetFieldInt64(field) return v1 <= v2, nil } if v1, err := lf.GetFieldString(field); err == nil { v2, _ := rf.GetFieldString(field) return v1 <= v2, nil } return false, common.ErrFieldNotFound } // mergeDedup merges the flowset given as argument. Both of the flowset have // to be dedup before calling this function. func (fs *FlowSet) mergeDedup(ofs *FlowSet, field string) error { if len(ofs.Flows) == 0 { return nil } visited := make(map[interface{}]bool) for _, flow := range fs.Flows { kvisited, err := getDedupField(flow, field) if err != nil { return err } visited[kvisited] = true } for _, flow := range ofs.Flows { kvisited, err := getDedupField(flow, field) if err != nil { return err } if _, ok := visited[kvisited]; !ok { fs.Flows = append(fs.Flows, flow) } } return nil } // Merge merges two FlowSet. If Sorted both of the FlowSet have to be sorted // first. If Dedup both of the FlowSet have to be dedup first too. func (fs *FlowSet) Merge(ofs *FlowSet, context MergeContext) error { fs.Start = common.MinInt64(fs.Start, ofs.Start) if fs.Start == 0 { fs.Start = ofs.Start } fs.End = common.MaxInt64(fs.End, ofs.End) var err error if context.Sort { if fs.Flows, err = fs.mergeSortedFlows(fs.Flows, ofs.Flows, context); err != nil { return err } } else if context.Dedup { return fs.mergeDedup(ofs, context.DedupBy) } else { fs.Flows = append(fs.Flows, ofs.Flows...) } return nil } func (fs *FlowSet) sortFlows(f []*Flow, context MergeContext) []*Flow { if len(f) <= 1 { return f } mid := len(f) / 2 left := f[:mid] right := f[mid:] left = fs.sortFlows(left, context) right = fs.sortFlows(right, context) flows, _ := fs.mergeSortedFlows(left, right, context) return flows } func (fs *FlowSet) mergeSortedFlows(left, right []*Flow, context MergeContext) ([]*Flow, error) { var ret []*Flow if !context.Dedup { ret = make([]*Flow, 0, len(left)+len(right)) } visited := make(map[interface{}]bool) for len(left) > 0 || len(right) > 0 { if len(left) == 0 { if context.Dedup { for _, flow := range right { kvisited, err := getDedupField(flow, context.DedupBy) if err != nil { return ret, err } if _, ok := visited[kvisited]; !ok { ret = append(ret, flow) visited[kvisited] = true } } return ret, nil } return append(ret, right...), nil } if len(right) == 0 { if context.Dedup { for _, flow := range left { kvisited, err := getDedupField(flow, context.DedupBy) if err != nil { return ret, err } if _, ok := visited[kvisited]; !ok { ret = append(ret, flow) visited[kvisited] = true } } return ret, nil } return append(ret, left...), nil } lf, rf := left[0], right[0] cv, err := compareByField(lf, rf, context.SortBy) if err != nil { return nil, err } if context.SortOrder != common.SortAscending { cv = !cv } if cv { if !context.Dedup { ret = append(ret, lf) } else { kvisited, err := getDedupField(lf, context.DedupBy) if err != nil { return ret, err } if _, ok := visited[kvisited]; !ok { ret = append(ret, lf) visited[kvisited] = true } } left = left[1:] } else { if !context.Dedup { ret = append(ret, rf) } else { kvisited, err := getDedupField(rf, context.DedupBy) if err != nil { return ret, err } if _, ok := visited[kvisited]; !ok { ret = append(ret, rf) visited[kvisited] = true } } right = right[1:] } } return ret, nil } // Slice returns a slice of a FlowSet func (fs *FlowSet) Slice(from, to int) { if from > len(fs.Flows) { from = len(fs.Flows) } if to > len(fs.Flows) { to = len(fs.Flows) } fs.Flows = fs.Flows[from:to] } // Dedup deduplicate a flows in a FlowSet func (fs *FlowSet) Dedup(field string) error { var deduped []*Flow if len(fs.Flows) == 0 { return nil } visited := make(map[interface{}]bool) for _, flow := range fs.Flows { kvisited, err := getDedupField(flow, field) if err != nil { return err } if _, ok := visited[kvisited]; !ok { deduped = append(deduped, flow) visited[kvisited] = true } } fs.Flows = deduped return nil } // Sort flows in a FlowSet func (fs *FlowSet) Sort(order common.SortOrder, orberBy string) { context := MergeContext{Sort: true, SortBy: orberBy, SortOrder: order} fs.Flows = fs.sortFlows(fs.Flows, context) } // Filter flows in a FlowSet func (fs *FlowSet) Filter(filter *filters.Filter) *FlowSet { flowset := NewFlowSet() for _, f := range fs.Flows { if filter == nil || filter.Eval(f) { if flowset.Start == 0 || flowset.Start > f.Start { flowset.Start = f.Start } if flowset.End == 0 || flowset.Start < f.Last { flowset.End = f.Last } flowset.Flows = append(flowset.Flows, f) } } return flowset }
flow/set.go
0.747063
0.475179
set.go
starcoder
package number import ( "fmt" "github.com/codingsince1985/geo-golang" "github.com/codingsince1985/geo-golang/openstreetmap" "math" ) const ( earthRadius float64 = 6371 ) type city struct { name string latitude, longitude float64 } func getDistance(source, destination city) float64 { // Haversine formula: a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2) // c = 2 ⋅ atan2( √a, √(1−a) ) // d = R ⋅ c // where φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km); // note that angles need to be in radians to pass to trig functions! var distance float64 fmt.Println(source, destination) a := math.Pow(math.Sin((math.Abs(destination.latitude-source.latitude)/2)*math.Pi/180), 2) + (math.Cos(source.latitude*math.Pi/180)*math.Cos(destination.latitude*math.Pi/180))*math.Pow(math.Sin((math.Abs(destination.longitude-source.longitude)/2)*math.Pi/180), 2) c := 2 * math.Atan2(math.Sqrt(a), math.Sqrt(1-a)) distance = earthRadius * c return distance } // DistanceBetweenTwoCities : Calculates the distance between two cities and allows the user to specify a unit of distance. // This program may require finding coordinates for the cities like latitude and longitude. func DistanceBetweenTwoCities() { var ( source, destination city geocoder geo.Geocoder ) fmt.Print("Enter source city : ") fmt.Scan(&source.name) fmt.Print("Enter destination city : ") fmt.Scan(&destination.name) geocoder = openstreetmap.Geocoder() location, _ := geocoder.Geocode(source.name) source.latitude, source.longitude = location.Lat, location.Lng location, _ = geocoder.Geocode(destination.name) destination.latitude, destination.longitude = location.Lat, location.Lng fmt.Println(getDistance(source, destination)) } // TODO: https://www.movable-type.co.uk/scripts/latlong.html // https://github.com/dnf0/pyprojects/blob/master/citydistance.py // Calculate distance between 2 cities by checking the program in main.go // https://www.geeksforgeeks.org/program-distance-two-points-earth/ // https://github.com/codingsince1985/geo-golang/blob/master/openstreetmap/geocoder.go
number/distancecalculator.go
0.668339
0.539105
distancecalculator.go
starcoder
package cp import ( "fmt" "math" ) type Vector struct { X, Y float64 } func (v Vector) String() string { return fmt.Sprintf("%f,%f", v.X, v.Y) } func (v Vector) Equal(other Vector) bool { return v.X == other.X && v.Y == other.Y } func (v Vector) Add(other Vector) Vector { return Vector{v.X + other.X, v.Y + other.Y} } func (v Vector) Sub(other Vector) Vector { return Vector{v.X - other.X, v.Y - other.Y} } func (v Vector) Neg() Vector { return Vector{-v.X, -v.Y} } func (v Vector) Mult(s float64) Vector { return Vector{v.X * s, v.Y * s} } func (v Vector) Dot(other Vector) float64 { return v.X*other.X + v.Y*other.Y } /// 2D vector cross product analog. /// The cross product of 2D vectors results in a 3D vector with only a z component. /// This function returns the magnitude of the z value. func (v Vector) Cross(other Vector) float64 { return v.X*other.Y - v.Y*other.X } func (v Vector) Perp() Vector { return Vector{-v.Y, v.X} } func (v Vector) ReversePerp() Vector { return Vector{v.Y, -v.X} } func (v Vector) Project(other Vector) Vector { return other.Mult(v.Dot(other) / other.Dot(other)) } /// Returns the unit length vector for the given angle (in radians). func ForAngle(a float64) Vector { return Vector{math.Cos(a), math.Sin(a)} } func (v Vector) ToAngle() float64 { return math.Atan2(v.Y, v.X) } func (v Vector) Rotate(other Vector) Vector { return Vector{v.X*other.X - v.Y*other.Y, v.X*other.Y + v.Y*other.X} } func (v Vector) Unrotate(other Vector) Vector { return Vector{v.X*other.X + v.Y*other.Y, v.Y*other.X - v.X*other.Y} } func (v Vector) LengthSq() float64 { return v.Dot(v) } func (v Vector) Length() float64 { return math.Sqrt(v.Dot(v)) } func (v Vector) Lerp(other Vector, t float64) Vector { return v.Mult(1.0 - t).Add(other.Mult(t)) } func (v Vector) Normalize() Vector { return v.Mult(1.0 / (v.Length() + math.SmallestNonzeroFloat64)) } func (v Vector) SLerp(other Vector, t float64) Vector { dot := v.Normalize().Dot(other.Normalize()) omega := math.Acos(Clamp(dot, -1, 1)) if omega < 1e-3 { return v.Lerp(other, t) } denom := 1.0 / math.Sin(omega) return v.Mult(math.Sin((1.0-t)*omega) * denom).Add(other.Mult(math.Sin(t*omega) * denom)) } func Clamp(f, min, max float64) float64 { if f > min { return math.Min(f, max) } else { return math.Min(min, max) } } func Clamp01(f float64) float64 { return math.Max(0, math.Min(f, 1)) } func Lerp(f1, f2, t float64) float64 { return f1*(1.0-t) + f2*t } func LerpConst(f1, f2, d float64) float64 { return f1 + Clamp(f2-f1, -d, d) } func (v Vector) SlerpConst(other Vector, a float64) Vector { dot := v.Normalize().Dot(other.Normalize()) omega := math.Acos(Clamp(dot, -1, 1)) return v.SLerp(other, math.Min(a, omega)/omega) } func (v Vector) Clamp(length float64) Vector { if v.Dot(v) > length*length { return v.Normalize().Mult(length) } return Vector{v.X, v.Y} } func (v Vector) LerpConst(other Vector, d float64) Vector { return v.Add(other.Sub(v).Clamp(d)) } func (v Vector) Distance(other Vector) float64 { return v.Sub(other).Length() } func (v Vector) DistanceSq(other Vector) float64 { return v.Sub(other).LengthSq() } func (v Vector) Near(other Vector, d float64) bool { return v.DistanceSq(other) < d*d } // Collision related below func (a Vector) PointGreater(b, c Vector) bool { return (b.Y-a.Y)*(a.X+b.X-2*c.X) > (b.X-a.X)*(a.Y+b.Y-2*c.Y) } func (v0 Vector) CheckAxis(v1, p, n Vector) bool { return p.Dot(n) <= math.Max(v0.Dot(n), v1.Dot(n)) } func (a Vector) ClosestT(b Vector) float64 { delta := b.Sub(a) return -Clamp(delta.Dot(a.Add(b))/delta.LengthSq(), -1.0, 1.0) } func (a Vector) LerpT(b Vector, t float64) Vector { ht := 0.5 * t return a.Mult(0.5 - ht).Add(b.Mult(0.5 + ht)) } func (v0 Vector) ClosestDist(v1 Vector) float64 { return v0.LerpT(v1, v0.ClosestT(v1)).LengthSq() } func (p Vector) ClosestPointOnSegment(a, b Vector) Vector { delta := a.Sub(b) t := Clamp01(delta.Dot(p.Sub(b)) / delta.LengthSq()) return b.Add(delta.Mult(t)) } func (p Vector) Clone() Vector { return Vector{p.X, p.Y} }
vector.go
0.907556
0.729423
vector.go
starcoder
package patch import ( "encoding/json" "fmt" "reflect" "strings" "github.com/pkg/errors" ) // ValidateError is the error type that will be returned if an update fails in the validation step. type ValidateError struct { key string err error } func (u ValidateError) Error() string { return fmt.Sprintf("validate error on key %s: %s", u.key, u.err.Error()) } // Validator is an interface that describes how an object should be validated before updating. type Validator interface { // Validate takes a key to describe what the value is and the value and returns an error if it // fails validation. Validate(key string, value interface{}) error } // ValidateFunc wraps the func(string, interface{}) error signature in a type to make building // Validators more convenient. type ValidateFunc func(string, interface{}) error // Validate implements Validator, and just returns the function itself. func (vf ValidateFunc) Validate(key string, value interface{}) error { return vf(key, value) } // Apply takes a JSON blob (as a []byte) which represents a partial target object in JSON. It then applies the // values set in the map to the current object, only touching what's changed. func Apply(dest interface{}, src []byte, validator Validator) error { // Unmarshal src into a map[string]json.RawMessage. m := map[string]json.RawMessage{} err := json.Unmarshal(src, &m) if err != nil { return errors.Wrap(err, "can't unmarshal src") } // dest should be a pointer here, because when we're done we'll overwrite zero or more values on it. if reflect.ValueOf(dest).Kind() != reflect.Ptr { return errors.New("destination must be a pointer") } // Get the indirect of dest to determine its concrete type. indirect := reflect.Indirect(reflect.ValueOf(dest)) // We only want to touch dest if the entire function finishes successfully, rather than erroring in the // middle of setting some fields but not others. So we'll create a copy of dest and work with the copy // until the end. destVal := reflect.New(indirect.Type()) reflect.Indirect(destVal).Set(indirect) // Iterate through all of dest's fields, taking note of what they marshal to in JSON via the struct tags. // (If there is no json tag, we assume they map to the same name as the field.) fieldMap := map[string]int{} for i := 0; i < indirect.Type().NumField(); i++ { field := indirect.Type().Field(i) tag, ok := field.Tag.Lookup("json") if ok { v := strings.SplitN(tag, ",", 2) if v[0] != "-" { fieldMap[v[0]] = i } } else { fieldMap[field.Name] = i } } // We now have a map of all fields representation in JSON and where they map to on the struct. All that's left to // do is iterate through the incoming values and attempt to set them on our target. for key, val := range m { // Find the field on the target struct; if it's not in the map, something fishy is going on and we better // abort. fieldIndex, ok := fieldMap[key] if !ok { return errors.Errorf("key %s wasn't found in field map", key) } // We found the field, so make a target of the same type that we can unmarshal into, then try to unmarshal it. // If we can't unmarshal it, abort. target := reflect.New(indirect.Type().Field(fieldIndex).Type).Interface() err := json.Unmarshal(val, target) if err != nil { return errors.Wrapf(err, "error unmarshaling %s", key) } if validator != nil { err = validator.Validate(key, target) if err != nil { return ValidateError{err: err, key: key} } } // We have our field and we have our new value, so we can go ahead and set it. Broken up into a couple // lines for readability. targetField := reflect.Indirect(destVal).Field(fieldIndex) targetValue := reflect.Indirect(reflect.ValueOf(target)) targetField.Set(targetValue) } // We're done! Now we can update our original target (dest) and return. reflect.Indirect(reflect.ValueOf(dest)).Set(reflect.Indirect(destVal)) return nil }
patch.go
0.674694
0.401131
patch.go
starcoder
package chess type Board struct { x int y int cells map[int]map[int]*Cell } func (Board) Create(x int, y int) *Board { cells := make(map[int]map[int]*Cell, y) for i := 1; i <= y; i++ { cells[i] = make(map[int]*Cell, x) for j := 1; j <= y; j++ { cells[i][j] = &Cell{} } } board := &Board{x: x, y: y, cells: cells} board.addStandardFigures() return board } func (board *Board) AddFigure(figure *Figure, x int, y int) { board.cells[x][y].Figure = figure } func (board *Board) Size() (x int, y int) { return board.x, board.y } // Cell retrieves Figure in cell, or nil if it is empty func (board *Board) Figure(x int, y int) *Figure { cell := board.cells[x][y] if cell == nil { return nil } return cell.Figure } func (board *Board) addStandardFigures() { board.AddFigure(Figure{}.Create(Rook, White), 1, 8) board.AddFigure(Figure{}.Create(Knight, White), 2, 8) board.AddFigure(Figure{}.Create(Bishop, White), 3, 8) board.AddFigure(Figure{}.Create(Queen, White), 4, 8) board.AddFigure(Figure{}.Create(King, White), 5, 8) board.AddFigure(Figure{}.Create(Bishop, White), 6, 8) board.AddFigure(Figure{}.Create(Knight, White), 7, 8) board.AddFigure(Figure{}.Create(Rook, White), 8, 8) board.AddFigure(Figure{}.Create(Pawn, White), 1, 7) board.AddFigure(Figure{}.Create(Pawn, White), 2, 7) board.AddFigure(Figure{}.Create(Pawn, White), 3, 7) board.AddFigure(Figure{}.Create(Pawn, White), 4, 7) board.AddFigure(Figure{}.Create(Pawn, White), 5, 7) board.AddFigure(Figure{}.Create(Pawn, White), 6, 7) board.AddFigure(Figure{}.Create(Pawn, White), 7, 7) board.AddFigure(Figure{}.Create(Pawn, White), 8, 7) board.AddFigure(Figure{}.Create(Rook, Black), 1, 1) board.AddFigure(Figure{}.Create(Knight, Black), 2, 1) board.AddFigure(Figure{}.Create(Bishop, Black), 3, 1) board.AddFigure(Figure{}.Create(Queen, Black), 4, 1) board.AddFigure(Figure{}.Create(King, Black), 5, 1) board.AddFigure(Figure{}.Create(Bishop, Black), 6, 1) board.AddFigure(Figure{}.Create(Knight, Black), 7, 1) board.AddFigure(Figure{}.Create(Rook, Black), 8, 1) board.AddFigure(Figure{}.Create(Pawn, Black), 1, 2) board.AddFigure(Figure{}.Create(Pawn, Black), 2, 2) board.AddFigure(Figure{}.Create(Pawn, Black), 3, 2) board.AddFigure(Figure{}.Create(Pawn, Black), 4, 2) board.AddFigure(Figure{}.Create(Pawn, Black), 5, 2) board.AddFigure(Figure{}.Create(Pawn, Black), 6, 2) board.AddFigure(Figure{}.Create(Pawn, Black), 7, 2) board.AddFigure(Figure{}.Create(Pawn, Black), 8, 2) }
internal/chess/Board.go
0.813572
0.575111
Board.go
starcoder
package table import ( "fmt" "github.com/charmbracelet/lipgloss" ) // RowData is a map of string column keys to interface{} data. Data with a key // that matches a column key will be displayed. Data with a key that does not // match a column key will not be displayed, but will remain attached to the Row. // This can be useful for attaching hidden metadata for future reference when // retrieving rows. type RowData map[string]interface{} // Row represents a row in the table with some data keyed to the table columns> // Can have a style applied to it such as color/bold. Create using NewRow(). type Row struct { Style lipgloss.Style Data RowData selected bool } // NewRow creates a new row and copies the given row data. func NewRow(data RowData) Row { row := Row{ Data: make(map[string]interface{}), } for key, val := range data { // Doesn't deep copy val, but close enough for now... row.Data[key] = val } return row } // WithStyle uses the given style for the text in the row. func (r Row) WithStyle(style lipgloss.Style) Row { r.Style = style.Copy() return r } // This is somewhat complicated but at the moment splitting this out feels like // it would just make things harder to read. May revisit later. // nolint: cyclop func (m Model) renderRow(rowIndex int, last bool) string { numColumns := len(m.columns) row := m.GetVisibleRows()[rowIndex] highlighted := rowIndex == m.rowCursorIndex columnStrings := []string{} rowStyle := row.Style.Copy() if m.focused && highlighted { rowStyle = rowStyle.Inherit(m.highlightStyle) } stylesInner, stylesLast := m.styleRows() for columnIndex, column := range m.columns { cellStyle := rowStyle.Copy().Inherit(column.style).Inherit(m.baseStyle) var str string if column.key == columnKeySelect { if row.selected { str = m.selectedText } else { str = m.unselectedText } } else if entry, exists := row.Data[column.key]; exists { switch entry := entry.(type) { case StyledCell: str = fmt.Sprintf("%v", entry.Data) cellStyle = entry.Style.Copy().Inherit(cellStyle) default: str = fmt.Sprintf("%v", entry) } } var rowStyles borderStyleRow if !last { rowStyles = stylesInner } else { rowStyles = stylesLast } if columnIndex == 0 { cellStyle = cellStyle.Inherit(rowStyles.left) } else if columnIndex < numColumns-1 { cellStyle = cellStyle.Inherit(rowStyles.inner) } else { cellStyle = cellStyle.Inherit(rowStyles.right) } cellStr := cellStyle.Render(limitStr(str, column.width)) columnStrings = append(columnStrings, cellStr) } return lipgloss.JoinHorizontal(lipgloss.Bottom, columnStrings...) }
table/row.go
0.722918
0.44342
row.go
starcoder
package jsonlogic import ( "fmt" "strings" ) // AddOpMap adds "map" operation to the JSONLogic instance. Param restriction: // - At least two params: the first evaluated to an array and the second the logic. func AddOpMap(jl *JSONLogic) { jl.AddOperation("map", opMap) } func opMap(apply Applier, params []interface{}, data interface{}) (res interface{}, err error) { if len(params) < 2 { return nil, fmt.Errorf("map: expect at least two params") } scopedData, err := apply(params[0], data) if err != nil { return } scopedLogic := params[1] arr, ok := scopedData.([]interface{}) if !ok { return []interface{}{}, nil } mappedArr := []interface{}{} for _, item := range arr { mappedItem, err := apply(scopedLogic, item) if err != nil { return nil, err } mappedArr = append(mappedArr, mappedItem) } return mappedArr, nil } // AddOpFilter adds "filter" operation to the JSONLogic instance. Param restriction: // - At least two params: the first evaluated to an array and the second the logic. func AddOpFilter(jl *JSONLogic) { jl.AddOperation("filter", opFilter) } func opFilter(apply Applier, params []interface{}, data interface{}) (res interface{}, err error) { if len(params) < 2 { return nil, fmt.Errorf("filter: expect at least two params") } scopedData, err := apply(params[0], data) if err != nil { return } scopedLogic := params[1] arr, ok := scopedData.([]interface{}) if !ok { return []interface{}{}, nil } filteredArr := []interface{}{} for _, item := range arr { r, err := apply(scopedLogic, item) if err != nil { return nil, err } if ToBool(r) { filteredArr = append(filteredArr, item) } } return filteredArr, nil } // AddOpReduce adds "reduce" operation to the JSONLogic instance. Param restriction: // - At least three params: the first evaluated to an array, the second the logic and the third the initial value. func AddOpReduce(jl *JSONLogic) { jl.AddOperation("reduce", opReduce) } func opReduce(apply Applier, params []interface{}, data interface{}) (res interface{}, err error) { if len(params) < 3 { return nil, fmt.Errorf("filter: expect at least three params") } scopedData, err := apply(params[0], data) if err != nil { return } scopedLogic := params[1] initial := params[2] arr, ok := scopedData.([]interface{}) if !ok { return initial, nil } for _, item := range arr { r, err := apply(scopedLogic, map[string]interface{}{ "current": item, "accumulator": initial, }) if err != nil { return nil, err } initial = r } return initial, nil } // AddOpAll adds "all" operation to the JSONLogic instance. Param restriction: // - At least two params: the first evaluated to an array and the second the logic. func AddOpAll(jl *JSONLogic) { jl.AddOperation("all", opAll) } func opAll(apply Applier, params []interface{}, data interface{}) (res interface{}, err error) { if len(params) < 2 { return nil, fmt.Errorf("all: expect at least two params") } scopedData, err := apply(params[0], data) if err != nil { return } scopedLogic := params[1] arr, ok := scopedData.([]interface{}) if !ok { return nil, fmt.Errorf("all: expect array as the first param but got %T", scopedData) } if len(arr) == 0 { return false, nil } for _, item := range arr { r, err := apply(scopedLogic, item) if err != nil { return nil, err } if !ToBool(r) { return false, nil } } return true, nil } // AddOpNone adds "none" operation to the JSONLogic instance. Param restriction: // - At least two params: the first evaluated to an array and the second the logic. func AddOpNone(jl *JSONLogic) { jl.AddOperation("none", opNone) } func opNone(apply Applier, params []interface{}, data interface{}) (res interface{}, err error) { if len(params) < 2 { return nil, fmt.Errorf("none: expect at least two params") } scopedData, err := apply(params[0], data) if err != nil { return } scopedLogic := params[1] arr, ok := scopedData.([]interface{}) if !ok { return nil, fmt.Errorf("none: expect array as the first param but got %T", scopedData) } if len(arr) == 0 { return true, nil } for _, item := range arr { r, err := apply(scopedLogic, item) if err != nil { return nil, err } if ToBool(r) { return false, nil } } return true, nil } // AddOpSome adds "some" operation to the JSONLogic instance. Param restriction: // - At least two params: the first evaluated to an array and the second the logic. func AddOpSome(jl *JSONLogic) { jl.AddOperation("some", opSome) } func opSome(apply Applier, params []interface{}, data interface{}) (res interface{}, err error) { if len(params) < 2 { return nil, fmt.Errorf("none: expect at least two params") } scopedData, err := apply(params[0], data) if err != nil { return } scopedLogic := params[1] arr, ok := scopedData.([]interface{}) if !ok { return nil, fmt.Errorf("some: expect array as the first param but got %T", scopedData) } if len(arr) == 0 { return false, nil } for _, item := range arr { r, err := apply(scopedLogic, item) if err != nil { return nil, err } if ToBool(r) { return true, nil } } return false, nil } // AddOpMerge adds "merge" operation to the JSONLogic instance. func AddOpMerge(jl *JSONLogic) { jl.AddOperation("merge", opMerge) } func opMerge(apply Applier, params []interface{}, data interface{}) (res interface{}, err error) { params, err = ApplyParams(apply, params, data) if err != nil { return } ret := []interface{}{} for _, param := range params { if arr, ok := param.([]interface{}); ok { ret = append(ret, arr...) } else { ret = append(ret, param) } } return ret, nil } // AddOpIn adds "in" operation to the JSONLogic instance. Params restriction: // - At least two params: the first to check and the second evaluated to an array or string. // - All items must be evaluated to json primitives. func AddOpIn(jl *JSONLogic) { jl.AddOperation("in", opIn) } func opIn(apply Applier, params []interface{}, data interface{}) (res interface{}, err error) { if len(params) < 2 { return nil, fmt.Errorf("in: expect at least two params") } params, err = ApplyParams(apply, params, data) if err != nil { return } param0 := params[0] if !IsPrimitive(param0) { return nil, fmt.Errorf("in: expect json primitive as first param but got %T", param0) } switch param1 := params[1].(type) { case []interface{}: for _, item := range param1 { if !IsPrimitive(item) { return nil, fmt.Errorf("in: expect json primitives in array but got %T", item) } if param0 == item { return true, nil } } return false, nil case string: s, err := ToString(param0) if err != nil { return nil, err } return strings.Contains(param1, s), nil default: return nil, fmt.Errorf("in: expect array/string as the second param but got %T", params[1]) } } // AddOpCat adds "cat" operation to the JSONLogic instance. Params restriction: // - All items must be evaluated to json primitives that can converted to string. func AddOpCat(jl *JSONLogic) { jl.AddOperation("cat", opCat) } func opCat(apply Applier, params []interface{}, data interface{}) (res interface{}, err error) { params, err = ApplyParams(apply, params, data) if err != nil { return } parts := []string{} for _, param := range params { s, err := ToString(param) if err != nil { return nil, err } parts = append(parts, s) } return strings.Join(parts, ""), nil } // AddOpSubstr adds "substr" operation to the JSONLogic instance. Params restriction: // - Two to three params: the first evaluated to string, and the second/third to numbers. func AddOpSubstr(jl *JSONLogic) { jl.AddOperation("substr", opSubstr) } func opSubstr(apply Applier, params []interface{}, data interface{}) (res interface{}, err error) { if len(params) < 2 { return nil, fmt.Errorf("substr: expect at least two params") } params, err = ApplyParams(apply, params, data) if err != nil { return } s, err := ToString(params[0]) if err != nil { return nil, err } r := []rune(s) var start int { param1, err := ToNumeric(params[1]) if err != nil { return nil, err } start = int(param1) if start < 0 { start += len(r) if start < 0 { start = 0 } } } var ( end int hasEnd bool ) if len(params) > 2 { param2, err := ToNumeric(params[2]) if err != nil { return nil, err } end = int(param2) hasEnd = true } if !hasEnd { return string(r[start:]), nil } if end >= 0 { return string(r[start : start+end]), nil } end += len(r) if end < 0 { end = 0 } return string(r[start:end]), nil }
array_str.go
0.714628
0.506774
array_str.go
starcoder
package plaid import ( "encoding/json" ) // PayPeriodDetails Details about the pay period. type PayPeriodDetails struct { // The amount of the paycheck. CheckAmount NullableFloat32 `json:"check_amount,omitempty"` DistributionBreakdown *[]DistributionBreakdown `json:"distribution_breakdown,omitempty"` // The pay period end date, in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format: \"yyyy-mm-dd\". EndDate NullableString `json:"end_date,omitempty"` // Total earnings before tax/deductions. GrossEarnings NullableFloat32 `json:"gross_earnings,omitempty"` // The date on which the paystub was issued, in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (\"yyyy-mm-dd\"). PayDate NullableString `json:"pay_date,omitempty"` // The frequency at which an individual is paid. PayFrequency NullableString `json:"pay_frequency,omitempty"` // The date on which the paystub was issued, in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format (\"yyyy-mm-dd\"). PayDay NullableString `json:"pay_day,omitempty"` // The pay period start date, in [ISO 8601](https://wikipedia.org/wiki/ISO_8601) format: \"yyyy-mm-dd\". StartDate NullableString `json:"start_date,omitempty"` AdditionalProperties map[string]interface{} } type _PayPeriodDetails PayPeriodDetails // NewPayPeriodDetails instantiates a new PayPeriodDetails object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewPayPeriodDetails() *PayPeriodDetails { this := PayPeriodDetails{} return &this } // NewPayPeriodDetailsWithDefaults instantiates a new PayPeriodDetails object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewPayPeriodDetailsWithDefaults() *PayPeriodDetails { this := PayPeriodDetails{} return &this } // GetCheckAmount returns the CheckAmount field value if set, zero value otherwise (both if not set or set to explicit null). func (o *PayPeriodDetails) GetCheckAmount() float32 { if o == nil || o.CheckAmount.Get() == nil { var ret float32 return ret } return *o.CheckAmount.Get() } // GetCheckAmountOk returns a tuple with the CheckAmount field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *PayPeriodDetails) GetCheckAmountOk() (*float32, bool) { if o == nil { return nil, false } return o.CheckAmount.Get(), o.CheckAmount.IsSet() } // HasCheckAmount returns a boolean if a field has been set. func (o *PayPeriodDetails) HasCheckAmount() bool { if o != nil && o.CheckAmount.IsSet() { return true } return false } // SetCheckAmount gets a reference to the given NullableFloat32 and assigns it to the CheckAmount field. func (o *PayPeriodDetails) SetCheckAmount(v float32) { o.CheckAmount.Set(&v) } // SetCheckAmountNil sets the value for CheckAmount to be an explicit nil func (o *PayPeriodDetails) SetCheckAmountNil() { o.CheckAmount.Set(nil) } // UnsetCheckAmount ensures that no value is present for CheckAmount, not even an explicit nil func (o *PayPeriodDetails) UnsetCheckAmount() { o.CheckAmount.Unset() } // GetDistributionBreakdown returns the DistributionBreakdown field value if set, zero value otherwise. func (o *PayPeriodDetails) GetDistributionBreakdown() []DistributionBreakdown { if o == nil || o.DistributionBreakdown == nil { var ret []DistributionBreakdown return ret } return *o.DistributionBreakdown } // GetDistributionBreakdownOk returns a tuple with the DistributionBreakdown field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *PayPeriodDetails) GetDistributionBreakdownOk() (*[]DistributionBreakdown, bool) { if o == nil || o.DistributionBreakdown == nil { return nil, false } return o.DistributionBreakdown, true } // HasDistributionBreakdown returns a boolean if a field has been set. func (o *PayPeriodDetails) HasDistributionBreakdown() bool { if o != nil && o.DistributionBreakdown != nil { return true } return false } // SetDistributionBreakdown gets a reference to the given []DistributionBreakdown and assigns it to the DistributionBreakdown field. func (o *PayPeriodDetails) SetDistributionBreakdown(v []DistributionBreakdown) { o.DistributionBreakdown = &v } // GetEndDate returns the EndDate field value if set, zero value otherwise (both if not set or set to explicit null). func (o *PayPeriodDetails) GetEndDate() string { if o == nil || o.EndDate.Get() == nil { var ret string return ret } return *o.EndDate.Get() } // GetEndDateOk returns a tuple with the EndDate field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *PayPeriodDetails) GetEndDateOk() (*string, bool) { if o == nil { return nil, false } return o.EndDate.Get(), o.EndDate.IsSet() } // HasEndDate returns a boolean if a field has been set. func (o *PayPeriodDetails) HasEndDate() bool { if o != nil && o.EndDate.IsSet() { return true } return false } // SetEndDate gets a reference to the given NullableString and assigns it to the EndDate field. func (o *PayPeriodDetails) SetEndDate(v string) { o.EndDate.Set(&v) } // SetEndDateNil sets the value for EndDate to be an explicit nil func (o *PayPeriodDetails) SetEndDateNil() { o.EndDate.Set(nil) } // UnsetEndDate ensures that no value is present for EndDate, not even an explicit nil func (o *PayPeriodDetails) UnsetEndDate() { o.EndDate.Unset() } // GetGrossEarnings returns the GrossEarnings field value if set, zero value otherwise (both if not set or set to explicit null). func (o *PayPeriodDetails) GetGrossEarnings() float32 { if o == nil || o.GrossEarnings.Get() == nil { var ret float32 return ret } return *o.GrossEarnings.Get() } // GetGrossEarningsOk returns a tuple with the GrossEarnings field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *PayPeriodDetails) GetGrossEarningsOk() (*float32, bool) { if o == nil { return nil, false } return o.GrossEarnings.Get(), o.GrossEarnings.IsSet() } // HasGrossEarnings returns a boolean if a field has been set. func (o *PayPeriodDetails) HasGrossEarnings() bool { if o != nil && o.GrossEarnings.IsSet() { return true } return false } // SetGrossEarnings gets a reference to the given NullableFloat32 and assigns it to the GrossEarnings field. func (o *PayPeriodDetails) SetGrossEarnings(v float32) { o.GrossEarnings.Set(&v) } // SetGrossEarningsNil sets the value for GrossEarnings to be an explicit nil func (o *PayPeriodDetails) SetGrossEarningsNil() { o.GrossEarnings.Set(nil) } // UnsetGrossEarnings ensures that no value is present for GrossEarnings, not even an explicit nil func (o *PayPeriodDetails) UnsetGrossEarnings() { o.GrossEarnings.Unset() } // GetPayDate returns the PayDate field value if set, zero value otherwise (both if not set or set to explicit null). func (o *PayPeriodDetails) GetPayDate() string { if o == nil || o.PayDate.Get() == nil { var ret string return ret } return *o.PayDate.Get() } // GetPayDateOk returns a tuple with the PayDate field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *PayPeriodDetails) GetPayDateOk() (*string, bool) { if o == nil { return nil, false } return o.PayDate.Get(), o.PayDate.IsSet() } // HasPayDate returns a boolean if a field has been set. func (o *PayPeriodDetails) HasPayDate() bool { if o != nil && o.PayDate.IsSet() { return true } return false } // SetPayDate gets a reference to the given NullableString and assigns it to the PayDate field. func (o *PayPeriodDetails) SetPayDate(v string) { o.PayDate.Set(&v) } // SetPayDateNil sets the value for PayDate to be an explicit nil func (o *PayPeriodDetails) SetPayDateNil() { o.PayDate.Set(nil) } // UnsetPayDate ensures that no value is present for PayDate, not even an explicit nil func (o *PayPeriodDetails) UnsetPayDate() { o.PayDate.Unset() } // GetPayFrequency returns the PayFrequency field value if set, zero value otherwise (both if not set or set to explicit null). func (o *PayPeriodDetails) GetPayFrequency() string { if o == nil || o.PayFrequency.Get() == nil { var ret string return ret } return *o.PayFrequency.Get() } // GetPayFrequencyOk returns a tuple with the PayFrequency field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *PayPeriodDetails) GetPayFrequencyOk() (*string, bool) { if o == nil { return nil, false } return o.PayFrequency.Get(), o.PayFrequency.IsSet() } // HasPayFrequency returns a boolean if a field has been set. func (o *PayPeriodDetails) HasPayFrequency() bool { if o != nil && o.PayFrequency.IsSet() { return true } return false } // SetPayFrequency gets a reference to the given NullableString and assigns it to the PayFrequency field. func (o *PayPeriodDetails) SetPayFrequency(v string) { o.PayFrequency.Set(&v) } // SetPayFrequencyNil sets the value for PayFrequency to be an explicit nil func (o *PayPeriodDetails) SetPayFrequencyNil() { o.PayFrequency.Set(nil) } // UnsetPayFrequency ensures that no value is present for PayFrequency, not even an explicit nil func (o *PayPeriodDetails) UnsetPayFrequency() { o.PayFrequency.Unset() } // GetPayDay returns the PayDay field value if set, zero value otherwise (both if not set or set to explicit null). func (o *PayPeriodDetails) GetPayDay() string { if o == nil || o.PayDay.Get() == nil { var ret string return ret } return *o.PayDay.Get() } // GetPayDayOk returns a tuple with the PayDay field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *PayPeriodDetails) GetPayDayOk() (*string, bool) { if o == nil { return nil, false } return o.PayDay.Get(), o.PayDay.IsSet() } // HasPayDay returns a boolean if a field has been set. func (o *PayPeriodDetails) HasPayDay() bool { if o != nil && o.PayDay.IsSet() { return true } return false } // SetPayDay gets a reference to the given NullableString and assigns it to the PayDay field. func (o *PayPeriodDetails) SetPayDay(v string) { o.PayDay.Set(&v) } // SetPayDayNil sets the value for PayDay to be an explicit nil func (o *PayPeriodDetails) SetPayDayNil() { o.PayDay.Set(nil) } // UnsetPayDay ensures that no value is present for PayDay, not even an explicit nil func (o *PayPeriodDetails) UnsetPayDay() { o.PayDay.Unset() } // GetStartDate returns the StartDate field value if set, zero value otherwise (both if not set or set to explicit null). func (o *PayPeriodDetails) GetStartDate() string { if o == nil || o.StartDate.Get() == nil { var ret string return ret } return *o.StartDate.Get() } // GetStartDateOk returns a tuple with the StartDate field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *PayPeriodDetails) GetStartDateOk() (*string, bool) { if o == nil { return nil, false } return o.StartDate.Get(), o.StartDate.IsSet() } // HasStartDate returns a boolean if a field has been set. func (o *PayPeriodDetails) HasStartDate() bool { if o != nil && o.StartDate.IsSet() { return true } return false } // SetStartDate gets a reference to the given NullableString and assigns it to the StartDate field. func (o *PayPeriodDetails) SetStartDate(v string) { o.StartDate.Set(&v) } // SetStartDateNil sets the value for StartDate to be an explicit nil func (o *PayPeriodDetails) SetStartDateNil() { o.StartDate.Set(nil) } // UnsetStartDate ensures that no value is present for StartDate, not even an explicit nil func (o *PayPeriodDetails) UnsetStartDate() { o.StartDate.Unset() } func (o PayPeriodDetails) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.CheckAmount.IsSet() { toSerialize["check_amount"] = o.CheckAmount.Get() } if o.DistributionBreakdown != nil { toSerialize["distribution_breakdown"] = o.DistributionBreakdown } if o.EndDate.IsSet() { toSerialize["end_date"] = o.EndDate.Get() } if o.GrossEarnings.IsSet() { toSerialize["gross_earnings"] = o.GrossEarnings.Get() } if o.PayDate.IsSet() { toSerialize["pay_date"] = o.PayDate.Get() } if o.PayFrequency.IsSet() { toSerialize["pay_frequency"] = o.PayFrequency.Get() } if o.PayDay.IsSet() { toSerialize["pay_day"] = o.PayDay.Get() } if o.StartDate.IsSet() { toSerialize["start_date"] = o.StartDate.Get() } for key, value := range o.AdditionalProperties { toSerialize[key] = value } return json.Marshal(toSerialize) } func (o *PayPeriodDetails) UnmarshalJSON(bytes []byte) (err error) { varPayPeriodDetails := _PayPeriodDetails{} if err = json.Unmarshal(bytes, &varPayPeriodDetails); err == nil { *o = PayPeriodDetails(varPayPeriodDetails) } additionalProperties := make(map[string]interface{}) if err = json.Unmarshal(bytes, &additionalProperties); err == nil { delete(additionalProperties, "check_amount") delete(additionalProperties, "distribution_breakdown") delete(additionalProperties, "end_date") delete(additionalProperties, "gross_earnings") delete(additionalProperties, "pay_date") delete(additionalProperties, "pay_frequency") delete(additionalProperties, "pay_day") delete(additionalProperties, "start_date") o.AdditionalProperties = additionalProperties } return err } type NullablePayPeriodDetails struct { value *PayPeriodDetails isSet bool } func (v NullablePayPeriodDetails) Get() *PayPeriodDetails { return v.value } func (v *NullablePayPeriodDetails) Set(val *PayPeriodDetails) { v.value = val v.isSet = true } func (v NullablePayPeriodDetails) IsSet() bool { return v.isSet } func (v *NullablePayPeriodDetails) Unset() { v.value = nil v.isSet = false } func NewNullablePayPeriodDetails(val *PayPeriodDetails) *NullablePayPeriodDetails { return &NullablePayPeriodDetails{value: val, isSet: true} } func (v NullablePayPeriodDetails) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullablePayPeriodDetails) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
plaid/model_pay_period_details.go
0.912631
0.416322
model_pay_period_details.go
starcoder
package scv import ( "sort" "github.com/knightjdr/prohits-viz-analysis/pkg/slice" customSort "github.com/knightjdr/prohits-viz-analysis/pkg/sort" "github.com/knightjdr/prohits-viz-analysis/pkg/types" ) func createPlotData(data map[string]map[string]map[string]float64, known map[string]map[string]bool, legend types.CircHeatmapLegend, settings types.Settings) []types.CircHeatmap { conditions := getAndSortConditions(data) writeKnownness := getKnownessInteractiveWriter(settings.Known, known) plots := make([]types.CircHeatmap, len(conditions)) for i, condition := range conditions { readouts := getAndSortReadouts(data[condition], known[condition], settings.Known, legend[0].Attribute) plots[i] = types.CircHeatmap{ Name: condition, Readouts: make([]types.CircHeatmapReadout, len(readouts)), } for j, readout := range readouts { plots[i].Readouts[j] = types.CircHeatmapReadout{ Known: writeKnownness(condition, readout), Label: readout, Segments: make(map[string]types.RoundedSegment, len(legend)), } for _, legendElement := range legend { plots[i].Readouts[j].Segments[legendElement.Attribute] = types.RoundedSegment(data[condition][readout][legendElement.Attribute]) } } } return plots } func getAndSortConditions(data map[string]map[string]map[string]float64) []string { conditions := make([]string, len(data)) i := 0 for condition := range data { conditions[i] = condition i++ } sort.Strings(conditions) return conditions } func getKnownessInteractiveWriter(known string, knownMap map[string]map[string]bool) func(string, string) bool { if known != "" && knownMap != nil { return func(condition string, readout string) bool { return knownMap[condition][readout] } } return func(condition string, readout string) bool { return false } } func getAndSortReadouts(data map[string]map[string]float64, knownMap map[string]bool, sortByKnown string, attribute string) []string { readouts := make([]string, 0) values := make([]float64, 0) if sortByKnown != "" && knownMap != nil { knownReadouts := make([]string, 0) knownValues := make([]float64, 0) unknownReadouts := make([]string, 0) unknownValues := make([]float64, 0) for readout, readoutData := range data { value := readoutData[attribute] if knownMap[readout] { knownReadouts = append(knownReadouts, readout) knownValues = append(knownValues, value) } else { unknownReadouts = append(unknownReadouts, readout) unknownValues = append(unknownValues, value) } } readouts = append(readouts, knownReadouts...) readouts = append(readouts, unknownReadouts...) values = append(values, knownValues...) values = append(values, unknownValues...) sorted := sortReadouts(knownValues, knownReadouts) return append(sorted, sortReadouts(unknownValues, unknownReadouts)...) } for readout, readoutData := range data { readouts = append(readouts, readout) values = append(values, readoutData[attribute]) } return sortReadouts(values, readouts) } func sortReadouts(values []float64, readouts []string) []string { indices := customSort.ArgsortFloat(values) indices = slice.ReverseInt(indices) sorted := make([]string, 0) for _, index := range indices { sorted = append(sorted, readouts[index]) } return sorted }
pkg/tools/analyze/scv/createplotdata.go
0.618089
0.413418
createplotdata.go
starcoder
package gl import "github.com/ContextLogic/cldr" var calendar = cldr.Calendar{ Formats: cldr.CalendarFormats{ Date: cldr.CalendarDateFormat{Full: "EEEE dd MMMM y", Long: "dd MMMM y", Medium: "d MMM, y", Short: "dd/MM/yy"}, Time: cldr.CalendarDateFormat{Full: "HH:mm:ss zzzz", Long: "HH:mm:ss z", Medium: "HH:mm:ss", Short: "HH:mm"}, DateTime: cldr.CalendarDateFormat{Full: "{1} {0}", Long: "{1} {0}", Medium: "{1} {0}", Short: "{1} {0}"}, }, FormatNames: cldr.CalendarFormatNames{ Months: cldr.CalendarMonthFormatNames{ Abbreviated: cldr.CalendarMonthFormatNameValue{Jan: "Xan", Feb: "Feb", Mar: "Mar", Apr: "Abr", May: "Mai", Jun: "Xuñ", Jul: "Xul", Aug: "Ago", Sep: "Set", Oct: "Out", Nov: "Nov", Dec: "Dec"}, Narrow: cldr.CalendarMonthFormatNameValue{Jan: "X", Feb: "F", Mar: "M", Apr: "A", May: "M", Jun: "X", Jul: "X", Aug: "A", Sep: "S", Oct: "O", Nov: "N", Dec: "D"}, Short: cldr.CalendarMonthFormatNameValue{}, Wide: cldr.CalendarMonthFormatNameValue{Jan: "Xaneiro", Feb: "Febreiro", Mar: "Marzo", Apr: "Abril", May: "Maio", Jun: "Xuño", Jul: "Xullo", Aug: "Agosto", Sep: "Setembro", Oct: "Outubro", Nov: "Novembro", Dec: "Decembro"}, }, Days: cldr.CalendarDayFormatNames{ Abbreviated: cldr.CalendarDayFormatNameValue{Sun: "Dom", Mon: "Lun", Tue: "Mar", Wed: "Mér", Thu: "Xov", Fri: "Ven", Sat: "Sáb"}, Narrow: cldr.CalendarDayFormatNameValue{Sun: "D", Mon: "L", Tue: "M", Wed: "M", Thu: "X", Fri: "V", Sat: "S"}, Short: cldr.CalendarDayFormatNameValue{Sun: "Dom", Mon: "Luns", Tue: "Mt", Wed: "Mc", Thu: "Xv", Fri: "Ven", Sat: "Sáb"}, Wide: cldr.CalendarDayFormatNameValue{Sun: "Domingo", Mon: "Luns", Tue: "Martes", Wed: "Mércores", Thu: "Xoves", Fri: "Venres", Sat: "Sábado"}, }, Periods: cldr.CalendarPeriodFormatNames{ Abbreviated: cldr.CalendarPeriodFormatNameValue{AM: "a.m.", PM: "p.m."}, Narrow: cldr.CalendarPeriodFormatNameValue{AM: "a", PM: "p"}, Short: cldr.CalendarPeriodFormatNameValue{}, Wide: cldr.CalendarPeriodFormatNameValue{AM: "a.m.", PM: "p.m."}, }, }, }
resources/locales/gl/calendar.go
0.534127
0.469095
calendar.go
starcoder
package ugo import ( "math" "strconv" "strings" "github.com/ozanh/ugo/token" ) // Int represents signed integer values and implements Object interface. type Int int64 // TypeName implements Object interface. func (Int) TypeName() string { return "int" } // String implements Object interface. func (o Int) String() string { return strconv.FormatInt(int64(o), 10) } // Equal implements Object interface. func (o Int) Equal(right Object) bool { switch v := right.(type) { case Int: return o == v case Uint: return Uint(o) == v case Float: return Float(o) == v case Char: return o == Int(v) case Bool: if v { return o == 1 } return o == 0 } return false } // IsFalsy implements Object interface. func (o Int) IsFalsy() bool { return o == 0 } // CanCall implements Object interface. func (o Int) CanCall() bool { return false } // Call implements Object interface. func (o Int) Call(_ ...Object) (Object, error) { return nil, ErrNotCallable } // CanIterate implements Object interface. func (Int) CanIterate() bool { return false } // Iterate implements Object interface. func (Int) Iterate() Iterator { return nil } // IndexSet implements Object interface. func (Int) IndexSet(index, value Object) error { return ErrNotIndexAssignable } // IndexGet implements Object interface. func (Int) IndexGet(index Object) (Object, error) { return nil, ErrNotIndexable } // BinaryOp implements Object interface. func (o Int) BinaryOp(tok token.Token, right Object) (Object, error) { switch v := right.(type) { case Int: switch tok { case token.Add: return o + v, nil case token.Sub: return o - v, nil case token.Mul: return o * v, nil case token.Quo: if v == 0 { return nil, ErrZeroDivision } return o / v, nil case token.Rem: return o % v, nil case token.And: return o & v, nil case token.Or: return o | v, nil case token.Xor: return o ^ v, nil case token.AndNot: return o &^ v, nil case token.Shl: return o << v, nil case token.Shr: return o >> v, nil case token.Less: return Bool(o < v), nil case token.LessEq: return Bool(o <= v), nil case token.Greater: return Bool(o > v), nil case token.GreaterEq: return Bool(o >= v), nil } case Uint: return Uint(o).BinaryOp(tok, right) case Float: return Float(o).BinaryOp(tok, right) case Char: switch tok { case token.Add: return Char(o) + v, nil case token.Sub: return Char(o) - v, nil case token.Less: return Bool(o < Int(v)), nil case token.LessEq: return Bool(o <= Int(v)), nil case token.Greater: return Bool(o > Int(v)), nil case token.GreaterEq: return Bool(o >= Int(v)), nil } case Bool: if v { right = Int(1) } else { right = Int(0) } return o.BinaryOp(tok, right) case undefined: switch tok { case token.Less, token.LessEq: return False, nil case token.Greater, token.GreaterEq: return True, nil } } return nil, NewOperandTypeError( tok.String(), o.TypeName(), right.TypeName(), ) } // Uint represents unsigned integer values and implements Object interface. type Uint uint64 // TypeName implements Object interface. func (Uint) TypeName() string { return "uint" } // String implements Object interface. func (o Uint) String() string { return strconv.FormatUint(uint64(o), 10) } // Equal implements Object interface. func (o Uint) Equal(right Object) bool { switch v := right.(type) { case Uint: return o == v case Int: return o == Uint(v) case Float: return Float(o) == v case Char: return o == Uint(v) case Bool: if v { return o == 1 } return o == 0 } return false } // IsFalsy implements Object interface. func (o Uint) IsFalsy() bool { return o == 0 } // CanCall implements Object interface. func (o Uint) CanCall() bool { return false } // Call implements Object interface. func (o Uint) Call(_ ...Object) (Object, error) { return nil, ErrNotCallable } // CanIterate implements Object interface. func (Uint) CanIterate() bool { return false } // Iterate implements Object interface. func (Uint) Iterate() Iterator { return nil } // IndexSet implements Object interface. func (Uint) IndexSet(index, value Object) error { return ErrNotIndexAssignable } // IndexGet implements Object interface. func (Uint) IndexGet(index Object) (Object, error) { return nil, ErrNotIndexable } // BinaryOp implements Object interface. func (o Uint) BinaryOp(tok token.Token, right Object) (Object, error) { switch v := right.(type) { case Uint: switch tok { case token.Add: return o + v, nil case token.Sub: return o - v, nil case token.Mul: return o * v, nil case token.Quo: if v == 0 { return nil, ErrZeroDivision } return o / v, nil case token.Rem: return o % v, nil case token.And: return o & v, nil case token.Or: return o | v, nil case token.Xor: return o ^ v, nil case token.AndNot: return o &^ v, nil case token.Shl: return o << v, nil case token.Shr: return o >> v, nil case token.Less: return Bool(o < v), nil case token.LessEq: return Bool(o <= v), nil case token.Greater: return Bool(o > v), nil case token.GreaterEq: return Bool(o >= v), nil } case Int: return o.BinaryOp(tok, Uint(v)) case Float: return Float(o).BinaryOp(tok, right) case Char: switch tok { case token.Add: return Char(o) + v, nil case token.Sub: return Char(o) - v, nil case token.Less: return Bool(o < Uint(v)), nil case token.LessEq: return Bool(o <= Uint(v)), nil case token.Greater: return Bool(o > Uint(v)), nil case token.GreaterEq: return Bool(o >= Uint(v)), nil } case Bool: if v { right = Uint(1) } else { right = Uint(0) } return o.BinaryOp(tok, right) case undefined: switch tok { case token.Less, token.LessEq: return False, nil case token.Greater, token.GreaterEq: return True, nil } } return nil, NewOperandTypeError( tok.String(), o.TypeName(), right.TypeName(), ) } // Float represents float values and implements Object interface. type Float float64 // TypeName implements Object interface. func (Float) TypeName() string { return "float" } // String implements Object interface. func (o Float) String() string { return strconv.FormatFloat(float64(o), 'g', -1, 64) } // Equal implements Object interface. func (o Float) Equal(right Object) bool { switch v := right.(type) { case Float: return o == v case Int: return o == Float(v) case Uint: return o == Float(v) case Bool: if v { return o == 1 } return o == 0 } return false } // IsFalsy implements Object interface. func (o Float) IsFalsy() bool { return math.IsNaN(float64(o)) } // CanCall implements Object interface. func (o Float) CanCall() bool { return false } // Call implements Object interface. func (o Float) Call(_ ...Object) (Object, error) { return nil, ErrNotCallable } // CanIterate implements Object interface. func (Float) CanIterate() bool { return false } // Iterate implements Object interface. func (Float) Iterate() Iterator { return nil } // IndexSet implements Object interface. func (Float) IndexSet(index, value Object) error { return ErrNotIndexAssignable } // IndexGet implements Object interface. func (Float) IndexGet(index Object) (Object, error) { return nil, ErrNotIndexable } // BinaryOp implements Object interface. func (o Float) BinaryOp(tok token.Token, right Object) (Object, error) { switch v := right.(type) { case Float: switch tok { case token.Add: return o + v, nil case token.Sub: return o - v, nil case token.Mul: return o * v, nil case token.Quo: if v == 0 { return nil, ErrZeroDivision } return o / v, nil case token.Less: return Bool(o < v), nil case token.LessEq: return Bool(o <= v), nil case token.Greater: return Bool(o > v), nil case token.GreaterEq: return Bool(o >= v), nil } case Int: return o.BinaryOp(tok, Float(v)) case Uint: return o.BinaryOp(tok, Float(v)) case Bool: if v { right = Float(1) } else { right = Float(0) } return o.BinaryOp(tok, right) case undefined: switch tok { case token.Less, token.LessEq: return False, nil case token.Greater, token.GreaterEq: return True, nil } } return nil, NewOperandTypeError( tok.String(), o.TypeName(), right.TypeName(), ) } // Char represents a rune and implements Object interface. type Char rune // TypeName implements Object interface. func (Char) TypeName() string { return "char" } // String implements Object interface. func (o Char) String() string { return string(o) } // Equal implements Object interface. func (o Char) Equal(right Object) bool { switch v := right.(type) { case Char: return o == v case Int: return Int(o) == v case Uint: return Uint(o) == v case Float: return Float(o) == v case Bool: if v { return o == 1 } return o == 0 } return false } // IsFalsy implements Object interface. func (o Char) IsFalsy() bool { return o == 0 } // CanCall implements Object interface. func (o Char) CanCall() bool { return false } // Call implements Object interface. func (o Char) Call(_ ...Object) (Object, error) { return nil, ErrNotCallable } // CanIterate implements Object interface. func (Char) CanIterate() bool { return false } // Iterate implements Object interface. func (Char) Iterate() Iterator { return nil } // IndexSet implements Object interface. func (Char) IndexSet(index, value Object) error { return ErrNotIndexAssignable } // IndexGet implements Object interface. func (Char) IndexGet(index Object) (Object, error) { return nil, ErrNotIndexable } // BinaryOp implements Object interface. func (o Char) BinaryOp(tok token.Token, right Object) (Object, error) { switch v := right.(type) { case Char: switch tok { case token.Add: return o + v, nil case token.Sub: return o - v, nil case token.Mul: return o * v, nil case token.Quo: if v == 0 { return nil, ErrZeroDivision } return o / v, nil case token.Rem: return o % v, nil case token.And: return o & v, nil case token.Or: return o | v, nil case token.Xor: return o ^ v, nil case token.AndNot: return o &^ v, nil case token.Shl: return o << v, nil case token.Shr: return o >> v, nil case token.Less: return Bool(o < v), nil case token.LessEq: return Bool(o <= v), nil case token.Greater: return Bool(o > v), nil case token.GreaterEq: return Bool(o >= v), nil } case Int: switch tok { case token.Add: return o + Char(v), nil case token.Sub: return o - Char(v), nil case token.Less: return Bool(Int(o) < v), nil case token.LessEq: return Bool(Int(o) <= v), nil case token.Greater: return Bool(Int(o) > v), nil case token.GreaterEq: return Bool(Int(o) >= v), nil } case Uint: switch tok { case token.Add: return o + Char(v), nil case token.Sub: return o - Char(v), nil case token.Less: return Bool(Uint(o) < v), nil case token.LessEq: return Bool(Uint(o) <= v), nil case token.Greater: return Bool(Uint(o) > v), nil case token.GreaterEq: return Bool(Uint(o) >= v), nil } case Bool: if v { right = Char(1) } else { right = Char(0) } return o.BinaryOp(tok, right) case String: if tok == token.Add { var sb strings.Builder sb.Grow(len(v) + 4) sb.WriteRune(rune(o)) sb.WriteString(string(v)) return String(sb.String()), nil } case undefined: switch tok { case token.Less, token.LessEq: return False, nil case token.Greater, token.GreaterEq: return True, nil } } return nil, NewOperandTypeError( tok.String(), o.TypeName(), right.TypeName(), ) }
numeric.go
0.726814
0.471771
numeric.go
starcoder
package utils import ( "fmt" "github.com/google/go-cmp/cmp" "github.com/google/go-cmp/cmp/cmpopts" "github.com/mitchellh/mapstructure" "math" "math/rand" "reflect" "testing" ) func ContainsString(slice *[]string, value *string) bool { for _, v := range *slice { if v == *value { return true } } return false } func RemoveSingleStringOccurrence(s []string, r string) []string { for i, v := range s { if v == r { return append(s[:i], s[i+1:]...) } } return s } func ContainsInts(slice *[]int, value *int) bool { for _, v := range *slice { if v == *value { return true } } return false } func FloatsAreEqual(expected float64, actual float64, epsilon float64) bool { return math.Abs(expected-actual) <= epsilon } func ErrorDiffers(err interface{}, message string) bool { return err.(error).Error() != message } func ExpectError(t *testing.T, expectedMessage string) func() { return func() { if e := recover(); e == nil { t.Errorf("expected error with message '%s'", expectedMessage) } else if ErrorDiffers(e, expectedMessage) { t.Errorf("invalid error message:\nactual '%s'\nexpected '%s'", e, expectedMessage) } } } func CheckValueRange(t *testing.T, valueRange ValueRange, expMin, expMax float64) { validateValue(t, "min", expMin, valueRange.Min) validateValue(t, "max", expMax, valueRange.Max) } func validateValue(t *testing.T, name string, expected, actual float64) { if !FloatsAreEqual(actual, expected, 1e-6) { t.Errorf("%s value expected %f, got %f", name, expected, actual) } } func IsPositive(value float64) bool { return value > 0 } func IsInBounds(value float64, lower float64, upper float64) bool { return value >= lower && value <= upper } func IsProbability(value float64) bool { return IsInBounds(value, 0, 1) } func DecodeToStruct(src, target interface{}) { e := mapstructure.Decode(src, target) if e != nil { panic(e) } } type ValueRange struct { Min float64 `json:"min"` Max float64 `json:"max"` } func (r *ValueRange) String() string { return fmt.Sprintf("min: %.4f, max: %.4f", r.Min, r.Max) } func (r *ValueRange) Diff() float64 { return r.Max - r.Min } func (r *ValueRange) ScaleEqually(scale float64) *ValueRange { dif := r.Diff() / 2 return &ValueRange{ Min: r.Min + dif - dif*scale, Max: r.Max - dif + dif*scale, } } func NewValueRange() *ValueRange { return &ValueRange{ Min: 0, Max: 0, } } type SeededValueGenerator = func(seed int64) ValueGenerator type ValueGenerator = func() float64 func RandomGenerator(seed int64) *rand.Rand { source := rand.NewSource(seed) return rand.New(source) } func RandomBasedSeedValueGenerator(seed int64) ValueGenerator { gen := RandomGenerator(seed) return func() float64 { return gen.Float64() } } func NewValueInRangeGenerator(generator ValueGenerator, valueRange *ValueRange) ValueGenerator { dif := valueRange.Max - valueRange.Min return func() float64 { return generator()*dif + valueRange.Min } } type Map = map[string]interface{} type Array = []interface{} func Differs(a, b interface{}) bool { return !cmp.Equal(a, b, cmpopts.EquateApprox(0, 1e-8), cmp.Exporter(func(r reflect.Type) bool { return true })) }
lib/utils/utils.go
0.727782
0.511168
utils.go
starcoder
package datadog import ( "encoding/json" ) // SLOHistoryMetricsSeriesMetadata Query metadata. type SLOHistoryMetricsSeriesMetadata struct { // Query aggregator function. Aggr *string `json:"aggr,omitempty"` // Query expression. Expression *string `json:"expression,omitempty"` // Query metric used. Metric *string `json:"metric,omitempty"` // Query index from original combined query. QueryIndex *int64 `json:"query_index,omitempty"` // Query scope. Scope *string `json:"scope,omitempty"` // An array of metric units that contains up to two unit objects. For example, bytes represents one unit object and bytes per second represents two unit objects. If a metric query only has one unit object, the second array element is null. Unit []SLOHistoryMetricsSeriesMetadataUnit `json:"unit,omitempty"` // UnparsedObject contains the raw value of the object if there was an error when deserializing into the struct UnparsedObject map[string]interface{} `json:-` } // NewSLOHistoryMetricsSeriesMetadata instantiates a new SLOHistoryMetricsSeriesMetadata object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewSLOHistoryMetricsSeriesMetadata() *SLOHistoryMetricsSeriesMetadata { this := SLOHistoryMetricsSeriesMetadata{} return &this } // NewSLOHistoryMetricsSeriesMetadataWithDefaults instantiates a new SLOHistoryMetricsSeriesMetadata object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewSLOHistoryMetricsSeriesMetadataWithDefaults() *SLOHistoryMetricsSeriesMetadata { this := SLOHistoryMetricsSeriesMetadata{} return &this } // GetAggr returns the Aggr field value if set, zero value otherwise. func (o *SLOHistoryMetricsSeriesMetadata) GetAggr() string { if o == nil || o.Aggr == nil { var ret string return ret } return *o.Aggr } // GetAggrOk returns a tuple with the Aggr field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SLOHistoryMetricsSeriesMetadata) GetAggrOk() (*string, bool) { if o == nil || o.Aggr == nil { return nil, false } return o.Aggr, true } // HasAggr returns a boolean if a field has been set. func (o *SLOHistoryMetricsSeriesMetadata) HasAggr() bool { if o != nil && o.Aggr != nil { return true } return false } // SetAggr gets a reference to the given string and assigns it to the Aggr field. func (o *SLOHistoryMetricsSeriesMetadata) SetAggr(v string) { o.Aggr = &v } // GetExpression returns the Expression field value if set, zero value otherwise. func (o *SLOHistoryMetricsSeriesMetadata) GetExpression() string { if o == nil || o.Expression == nil { var ret string return ret } return *o.Expression } // GetExpressionOk returns a tuple with the Expression field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SLOHistoryMetricsSeriesMetadata) GetExpressionOk() (*string, bool) { if o == nil || o.Expression == nil { return nil, false } return o.Expression, true } // HasExpression returns a boolean if a field has been set. func (o *SLOHistoryMetricsSeriesMetadata) HasExpression() bool { if o != nil && o.Expression != nil { return true } return false } // SetExpression gets a reference to the given string and assigns it to the Expression field. func (o *SLOHistoryMetricsSeriesMetadata) SetExpression(v string) { o.Expression = &v } // GetMetric returns the Metric field value if set, zero value otherwise. func (o *SLOHistoryMetricsSeriesMetadata) GetMetric() string { if o == nil || o.Metric == nil { var ret string return ret } return *o.Metric } // GetMetricOk returns a tuple with the Metric field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SLOHistoryMetricsSeriesMetadata) GetMetricOk() (*string, bool) { if o == nil || o.Metric == nil { return nil, false } return o.Metric, true } // HasMetric returns a boolean if a field has been set. func (o *SLOHistoryMetricsSeriesMetadata) HasMetric() bool { if o != nil && o.Metric != nil { return true } return false } // SetMetric gets a reference to the given string and assigns it to the Metric field. func (o *SLOHistoryMetricsSeriesMetadata) SetMetric(v string) { o.Metric = &v } // GetQueryIndex returns the QueryIndex field value if set, zero value otherwise. func (o *SLOHistoryMetricsSeriesMetadata) GetQueryIndex() int64 { if o == nil || o.QueryIndex == nil { var ret int64 return ret } return *o.QueryIndex } // GetQueryIndexOk returns a tuple with the QueryIndex field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SLOHistoryMetricsSeriesMetadata) GetQueryIndexOk() (*int64, bool) { if o == nil || o.QueryIndex == nil { return nil, false } return o.QueryIndex, true } // HasQueryIndex returns a boolean if a field has been set. func (o *SLOHistoryMetricsSeriesMetadata) HasQueryIndex() bool { if o != nil && o.QueryIndex != nil { return true } return false } // SetQueryIndex gets a reference to the given int64 and assigns it to the QueryIndex field. func (o *SLOHistoryMetricsSeriesMetadata) SetQueryIndex(v int64) { o.QueryIndex = &v } // GetScope returns the Scope field value if set, zero value otherwise. func (o *SLOHistoryMetricsSeriesMetadata) GetScope() string { if o == nil || o.Scope == nil { var ret string return ret } return *o.Scope } // GetScopeOk returns a tuple with the Scope field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *SLOHistoryMetricsSeriesMetadata) GetScopeOk() (*string, bool) { if o == nil || o.Scope == nil { return nil, false } return o.Scope, true } // HasScope returns a boolean if a field has been set. func (o *SLOHistoryMetricsSeriesMetadata) HasScope() bool { if o != nil && o.Scope != nil { return true } return false } // SetScope gets a reference to the given string and assigns it to the Scope field. func (o *SLOHistoryMetricsSeriesMetadata) SetScope(v string) { o.Scope = &v } // GetUnit returns the Unit field value if set, zero value otherwise (both if not set or set to explicit null). func (o *SLOHistoryMetricsSeriesMetadata) GetUnit() []SLOHistoryMetricsSeriesMetadataUnit { if o == nil { var ret []SLOHistoryMetricsSeriesMetadataUnit return ret } return o.Unit } // GetUnitOk returns a tuple with the Unit field value if set, nil otherwise // and a boolean to check if the value has been set. // NOTE: If the value is an explicit nil, `nil, true` will be returned func (o *SLOHistoryMetricsSeriesMetadata) GetUnitOk() (*[]SLOHistoryMetricsSeriesMetadataUnit, bool) { if o == nil || o.Unit == nil { return nil, false } return &o.Unit, true } // HasUnit returns a boolean if a field has been set. func (o *SLOHistoryMetricsSeriesMetadata) HasUnit() bool { if o != nil && o.Unit != nil { return true } return false } // SetUnit gets a reference to the given []SLOHistoryMetricsSeriesMetadataUnit and assigns it to the Unit field. func (o *SLOHistoryMetricsSeriesMetadata) SetUnit(v []SLOHistoryMetricsSeriesMetadataUnit) { o.Unit = v } func (o SLOHistoryMetricsSeriesMetadata) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.UnparsedObject != nil { return json.Marshal(o.UnparsedObject) } if o.Aggr != nil { toSerialize["aggr"] = o.Aggr } if o.Expression != nil { toSerialize["expression"] = o.Expression } if o.Metric != nil { toSerialize["metric"] = o.Metric } if o.QueryIndex != nil { toSerialize["query_index"] = o.QueryIndex } if o.Scope != nil { toSerialize["scope"] = o.Scope } if o.Unit != nil { toSerialize["unit"] = o.Unit } return json.Marshal(toSerialize) } func (o *SLOHistoryMetricsSeriesMetadata) UnmarshalJSON(bytes []byte) (err error) { raw := map[string]interface{}{} all := struct { Aggr *string `json:"aggr,omitempty"` Expression *string `json:"expression,omitempty"` Metric *string `json:"metric,omitempty"` QueryIndex *int64 `json:"query_index,omitempty"` Scope *string `json:"scope,omitempty"` Unit []SLOHistoryMetricsSeriesMetadataUnit `json:"unit,omitempty"` }{} err = json.Unmarshal(bytes, &all) if err != nil { err = json.Unmarshal(bytes, &raw) if err != nil { return err } o.UnparsedObject = raw return nil } o.Aggr = all.Aggr o.Expression = all.Expression o.Metric = all.Metric o.QueryIndex = all.QueryIndex o.Scope = all.Scope o.Unit = all.Unit return nil } type NullableSLOHistoryMetricsSeriesMetadata struct { value *SLOHistoryMetricsSeriesMetadata isSet bool } func (v NullableSLOHistoryMetricsSeriesMetadata) Get() *SLOHistoryMetricsSeriesMetadata { return v.value } func (v *NullableSLOHistoryMetricsSeriesMetadata) Set(val *SLOHistoryMetricsSeriesMetadata) { v.value = val v.isSet = true } func (v NullableSLOHistoryMetricsSeriesMetadata) IsSet() bool { return v.isSet } func (v *NullableSLOHistoryMetricsSeriesMetadata) Unset() { v.value = nil v.isSet = false } func NewNullableSLOHistoryMetricsSeriesMetadata(val *SLOHistoryMetricsSeriesMetadata) *NullableSLOHistoryMetricsSeriesMetadata { return &NullableSLOHistoryMetricsSeriesMetadata{value: val, isSet: true} } func (v NullableSLOHistoryMetricsSeriesMetadata) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableSLOHistoryMetricsSeriesMetadata) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }
api/v1/datadog/model_slo_history_metrics_series_metadata.go
0.827061
0.414662
model_slo_history_metrics_series_metadata.go
starcoder
package kernels //XtraKerns returns the kernel names through methods type XtraKerns struct { } //ConcatNHWCEXHalf - Does a concat backward with multiple outputs func (t XtraKerns) ConcatNHWCEXHalf() string { return "ConcatNHWCEXHalf" } //ConcatNHWCEX - Does a concat backward with multiple outputs func (t XtraKerns) ConcatNHWCEX() string { return "ConcatNHWCEX" } //ConcatNCHWEX - Does a concat forward with multiple inputs func (t XtraKerns) ConcatNCHWEX() string { return "ConcatNCHWEX" } //ConcatNCHWEXHalf - Does a concat forward with multiple inputs func (t XtraKerns) ConcatNCHWEXHalf() string { return "ConcatNCHWEXHalf" } //SoftMaxAverageLoss func (t XtraKerns) SoftMaxAverageLoss() string { return "SoftMaxAverageLoss" } //MSELoss Mean Squared Error Loss func (t XtraKerns) MSELoss() string { return "MSELoss" } //MSELossFP16 Mean Squared Error Loss func (t XtraKerns) MSELossFP16() string { return "MSELossFP16" } //ShapeToBatch4DNCHW transfers HW to batch and vice versa for NCHW tensors func (t XtraKerns) ShapeToBatch4DNCHW() string { return "ShapetoBatch4DNCHW" } //ShapetoBatch4DNCHWFP16 transfers HW to batch and vice versa for NCHW tensors func (t XtraKerns) ShapetoBatch4DNCHWFP16() string { return "ShapetoBatch4DNCHWFP16" } //SwapEveryOther allows the user to swap batches between to tensors //Either the even or the odd tensors. func (t XtraKerns) SwapEveryOther() string { return "SwapEveryOther" } //SwapEveryOtherFP16 does SwapEveryOther in fp16 func (t XtraKerns) SwapEveryOtherFP16() string { return "SwapEveryOtherFP16" } //SwapUpperLower takes to tensors and swaps the upper or lower batches between the two tensors func (t XtraKerns) SwapUpperLower() string { return "SwapUpperLower" } //SwapUpperLowerFP16 takes to tensors and swaps the upper or lower batches between the two tensors func (t XtraKerns) SwapUpperLowerFP16() string { return "SwapUpperLowerFP16" } //Transpose switches values around from one dimention to the other func (t XtraKerns) Transpose() string { return "Transpose" } //TransposeFP16 switches values around from one dimention to the other func (t XtraKerns) TransposeFP16() string { return "TransposeFP16" } //ShapeToBatch4DNHWC transfer HW to batch and vice versa through windows for NHWC tensors func (t XtraKerns) ShapeToBatch4DNHWC() string { return "ShapetoBatch4DNHWC" } //ShapetoBatch4DNHWCFP16 transfer HW to batch and vice versa through windows for NHWC tensors func (t XtraKerns) ShapetoBatch4DNHWCFP16() string { return "ShapetoBatch4DNHWCFP16" } //NearestNeighborNHWC Resize NearestNeightbor for NHWC tensors func (t XtraKerns) NearestNeighborNHWC() string { return "NearestNeighborNHWC" } //NearestNeighborNHWCFP16 Resize NearestNeightbor for NHWC tensors func (t XtraKerns) NearestNeighborNHWCFP16() string { return "NearestNeighborNHWCFP16" } //NearestNeighborNCHW Resize NearestNeightbor for NCHW tensors func (t XtraKerns) NearestNeighborNCHW() string { return "NearestNeighborNCHW" } //NearestNeighborNCHWFP16 Resize NearestNeightbor for NCHW tensors func (t XtraKerns) NearestNeighborNCHWFP16() string { return "NearestNeighborNCHWFP16" } //NearestNeighborNHWCBack Resize NearestNeightbor for NHWC tensors and accumulates gradients func (t XtraKerns) NearestNeighborNHWCBack() string { return "NearestNeighborNHWCBack" } //NearestNeighborNHWCBackFP16 Resize NearestNeightbor for NHWC tensors and accumulates gradients func (t XtraKerns) NearestNeighborNHWCBackFP16() string { return "NearestNeighborNHWCBackFP16" } //NearestNeighborNCHWBack Resize NearestNeightbor for NCHW tensors and accumulates gradients func (t XtraKerns) NearestNeighborNCHWBack() string { return "NearestNeighborNCHWBack" } //NearestNeighborNCHWBackFP16 Resize NearestNeightbor for NCHW tensors and accumulates gradients func (t XtraKerns) NearestNeighborNCHWBackFP16() string { return "NearestNeighborNCHWBackFP16" } //ThreshForward Not tested func (t XtraKerns) ThreshForward() string { return "ThreshForward" } //ThreshForwardFP16 Not tested func (t XtraKerns) ThreshForwardFP16() string { return "ThreshForwardFP16" } //ThreshBackward Not tested func (t XtraKerns) ThreshBackward() string { return "ThreshBackward" } //ThreshBackwardFP16 Not tested func (t XtraKerns) ThreshBackwardFP16() string { return "ThreshBackwardFP16" } //PreluForward Not tested func (t XtraKerns) PreluForward() string { return "PreluForward" } //PreluForwardFP16 Not tested func (t XtraKerns) PreluForwardFP16() string { return "PreluForwardFP16" } //PreluBackward Not tested func (t XtraKerns) PreluBackward() string { return "PreluBackward" } //PreluBackwardFP16 Not tested func (t XtraKerns) PreluBackwardFP16() string { return "PreluBackwardFP16" } //LeakyForward activation function Relu but negatives get a reduced value func (t XtraKerns) LeakyForward() string { return "LeakyForward" } //LeakyForwardFP16 activation function Relu but negatives get a reduced value func (t XtraKerns) LeakyForwardFP16() string { return "LeakyForwardFP16" } //LeakyBackward activation function Relu but negatives get a reduced value func (t XtraKerns) LeakyBackward() string { return "LeakyBackward" } //LeakyBackwardFP16 activation function Relu but negatives get a reduced value func (t XtraKerns) LeakyBackwardFP16() string { return "LeakyBackwardFP16" } //LeakyForwardAlpha activation function Relu but negatives get a reduced value result = alpha * activationfunc() func (t XtraKerns) LeakyForwardAlpha() string { return "LeakyForwardAlpha" } //LeakyForwardAlphaFP16 activation function Relu but negatives get a reduced value result = alpha * activationfunc() func (t XtraKerns) LeakyForwardAlphaFP16() string { return "LeakyForwardAlphaFP16" } //LeakyBackwardAlpha activation function Relu but negatives get a reduced value and function gets the ----- result = alpha * activationfunc() func (t XtraKerns) LeakyBackwardAlpha() string { return "LeakyBackwardAlpha" } //LeakyBackwardAlphaFP16 activation function Relu but negatives get a reduced value and function gets the ----- result = alpha * activationfunc() func (t XtraKerns) LeakyBackwardAlphaFP16() string { return "LeakyBackwardAlphaFP16" } //LeakyForwardAlphaBeta activation function Relu but negatives get a reduced value and function gets the ----- result = alpha * currentresult + beta * previousresult func (t XtraKerns) LeakyForwardAlphaBeta() string { return "LeakyForwardAlphaBeta" } //LeakyForwardAlphaBetaFP16 activation function Relu but negatives get a reduced value and function gets the ----- result = alpha * currentresult + beta * previousresult func (t XtraKerns) LeakyForwardAlphaBetaFP16() string { return "LeakyForwardAlphaBetaFP16" } //LeakyBackwardAlphaBeta activation function Relu but negatives get a reduced value and function gets the ----- result = alpha * currentresult + beta * previousresult func (t XtraKerns) LeakyBackwardAlphaBeta() string { return "LeakyBackwardAlphaBeta" } //LeakyBackwardAlphaBetaFP16 activation function Relu but negatives get a reduced value and function gets the ----- result = alpha * currentresult + beta * previousresult func (t XtraKerns) LeakyBackwardAlphaBetaFP16() string { return "LeakyBackwardAlphaBetaFP16" } //AdaDelta .. func (t XtraKerns) AdaDelta() string { return "AdaDelta" } //AdaDeltaFP16 .. func (t XtraKerns) AdaDeltaFP16() string { return "AdaDeltaFP16" } //AdaGrad .. func (t XtraKerns) AdaGrad() string { return "AdaGrad" } //AdaGradFP16 .. func (t XtraKerns) AdaGradFP16() string { return "AdaGradFP16" } //Adam .. func (t XtraKerns) Adam() string { return "Adam" } //AdamFP16 .. func (t XtraKerns) AdamFP16() string { return "AdamFP16" } /* //Batch Just reduces the values of the gradients by dividing the batch size func (t XtraKerns) Batch() string { return "batchregfloat" } //L1 .. func (t XtraKerns) L1() string { return "l1regularizationfloat" } //L2 .. func (t XtraKerns) L2() string { return "l2regularizationfloat" } */ //L1L2 .. func (t XtraKerns) L1L2() string { return "L1L2" } //L1L2FP16 .. func (t XtraKerns) L1L2FP16() string { return "L1L2FP16" }
kernels/gocudnnxtra.go
0.916666
0.560914
gocudnnxtra.go
starcoder
package math import ( "math/big" ) func Mul(x, y *big.Int) *big.Int { return big.NewInt(0).Mul(x, y) } func Div(x, y *big.Int) *big.Int { return big.NewInt(0).Div(x, y) } func Add(x, y *big.Int) *big.Int { return big.NewInt(0).Add(x, y) } func Sub(x, y *big.Int) *big.Int { return big.NewInt(0).Sub(x, y) } func Neg(x *big.Int) *big.Int { return big.NewInt(0).Neg(x) } func Avg(x *big.Int, y *big.Int) *big.Int { return Div(Add(x, y), big.NewInt(2)) } func ToBigInt(s string) *big.Int { res := big.NewInt(0) res.SetString(s, 10) return res } func Exp(x, y *big.Int) *big.Int { return big.NewInt(0).Exp(x, y, nil) } func BigIntToBigFloat(a *big.Int) *big.Float { b := new(big.Float).SetInt(a) return b } func ToBigFraction(a, b *big.Int) *big.Rat { return big.NewRat(1, 1).SetFrac(a, b) } func DivideToFloat(a, b *big.Int) float64 { res, _ := big.NewRat(1, 1).SetFrac(a, b).Float64() return res } func ToDecimal(value *big.Int) float64 { bigFloatValue := BigIntToBigFloat(value) result := DivFloat(bigFloatValue, big.NewFloat(1e18)) floatValue, _ := result.Float64() return floatValue } func DivFloat(x, y *big.Float) *big.Float { return big.NewFloat(0).Quo(x, y) } func Max(a, b *big.Int) *big.Int { if a.Cmp(b) == 1 { return a } else { return b } } func IsZero(x *big.Int) bool { if x.Cmp(big.NewInt(0)) == 0 { return true } else { return false } } func IsEqual(x, y *big.Int) bool { if x.Cmp(y) == 0 { return true } else { return false } } func IsNotEqual(x, y *big.Int) bool { if x.Cmp(y) != 0 { return true } else { return false } } func IsGreaterThan(x, y *big.Int) bool { if x.Cmp(y) == 1 || x.Cmp(y) == 0 { return true } else { return false } } func IsStrictlyGreaterThan(x, y *big.Int) bool { if x.Cmp(y) == 1 { return true } else { return false } } func IsSmallerThan(x, y *big.Int) bool { if x.Cmp(y) == -1 || x.Cmp(y) == 0 { return true } else { return false } } func IsStrictlySmallerThan(x, y *big.Int) bool { if x.Cmp(y) == -1 { return true } else { return false } } func IsEqualOrGreaterThan(x, y *big.Int) bool { return (IsEqual(x, y) || IsGreaterThan(x, y)) } func IsEqualOrSmallerThan(x, y *big.Int) bool { return (IsEqual(x, y) || IsSmallerThan(x, y)) }
utils/math/big.go
0.75274
0.630884
big.go
starcoder
package gokalman import ( "fmt" "math" "github.com/gonum/matrix/mat64" ) // NewInformation returns a new Information KF. To get the next estimate, call // Update() with the next measurement and the control vector. This will return a // new InformationEstimate which contains everything of this step and an error if any. // Parameters: // - i0: initial information state (usually a zero vector) // - I0: initial information matrix (usually a zero matrix) // - F: state update matrix // - G: control matrix (if all zeros, then control vector will not be used) // - H: measurement update matrix // - noise: Noise func NewInformation(i0 *mat64.Vector, I0 mat64.Symmetric, F, G, H mat64.Matrix, noise Noise) (*Information, *InformationEstimate, error) { // Let's check the dimensions of everything here to panic ASAP. if err := checkMatDims(i0, I0, "i0", "I0", rows2cols); err != nil { return nil, nil, err } if err := checkMatDims(F, I0, "F", "I0", rows2cols); err != nil { return nil, nil, err } if err := checkMatDims(H, i0, "H", "i0", cols2rows); err != nil { return nil, nil, err } // Populate with the initial values. rowsH, _ := H.Dims() Ir, _ := I0.Dims() I0Pred := mat64.NewSymDense(Ir, nil) est0 := NewInformationEstimate(i0, mat64.NewVector(rowsH, nil), I0, I0Pred) var Finv mat64.Dense if err := Finv.Inverse(mat64.DenseCopyOf(F)); err != nil { fmt.Printf("F *might* not invertible: %s\n", err) } var Qinv mat64.Dense if err := Qinv.Inverse(mat64.DenseCopyOf(noise.ProcessMatrix())); err != nil { fmt.Printf("Q *might* not invertible: %s\n", err) } var Rinv mat64.Dense if err := Rinv.Inverse(mat64.DenseCopyOf(noise.MeasurementMatrix())); err != nil { fmt.Printf("R *might* not invertible: %s\n", err) } return &Information{&Finv, G, H, &Qinv, &Rinv, noise, !IsNil(G), est0, est0, 0}, &est0, nil } // NewInformationFromState returns a new Information KF. To get the next estimate, call // Update() with the next measurement and the control vector. This will return a // new InformationEstimate which contains everything of this step and an error if any. // Parameters: // - i0: initial information state (usually a zero vector) // - I0: initial information matrix (usually a zero matrix) // - F: state update matrix // - G: control matrix (if all zeros, then control vector will not be used) // - H: measurement update matrix // - noise: Noise func NewInformationFromState(x0 *mat64.Vector, P0 mat64.Symmetric, F, G, H mat64.Matrix, noise Noise) (*Information, *InformationEstimate, error) { var I0 *mat64.SymDense var I0temp mat64.Dense if err := I0temp.Inverse(P0); err != nil { rI, _ := P0.Dims() I0 = mat64.NewSymDense(rI, nil) fmt.Printf("gokalman: initial covariance not invertible, using nil matrix: %s\n", err) } else { I0, _ = AsSymDense(&I0temp) } var i0 mat64.Vector i0.MulVec(I0, x0) return NewInformation(&i0, I0, F, G, H, noise) } // Information defines a vanilla kalman filter. Use NewVanilla to initialize. type Information struct { Finv mat64.Matrix G mat64.Matrix H mat64.Matrix Qinv mat64.Matrix Rinv mat64.Matrix Noise Noise needCtrl bool prevEst, initEst InformationEstimate step int } func (kf *Information) String() string { return fmt.Sprintf("inv(F)=%v\nG=%v\nH=%v\n%s", mat64.Formatted(kf.Finv, mat64.Prefix(" ")), mat64.Formatted(kf.G, mat64.Prefix(" ")), mat64.Formatted(kf.H, mat64.Prefix(" ")), kf.Noise) } // GetStateTransition returns the F matrix. // *WARNING:* Returns the *INVERSE* of F for the information filter. func (kf *Information) GetStateTransition() mat64.Matrix { return kf.Finv } // GetInputControl returns the G matrix. func (kf *Information) GetInputControl() mat64.Matrix { return kf.G } // GetMeasurementMatrix returns the H matrix. func (kf *Information) GetMeasurementMatrix() mat64.Matrix { return kf.H } // SetStateTransition updates the F matrix. func (kf *Information) SetStateTransition(F mat64.Matrix) { var Finv mat64.Dense if err := Finv.Inverse(mat64.DenseCopyOf(F)); err != nil { fmt.Printf("F *might* not invertible: %s\n", err) } kf.Finv = &Finv } // SetInputControl updates the G matrix. func (kf *Information) SetInputControl(G mat64.Matrix) { kf.G = G } // SetMeasurementMatrix updates the H matrix. func (kf *Information) SetMeasurementMatrix(H mat64.Matrix) { kf.H = H } // SetNoise updates the Noise. func (kf *Information) SetNoise(n Noise) { kf.Noise = n } // GetNoise updates the F matrix. func (kf *Information) GetNoise() Noise { return kf.Noise } // Reset reinitializes the KF with its initial estimate. func (kf *Information) Reset() { kf.prevEst = kf.initEst kf.step = 0 kf.Noise.Reset() } // Update implements the KalmanFilter interface. func (kf *Information) Update(measurement, control *mat64.Vector) (est Estimate, err error) { if err = checkMatDims(control, kf.G, "control (u)", "G", rows2cols); kf.needCtrl && err != nil { return nil, err } if err = checkMatDims(measurement, kf.H, "measurement (y)", "H", rows2rows); err != nil { return nil, err } // zMat computation var zk mat64.Dense zk.Mul(kf.prevEst.infoMat, kf.Finv) zk.Mul(kf.Finv.T(), &zk) // Prediction step. // \hat{i}_{k+1}^{-} var zkzkqi mat64.Dense zkzkqi.Add(&zk, kf.Qinv) zkzkqi.Inverse(&zkzkqi) zkzkqi.Mul(&zk, &zkzkqi) zkzkqi.Scale(-1.0, &zkzkqi) rzk, _ := zkzkqi.Dims() var iKp1Minus, iKp1Minus1 mat64.Vector iKp1Minus.MulVec(kf.Finv.T(), kf.prevEst.infoState) if kf.needCtrl { iKp1Minus1.MulVec(kf.G, control) iKp1Minus1.MulVec(&zk, &iKp1Minus1) iKp1Minus.AddVec(&iKp1Minus, &iKp1Minus1) } var iKp1MinusM mat64.Dense iKp1MinusM.Add(Identity(rzk), &zkzkqi) iKp1Minus.MulVec(&iKp1MinusM, &iKp1Minus) // I_{k+1}^{-} var Ikp1Minus mat64.Dense Ikp1Minus.Mul(&zkzkqi, zk.T()) Ikp1Minus.Add(&zk, &Ikp1Minus) var ykHat mat64.Vector ykHat.MulVec(kf.H, kf.prevEst.State()) ykHat.AddVec(&ykHat, kf.Noise.Measurement(kf.step)) // Measurement update var HTR mat64.Dense if rR, cR := kf.Rinv.Dims(); rR == 1 && cR == 1 { // Rinv is a scalar and mat64 won't be happy. HTR.Scale(kf.Rinv.At(0, 0), kf.H.T()) } else { HTR.Mul(kf.H.T(), kf.Rinv) } var ikp1Plus mat64.Vector ikp1Plus.MulVec(&HTR, measurement) ikp1Plus.AddVec(&ikp1Plus, &iKp1Minus) // I_{k+1}^{+} var Ikp1Plus mat64.Dense Ikp1Plus.Mul(&HTR, kf.H) Ikp1Plus.Add(&Ikp1Minus, &Ikp1Plus) Ikp1MinusSym, err := AsSymDense(&Ikp1Minus) if err != nil { panic(err) } Ikp1PlusSym, err := AsSymDense(&Ikp1Plus) if err != nil { panic(err) } est = NewInformationEstimate(&ikp1Plus, &ykHat, Ikp1PlusSym, Ikp1MinusSym) kf.prevEst = est.(InformationEstimate) kf.step++ return } // InformationEstimate is the output of each update state of the Information KF. // It implements the Estimate interface. type InformationEstimate struct { infoState, meas *mat64.Vector infoMat, predInfoMat mat64.Symmetric cachedState *mat64.Vector cachedCovar, predCachedCovar mat64.Symmetric } // IsWithinNσ returns whether the estimation is within the 2σ bounds. func (e InformationEstimate) IsWithinNσ(N float64) bool { state := e.State() covar := e.Covariance() for i := 0; i < state.Len(); i++ { nσ := N * math.Sqrt(covar.At(i, i)) if state.At(i, 0) > nσ || state.At(i, 0) < -nσ { return false } } return true } // IsWithin2σ returns whether the estimation is within the 2σ bounds. func (e InformationEstimate) IsWithin2σ() bool { return e.IsWithinNσ(2) } // State implements the Estimate interface. func (e InformationEstimate) State() *mat64.Vector { if e.cachedState == nil { rState, _ := e.infoState.Dims() e.cachedState = mat64.NewVector(rState, nil) e.cachedState.MulVec(e.Covariance(), e.infoState) } return e.cachedState } // Measurement implements the Estimate interface. func (e InformationEstimate) Measurement() *mat64.Vector { return e.meas } // Innovation implements the Estimate interface. func (e InformationEstimate) Innovation() *mat64.Vector { return e.infoState } // Covariance implements the Estimate interface. // *NOTE:* With the IF, one cannot view the covariance matrix until there is enough information. func (e InformationEstimate) Covariance() mat64.Symmetric { if e.cachedCovar == nil { rCovar, _ := e.infoMat.Dims() e.cachedCovar = mat64.NewSymDense(rCovar, nil) infoMat := mat64.DenseCopyOf(e.infoMat) var tmpCovar mat64.Dense err := tmpCovar.Inverse(infoMat) if err != nil { fmt.Printf("gokalman: InformationEstimate: information matrix is not (yet) invertible: %s\n", err) return e.cachedCovar } cachedCovar, _ := AsSymDense(&tmpCovar) e.cachedCovar = cachedCovar } return e.cachedCovar } // PredCovariance implements the Estimate interface. // *NOTE:* With the IF, one cannot view the prediction covariance matrix until there is enough information. func (e InformationEstimate) PredCovariance() mat64.Symmetric { if e.predCachedCovar == nil { rCovar, _ := e.predInfoMat.Dims() e.predCachedCovar = mat64.NewSymDense(rCovar, nil) predInfoMat := mat64.DenseCopyOf(e.predInfoMat) var tmpCovar mat64.Dense err := tmpCovar.Inverse(predInfoMat) if err != nil { fmt.Printf("gokalman: InformationEstimate: prediction information matrix is not (yet) invertible: %s\n", err) return e.predCachedCovar } predCachedCovar, err := AsSymDense(&tmpCovar) if err != nil { fmt.Printf("gokalman: InformationEstimate: prediction covariance matrix: %s\n", err) return e.predCachedCovar } e.predCachedCovar = predCachedCovar } return e.predCachedCovar } func (e InformationEstimate) String() string { state := mat64.Formatted(e.State(), mat64.Prefix(" ")) meas := mat64.Formatted(e.Measurement(), mat64.Prefix(" ")) covar := mat64.Formatted(e.Covariance(), mat64.Prefix(" ")) innov := mat64.Formatted(e.Innovation(), mat64.Prefix(" ")) predp := mat64.Formatted(e.PredCovariance(), mat64.Prefix(" ")) return fmt.Sprintf("{\ns=%v\ny=%v\nP=%v\nP-=%v\ni=%v\n}", state, meas, covar, predp, innov) } // NewInformationEstimate initializes a new InformationEstimate. func NewInformationEstimate(infoState, meas *mat64.Vector, infoMat, predInfoMat mat64.Symmetric) InformationEstimate { return InformationEstimate{infoState, meas, infoMat, predInfoMat, nil, nil, nil} }
information.go
0.781205
0.561876
information.go
starcoder
package mathservice import ( "context" "errors" "github.com/go-kit/kit/metrics" "math" "github.com/go-kit/kit/log" ) // Service describes a service that adds things together. type Service interface { // Divide two integers, a/b Divide(ctx context.Context, a, b float64) (float64, error) // Max two integers, returns the greater value of a and b Max(ctx context.Context, a, b float64) (float64, error) // Min two integers, returns the lesser value of a and b Min(ctx context.Context, a, b float64) (float64, error) // Multiply two integers, a*b Multiply(ctx context.Context, a, b float64) (float64, error) // Pow two integers, a^b Pow(ctx context.Context, a, b float64) (float64, error) // Subtract two integers, a-b Subtract(ctx context.Context, a, b float64) (float64, error) // Sums two integers. a+b Sum(ctx context.Context, a, b float64) (float64, error) } // New returns a basic Service with all of the expected middlewares wired in. func New(duration metrics.Histogram, logger log.Logger) Service { var svc Service { svc = NewBasicService() svc = ObservabilityMiddleware(duration, logger)(svc) } return svc } var ( ErrDivideByZero = errors.New("can't divide by zero") ErrNoMax = errors.New("no maximum value, a and b are the same") ErrNoMin = errors.New("no minimum value, a and b are the same") ) // NewBasicService returns a naïve, stateless implementation of Service. func NewBasicService() Service { return basicService{} } type basicService struct{} func (s basicService) Divide(ctx context.Context, a, b float64) (float64, error) { if b == 0 { return 0, ErrDivideByZero } return a/b, nil } func (s basicService) Max(ctx context.Context, a, b float64) (float64, error) { if a == b { return 0, ErrNoMax } return math.Max(a, b), nil } func (s basicService) Min(ctx context.Context, a, b float64) (float64, error) { if a == b { return 0, ErrNoMin } return math.Min(a, b), nil } func (s basicService) Multiply(ctx context.Context, a, b float64) (float64, error) { return a*b, nil } func (s basicService) Pow(ctx context.Context, a, b float64) (float64, error) { return math.Pow(a, b), nil } func (s basicService) Subtract(ctx context.Context, a, b float64) (float64, error) { return a-b, nil } func (s basicService) Sum(ctx context.Context, a, b float64) (float64, error) { return a + b, nil }
grpc_only/gokit/pkg/mathservice/service.go
0.841142
0.441432
service.go
starcoder
package address import ( "encoding/hex" "fmt" "github.com/alonp99/go-spacemesh/common" "github.com/alonp99/go-spacemesh/crypto/sha3" "math/big" "reflect" ) // Address represents the 20 byte address of an spacemesh account. type Address [common.AddressLength]byte var addressT = reflect.TypeOf(Address{}) // BytesToAddress returns Address with value b. // If b is larger than len(h), b will be cropped from the left. func BytesToAddress(b []byte) Address { var a Address a.SetBytes(b) return a } // BigToAddress returns Address with byte values of b. // If b is larger than len(h), b will be cropped from the left. func BigToAddress(b *big.Int) Address { return BytesToAddress(b.Bytes()) } // HexToAddress returns Address with byte values of s. // If s is larger than len(h), s will be cropped from the left. func HexToAddress(s string) Address { return BytesToAddress(common.FromHex(s)) } // Bytes gets the string representation of the underlying address. func (a Address) Bytes() []byte { return a[:] } // Big converts an address to a big integer. func (a Address) Big() *big.Int { return new(big.Int).SetBytes(a[:]) } // Hash converts an address to a hash by left-padding it with zeros. func (a Address) Hash() common.Hash { return common.BytesToHash(a[:]) } // Hex returns an EIP55-compliant hex string representation of the address. func (a Address) Hex() string { unchecksummed := hex.EncodeToString(a[:]) sha := sha3.NewKeccak256() sha.Write([]byte(unchecksummed)) hash := sha.Sum(nil) result := []byte(unchecksummed) for i := 0; i < len(result); i++ { hashByte := hash[i/2] if i%2 == 0 { hashByte = hashByte >> 4 } else { hashByte &= 0xf } if result[i] > '9' && hashByte > 7 { result[i] -= 32 } } return "0x" + string(result) } // String implements fmt.Stringer. func (a Address) String() string { return a.Hex() } // Format implements fmt.Formatter, forcing the byte slice to be formatted as is, // without going through the stringer interface used for logging. func (a Address) Format(s fmt.State, c rune) { fmt.Fprintf(s, "%"+string(c), a[:]) } // SetBytes sets the address to the value of b. // If b is larger than len(a) it will panic. func (a *Address) SetBytes(b []byte) { if len(b) > len(a) { b = b[len(b)-common.AddressLength:] } copy(a[common.AddressLength-len(b):], b) } /* // MarshalText returns the hex representation of a. func (a Address) MarshalText() ([]byte, error) { return hexutil.Bytes(a[:]).MarshalText() } // UnmarshalText parses a hash in hex syntax. func (a *Address) UnmarshalText(input []byte) error { return hexutil.UnmarshalFixedText("Address", input, a[:]) } // UnmarshalJSON parses a hash in hex syntax. func (a *Address) UnmarshalJSON(input []byte) error { return hexutil.UnmarshalFixedJSON(addressT, input, a[:]) } // Scan implements Scanner for database/sql. func (a *Address) Scan(src interface{}) error { srcB, ok := src.([]byte) if !ok { return fmt.Errorf("can't scan %T into Address", src) } if len(srcB) != AddressLength { return fmt.Errorf("can't scan []byte of len %d into Address, want %d", len(srcB), AddressLength) } copy(a[:], srcB) return nil } */
address/address.go
0.829043
0.485112
address.go
starcoder
package pgn func (b Board) findAttackingRook(pos Position, color Color, check bool) (Position, error) { count := 0 retPos := NoPosition r := pos.GetRank() f := pos.GetFile() for { f-- testPos := PositionFromFileRank(f, r) if b.checkRookColor(testPos, color) && (!check || !b.moveIntoCheck(Move{testPos, pos, NoPiece, ""}, color)) { retPos = testPos count++ break } else if testPos == NoPosition || b.containsPieceAt(testPos) { break } } r = pos.GetRank() f = pos.GetFile() for { f++ testPos := PositionFromFileRank(f, r) if b.checkRookColor(testPos, color) && (!check || !b.moveIntoCheck(Move{testPos, pos, NoPiece, ""}, color)) { retPos = testPos count++ break } else if testPos == NoPosition || b.containsPieceAt(testPos) { break } } r = pos.GetRank() f = pos.GetFile() for { r++ testPos := PositionFromFileRank(f, r) if b.checkRookColor(testPos, color) && (!check || !b.moveIntoCheck(Move{testPos, pos, NoPiece, ""}, color)) { retPos = testPos count++ break } else if testPos == NoPosition || b.containsPieceAt(testPos) { break } } r = pos.GetRank() f = pos.GetFile() for { r-- testPos := PositionFromFileRank(f, r) if b.checkRookColor(testPos, color) && (!check || !b.moveIntoCheck(Move{testPos, pos, NoPiece, ""}, color)) { retPos = testPos count++ break } else if testPos == NoPosition || b.containsPieceAt(testPos) { break } } if count > 1 { return NoPosition, ErrAmbiguousMove } if count == 0 { return NoPosition, ErrAttackerNotFound } return retPos, nil } func (b Board) findAttackingRookFromFile(pos Position, color Color, file File) (Position, error) { count := 0 retPos := NoPosition r := pos.GetRank() f := pos.GetFile() for { f-- testPos := PositionFromFileRank(f, r) if file == f && b.checkRookColor(testPos, color) { retPos = testPos count++ break } else if testPos == NoPosition || b.containsPieceAt(testPos) { break } } r = pos.GetRank() f = pos.GetFile() for { f++ testPos := PositionFromFileRank(f, r) if file == f && b.checkRookColor(testPos, color) { retPos = testPos count++ break } else if testPos == NoPosition || b.containsPieceAt(testPos) { break } } if file == pos.GetFile() { r = pos.GetRank() f = pos.GetFile() for { r++ testPos := PositionFromFileRank(f, r) if b.checkRookColor(testPos, color) { retPos = testPos count++ break } else if testPos == NoPosition || b.containsPieceAt(testPos) { break } } r = pos.GetRank() f = pos.GetFile() for { r-- testPos := PositionFromFileRank(f, r) if b.checkRookColor(testPos, color) { retPos = testPos count++ break } else if testPos == NoPosition || b.containsPieceAt(testPos) { break } } } if count > 1 { return NoPosition, ErrAmbiguousMove } if count == 0 { return NoPosition, ErrAttackerNotFound } return retPos, nil } func (b Board) findAttackingRookFromRank(pos Position, color Color, rank Rank) (Position, error) { count := 0 retPos := NoPosition r := pos.GetRank() f := pos.GetFile() for { r-- testPos := PositionFromFileRank(f, r) if rank == r && b.checkRookColor(testPos, color) { retPos = testPos count++ break } else if testPos == NoPosition || b.containsPieceAt(testPos) { break } } r = pos.GetRank() f = pos.GetFile() for { r++ testPos := PositionFromFileRank(f, r) if rank == r && b.checkRookColor(testPos, color) { retPos = testPos count++ break } else if testPos == NoPosition || b.containsPieceAt(testPos) { break } } if rank == pos.GetRank() { r := pos.GetRank() f := pos.GetFile() for { f-- testPos := PositionFromFileRank(f, r) if b.checkRookColor(testPos, color) { retPos = testPos count++ break } else if testPos == NoPosition || b.containsPieceAt(testPos) { break } } r = pos.GetRank() f = pos.GetFile() for { f++ testPos := PositionFromFileRank(f, r) if b.checkRookColor(testPos, color) { retPos = testPos count++ break } else if testPos == NoPosition || b.containsPieceAt(testPos) { break } } } if count > 1 { return NoPosition, ErrAmbiguousMove } if count == 0 { return NoPosition, ErrAttackerNotFound } return retPos, nil } func (b Board) checkRookColor(pos Position, color Color) bool { return (b.GetPiece(pos) == WhiteRook && color == White) || (b.GetPiece(pos) == BlackRook && color == Black) }
board_rook.go
0.512693
0.601125
board_rook.go
starcoder
package glist import ( "sync" ) type Array struct { sync.RWMutex slice []Element concurrent bool } func NewArray() *Array { return &Array{} } func NewArrayConcurrent() *Array { return &Array{concurrent: true} } // Add appends the specified element to the end of this list func (array *Array) Add(e Element) { if array.concurrent { array.Lock() } defer func() { if array.concurrent { array.Unlock() } }() array.slice = append(array.slice, e) } // Appends all of the elements in the specified slice to the end of this list func (array *Array) AddSlice(es []Element) { if array.concurrent { array.Lock() } defer func() { if array.concurrent { array.Unlock() } }() array.slice = append(array.slice, es...) } // Returns true if this list contains the specified element. func (array *Array) Contains(e Element) bool { if array.concurrent { array.RLock() } defer func() { if array.concurrent { array.RUnlock() } }() for i := range array.slice { if array.slice[i] != nil && array.slice[i].Equals(e) { return true } } return false } // Returns the element at the specified position in this list. func (array *Array) Get(index int) Element { if array.concurrent { array.RLock() } defer func() { if array.concurrent { array.RUnlock() } }() l := len(array.slice) if index < 0 || index >= l { return nil } return array.slice[index] } // Returns the index of the first occurrence of the specified element in this list // Or -1 if this list does not contain the element. func (array *Array) IndexOf(e Element) int { if array.concurrent { array.RLock() } defer func() { if array.concurrent { array.RUnlock() } }() for i := range array.slice { if array.slice[i] != nil && array.slice[i].Equals(e) { return i } } return -1 } // Removes the element at the specified position in this list func (array *Array) RemoveIndex(index int) { if array.concurrent { array.Lock() } defer func() { if array.concurrent { array.Unlock() } }() if index < 0 || index > len(array.slice) { return } array.slice = append(array.slice[:index], array.slice[index+1:]...) } // Removes the first occurrence of the specified element from this list, if it is present (optional operation). func (array *Array) Remove(e Element) { if array.concurrent { array.Lock() } defer func() { if array.concurrent { array.Unlock() } }() newSlice := make([]Element, 0, len(array.slice)) for i := range array.slice { if array.slice[i] != nil && array.slice[i].Equals(e) { continue } newSlice = append(newSlice, array.slice[i]) } array.slice = newSlice } // Sorts this list according to the order induced by the specified Comparator. func (array *Array) Sort() { if array.concurrent { array.Lock() } defer func() { if array.concurrent { array.Unlock() } }() // TODO } // Returns true if this list contains no elements. func (array *Array) IsEmpty() bool { if array.concurrent { array.RLock() } defer func() { if array.concurrent { array.RUnlock() } }() if len(array.slice) == 0 { return true } return false } func (array *Array) Len() int { if array.concurrent { array.RLock() } defer func() { if array.concurrent { array.RUnlock() } }() return len(array.slice) } // Removes all of the elements from this list (optional operation). func (array *Array) Clear() { if array.concurrent { array.Lock() } defer func() { if array.concurrent { array.Unlock() } }() array.slice = nil }
go-collection/glist/array.go
0.619126
0.515071
array.go
starcoder
package stack import ( "eslang/core" "fmt" ) // StackValueInt struct  represents an integer value. type StackValueInt struct { value int64 } // NewStackValueInt function  creates a new integer value. func NewStackValueInt(value int64) StackValue { return StackValueInt{ value: value, } } // Type method  returns the type of the value. func (v StackValueInt) Type() core.Type { return core.Int } // Value method  returns the value of the value. func (v StackValueInt) Value() any { return v.value } // TestTruthy method  returns true if the value is truthy. func (v StackValueInt) TestTruthy() (bool, error) { return v.value != 0, nil } // StackValueFloat struct  represents a floating point value. type StackValueFloat struct { value float64 } // NewStackValueFloat function  creates a new floating point value. func NewStackValueFloat(value float64) StackValue { return StackValueFloat{ value: value, } } // Type method  returns the type of the value. func (v StackValueFloat) Type() core.Type { return core.Float } // Value method  returns the value of the value. func (v StackValueFloat) Value() any { return v.value } // TestTruthy method  returns true if the value is truthy. func (v StackValueFloat) TestTruthy() (bool, error) { return v.value != 0, nil } // StackValueString struct  represents a string value. type StackValueString struct { value string } // NewStackValueString function  creates a new string value. func NewStackValueString(value string) StackValue { return StackValueString{ value: value, } } // Type method  returns the type of the value. func (v StackValueString) Type() core.Type { return core.String } // Value method  returns the value of the value. func (v StackValueString) Value() any { return v.value } // TestTruthy method  returns true if the value is truthy. func (v StackValueString) TestTruthy() (bool, error) { return v.value != "", nil } // StackValueBool type StackValueBool struct { value bool } // NewStackValueBool function  creates a new boolean value. func NewStackValueBool(value bool) StackValue { return StackValueBool{ value: value, } } // Type method  return the type of the value. func (v StackValueBool) Type() core.Type { return core.Bool } // Value method  returns a boolean value. func (v StackValueBool) Value() any { return v.value } // TestTruthy method  returns true if the value is truthy. func (v StackValueBool) TestTruthy() (bool, error) { return v.value, nil } // StackValueVar struct  contains a variable value. type StackValueVar struct { value StackValue name string } // NewStackValueVariable function  creates a new variable value. func NewStackValueVariable(name string, value StackValue) StackValueVar { return StackValueVar{ value: value, name: name, } } // Type method  returns the type of the variable value. func (v StackValueVar) Type() core.Type { if v.value == nil { return core.Nil } return v.value.Type() } // Value method  returns the value of the variable. func (v StackValueVar) Value() any { if v.value == nil { return nil } return v.value.Value() } // TestTruthy method  returns true if the value of the variable is truthy. func (v StackValueVar) TestTruthy() (bool, error) { if v.value == nil { return false, fmt.Errorf("variable %s is not defined", v.name) } return v.value.TestTruthy() } // Name method  returns the name of the variable. func (v StackValueVar) Name() string { return v.name }
interpreter/stack/values.go
0.682574
0.558387
values.go
starcoder
package p2019 /** You are given a string s that contains digits 0-9, addition symbols '+', and multiplication symbols '*' only, representing a valid math expression of single digit numbers (e.g., 3+5*2). This expression was given to n elementary school students. The students were instructed to get the answer of the expression by following this order of operations: Compute multiplication, reading from left to right; Then, Compute addition, reading from left to right. You are given an integer array answers of length n, which are the submitted answers of the students in no particular order. You are asked to grade the answers, by following these rules: If an answer equals the correct answer of the expression, this student will be rewarded 5 points; Otherwise, if the answer could be interpreted as if the student used the incorrect order of operations, once or multiple times, this student will be rewarded 2 points; Otherwise, this student will be rewarded 0 points. Return the sum of the points of the students. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/the-score-of-students-solving-math-expression */ func scoreOfStudents(s string, answers []int) int { l := len(s) h := (l + 1) / 2 // every num will company by a ( or ), // a+b*c => ((a+b)*c) or (a+(b*c)) or (a)+((b)*c) good := calc(s) dp := make([][]map[int]bool, h) for i := 0; i < h; i++ { dp[i] = make([]map[int]bool, h) for j := 0; j < h; j++ { dp[i][j] = make(map[int]bool) } dp[i][i][int(s[2*i]-'0')] = true } for l := 2; l <= h; l++ { for i := 0; i+l <= h; i++ { j := i + l - 1 // dp[i][j] for k := i; k < j; k++ { // dp[i][k] * dp[k+1][j] op := s[2*k+1] for x := range dp[i][k] { for y := range dp[k+1][j] { z := x + y if op == '*' { z = x * y } if z <= 1000 { dp[i][j][z] = true } } } } } } var res int cnt := make([]int, 1001) for _, cur := range answers { cnt[cur]++ } for k, v := range cnt { if k == good { res += 5 * v } else if dp[0][h-1][k] { res += 2 * v } } return res } func calc(s string) int { n := len(s) correct := 0 for i := 0; i < n; { mul := int(s[i] & 15) for i += 2; i < n && s[i-1] == '*'; i += 2 { mul *= int(s[i] & 15) } correct += mul } return correct }
src/leetcode/set1000/set2000/set2000/set2010/p2019/solution.go
0.841207
0.6937
solution.go
starcoder
package chunks import ( "fmt" "io" "github.com/attic-labs/noms/go/hash" ) // ChunkStore is the core storage abstraction in noms. We can put data anyplace we have a ChunkStore implementation for. type ChunkStore interface { ChunkSource ChunkSink RootTracker } // Factory allows the creation of namespaced ChunkStore instances. The details of how namespaces are separated is left up to the particular implementation of Factory and ChunkStore. type Factory interface { CreateStore(ns string) ChunkStore // Shutter shuts down the factory. Subsequent calls to CreateStore() will fail. Shutter() } // RootTracker allows querying and management of the root of an entire tree of references. The "root" is the single mutable variable in a ChunkStore. It can store any hash, but it is typically used by higher layers (such as Database) to store a hash to a value that represents the current state and entire history of a database. type RootTracker interface { Root() hash.Hash UpdateRoot(current, last hash.Hash) bool } // ChunkSource is a place to get chunks from. type ChunkSource interface { // Get the Chunk for the value of the hash in the store. If the hash is absent from the store nil is returned. Get(h hash.Hash) Chunk // Returns true iff the value at the address |h| is contained in the source Has(h hash.Hash) bool // Returns the NomsVersion with which this ChunkSource is compatible. Version() string } // ChunkSink is a place to put chunks. type ChunkSink interface { // Put writes c into the ChunkSink, blocking until the operation is complete. Put(c Chunk) // PutMany tries to write chunks into the sink. It will block as it handles as many as possible, then return a BackpressureError containing the rest (if any). PutMany(chunks []Chunk) BackpressureError io.Closer } // BackpressureError is a slice of hash.Hash that indicates some chunks could not be Put(). Caller is free to try to Put them again later. type BackpressureError hash.HashSlice func (b BackpressureError) Error() string { return fmt.Sprintf("Tried to Put %d too many Chunks", len(b)) } func (b BackpressureError) AsHashes() hash.HashSlice { return hash.HashSlice(b) }
go/chunks/chunk_store.go
0.748076
0.563138
chunk_store.go
starcoder
package crf import ( "fmt" "math" "math/rand" "strings" ) // Label is a label applied to a word in a sentence type Label string // FeatureFunction is a feature function for linear-chain CRF type FeatureFunction func(s []string, i int, labelCurr Label, labelPrev Label) bool // Feature includes the weight and feature function for a CRF feature type Feature struct { Weight float64 Value FeatureFunction } // EvaluateFeature evalutes the score of a given labeling using the feature function func (f *Feature) EvaluateFeature(s []string, labeling *SentenceLabeling) float64 { score := float64(0) if len(s) != len(labeling.Labels) { panic(fmt.Sprintf("Misaligned labels for \"%v\" labeled with \"%v\"\n", s, labeling.Labels)) } for i := range s { var val bool if i == 0 { val = f.Value(s, i, labeling.Labels[i], "") } else { val = f.Value(s, i, labeling.Labels[i], labeling.Labels[i-1]) } if val { score += f.Weight } } return score } // SentenceLabeling is a specific order of labels for a sentence type SentenceLabeling struct { Labels []Label Score float64 Probability float64 } // Sentence is a sentence to be processed using CRF type Sentence struct { Words []string Labeling SentenceLabeling } // MakeSentence makes a new Sentence with the given sentence and features func MakeSentence(sentence string) *Sentence { return &Sentence{Words: removeEmptyString(strings.Split(sentence, " "))} } // ScoreLabeling determines the score of a given labeling of the sentence func (s *Sentence) ScoreLabeling(labeling *SentenceLabeling, features []Feature) float64 { score := float64(0) for _, feature := range features { score += feature.EvaluateFeature(s.Words, labeling) } return math.Exp(score) } func recursivelyLabelWord(words []string, allLabels []Label, appliedLabels []Label) []SentenceLabeling { var result []SentenceLabeling if len(words) == len(appliedLabels) { result = append(result, SentenceLabeling{Labels: appliedLabels}) return result } for _, label := range allLabels { restLabels := append(appliedLabels, label) subResult := recursivelyLabelWord(words, allLabels, restLabels) for _, r := range subResult { result = append(result, r) } } return result } func getAllPossibleLabelings(words []string, labels []Label) []SentenceLabeling { var result []SentenceLabeling for _, label := range labels { restLabels := []Label{label} subResult := recursivelyLabelWord(words, labels, restLabels) for _, r := range subResult { result = append(result, r) } } return result } func (s *Sentence) scoreAllLabelings(features []Feature, labels []Label) []SentenceLabeling { labelings := getAllPossibleLabelings(s.Words, labels) for i := range labelings { labelings[i].Score = s.ScoreLabeling(&labelings[i], features) } return labelings } func calculateNormalizationConstant(labelings []SentenceLabeling) float64 { sum := float64(0) for _, labeling := range labelings { sum += labeling.Score } return sum } func (s *Sentence) calculateLabelProbabilities(features []Feature, labels []Label) []SentenceLabeling { labelings := s.scoreAllLabelings(features, labels) normalizationConstant := calculateNormalizationConstant(labelings) for i := range labelings { labelings[i].Probability = labelings[i].Score / normalizationConstant } return labelings } // CalculateBestLabeling determines the best labeling of the sentence func (s *Sentence) CalculateBestLabeling(features []Feature, labels []Label) { labelings := s.calculateLabelProbabilities(features, labels) currentBestLabel := labelings[0] for _, labeling := range labelings { if labeling.Probability > currentBestLabel.Probability { currentBestLabel = labeling } } s.Labeling = currentBestLabel } // LearnWeights attempts to learn the weight to use for each of the given feature functions // using the provided labels and training data func LearnWeights(features []Feature, labels []Label, trainingData []Sentence) { randomWeights := getRandomWeights(len(features)) // assign random weights to each feature function for i := 0; i < len(features); i++ { features[i].Weight = randomWeights[i] } // loop through all of the training sentences for i := 0; i < len(trainingData); i++ { fmt.Printf("Analyzing sentence: %v\n", trainingData[i].Words) const threshold = float64(0.01) const learningRate = float64(1) lastChange := float64(1) // keep moving the weights until they coalesce on a value for lastChange > threshold { possibleLabelings := getAllPossibleLabelings(trainingData[i].Words, labels) // loop through each feature function and calculate the difference between the contribution // of the feature function for the correct labeling and the contribution of the feature function // given the current model for j := 0; j < len(features); j++ { trueValue := features[j].EvaluateFeature(trainingData[i].Words, &trainingData[i].Labeling) expectedContribution := float64(0) for k := 0; k < len(possibleLabelings); k++ { expectedContribution += possibleLabelings[k].Probability * features[j].EvaluateFeature(trainingData[i].Words, &possibleLabelings[k]) } // calculate gradient of the log probability of the training example gradProb := trueValue - expectedContribution lastChange = learningRate * gradProb features[j].Weight += lastChange } } } } func getRandomWeights(num int) []float64 { randomNumbers := make([]float64, num) sum := float64(0) for i := 0; i < num; i++ { randomNumbers[i] = rand.Float64() sum += randomNumbers[i] } for i := 0; i < num; i++ { randomNumbers[i] = randomNumbers[i] / sum } return randomNumbers } func removeEmptyString(arr []string) []string { if arr == nil { return arr } result := make([]string, 0) for i := 0; i < len(arr); i++ { if arr[i] != "" { result = append(result, arr[i]) } } return result }
crf/crf.go
0.7324
0.57827
crf.go
starcoder
package gem import ( "fmt" "regexp" "strings" "golang.org/x/xerrors" ) var ( constraintOperators = map[string]operatorFunc{ "": constraintEqual, "=": constraintEqual, "==": constraintEqual, "!=": constraintNotEqual, ">": constraintGreaterThan, "<": constraintLessThan, ">=": constraintGreaterThanEqual, "=>": constraintGreaterThanEqual, "<=": constraintLessThanEqual, "=<": constraintLessThanEqual, "~>": constraintPessimistic, } constraintRegexp *regexp.Regexp validConstraintRegexp *regexp.Regexp ) type operatorFunc func(v, c Version) bool func init() { ops := make([]string, 0, len(constraintOperators)) for k := range constraintOperators { ops = append(ops, regexp.QuoteMeta(k)) } constraintRegexp = regexp.MustCompile(fmt.Sprintf( `(%s)\s*(%s)`, strings.Join(ops, "|"), versionPattern)) validConstraintRegexp = regexp.MustCompile(fmt.Sprintf( `^\s*(\s*(%s)\s*(%s)\s*\,?)*\s*$`, strings.Join(ops, "|"), versionPattern)) } // Constraints is one or more constraint that a version can be checked against. type Constraints [][]constraint type constraint struct { version Version operator operatorFunc original string } // NewConstraints parses a given constraint and returns a new instance of Constraints func NewConstraints(v string) (Constraints, error) { var css [][]constraint for _, vv := range strings.Split(v, "||") { // Validate the segment if !validConstraintRegexp.MatchString(vv) { return Constraints{}, xerrors.Errorf("improper constraint: %s", vv) } ss := constraintRegexp.FindAllString(vv, -1) if ss == nil { ss = append(ss, strings.TrimSpace(vv)) } var cs []constraint for _, single := range ss { c, err := newConstraint(single) if err != nil { return Constraints{}, err } cs = append(cs, c) } css = append(css, cs) } return css, nil } func newConstraint(c string) (constraint, error) { m := constraintRegexp.FindStringSubmatch(c) if m == nil { return constraint{}, xerrors.Errorf("improper constraint: %s", c) } v, err := NewVersion(m[2]) if err != nil { return constraint{}, xerrors.Errorf("version parse error (%s): %w", m[2], err) } return constraint{ version: v, operator: constraintOperators[m[1]], original: c, }, nil } func (c constraint) check(v Version) bool { return c.operator(v, c.version) } func (c constraint) String() string { return c.original } // Check tests if a version satisfies all the constraints. func (cs Constraints) Check(v Version) bool { for _, c := range cs { if andCheck(v, c) { return true } } return false } // Returns the string format of the constraints func (cs Constraints) String() string { var csStr []string for _, orC := range cs { var cstr []string for _, andC := range orC { cstr = append(cstr, andC.String()) } csStr = append(csStr, strings.Join(cstr, ",")) } return strings.Join(csStr, "||") } func andCheck(v Version, constraints []constraint) bool { for _, c := range constraints { if !c.check(v) { return false } } return true } //------------------------------------------------------------------- // Constraint functions //------------------------------------------------------------------- func constraintEqual(v, c Version) bool { return v.Equal(c) } func constraintNotEqual(v, c Version) bool { return !v.Equal(c) } func constraintGreaterThan(v, c Version) bool { return v.GreaterThan(c) } func constraintLessThan(v, c Version) bool { return v.LessThan(c) } func constraintGreaterThanEqual(v, c Version) bool { return v.GreaterThanOrEqual(c) } func constraintLessThanEqual(v, c Version) bool { return v.LessThanOrEqual(c) } func constraintPessimistic(v, c Version) bool { return v.GreaterThanOrEqual(c) && v.Release().LessThan(c.Bump()) }
vendor/github.com/aquasecurity/go-gem-version/constraint.go
0.744378
0.410343
constraint.go
starcoder
package create import ( "encoding/json" "testing" "github.com/infracloudio/botkube/pkg/config" "github.com/infracloudio/botkube/pkg/notify" "github.com/infracloudio/botkube/pkg/utils" "github.com/infracloudio/botkube/test/e2e/env" testutils "github.com/infracloudio/botkube/test/e2e/utils" "github.com/nlopes/slack" "github.com/stretchr/testify/assert" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) type context struct { *env.TestEnv } // Test if BotKube sends notification when a resource is created func (c *context) testCreateResource(t *testing.T) { // Test cases tests := map[string]testutils.CreateObjects{ "create pod in configured namespace": { Kind: "pod", Namespace: "test", Specs: &v1.Pod{ObjectMeta: metav1.ObjectMeta{Name: "test-pod"}}, ExpectedSlackMessage: testutils.SlackMessage{ Attachments: []slack.Attachment{{Color: "good", Title: "Pod Created", Fields: []slack.AttachmentField{{Value: "Pod *test/test-pod* has been created in *test-cluster-1* cluster\n```\nRecommendations:\n- pod 'test-pod' creation without labels should be avoided.\n```", Short: false}}, Footer: "BotKube"}}, }, ExpectedWebhookPayload: testutils.WebhookPayload{ EventMeta: notify.EventMeta{Kind: "Pod", Name: "test-pod", Namespace: "test", Cluster: "test-cluster-1"}, EventStatus: notify.EventStatus{Type: "create", Level: "info", Reason: "", Error: ""}, Summary: "Pod *test/test-pod* has been created in *test-cluster-1* cluster\n```\nRecommendations:\n- pod 'test-pod' creation without labels should be avoided.\n```", }, }, "create service in configured namespace": { Kind: "service", Namespace: "test", Specs: &v1.Service{ObjectMeta: metav1.ObjectMeta{Name: "test-service"}}, ExpectedSlackMessage: testutils.SlackMessage{ Attachments: []slack.Attachment{{Color: "good", Title: "Service Created", Fields: []slack.AttachmentField{{Value: "Service *test/test-service* has been created in *test-cluster-1* cluster\n", Short: false}}, Footer: "BotKube"}}, }, ExpectedWebhookPayload: testutils.WebhookPayload{ EventMeta: notify.EventMeta{Kind: "Service", Name: "test-service", Namespace: "test", Cluster: "test-cluster-1"}, EventStatus: notify.EventStatus{Type: "create", Level: "info", Reason: "", Error: ""}, Summary: "Service *test/test-service* has been created in *test-cluster-1* cluster\n", }, }, "create a namespace": { Kind: "namespace", Specs: &v1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "test-namespace"}}, ExpectedSlackMessage: testutils.SlackMessage{ Attachments: []slack.Attachment{{Color: "good", Title: "Namespace Created", Fields: []slack.AttachmentField{{Value: "Namespace *test-namespace* has been created in *test-cluster-1* cluster\n", Short: false}}, Footer: "BotKube"}}, }, ExpectedWebhookPayload: testutils.WebhookPayload{ EventMeta: notify.EventMeta{Kind: "Namespace", Name: "test-namespace", Namespace: "", Cluster: "test-cluster-1"}, EventStatus: notify.EventStatus{Type: "create", Level: "info", Reason: "", Error: ""}, Summary: "Namespace *test-namespace* has been created in *test-cluster-1* cluster\n", }, }, } for name, test := range tests { t.Run(name, func(t *testing.T) { // Inject an event into the fake client. testutils.CreateResource(t, test) if c.TestEnv.Config.Communications.Slack.Enabled { // Get last seen slack message lastSeenMsg := c.GetLastSeenSlackMessage() // Convert text message into Slack message structure m := slack.Message{} err := json.Unmarshal([]byte(*lastSeenMsg), &m) assert.NoError(t, err, "message should decode properly") assert.Equal(t, c.Config.Communications.Slack.Channel, m.Channel) assert.Equal(t, test.ExpectedSlackMessage.Attachments, m.Attachments) } if c.TestEnv.Config.Communications.Webhook.Enabled { // Get last seen webhook payload lastSeenPayload := c.GetLastReceivedPayload() assert.Equal(t, test.ExpectedWebhookPayload.EventMeta, lastSeenPayload.EventMeta) assert.Equal(t, test.ExpectedWebhookPayload.EventStatus, lastSeenPayload.EventStatus) assert.Equal(t, test.ExpectedWebhookPayload.Summary, lastSeenPayload.Summary) } isAllowed := utils.AllowedEventKindsMap[utils.EventKind{Resource: test.Kind, Namespace: "all", EventType: config.CreateEvent}] || utils.AllowedEventKindsMap[utils.EventKind{Resource: test.Kind, Namespace: test.Namespace, EventType: config.CreateEvent}] assert.Equal(t, isAllowed, true) }) } } // Run tests func (c *context) Run(t *testing.T) { t.Run("create resource", c.testCreateResource) } // E2ETests runs create notification tests func E2ETests(testEnv *env.TestEnv) env.E2ETest { return &context{ testEnv, } }
test/e2e/notifier/create/create.go
0.561455
0.658822
create.go
starcoder
package input import ( "github.com/Jeffail/benthos/v3/internal/docs" "github.com/Jeffail/benthos/v3/lib/input/reader" "github.com/Jeffail/benthos/v3/lib/log" "github.com/Jeffail/benthos/v3/lib/metrics" "github.com/Jeffail/benthos/v3/lib/types" "github.com/Jeffail/benthos/v3/lib/util/aws/session" ) //------------------------------------------------------------------------------ func init() { Constructors[TypeS3] = TypeSpec{ constructor: fromSimpleConstructor(NewAmazonS3), Summary: ` Downloads objects within an Amazon S3 bucket, optionally filtered by a prefix. If an SQS queue has been configured then only object keys read from the queue will be downloaded.`, Description: ` ## Alternatives This input is being replaced with the shiny new ` + "[`aws_s3` input](/docs/components/inputs/aws_s3)" + `, which has improved features, consider trying it out instead. If an SQS queue is not specified the entire list of objects found when this input starts will be consumed. Note that the prefix configuration is only used when downloading objects without SQS configured. If your bucket is configured to send events directly to an SQS queue then you need to set the ` + "`sqs_body_path`" + ` field to a [dot path](/docs/configuration/field_paths) where the object key is found in the payload. However, it is also common practice to send bucket events to an SNS topic which sends enveloped events to SQS, in which case you must also set the ` + "`sqs_envelope_path`" + ` field to where the payload can be found. When using SQS events it's also possible to extract target bucket names from the events by specifying a path in the field ` + "`sqs_bucket_path`" + `. For each SQS event, if that path exists and contains a string it will used as the bucket of the download instead of the ` + "`bucket`" + ` field. Here is a guide for setting up an SQS queue that receives events for new S3 bucket objects: https://docs.aws.amazon.com/AmazonS3/latest/dev/ways-to-add-notification-config-to-bucket.html WARNING: When using SQS please make sure you have sensible values for ` + "`sqs_max_messages`" + ` and also the visibility timeout of the queue itself. When Benthos consumes an S3 item as a result of receiving an SQS message the message is not deleted until the S3 item has been sent onwards. This ensures at-least-once crash resiliency, but also means that if the S3 item takes longer to process than the visibility timeout of your queue then the same items might be processed multiple times. ### Credentials By default Benthos will use a shared credentials file when connecting to AWS services. It's also possible to set them explicitly at the component level, allowing you to transfer data across accounts. You can find out more [in this document](/docs/guides/aws). ### Metadata This input adds the following metadata fields to each message: ` + "```" + ` - s3_key - s3_bucket - s3_last_modified_unix* - s3_last_modified (RFC3339)* - s3_content_type* - s3_content_encoding* - All user defined metadata* * Only added when NOT using download manager ` + "```" + ` You can access these metadata fields using [function interpolation](/docs/configuration/interpolation#metadata).`, FieldSpecs: append( append(docs.FieldSpecs{ docs.FieldCommon("bucket", "The bucket to consume from. If `sqs_bucket_path` is set this field is still required as a fallback."), docs.FieldCommon("prefix", "An optional path prefix, if set only objects with the prefix are consumed. This field is ignored when SQS is used."), docs.FieldCommon("sqs_url", "An optional SQS URL to connect to. When specified this queue will control which objects are downloaded from the target bucket."), docs.FieldCommon("sqs_body_path", "A [dot path](/docs/configuration/field_paths) whereby object keys are found in SQS messages, this field is only required when an `sqs_url` is specified."), docs.FieldCommon("sqs_bucket_path", "An optional [dot path](/docs/configuration/field_paths) whereby the bucket of an object can be found in consumed SQS messages."), docs.FieldCommon("sqs_envelope_path", "An optional [dot path](/docs/configuration/field_paths) of enveloped payloads to extract from SQS messages. This is required when pushing events from S3 to SNS to SQS."), docs.FieldAdvanced("sqs_max_messages", "The maximum number of SQS messages to consume from each request."), docs.FieldAdvanced("sqs_endpoint", "A custom endpoint to use when connecting to SQS."), }, session.FieldSpecs()...), docs.FieldAdvanced("retries", "The maximum number of times to attempt an object download."), docs.FieldAdvanced("force_path_style_urls", "Forces the client API to use path style URLs, which helps when connecting to custom endpoints."), docs.FieldAdvanced("delete_objects", "Whether to delete downloaded objects from the bucket."), docs.FieldAdvanced("download_manager", "Controls if and how to use the download manager API. This can help speed up file downloads, but results in file metadata not being copied.").WithChildren( docs.FieldCommon("enabled", "Whether to use to download manager API."), ), docs.FieldAdvanced("timeout", "The period of time to wait before abandoning a request and trying again."), docs.FieldDeprecated("max_batch_count"), ), Categories: []Category{ CategoryServices, CategoryAWS, }, } } //------------------------------------------------------------------------------ // NewAmazonS3 creates a new AWS S3 input type. func NewAmazonS3(conf Config, mgr types.Manager, log log.Modular, stats metrics.Type) (Type, error) { // TODO: V4 Remove this. if conf.S3.MaxBatchCount > 1 { log.Warnf("Field '%v.max_batch_count' is deprecated, use the batching methods outlined in https://benthos.dev/docs/configuration/batching instead.\n", conf.Type) } r, err := reader.NewAmazonS3(conf.S3, log, stats) if err != nil { return nil, err } return NewAsyncReader( TypeS3, true, reader.NewAsyncBundleUnacks( reader.NewAsyncPreserver(r), ), log, stats, ) } //------------------------------------------------------------------------------
lib/input/s3.go
0.809276
0.752058
s3.go
starcoder
package main import ( "fmt" ecs "github.com/x-hgg-x/goecs/v2" ) func main() { // List of component data types type Shape struct{ shape string } type Color struct{ color string } type Name struct{ name string } // Structure for storing components // Several storage types are possible components := struct { Flag *ecs.NullComponent Shape *ecs.SliceComponent Color *ecs.DenseSliceComponent Name *ecs.MapComponent Value *ecs.SliceComponent }{} // Initialize a new manager manager := ecs.NewManager() // Create components components.Flag = manager.NewNullComponent() components.Shape = manager.NewSliceComponent() components.Color = manager.NewDenseSliceComponent() components.Name = manager.NewMapComponent() components.Value = manager.NewSliceComponent() // Create entities manager.NewEntity().AddComponent(components.Shape, &Shape{"square"}).AddComponent(components.Color, &Color{"red"}) manager.NewEntity().AddComponent(components.Shape, &Shape{"circle"}).AddComponent(components.Name, &Name{"tom"}).AddComponent(components.Flag, nil) manager.NewEntity().AddComponent(components.Color, &Color{"blue"}).AddComponent(components.Name, &Name{"john"}) manager.NewEntity(). AddComponent(components.Shape, &Shape{"triangle"}). AddComponent(components.Color, &Color{"green"}). AddComponent(components.Name, &Name{"paul"}). AddComponent(components.Flag, nil) // Loop on entities which have specified components // The Join() method gives a bit.Set tag containing integers which can be converted to entities, // and we use the bit.Set.Visit() method to loop through the set. // The decorator ecs.Visit() is used when we want to iterate through all elements of the set. // It converts each set element to an entity. manager.Join(components.Shape, components.Name).Visit(ecs.Visit(func(entity ecs.Entity) { shape := components.Shape.Get(entity).(*Shape) name := components.Name.Get(entity).(*Name) fmt.Printf("Entity has the shape '%s' and the name '%s'\n", shape.shape, name.name) })) fmt.Println() // If we want to break the loop when some condition is met, we use the Visit() method directly aborted := manager.Join(components.Shape).Visit(func(index int) (skip bool) { shape := components.Shape.Get(ecs.Entity(index)).(*Shape) fmt.Printf("Entity has the shape '%s'\n", shape.shape) if shape.shape == "circle" { shape.shape = "CIRCLE" fmt.Printf("Entity has now the shape '%s'\n", shape.shape) return true } return false }) fmt.Printf("Loop aborted: %v\n\n", aborted) // The helper function ecs.GetFirst() is useful if we want only the first entity matching a tag if firstEntity := ecs.GetFirst(manager.Join(components.Shape, components.Color, components.Name)); firstEntity != nil { shape := components.Shape.Get(*firstEntity).(*Shape) color := components.Color.Get(*firstEntity).(*Color) name := components.Name.Get(*firstEntity).(*Name) fmt.Printf("First matching entity has the shape '%s', the color '%s' and the name '%s'\n", shape.shape, color.color, name.name) } fmt.Println() // The Not() method is used when we want to exclude a particular component manager.Join(components.Flag.Not()).Visit(ecs.Visit(func(entity ecs.Entity) { fmt.Printf("Entity components: ") if entity.HasComponent(components.Shape) { fmt.Printf("Shape: '%s', ", components.Shape.Get(entity).(*Shape).shape) } if entity.HasComponent(components.Color) { fmt.Printf("Color: '%s', ", components.Color.Get(entity).(*Color).color) } if entity.HasComponent(components.Name) { fmt.Printf("Name: '%s'", components.Name.Get(entity).(*Name).name) } fmt.Println() })) fmt.Println() // To iterate through all entities with at least one component, we use the Join() method without any argument manager.Join().Visit(ecs.Visit(func(entity ecs.Entity) { fmt.Printf("Entity components: ") if entity.HasComponent(components.Shape) { fmt.Printf("Shape: '%s', ", components.Shape.Get(entity).(*Shape).shape) } if entity.HasComponent(components.Color) { fmt.Printf("Color: '%s', ", components.Color.Get(entity).(*Color).color) } if entity.HasComponent(components.Name) { fmt.Printf("Name: '%s'", components.Name.Get(entity).(*Name).name) } fmt.Println() })) fmt.Println() // If the component data is not a pointer, we can use the Set() method to change its value manager.NewEntity().AddComponent(components.Value, 3) firstEntity := *ecs.GetFirst(manager.Join(components.Value)) fmt.Println("Old value:", components.Value.Get(firstEntity).(int)) components.Value.Set(firstEntity, 4) fmt.Println("New value:", components.Value.Get(firstEntity).(int)) }
cmd/example/main.go
0.575588
0.401893
main.go
starcoder
package spec // Parameter Locations // There are four possible parameter locations specified by the in field: const ( InPath = "path" // Used together with Path Templating, where the parameter value is actually part of the operation's URL. This does not include the host or base path of the API. For example, in /items/{itemId}, the path parameter is itemId. InQuery = "query" // Parameters that are appended to the URL. For example, in /items?id=###, the query parameter is id. InHeader = "header" // Custom headers that are expected as part of the request. Note that RFC7230 states header names are case insensitive. InCookie = "cookie" // Used to pass a specific cookie value to the API. ) // QueryParam creates a query parameter func QueryParam(name string, schema *Schema) *Parameter { p := &Parameter{} p.In = InQuery p.Name = name p.Schema = schema return p } // HeaderParam creates a header parameter, this is always required by default func HeaderParam(name string, schema *Schema) *Parameter { p := &Parameter{} p.In = InHeader p.Name = name p.Schema = schema return p } // PathParam creates a path parameter, this is always required func PathParam(name string, schema *Schema) *Parameter { p := &Parameter{} p.In = InPath p.Name = name p.Schema = schema p.Required = true return p } // CookieParam creates a path parameter, this is always required func CookieParam(name string, schema *Schema) *Parameter { p := &Parameter{} p.In = InCookie p.Name = name p.Schema = schema return p } // WithDescription sets the description on this response, allows for chaining func (p *Parameter) WithDescription(description string) *Parameter { p.Description = description return p } // WithName a fluent builder method to override the name of the parameter func (p *Parameter) WithName(name string) *Parameter { p.Name = name return p } // WithSchema a fluent builder method to override the schema of the parameter func (p *Parameter) WithSchema(schema *Schema) *Parameter { p.Schema = schema return p } // WithLocation a fluent builder method to override the location of the parameter func (p *Parameter) WithLocation(in string) *Parameter { p.In = in return p } // AllowsEmptyValues flags this parameter as being ok with empty values func (p *Parameter) AllowsEmptyValues() *Parameter { p.AllowEmptyValue = true return p } // NoEmptyValues flags this parameter as not liking empty values func (p *Parameter) NoEmptyValues() *Parameter { p.AllowEmptyValue = false return p } // AsOptional flags this parameter as optional func (p *Parameter) AsOptional() *Parameter { p.Required = false return p }
vendor/github.com/wzshiming/openapi/spec/parameter_util.go
0.762336
0.453927
parameter_util.go
starcoder
package collator // The Collator watches a log file in the Common Log format and sends data // to a listener. import ( "context" "github.com/RobinUS2/golang-moving-average" "github.com/gilramir/monitor-weblog/xojoc/logparse" "github.com/hpcloud/tail" "sort" "strings" "time" ) const ( // How often to report Sites information kSitesTimerDuration = 10 * time.Second // How often to check the moving average of hits, and thus, // how often to check to see if we need to send an alert. This is also // used to send Status objects. kMovingAverageTimerDuration = 1 * time.Second ) // An Alert notifies the listener of high traffic, and also when traffic // returns to a normal level type Alert struct { InAlertState bool AverageHitsPerSecond float64 Time time.Time } // The Sites object lists the # of hits per site, and are sent less often // (every 10 seconds) type Sites struct { Sites []Site } type Site struct { TotalHits int Site string } // These Status objects are sent frequently (one per second) type Status struct { HitsLastSecond int AverageHitsPerSecond float64 // Additional information could be added here in the future } // ByHits implements sort.Interface for []SizeHite, based on the number of hits type ByHits []Site func (a ByHits) Len() int { return len(a) } func (a ByHits) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByHits) Less(i, j int) bool { return a[i].TotalHits < a[j].TotalHits } type Collator struct { ErrorChan chan error SitesChan chan *Sites StatusChan chan *Status AlertChan chan *Alert ResetChan chan bool alertThreshold float64 tailer *tail.Tail accumHits int inAlertedState bool sitesTimer *time.Timer movingAverageTimer *time.Timer hitsMovingAverage *movingaverage.MovingAverage siteHits map[string]int } // Create a new Collator and start running its goroutines. The caller can // stop the Collator by calling the CancelFunc in the passed-in context. func NewAndRun(ctx context.Context, filename string, alertThreshold int) (*Collator, error) { c := &Collator{ ErrorChan: make(chan error, 1), // buffered so anyone can write an error at any time SitesChan: make(chan *Sites), AlertChan: make(chan *Alert), StatusChan: make(chan *Status), ResetChan: make(chan bool), siteHits: make(map[string]int), hitsMovingAverage: movingaverage.New(2 * 60), // 2 minutes, with 1-second windows alertThreshold: float64(alertThreshold), } // Tail the log lineChan := make(chan string) err := c.startTail(ctx, filename, lineChan) if err != nil { return nil, err } // Parse each line entryChan := make(chan *logparse.Entry) go c._parse(ctx, lineChan, entryChan) // And monitor the information go c._collate(ctx, entryChan) return c, nil } func (self *Collator) _collate(ctx context.Context, entryChan <-chan *logparse.Entry) { defer self.tailer.Stop() // this will ignore a possible error, but that's ok defer close(self.ErrorChan) defer close(self.SitesChan) defer close(self.AlertChan) defer close(self.StatusChan) self.sitesTimer = time.NewTimer(kSitesTimerDuration) self.movingAverageTimer = time.NewTimer(kMovingAverageTimerDuration) for { select { // We've been told to stop working case <-ctx.Done(): return // A log entry case entry := <-entryChan: self.recordEntry(entry) self.accumHits++ // Moving Average timer case now := <-self.movingAverageTimer.C: // Calculate the 2-minute moving average self.hitsMovingAverage.Add(float64(self.accumHits)) avg := self.hitsMovingAverage.Avg() // Send the per-second status self.StatusChan <- &Status{ HitsLastSecond: self.accumHits, AverageHitsPerSecond: avg, } self.accumHits = 0 // Need to alert? if self.inAlertedState { if avg < self.alertThreshold { self.AlertChan <- &Alert{false, avg, now} self.inAlertedState = false } } else { if avg > self.alertThreshold { self.AlertChan <- &Alert{true, avg, now} self.inAlertedState = true } } self.movingAverageTimer.Reset(kMovingAverageTimerDuration) // Sitest timer case <-self.sitesTimer.C: self.sendSites() self.sitesTimer.Reset(kSitesTimerDuration) // User requests a reset of counters case <-self.ResetChan: self.siteHits = make(map[string]int) } } } // Given a single log entry, record any useful info from it. func (self *Collator) recordEntry(entry *logparse.Entry) { // Sanity check if len(entry.Request.URL.Path) < 3 || entry.Request.URL.Path[0] != '/' { return } secondSlashIndex := strings.Index(entry.Request.URL.Path[1:], "/") if secondSlashIndex == -1 { // Not present return } // Add 1 to the index because the Index() call was made on a substring starting at position 1 site := entry.Request.URL.Path[:secondSlashIndex+1] _, has := self.siteHits[site] if has { self.siteHits[site]++ } else { self.siteHits[site] = 1 } } // Send a Hit struct to the client func (self *Collator) sendSites() { // Create the slice of Site's sites := make([]Site, len(self.siteHits)) i := 0 for site, totalHits := range self.siteHits { sites[i].Site = site sites[i].TotalHits = totalHits i++ } // Reverse sort them by number of hits per site sort.Sort(sort.Reverse(ByHits(sites))) self.SitesChan <- &Sites{ Sites: sites, } }
collator/collator.go
0.624064
0.46035
collator.go
starcoder
package image import ( "image" "image/color" "sync" "github.com/hajimehoshi/ebiten/v2" ) // A NineSlice is an image that can be drawn with any width and height. It is basically a 3x3 grid of image tiles: // The corner tiles are drawn as-is, while the center columns and rows of tiles will be stretched to fit the desired // width and height. type NineSlice struct { image *ebiten.Image widths [3]int heights [3]int transparent bool init sync.Once tiles [9]*ebiten.Image } // A DrawImageOptionsFunc is responsible for setting DrawImageOptions when drawing an image. // This is usually used to translate the image. type DrawImageOptionsFunc func(opts *ebiten.DrawImageOptions) var colorImages map[color.Color]*ebiten.Image = map[color.Color]*ebiten.Image{} var colorNineSlices map[color.Color]*NineSlice = map[color.Color]*NineSlice{} // NewNineSlice constructs a new NineSlice from i, having columns widths w and row heights h. func NewNineSlice(i *ebiten.Image, w [3]int, h [3]int) *NineSlice { return &NineSlice{ image: i, widths: w, heights: h, } } // NewNineSliceSimple constructs a new NineSlice from image. borderWidthHeight specifies the width of the // left and right column and the height of the top and bottom row. centerWidthHeight specifies the width // of the center column and row. func NewNineSliceSimple(image *ebiten.Image, borderWidthHeight int, centerWidthHeight int) *NineSlice { return &NineSlice{ image: image, widths: [3]int{borderWidthHeight, centerWidthHeight, borderWidthHeight}, heights: [3]int{borderWidthHeight, centerWidthHeight, borderWidthHeight}, } } // NewNineSliceColor constructs a new NineSlice that when drawn fills with color c. func NewNineSliceColor(c color.Color) *NineSlice { if n, ok := colorNineSlices[c]; ok { return n } var n *NineSlice if _, _, _, a := c.RGBA(); a == 0 { n = &NineSlice{ transparent: true, } } else { n = &NineSlice{ image: NewImageColor(c), widths: [3]int{0, 1, 0}, heights: [3]int{0, 1, 0}, } } colorNineSlices[c] = n return n } // NewImageColor constructs a new Image that when drawn fills with color c. func NewImageColor(c color.Color) *ebiten.Image { if i, ok := colorImages[c]; ok { return i } i := ebiten.NewImage(1, 1) i.Fill(c) colorImages[c] = i return i } // Draw draws n onto screen, with the size specified by width and height. If optsFunc is not nil, it is used to set // DrawImageOptions for each tile drawn. func (n *NineSlice) Draw(screen *ebiten.Image, width int, height int, optsFunc DrawImageOptionsFunc) { if n.transparent { return } n.drawTiles(screen, width, height, optsFunc) } func (n *NineSlice) drawTiles(screen *ebiten.Image, width int, height int, optsFunc DrawImageOptionsFunc) { n.init.Do(n.createTiles) sy := 0 ty := 0 for r, sh := range n.heights { sx := 0 tx := 0 var th int if r == 1 { th = height - n.heights[0] - n.heights[2] } else { th = sh } for c, sw := range n.widths { var tw int if c == 1 { tw = width - n.widths[0] - n.widths[2] } else { tw = sw } n.drawTile(screen, n.tiles[r*3+c], tx, ty, sw, sh, tw, th, optsFunc) sx += sw tx += tw } sy += sh ty += th } } func (n *NineSlice) drawTile(screen *ebiten.Image, tile *ebiten.Image, tx int, ty int, sw int, sh int, tw int, th int, optsFunc DrawImageOptionsFunc) { if sw <= 0 || sh <= 0 || tw <= 0 || th <= 0 { return } opts := ebiten.DrawImageOptions{ Filter: ebiten.FilterNearest, } if tw != sw || th != sh { opts.GeoM.Scale(float64(tw)/float64(sw), float64(th)/float64(sh)) } opts.GeoM.Translate(float64(tx), float64(ty)) if optsFunc != nil { optsFunc(&opts) } screen.DrawImage(tile, &opts) } func (n *NineSlice) createTiles() { defer func() { n.image = nil }() n.tiles = [9]*ebiten.Image{} if n.centerOnly() { n.tiles[1*3+1] = n.image return } sy := 0 for r, sh := range n.heights { sx := 0 for c, sw := range n.widths { if sh > 0 && sw > 0 { rect := image.Rect(0, 0, sw, sh) rect = rect.Add(image.Point{sx, sy}) n.tiles[r*3+c] = n.image.SubImage(rect).(*ebiten.Image) } sx += sw } sy += sh } } func (n *NineSlice) centerOnly() bool { if n.widths[0] > 0 || n.widths[2] > 0 || n.heights[0] > 0 || n.heights[2] > 0 { return false } w, h := n.image.Size() return n.widths[1] == w && n.heights[1] == h } // MinSize returns the minimum width and height to draw n correctly. If n is drawn with a smaller size, // the corner or edge tiles will overlap. func (n *NineSlice) MinSize() (int, int) { if n.transparent { return 0, 0 } return n.widths[0] + n.widths[2], n.heights[0] + n.heights[2] }
image/nineslice.go
0.733738
0.524029
nineslice.go
starcoder
package advent import ( "strconv" ) var _ Problem = &binaryDiagnostic{} type binaryDiagnostic struct { dailyProblem } func NewBinaryDiagnostic() Problem { return &binaryDiagnostic{ dailyProblem{ day: 3, }, } } func (b *binaryDiagnostic) Solve() interface{} { input := b.GetInputLines() var results []int results = append(results, b.powerConsumption(input)) results = append(results, b.lifeSupportRating(input)) return results } /* The submarine has been making some odd creaking noises, so you ask it to produce a diagnostic report just in case. The diagnostic report (your puzzle input) consists of a list of binary numbers which, when decoded properly, can tell you many useful things about the conditions of the submarine. The first parameter to check is the power consumption. You need to use the binary numbers in the diagnostic report to generate two new binary numbers (called the gamma rate and the epsilon rate). The power consumption can then be found by multiplying the gamma rate by the epsilon rate. Each bit in the gamma rate can be determined by finding the most common bit in the corresponding position of all numbers in the diagnostic report. For example, given the following diagnostic report: 00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010 Considering only the first bit of each number, there are five 0 bits and seven 1 bits. Since the most common bit is 1, the first bit of the gamma rate is 1. The most common second bit of the numbers in the diagnostic report is 0, so the second bit of the gamma rate is 0. The most common value of the third, fourth, and fifth bits are 1, 1, and 0, respectively, and so the final three bits of the gamma rate are 110. So, the gamma rate is the binary number 10110, or 22 in decimal. The epsilon rate is calculated in a similar way; rather than use the most common bit, the least common bit from each position is used. So, the epsilon rate is 01001, or 9 in decimal. Multiplying the gamma rate (22) by the epsilon rate (9) produces the power consumption, 198. Use the binary numbers in your diagnostic report to calculate the gamma rate and epsilon rate, then multiply them together. What is the power consumption of the submarine? (Be sure to represent your answer in decimal, not binary.) */ func (b *binaryDiagnostic) powerConsumption(input []string) int { mostCommonBits := make(map[int]int) for _, line := range input { for i, bit := range line { if bit == '1' { mostCommonBits[i]++ } } } var gamma int for i := 0; i < len(input[0]); i++ { gamma = gamma << 1 if mostCommonBits[i] > len(input)/2 { gamma = gamma | 1 } } return int(gamma) * (^int(gamma) & 4095) //4095 = 2^12-1 } /* Next, you should verify the life support rating, which can be determined by multiplying the oxygen generator rating by the CO2 scrubber rating. Both the oxygen generator rating and the CO2 scrubber rating are values that can be found in your diagnostic report - finding them is the tricky part. Both values are located using a similar process that involves filtering out values until only one remains. Before searching for either rating value, start with the full list of binary numbers from your diagnostic report and consider just the first bit of those numbers. Then: Keep only numbers selected by the bit criteria for the type of rating value for which you are searching. Discard numbers which do not match the bit criteria. If you only have one number left, stop; this is the rating value for which you are searching. Otherwise, repeat the process, considering the next bit to the right. The bit criteria depends on which type of rating value you want to find: To find oxygen generator rating, determine the most common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 1 in the position being considered. To find CO2 scrubber rating, determine the least common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 0 in the position being considered. For example, to determine the oxygen generator rating value using the same example diagnostic report from above: Start with all 12 numbers and consider only the first bit of each number. There are more 1 bits (7) than 0 bits (5), so keep only the 7 numbers with a 1 in the first position: 11110, 10110, 10111, 10101, 11100, 10000, and 11001. Then, consider the second bit of the 7 remaining numbers: there are more 0 bits (4) than 1 bits (3), so keep only the 4 numbers with a 0 in the second position: 10110, 10111, 10101, and 10000. In the third position, three of the four numbers have a 1, so keep those three: 10110, 10111, and 10101. In the fourth position, two of the three numbers have a 1, so keep those two: 10110 and 10111. In the fifth position, there are an equal number of 0 bits and 1 bits (one each). So, to find the oxygen generator rating, keep the number with a 1 in that position: 10111. As there is only one number left, stop; the oxygen generator rating is 10111, or 23 in decimal. Then, to determine the CO2 scrubber rating value from the same example above: Start again with all 12 numbers and consider only the first bit of each number. There are fewer 0 bits (5) than 1 bits (7), so keep only the 5 numbers with a 0 in the first position: 00100, 01111, 00111, 00010, and 01010. Then, consider the second bit of the 5 remaining numbers: there are fewer 1 bits (2) than 0 bits (3), so keep only the 2 numbers with a 1 in the second position: 01111 and 01010. In the third position, there are an equal number of 0 bits and 1 bits (one each). So, to find the CO2 scrubber rating, keep the number with a 0 in that position: 01010. As there is only one number left, stop; the CO2 scrubber rating is 01010, or 10 in decimal. Finally, to find the life support rating, multiply the oxygen generator rating (23) by the CO2 scrubber rating (10) to get 230. Use the binary numbers in your diagnostic report to calculate the oxygen generator rating and CO2 scrubber rating, then multiply them together. What is the life support rating of the submarine? (Be sure to represent your answer in decimal, not binary.) */ func (b *binaryDiagnostic) lifeSupportRating(input []string) int { bitlength := len(input[0]) indexMap := func() map[int]*string { stringsByIndex := make(map[int]*string) for i := 0; i < len(input); i++ { stringsByIndex[i] = &input[i] } return stringsByIndex } getDiagnostic := func(isOxygen bool) int { validInputs := indexMap() var i int var line *string var mostCommonBit uint8 //store MCB var lastValid int var oneCount int var bitIndex int for { //find most common bit at bit index for _, line = range validInputs { if (*line)[bitIndex] == '1' { oneCount++ } } if oneCount >= (len(validInputs)+1)/2 { mostCommonBit = '1' } else { mostCommonBit = '0' } //remove all strings that don't have MCB at bit index for i, line = range validInputs { if (isOxygen && (*line)[bitIndex] != mostCommonBit) || (!isOxygen && (*line)[bitIndex] == mostCommonBit) { delete(validInputs, i) } else { lastValid = i } } if len(validInputs) == 1 { oxygen, _ := strconv.ParseInt(*validInputs[lastValid], 2, 32) return int(oxygen) } //move bit index to next bit bitIndex = (bitIndex + 1) % bitlength oneCount = 0 } } oxygen := getDiagnostic(true) cO2 := getDiagnostic(false) return oxygen * cO2 }
internal/advent/day3.go
0.761538
0.681369
day3.go
starcoder
package types import ( "io" "github.com/lyraproj/pcore/px" ) type TypeType struct { typ px.Type } var typeTypeDefault = &TypeType{typ: anyTypeDefault} var TypeMetaType px.ObjectType func init() { TypeMetaType = newObjectType(`Pcore::TypeType`, `Pcore::AnyType { attributes => { type => { type => Optional[Type], value => Any }, } }`, func(ctx px.Context, args []px.Value) px.Value { return newTypeType2(args...) }) newGoConstructor(`Type`, func(d px.Dispatch) { d.Param(`String`) d.Function(func(c px.Context, args []px.Value) px.Value { return c.ParseTypeValue(args[0]) }) }, func(d px.Dispatch) { d.Param2(TypeObjectInitHash) d.Function(func(c px.Context, args []px.Value) px.Value { return MakeObjectType(``, nil, args[0].(px.OrderedMap), false).Resolve(c) }) }) } func DefaultTypeType() *TypeType { return typeTypeDefault } func NewTypeType(containedType px.Type) *TypeType { if containedType == nil || containedType == anyTypeDefault { return DefaultTypeType() } return &TypeType{containedType} } func newTypeType2(args ...px.Value) *TypeType { switch len(args) { case 0: return DefaultTypeType() case 1: if containedType, ok := args[0].(px.Type); ok { return NewTypeType(containedType) } panic(illegalArgumentType(`Type[]`, 0, `Type`, args[0])) default: panic(illegalArgumentCount(`Type[]`, `0 or 1`, len(args))) } } func (t *TypeType) ContainedType() px.Type { return t.typ } func (t *TypeType) Accept(v px.Visitor, g px.Guard) { v(t) t.typ.Accept(v, g) } func (t *TypeType) Default() px.Type { return typeTypeDefault } func (t *TypeType) Equals(o interface{}, g px.Guard) bool { if ot, ok := o.(*TypeType); ok { return t.typ.Equals(ot.typ, g) } return false } func (t *TypeType) Generic() px.Type { return NewTypeType(px.GenericType(t.typ)) } func (t *TypeType) Get(key string) (value px.Value, ok bool) { switch key { case `type`: return t.typ, true } return nil, false } func (t *TypeType) IsAssignable(o px.Type, g px.Guard) bool { if ot, ok := o.(*TypeType); ok { return GuardedIsAssignable(t.typ, ot.typ, g) } return false } func (t *TypeType) IsInstance(o px.Value, g px.Guard) bool { if ot, ok := o.(px.Type); ok { return GuardedIsAssignable(t.typ, ot, g) } return false } func (t *TypeType) MetaType() px.ObjectType { return TypeMetaType } func (t *TypeType) Name() string { return `Type` } func (t *TypeType) Parameters() []px.Value { if t.typ == DefaultAnyType() { return px.EmptyValues } return []px.Value{t.typ} } func (t *TypeType) Resolve(c px.Context) px.Type { t.typ = resolve(c, t.typ) return t } func (t *TypeType) CanSerializeAsString() bool { return canSerializeAsString(t.typ) } func (t *TypeType) SerializationString() string { return t.String() } func (t *TypeType) String() string { return px.ToString2(t, None) } func (t *TypeType) PType() px.Type { return &TypeType{t} } func (t *TypeType) ToString(b io.Writer, s px.FormatContext, g px.RDetect) { TypeToString(t, b, s, g) }
types/typetype.go
0.60743
0.53868
typetype.go
starcoder
package crdt import ( "fmt" "github.com/cloudstateio/go-support/cloudstate/entity" ) // A Vote is a CRDT which allows nodes to vote on a condition. It’s similar // to a GCounter, each node has its own counter, and an odd value is considered // a vote for the condition, while an even value is considered a vote against. // The result of the vote is decided by taking the votes of all nodes that are // currently members of the cluster (when a node leave, its vote is discarded). // Multiple decision strategies can be used to decide the result of the vote, // such as at least one, majority and all. type Vote struct { selfVote bool selfVoteChanged bool // delta seen voters uint32 votesFor uint32 } var _ CRDT = (*Vote)(nil) func NewVote() *Vote { return &Vote{ selfVote: false, selfVoteChanged: false, voters: 1, votesFor: 0, } } // SelfVote is the vote of the current node, // which is included in Voters and VotesFor. func (v *Vote) SelfVote() bool { return v.selfVote } // Voters is the total number of voters. func (v *Vote) Voters() uint32 { return v.voters } // VotesFor is the number of votes for. func (v *Vote) VotesFor() uint32 { return v.votesFor } // AtLeastOne returns true if there is at least one voter for the condition. func (v *Vote) AtLeastOne() bool { return v.votesFor > 0 } // Majority returns true if the number of votes for is more than half the number of voters. func (v *Vote) Majority() bool { return v.votesFor > v.voters/2 } // All returns true if the number of votes for equals the number of voters. func (v *Vote) All() bool { return v.votesFor == v.voters } // Vote votes with the given boolean for a condition. func (v *Vote) Vote(vote bool) { if v.selfVote == vote { return } v.selfVoteChanged = !v.selfVoteChanged v.selfVote = vote if v.selfVote { v.votesFor += 1 } else { v.votesFor -= 1 } } func (v *Vote) HasDelta() bool { return v.selfVoteChanged } func (v *Vote) Delta() *entity.CrdtDelta { return &entity.CrdtDelta{ Delta: &entity.CrdtDelta_Vote{Vote: &entity.VoteDelta{ SelfVote: v.selfVote, // VotesFor: int32(v.votesFor), // TotalVoters: int32(v.voters), TODO: ignored by the proxy says the Spec, but the TCK would complain. }}, } } func (v *Vote) resetDelta() { v.selfVoteChanged = false } func (v *Vote) applyDelta(delta *entity.CrdtDelta) error { d := delta.GetVote() if d == nil { return fmt.Errorf("unable to apply delta %+v to the Vote", delta) } v.selfVote = d.SelfVote v.voters = uint32(d.TotalVoters) v.votesFor = uint32(d.VotesFor) return nil }
cloudstate/crdt/vote.go
0.60964
0.401512
vote.go
starcoder
package series import "github.com/WinPooh32/math" type Data struct { samplesize int64 index []int64 data []float32 } func (d Data) Index() (data []int64) { return d.index } func (d Data) Data() (data []float32) { return d.data } func (d Data) Len() int { return len(d.index) } func (d Data) SampleSize() int64 { return d.samplesize } // Slices makes slice of data. func (d Data) Slice(l, r int) Data { return Data{ d.samplesize, d.index[l:r], d.data[l:r], } } // Clone makes full copy of data. func (d Data) Clone() Data { var clone = Data{ samplesize: d.samplesize, index: append([]int64(nil), d.index...), data: append([]float32(nil), d.data...), } return clone } func (d Data) Add(r Data) Data { // Slices prevent implicit bounds checks. sl := d.data sr := r.data if len(sl) != len(sr) { panic("sizes of data series must be equal") } for i := range sl { sl[i] += sr[i] } return d } func (d Data) Sub(r Data) Data { // Slices prevent implicit bounds checks. sl := d.data sr := r.data if len(sl) != len(sr) { panic("sizes of data series must be equal") } for i := range sl { sl[i] -= sr[i] } return d } func (d Data) Mul(r Data) Data { // Slices prevent implicit bounds checks. sl := d.data sr := r.data if len(sl) != len(sr) { panic("sizes of data series must be equal") } for i := range sl { sl[i] *= sr[i] } return d } func (d Data) Div(r Data) Data { // Slices prevent implicit bounds checks. sl := d.data sr := r.data if len(sl) != len(sr) { panic("sizes of data series must be equal") } for i := range sl { sl[i] /= sr[i] } return d } func (d Data) AddScalar(s float32) Data { sl := d.data for i := range sl { sl[i] += s } return d } func (d Data) SubScalar(s float32) Data { sl := d.data for i := range sl { sl[i] -= s } return d } func (d Data) MulScalar(s float32) Data { sl := d.data for i := range sl { sl[i] *= s } return d } func (d Data) DivScalar(s float32) Data { sl := d.data for i := range sl { sl[i] /= s } return d } // Log applies natural logarithm function to values of data. func (d Data) Log() Data { sl := d.data for i, v := range sl { sl[i] = math.Log(v) } return d } // Abs replace each elemnt by their absolute value. func (d Data) Abs() Data { sl := d.data for i, v := range sl { sl[i] = math.Abs(v) } return d } // Apply applies user's function to every value of data. func (d Data) Apply(fn func(float32) float32) Data { sl := d.data for i, v := range sl { sl[i] = fn(v) } return d } // Rolling provides rolling window calculations. func (d Data) Rolling(window int) Window { return Window{ len: window, data: d, } } // EWM provides exponential weighted calculations. func (d Data) EWM(atype AlphaType, param float32, adjust bool, ignoreNA bool) ExpWindow { return ExpWindow{ data: d, atype: atype, param: param, adjust: adjust, ignoreNA: ignoreNA, } } // RollData applies custom function to rolling window of data. // Function accepts window bounds. func (d Data) RollData(window int, cb func(l int, r int)) { if len(d.data) <= window { cb(0, len(d.data)) } for i := window; i <= len(d.data); i++ { cb(i-window, i) } } func (d Data) Resample(samplesize int64) Data { switch { case samplesize == d.samplesize: case samplesize < d.samplesize: d = d.resampleLess(d, samplesize) default: d = d.resampleMore(d, samplesize) } return d } func (d Data) Fillna(value float32, inplace bool) Data { var data Data if inplace { data = d } else { data = d.Clone() } dd := data.Data() for i, v := range dd { if math.IsNaN(v) { dd[i] = value } } return data } func (d Data) resampleLess(data Data, samplesize int64) Data { // TODO panic("not implemented!") } func (d Data) resampleMore(data Data, samplesize int64) Data { var index = data.index var resIndex = data.Index()[:0] var resData = data.Data()[:0] for i := 0; i < len(index); { beg, end := i, d.nextSample(index, i, samplesize) resIndex = append(resIndex, index[end-1]) resData = append(resData, Mean(data.Slice(beg, end))) i = end } return MakeData(samplesize, resIndex, resData) } func (d Data) nextSample(index []int64, i int, samplesize int64) (end int) { size := len(index) border := index[i] + samplesize for i < size && index[i] < border { i++ end = i } return end } func MakeData(samplesize int64, index []int64, data []float32) Data { if len(index) != len(data) { panic("size of index and data must be equal") } return Data{samplesize, index, data} }
data.go
0.654564
0.669509
data.go
starcoder
package mimir import ( "strconv" "strings" ) const ( abaExpectedLength = 9 abaStructure = "ffffaaaak" ) // IsABARTNValid checks if the given ABA Routing Number is valid. func IsABARTNValid(aba string) error { aba = standardizeABARTN(aba) if len(aba) != abaExpectedLength { return ErrABARTNInvalidLength } n := computeABARTN(aba) if n == 0 || n%10 != 0 { return ErrABAInvalidChecksum } return nil } // GetABARTNCheckDigit compute the check digits from a given ABA Routing Number. // Returns the computed digit and the ABA updated with the check digits or an error if something goes wrong. // The ABA must contains 9 digits but the last one will ignored. It's possible to use this function by adding an extra 0 // at the end if the ABA is not a valid one. func GetABARTNCheckDigit(aba string) (string, string, error) { aba = standardizeABARTN(aba) if len(aba) != abaExpectedLength { return "", "", ErrABARTNInvalidLength } n := computeABARTN(aba) // Removes the last digit from the computation n -= int(aba[len(aba)-1] - '0') checksum := 0 if mod := n % 10; mod > checksum { checksum = 10 - mod } sChecksum := strconv.Itoa(checksum) aba = aba[:abaExpectedLength-1] + sChecksum return sChecksum, aba, nil } // SplitABARTN splits a given valid ABA Routing Number depending its structure. It returns a list of digit keys and a list // that contains each part of the structure or an error if something went wrong. func SplitABARTN(aba string) ([]string, []string, error) { aba = standardizeABARTN(aba) if len(aba) != abaExpectedLength { return nil, nil, ErrABARTNInvalidLength } s := abaStructure var keys []string var values []string lastRune := "" currentPart := "" for i, r := range aba { y := string(s[i]) if lastRune != "" && lastRune != y { keys = append(keys, string(lastRune)) values = append(values, currentPart) currentPart = "" } currentPart += string(r) lastRune = y } if lastRune != "" { keys = append(keys, string(lastRune)) values = append(values, currentPart) } return keys, values, nil } // standardizeABARTN removes useless spaces from ABA Routing Number. func standardizeABARTN(aba string) string { // Remove all spaces return strings.Replace(aba, " ", "", -1) } // computeABARTN expects an 9 length string that contains digit from 0-9. // It going to sum them using the following formula according Wikipedia : https://en.wikipedia.org/wiki/ABA_routing_transit_number#Check_digit // [3(d1 + d4 + d7) + 7(d2 + d5 + d8) + (d3 + d6 + d9)] func computeABARTN(aba string) int { n := 0 for i := 0; i < len(aba); i += 3 { n += int(aba[i]-'0') * 3 n += int(aba[i+1]-'0') * 7 n += int(aba[i+2] - '0') } return n }
aba.go
0.712632
0.46035
aba.go
starcoder
package arts import ( "fmt" "math" "math/rand" "github.com/andrewwatson/generativeart" "github.com/andrewwatson/generativeart/common" "github.com/fogleman/gg" ) type circleLoop2 struct { depth int noise *common.PerlinNoise } func NewCircleLoop2(depth int) *circleLoop2 { return &circleLoop2{ depth: depth, noise: common.NewPerlinNoise(), } } // Generative draws a circle composed by many colored circles. func (cl *circleLoop2) Generative(c *generativeart.Canva) string { ctex := gg.NewContextForRGBA(c.Img()) ctex.Translate(float64(c.Width())/2, float64(c.Height())/2) numCircles := cl.recursionDraw(ctex, c, float64(c.Width()), cl.depth) return fmt.Sprintf("Circles: %d", numCircles) } func (cl *circleLoop2) recursionDraw(ctex *gg.Context, c *generativeart.Canva, x float64, depth int) int { if depth <= 0 { return 0 } circles := 0 circles += cl.draw(ctex, c, x) circles += cl.recursionDraw(ctex, c, 1*x/4.0, depth-1) circles += cl.recursionDraw(ctex, c, 2*x/4.0, depth-1) circles += cl.recursionDraw(ctex, c, 3*x/4.0, depth-1) return circles } func (cl *circleLoop2) draw(ctex *gg.Context, c *generativeart.Canva, x float64) int { var lw float64 odds := rand.Float64() if odds < 0.8 { lw = 2 } else if odds > 0.95 { lw = 9 } else { lw = common.RandomRangeFloat64(2.0, common.RandomRangeFloat64(1, 6)) } ctex.SetLineWidth(lw) noise := cl.noise.Noise3D(x*0.02+123.234, (1-x)*0.02, 345.4123) noise = math.Pow(noise, 0.5) a2 := common.Remap(noise, 0.15, 0.85, 0.1, 0.6) px := math.Pow(x/float64(c.Height()), a2) * float64(c.Height()) py := math.Pow(1-x/float64(c.Height()), a2)*float64(c.Height()) - common.RandomRangeFloat64(0, common.RandomRangeFloat64(float64(c.Height())*0.18, common.RandomRangeFloat64(float64(c.Height())*0.18, float64(c.Height())*0.7, ), ), ) cls := c.Opts().ColorSchema()[rand.Intn(len(c.Opts().ColorSchema()))] ctex.SetColor(cls) nCircles := common.RandomRangeInt(1, 4) if rand.Float64() < 0.05 { nCircles = common.RandomRangeInt(10, 20) } r := math.Pow(rand.Float64(), 2) * 150 var flag bool if rand.Float64() < 0.7 { flag = true } drawSquare := false if rand.Float64() < 0.005 { drawSquare = true } for i := 0; i < nCircles; i++ { if flag { if drawSquare { length := rand.Float64() * float64(i) * r / float64(nCircles) ctex.DrawRectangle(px*0.65, px*0.65, length, length) } else { ctex.DrawCircle( px*0.39, py*0.39, rand.Float64()*float64(i)*r/float64(nCircles), ) } } else { if drawSquare { length := float64(i) * r / float64(nCircles) ctex.DrawRectangle(px*0.65, px*0.65, length, length) } else { ctex.DrawCircle(px*0.39, py*0.39, float64(i)*r/float64(nCircles)) } } ctex.Stroke() } ctex.Rotate(x / float64(c.Height()) * 0.2) return nCircles }
arts/circleloop2.go
0.605449
0.410343
circleloop2.go
starcoder
package image import ( "bytes" "context" "errors" "fmt" "image" "image/color" "image/png" "io/ioutil" "math" "github.com/airbusgeo/geocube/internal/geocube" "github.com/airbusgeo/geocube/internal/utils" "github.com/airbusgeo/geocube/internal/utils/affine" "github.com/airbusgeo/godal" "github.com/google/uuid" ) type Dataset struct { URI string SubDir string Bands []int64 DataMapping geocube.DataMapping } func (d Dataset) GDALURI() string { return geocube.GDALURI(d.URI, d.SubDir) } var ErrLoger = godal.ErrLogger(func(ec godal.ErrorCategory, code int, msg string) error { if ec <= godal.CE_Warning { return nil } return fmt.Errorf("GDAL %d: %s", code, msg) }) type GdalDatasetDescriptor struct { WktCRS string PixToCRS *affine.Affine Width, Height int Bands int Resampling geocube.Resampling DataMapping geocube.DataMapping ValidPixPc int // Minimum percentage of valid pixels (or image not found is returned) Format string Palette *geocube.Palette } var ( ErrNoCastToPerform = errors.New("no cast to perform") ErrUnableToCast = errors.New("unableToCast") ) // CastDataset creates a new dataset and cast fromDFormat toDFormat // The caller is responsible to close the dataset // fromDFormat: NoData is ignored // dstDS [optional] If empty, the dataset is stored in memory func CastDataset(ctx context.Context, ds *godal.Dataset, fromDFormat, toDFormat geocube.DataMapping, dstDS string) (*godal.Dataset, error) { if fromDFormat.Equals(toDFormat) { return nil, ErrNoCastToPerform } // Reminder : ve = f(vi) = RangeExt.Min + (RangeExt.Max - RangeExt.Min) * ((vi - Range.Min)/(Range.Max - Range.Min))^Exponent // vinter = f(vfrom) = f(vto) // In some cases the formula is very simple ! if toDFormat.Exponent == 1 { /* This is just a special case of the following if toDFormat.Range == toDFormat.RangeExt { return castDataset(ds, fromDFormat.Range, fromDFormat.Exponent, geocube.DataFormat{ DType: toDFormat.DType, Range: fromDFormat.RangeExt, NoData: toDFormat.NoData, }, dstDS) } */ f := toDFormat.Range.Interval() / toDFormat.RangeExt.Interval() rangeEq := geocube.Range{Min: toDFormat.Range.Min + (fromDFormat.RangeExt.Min-toDFormat.RangeExt.Min)*f} rangeEq.Max = fromDFormat.RangeExt.Interval()*f + rangeEq.Min return castDataset(ds, fromDFormat.Range, fromDFormat.Exponent, geocube.DataFormat{ DType: toDFormat.DType, Range: rangeEq, NoData: toDFormat.NoData, }, dstDS) } if fromDFormat.Exponent == 1 { f := fromDFormat.Range.Interval() / fromDFormat.RangeExt.Interval() rangeEq := geocube.Range{Min: fromDFormat.Range.Min + (toDFormat.RangeExt.Min-fromDFormat.RangeExt.Min)*f} rangeEq.Max = toDFormat.RangeExt.Interval()*f + rangeEq.Min return castDataset(ds, rangeEq, 1/toDFormat.Exponent, toDFormat.DataFormat, dstDS) } if fromDFormat.Exponent == toDFormat.Exponent { if fromDFormat.RangeExt.Min == toDFormat.RangeExt.Min { f := fromDFormat.RangeExt.Interval() / toDFormat.RangeExt.Interval() rangeEq := geocube.Range{ Min: toDFormat.Range.Min, Max: toDFormat.Range.Interval()*math.Pow(f, 1/toDFormat.Exponent) + toDFormat.Range.Min, } return castDataset(ds, fromDFormat.Range, 1, geocube.DataFormat{ DType: toDFormat.DType, Range: rangeEq, NoData: toDFormat.NoData, }, dstDS) } } return nil, fmt.Errorf(" Unable to cast %v to %v %w", fromDFormat, toDFormat, ErrUnableToCast) } // castDataset creates a new dataset with toDFormat and converts the ds.pixels fromRange toDFormat (using an non-linear mapping if exponent != 1) // The caller is responsible to close the dataset // dstDS [optional] If empty, the dataset is stored in memory func castDataset(ds *godal.Dataset, fromRange geocube.Range, exponent float64, toDFormat geocube.DataFormat, dstDS string) (*godal.Dataset, error) { options := []string{ "-ot", toDFormat.DType.ToGDAL().String(), "-scale", toS(fromRange.Min), toS(fromRange.Max), toS(toDFormat.Range.Min), toS(toDFormat.Range.Max), "-a_nodata", toS(toDFormat.NoData), } if exponent != 1 { options = append(options, "-exponent", toS(exponent)) } var opts []godal.DatasetTranslateOption if dstDS == "" { opts = append(opts, godal.Memory) } outDs, err := ds.Translate(dstDS, options, opts...) if err != nil { return nil, fmt.Errorf("castDataset.Translate: %w", err) } return outDs, nil } func closeNonNilDatasets(datasets []*godal.Dataset) { for _, ds := range datasets { if ds != nil { ds.Close() } } } // MergeDatasets merge the given datasets into one in the format defined by outDesc // The caller is responsible to close the output dataset func MergeDatasets(ctx context.Context, datasets []*Dataset, outDesc *GdalDatasetDescriptor) (*godal.Dataset, error) { if len(datasets) == 0 { return nil, fmt.Errorf("mergeDatasets: no dataset to merge") } // Group datasets that share the same DataMapping groupedDatasets := [][]*Dataset{} for _, dataset := range datasets { found := false for i, groupeDs := range groupedDatasets { if dataset.DataMapping.Equals(groupeDs[0].DataMapping) { groupedDatasets[i] = append(groupedDatasets[i], dataset) found = true break } } if !found { groupedDatasets = append(groupedDatasets, []*Dataset{dataset}) } } var rerr error var mergedDatasets []*godal.Dataset defer closeNonNilDatasets(mergedDatasets) for _, groupedDs := range groupedDatasets { // Merge Datasets that share the same DataMapping commonDMapping := groupedDs[0].DataMapping mergedDs, err := warpDatasets(groupedDs, outDesc.WktCRS, outDesc.PixToCRS, float64(outDesc.Width), float64(outDesc.Height), outDesc.Resampling, commonDMapping.DataFormat) if rerr = err; rerr != nil { return nil, fmt.Errorf("mergeDatasets: %w", err) } // Convert dataset to outDesc.DataFormat if !commonDMapping.Equals(outDesc.DataMapping) { tmpDS := mergedDs defer tmpDS.Close() if mergedDs, rerr = CastDataset(ctx, tmpDS, commonDMapping, outDesc.DataMapping, ""); rerr != nil { return nil, fmt.Errorf("mergeDatasets: %w", err) } } mergedDatasets = append(mergedDatasets, mergedDs) } // Merge all the datasets together var mergedDs *godal.Dataset if len(mergedDatasets) == 1 { mergedDs = mergedDatasets[0] mergedDatasets[0] = nil } else if mergedDs, rerr = mosaicDatasets(mergedDatasets, outDesc.PixToCRS.Rx(), outDesc.PixToCRS.Ry()); rerr != nil { return nil, fmt.Errorf("mergeDatasets.%w", rerr) } // Test whether image has enough valid pixels if outDesc.ValidPixPc >= 0 { if nb, err := countValidPix(mergedDs.Bands()[0]); err != nil || int(100*nb) <= outDesc.Width*outDesc.Height*outDesc.ValidPixPc { mergedDs.Close() if rerr = err; rerr != nil { return nil, fmt.Errorf("countValidPix: %w", rerr) } return nil, geocube.NewEntityNotFound("", "", "", "Not enough valid pixels (skipped)") } } return mergedDs, nil } // mosaicDatasets calls godal.Warp to merge all the datasets into one without reprojection // The caller is responsible to close the output dataset func mosaicDatasets(datasets []*godal.Dataset, rx, ry float64) (*godal.Dataset, error) { outDs, err := godal.Warp("", datasets, []string{"-tr", toS(rx), toS(ry)}, godal.Memory, ErrLoger) if err != nil { if outDs != nil { outDs.Close() } return nil, fmt.Errorf("failed to mosaic dataset: %w", err) } return outDs, nil } // warpDatasets calls godal.Warp on datasets, performing a reprojection // The caller is responsible to close the output dataset func warpDatasets(datasets []*Dataset, wktCRS string, transform *affine.Affine, width, height float64, resampling geocube.Resampling, commonDFormat geocube.DataFormat) (*godal.Dataset, error) { listFile := make([]string, len(datasets)) gdatasets := make([]*godal.Dataset, len(datasets)) for i, dataset := range datasets { var err error uri := dataset.GDALURI() listFile[i] = uri gdatasets[i], err = godal.Open(uri, ErrLoger) if err != nil { return nil, fmt.Errorf("while opening %s: %w", uri, err) } defer gdatasets[i].Close() } options := []string{ "-t_srs", wktCRS, "-ts", toS(width), toS(height), "-ovr", "AUTO", //TODO user-defined ? "-wo", "INIT_DEST=" + toS(commonDFormat.NoData), "-wm", "2047", "-ot", commonDFormat.DType.ToGDAL().String(), "-r", resampling.String(), "-srcnodata", toS(commonDFormat.NoData), "-nomd", } if commonDFormat.NoDataDefined() { options = append(options, "-dstnodata", toS(commonDFormat.NoData)) } if transform != nil { xMin, yMax := transform.Transform(0, 0) xMax, yMin := transform.Transform(width, height) options = append(options, "-te", toS(xMin), toS(yMin), toS(xMax), toS(yMax)) } outDs, err := godal.Warp("", gdatasets, options, godal.Memory, ErrLoger) if err != nil { if outDs != nil { outDs.Close() } return nil, fmt.Errorf("failed to warp dataset: %w", err) } return outDs, nil } func countValidPix(band godal.Band) (uint64, error) { // Histogram does not count nodata histogram, err := band.Histogram(godal.Intervals(1, 0, 0), godal.IncludeOutOfRange(), godal.Approximate()) if err != nil { return 0, fmt.Errorf("countValidPix: %w", err) } return histogram.Bucket(0).Count, nil } func toS(f float64) string { return utils.F64ToS(f) } // colorTableFromPalette creates a gdal.ColorTable from a palette // The results must be Detroy() by the caller func colorTableFromPalette(palette *geocube.Palette) (*godal.ColorTable, error) { if palette == nil { return nil, nil } else { return nil, fmt.Errorf("palette not supported yet") } /* colorTable := &godal.ColorTable{PaletteInterp: godal.PaletteInterp(godal.RGBPalette)} pts := make([][4]int16, len(palette.Points)) for i, pt := range palette.Points { pts[i] = [4]int16{int16(pt.R), int16(pt.G), int16(pt.B), int16(pt.A)} } // Create ColorTable //colorTable.CreateColorRamp(0, 254, pts[0], pts[len(pts)-1]) for i := 1; i < len(pts)-1; i++ { colorTable.Entries[int(palette.Points[i].Val*254)] = pts[i] } return colorTable, nil*/ } // DatasetToPngAsBytes translates the dataset to a png and returns the byte representation // canInterpolateColor is true if dataset pixel value can be interpolated func DatasetToPngAsBytes(ctx context.Context, ds *godal.Dataset, fromDFormat geocube.DataMapping, palette *geocube.Palette, canInterpolateColor bool) ([]byte, error) { var palette256 color.Palette var virtualname string toDformat := fromDFormat if !canInterpolateColor { if fromDFormat.Range.Min < 0 || fromDFormat.Range.Max > 255 || fromDFormat.NoData < 0 || fromDFormat.NoData > 255 { return nil, fmt.Errorf("cannot create a png, because the color interpolation is forbidden") } if palette != nil { palette256 = palette.PaletteN(256) } } else { toDformat.DataFormat = geocube.DataFormat{ DType: geocube.DTypeUINT8, NoData: 255, Range: geocube.Range{Min: 0, Max: 254}, } toDformat.Exponent = 1 if palette != nil { palette256 = palette.PaletteN(255) palette256 = append(palette256, color.RGBA{}) } } if palette256 == nil { // To cast non-paletted to png virtualname = "/vsimem/" + uuid.New().String() + ".png" } // Cast to PNG pngDs, err := CastDataset(ctx, ds, fromDFormat, toDformat, virtualname) if err != nil { return nil, fmt.Errorf("DatasetToPngAsBytes.%w", err) } defer func() { pngDs.Close() godal.VSIUnlink(virtualname) }() // Apply palette if palette256 != nil { bitmap, err := geocube.NewBitmapFromDataset(pngDs) if err != nil { return nil, fmt.Errorf("DatasetToPngAsBytes.%w", err) } paletted := image.NewPaletted(bitmap.Rect, palette256) paletted.Pix = bitmap.Bytes b := bytes.Buffer{} if err = png.Encode(&b, paletted); err != nil { return nil, fmt.Errorf("DatasetToPngAsBytes.PngEncode: %w", err) } return b.Bytes(), nil } // Returns byte representation of the PNG file vsiFile, err := godal.VSIOpen(virtualname) if err != nil { return nil, fmt.Errorf("DatasetToPngAsBytes.%w", err) } defer vsiFile.Close() return ioutil.ReadAll(vsiFile) } // DatasetToTiffAsBytes translates the dataset to a tiff and returns the byte representation func DatasetToTiffAsBytes(ds *godal.Dataset, fromDFormat geocube.DataMapping, tags map[string]string, palette *geocube.Palette) ([]byte, error) { // Todo fromDFormat is not taken into account // Prepare options var options []string for k, t := range tags { options = append(options, "-mo", fmt.Sprintf("%s=%s", k, t)) } // Translate to Tiff virtualname := "/vsimem/" + uuid.New().String() + ".tif" tifDs, err := ds.Translate(virtualname, options) if err != nil { return nil, fmt.Errorf("datasetToTiff.Translate: %w", err) } defer func() { tifDs.Close() godal.VSIUnlink(virtualname) }() // Apply palette if palette != nil { tifDs.Bands()[0].SetColorInterp(godal.CIPalette) c, err := colorTableFromPalette(palette) if err != nil { return nil, fmt.Errorf("colorTableFromPalette: %w", err) } tifDs.Bands()[0].SetColorTable(*c) } // Returns byte representation of the TIFF file vsiFile, err := godal.VSIOpen(virtualname) if err != nil { return nil, fmt.Errorf("datasetToTiff.%w", err) } defer vsiFile.Close() return ioutil.ReadAll(vsiFile) }
internal/image/image.go
0.650911
0.469095
image.go
starcoder
package solver import ( "fmt" "sort" "strings" ) // Bit alignment divisor. const boardAlignment = 64 // allSet has is an int64 with all bits set. Used to skip over full board cells. const allSet = ^uint64(0) // Board is an array of uint64's, meant to be interpreted as a single long bitfield. // Unfortunately Go doesn't support arbitrary-size bitfields, so this is the next best thing. // The board cell at 0-index row `i` and 0-index column `j` is located at bit `j*width + i`. // A 1 set means that a piece occupies the cell. A 0 means no piece occupies the cell. type Board []uint64 func (b Board) String() string { s := make([]string, len(b)) for i, v := range b { s[i] = fmt.Sprintf("%d: %x", i, v) } return strings.Join(s, "\n") } // FirstFreeSpot finds the first free board position. // If there are no free spots, returns -1. func (b Board) FirstFreeSpot() int { for i, v := range b { if v^allSet == 0 { continue } for x := 0; x < boardAlignment; x++ { if v&1 == 0 { return i*boardAlignment + x } v = v >> 1 } panic(fmt.Sprintf("%x (index %d) is not all set, yet could not find unset bit", b[i], i)) } return -1 } func NewBoard(width, height int) Board { boardSize := width * height roundedUp := boardSize / boardAlignment if boardSize%boardAlignment != 0 { roundedUp++ } board := make([]uint64, roundedUp) // Flip the bits that are out of bounds. var lastValue uint64 for b := uint(boardSize % boardAlignment); b < 64; b++ { lastValue |= 1 << b } board[roundedUp-1] = lastValue return board } type CellBitmask struct { // The index within the Board []uint64 for which the Mask applies. BoardIndex int // The bit mask to check. Mask uint64 } type BoardBitmask []CellBitmask // GridPositions returns a list of (x, y)-tuples that correspond to the bits // set in the bitmask, assuming the given board width and height. func (bitmask BoardBitmask) GridPositions(width, height int) [][]int { w := uint(width) var positions [][]int for _, cellBitmask := range bitmask { mask := cellBitmask.Mask for b := uint(0); b < boardAlignment; b++ { bit := uint64(1 << b) if mask&bit == bit { boardPosition := uint(cellBitmask.BoardIndex)*boardAlignment + b positions = append(positions, []int{ int(boardPosition % w), int(boardPosition / w), }) } } } return positions } // NewBoardBitmask returns a new BoardBitmask that contains a mask where each given // position in `boardPositions` corresponds to a `1` bit. func NewBoardBitmask(boardPositions []int) BoardBitmask { bitMaskMap := make(map[int]uint64, len(boardPositions)) for _, boardPosition := range boardPositions { boardIndex := boardPosition / boardAlignment bitIndex := uint(boardPosition % boardAlignment) bitMaskMap[boardIndex] = bitMaskMap[boardIndex] | (1 << bitIndex) } sortedIndexes := make([]int, 0, len(bitMaskMap)) for boardIndex := range bitMaskMap { sortedIndexes = append(sortedIndexes, boardIndex) } sort.Ints(sortedIndexes) boardBitMask := make([]CellBitmask, len(sortedIndexes)) for i, boardIndex := range sortedIndexes { boardBitMask[i] = CellBitmask{ BoardIndex: boardIndex, Mask: bitMaskMap[boardIndex], } } return BoardBitmask(boardBitMask) } // Add adds the given BoardBitmask to the board. // On success, returns a new Board with the bitmask applied. // The original Board is not modified. // On failure, returns nil. func (b Board) Add(bitmask BoardBitmask) Board { for _, cellBitmask := range bitmask { if b[cellBitmask.BoardIndex]&cellBitmask.Mask != 0 { // Doesn't fit. return nil } } // Fits. Make new board. newBoard := make([]uint64, len(b)) copy(newBoard, b) for _, cellBitmask := range bitmask { newBoard[cellBitmask.BoardIndex] |= cellBitmask.Mask } return newBoard }
solver/board.go
0.800497
0.414129
board.go
starcoder
package queue /** FanOutQueue structure +---------------------------------------------------------+ | Tail FanOutQueue Head | | | | | | +-----------+ +-----------+ | | | Segment | | Segment..| | | | Begin | | | | | | End | | | | | | Append | | | | | | Read | | | | | | | | | | | +----+------+ +------+----+ | | ^ ^ | +---------+-----------------+-----------------------------+ | | | ^ | | | | +---------+--+ +----------+-+ | Append | FanOut | | FanOut.. | | | Name | | | + +--------+ | Consume | | | | Data...| | Get | | | | | | Ack | | | | | | | | | +--------+ +------------+ +------------+ Segment structure +-----------------------------------------------+ | Segment | | | | +----------------------+ +----------+ | | | IndexPage | | DataPage | | | | dataOffset dataLen+------->Message1 | | | | (4 bytes) (4 bytes) | | Message2 | | | | .... | | .... | | | | | | | | | | | | | | | +----------------------+ +----------+ | | | +-----------------------------------------------+ directory structure /fanoutQueueDir queue.meta /segments 0.idx 0.dat 100.idx 100.dat ... /fanOut fanOutName1.meta fanOutName2.meta ... */
pkg/queue/doc.go
0.501465
0.532607
doc.go
starcoder
package pcapng /* 4.3.1. Enhanced Packet Block Flags Word The Enhanced Packet Block Flags Word is a 32-bit value that contains link-layer information about the packet. The word is encoded as an unsigned 32-bit integer, using the endianness of the Section Header Block scope it is in. In the following table, the bits are numbered with 0 being the most- significant bit and 31 being the least-significant bit of the 32-bit unsigned integer. The meaning of the bits is the following: +--------+----------------------------------------------------------+ | Bit | Description | | Number | | +--------+----------------------------------------------------------+ | 0-1 | Inbound / Outbound packet (00 = information not | | | available, 01 = inbound, 10 = outbound) | | 2-4 | Reception type (000 = not specified, 001 = unicast, 010 | | | = multicast, 011 = broadcast, 100 = promiscuous). | | 5-8 | FCS length, in octets (0000 if this information is not | | | available). This value overrides the if_fcslen option | | | of the Interface Description Block, and is used with | | | those link layers (e.g. PPP) where the length of the FCS | | | can change during time. | | 9-15 | Reserved (MUST be set to zero). | | 16-31 | link-layer-dependent errors (Bit 31 = symbol error, Bit | | | 30 = preamble error, Bit 29 = Start Frame Delimiter | | | error, Bit 28 = unaligned frame error, Bit 27 = wrong | | | Inter Frame Gap error, Bit 26 = packet too short error, | | | Bit 25 = packet too long error, Bit 24 = CRC error, | | | other?? are 16 bit enough?). | +--------+----------------------------------------------------------+ */ type EnhancedPacketBlockFlags struct { Bound Bound ReceptionType ReceptionType FCSLength uint8 LinkLayerDependentErrors LinkLayerDependentErrors } func ParseEnhancedPacketBlockFlags(v uint32) EnhancedPacketBlockFlags { return EnhancedPacketBlockFlags{ Bound: Bound(v & 0x00000003), ReceptionType: ReceptionType((v & 0x0000001c) >> 2), FCSLength: uint8((v & 0x000001e0) >> 5), LinkLayerDependentErrors: ParseLinkLayerDependentErrors(uint16((v & 0xffff0000) >> 16)), } } type Bound uint8 const ( BoundUnknown Bound = iota Inbound Outbound ) type ReceptionType uint8 const ( ReceptionTypeNotSpecified ReceptionType = iota Unicast Multicast Broadcast Promiscuous ) type LinkLayerDependentErrors struct { SymbolError bool PreambleError bool StartFrameDelimiterError bool UnalignedFrameError bool WrongInterFrameGapError bool PacketTooShortError bool PacketTooLongError bool CRCError bool } func ParseLinkLayerDependentErrors(flags uint16) LinkLayerDependentErrors { return LinkLayerDependentErrors{ SymbolError: flags&0x8000 != 0, PreambleError: flags&0x4000 != 0, StartFrameDelimiterError: flags&0x2000 != 0, UnalignedFrameError: flags&0x1000 != 0, WrongInterFrameGapError: flags&0x0800 != 0, PacketTooShortError: flags&0x0400 != 0, PacketTooLongError: flags&0x0200 != 0, CRCError: flags&0x0100 != 0, } } func (e LinkLayerDependentErrors) Encode() uint16 { var se, pe, sfde, ufe, wifge, ptse, ptle, ce uint16 if e.SymbolError { se = 1 << 15 } if e.PreambleError { pe = 1 << 14 } if e.StartFrameDelimiterError { sfde = 1 << 13 } if e.UnalignedFrameError { ufe = 1 << 12 } if e.WrongInterFrameGapError { wifge = 1 << 11 } if e.PacketTooShortError { ptse = 1 << 10 } if e.PacketTooLongError { ptle = 1 << 9 } if e.CRCError { ce = 1 << 8 } return se | pe | sfde | ufe | wifge | ptse | ptle | ce }
pcapng/enhanced_packet_block_flags.go
0.652463
0.585309
enhanced_packet_block_flags.go
starcoder
package iso20022 // Details of the statement reporting the bank services billing. type BillingStatement1 struct { // Identification of the customer billing statement. StatementIdentification *Max35Text `xml:"StmtId"` // Date range between the start date and the end date for which the statement is issued. FromToDate *DatePeriod1 `xml:"FrToDt"` // Date the statement message was created. CreationDateTime *ISODateTime `xml:"CreDtTm"` // Defines the status of the statement. Status *BillingStatementStatus1Code `xml:"Sts"` // Specifies the details of the account characteristics. AccountCharacteristics *CashAccountCharacteristics1 `xml:"AcctChrtcs"` // Identifies the non tax per annum rate and factor values used within the statement along with any time dependent charge basis. RateData []*BillingRate1 `xml:"RateData,omitempty"` // Specifies details related to currency exchange data. CurrencyExchange []*CurrencyExchange6 `xml:"CcyXchg,omitempty"` // Identifies the average value of balances held within the statement period. Balance []*BillingBalance1 `xml:"Bal,omitempty"` // Identifies the set of values and totals that are used to provide compensation information, service and tax totals. Compensation []*BillingCompensation1 `xml:"Compstn,omitempty"` // Specifies the values used for every line item service in the statement. Service []*BillingService1 `xml:"Svc,omitempty"` // Tax region(s) that levy a tax on the services within this statement. TaxRegion []*BillingTaxRegion1 `xml:"TaxRgn,omitempty"` // One or more sections that identify balance or float adjustments to the account. They can reflect either adjustments to the current statement or adjustments to statements from prior reporting periods. BalanceAdjustment []*BalanceAdjustment1 `xml:"BalAdjstmnt,omitempty"` // One or more sections that identify line item service adjustments to the account. They reflect adjustments to statements from prior reporting periods. ServiceAdjustment []*BillingServiceAdjustment1 `xml:"SvcAdjstmnt,omitempty"` } func (b *BillingStatement1) SetStatementIdentification(value string) { b.StatementIdentification = (*Max35Text)(&value) } func (b *BillingStatement1) AddFromToDate() *DatePeriod1 { b.FromToDate = new(DatePeriod1) return b.FromToDate } func (b *BillingStatement1) SetCreationDateTime(value string) { b.CreationDateTime = (*ISODateTime)(&value) } func (b *BillingStatement1) SetStatus(value string) { b.Status = (*BillingStatementStatus1Code)(&value) } func (b *BillingStatement1) AddAccountCharacteristics() *CashAccountCharacteristics1 { b.AccountCharacteristics = new(CashAccountCharacteristics1) return b.AccountCharacteristics } func (b *BillingStatement1) AddRateData() *BillingRate1 { newValue := new(BillingRate1) b.RateData = append(b.RateData, newValue) return newValue } func (b *BillingStatement1) AddCurrencyExchange() *CurrencyExchange6 { newValue := new(CurrencyExchange6) b.CurrencyExchange = append(b.CurrencyExchange, newValue) return newValue } func (b *BillingStatement1) AddBalance() *BillingBalance1 { newValue := new(BillingBalance1) b.Balance = append(b.Balance, newValue) return newValue } func (b *BillingStatement1) AddCompensation() *BillingCompensation1 { newValue := new(BillingCompensation1) b.Compensation = append(b.Compensation, newValue) return newValue } func (b *BillingStatement1) AddService() *BillingService1 { newValue := new(BillingService1) b.Service = append(b.Service, newValue) return newValue } func (b *BillingStatement1) AddTaxRegion() *BillingTaxRegion1 { newValue := new(BillingTaxRegion1) b.TaxRegion = append(b.TaxRegion, newValue) return newValue } func (b *BillingStatement1) AddBalanceAdjustment() *BalanceAdjustment1 { newValue := new(BalanceAdjustment1) b.BalanceAdjustment = append(b.BalanceAdjustment, newValue) return newValue } func (b *BillingStatement1) AddServiceAdjustment() *BillingServiceAdjustment1 { newValue := new(BillingServiceAdjustment1) b.ServiceAdjustment = append(b.ServiceAdjustment, newValue) return newValue }
BillingStatement1.go
0.78838
0.509276
BillingStatement1.go
starcoder
package labels import ( "encoding/json" "fmt" "testing" "github.com/ingrammicro/cio/api/types" "github.com/ingrammicro/cio/utils" "github.com/stretchr/testify/assert" ) // ListLabelsMocked test mocked function func ListLabelsMocked(t *testing.T, labelsIn []*types.Label) []*types.Label { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // to json dIn, err := json.Marshal(labelsIn) assert.Nil(err, "Label test data corrupted") // call service cs.On("Get", APIPathLabels).Return(dIn, 200, nil) labelsOut, err := ds.ListLabels() assert.Nil(err, "Error getting labels list") assert.Equal(labelsIn, labelsOut, "ListLabels returned different labels") return labelsOut } // ListLabelsMockedWithNamespace test mocked function func ListLabelsMockedWithNamespace(t *testing.T, labelsIn []*types.Label) []*types.Label { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // to json dIn, err := json.Marshal(labelsIn) assert.Nil(err, "Label test data corrupted") // call service cs.On("Get", APIPathLabels).Return(dIn, 200, nil) labelsOut, err := ds.ListLabels() assert.Nil(err, "Error getting labels list") assert.NotEqual(labelsIn, labelsOut, "ListLabels returned labels with Namespaces") return labelsOut } // ListLabelsFailErrMocked test mocked function func ListLabelsFailErrMocked(t *testing.T, labelsIn []*types.Label) []*types.Label { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // to json dIn, err := json.Marshal(labelsIn) assert.Nil(err, "Label test data corrupted") // call service cs.On("Get", APIPathLabels).Return(dIn, 200, fmt.Errorf("mocked error")) labelsOut, err := ds.ListLabels() assert.NotNil(err, "We are expecting an error") assert.Nil(labelsOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return labelsOut } // ListLabelsFailStatusMocked test mocked function func ListLabelsFailStatusMocked(t *testing.T, labelsIn []*types.Label) []*types.Label { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // to json dIn, err := json.Marshal(labelsIn) assert.Nil(err, "Label test data corrupted") // call service cs.On("Get", APIPathLabels).Return(dIn, 499, nil) labelsOut, err := ds.ListLabels() assert.NotNil(err, "We are expecting an status code error") assert.Nil(labelsOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return labelsOut } // ListLabelsFailJSONMocked test mocked function func ListLabelsFailJSONMocked(t *testing.T, labelsIn []*types.Label) []*types.Label { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Get", APIPathLabels).Return(dIn, 200, nil) labelsOut, err := ds.ListLabels() assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(labelsOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return labelsOut } // CreateLabelMocked test mocked function func CreateLabelMocked(t *testing.T, labelIn *types.Label) *types.Label { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*labelIn) assert.Nil(err, "Label test data corrupted") // to json dOut, err := json.Marshal(labelIn) assert.Nil(err, "Label test data corrupted") // call service cs.On("Post", APIPathLabels, mapIn).Return(dOut, 200, nil) labelOut, err := ds.CreateLabel(mapIn) assert.Nil(err, "Error creating label") assert.Equal(labelIn, labelOut, "CreateLabel returned different labels") return labelOut } // CreateLabelFailErrMocked test mocked function func CreateLabelFailErrMocked(t *testing.T, labelIn *types.Label) *types.Label { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*labelIn) assert.Nil(err, "Label test data corrupted") // to json dOut, err := json.Marshal(labelIn) assert.Nil(err, "Label test data corrupted") // call service cs.On("Post", APIPathLabels, mapIn).Return(dOut, 200, fmt.Errorf("mocked error")) labelOut, err := ds.CreateLabel(mapIn) assert.NotNil(err, "We are expecting an error") assert.Nil(labelOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return labelOut } // CreateLabelFailStatusMocked test mocked function func CreateLabelFailStatusMocked(t *testing.T, labelIn *types.Label) *types.Label { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*labelIn) assert.Nil(err, "Label test data corrupted") // to json dOut, err := json.Marshal(labelIn) assert.Nil(err, "Label test data corrupted") // call service cs.On("Post", APIPathLabels, mapIn).Return(dOut, 499, nil) labelOut, err := ds.CreateLabel(mapIn) assert.NotNil(err, "We are expecting an status code error") assert.Nil(labelOut, "Expecting nil output") assert.Contains(err.Error(), "499", "Error should contain http code 499") return labelOut } // CreateLabelFailJSONMocked test mocked function func CreateLabelFailJSONMocked(t *testing.T, labelIn *types.Label) *types.Label { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*labelIn) assert.Nil(err, "Label test data corrupted") // wrong json dIn := []byte{10, 20, 30} // call service cs.On("Post", APIPathLabels, mapIn).Return(dIn, 200, nil) labelOut, err := ds.CreateLabel(mapIn) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(labelOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return labelOut } // AddLabelMocked test mocked function func AddLabelMocked( t *testing.T, labelIn *types.Label, labeledResourcesOut []*types.LabeledResource, ) []*types.LabeledResource { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*labelIn) assert.Nil(err, "Label test data corrupted") // to json dOut, err := json.Marshal(labeledResourcesOut) assert.Nil(err, "Label test data corrupted") // call service cs.On("Post", fmt.Sprintf(APIPathLabelResources, labelIn.ID), mapIn).Return(dOut, 200, nil) labeledOut, err := ds.AddLabel(labelIn.ID, mapIn) assert.Nil(err, "Error creating label") assert.Equal(labeledOut, labeledResourcesOut, "CreateLabel returned invalid labeled resources") return labeledResourcesOut } // AddLabelFailErrMocked test mocked function func AddLabelFailErrMocked( t *testing.T, labelIn *types.Label, labeledResourcesOut []*types.LabeledResource, ) []*types.LabeledResource { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*labelIn) assert.Nil(err, "Label test data corrupted") // to json dOut, err := json.Marshal(labeledResourcesOut) assert.Nil(err, "Label test data corrupted") // call service cs.On("Post", fmt.Sprintf(APIPathLabelResources, labelIn.ID), mapIn).Return(dOut, 200, fmt.Errorf("mocked error")) labeledOut, err := ds.AddLabel(labelIn.ID, mapIn) assert.NotNil(err, "We are expecting an error") assert.Nil(labeledOut, "Expecting nil output") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") return labeledResourcesOut } // AddLabelFailStatusMocked test mocked function func AddLabelFailStatusMocked( t *testing.T, labelIn *types.Label, labeledResourcesOut []*types.LabeledResource, ) []*types.LabeledResource { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*labelIn) assert.Nil(err, "Label test data corrupted") // to json dOut, err := json.Marshal(labeledResourcesOut) assert.Nil(err, "Label test data corrupted") // call service cs.On("Post", fmt.Sprintf(APIPathLabelResources, labelIn.ID), mapIn).Return(dOut, 404, nil) labeledOut, err := ds.AddLabel(labelIn.ID, mapIn) assert.NotNil(err, "We are expecting an status code error") assert.Nil(labeledOut, "Expecting nil output") assert.Contains(err.Error(), "404", "Error should contain http code 404") return labeledResourcesOut } // AddLabelFailJSONMocked test mocked function func AddLabelFailJSONMocked( t *testing.T, labelIn *types.Label, labeledResourcesOut []*types.LabeledResource, ) []*types.LabeledResource { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // convertMap mapIn, err := utils.ItemConvertParams(*labelIn) assert.Nil(err, "Label test data corrupted") // wrong json dOut := []byte{10, 20, 30} // call service cs.On("Post", fmt.Sprintf(APIPathLabelResources, labelIn.ID), mapIn).Return(dOut, 200, nil) labeledOut, err := ds.AddLabel(labelIn.ID, mapIn) assert.NotNil(err, "We are expecting a marshalling error") assert.Nil(labeledOut, "Expecting nil output") assert.Contains(err.Error(), "invalid character", "Error message should include the string 'invalid character'") return labeledResourcesOut } // RemoveLabelMocked test mocked function func RemoveLabelMocked(t *testing.T, labelIn *types.Label) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // to json dIn, err := json.Marshal(labelIn) assert.Nil(err, "Label test data corrupted") // call service resourceID := "5b5074735f7c880ad9c6bbce" cs.On("Delete", fmt.Sprintf(APIPathLabelResource, labelIn.ID, labelIn.ResourceType, resourceID)). Return(dIn, 204, nil) err = ds.RemoveLabel(labelIn.ID, labelIn.ResourceType, resourceID) assert.Nil(err, "Error removing label") } // RemoveLabelFailErrMocked test mocked function func RemoveLabelFailErrMocked(t *testing.T, labelIn *types.Label) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // to json dIn, err := json.Marshal(labelIn) assert.Nil(err, "Label test data corrupted") // call service resourceID := "5b5074735f7c880ad9c6bbce" cs.On("Delete", fmt.Sprintf(APIPathLabelResource, labelIn.ID, labelIn.ResourceType, resourceID)). Return(dIn, 204, fmt.Errorf("mocked error")) err = ds.RemoveLabel(labelIn.ID, labelIn.ResourceType, resourceID) assert.NotNil(err, "We are expecting an error") assert.Equal(err.Error(), "mocked error", "Error should be 'mocked error'") } // RemoveLabelFailStatusMocked test mocked function func RemoveLabelFailStatusMocked(t *testing.T, labelIn *types.Label) { assert := assert.New(t) // wire up cs := &utils.MockConcertoService{} ds, err := NewLabelService(cs) assert.Nil(err, "Couldn't load label service") assert.NotNil(ds, "Label service not instanced") // to json dIn, err := json.Marshal(labelIn) assert.Nil(err, "Label test data corrupted") // call service resourceID := "5b5074735f7c880ad9c6bbce" cs.On("Delete", fmt.Sprintf(APIPathLabelResource, labelIn.ID, labelIn.ResourceType, resourceID)). Return(dIn, 404, nil) err = ds.RemoveLabel(labelIn.ID, labelIn.ResourceType, resourceID) assert.NotNil(err, "We are expecting an status code error") assert.Contains(err.Error(), "404", "Error should contain http code 404") }
api/labels/labels_api_mocked.go
0.721841
0.559711
labels_api_mocked.go
starcoder
package main import ( "sort" ) type dungeonPath struct { dungeon *dungeon neighbors [8]position wcost int } func (dp *dungeonPath) Neighbors(pos position) []position { nb := dp.neighbors[:0] return pos.CardinalNeighbors(nb, func(npos position) bool { return npos.valid() }) } func (dp *dungeonPath) Cost(from, to position) int { if dp.dungeon.Cell(to).T == WallCell { if dp.wcost > 0 { return dp.wcost } return 4 } return 1 } func (dp *dungeonPath) Estimation(from, to position) int { return from.Distance(to) } type gridPath struct { dungeon *dungeon neighbors [4]position } func (gp *gridPath) Neighbors(pos position) []position { nb := gp.neighbors[:0] return pos.CardinalNeighbors(nb, func(npos position) bool { return npos.valid() }) } func (gp *gridPath) Cost(from, to position) int { return 1 } func (gp *gridPath) Estimation(from, to position) int { return from.Distance(to) } type mappingPath struct { game *game neighbors [8]position } func (dp *mappingPath) Neighbors(pos position) []position { d := dp.game.Dungeon if d.Cell(pos).T == WallCell { return nil } nb := dp.neighbors[:0] keep := func(npos position) bool { return npos.valid() } return pos.CardinalNeighbors(nb, keep) } func (dp *mappingPath) Cost(from, to position) int { return 1 } func (dp *mappingPath) Estimation(from, to position) int { return from.Distance(to) } type tunnelPath struct { dg *dgen neighbors [4]position area [9]position } func (tp *tunnelPath) Neighbors(pos position) []position { nb := tp.neighbors[:0] return pos.CardinalNeighbors(nb, func(npos position) bool { return npos.valid() }) } func (tp *tunnelPath) Cost(from, to position) int { if tp.dg.room[from] && !tp.dg.tunnel[from] { return 50 } cost := 1 c := tp.dg.d.Cell(from) if tp.dg.room[from] { cost += 7 } else if !tp.dg.tunnel[from] && c.T != GroundCell { cost++ } if c.IsPassable() { return cost } wc := tp.dg.WallAreaCount(tp.area[:0], from, 1) return cost + 8 - wc } func (tp *tunnelPath) Estimation(from, to position) int { return from.Distance(to) } type playerPath struct { game *game neighbors [8]position goal position } func (pp *playerPath) Neighbors(pos position) []position { d := pp.game.Dungeon nb := pp.neighbors[:0] keep := func(npos position) bool { t, okT := pp.game.TerrainKnowledge[npos] if cld, ok := pp.game.Clouds[npos]; ok && cld == CloudFire && (!okT || t != FoliageCell && t != DoorCell) { return false } return npos.valid() && d.Cell(npos).Explored && (d.Cell(npos).T.IsPlayerPassable() && !okT || okT && t.IsPlayerPassable() || pp.game.Player.HasStatus(StatusLevitation) && (t == BarrierCell || t == ChasmCell) || pp.game.Player.HasStatus(StatusDig) && (d.Cell(npos).T.IsDiggable() && !okT || (okT && t.IsDiggable()))) } nb = pos.CardinalNeighbors(nb, keep) sort.Slice(nb, func(i, j int) bool { return nb[i].MaxCardinalDist(pp.goal) <= nb[j].MaxCardinalDist(pp.goal) }) return nb } func (pp *playerPath) Cost(from, to position) int { if !pp.game.ExclusionsMap[from] && pp.game.ExclusionsMap[to] { return unreachable } return 1 } func (pp *playerPath) Estimation(from, to position) int { return from.Distance(to) } type noisePath struct { game *game neighbors [8]position } func (fp *noisePath) Neighbors(pos position) []position { nb := fp.neighbors[:0] d := fp.game.Dungeon keep := func(npos position) bool { return npos.valid() && d.Cell(npos).T != WallCell } return pos.CardinalNeighbors(nb, keep) } func (fp *noisePath) Cost(from, to position) int { return 1 } type autoexplorePath struct { game *game neighbors [8]position } func (ap *autoexplorePath) Neighbors(pos position) []position { if ap.game.ExclusionsMap[pos] { return nil } d := ap.game.Dungeon nb := ap.neighbors[:0] keep := func(npos position) bool { t, okT := ap.game.TerrainKnowledge[npos] if cld, ok := ap.game.Clouds[npos]; ok && cld == CloudFire && (!okT || t != FoliageCell && t != DoorCell) { // XXX little info leak return false } return npos.valid() && (d.Cell(npos).T.IsPlayerPassable() && (!okT || t != WallCell)) && !ap.game.ExclusionsMap[npos] } nb = pos.CardinalNeighbors(nb, keep) return nb } func (ap *autoexplorePath) Cost(from, to position) int { return 1 } type monPath struct { game *game monster *monster destruct bool neighbors [8]position } func (mp *monPath) Neighbors(pos position) []position { nb := mp.neighbors[:0] d := mp.game.Dungeon keep := func(npos position) bool { if !npos.valid() { return false } c := d.Cell(npos) return c.IsPassable() || c.IsDestructible() && mp.destruct || c.T == DoorCell && (mp.monster.Kind.CanOpenDoors() || mp.destruct) || c.IsLevitatePassable() && mp.monster.Kind.CanFly() || c.IsSwimPassable() && (mp.monster.Kind.CanSwim() || mp.monster.Kind.CanFly()) || c.T == HoledWallCell && mp.monster.Kind.Size() == MonsSmall } ret := pos.CardinalNeighbors(nb, keep) // shuffle so that monster movement is not unnaturally predictable for i := 0; i < len(ret); i++ { j := i + RandInt(len(ret)-i) ret[i], ret[j] = ret[j], ret[i] } return ret } func (mp *monPath) Cost(from, to position) int { g := mp.game mons := g.MonsterAt(to) if !mons.Exists() { c := g.Dungeon.Cell(to) if mp.destruct && c.IsDestructible() { return 5 } if to == g.Player.Pos && mp.monster.Kind.Peaceful() { switch mp.monster.Kind { case MonsEarthDragon: return 1 default: return 4 } } if mp.monster.Kind.Patrolling() && mp.monster.State != Hunting && !c.IsNormalPatrolWay() { return 4 } return 1 } if mons.Status(MonsLignified) { return 8 } return 6 } func (mp *monPath) Estimation(from, to position) int { return from.Distance(to) } func (m *monster) APath(g *game, from, to position) []position { mp := &monPath{game: g, monster: m} if m.Kind == MonsEarthDragon { mp.destruct = true } path, _, found := AstarPath(mp, from, to) if !found { return nil } return path } func (g *game) PlayerPath(from, to position) []position { pp := &playerPath{game: g, goal: to} path, _, found := AstarPath(pp, from, to) if !found { return nil } return path } func (g *game) SortedNearestTo(cells []position, to position) []position { ps := posSlice{} for _, pos := range cells { pp := &dungeonPath{dungeon: g.Dungeon, wcost: unreachable} _, cost, found := AstarPath(pp, pos, to) if found { ps = append(ps, posCost{pos, cost}) } } sort.Sort(ps) sorted := []position{} for _, pc := range ps { sorted = append(sorted, pc.pos) } return sorted } type posCost struct { pos position cost int } type posSlice []posCost func (ps posSlice) Len() int { return len(ps) } func (ps posSlice) Swap(i, j int) { ps[i], ps[j] = ps[j], ps[i] } func (ps posSlice) Less(i, j int) bool { return ps[i].cost < ps[j].cost }
path.go
0.624866
0.565299
path.go
starcoder
package cxcore import ( "github.com/skycoin/skycoin/src/cipher/encoder" ) //Why do these functions need CXArgument as imput!? func ReadData(fp int, inp *CXArgument, dataType int) interface{} { elt := GetAssignmentElement(inp) if elt.IsSlice { return ReadSlice(fp, inp, dataType) } else if elt.IsArray { return ReadArray(fp, inp, dataType) } else { return ReadObject(fp, inp, dataType) } } // ReadData_i8 ... func ReadData_i8(fp int, inp *CXArgument, dataType int) interface{} { return ReadData(fp, inp, dataType) } // ReadData_i16 ... func ReadData_i16(fp int, inp *CXArgument, dataType int) interface{} { return ReadData(fp, inp, dataType) } // ReadData_i32 ... func ReadData_i32(fp int, inp *CXArgument, dataType int) interface{} { return ReadData(fp, inp, dataType) } // ReadData_i64 ... func ReadData_i64(fp int, inp *CXArgument, dataType int) interface{} { return ReadData(fp, inp, dataType) } // ReadData_ui8 ... func ReadData_ui8(fp int, inp *CXArgument, dataType int) interface{} { return ReadData(fp, inp, dataType) } // ReadData_ui16 ... func ReadData_ui16(fp int, inp *CXArgument, dataType int) interface{} { return ReadData(fp, inp, dataType) } // ReadData_ui32 ... func ReadData_ui32(fp int, inp *CXArgument, dataType int) interface{} { return ReadData(fp, inp, dataType) } // ReadData_ui64 ... func ReadData_ui64(fp int, inp *CXArgument, dataType int) interface{} { return ReadData(fp, inp, dataType) } // ReadData_f32 ... func ReadData_f32(fp int, inp *CXArgument, dataType int) interface{} { return ReadData(fp, inp, dataType) } // ReadData_f64 ... func ReadData_f64(fp int, inp *CXArgument, dataType int) interface{} { return ReadData(fp, inp, dataType) } //Note: Only called once and only by ReadData // ReadObject ... func ReadObject(fp int, inp *CXArgument, dataType int) interface{} { offset := GetFinalOffset(fp, inp) array := ReadMemory(offset, inp) return readAtomic(inp, array) } //Note: I modified this to crash if invalid type was used func readAtomic(inp *CXArgument, bytes []byte) interface{} { switch inp.Type { case TYPE_I8: data := readDataI8(bytes) if len(data) > 0 { return interface{}(data) } case TYPE_I16: data := readDataI16(bytes) if len(data) > 0 { return interface{}(data) } case TYPE_I32: data := readDataI32(bytes) if len(data) > 0 { return interface{}(data) } case TYPE_I64: data := readDataI64(bytes) if len(data) > 0 { return interface{}(data) } case TYPE_UI8: data := readDataUI8(bytes) if len(data) > 0 { return interface{}(data) } case TYPE_UI16: data := readDataUI16(bytes) if len(data) > 0 { return interface{}(data) } case TYPE_UI32: data := readDataUI32(bytes) if len(data) > 0 { return interface{}(data) } case TYPE_UI64: data := readDataUI64(bytes) if len(data) > 0 { return interface{}(data) } case TYPE_F32: data := readDataF32(bytes) if len(data) > 0 { return interface{}(data) } case TYPE_F64: data := readDataF64(bytes) if len(data) > 0 { return interface{}(data) } default: data := readDataUI8(bytes) if len(data) > 0 { return interface{}(data) } } //should this crash if it gets here? panic(CX_RUNTIME_INVALID_ARGUMENT) //Note: modified this so it crashes if it gets here for some reason return interface{}(nil) } // ReadSlice ... func ReadSlice(fp int, inp *CXArgument, dataType int) interface{} { sliceOffset := GetSliceOffset(fp, inp) if sliceOffset >= 0 && (dataType < 0 || inp.Type == dataType) { slice := GetSliceData(sliceOffset, GetAssignmentElement(inp).Size) if slice != nil { return readAtomic(inp, slice) //readData } } else { panic(CX_RUNTIME_INVALID_ARGUMENT) } return interface{}(nil) } // ReadArray ... func ReadArray(fp int, inp *CXArgument, dataType int) interface{} { offset := GetFinalOffset(fp, inp) if dataType < 0 || inp.Type == dataType { array := ReadMemory(offset, inp) return readAtomic(inp, array) //readData } panic(CX_RUNTIME_INVALID_ARGUMENT) } // ReadSliceBytes ... func ReadSliceBytes(fp int, inp *CXArgument, dataType int) []byte { sliceOffset := GetSliceOffset(fp, inp) if sliceOffset >= 0 && (dataType < 0 || inp.Type == dataType) { slice := GetSliceData(sliceOffset, GetAssignmentElement(inp).Size) return slice } panic(CX_RUNTIME_INVALID_ARGUMENT) } // second section // ReadBool ... func ReadBool(fp int, inp *CXArgument) (out bool) { offset := GetFinalOffset(fp, inp) out = DeserializeBool(ReadMemory(offset, inp)) return } // ReadStrFromOffset ... func ReadStrFromOffset(off int, inp *CXArgument) (out string) { var offset int32 if inp.Name == "" { // Then it's a literal. offset = int32(off) } else { offset = Deserialize_i32(PROGRAM.Memory[off : off+TYPE_POINTER_SIZE]) } if offset == 0 { // Then it's nil string. out = "" return } // We need to check if the string lives on the data segment or on the // heap to know if we need to take into consideration the object header's size. if int(offset) > PROGRAM.HeapStartsAt { size := Deserialize_i32(PROGRAM.Memory[offset+OBJECT_HEADER_SIZE : offset+OBJECT_HEADER_SIZE+STR_HEADER_SIZE]) DeserializeRaw(PROGRAM.Memory[offset+OBJECT_HEADER_SIZE:offset+OBJECT_HEADER_SIZE+STR_HEADER_SIZE+size], &out) } else { size := Deserialize_i32(PROGRAM.Memory[offset : offset+STR_HEADER_SIZE]) DeserializeRaw(PROGRAM.Memory[offset:offset+STR_HEADER_SIZE+size], &out) } return out } // ReadStr ... func ReadStr(fp int, inp *CXArgument) (out string) { off := GetFinalOffset(fp, inp) return ReadStrFromOffset(off, inp) } // ReadStringFromObject reads the string located at offset `off`. func ReadStringFromObject(off int32) string { var plusOff int32 if int(off) > PROGRAM.HeapStartsAt { // Found in heap segment. plusOff += OBJECT_HEADER_SIZE } size := Deserialize_i32(PROGRAM.Memory[off+plusOff : off+plusOff+STR_HEADER_SIZE]) str := "" _, err := encoder.DeserializeRaw(PROGRAM.Memory[off+plusOff:off+plusOff+STR_HEADER_SIZE+size], &str) if err != nil { panic(err) } return str }
cx/fix_read3.go
0.526343
0.490968
fix_read3.go
starcoder
package indicators import ( "container/list" "errors" "github.com/thetruetrade/gotrade" ) // A Weighted Moving Average Indicator (Wma), no storage, for use in other indicators type WmaWithoutStorage struct { *baseIndicatorWithFloatBounds // private variables periodTotal float64 periodHistory *list.List periodCounter int periodWeightTotal int timePeriod int } // NewWmaWithoutStorage creates a Weighted Moving Average Indicator (Wma) without storage func NewWmaWithoutStorage(timePeriod int, valueAvailableAction ValueAvailableActionFloat) (indicator *WmaWithoutStorage, err error) { // an indicator without storage MUST have a value available action if valueAvailableAction == nil { return nil, ErrValueAvailableActionIsNil } // the minimum timeperiod for this indicator is 2 if timePeriod < 2 { return nil, errors.New("timePeriod is less than the minimum (2)") } // check the maximum timeperiod if timePeriod > MaximumLookbackPeriod { return nil, errors.New("timePeriod is greater than the maximum (100000)") } lookback := timePeriod - 1 ind := WmaWithoutStorage{ baseIndicatorWithFloatBounds: newBaseIndicatorWithFloatBounds(lookback, valueAvailableAction), periodCounter: timePeriod * -1, periodHistory: list.New(), timePeriod: timePeriod, } var weightedTotal int = 0 for i := 1; i <= timePeriod; i++ { weightedTotal += i } ind.periodWeightTotal = weightedTotal return &ind, nil } // A Weighted Moving Average Indicator (Wma) type Wma struct { *WmaWithoutStorage selectData gotrade.DOHLCVDataSelectionFunc // public variables Data []float64 } // NewWma creates a Weighted Moving Average Indicator (Wma) for online usage func NewWma(timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *Wma, err error) { if selectData == nil { return nil, ErrDOHLCVDataSelectFuncIsNil } ind := Wma{ selectData: selectData, } ind.WmaWithoutStorage, err = NewWmaWithoutStorage(timePeriod, func(dataItem float64, streamBarIndex int) { ind.Data = append(ind.Data, dataItem) }) return &ind, err } // NewDefaultWma creates a Weighted Moving Average Indicator (Wma) for online usage with default parameters // - timePeriod: 10 func NewDefaultWma() (indicator *Wma, err error) { timePeriod := 10 return NewWma(timePeriod, gotrade.UseClosePrice) } // NewWmaWithSrcLen creates a Weighted Moving Average Indicator (Wma) for offline usage func NewWmaWithSrcLen(sourceLength uint, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *Wma, err error) { ind, err := NewWma(timePeriod, selectData) // only initialise the storage if there is enough source data to require it if sourceLength-uint(ind.GetLookbackPeriod()) > 1 { ind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod())) } return ind, err } // NewDefaultWmaWithSrcLen creates a Weighted Moving Average Indicator (Wma) for offline usage with default parameters func NewDefaultWmaWithSrcLen(sourceLength uint) (indicator *Wma, err error) { ind, err := NewDefaultWma() // only initialise the storage if there is enough source data to require it if sourceLength-uint(ind.GetLookbackPeriod()) > 1 { ind.Data = make([]float64, 0, sourceLength-uint(ind.GetLookbackPeriod())) } return ind, err } // NewWmaForStream creates a Weighted Moving Average Indicator (Wma) for online usage with a source data stream func NewWmaForStream(priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *Wma, err error) { ind, err := NewWma(timePeriod, selectData) priceStream.AddTickSubscription(ind) return ind, err } // NewDefaultWmaForStream creates a Weighted Moving Average Indicator (Wma) for online usage with a source data stream func NewDefaultWmaForStream(priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Wma, err error) { ind, err := NewDefaultWma() priceStream.AddTickSubscription(ind) return ind, err } // NewWmaForStreamWithSrcLen creates a Weighted Moving Average Indicator (Wma) for offline usage with a source data stream func NewWmaForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *Wma, err error) { ind, err := NewWmaWithSrcLen(sourceLength, timePeriod, selectData) priceStream.AddTickSubscription(ind) return ind, err } // NewDefaultWmaForStreamWithSrcLen creates a Weighted Moving Average Indicator (Wma) for offline usage with a source data stream func NewDefaultWmaForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber) (indicator *Wma, err error) { ind, err := NewDefaultWmaWithSrcLen(sourceLength) priceStream.AddTickSubscription(ind) return ind, err } // ReceiveDOHLCVTick consumes a source data DOHLCV price tick func (ind *Wma) ReceiveDOHLCVTick(tickData gotrade.DOHLCV, streamBarIndex int) { var selectedData = ind.selectData(tickData) ind.ReceiveTick(selectedData, streamBarIndex) } func (ind *WmaWithoutStorage) ReceiveTick(tickData float64, streamBarIndex int) { ind.periodCounter += 1 ind.periodHistory.PushBack(tickData) if ind.periodCounter > 0 { } if ind.periodHistory.Len() > ind.timePeriod { var first = ind.periodHistory.Front() ind.periodHistory.Remove(first) } if ind.periodCounter >= 0 { // calculate the ind var iter int = 1 var sum float64 = 0 for e := ind.periodHistory.Front(); e != nil; e = e.Next() { var localSum float64 = 0 for i := 1; i <= iter; i++ { localSum += e.Value.(float64) } sum += localSum iter++ } var result float64 = sum / float64(ind.periodWeightTotal) ind.UpdateIndicatorWithNewValue(result, streamBarIndex) } }
indicators/wma.go
0.660939
0.406126
wma.go
starcoder
package sql import ( "bytes" "context" "fmt" "github.com/cockroachdb/cockroach/pkg/sql/sem/tree" "github.com/cockroachdb/cockroach/pkg/sql/sem/types" "github.com/cockroachdb/cockroach/pkg/sql/sqlbase" "github.com/cockroachdb/cockroach/pkg/util/treeprinter" ) // explainPlanNode wraps the logic for EXPLAIN as a planNode. type explainPlanNode struct { explainer explainer // plan is the sub-node being explained. plan planNode // expanded indicates whether to invoke expandPlan() on the sub-node. expanded bool // optimized indicates whether to invoke setNeededColumns() on the sub-node. optimized bool run explainPlanRun } var explainPlanColumns = sqlbase.ResultColumns{ // Tree shows the node type with the tree structure. {Name: "Tree", Typ: types.String}, // Field is the part of the node that a row of output pertains to. {Name: "Field", Typ: types.String}, // Description contains details about the field. {Name: "Description", Typ: types.String}, } var explainPlanVerboseColumns = sqlbase.ResultColumns{ // Tree shows the node type with the tree structure. {Name: "Tree", Typ: types.String}, // Level is the depth of the node in the tree. {Name: "Level", Typ: types.Int}, // Type is the node type. {Name: "Type", Typ: types.String}, // Field is the part of the node that a row of output pertains to. {Name: "Field", Typ: types.String}, // Description contains details about the field. {Name: "Description", Typ: types.String}, // Columns is the type signature of the data source. {Name: "Columns", Typ: types.String}, // Ordering indicates the known ordering of the data from this source. {Name: "Ordering", Typ: types.String}, } // newExplainPlanNode instantiates a planNode that runs an EXPLAIN query. func (p *planner) makeExplainPlanNode( explainer explainer, expanded, optimized bool, origStmt tree.Statement, plan planNode, ) planNode { columns := explainPlanColumns if explainer.showMetadata { columns = explainPlanVerboseColumns } noPlaceholderFlags := tree.FmtExpr( tree.FmtSimple, explainer.showTypes, explainer.symbolicVars, explainer.qualifyNames, ) explainer.fmtFlags = tree.FmtPlaceholderFormat(noPlaceholderFlags, func(buf *bytes.Buffer, f tree.FmtFlags, placeholder *tree.Placeholder) { d, err := placeholder.Eval(&p.evalCtx) if err != nil { placeholder.Format(buf, noPlaceholderFlags) return } d.Format(buf, f) }) node := &explainPlanNode{ explainer: explainer, expanded: expanded, optimized: optimized, plan: plan, run: explainPlanRun{ results: p.newContainerValuesNode(columns, 0), }, } return node } // explainPlanRun is the run-time state of explainPlanNode during local execution. type explainPlanRun struct { // results is the container for EXPLAIN's output. results *valuesNode } func (e *explainPlanNode) startExec(params runParams) error { return params.p.populateExplain(params.ctx, &e.explainer, e.run.results, e.plan) } func (e *explainPlanNode) Next(params runParams) (bool, error) { return e.run.results.Next(params) } func (e *explainPlanNode) Values() tree.Datums { return e.run.results.Values() } func (e *explainPlanNode) Close(ctx context.Context) { e.plan.Close(ctx) e.run.results.Close(ctx) } // explainEntry is a representation of the info that makes it into an output row // of an EXPLAIN statement. type explainEntry struct { level int node, field, fieldVal string plan planNode } // explainer represents the run-time state of the EXPLAIN logic. type explainer struct { // showMetadata indicates whether the output has separate columns for the // schema signature and ordering information of the intermediate // nodes. showMetadata bool // showExprs indicates whether the plan prints expressions // embedded inside the node. showExprs bool // qualifyNames determines whether column names in expressions // should be fully qualified during pretty-printing. qualifyNames bool // symbolicVars determines whether ordinal column references // should be printed numerically. symbolicVars bool // fmtFlags is the formatter to use for pretty-printing expressions. fmtFlags tree.FmtFlags // showTypes indicates whether to print the type of embedded // expressions and result columns. showTypes bool // level is the current depth in the tree of planNodes. level int // explainEntry accumulates entries (nodes or attributes). entries []explainEntry } var emptyString = tree.NewDString("") // populateExplain walks the plan and generates rows in a valuesNode. func (p *planner) populateExplain( ctx context.Context, e *explainer, v *valuesNode, plan planNode, ) error { e.entries = nil _ = walkPlan(ctx, plan, e.observer()) tp := treeprinter.New() // n keeps track of the current node on each level. n := []treeprinter.Node{tp} for _, entry := range e.entries { if entry.plan != nil { n = append(n[:entry.level+1], n[entry.level].Child(entry.node)) } else { tp.AddEmptyLine() } } treeRows := tp.FormattedRows() for i, entry := range e.entries { var row tree.Datums if !e.showMetadata { row = tree.Datums{ tree.NewDString(treeRows[i]), // Tree tree.NewDString(entry.field), // Field tree.NewDString(entry.fieldVal), // Description } } else { row = tree.Datums{ tree.NewDString(treeRows[i]), // Tree tree.NewDInt(tree.DInt(entry.level)), // Level tree.NewDString(entry.node), // Type tree.NewDString(entry.field), // Field tree.NewDString(entry.fieldVal), // Description emptyString, // Columns emptyString, // Ordering } if entry.plan != nil { cols := planColumns(plan) // Columns metadata. row[5] = tree.NewDString(formatColumns(cols, e.showTypes)) // Ordering metadata. row[6] = tree.NewDString(planPhysicalProps(plan).AsString(cols)) } } if _, err := v.rows.AddRow(ctx, row); err != nil { return err } } return nil } // planToString uses explain() to build a string representation of the planNode. func planToString(ctx context.Context, plan planNode) string { e := explainer{ showMetadata: true, showExprs: true, showTypes: true, fmtFlags: tree.FmtExpr(tree.FmtSimple, true, true, true), } _ = walkPlan(ctx, plan, e.observer()) var buf bytes.Buffer for _, e := range e.entries { field := e.field if field != "" { field = "." + field } if plan == nil { fmt.Fprintf(&buf, "%d %s%s %s\n", e.level, e.node, field, e.fieldVal) } else { cols := planColumns(plan) fmt.Fprintf( &buf, "%d %s%s %s %s %s\n", e.level, e.node, field, e.fieldVal, formatColumns(cols, true), planPhysicalProps(plan).AsString(cols), ) } } return buf.String() } func (e *explainer) observer() planObserver { return planObserver{ enterNode: e.enterNode, expr: e.expr, attr: e.attr, leaveNode: e.leaveNode, } } // expr implements the planObserver interface. func (e *explainer) expr(nodeName, fieldName string, n int, expr tree.Expr) { if e.showExprs && expr != nil { if nodeName == "join" { qualifySave := e.fmtFlags.ShowTableAliases e.fmtFlags.ShowTableAliases = true defer func() { e.fmtFlags.ShowTableAliases = qualifySave }() } if n >= 0 { fieldName = fmt.Sprintf("%s %d", fieldName, n) } e.attr(nodeName, fieldName, tree.AsStringWithFlags(expr, e.fmtFlags)) } } // enterNode implements the planObserver interface. func (e *explainer) enterNode(_ context.Context, name string, plan planNode) (bool, error) { e.entries = append(e.entries, explainEntry{ level: e.level, node: name, plan: plan, }) e.level++ return true, nil } // attr implements the planObserver interface. func (e *explainer) attr(nodeName, fieldName, attr string) { e.entries = append(e.entries, explainEntry{ level: e.level - 1, field: fieldName, fieldVal: attr, }) } // leaveNode implements the planObserver interface. func (e *explainer) leaveNode(name string, _ planNode) error { e.level-- return nil } // formatColumns converts a column signature for a data source / // planNode to a string. The column types are printed iff the 2nd // argument specifies so. func formatColumns(cols sqlbase.ResultColumns, printTypes bool) string { var buf bytes.Buffer buf.WriteByte('(') for i, rCol := range cols { if i > 0 { buf.WriteString(", ") } tree.FormatNode(&buf, tree.FmtSimple, tree.Name(rCol.Name)) // Output extra properties like [hidden,omitted]. hasProps := false outputProp := func(prop string) { if hasProps { buf.WriteByte(',') } else { buf.WriteByte('[') } hasProps = true buf.WriteString(prop) } if rCol.Hidden { outputProp("hidden") } if rCol.Omitted { outputProp("omitted") } if hasProps { buf.WriteByte(']') } if printTypes { buf.WriteByte(' ') buf.WriteString(rCol.Typ.String()) } } buf.WriteByte(')') return buf.String() }
pkg/sql/explain_plan.go
0.721939
0.425187
explain_plan.go
starcoder
package influxql import ( "fmt" "github.com/influxdata/flux/ast" "github.com/influxdata/influxql" ) type joinCursor struct { expr ast.Expression m map[influxql.Expr]string exprs []influxql.Expr } func Join(t *transpilerState, cursors []cursor, on []string) cursor { if len(cursors) == 1 { return cursors[0] } // Iterate through each cursor and each expression within each cursor to assign them an id. var exprs []influxql.Expr m := make(map[influxql.Expr]string) tables := make([]*ast.Property, 0, len(cursors)) for _, cur := range cursors { // Perform a variable assignment and use it for the table name. ident := t.assignment(cur.Expr()) tableName := ident.Name tables = append(tables, &ast.Property{ Key: ident, Value: &ast.Identifier{ Name: ident.Name, }, }) for _, k := range cur.Keys() { // Combine the table name with the name to access this attribute so we can know // what it will be mapped to. varName, _ := cur.Value(k) name := fmt.Sprintf("%s_%s", tableName, varName) exprs = append(exprs, k) m[k] = name } } // Construct the expression for the on parameter. onExpr := make([]ast.Expression, 0, len(on)) for _, name := range on { onExpr = append(onExpr, &ast.StringLiteral{ Value: name, }) } expr := &ast.CallExpression{ Callee: &ast.Identifier{ Name: "join", }, Arguments: []ast.Expression{ &ast.ObjectExpression{ Properties: []*ast.Property{ { Key: &ast.Identifier{Name: "tables"}, Value: &ast.ObjectExpression{ Properties: tables, }, }, { Key: &ast.Identifier{Name: "on"}, Value: &ast.ArrayExpression{ Elements: onExpr, }, }, }, }, }, } return &joinCursor{ expr: expr, m: m, exprs: exprs, } } func (c *joinCursor) Expr() ast.Expression { return c.expr } func (c *joinCursor) Keys() []influxql.Expr { keys := make([]influxql.Expr, 0, len(c.m)) for k := range c.m { keys = append(keys, k) } return keys } func (c *joinCursor) Value(expr influxql.Expr) (string, bool) { value, ok := c.m[expr] return value, ok }
query/influxql/join.go
0.5144
0.420421
join.go
starcoder
package as import ( "github.com/meowpub/meow/ld" ) // Specifies the accuracy around the point established by the longitude and latitude func GetAccuracy(e ld.Entity) interface{} { return e.Get(Prop_Accuracy.ID) } func SetAccuracy(e ld.Entity, v interface{}) { e.Set(Prop_Accuracy.ID, v) } // Subproperty of as:attributedTo that identifies the primary actor func GetActor(e ld.Entity) interface{} { return e.Get(Prop_Actor.ID) } func SetActor(e ld.Entity, v interface{}) { e.Set(Prop_Actor.ID, v) } // The altitude of a place func GetAltitude(e ld.Entity) interface{} { return e.Get(Prop_Altitude.ID) } func SetAltitude(e ld.Entity, v interface{}) { e.Set(Prop_Altitude.ID, v) } // Describes a possible inclusive answer or option for a question. func GetAnyOf(e ld.Entity) interface{} { return e.Get(Prop_AnyOf.ID) } func SetAnyOf(e ld.Entity, v interface{}) { e.Set(Prop_AnyOf.ID, v) } func GetAttachment(e ld.Entity) interface{} { return e.Get(Prop_Attachment.ID) } func SetAttachment(e ld.Entity, v interface{}) { e.Set(Prop_Attachment.ID, v) } func GetAttachments(e ld.Entity) interface{} { return e.Get(Prop_Attachments.ID) } func SetAttachments(e ld.Entity, v interface{}) { e.Set(Prop_Attachments.ID, v) } // Identifies an entity to which an object is attributed func GetAttributedTo(e ld.Entity) interface{} { return e.Get(Prop_AttributedTo.ID) } func SetAttributedTo(e ld.Entity, v interface{}) { e.Set(Prop_AttributedTo.ID, v) } func GetAudience(e ld.Entity) interface{} { return e.Get(Prop_Audience.ID) } func SetAudience(e ld.Entity, v interface{}) { e.Set(Prop_Audience.ID, v) } // Identifies the author of an object. Deprecated. Use as:attributedTo instead func GetAuthor(e ld.Entity) interface{} { return e.Get(Prop_Author.ID) } func SetAuthor(e ld.Entity, v interface{}) { e.Set(Prop_Author.ID, v) } func GetBcc(e ld.Entity) interface{} { return e.Get(Prop_Bcc.ID) } func SetBcc(e ld.Entity, v interface{}) { e.Set(Prop_Bcc.ID, v) } func GetBto(e ld.Entity) interface{} { return e.Get(Prop_Bto.ID) } func SetBto(e ld.Entity, v interface{}) { e.Set(Prop_Bto.ID, v) } func GetCc(e ld.Entity) interface{} { return e.Get(Prop_Cc.ID) } func SetCc(e ld.Entity, v interface{}) { e.Set(Prop_Cc.ID, v) } // The content of the object. func GetContent(e ld.Entity) interface{} { return e.Get(Prop_Content.ID) } func SetContent(e ld.Entity, v interface{}) { e.Set(Prop_Content.ID, v) } // Specifies the context within which an object exists or an activity was performed func GetContext(e ld.Entity) interface{} { return e.Get(Prop_Context.ID) } func SetContext(e ld.Entity, v interface{}) { e.Set(Prop_Context.ID, v) } func GetCurrent(e ld.Entity) interface{} { return e.Get(Prop_Current.ID) } func SetCurrent(e ld.Entity, v interface{}) { e.Set(Prop_Current.ID, v) } // Specifies the date and time the object was deleted func GetDeleted(e ld.Entity) interface{} { return e.Get(Prop_Deleted.ID) } func SetDeleted(e ld.Entity, v interface{}) { e.Set(Prop_Deleted.ID, v) } // On a Profile object, describes the object described by the profile func GetDescribes(e ld.Entity) interface{} { return e.Get(Prop_Describes.ID) } func SetDescribes(e ld.Entity, v interface{}) { e.Set(Prop_Describes.ID, v) } func GetDownstreamDuplicates(e ld.Entity) interface{} { return e.Get(Prop_DownstreamDuplicates.ID) } func SetDownstreamDuplicates(e ld.Entity, v interface{}) { e.Set(Prop_DownstreamDuplicates.ID, v) } // The duration of the object func GetDuration(e ld.Entity) interface{} { return e.Get(Prop_Duration.ID) } func SetDuration(e ld.Entity, v interface{}) { e.Set(Prop_Duration.ID, v) } // The ending time of the object func GetEndTime(e ld.Entity) interface{} { return e.Get(Prop_EndTime.ID) } func SetEndTime(e ld.Entity, v interface{}) { e.Set(Prop_EndTime.ID, v) } func GetFirst(e ld.Entity) interface{} { return e.Get(Prop_First.ID) } func SetFirst(e ld.Entity, v interface{}) { e.Set(Prop_First.ID, v) } // On a Tombstone object, describes the former type of the deleted object func GetFormerType(e ld.Entity) interface{} { return e.Get(Prop_FormerType.ID) } func SetFormerType(e ld.Entity, v interface{}) { e.Set(Prop_FormerType.ID, v) } func GetGenerator(e ld.Entity) interface{} { return e.Get(Prop_Generator.ID) } func SetGenerator(e ld.Entity, v interface{}) { e.Set(Prop_Generator.ID, v) } // The display height expressed as device independent pixels func GetHeight(e ld.Entity) interface{} { return e.Get(Prop_Height.ID) } func SetHeight(e ld.Entity, v interface{}) { e.Set(Prop_Height.ID, v) } // The target URI of the Link func GetHref(e ld.Entity) interface{} { return e.Get(Prop_Href.ID) } func SetHref(e ld.Entity, v interface{}) { e.Set(Prop_Href.ID, v) } // A hint about the language of the referenced resource func GetHreflang(e ld.Entity) interface{} { return e.Get(Prop_Hreflang.ID) } func SetHreflang(e ld.Entity, v interface{}) { e.Set(Prop_Hreflang.ID, v) } func GetIcon(e ld.Entity) interface{} { return e.Get(Prop_Icon.ID) } func SetIcon(e ld.Entity, v interface{}) { e.Set(Prop_Icon.ID, v) } func GetId(e ld.Entity) interface{} { return e.Get(Prop_Id.ID) } func SetId(e ld.Entity, v interface{}) { e.Set(Prop_Id.ID, v) } func GetImage(e ld.Entity) interface{} { return e.Get(Prop_Image.ID) } func SetImage(e ld.Entity, v interface{}) { e.Set(Prop_Image.ID, v) } func GetInReplyTo(e ld.Entity) interface{} { return e.Get(Prop_InReplyTo.ID) } func SetInReplyTo(e ld.Entity, v interface{}) { e.Set(Prop_InReplyTo.ID, v) } // Indentifies an object used (or to be used) to complete an activity func GetInstrument(e ld.Entity) interface{} { return e.Get(Prop_Instrument.ID) } func SetInstrument(e ld.Entity, v interface{}) { e.Set(Prop_Instrument.ID, v) } func GetItems(e ld.Entity) interface{} { return e.Get(Prop_Items.ID) } func SetItems(e ld.Entity, v interface{}) { e.Set(Prop_Items.ID, v) } func GetLast(e ld.Entity) interface{} { return e.Get(Prop_Last.ID) } func SetLast(e ld.Entity, v interface{}) { e.Set(Prop_Last.ID, v) } // The latitude func GetLatitude(e ld.Entity) interface{} { return e.Get(Prop_Latitude.ID) } func SetLatitude(e ld.Entity, v interface{}) { e.Set(Prop_Latitude.ID, v) } func GetLocation(e ld.Entity) interface{} { return e.Get(Prop_Location.ID) } func SetLocation(e ld.Entity, v interface{}) { e.Set(Prop_Location.ID, v) } // The longitude func GetLongitude(e ld.Entity) interface{} { return e.Get(Prop_Longitude.ID) } func SetLongitude(e ld.Entity, v interface{}) { e.Set(Prop_Longitude.ID, v) } // The MIME Media Type func GetMediaType(e ld.Entity) interface{} { return e.Get(Prop_MediaType.ID) } func SetMediaType(e ld.Entity, v interface{}) { e.Set(Prop_MediaType.ID, v) } func GetName(e ld.Entity) interface{} { return e.Get(Prop_Name.ID) } func SetName(e ld.Entity, v interface{}) { e.Set(Prop_Name.ID, v) } func GetNext(e ld.Entity) interface{} { return e.Get(Prop_Next.ID) } func SetNext(e ld.Entity, v interface{}) { e.Set(Prop_Next.ID, v) } func GetObject(e ld.Entity) interface{} { return e.Get(Prop_Object.ID) } func SetObject(e ld.Entity, v interface{}) { e.Set(Prop_Object.ID, v) } func GetObjectType(e ld.Entity) interface{} { return e.Get(Prop_ObjectType.ID) } func SetObjectType(e ld.Entity, v interface{}) { e.Set(Prop_ObjectType.ID, v) } // Describes a possible exclusive answer or option for a question. func GetOneOf(e ld.Entity) interface{} { return e.Get(Prop_OneOf.ID) } func SetOneOf(e ld.Entity, v interface{}) { e.Set(Prop_OneOf.ID, v) } // For certain activities, specifies the entity from which the action is directed. func GetOrigin(e ld.Entity) interface{} { return e.Get(Prop_Origin.ID) } func SetOrigin(e ld.Entity, v interface{}) { e.Set(Prop_Origin.ID, v) } func GetPartOf(e ld.Entity) interface{} { return e.Get(Prop_PartOf.ID) } func SetPartOf(e ld.Entity, v interface{}) { e.Set(Prop_PartOf.ID, v) } func GetPrev(e ld.Entity) interface{} { return e.Get(Prop_Prev.ID) } func SetPrev(e ld.Entity, v interface{}) { e.Set(Prop_Prev.ID, v) } func GetPreview(e ld.Entity) interface{} { return e.Get(Prop_Preview.ID) } func SetPreview(e ld.Entity, v interface{}) { e.Set(Prop_Preview.ID, v) } func GetProvider(e ld.Entity) interface{} { return e.Get(Prop_Provider.ID) } func SetProvider(e ld.Entity, v interface{}) { e.Set(Prop_Provider.ID, v) } // Specifies the date and time the object was published func GetPublished(e ld.Entity) interface{} { return e.Get(Prop_Published.ID) } func SetPublished(e ld.Entity, v interface{}) { e.Set(Prop_Published.ID, v) } // Specifies a radius around the point established by the longitude and latitude func GetRadius(e ld.Entity) interface{} { return e.Get(Prop_Radius.ID) } func SetRadius(e ld.Entity, v interface{}) { e.Set(Prop_Radius.ID, v) } // A numeric rating (>= 0.0, <= 5.0) for the object func GetRating(e ld.Entity) interface{} { return e.Get(Prop_Rating.ID) } func SetRating(e ld.Entity, v interface{}) { e.Set(Prop_Rating.ID, v) } // The RFC 5988 or HTML5 Link Relation associated with the Link func GetRel(e ld.Entity) interface{} { return e.Get(Prop_Rel.ID) } func SetRel(e ld.Entity, v interface{}) { e.Set(Prop_Rel.ID, v) } // On a Relationship object, describes the type of relationship func GetRelationship(e ld.Entity) interface{} { return e.Get(Prop_Relationship.ID) } func SetRelationship(e ld.Entity, v interface{}) { e.Set(Prop_Relationship.ID, v) } func GetReplies(e ld.Entity) interface{} { return e.Get(Prop_Replies.ID) } func SetReplies(e ld.Entity, v interface{}) { e.Set(Prop_Replies.ID, v) } func GetResult(e ld.Entity) interface{} { return e.Get(Prop_Result.ID) } func SetResult(e ld.Entity, v interface{}) { e.Set(Prop_Result.ID, v) } // In a strictly ordered logical collection, specifies the index position of the first item in the items list func GetStartIndex(e ld.Entity) interface{} { return e.Get(Prop_StartIndex.ID) } func SetStartIndex(e ld.Entity, v interface{}) { e.Set(Prop_StartIndex.ID, v) } // The starting time of the object func GetStartTime(e ld.Entity) interface{} { return e.Get(Prop_StartTime.ID) } func SetStartTime(e ld.Entity, v interface{}) { e.Set(Prop_StartTime.ID, v) } // On a Relationship object, identifies the subject. e.g. when saying "John is connected to Sally", 'subject' refers to 'John' func GetSubject(e ld.Entity) interface{} { return e.Get(Prop_Subject.ID) } func SetSubject(e ld.Entity, v interface{}) { e.Set(Prop_Subject.ID, v) } // A short summary of the object func GetSummary(e ld.Entity) interface{} { return e.Get(Prop_Summary.ID) } func SetSummary(e ld.Entity, v interface{}) { e.Set(Prop_Summary.ID, v) } func GetTag(e ld.Entity) interface{} { return e.Get(Prop_Tag.ID) } func SetTag(e ld.Entity, v interface{}) { e.Set(Prop_Tag.ID, v) } func GetTags(e ld.Entity) interface{} { return e.Get(Prop_Tags.ID) } func SetTags(e ld.Entity, v interface{}) { e.Set(Prop_Tags.ID, v) } func GetTarget(e ld.Entity) interface{} { return e.Get(Prop_Target.ID) } func SetTarget(e ld.Entity, v interface{}) { e.Set(Prop_Target.ID, v) } func GetTo(e ld.Entity) interface{} { return e.Get(Prop_To.ID) } func SetTo(e ld.Entity, v interface{}) { e.Set(Prop_To.ID, v) } // The total number of items in a logical collection func GetTotalItems(e ld.Entity) interface{} { return e.Get(Prop_TotalItems.ID) } func SetTotalItems(e ld.Entity, v interface{}) { e.Set(Prop_TotalItems.ID, v) } // Identifies the unit of measurement used by the radius, altitude and accuracy properties. The value can be expressed either as one of a set of predefined units or as a well-known common URI that identifies units. func GetUnits(e ld.Entity) interface{} { return e.Get(Prop_Units.ID) } func SetUnits(e ld.Entity, v interface{}) { e.Set(Prop_Units.ID, v) } // Specifies when the object was last updated func GetUpdated(e ld.Entity) interface{} { return e.Get(Prop_Updated.ID) } func SetUpdated(e ld.Entity, v interface{}) { e.Set(Prop_Updated.ID, v) } func GetUpstreamDuplicates(e ld.Entity) interface{} { return e.Get(Prop_UpstreamDuplicates.ID) } func SetUpstreamDuplicates(e ld.Entity, v interface{}) { e.Set(Prop_UpstreamDuplicates.ID, v) } // Specifies a link to a specific representation of the Object func GetUrl(e ld.Entity) interface{} { return e.Get(Prop_Url.ID) } func SetUrl(e ld.Entity, v interface{}) { e.Set(Prop_Url.ID, v) } func GetVerb(e ld.Entity) interface{} { return e.Get(Prop_Verb.ID) } func SetVerb(e ld.Entity, v interface{}) { e.Set(Prop_Verb.ID, v) } // Specifies the preferred display width of the content, expressed in terms of device independent pixels. func GetWidth(e ld.Entity) interface{} { return e.Get(Prop_Width.ID) } func SetWidth(e ld.Entity, v interface{}) { e.Set(Prop_Width.ID, v) }
ld/ns/as/properties.gen.go
0.83602
0.53443
properties.gen.go
starcoder
package game import "fmt" /* 8 7 6 5 4 3 2 1 0 +--------------------------------------------+ | wL | wN | wS | wG | wK | wG | wS | wN | wL | a +--------------------------------------------+ | | wR | | | | | | wB | | b +--------------------------------------------+ | wP | wP | wP | wP | wP | wP | wP | wP | wP | c +--------------------------------------------+ | | | | | | | | | | d +--------------------------------------------+ | | | | | | | | | | e +--------------------------------------------+ | | | | | | | | | | f +--------------------------------------------+ | bP | bP | bP | bP | bP | bP | bP | bP | bP | g +--------------------------------------------+ | | bB | | | | | | bR | | h +--------------------------------------------+ | bL | bN | bS | bG | bK | bG | bS | bN | bL | i +--------------------------------------------+ */ // Board is the board of shogi type Board struct { grid [9][9]*Spot } // GetSpot returns a spot on the board func (b *Board) getSpot(x int, y int) *Spot { return b.grid[x][y] } // SetSpot sets a spot on the board func (b *Board) setSpot(x int, y int, s *Spot) { b.grid[x][y] = s } // NewBoard returns a New instance of a fresh shogi board func NewBoard() *Board { var grid [9][9]*Spot grid[0][0] = NewSpot(0, 0, NewLance(true)) grid[1][0] = NewSpot(1, 0, NewKnight(true)) grid[2][0] = NewSpot(2, 0, NewSilverGeneral(true)) grid[3][0] = NewSpot(3, 0, NewGoldGeneral(true)) grid[4][0] = NewSpot(4, 0, NewKing(true)) grid[5][0] = NewSpot(5, 0, NewGoldGeneral(true)) grid[6][0] = NewSpot(6, 0, NewSilverGeneral(true)) grid[7][0] = NewSpot(7, 0, NewKnight(true)) grid[8][0] = NewSpot(8, 0, NewLance(true)) grid[0][1] = NewSpot(0, 1, nil) grid[1][1] = NewSpot(1, 1, NewRook(true)) for i := 2; i < 7; i++ { grid[i][1] = NewSpot(i, 1, nil) } grid[7][1] = NewSpot(7, 1, NewBishop(true)) grid[8][1] = NewSpot(8, 1, nil) for i := 0; i < 9; i++ { grid[i][2] = NewSpot(i, 2, NewPawn(true)) } for i := 0; i < 9; i++ { for j := 3; j < 6; j++ { grid[i][j] = NewSpot(i, j, nil) } } for i := 0; i < 9; i++ { grid[i][6] = NewSpot(i, 6, NewPawn(false)) } grid[0][7] = NewSpot(0, 7, nil) grid[1][7] = NewSpot(1, 7, NewBishop(false)) for i := 2; i < 7; i++ { grid[i][7] = NewSpot(i, 7, nil) } grid[7][7] = NewSpot(7, 7, NewRook(false)) grid[8][7] = NewSpot(8, 7, nil) grid[0][8] = NewSpot(0, 8, NewLance(false)) grid[1][8] = NewSpot(1, 8, NewKnight(false)) grid[2][8] = NewSpot(2, 8, NewSilverGeneral(false)) grid[3][8] = NewSpot(3, 8, NewGoldGeneral(false)) grid[4][8] = NewSpot(4, 8, NewKing(false)) grid[5][8] = NewSpot(5, 8, NewGoldGeneral(false)) grid[6][8] = NewSpot(6, 8, NewSilverGeneral(false)) grid[7][8] = NewSpot(7, 8, NewKnight(false)) grid[8][8] = NewSpot(8, 8, NewLance(false)) b := Board{ grid: grid, } return &b } func (b *Board) resetBoard() { grid := b.grid grid[0][0] = NewSpot(0, 0, NewLance(false)) grid[1][0] = NewSpot(1, 0, NewKnight(false)) grid[2][0] = NewSpot(2, 0, NewSilverGeneral(false)) grid[3][0] = NewSpot(3, 0, NewGoldGeneral(false)) grid[4][0] = NewSpot(4, 0, NewKing(false)) grid[5][0] = NewSpot(5, 0, NewGoldGeneral(false)) grid[6][0] = NewSpot(6, 0, NewSilverGeneral(false)) grid[7][0] = NewSpot(7, 0, NewKnight(false)) grid[8][0] = NewSpot(8, 0, NewLance(false)) grid[0][1] = NewSpot(0, 1, nil) grid[1][1] = NewSpot(1, 1, NewRook(false)) for i := 2; i < 7; i++ { grid[i][1] = NewSpot(i, 1, nil) } grid[7][1] = NewSpot(7, 1, NewBishop(false)) grid[8][1] = NewSpot(8, 1, nil) for i := 0; i < 9; i++ { grid[i][2] = NewSpot(i, 2, NewPawn(false)) } for i := 0; i < 9; i++ { for j := 3; j < 6; j++ { grid[i][j] = NewSpot(i, j, nil) } } for i := 0; i < 9; i++ { grid[i][6] = NewSpot(i, 6, NewPawn(true)) } grid[0][7] = NewSpot(0, 7, nil) grid[1][7] = NewSpot(1, 7, NewBishop(true)) for i := 2; i < 7; i++ { grid[i][7] = NewSpot(i, 7, nil) } grid[7][7] = NewSpot(7, 7, NewRook(true)) grid[8][7] = NewSpot(8, 7, nil) grid[0][8] = NewSpot(0, 8, NewLance(true)) grid[1][8] = NewSpot(1, 8, NewKnight(true)) grid[2][8] = NewSpot(2, 8, NewSilverGeneral(true)) grid[3][8] = NewSpot(3, 8, NewGoldGeneral(true)) grid[4][8] = NewSpot(4, 8, NewKing(true)) grid[5][8] = NewSpot(5, 8, NewGoldGeneral(true)) grid[6][8] = NewSpot(6, 8, NewSilverGeneral(true)) grid[7][8] = NewSpot(7, 8, NewKnight(true)) grid[8][8] = NewSpot(8, 8, NewLance(true)) } // PrintBoard prints the current game board func (b *Board) PrintBoard() { rowNames := [9]string{"a", "b", "c", "d", "e", "f", "g", "h", "i"} for i := 8; i >= 0; i-- { fmt.Print("| ") fmt.Print(i) fmt.Print("|") } fmt.Println() for y := 0; y < 9; y++ { for x := 0; x < 9; x++ { p := b.grid[x][y].p if p != nil { fmt.Printf("|%s|", p.getKanji()) } else { fmt.Print("| |") } } fmt.Print(rowNames[y]) fmt.Println() } }
pkg/game/board.go
0.608361
0.430147
board.go
starcoder
package core import ( "encoding/gob" "encoding/json" "io" ) // TODO: Store values at certain tick intervals and calculate values for a period. // MovingAverage contains logic related to a moving average. type MovingAverage struct { EMAs []float64 Period int Signal int SMAs []float64 Values []float64 } // NewMovingAverage returns an initialized MovingAverage for storing values. func NewMovingAverage(period int) *MovingAverage { return &MovingAverage{ EMAs: make([]float64, 0), Period: period, Signal: 0, SMAs: make([]float64, 0), Values: make([]float64, 0), } } // Multiplier returns the multiplier used for EMA. func Multiplier(period int) float64 { return float64(2) / float64(period+1) } // Append adds to the slices of values. func (ma *MovingAverage) Append(value float64) { ma.Values = append(ma.Values, value) } // Crossover returns an integer signifying which has crossovered. // -1 if sma < ema // 0 if sma == ema // +1 if sma > ema func (ma *MovingAverage) Crossover() int { sma := ma.SMAs[len(ma.SMAs)-1] ema := ma.EMAs[len(ma.EMAs)-1] switch { case sma < ema: return -1 case sma > ema: return 1 } return 0 } // EMA calculates the exponential moving average based on the given period. func (ma *MovingAverage) EMA() float64 { var prev float64 length := len(ma.EMAs) if length == 0 { prev = ma.SMAs[len(ma.SMAs)-1] } else { prev = ma.EMAs[length-1] } closing := ma.Values[len(ma.Values)-1] ema := ((closing - prev) * Multiplier(ma.Period)) + prev ma.EMAs = append(ma.EMAs, ema) return ema } // SMA calculates the simple moving average based on the given period. func (ma *MovingAverage) SMA() float64 { var sum float64 start := 0 length := len(ma.Values) if length > ma.Period { start = length - ma.Period } for _, value := range ma.Values[start:] { sum += value } period := ma.Period if length < period { period = length } sma := sum / float64(period) ma.SMAs = append(ma.SMAs, sma) return sma } // Update updates the moving averages for both SMA and EMA. func (ma *MovingAverage) Update() (float64, float64, bool) { sma := ma.SMA() ema := ma.EMA() crossed := false if signal := ma.Crossover(); (signal != 0) && (signal != ma.Signal) { crossed = true ma.Signal = signal } return sma, ema, crossed } // Deserialize decodes byte data encoded by gob. func (ma *MovingAverage) Deserialize(r io.Reader) error { decoder := gob.NewDecoder(r) return decoder.Decode(ma) } // DeserializeJSON decodes JSON data. func (ma *MovingAverage) DeserializeJSON(r io.Reader) error { decoder := json.NewDecoder(r) return decoder.Decode(ma) } // Serialize encodes to byte data using gob. func (ma *MovingAverage) Serialize(w io.Writer) error { encoder := gob.NewEncoder(w) return encoder.Encode(ma) } // SerializeJSON encodes to JSON data. func (ma *MovingAverage) SerializeJSON(w io.Writer) error { encoder := json.NewEncoder(w) return encoder.Encode(ma) }
core/ma.go
0.653348
0.529811
ma.go
starcoder
package sgd import ( "github.com/nlpodyssey/spago/gd" "github.com/nlpodyssey/spago/mat" "github.com/nlpodyssey/spago/nn" ) var _ gd.MethodConfig = &Config[float32]{} // Config provides configuration settings for an SGD optimizer. type Config[T mat.DType] struct { gd.MethodConfig LR T Mu T Nesterov bool } // NewConfig returns a new SGD Config. func NewConfig[T mat.DType](lr, momentum T, nesterov bool) Config[T] { return Config[T]{ LR: lr, Mu: momentum, Nesterov: nesterov, } } var _ gd.Method[float32] = &SGD[float32]{} // SGD implements the SGD gradient descent optimization method. type SGD[T mat.DType] struct { Config[T] Alpha T } // New returns a new SGD optimizer, initialized according to the given configuration. func New[T mat.DType](c Config[T]) *SGD[T] { return &SGD[T]{Config: c, Alpha: c.LR} } // Label returns the enumeration-like value which identifies this gradient descent method. func (o *SGD[_]) Label() int { return gd.SGD } const ( v int = 0 buf int = 1 vPrev int = 2 vTmp int = 3 ) // NewSupport returns a new support structure with the given dimensions. func (o *SGD[T]) NewSupport(r, c int) *nn.Payload[T] { if o.Mu == 0.0 { // Vanilla SGD doesn't require any support structure, this is just to avoid memory allocation return &nn.Payload[T]{ Label: o.Label(), Data: []mat.Matrix[T]{mat.NewEmptyDense[T](r, c)}, // v at index 0 } } if !o.Nesterov { supp := make([]mat.Matrix[T], 2) supp[v] = mat.NewEmptyDense[T](r, c) supp[buf] = mat.NewEmptyDense[T](r, c) return &nn.Payload[T]{ Label: o.Label(), Data: supp, } } supp := make([]mat.Matrix[T], 4) supp[v] = mat.NewEmptyDense[T](r, c) supp[buf] = mat.NewEmptyDense[T](r, c) supp[vPrev] = mat.NewEmptyDense[T](r, c) supp[vTmp] = mat.NewEmptyDense[T](r, c) return &nn.Payload[T]{ Label: o.Label(), Data: supp, } } // Delta returns the difference between the current params and where the method wants it to be. func (o *SGD[T]) Delta(param nn.Param[T]) mat.Matrix[T] { return o.calcDelta(param.Grad(), gd.GetOrSetPayload[T](param, o).Data) } func (o *SGD[T]) calcDelta(grads mat.Matrix[T], supp []mat.Matrix[T]) mat.Matrix[T] { if o.Mu == 0.0 { return o.calcVanillaSGD(grads, supp) } else if o.Nesterov { return o.calcNesterovMomentumDelta(grads, supp) } else { return o.calcMomentumDelta(grads, supp) } } func (o *SGD[T]) calcVanillaSGD(grads mat.Matrix[T], supp []mat.Matrix[T]) mat.Matrix[T] { supp[v].ProdMatrixScalarInPlace(grads, o.Alpha) return supp[v] } func (o *SGD[T]) calcMomentumDelta(grads mat.Matrix[T], supp []mat.Matrix[T]) mat.Matrix[T] { supp[buf].ProdMatrixScalarInPlace(grads, o.Alpha) supp[v].ProdScalarInPlace(o.Mu) supp[v].AddInPlace(supp[buf]) return supp[v] } func (o *SGD[T]) calcNesterovMomentumDelta(grads mat.Matrix[T], supp []mat.Matrix[T]) mat.Matrix[T] { supp[buf].ProdMatrixScalarInPlace(grads, o.Alpha) supp[vPrev].ProdMatrixScalarInPlace(supp[v], o.Mu) supp[v].ProdScalarInPlace(o.Mu) supp[v].AddInPlace(supp[buf]) // += grad * alpha supp[vTmp].ProdMatrixScalarInPlace(supp[v], 1.0+o.Mu) supp[vTmp].SubInPlace(supp[vPrev]) return supp[vTmp] }
gd/sgd/sgd.go
0.735071
0.444746
sgd.go
starcoder
package gohex import ( "bufio" "encoding/hex" "io" "sort" ) // Constants definitions of IntelHex record types const ( _DATA_RECORD byte = 0 // Record with data bytes _EOF_RECORD byte = 1 // Record with end of file indicator _ADR_20_RECORD byte = 2 // Record with extended 20-bit linear address _ADR_32_RECORD byte = 4 // Record with extended 32-bit linear address _START_RECORD byte = 5 // Record with start linear address ) // Structure with binary data segment fields type DataSegment struct { Address uint32 // Starting address of data segment Data []byte // Data segment bytes } // Helper type for data segments sorting operations type sortByAddress []*DataSegment func (segs sortByAddress) Len() int { return len(segs) } func (segs sortByAddress) Swap(i, j int) { segs[i], segs[j] = segs[j], segs[i] } func (segs sortByAddress) Less(i, j int) bool { return segs[i].Address < segs[j].Address } // Main structure with private fields of IntelHex parser type Memory struct { dataSegments []*DataSegment // Slice with pointers to DataSegments startAddress uint32 // Start linear address extendedAddress uint32 // Extended linear address eofFlag bool // End of file record exist flag startFlag bool // Start address record exist flag lineNum uint // Parser input line number firstAddressFlag bool // Dump first address line } // Constructor of Memory structure func NewMemory() *Memory { m := new(Memory) m.Clear() return m } // Method to getting start address from IntelHex data func (m *Memory) GetStartAddress() (adr uint32, ok bool) { if m.startFlag { return m.startAddress, true } return 0, false } // Method to setting start address to IntelHex data func (m *Memory) SetStartAddress(adr uint32) { m.startAddress = adr m.startFlag = true } // Method to getting data segments address from IntelHex data func (m *Memory) GetDataSegments() []DataSegment { segs := []DataSegment{} for _, s := range m.dataSegments { segs = append(segs, *s) } return segs } func (m *Memory) GetRawSegments() []*DataSegment { return m.dataSegments } // Method to clear memory structure func (m *Memory) Clear() { m.startAddress = 0 m.extendedAddress = 0 m.lineNum = 0 m.dataSegments = []*DataSegment{} m.startFlag = false m.eofFlag = false m.firstAddressFlag = false } func (seg *DataSegment) isOverlap(adr uint32, size uint32) bool { if ((adr >= seg.Address) && (adr < seg.Address+uint32(len(seg.Data)))) || ((adr < seg.Address) && (adr+size) > seg.Address) { return true } return false } func (m *Memory) removeSegment(index int) { size := len(m.dataSegments) if size == 0 { return } else if size == 1 { m.dataSegments = []*DataSegment{} } else { if index == 0 { m.dataSegments = m.dataSegments[1:] } else if index == size-1 { m.dataSegments = m.dataSegments[:index] } else { m.dataSegments = append(m.dataSegments[:index], m.dataSegments[index+1:]...) } } } func (m *Memory) findDataSegment(adr uint32) (seg *DataSegment, offset uint32, index int) { for i, s := range m.dataSegments { if s.isOverlap(adr, 1) == true { return s, adr - s.Address, i } } return nil, 0, 0 } // Method to add binary data to memory (auto segmented and sorted) func (m *Memory) AddBinary(adr uint32, bytes []byte) error { var segBefore *DataSegment = nil var segAfter *DataSegment = nil var segAfterIndex int for i, s := range m.dataSegments { if s.isOverlap(adr, uint32(len(bytes))) == true { return newParseError(_DATA_ERROR, "data segments overlap", m.lineNum) } if adr == s.Address+uint32(len(s.Data)) { segBefore = s } if adr+uint32(len(bytes)) == s.Address { segAfter, segAfterIndex = s, i } } if segBefore != nil && segAfter != nil { segBefore.Data = append(segBefore.Data, bytes...) segBefore.Data = append(segBefore.Data, segAfter.Data...) m.dataSegments = append(m.dataSegments[:segAfterIndex], m.dataSegments[segAfterIndex+1:]...) } else if segBefore != nil && segAfter == nil { segBefore.Data = append(segBefore.Data, bytes...) } else if segBefore == nil && segAfter != nil { segAfter.Address = adr segAfter.Data = append(bytes, segAfter.Data...) } else { m.dataSegments = append(m.dataSegments, &DataSegment{Address: adr, Data: bytes}) } sort.Sort(sortByAddress(m.dataSegments)) return nil } // Method to set binary data to memory (data overlapped will change, auto segmented and sorted) func (m *Memory) SetBinary(adr uint32, bytes []byte) { for a, b := range bytes { currentAdr := adr + uint32(a) seg, offset, _ := m.findDataSegment(currentAdr) if seg != nil { seg.Data[offset] = b } else { m.AddBinary(currentAdr, []byte{b}) } } } // Method to remove binary data from memory (auto segmented and sorted) func (m *Memory) RemoveBinary(adr uint32, size uint32) { adrEnd := adr + size for currentAdr := adr; currentAdr < adrEnd; currentAdr++ { seg, offset, index := m.findDataSegment(currentAdr) if seg == nil { continue } if offset == 0 { seg.Address += 1 if len(seg.Data) > 1 { seg.Data = seg.Data[1:] } else { m.removeSegment(index) } } else if offset == uint32(len(seg.Data)-1) { if len(seg.Data) > 1 { seg.Data = seg.Data[:offset] } else { m.removeSegment(index) } } else { newSeg := DataSegment{Address: seg.Address + offset + 1, Data: seg.Data[offset+1:]} seg.Data = seg.Data[:offset] m.dataSegments = append(m.dataSegments, &newSeg) } } sort.Sort(sortByAddress(m.dataSegments)) } func (m *Memory) parseIntelHexRecord(bytes []byte) error { if len(bytes) < 5 { return newParseError(_DATA_ERROR, "not enought data bytes", m.lineNum) } err := checkSum(bytes) if err != nil { return newParseError(_CHECKSUM_ERROR, err.Error(), m.lineNum) } err = checkRecordSize(bytes) if err != nil { return newParseError(_DATA_ERROR, err.Error(), m.lineNum) } switch record_type := bytes[3]; record_type { case _DATA_RECORD: a, data := getDataLine(bytes) adr := uint32(a) + m.extendedAddress err = m.AddBinary(adr, data) if err != nil { return err } case _EOF_RECORD: err = checkEOF(bytes) if err != nil { return newParseError(_RECORD_ERROR, err.Error(), m.lineNum) } m.eofFlag = true case _ADR_20_RECORD: fallthrough case _ADR_32_RECORD: m.extendedAddress, err = getExtendedAddress(bytes) if err != nil { return newParseError(_RECORD_ERROR, err.Error(), m.lineNum) } case _START_RECORD: if m.startFlag == true { return newParseError(_DATA_ERROR, "multiple start address lines", m.lineNum) } m.startAddress, err = getStartAddress(bytes) if err != nil { return newParseError(_RECORD_ERROR, err.Error(), m.lineNum) } m.startFlag = true } return nil } func (m *Memory) parseIntelHexLine(line string) error { if len(line) == 0 { return nil } if line[0] != ':' { return newParseError(_SYNTAX_ERROR, "no colon char on the first line character", m.lineNum) } bytes, err := hex.DecodeString(line[1:]) if err != nil { return newParseError(_SYNTAX_ERROR, err.Error(), m.lineNum) } return m.parseIntelHexRecord(bytes) } // Method to parsing IntelHex data and add into memory func (m *Memory) ParseIntelHex(reader io.Reader) error { scanner := bufio.NewScanner(reader) m.Clear() for scanner.Scan() { m.lineNum++ line := scanner.Text() err := m.parseIntelHexLine(line) if err != nil { return err } } if err := scanner.Err(); err != nil { return newParseError(_SYNTAX_ERROR, err.Error(), m.lineNum) } if m.eofFlag == false { return newParseError(_DATA_ERROR, "no end of file line", m.lineNum) } return nil } func (m *Memory) dumpDataSegment(writer io.Writer, s *DataSegment, lineLength byte) error { lineAdr := s.Address lineData := []byte{} for byteAdr := s.Address; byteAdr < s.Address+uint32(len(s.Data)); byteAdr++ { if ((byteAdr & 0xFFFF0000) != m.extendedAddress) || (m.firstAddressFlag == false) { m.firstAddressFlag = true if len(lineData) != 0 { err := writeDataLine(writer, &lineAdr, byteAdr, &lineData) if err != nil { return err } } m.extendedAddress = (byteAdr & 0xFFFF0000) writeExtendedAddressLine(writer, m.extendedAddress) } if len(lineData) >= int(lineLength) { err := writeDataLine(writer, &lineAdr, byteAdr, &lineData) if err != nil { return err } } lineData = append(lineData, s.Data[byteAdr-s.Address]) } if len(lineData) != 0 { return writeDataLine(writer, &lineAdr, 0, &lineData) } return nil } // Method to dumping IntelHex data previously loaded into memory func (m *Memory) DumpIntelHex(writer io.Writer, lineLength byte) error { if m.startFlag { err := writeStartAddressLine(writer, m.startAddress) if err != nil { return err } } m.firstAddressFlag = false m.extendedAddress = 0 for _, s := range m.dataSegments { err := m.dumpDataSegment(writer, s, lineLength) if err != nil { return err } } return writeEofLine(writer) } // Method to load binary data previously loaded into memory func (m *Memory) ToBinary(address uint32, size uint32, padding byte) []byte { data := make([]byte, size) i := uint32(0) for i < size { ok := false for _, s := range m.dataSegments { if (address >= s.Address) && (address < s.Address+uint32(len(s.Data))) { data[i] = s.Data[address-s.Address] i++ address++ ok = true break } } if ok == false { data[i] = padding i++ address++ } } return data }
gohex.go
0.570451
0.503601
gohex.go
starcoder